const std = @import("std"); const builtin = @import("builtin"); const assert = std.debug.assert; const zf = @import("zf"); const vaxis = @import("vaxis"); const vxfw = vaxis.vxfw; const config = @import("config.zig"); const input_output = @import("input_output.zig"); const walker = @import("walker.zig"); pub const max_grep_lines: usize = 10_000; pub const max_grep_file_bytes: usize = 1 * 1024 * 1024; pub const max_grep_corpus_bytes: usize = 256 * 1024 * 1024; /// Ceiling on the number of files kept in memory. Trees with millions of /// files would otherwise cost hours of stat and read calls even when the /// byte budget already matches. pub const max_grep_files: usize = 50_000; const min_terminal_columns: u16 = 20; const min_terminal_rows: u16 = 8; pub const excerpt_context_before: usize = 5; pub const excerpt_context_after: usize = 15; const binary_probe_bytes: usize = 8192; /// One background loading step inspects at most this many tree entries /// before it hands control back to the event loop. const grep_slice_entries: usize = 512; /// One background loading step runs at most this long before it hands /// control back to the event loop, keeping typing responsive. const grep_slice_time_ns: i96 = 12 * std.time.ns_per_ms; /// A query tracks its words in a u64 bitmask, so words past the 64th are /// ignored rather than overflowing the shift. const max_grep_words: usize = 64; fn hasUppercase(text: []const u8) bool { for (text) |byte| { if (std.ascii.isUpper(byte)) { return true; } } return false; } fn checkTerminalSize(input_output_handle: std.Io) !void { if (input_output.getenv("TERM")) |term| { if (std.mem.eql(u8, term, "dumb")) { input_output.warn("dumb terminal cannot run picker\n", .{}); return error.NoTerminal; } } if (builtin.os.tag != .linux) { return; } const tty = std.Io.Dir.openFileAbsolute(input_output_handle, "/dev/tty", .{ .mode = .read_only, .allow_directory = false, .path_only = false, }) catch |err| { input_output.warn("cannot open terminal for picker: {}\n", .{err}); return error.NoTerminal; }; defer tty.close(input_output_handle); var size: std.posix.winsize = .{ .row = 0, .col = 0, .xpixel = 0, .ypixel = 0 }; const ioctl_rc = std.os.linux.ioctl(tty.handle, std.os.linux.T.IOCGWINSZ, @intFromPtr(&size)); if (ioctl_rc != 0) { input_output.warn("cannot query terminal size for picker: {d}\n", .{ioctl_rc}); return error.NoTerminal; } if (size.col < min_terminal_columns) { input_output.warn( "terminal too narrow for picker: {d} columns, need {d}\n", .{ size.col, min_terminal_columns }, ); return error.TerminalTooSmall; } if (size.row < min_terminal_rows) { input_output.warn( "terminal too short for picker: {d} rows, need {d}\n", .{ size.row, min_terminal_rows }, ); return error.TerminalTooSmall; } } pub const ResolvedTheme = struct { prompt: vaxis.Style, match: vaxis.Style, cursor_row: vaxis.Style, status: vaxis.Style, preview_current: vaxis.Style, bg: vaxis.Color, fg: vaxis.Color, }; fn defaultTheme() ResolvedTheme { return .{ .prompt = .{ .fg = .{ .index = 4 } }, .match = .{ .fg = .{ .index = 4 }, .reverse = true }, .cursor_row = .{ .bg = .{ .index = 8 } }, .status = .{ .fg = .{ .index = 8 } }, .preview_current = .{ .fg = .{ .index = 4 } }, .bg = .default, .fg = .default, }; } comptime { // The default theme is the reference the theme tests compare against. const theme = defaultTheme(); assert(theme.prompt.fg.index == 4); assert(theme.match.reverse); assert(theme.cursor_row.bg.index == 8); } pub fn parseThemeColor(text: []const u8) !vaxis.Color { if (std.mem.eql(u8, text, "default")) { return .default; } if (text.len == 0) { return error.InvalidColor; } if (text[0] == '#') { return parseHexColor(text); } const index = std.fmt.parseInt(u16, text, 10) catch { return error.InvalidColor; }; if (index > 255) { return error.InvalidColor; } assert(index <= 255); return .{ .index = @intCast(index) }; } fn parseHexColor(text: []const u8) !vaxis.Color { assert(text.len > 0); if (text[0] != '#') { return error.InvalidColor; } if (text.len != 7) { return error.InvalidColor; } var rgb: [3]u8 = undefined; var channel: usize = 0; while (channel < 3) { assert(channel < 3); const pair = text[1 + channel * 2 ..][0..2]; assert(pair.len == 2); rgb[channel] = std.fmt.parseUnsigned(u8, pair, 16) catch { return error.InvalidColor; }; channel += 1; } assert(channel == 3); return .{ .rgb = rgb }; } fn noColorSet() bool { const raw = std.c.getenv("NO_COLOR") orelse return false; return std.mem.span(raw).len > 0; } fn resolveRoleColor( input_output_handle: std.Io, role: []const u8, maybe_text: ?[]const u8, fallback: vaxis.Color, ) vaxis.Color { assert(role.len > 0); const text = maybe_text orelse return fallback; return parseThemeColor(text) catch { warn(input_output_handle, "invalid theme color for '{s}': '{s}', using default\n", .{ role, text, }); return fallback; }; } pub fn resolveTheme(input_output_handle: std.Io, app_config: config.Config) ResolvedTheme { if (noColorSet()) { return .{ .prompt = .{}, .match = .{}, .cursor_row = .{}, .status = .{}, .preview_current = .{}, .bg = .default, .fg = .default, }; } const defaults = defaultTheme(); const theme = app_config.theme; const prompt_fg = resolveRoleColor( input_output_handle, "prompt", theme.prompt, defaults.prompt.fg, ); const match_fg = resolveRoleColor(input_output_handle, "match", theme.match, defaults.match.fg); const cursor_bg = resolveRoleColor( input_output_handle, "cursor_row", theme.cursor_row, defaults.cursor_row.bg, ); const status_fg = resolveRoleColor( input_output_handle, "status", theme.status, defaults.status.fg, ); const marker_fg = resolveRoleColor( input_output_handle, "preview_current", theme.preview_current, defaults.preview_current.fg, ); const bg_color = resolveRoleColor( input_output_handle, "bg", theme.bg, defaults.bg, ); const fg_color = resolveRoleColor( input_output_handle, "fg", theme.fg, defaults.fg, ); const resolved: ResolvedTheme = .{ .prompt = .{ .fg = prompt_fg }, .match = .{ .fg = match_fg, .reverse = true }, .cursor_row = .{ .bg = cursor_bg }, .status = .{ .fg = status_fg }, .preview_current = .{ .fg = marker_fg }, .bg = bg_color, .fg = fg_color, }; return resolved; } pub const RankedItem = struct { index: usize, score: f64, length: usize, tail_offset: usize, matches: []const usize, }; pub fn rankItems( arena: std.mem.Allocator, items: []const []const u8, query: []const u8, ) ![]RankedItem { var ranked = std.ArrayListUnmanaged(RankedItem).empty; if (query.len == 0) { return unrankedItems(arena, items); } const case_sensitive = hasUppercase(query); var needles = std.ArrayListUnmanaged([]const u8).empty; defer needles.deinit(arena); var split = std.mem.splitScalar(u8, query, ' '); while (split.next()) |part| { if (part.len == 0) continue; try needles.append(arena, part); } if (needles.items.len == 0) { return unrankedItems(arena, items); } const total_needle_len = blk: { var sum: usize = 0; for (needles.items) |n| sum += n.len; break :blk sum; }; for (items, 0..) |item, index| { if (item.len == 0) continue; const score = zf.rank( item, needles.items, .{ .case_sensitive = case_sensitive }, ) orelse continue; const matches_buf = try arena.alloc(usize, total_needle_len); const matches = zf.highlight( item, needles.items, matches_buf, .{ .case_sensitive = case_sensitive }, ); try ranked.append(arena, .{ .index = index, .score = @floatCast(score), .length = item.len, .tail_offset = 0, .matches = matches, }); } std.mem.sortUnstable(RankedItem, ranked.items, {}, compareRankedItem); return ranked.toOwnedSlice(arena); } /// Returns every non-empty item with a score of zero. Used when the query has /// no words. fn unrankedItems(arena: std.mem.Allocator, items: []const []const u8) ![]RankedItem { var ranked = std.ArrayListUnmanaged(RankedItem).empty; for (items, 0..) |item, index| { if (item.len == 0) continue; try ranked.append(arena, .{ .index = index, .score = 0, .length = item.len, .tail_offset = 0, .matches = &.{}, }); } std.mem.sortUnstable(RankedItem, ranked.items, {}, compareRankedItem); return ranked.toOwnedSlice(arena); } fn compareRankedItem(_: void, left: RankedItem, right: RankedItem) bool { if (left.score != right.score) { return left.score < right.score; } // zf scores are always positive, because scanToEnd starts at rank 1. A // score of zero means the query was empty, so keep the original order. // When 2 real scores tie, prefer the shorter item so shallow paths come // before deep ones. if (left.score != 0 and left.length != right.length) { return left.length < right.length; } return left.index < right.index; } pub fn appendHighlightSpans( spans: *std.ArrayListUnmanaged(vxfw.RichText.TextSpan), arena: std.mem.Allocator, text: []const u8, matches: []const usize, match_style: vaxis.Style, ) !void { assert(text.len > 0); const start_len = spans.items.len; var cursor: usize = 0; var match_index: usize = 0; while (match_index < matches.len) { assert(match_index < matches.len); const position = matches[match_index]; assert(position < text.len); var run_end = position + 1; while (match_index + 1 < matches.len) { if (matches[match_index + 1] != run_end) { break; } match_index += 1; run_end += 1; } assert(run_end <= text.len); if (position > cursor) { try appendDisplaySafeText(spans, arena, text[cursor..position], .{}); } try appendDisplaySafeText(spans, arena, text[position..run_end], match_style); cursor = run_end; match_index += 1; } if (cursor < text.len) { try appendDisplaySafeText(spans, arena, text[cursor..], .{}); } assert(spans.items.len >= start_len); } pub fn sanitizeDisplayText(allocator: std.mem.Allocator, text: []const u8) ![]u8 { var out = std.ArrayListUnmanaged(u8).empty; errdefer out.deinit(allocator); const replacement = [_]u8{ 0xEF, 0xBF, 0xBD }; var i: usize = 0; var col: usize = 0; while (i < text.len) { const b = text[i]; if (b == '\n') { try out.append(allocator, '\n'); i += 1; col = 0; continue; } if (b == '\t') { const width = 8 - (col % 8); assert(width >= 1 and width <= 8); try out.appendNTimes(allocator, ' ', width); col += width; i += 1; continue; } if (b == 0x1B) { i = skipAnsiEscape(text, i); continue; } if (b < 0x20 or b == 0x7F) { try out.append(allocator, ' '); col += 1; i += 1; continue; } if (b < 0x80) { try out.append(allocator, b); col += 1; i += 1; continue; } const seq_len = std.unicode.utf8ByteSequenceLength(b) catch { try out.appendSlice(allocator, &replacement); col += 1; i += 1; continue; }; if (i + seq_len > text.len) { try out.appendSlice(allocator, &replacement); col += 1; i += 1; continue; } const codepoint = std.unicode.utf8Decode(text[i..][0..seq_len]) catch { try out.appendSlice(allocator, &replacement); col += 1; i += 1; continue; }; if (codepoint < 0x20 or (codepoint >= 0x7F and codepoint <= 0x9F)) { try out.append(allocator, ' '); } else { try out.appendSlice(allocator, text[i..][0..seq_len]); } col += 1; i += seq_len; } return out.toOwnedSlice(allocator); } fn skipAnsiEscape(text: []const u8, index: usize) usize { assert(text[index] == 0x1B); var j = index + 1; if (j >= text.len) { return j; } const kind = text[j]; if (kind == '[') { j += 1; while (j < text.len) : (j += 1) { if (text[j] >= 0x40 and text[j] <= 0x7E) { return j + 1; } } return j; } if (kind == ']') { j += 1; while (j < text.len) : (j += 1) { if (text[j] == 0x07) { return j + 1; } if (text[j] == 0x1B and j + 1 < text.len and text[j + 1] == '\\') { return j + 2; } } return j; } if (kind == 'P' or kind == 'X' or kind == '^' or kind == '_') { j += 1; while (j < text.len) : (j += 1) { if (text[j] == 0x1B and j + 1 < text.len and text[j + 1] == '\\') { return j + 2; } } return j; } return j + 1; } pub fn appendDisplaySafeText( spans: *std.ArrayListUnmanaged(vxfw.RichText.TextSpan), arena: std.mem.Allocator, text: []const u8, style: vaxis.Style, ) !void { assert(text.len > 0); const start_len = spans.items.len; const clean = try sanitizeDisplayText(arena, text); if (clean.len == 0) { try spans.append(arena, .{ .text = try arena.dupe(u8, " "), .style = style }); } else { try spans.append(arena, .{ .text = clean, .style = style }); } assert(spans.items.len > start_len); } pub fn appendCursorSpans( spans: *std.ArrayListUnmanaged(vxfw.RichText.TextSpan), arena: std.mem.Allocator, source: []const vxfw.RichText.TextSpan, cursor_row: vaxis.Style, ) !void { assert(source.len > 0); const start_len = spans.items.len; for (source) |span| { assert(span.text.len > 0); var styled = span; styled.style.bg = cursor_row.bg; try spans.append(arena, styled); } assert(spans.items.len == start_len + source.len); } pub fn appendPreviewSpans( spans: *std.ArrayListUnmanaged(vxfw.RichText.TextSpan), arena: std.mem.Allocator, excerpt: []const u8, column_one_based: usize, query_len: usize, theme: ResolvedTheme, ) !void { assert(excerpt.len > 0); const start_len = spans.items.len; var split = std.mem.splitScalar(u8, excerpt, '\n'); while (split.next()) |line| { if (line.len == 0) { continue; } if (isTargetLine(line)) { try appendTargetLineSpans(spans, arena, line, column_one_based, query_len, theme); continue; } try appendDisplaySafeText(spans, arena, line, .{}); try spans.append(arena, .{ .text = "\n" }); } assert(spans.items.len > start_len); } fn isTargetLine(line: []const u8) bool { return std.mem.startsWith(u8, line, "> "); } const PreviewRegion = struct { start: usize, end: usize, }; fn appendTargetLineSpans( spans: *std.ArrayListUnmanaged(vxfw.RichText.TextSpan), arena: std.mem.Allocator, line: []const u8, column_one_based: usize, query_len: usize, theme: ResolvedTheme, ) !void { assert(line.len >= 2); try spans.append(arena, .{ .text = line[0..2], .style = theme.preview_current }); const content = line[2..]; assert(content.len <= line.len); const region = previewMatchRegion(content, column_one_based, query_len); if (region) |match| { assert(match.start <= content.len); assert(match.end <= content.len); if (match.start > 0) { try appendDisplaySafeText(spans, arena, content[0..match.start], .{}); } try appendDisplaySafeText(spans, arena, content[match.start..match.end], theme.match); if (match.end < content.len) { try appendDisplaySafeText(spans, arena, content[match.end..], .{}); } try spans.append(arena, .{ .text = "\n" }); return; } if (content.len > 0) { try appendDisplaySafeText(spans, arena, content, .{}); } try spans.append(arena, .{ .text = "\n" }); } fn previewMatchRegion( content: []const u8, column_one_based: usize, query_len: usize, ) ?PreviewRegion { if (column_one_based == 0 or query_len == 0 or content.len == 0) { return null; } const start = column_one_based - 1; if (start >= content.len) { return null; } const end = @min(start + query_len, content.len); if (end <= start) { return null; } return .{ .start = start, .end = end }; } fn rowConstraints(ctx: vxfw.DrawContext, width: u16, height: u16) vxfw.DrawContext { const constrained = ctx.withConstraints(ctx.min, .{ .width = width, .height = height }); assert(constrained.max.width != null); assert(constrained.max.height != null); return constrained; } /// What a key press does in either picker. const KeyAction = enum { quit, previous, next, preview_page_down, preview_page_up, preview_lines_down, preview_lines_up, }; const KeyBinding = struct { codepoint: u21, mods: vaxis.Key.Modifiers = .{}, action: KeyAction, }; const key_bindings = [_]KeyBinding{ .{ .codepoint = vaxis.Key.escape, .action = .quit }, .{ .codepoint = 'c', .mods = .{ .ctrl = true }, .action = .quit }, .{ .codepoint = 'd', .mods = .{ .ctrl = true }, .action = .quit }, .{ .codepoint = 'g', .mods = .{ .ctrl = true }, .action = .quit }, .{ .codepoint = vaxis.Key.up, .action = .previous }, .{ .codepoint = 'p', .mods = .{ .ctrl = true }, .action = .previous }, .{ .codepoint = vaxis.Key.down, .action = .next }, .{ .codepoint = 'n', .mods = .{ .ctrl = true }, .action = .next }, .{ .codepoint = vaxis.Key.page_down, .action = .preview_page_down }, .{ .codepoint = 'j', .mods = .{ .alt = true }, .action = .preview_lines_down }, .{ .codepoint = vaxis.Key.page_up, .action = .preview_page_up }, .{ .codepoint = 'k', .mods = .{ .alt = true }, .action = .preview_lines_up }, }; fn keyAction(key: vaxis.Key) ?KeyAction { for (key_bindings) |binding| { if (key.matches(binding.codepoint, binding.mods)) { return binding.action; } } return null; } /// Handles the actions both pickers share: quitting and moving the cursor. /// Returns false for preview actions. Only the list picker supports those. fn handleListAction(model: anytype, ctx: *vxfw.EventContext, action: KeyAction) bool { switch (action) { .quit => { ctx.quit = true; }, .previous => { model.list_view.prevItem(ctx); model.refreshPreview(); }, .next => { model.list_view.nextItem(ctx); model.refreshPreview(); }, .preview_page_down, .preview_page_up, .preview_lines_down, .preview_lines_up, => return false, } return true; } /// Handles the events both pickers share. Each picker handles ticks itself: /// it loads its items on the first tick, after the empty frame is drawn. fn handleCommonEvent(model: anytype, ctx: *vxfw.EventContext, event: vxfw.Event) !void { switch (event) { .init => { try ctx.tick(0, model.widget()); return ctx.requestFocus(model.text_field.widget()); }, .focus_in => { return ctx.requestFocus(model.text_field.widget()); }, .key_press => |key| { const action = keyAction(key) orelse return; _ = handleListAction(model, ctx, action); }, else => {}, } } /// Connects the list and prompt of a new model to the model's callbacks. fn connectModel(model: anytype) void { const Model = @TypeOf(model.*); model.list_view.children = .{ .builder = .{ .userdata = model, .buildFn = Model.widgetBuilder, } }; model.list_view.item_count = 0; model.text_field.userdata = model; model.text_field.onChange = Model.onChange; model.text_field.onSubmit = Model.onSubmit; assert(model.text_field.userdata != null); } /// Draws the picker. The prompt and query fill the first row and the status /// fills the second. The list takes the rest. An optional preview pane takes /// 3/5 of the width. fn drawPicker( ctx: vxfw.DrawContext, owner: vxfw.Widget, theme: ResolvedTheme, text_field: *vxfw.TextField, list_view: *vxfw.ListView, status_text: []const u8, preview: ?vxfw.Widget, ) std.mem.Allocator.Error!vxfw.Surface { const max_size = ctx.max.size(); assert(max_size.width > 0); assert(max_size.height > 0); const status: vxfw.Text = .{ .text = status_text, .style = theme.status }; const prompt: vxfw.Text = .{ .text = ">", .style = theme.prompt }; const total_width: u32 = max_size.width; const preview_width: u16 = if (preview != null) @intCast(total_width * 3 / 5) else 0; const list_width: u16 = @intCast(total_width - preview_width); const list_height = max_size.height -| 2; const child_count: usize = if (preview != null) 5 else 4; const children = try ctx.arena.alloc(vxfw.SubSurface, child_count); children[0] = .{ .origin = .{ .row = 0, .col = 0 }, .surface = try prompt.draw(rowConstraints(ctx, 2, 1)), }; children[1] = .{ .origin = .{ .row = 0, .col = 2 }, .surface = try text_field.draw(rowConstraints(ctx, max_size.width -| 2, 1)), }; children[2] = .{ .origin = .{ .row = 1, .col = 2 }, .surface = try status.draw(rowConstraints(ctx, max_size.width -| 2, 1)), }; children[3] = .{ .origin = .{ .row = 2, .col = 0 }, .surface = try list_view.draw(rowConstraints(ctx, list_width, list_height)), }; if (preview) |preview_widget| { children[4] = .{ .origin = .{ .row = 2, .col = list_width }, .surface = try preview_widget.draw(rowConstraints(ctx, preview_width, list_height)), }; } const bg_style: vaxis.Style = .{ .bg = theme.bg, .fg = theme.fg }; const buffer = try ctx.arena.alloc(vaxis.Cell, max_size.width * max_size.height); @memset(buffer, .{ .style = bg_style }); return .{ .size = max_size, .widget = owner, .buffer = buffer, .children = children, }; } /// Builds list row index. The row under the cursor uses its highlighted /// version from cursor_rows. fn rowWidget( rows: []const vxfw.RichText, cursor_rows: []const vxfw.RichText, index: usize, cursor: usize, ) ?vxfw.Widget { assert(cursor_rows.len == rows.len); if (index >= rows.len) { return null; } if (index == cursor) { return cursor_rows[index].widget(); } return rows[index].widget(); } /// Returns a copy of spans styled for the cursor row. The copy uses /// allocator. fn cursorRowSpans( allocator: std.mem.Allocator, spans: []const vxfw.RichText.TextSpan, cursor_style: vaxis.Style, ) ![]vxfw.RichText.TextSpan { var cursor_spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; errdefer cursor_spans.deinit(allocator); try appendCursorSpans(&cursor_spans, allocator, spans, cursor_style); const owned = try cursor_spans.toOwnedSlice(allocator); assert(owned.len == spans.len); return owned; } /// Resets the list to show count new rows, with the cursor on the first. fn resetListView(list_view: *vxfw.ListView, count: usize) void { assert(count <= std.math.maxInt(u32)); list_view.cursor = 0; list_view.scroll.top = 0; list_view.scroll.offset = 0; list_view.item_count = @intCast(count); } /// Runs the terminal UI until the root widget quits. fn runApp(allocator: std.mem.Allocator, root: vxfw.Widget) !void { var app_buffer: [4096]u8 = undefined; var app: vxfw.App = try .init( input_output.runtime(), allocator, input_output.environMap(), &app_buffer, ); defer app.deinit(); try app.run(root, .{}); } /// Loads previews on demand. The picker calls load with the index of the /// highlighted item and shows the returned text in the side pane. Each /// refresh gets a new arena for all allocations, so load never frees memory. pub const PreviewSource = struct { ctx: ?*anyopaque, load: *const fn (ctx: ?*anyopaque, arena: std.mem.Allocator, index: usize) anyerror!?[]const u8, }; const ListModel = struct { allocator: std.mem.Allocator, items: []const []const u8, preview_source: ?PreviewSource, theme: ResolvedTheme, arena: std.heap.ArenaAllocator, preview_arena: std.heap.ArenaAllocator, preview_lines: []const vxfw.RichText = &no_preview_lines, preview_scroll: vxfw.ScrollView, ranked: []RankedItem = &.{}, filtered: std.ArrayListUnmanaged(vxfw.RichText) = .empty, filtered_cursor: std.ArrayListUnmanaged(vxfw.RichText) = .empty, list_view: vxfw.ListView, text_field: vxfw.TextField, selected: ?usize = null, loaded: bool = false, fn init( allocator: std.mem.Allocator, items: []const []const u8, preview_source: ?PreviewSource, theme: ResolvedTheme, ) !*ListModel { assert(items.len > 0); assert(items.len <= std.math.maxInt(u32)); const self = try allocator.create(ListModel); self.* = .{ .allocator = allocator, .items = items, .preview_source = preview_source, .theme = theme, .arena = std.heap.ArenaAllocator.init(allocator), .preview_arena = std.heap.ArenaAllocator.init(allocator), .preview_scroll = .{ // SAFETY: init replaces this placeholder before it returns. .children = .{ .builder = undefined }, }, .list_view = .{ // SAFETY: init replaces this placeholder before it returns. .children = .{ .builder = undefined }, }, .text_field = vxfw.TextField.init(allocator), }; connectModel(self); self.preview_scroll.children = .{ .builder = .{ .userdata = self, .buildFn = ListModel.previewBuilder, } }; self.preview_scroll.item_count = @intCast(self.preview_lines.len); return self; } fn deinit(self: *ListModel) void { const allocator = self.allocator; self.arena.deinit(); self.preview_arena.deinit(); self.text_field.deinit(); allocator.destroy(self); } fn widget(self: *ListModel) vxfw.Widget { const result: vxfw.Widget = .{ .userdata = self, .eventHandler = ListModel.typeErasedEventHandler, .drawFn = ListModel.typeErasedDrawFn, }; assert(result.userdata == @as(*anyopaque, @ptrCast(self))); return result; } fn typeErasedEventHandler( ptr: *anyopaque, ctx: *vxfw.EventContext, event: vxfw.Event, ) anyerror!void { const self: *ListModel = @ptrCast(@alignCast(ptr)); switch (event) { .tick => { if (!self.loaded) { self.loaded = true; const query = try self.text_field.buf.dupe(); defer self.text_field.buf.allocator.free(query); try self.refilter(query); ctx.redraw = true; } }, .key_press => |key| { const action = keyAction(key) orelse return; if (handleListAction(self, ctx, action)) { return; } const scroll = &self.preview_scroll.scroll; const moved = switch (action) { .preview_page_down => scroll.linesDown(self.previewPageLines()), .preview_page_up => scroll.linesUp(self.previewPageLines()), .preview_lines_down => scroll.linesDown(preview_scroll_lines), .preview_lines_up => scroll.linesUp(preview_scroll_lines), else => unreachable, }; if (moved) { ctx.redraw = true; } }, .mouse => { // Pass wheel events to the preview pane, so it scrolls even // while the text field has focus. if (self.preview_source != null) { try self.preview_scroll.handleEvent(ctx, event); } }, else => try handleCommonEvent(self, ctx, event), } } fn typeErasedDrawFn( ptr: *anyopaque, ctx: vxfw.DrawContext, ) std.mem.Allocator.Error!vxfw.Surface { const self: *ListModel = @ptrCast(@alignCast(ptr)); const status_text = try std.fmt.allocPrint( ctx.arena, "{d}/{d}", .{ self.filtered.items.len, self.items.len }, ); const preview: ?vxfw.Widget = if (self.preview_source != null) self.preview_scroll.widget() else null; return drawPicker( ctx, self.widget(), self.theme, &self.text_field, &self.list_view, status_text, preview, ); } fn previewBuilder(ptr: *const anyopaque, index: usize, _: usize) ?vxfw.Widget { const self: *const ListModel = @ptrCast(@alignCast(ptr)); if (self.preview_source == null) { return null; } if (index >= self.preview_lines.len) { return null; } return self.preview_lines[index].widget(); } fn previewPageLines(self: *const ListModel) u8 { const height = self.preview_scroll.last_height; return if (height > 0) height else 10; } fn widgetBuilder(ptr: *const anyopaque, index: usize, cursor: usize) ?vxfw.Widget { const self: *const ListModel = @ptrCast(@alignCast(ptr)); return rowWidget(self.filtered.items, self.filtered_cursor.items, index, cursor); } fn onChange(maybe_ptr: ?*anyopaque, _: *vxfw.EventContext, query: []const u8) anyerror!void { const ptr = maybe_ptr orelse return; const self: *ListModel = @ptrCast(@alignCast(ptr)); try self.refilter(query); } fn refilter(self: *ListModel, query: []const u8) !void { _ = self.arena.reset(.free_all); const arena = self.arena.allocator(); const display = try arena.alloc([]const u8, self.items.len); for (self.items, 0..) |item, index| { if (item.len == 0) { display[index] = item; continue; } const clean = try sanitizeDisplayText(arena, item); display[index] = if (clean.len == 0) " " else clean; } self.ranked = try rankItems(arena, display, query); self.filtered = .empty; self.filtered_cursor = .empty; for (self.ranked) |ranked_item| { var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendHighlightSpans( &spans, arena, display[ranked_item.index], ranked_item.matches, self.theme.match, ); const owned = try spans.toOwnedSlice(arena); assert(owned.len > 0); try self.filtered.append(arena, .{ .text = owned }); const owned_cursor = try cursorRowSpans(arena, owned, self.theme.cursor_row); try self.filtered_cursor.append(arena, .{ .text = owned_cursor }); } assert(self.filtered.items.len == self.ranked.len); assert(self.filtered_cursor.items.len == self.ranked.len); resetListView(&self.list_view, self.filtered.items.len); self.refreshPreview(); } fn refreshPreview(self: *ListModel) void { _ = self.preview_arena.reset(.free_all); self.preview_lines = &no_preview_lines; self.preview_scroll.item_count = no_preview_lines.len; self.preview_scroll.scroll = .{}; const source = self.preview_source orelse return; if (self.list_view.cursor >= self.ranked.len) { return; } const arena = self.preview_arena.allocator(); const index = self.ranked[self.list_view.cursor].index; const text = source.load(source.ctx, arena, index) catch return orelse return; if (text.len == 0) { return; } const lines = buildDiffLines(arena, text) catch return; if (lines.len == 0) { return; } self.preview_lines = lines; self.preview_scroll.item_count = @intCast(lines.len); } fn onSubmit(maybe_ptr: ?*anyopaque, ctx: *vxfw.EventContext, _: []const u8) anyerror!void { const ptr = maybe_ptr orelse return; const self: *ListModel = @ptrCast(@alignCast(ptr)); if (self.list_view.cursor < self.ranked.len) { self.selected = self.ranked[self.list_view.cursor].index; } ctx.quit = true; assert(ctx.quit); } }; const diff_add_style: vaxis.Style = .{ .fg = .{ .index = 2 } }; const diff_delete_style: vaxis.Style = .{ .fg = .{ .index = 1 } }; const diff_hunk_style: vaxis.Style = .{ .fg = .{ .index = 6 } }; const preview_scroll_lines: u8 = 3; // vaxis sizes surfaces as u16 width * u16 height, so a wrapped line must stay // well under 65,536 cells. 2,048 bytes expand to at most 16,384 cells, because // a tab expands to 8 cells. const max_preview_line_bytes: usize = 2048; comptime { assert(preview_scroll_lines > 0); assert(max_preview_line_bytes * 8 * 2 < std.math.maxInt(u16)); } /// Splits diff text into one RichText per line. Additions are green, /// deletions are red and hunk headers are cyan. Other lines use the default /// style. With one widget per line, the preview ScrollView draws only the /// visible lines. A single RichText for the whole diff would overflow the /// u16 surface size in vaxis. pub fn buildDiffLines(arena: std.mem.Allocator, diff: []const u8) ![]vxfw.RichText { assert(diff.len > 0); // Follow the NO_COLOR convention: if the variable is set and not empty, // use plain styles. const color = !noColorSet(); var lines = std.ArrayListUnmanaged(vxfw.RichText).empty; var split = std.mem.splitScalar(u8, diff, '\n'); while (split.next()) |line| { if (line.len == 0 and split.peek() == null) { break; } var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; if (line.len == 0) { // An empty RichText takes up zero rows. Use a space so blank lines // stay visible. try spans.append(arena, .{ .text = " " }); } else { const style: vaxis.Style = if (!color) .{} else switch (line[0]) { '+' => diff_add_style, '-' => diff_delete_style, '@' => diff_hunk_style, else => .{}, }; try appendDisplaySafeText(&spans, arena, clipPreviewLine(line), style); } assert(spans.items.len > 0); try lines.append(arena, .{ .text = spans.items }); } return lines.items; } /// Cuts line to max_preview_line_bytes without splitting a UTF-8 sequence. fn clipPreviewLine(line: []const u8) []const u8 { assert(line.len > 0); if (line.len <= max_preview_line_bytes) { return line; } var end = max_preview_line_bytes; while (end > 0 and (line[end] & 0xC0) == 0x80) { end -= 1; } return if (end > 0) line[0..end] else line[0..max_preview_line_bytes]; } pub fn pickFromList( allocator: std.mem.Allocator, items: []const []const u8, theme: ResolvedTheme, ) ![]u8 { return pickFromListWithPreview(allocator, items, theme, null); } /// Works like pickFromList, and also shows a preview of the highlighted item /// in a side pane. The preview loads on demand. pub fn pickFromListWithPreview( allocator: std.mem.Allocator, items: []const []const u8, theme: ResolvedTheme, preview_source: ?PreviewSource, ) ![]u8 { try checkTerminalSize(input_output.runtime()); for (items) |item| { if (item.len > 0) { break; } } else { return error.UserAbort; } const model = try ListModel.init(allocator, items, preview_source, theme); defer model.deinit(); try runApp(allocator, model.widget()); const selected = model.selected orelse return error.UserAbort; assert(selected < items.len); const result = try allocator.dupe(u8, items[selected]); assert(result.len == items[selected].len); return result; } /// A file held in memory for the grep picker. The content is the raw file /// bytes; case-insensitive matching scans it directly instead of keeping a /// second lowered copy around. pub const GrepFile = struct { path: []const u8, content: []const u8, /// Lowercase file copy for case-insensitive AC scans. Built once /// when the file enters the corpus; freed on deinit. lower: ?[]const u8 = null, fn deinit(self: *const GrepFile, allocator: std.mem.Allocator) void { allocator.free(self.path); allocator.free(self.content); if (self.lower) |lower| { allocator.free(lower); } } }; pub fn isBinaryContent(content: []const u8) bool { const probe = content[0..@min(content.len, binary_probe_bytes)]; return std.mem.indexOfScalar(u8, probe, 0) != null; } /// Real Aho-Corasick automaton. Scans a byte stream for all patterns /// at once, then groups hits by line. const Hit = struct { byte_index: usize, pattern_idx: usize, }; const AcNode = struct { fail: usize, next: std.AutoHashMap(u8, usize), output: std.ArrayListUnmanaged(usize), }; const AhoCorasick = struct { nodes: std.ArrayListUnmanaged(AcNode), allocator: std.mem.Allocator, fn init(allocator: std.mem.Allocator) !AhoCorasick { var nodes = std.ArrayListUnmanaged(AcNode).empty; errdefer nodes.deinit(allocator); try nodes.append(allocator, .{ .fail = 0, .next = std.AutoHashMap(u8, usize).init(allocator), .output = std.ArrayListUnmanaged(usize).empty, }); return .{ .nodes = nodes, .allocator = allocator }; } fn deinit(self: *AhoCorasick) void { for (self.nodes.items) |*node| { node.next.deinit(); node.output.deinit(self.allocator); } self.nodes.deinit(self.allocator); } fn addPattern(self: *AhoCorasick, pattern: []const u8, pattern_idx: usize) !void { var state: usize = 0; for (pattern) |byte| { const child = self.nodes.items[state].next.get(byte) orelse blk: { const new_state = self.nodes.items.len; try self.nodes.append(self.allocator, .{ .fail = 0, .next = std.AutoHashMap(u8, usize).init(self.allocator), .output = std.ArrayListUnmanaged(usize).empty, }); try self.nodes.items[state].next.put(byte, new_state); break :blk new_state; }; state = child; } try self.nodes.items[state].output.append(self.allocator, pattern_idx); } fn buildFail(self: *AhoCorasick) !void { var queue_items = std.ArrayListUnmanaged(usize).empty; defer queue_items.deinit(self.allocator); // Initialize depth-1 nodes var it = self.nodes.items[0].next.iterator(); while (it.next()) |entry| { const child = entry.value_ptr.*; self.nodes.items[child].fail = 0; try queue_items.append(self.allocator, child); } var read_idx: usize = 0; while (read_idx < queue_items.items.len) { const state_idx = queue_items.items[read_idx]; read_idx += 1; var it2 = self.nodes.items[state_idx].next.iterator(); while (it2.next()) |entry| { const byte = entry.key_ptr.*; const child_idx = entry.value_ptr.*; // Set the failure link for this transition. var fail_state = self.nodes.items[state_idx].fail; while (fail_state != 0) { if (self.nodes.items[fail_state].next.get(byte)) |fs_child| { fail_state = fs_child; break; } fail_state = self.nodes.items[fail_state].fail; } if (self.nodes.items[fail_state].next.get(byte)) |fs_child| { self.nodes.items[child_idx].fail = fs_child; } else { self.nodes.items[child_idx].fail = 0; } // Merge output patterns from the failure link. const fail_node_idx = self.nodes.items[child_idx].fail; const fail_outputs = self.nodes.items[fail_node_idx].output.items; try self.nodes.items[child_idx].output.appendSlice(self.allocator, fail_outputs); try queue_items.append(self.allocator, child_idx); } } } fn search( self: *const AhoCorasick, haystack: []const u8, allocator: std.mem.Allocator, hits: *std.ArrayListUnmanaged(Hit), ) !void { var state: usize = 0; for (haystack, 0..) |byte, i| { while (true) { if (self.nodes.items[state].next.get(byte)) |child| { state = child; break; } if (state == 0) { break; } state = self.nodes.items[state].fail; } for (self.nodes.items[state].output.items) |pattern_idx| { try hits.append(allocator, .{ .byte_index = i, .pattern_idx = pattern_idx }); } } } }; /// Returns true when the row list hits max_grep_lines. Appends a /// 'path:line:column:text' row for each line that contains all words. pub fn grepFiles( allocator: std.mem.Allocator, lines: *std.ArrayListUnmanaged([]const u8), files: []GrepFile, query: []const u8, ) !bool { const case_sensitive = hasUppercase(query); var needles = std.ArrayListUnmanaged([]const u8).empty; defer { for (needles.items) |needle| { allocator.free(needle); } needles.deinit(allocator); } var words = std.mem.splitScalar(u8, query, ' '); while (words.next()) |word| { if (word.len == 0) { continue; } // A query's words fill a u64 bitmask per line, so extra words are // dropped instead of overflowing the mask. if (needles.items.len == max_grep_words) { break; } const needle = if (case_sensitive) try allocator.dupe(u8, word) else try std.ascii.allocLowerString(allocator, word); try needles.append(allocator, needle); } if (needles.items.len == 0) { return false; } for (files) |file| { const truncated = try grepOneFile(allocator, lines, file, needles.items, case_sensitive); if (lines.items.len >= max_grep_lines) { return true; } if (truncated) { return true; } } return false; } fn grepOneFile( allocator: std.mem.Allocator, lines: *std.ArrayListUnmanaged([]const u8), file: GrepFile, needles: []const []const u8, case_sensitive: bool, ) !bool { assert(file.path.len > 0); assert(needles.len > 0); assert(needles.len <= max_grep_words); var lower_copy: ?[]u8 = null; defer if (lower_copy) |copy| allocator.free(copy); var haystack = file.content; if (!case_sensitive) { if (file.lower) |existing| { haystack = existing; } else { const copy = try std.ascii.allocLowerString(allocator, file.content); lower_copy = copy; haystack = copy; } } var ac = try AhoCorasick.init(allocator); defer ac.deinit(); for (needles, 0..) |needle, idx| { try ac.addPattern(needle, idx); } try ac.buildFail(); var hits = std.ArrayListUnmanaged(Hit).empty; defer hits.deinit(allocator); try ac.search(haystack, allocator, &hits); if (hits.items.len == 0) return false; const sorted = try allocator.alloc(Hit, hits.items.len); defer allocator.free(sorted); @memcpy(sorted, hits.items); std.mem.sort(Hit, sorted, {}, struct { fn lessThan(_: void, a: Hit, b: Hit) bool { return a.byte_index < b.byte_index; } }.lessThan); // Group hits by line (line start = index after previous newline, or 0). var i: usize = 0; while (i < sorted.len) { const first_byte = sorted[i].byte_index; // Find line start var line_start: usize = 0; if (first_byte > 0) { var s = first_byte; while (s > 0) : (s -= 1) { if (haystack[s - 1] == '\n') { line_start = s; break; } } } // Find line end (next newline or end of haystack) var line_end = haystack.len; var s = first_byte; while (s < haystack.len) : (s += 1) { if (haystack[s] == '\n') { line_end = s; break; } } // Count unique patterns on this line. var found: u64 = 0; const needle_len_first = needles[sorted[i].pattern_idx].len; var earliest_start: usize = sorted[i].byte_index - (needle_len_first - 1); var j = i; while (j < sorted.len) { const hit_byte = sorted[j].byte_index; // Compute line start for hit_byte var hit_line_start: usize = 0; if (hit_byte > 0) { var hs = hit_byte; while (hs > 0) : (hs -= 1) { if (haystack[hs - 1] == '\n') { hit_line_start = hs; break; } } } if (hit_line_start != line_start) break; const needle_len = needles[sorted[j].pattern_idx].len; const start_index = hit_byte - (needle_len - 1); found |= @as(u64, 1) << @intCast(sorted[j].pattern_idx); if (start_index < earliest_start) earliest_start = start_index; j += 1; } i = j; const full_mask = ~@as(u64, 0) >> @as(u6, @intCast(max_grep_words - needles.len)); if (found == full_mask) { const line_slice = haystack[line_start..line_end]; // Compute line number by counting newlines before line_start. var ln: usize = 1; if (line_start > 0) { ln = std.mem.count(u8, haystack[0..line_start], "\n") + 1; } const row = try std.fmt.allocPrint(allocator, "{s}:{d}:{d}:{s}", .{ file.path, ln, earliest_start - line_start + 1, line_slice, }); try lines.append(allocator, row); if (lines.items.len >= max_grep_lines) { return true; } } } return false; } /// Frees every line and leaves the list empty. fn freeLines(allocator: std.mem.Allocator, lines: *std.ArrayListUnmanaged([]const u8)) void { for (lines.items) |line| { allocator.free(line); } lines.deinit(allocator); lines.* = .empty; } pub const GrepTarget = struct { file: []const u8, line: usize, column: usize, }; pub fn splitGrepLine(selected: []const u8) GrepTarget { assert(selected.len > 0); var fields = std.mem.splitScalar(u8, selected, ':'); if (fields.next()) |file| { const line = if (fields.next()) |text| parseGrepNumber(text) else 0; const column = if (fields.next()) |text| parseGrepNumber(text) else 0; return .{ .file = file, .line = line, .column = column }; } return .{ .file = selected, .line = 0, .column = 0 }; } fn parseGrepNumber(text: []const u8) usize { const number = std.fmt.parseInt(usize, text, 10) catch return 0; return number; } /// Returns the lines of content around line_one_based. The target line /// starts with "> " and the others start with 2 spaces. pub fn excerptFromContent( allocator: std.mem.Allocator, content: []const u8, line_one_based: usize, ) ![]u8 { assert(line_one_based > 0); const first = excerptFirstLine(line_one_based); const last = first + excerpt_context_before + excerpt_context_after; assert(first >= 1); assert(last >= first); var out = std.ArrayListUnmanaged(u8).empty; errdefer out.deinit(allocator); var number: usize = 0; var split = std.mem.splitScalar(u8, content, '\n'); while (split.next()) |text| { number += 1; if (number < first) { continue; } if (number > last) { break; } if (number == line_one_based) { try out.appendSlice(allocator, "> "); } else { try out.appendSlice(allocator, " "); } try out.appendSlice(allocator, text); try out.append(allocator, '\n'); } return out.toOwnedSlice(allocator); } fn excerptFirstLine(line_one_based: usize) usize { assert(line_one_based > 0); if (line_one_based > excerpt_context_before) { const first = line_one_based - excerpt_context_before; assert(first < line_one_based); assert(first >= 1); return first; } return 1; } const no_preview_text = "[no preview]"; const no_preview_spans = [_]vxfw.RichText.TextSpan{ .{ .text = no_preview_text }, }; const no_preview_lines = [_]vxfw.RichText{ .{ .text = &no_preview_spans }, }; /// Writes picker warnings to stderr. Tests skip them, because there they are /// only noise. fn warn(input_output_handle: std.Io, comptime fmt: []const u8, arguments: anytype) void { if (builtin.is_test) { return; } input_output.warnTo(input_output_handle, fmt, arguments); } /// What the file walk is doing right now. The corpus loads in small steps /// from tick events, so the picker always keeps accepting input while a /// directory walk is still running. const GrepState = enum { /// The walk has not started yet. pending, /// The walk is running in bounded steps. loading, /// The walk is parked because the current query already filled the row /// list. A new query resumes it, because narrower queries may fit. paused, /// A stop reason fired (too many files or bytes) and the walk ended /// early. The corpus is final. capped, /// The whole tree was walked. The corpus is final. done, /// The walk or a read failed partway. The corpus keeps what loaded. failed, }; /// The tree walk that feeds the corpus, kept across loading steps. const GrepLoader = struct { tree_walker: walker.TreeWalker, /// The same directory the tree walker holds; reads go through it. root: std.Io.Dir, corpus_bytes: usize = 0, }; const GrepModel = struct { input_output_handle: std.Io, allocator: std.mem.Allocator, patterns: []const []const u8, theme: ResolvedTheme, corpus: std.ArrayListUnmanaged(GrepFile) = .empty, state: GrepState = .pending, loader: ?GrepLoader = null, /// Number of corpus files that the current query already searched. Files /// are searched once per query; each loading step fills the gap between /// this count and the corpus length. searched_files: usize = 0, truncated: bool = false, lines: std.ArrayListUnmanaged([]const u8) = .empty, query_len: usize = 0, preview_arena: std.heap.ArenaAllocator, preview_text: []const u8 = &.{}, preview_spans: []const vxfw.RichText.TextSpan = &.{}, preview: vxfw.RichText = .{ .text = &no_preview_spans }, /// Holds the styled spans of the rows built for the frame being drawn. /// Rows are built on demand from `lines` for the rows on screen only, /// which keeps typing cheap even when a query matches thousands of lines. row_arena: std.heap.ArenaAllocator, list_view: vxfw.ListView, text_field: vxfw.TextField, selected: ?usize = null, fn init( input_output_handle: std.Io, allocator: std.mem.Allocator, patterns: []const []const u8, theme: ResolvedTheme, ) !*GrepModel { const self = try allocator.create(GrepModel); self.* = .{ .input_output_handle = input_output_handle, .allocator = allocator, .patterns = patterns, .theme = theme, .preview_arena = std.heap.ArenaAllocator.init(allocator), .row_arena = std.heap.ArenaAllocator.init(allocator), .list_view = .{ // SAFETY: init replaces this placeholder before it returns. .children = .{ .builder = undefined }, }, .text_field = vxfw.TextField.init(allocator), }; connectModel(self); return self; } fn deinit(self: *GrepModel) void { const allocator = self.allocator; self.clearResults(); self.freeCorpus(); self.dropLoader(null); self.row_arena.deinit(); self.preview_arena.deinit(); self.text_field.deinit(); allocator.destroy(self); } fn freeCorpus(self: *GrepModel) void { assert(self.searched_files <= self.corpus.items.len); for (self.corpus.items) |*file| { file.deinit(self.allocator); } self.corpus.deinit(self.allocator); self.corpus = .empty; self.searched_files = 0; assert(self.corpus.items.len == 0); assert(self.searched_files == 0); } /// Starts the walk from the current directory. Runs on the first tick. fn startLoading(self: *GrepModel) void { assert(self.state == .pending); const root = walker.openWalkRoot() catch { self.state = .failed; return; }; self.openLoader(root); } /// Takes a directory that was already opened with walker access. Used /// by tests and by startLoading after opening the root itself. fn openLoader(self: *GrepModel, root: std.Io.Dir) void { assert(self.state == .pending); const tree_walker = walker.TreeWalker.init( self.input_output_handle, self.allocator, root, self.patterns, walker.max_supported_depth, // The walk runs while the picker is on screen. Walk failures are // skipped silently; a stderr write would garble the drawing. true, ) catch { // TreeWalker.init closes the root when it fails. self.state = .failed; return; }; self.loader = .{ .tree_walker = tree_walker, .root = root }; self.state = .loading; } /// Ends the walk and keeps the corpus loaded so far. Without an /// argument the state stays untouched; deinit uses that to free things. fn dropLoader(self: *GrepModel, end_state: ?GrepState) void { if (end_state) |target| { assert(target != .loading and target != .pending); self.state = target; } if (self.loader) |*loader| { loader.tree_walker.deinit(); self.loader = null; } } /// Loads the entire corpus from root in one pass, without giving control /// back to an event loop. The UI loads in bounded steps through /// handleTick instead. Tests use this to simulate a finished walk. fn loadCorpus(self: *GrepModel, root: std.Io.Dir) !void { if (self.state != .pending) { return; } self.openLoader(root); while (self.state == .loading) { _ = try self.loadCorpusStep( std.math.maxInt(usize), std.math.maxInt(i96), max_grep_files, ); } } /// Inspects at most max_entries tree entries, staying within the time /// budget and the file cap. Binary files are detected with a cheap probe /// before a full read. Returns true when the walk wants to continue. fn loadCorpusStep( self: *GrepModel, max_entries: usize, time_budget_ns: i96, file_cap: usize, ) !bool { assert(self.state == .loading); assert(max_entries > 0); assert(time_budget_ns > 0); assert(file_cap > 0); const loader = &(self.loader orelse { // Only .loading steps reach here and .loading implies a loader; // treat a missing one as an ended walk, not a crash. self.dropLoader(.done); return false; }); const started = std.Io.Timestamp.now(self.input_output_handle, .awake); var examined: usize = 0; while (examined < max_entries) : (examined += 1) { const now = std.Io.Timestamp.now(self.input_output_handle, .awake); assert(now.nanoseconds >= started.nanoseconds); if (started.durationTo(now).nanoseconds > time_budget_ns) { break; } const item = try loader.tree_walker.next(); if (item == null) { self.dropLoader(.done); return false; } const entry = item.?; defer self.allocator.free(entry.path); assert(entry.path.len > 0); if (entry.stat_kind != .file) { continue; } // Empty files can never match and files above the single-file // ceiling are not worth reading. The walker already stat'ed the // file, so there is no second stat here; files that grow between // this check and the read hit the StreamTooLong backstop below. if (entry.size_bytes == 0 or entry.size_bytes > max_grep_file_bytes) { continue; } if (self.corpus.items.len >= file_cap) { self.dropLoader(.capped); return false; } // A short probe goes first, so binary blobs are detected before // the file is fully read. A probe that ends early carries the // whole file, and reading the rest is saved. var probe: [binary_probe_bytes]u8 = undefined; const got = self.readGrepProbe(loader.root, entry.path, &probe) orelse continue; if (isBinaryContent(probe[0..got])) { continue; } const content = if (got < probe.len) try self.allocator.dupe(u8, probe[0..got]) else (try self.readGrepFile(loader.root, entry.path)) orelse continue; if (loader.corpus_bytes + content.len > max_grep_corpus_bytes) { self.allocator.free(content); self.dropLoader(.capped); return false; } loader.corpus_bytes += content.len; const owned_path = try self.allocator.dupe(u8, entry.path); const lower_content = try std.ascii.allocLowerString(self.allocator, content); self.corpus.append(self.allocator, .{ .path = owned_path, .content = content, .lower = lower_content, }) catch |err| { self.allocator.free(owned_path); self.allocator.free(lower_content); return err; }; } assert(self.state == .loading); return true; } /// Reads the first bytes of a file into probe. Returns null when the /// file cannot be opened or read; unreadable files are simply not /// searched. fn readGrepProbe( self: *GrepModel, root: std.Io.Dir, path: []const u8, probe: []u8, ) ?usize { var file = root.openFile(self.input_output_handle, path, .{ .mode = .read_only, .allow_directory = false, }) catch return null; defer file.close(self.input_output_handle); var file_reader = file.reader(self.input_output_handle, &.{}); return file_reader.interface.readSliceShort(probe) catch return null; } /// Reads a whole file that already passed the probe check. Returns null /// when the file cannot be read; only out of memory propagates. fn readGrepFile(self: *GrepModel, root: std.Io.Dir, path: []const u8) !?[]u8 { const content = root.readFileAlloc( self.input_output_handle, path, self.allocator, .limited(max_grep_file_bytes), ) catch |err| { // The file grew past the single-file ceiling between the stat // and this read, or it vanished, or it is not readable. Skip it. if (err == error.OutOfMemory) { return err; } return null; }; if (isBinaryContent(content)) { self.allocator.free(content); return null; } assert(content.len <= max_grep_file_bytes); return content; } fn widget(self: *GrepModel) vxfw.Widget { const result: vxfw.Widget = .{ .userdata = self, .eventHandler = GrepModel.typeErasedEventHandler, .drawFn = GrepModel.typeErasedDrawFn, }; assert(result.userdata == @as(*anyopaque, @ptrCast(self))); return result; } /// Handles one loading tick: walk a bounded slice of the tree, search /// the newly loaded files, and ask for another tick while there is more /// work. The bounded slices keep every step short, so picking or typing /// stays responsive even in huge trees. fn handleTick(self: *GrepModel, ctx: *vxfw.EventContext) !void { if (self.state == .pending) { self.startLoading(); } ctx.redraw = true; if (self.state == .loading) { _ = self.loadCorpusStep(grep_slice_entries, grep_slice_time_ns, max_grep_files) catch { self.dropLoader(.failed); }; } // Search the files this step loaded, even when the walk just // reached its end; cap hits only park a walk that still runs. if (self.searched_files < self.corpus.items.len) { const query = try self.text_field.buf.dupe(); defer self.text_field.buf.allocator.free(query); self.query_len = query.len; const truncated = try self.appendMatches(query); if (truncated and self.state == .loading) { self.state = .paused; } self.updateListView(false); self.refreshPreview(); } if (self.state == .loading) { try ctx.tick(0, self.widget()); } } fn typeErasedEventHandler( ptr: *anyopaque, ctx: *vxfw.EventContext, event: vxfw.Event, ) anyerror!void { const self: *GrepModel = @ptrCast(@alignCast(ptr)); switch (event) { .tick => try self.handleTick(ctx), else => try handleCommonEvent(self, ctx, event), } } fn statusText(self: *GrepModel, allocator: std.mem.Allocator) ![]const u8 { const matches = self.lines.items.len; if (self.truncated or self.state == .paused) { return "too many matches, keep typing to narrow"; } return switch (self.state) { .pending, .loading => std.fmt.allocPrint( allocator, "{d} matches, scanning {d} files", .{ matches, self.corpus.items.len }, ), .capped => std.fmt.allocPrint( allocator, "{d} matches in {d} files, list capped", .{ matches, self.corpus.items.len }, ), .done => std.fmt.allocPrint(allocator, "{d} matches", .{matches}), .failed => std.fmt.allocPrint( allocator, "{d} matches, directory read failed", .{matches}, ), .paused => unreachable, }; } fn typeErasedDrawFn( ptr: *anyopaque, ctx: vxfw.DrawContext, ) std.mem.Allocator.Error!vxfw.Surface { const self: *GrepModel = @ptrCast(@alignCast(ptr)); // Rows are built into the row arena on demand, and nothing built // for the previous frame is needed anymore. _ = self.row_arena.reset(.free_all); const status_text = try self.statusText(ctx.arena); return drawPicker( ctx, self.widget(), self.theme, &self.text_field, &self.list_view, status_text, self.preview.widget(), ); } fn widgetBuilder(ptr: *const anyopaque, index: usize, cursor: usize) ?vxfw.Widget { // SAFETY: the ListView hands its builders a const pointer, but rows // are scratch built into the row arena for the frame being drawn, // so the model must stay mutable here. const self: *GrepModel = @ptrCast(@alignCast(@constCast(ptr))); return self.rowWidget(index, cursor); } /// Builds the styled spans for one result row. Only called for rows on /// the screen, so a search that matches thousands of lines costs no more /// styling work than the visible window. fn rowWidget(self: *GrepModel, index: usize, cursor: usize) ?vxfw.Widget { assert(cursor <= self.lines.items.len); if (index >= self.lines.items.len) { return null; } const arena = self.row_arena.allocator(); const line = self.lines.items[index]; assert(line.len > 0); var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; appendDisplaySafeText(&spans, arena, line, .{}) catch return null; const normal = spans.toOwnedSlice(arena) catch return null; assert(normal.len > 0); const shown = if (index == cursor) cursorRowSpans(arena, normal, self.theme.cursor_row) catch return null else normal; const rich = arena.create(vxfw.RichText) catch return null; rich.* = .{ .text = shown }; return rich.widget(); } fn onChange(maybe_ptr: ?*anyopaque, ctx: *vxfw.EventContext, query: []const u8) anyerror!void { const ptr = maybe_ptr orelse return; const self: *GrepModel = @ptrCast(@alignCast(ptr)); _ = try self.runSearch(query); if (self.state == .paused) { // The query narrowed, so files skipped while the row list was // full get searched while the walk resumes. self.state = .loading; try ctx.tick(0, self.widget()); } } /// Runs a full search over the loaded corpus with the new query. fn runSearch(self: *GrepModel, query: []const u8) !bool { self.clearResults(); self.query_len = query.len; self.searched_files = 0; const truncated = try self.appendMatches(query); resetListView(&self.list_view, self.lines.items.len); self.refreshPreview(); return truncated; } /// Greps the corpus files that this query has not seen yet and appends /// rows for their matches. Files are searched at most once per query. fn appendMatches(self: *GrepModel, query: []const u8) !bool { assert(self.searched_files <= self.corpus.items.len); const truncated = try grepFiles( self.allocator, &self.lines, self.corpus.items[self.searched_files..], query, ); self.searched_files = self.corpus.items.len; if (truncated) { self.truncated = true; } return truncated; } fn updateListView(self: *GrepModel, reset: bool) void { if (reset) { resetListView(&self.list_view, self.lines.items.len); return; } // Rows only get appended, so the cursor stays where it is while the // corpus loads. It is pulled back when the list shrank below it. self.list_view.item_count = @intCast(self.lines.items.len); if (self.list_view.cursor >= self.lines.items.len) { self.list_view.cursor = 0; self.list_view.scroll = .{}; } } fn clearResults(self: *GrepModel) void { freeLines(self.allocator, &self.lines); self.truncated = false; assert(self.lines.items.len == 0); } fn refreshPreview(self: *GrepModel) void { _ = self.preview_arena.reset(.free_all); self.preview_text = &.{}; self.preview_spans = &.{}; self.preview = .{ .text = &no_preview_spans }; const cursor = self.list_view.cursor; if (cursor >= self.lines.items.len) { return; } const target = splitGrepLine(self.lines.items[cursor]); if (target.file.len == 0) { return; } if (target.line == 0) { return; } self.loadPreview(target) catch return; } fn loadPreview(self: *GrepModel, target: GrepTarget) !void { assert(target.file.len > 0); assert(target.line > 0); for (self.corpus.items) |file| { if (!std.mem.eql(u8, file.path, target.file)) { continue; } const excerpt = try excerptFromContent( self.preview_arena.allocator(), file.content, target.line, ); if (excerpt.len == 0) { return; } assert(excerpt.len > 0); var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; defer spans.deinit(self.preview_arena.allocator()); try appendPreviewSpans( &spans, self.preview_arena.allocator(), excerpt, target.column, self.query_len, self.theme, ); self.preview_text = excerpt; self.preview_spans = try spans.toOwnedSlice(self.preview_arena.allocator()); assert(self.preview_spans.len > 0); self.preview = .{ .text = self.preview_spans }; assert(self.preview.text.len > 0); return; } } fn onSubmit(maybe_ptr: ?*anyopaque, ctx: *vxfw.EventContext, _: []const u8) anyerror!void { const ptr = maybe_ptr orelse return; const self: *GrepModel = @ptrCast(@alignCast(ptr)); if (self.list_view.cursor < self.lines.items.len) { self.selected = self.list_view.cursor; } ctx.quit = true; assert(ctx.quit); } }; pub fn pickGrepLine( allocator: std.mem.Allocator, ignored_patterns: []const []const u8, theme: ResolvedTheme, initial_query: ?[]const u8, ) ![]u8 { try checkTerminalSize(input_output.runtime()); const model = try GrepModel.init( input_output.runtime(), allocator, ignored_patterns, theme, ); defer model.deinit(); // The prompt is the single source of the query. Every loading step // searches with whatever the prompt holds, including an initial query // that was filled in here before the first tick. if (initial_query) |query| { if (query.len > 0) { try model.text_field.insertSliceAtCursor(query); } } try runApp(allocator, model.widget()); const selected = model.selected orelse return error.UserAbort; assert(selected < model.lines.items.len); const result = try allocator.dupe(u8, model.lines.items[selected]); assert(result.len == model.lines.items[selected].len); return result; } const testing = std.testing; test "rankItems: filename match beats non-matches" { const items = [_][]const u8{ "src/main.zig", "README.md" }; var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const ranked = try rankItems(arena.allocator(), &items, "main"); try testing.expectEqual(@as(usize, 1), ranked.len); try testing.expectEqual(@as(usize, 0), ranked[0].index); } test "rankItems: empty query keeps original order" { const items = [_][]const u8{ "b.txt", "a.txt", "c.txt" }; var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const ranked = try rankItems(arena.allocator(), &items, ""); try testing.expectEqual(@as(usize, 3), ranked.len); try testing.expectEqual(@as(usize, 0), ranked[0].index); try testing.expectEqual(@as(usize, 1), ranked[1].index); try testing.expectEqual(@as(usize, 2), ranked[2].index); } test "rankItems: score ties prefer the shortest path" { const items = [_][]const u8{ "extensions/browser/README.md", "deprecated/extensions/filechanges/README.md", "README.md", }; var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const ranked = try rankItems(arena.allocator(), &items, "README"); try testing.expectEqual(@as(usize, 3), ranked.len); try testing.expectEqual(@as(usize, 2), ranked[0].index); try testing.expectEqual(@as(usize, 0), ranked[1].index); try testing.expectEqual(@as(usize, 1), ranked[2].index); } test "rankItems: empty query keeps original order for mixed lengths" { const items = [_][]const u8{ "bbbb", "a", "cc" }; var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const ranked = try rankItems(arena.allocator(), &items, ""); try testing.expectEqual(@as(usize, 3), ranked.len); try testing.expectEqual(@as(usize, 0), ranked[0].index); try testing.expectEqual(@as(usize, 1), ranked[1].index); try testing.expectEqual(@as(usize, 2), ranked[2].index); } test "rankItems: no match yields nothing" { const items = [_][]const u8{"src/main.zig"}; var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const ranked = try rankItems(arena.allocator(), &items, "zzz"); try testing.expectEqual(@as(usize, 0), ranked.len); } test "rankItems: uppercase query matches case-sensitively" { const items = [_][]const u8{ "src/main.zig", "src/MAIN.zig" }; var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const lower = try rankItems(arena.allocator(), &items, "main"); try testing.expectEqual(@as(usize, 2), lower.len); const upper = try rankItems(arena.allocator(), &items, "MAIN"); try testing.expectEqual(@as(usize, 1), upper.len); try testing.expectEqual(@as(usize, 1), upper[0].index); } test "rankItems: results are deterministic across runs" { const items = [_][]const u8{ "src/main.zig", "src/picker.zig", "README.md" }; var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const first = try rankItems(arena.allocator(), &items, "z"); const second = try rankItems(arena.allocator(), &items, "z"); try testing.expectEqual(first.len, second.len); for (first, second) |left, right| { try testing.expectEqual(left.index, right.index); try testing.expectEqual(left.score, right.score); } } test "rankItems: space matches path separator like slash" { const items = [_][]const u8{ "hosts/impish/overlays/config/magdalena", "hosts/impish/overlays/config/MangoHud", }; var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const slashed = try rankItems(arena.allocator(), &items, "impish/mag"); const spaced = try rankItems(arena.allocator(), &items, "impish mag"); try testing.expectEqual(slashed.len, spaced.len); try testing.expect(spaced.len > 0); for (slashed, spaced) |left, right| { try testing.expectEqual(left.index, right.index); } } test "rankItems: literal space content still matches" { const items = [_][]const u8{ "foo bar", "foo/bar" }; var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const ranked = try rankItems(arena.allocator(), &items, "foo bar"); try testing.expectEqual(@as(usize, 2), ranked.len); try testing.expectEqual(@as(usize, 0), ranked[0].index); } test "appendHighlightSpans: text rebuilds and matches glow" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const text = "src/main.zig"; const matches = [_]usize{ 4, 5, 6, 7 }; var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendHighlightSpans(&spans, arena.allocator(), text, &matches, defaultTheme().match); var rebuilt = std.ArrayListUnmanaged(u8).empty; defer rebuilt.deinit(testing.allocator); var highlighted: ?[]const u8 = null; for (spans.items) |span| { try rebuilt.appendSlice(testing.allocator, span.text); if (span.style.reverse) { highlighted = span.text; } } try testing.expectEqualStrings(text, rebuilt.items); try testing.expectEqualStrings("main", highlighted.?); } test "appendHighlightSpans: no matches leaves plain text" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendHighlightSpans(&spans, arena.allocator(), "abc", &.{}, defaultTheme().match); try testing.expectEqual(@as(usize, 1), spans.items.len); try testing.expectEqualStrings("abc", spans.items[0].text); try testing.expect(!spans.items[0].style.reverse); } test "splitGrepLine: file with line and column" { const target = splitGrepLine("src/main.zig:12:4:needle"); try testing.expectEqualStrings("src/main.zig", target.file); try testing.expectEqual(@as(usize, 12), target.line); } test "splitGrepLine: missing line yields zero" { const target = splitGrepLine("README.md"); try testing.expectEqualStrings("README.md", target.file); try testing.expectEqual(@as(usize, 0), target.line); } test "splitGrepLine: malformed line yields zero" { const target = splitGrepLine("src/main.zig:deep:4:x"); try testing.expectEqualStrings("src/main.zig", target.file); try testing.expectEqual(@as(usize, 0), target.line); } extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int; test "GrepModel: prompt prefills and drives the background search" { var temp_directory = testing.tmpDir(.{ .iterate = true }); defer temp_directory.cleanup(); const test_input_output = testing.io; try input_output.writeFile( test_input_output, temp_directory.dir, "notes.txt", "hello\nfind the needle\n", 0o644, ); var model = try GrepModel.init(test_input_output, testing.allocator, &.{}, defaultTheme()); defer model.deinit(); try model.text_field.insertSliceAtCursor("needle"); const inserted = try model.text_field.buf.dupe(); defer model.text_field.buf.allocator.free(inserted); try testing.expectEqualStrings("needle", inserted); // Drive the loading the same way tick events do: bounded steps that // search with whatever the prompt holds. const root = try walker.openWalkDir(test_input_output, temp_directory.dir); model.openLoader(root); var ctx: vxfw.EventContext = .{ .io = test_input_output, .alloc = testing.allocator, .cmds = .empty, }; defer ctx.cmds.deinit(testing.allocator); while (model.state == .loading) { try model.handleTick(&ctx); } try testing.expectEqual(GrepState.done, model.state); try testing.expectEqual(@as(usize, 1), model.lines.items.len); const target = splitGrepLine(model.lines.items[0]); try testing.expectEqualStrings("notes.txt", target.file); try testing.expectEqual(@as(usize, 2), target.line); // The whole tree loaded in one step, so no follow-up tick was needed. try testing.expectEqual(@as(usize, 0), ctx.cmds.items.len); } test "parseThemeColor: default keyword" { const color = try parseThemeColor("default"); try testing.expect(color == .default); } test "parseThemeColor: palette bounds" { const zero = try parseThemeColor("0"); try testing.expectEqual(@as(u8, 0), zero.index); const top = try parseThemeColor("255"); try testing.expectEqual(@as(u8, 255), top.index); try testing.expectError(error.InvalidColor, parseThemeColor("256")); try testing.expectError(error.InvalidColor, parseThemeColor("-1")); } test "parseThemeColor: hex triple" { const color = try parseThemeColor("#ff0080"); try testing.expectEqual([3]u8{ 255, 0, 128 }, color.rgb); const black = try parseThemeColor("#000000"); try testing.expectEqual([3]u8{ 0, 0, 0 }, black.rgb); } test "parseThemeColor: malformed input errors" { try testing.expectError(error.InvalidColor, parseThemeColor("")); try testing.expectError(error.InvalidColor, parseThemeColor("blue")); try testing.expectError(error.InvalidColor, parseThemeColor("red")); try testing.expectError(error.InvalidColor, parseThemeColor("#xyz")); try testing.expectError(error.InvalidColor, parseThemeColor("#12345")); try testing.expectError(error.InvalidColor, parseThemeColor("#1234567")); try testing.expectError(error.InvalidColor, parseThemeColor("#zzzzzz")); } test "resolveTheme: empty config yields defaults" { const theme = resolveTheme(testing.io, config.Config{}); try testing.expectEqual(@as(u8, 4), theme.prompt.fg.index); try testing.expect(!theme.prompt.reverse); try testing.expectEqual(@as(u8, 4), theme.match.fg.index); try testing.expect(theme.match.reverse); try testing.expectEqual(@as(u8, 8), theme.cursor_row.bg.index); try testing.expectEqual(@as(u8, 8), theme.status.fg.index); try testing.expectEqual(@as(u8, 4), theme.preview_current.fg.index); } test "resolveTheme: partial theme fills only set roles" { const app_config = config.Config{ .theme = .{ .prompt = "9" } }; const theme = resolveTheme(testing.io, app_config); try testing.expectEqual(@as(u8, 9), theme.prompt.fg.index); try testing.expectEqual(@as(u8, 4), theme.match.fg.index); try testing.expectEqual(@as(u8, 8), theme.status.fg.index); } test "resolveTheme: invalid role warns and defaults that role" { const app_config = config.Config{ .theme = .{ .match = "not-a-color" } }; const theme = resolveTheme(testing.io, app_config); try testing.expectEqual(@as(u8, 4), theme.match.fg.index); try testing.expect(theme.match.reverse); try testing.expectEqual(@as(u8, 4), theme.prompt.fg.index); } test "resolveTheme: NO_COLOR convention" { const old_value = if (std.c.getenv("NO_COLOR")) |existing| try testing.allocator.dupeSentinel(u8, std.mem.span(existing), 0) else null; defer { if (old_value) |saved| { defer testing.allocator.free(saved); _ = setenv("NO_COLOR", saved.ptr, 1); } else { _ = setenv("NO_COLOR", "", 1); } } assert(setenv("NO_COLOR", "1", 1) == 0); const app_config = config.Config{ .theme = .{ .prompt = "9" } }; const blank = resolveTheme(testing.io, app_config); try testing.expect(blank.prompt.fg == .default); try testing.expect(blank.match.fg == .default); try testing.expect(!blank.match.reverse); try testing.expect(blank.cursor_row.bg == .default); try testing.expect(blank.status.fg == .default); try testing.expect(blank.preview_current.fg == .default); assert(setenv("NO_COLOR", "", 1) == 0); const kept = resolveTheme(testing.io, config.Config{}); try testing.expectEqual(@as(u8, 4), kept.prompt.fg.index); try testing.expect(kept.match.reverse); } test "appendPreviewSpans: marker styled and match highlighted" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const excerpt = " line one\n> needle here\n line three\n"; var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendPreviewSpans(&spans, arena.allocator(), excerpt, 1, 6, defaultTheme()); var rebuilt = std.ArrayListUnmanaged(u8).empty; defer rebuilt.deinit(testing.allocator); var marker_style: ?vaxis.Style = null; var match_text: ?[]const u8 = null; for (spans.items) |span| { try rebuilt.appendSlice(testing.allocator, span.text); if (std.mem.eql(u8, span.text, "> ")) { marker_style = span.style; } if (span.style.reverse) { match_text = span.text; } } try testing.expectEqualStrings(excerpt, rebuilt.items); try testing.expectEqual(@as(u8, 4), marker_style.?.fg.index); try testing.expectEqualStrings("needle", match_text.?); } test "appendPreviewSpans: other lines stay plain" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const excerpt = " plain one\n> needle here\n plain two\n"; var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendPreviewSpans(&spans, arena.allocator(), excerpt, 1, 6, defaultTheme()); for (spans.items) |span| { if (std.mem.eql(u8, span.text, "> ")) { continue; } if (std.mem.eql(u8, span.text, "needle")) { continue; } try testing.expect(span.style.fg == .default); try testing.expect(!span.style.reverse); } } test "appendPreviewSpans: past-the-end column leaves plain text" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const excerpt = "> short\n"; var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendPreviewSpans(&spans, arena.allocator(), excerpt, 99, 3, defaultTheme()); var rebuilt = std.ArrayListUnmanaged(u8).empty; defer rebuilt.deinit(testing.allocator); for (spans.items) |span| { try rebuilt.appendSlice(testing.allocator, span.text); try testing.expect(!span.style.reverse); } try testing.expectEqualStrings(excerpt, rebuilt.items); } test "appendPreviewSpans: zero column yields no highlight" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const excerpt = "> needle here\n"; var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendPreviewSpans(&spans, arena.allocator(), excerpt, 0, 6, defaultTheme()); for (spans.items) |span| { try testing.expect(!span.style.reverse); } } test "appendPreviewSpans: match region clamps to the line" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const excerpt = "> abcdef\n"; var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendPreviewSpans(&spans, arena.allocator(), excerpt, 5, 99, defaultTheme()); var match_text: ?[]const u8 = null; for (spans.items) |span| { if (span.style.reverse) { match_text = span.text; } } try testing.expectEqualStrings("ef", match_text.?); } test "sanitizeDisplayText: CSI sequences stripped" { const clean = try sanitizeDisplayText(testing.allocator, "a\x1b[31mred\x1b[0mb"); defer testing.allocator.free(clean); try testing.expectEqualStrings("aredb", clean); } test "sanitizeDisplayText: OSC sequences stripped" { const clean = try sanitizeDisplayText(testing.allocator, "a\x1b]8;;http://x\x07linkb"); defer testing.allocator.free(clean); try testing.expectEqualStrings("alinkb", clean); } test "sanitizeDisplayText: controls become spaces, tabs expand" { const clean = try sanitizeDisplayText(testing.allocator, "a\x00b\x1bc\x7fd\te"); defer testing.allocator.free(clean); try testing.expectEqualStrings("a b d e", clean); } test "sanitizeDisplayText: bad UTF-8 repaired, good UTF-8 kept" { const clean = try sanitizeDisplayText(testing.allocator, "h\xff\xc3\xa9!\xe2\x82\xac"); defer testing.allocator.free(clean); try testing.expectEqualStrings("h�é!€", clean); try testing.expect(std.unicode.utf8ValidateSlice(clean)); } test "sanitizeDisplayText: output never carries ESC" { const inputs = [_][]const u8{ "\x1b[31m", "\x1b]0;title\x07", "plain", "a\rb\n", "\x9b31m", }; for (inputs) |input| { const clean = try sanitizeDisplayText(testing.allocator, input); defer testing.allocator.free(clean); try testing.expect(std.mem.indexOfScalar(u8, clean, 0x1B) == null); try testing.expect(std.unicode.utf8ValidateSlice(clean)); } } test "sanitizeDisplayText: idempotent" { const once = try sanitizeDisplayText(testing.allocator, "a\x1b[1mb\tc\xff"); defer testing.allocator.free(once); const twice = try sanitizeDisplayText(testing.allocator, once); defer testing.allocator.free(twice); try testing.expectEqualStrings(once, twice); } test "ListModel.init paints empty before first tick" { const items = [_][]const u8{ "src/main.zig", "README.md" }; const model = try ListModel.init(testing.allocator, &items, null, defaultTheme()); defer model.deinit(); try testing.expect(!model.loaded); try testing.expectEqual(@as(usize, 0), model.filtered.items.len); try testing.expectEqual(@as(?u32, 0), model.list_view.item_count); try model.refilter(""); try testing.expectEqual(@as(usize, 2), model.filtered.items.len); } test "ListModel.refilter scores sanitized text, selects raw" { const items = [_][]const u8{ "a\x1b[31mmain.zig", "README.md" }; const model = try ListModel.init(testing.allocator, &items, null, defaultTheme()); defer model.deinit(); try model.refilter("main"); try testing.expectEqual(@as(usize, 1), model.ranked.len); try testing.expectEqual(@as(usize, 0), model.ranked[0].index); for (model.filtered.items[0].text) |span| { try testing.expect(std.mem.indexOfScalar(u8, span.text, 0x1B) == null); } try testing.expectEqualStrings("a\x1b[31mmain.zig", model.items[model.ranked[0].index]); } test "buildDiffLines: colors additions, deletions and hunk headers" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const diff = "@@ -1 +1 @@\n-old\n+new\n\n context\n"; const lines = try buildDiffLines(arena.allocator(), diff); try testing.expectEqual(@as(usize, 5), lines.len); try testing.expectEqualStrings("@@ -1 +1 @@", lines[0].text[0].text); try testing.expectEqual(diff_hunk_style, lines[0].text[0].style); try testing.expectEqualStrings("-old", lines[1].text[0].text); try testing.expectEqual(diff_delete_style, lines[1].text[0].style); try testing.expectEqualStrings("+new", lines[2].text[0].text); try testing.expectEqual(diff_add_style, lines[2].text[0].style); try testing.expectEqualStrings(" ", lines[3].text[0].text); try testing.expectEqualStrings(" context", lines[4].text[0].text); try testing.expectEqual(@as(vaxis.Style, .{}), lines[4].text[0].style); } test "clipPreviewLine: keeps UTF-8 sequences whole" { var line: [max_preview_line_bytes + 8]u8 = undefined; @memset(&line, 'a'); // A 2-byte sequence that crosses the clip point. line[max_preview_line_bytes - 1] = 0xC3; line[max_preview_line_bytes] = 0xA9; const clipped = clipPreviewLine(&line); try testing.expectEqual(max_preview_line_bytes - 1, clipped.len); try testing.expectEqual( max_preview_line_bytes, clipPreviewLine(line[0..max_preview_line_bytes]).len, ); } test "ListModel.refreshPreview loads lazily for highlighted item" { const Loader = struct { fn load(_: ?*anyopaque, arena: std.mem.Allocator, index: usize) anyerror!?[]const u8 { return switch (index) { 0 => try arena.dupe(u8, "+one\n"), else => null, }; } }; const items = [_][]const u8{ " M a.txt", " M b.txt" }; const source: PreviewSource = .{ .ctx = null, .load = Loader.load }; const model = try ListModel.init(testing.allocator, &items, source, defaultTheme()); defer model.deinit(); try model.refilter(""); try testing.expectEqualStrings("+one", model.preview_lines[0].text[0].text); try model.refilter("b.txt"); try testing.expectEqualStrings(no_preview_text, model.preview_lines[0].text[0].text); } test "ListModel preview draws diffs taller than a u16 surface" { const Loader = struct { fn load(_: ?*anyopaque, arena: std.mem.Allocator, _: usize) anyerror!?[]const u8 { var text = std.ArrayListUnmanaged(u8).empty; for (0..2000) |_| { try text.appendSlice(arena, "+line\n"); } return text.items; } }; const items = [_][]const u8{" M a.txt"}; const source: PreviewSource = .{ .ctx = null, .load = Loader.load }; const model = try ListModel.init(testing.allocator, &items, source, defaultTheme()); defer model.deinit(); try model.refilter(""); try testing.expectEqual(@as(usize, 2000), model.preview_lines.len); var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); vxfw.DrawContext.init(.unicode); const ctx: vxfw.DrawContext = .{ .arena = arena.allocator(), .min = .{}, .max = .{ .width = 150, .height = 50 }, .cell_size = .{ .width = 10, .height = 20 }, }; const surface = try model.preview_scroll.draw(ctx); try testing.expectEqual(@as(u16, 50), surface.size.height); try testing.expect(model.preview_scroll.scroll.linesDown(preview_scroll_lines)); _ = try model.preview_scroll.draw(ctx); try testing.expectEqual(@as(u32, preview_scroll_lines), model.preview_scroll.scroll.top); } test "appendCursorSpans: differs only by background" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const text = "src/main.zig"; const matches = [_]usize{ 4, 5, 6, 7 }; var normal = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendHighlightSpans(&normal, arena.allocator(), text, &matches, defaultTheme().match); const theme = defaultTheme(); var cursor = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendCursorSpans(&cursor, arena.allocator(), normal.items, theme.cursor_row); try testing.expectEqual(normal.items.len, cursor.items.len); for (normal.items, cursor.items) |plain, highlighted| { try testing.expectEqualStrings(plain.text, highlighted.text); try testing.expect(vaxis.Color.eql(plain.style.fg, highlighted.style.fg)); try testing.expectEqual(plain.style.reverse, highlighted.style.reverse); try testing.expectEqual(@as(u8, 8), highlighted.style.bg.index); } for (normal.items) |span| { try testing.expect(span.style.bg == .default); } } test "splitGrepLine: column parsed" { const target = splitGrepLine("src/main.zig:12:4:needle"); try testing.expectEqualStrings("src/main.zig", target.file); try testing.expectEqual(@as(usize, 12), target.line); try testing.expectEqual(@as(usize, 4), target.column); } test "appendDisplaySafeText: carriage returns become spaces" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendDisplaySafeText(&spans, arena.allocator(), "a\rb\r", .{}); var rebuilt = std.ArrayListUnmanaged(u8).empty; defer rebuilt.deinit(testing.allocator); for (spans.items) |span| { try testing.expect(std.mem.indexOfScalar(u8, span.text, '\r') == null); try rebuilt.appendSlice(testing.allocator, span.text); } try testing.expectEqualStrings("a b ", rebuilt.items); } test "appendDisplaySafeText: clean text yields one span" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendDisplaySafeText(&spans, arena.allocator(), "abc", defaultTheme().match); try testing.expectEqual(@as(usize, 1), spans.items.len); try testing.expectEqualStrings("abc", spans.items[0].text); try testing.expect(spans.items[0].style.reverse); } test "appendPreviewSpans: carriage returns never reach spans" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const excerpt = "> ab\rcd\n"; var spans = std.ArrayListUnmanaged(vxfw.RichText.TextSpan).empty; try appendPreviewSpans(&spans, arena.allocator(), excerpt, 1, 5, defaultTheme()); for (spans.items) |span| { try testing.expect(std.mem.indexOfScalar(u8, span.text, '\r') == null); } } test "splitGrepLine: missing column yields zero" { const target = splitGrepLine("src/main.zig:12"); try testing.expectEqualStrings("src/main.zig", target.file); try testing.expectEqual(@as(usize, 12), target.line); try testing.expectEqual(@as(usize, 0), target.column); } test "grepFiles: single word reports path, line and column" { var files = [_]GrepFile{ .{ .path = "notes.txt", .content = "first line\nsecond needle here\nthird\n" }, }; var lines = std.ArrayListUnmanaged([]const u8).empty; defer freeLines(testing.allocator, &lines); const truncated = try grepFiles(testing.allocator, &lines, &files, "needle"); try testing.expect(!truncated); try testing.expectEqual(@as(usize, 1), lines.items.len); try testing.expectEqualStrings("notes.txt:2:8:second needle here", lines.items[0]); } test "grepFiles: space-separated words must share a line" { var files = [_]GrepFile{ .{ .path = "a.txt", .content = "alpha beta\nalpha only\nbeta only\n" }, }; var lines = std.ArrayListUnmanaged([]const u8).empty; defer freeLines(testing.allocator, &lines); const truncated = try grepFiles(testing.allocator, &lines, &files, "alpha beta"); try testing.expect(!truncated); try testing.expectEqual(@as(usize, 1), lines.items.len); try testing.expectEqualStrings("a.txt:1:1:alpha beta", lines.items[0]); } test "grepFiles: lowercase query is case-insensitive, uppercase sensitive" { var files = [_]GrepFile{ .{ .path = "f.txt", .content = "Readme\nreadme\nREADME\n" }, }; var lines = std.ArrayListUnmanaged([]const u8).empty; defer freeLines(testing.allocator, &lines); _ = try grepFiles(testing.allocator, &lines, &files, "readme"); try testing.expectEqual(@as(usize, 3), lines.items.len); for (lines.items) |line| testing.allocator.free(line); lines.clearRetainingCapacity(); _ = try grepFiles(testing.allocator, &lines, &files, "Read"); try testing.expectEqual(@as(usize, 1), lines.items.len); try testing.expectEqualStrings("f.txt:1:1:Readme", lines.items[0]); } test "grepFiles: repeated hits on one line collapse to a single row" { var files = [_]GrepFile{ .{ .path = "f.txt", .content = "needle and needle\nother\nneedle\n" }, }; var lines = std.ArrayListUnmanaged([]const u8).empty; defer freeLines(testing.allocator, &lines); _ = try grepFiles(testing.allocator, &lines, &files, "needle"); try testing.expectEqual(@as(usize, 2), lines.items.len); try testing.expectEqualStrings("f.txt:1:1:needle and needle", lines.items[0]); try testing.expectEqualStrings("f.txt:3:1:needle", lines.items[1]); } test "grepFiles: blank queries yield nothing" { var files = [_]GrepFile{ .{ .path = "f.txt", .content = "content\n" }, }; var lines = std.ArrayListUnmanaged([]const u8).empty; defer lines.deinit(testing.allocator); _ = try grepFiles(testing.allocator, &lines, &files, ""); _ = try grepFiles(testing.allocator, &lines, &files, " "); try testing.expectEqual(@as(usize, 0), lines.items.len); } test "grepFiles: reports truncated state at the row cap" { var content = std.ArrayListUnmanaged(u8).empty; defer content.deinit(testing.allocator); var number: usize = 0; const total_lines = max_grep_lines + 5; while (number < total_lines) : (number += 1) { try content.appendSlice(testing.allocator, "needle line\n"); } var files = [_]GrepFile{ .{ .path = "big.txt", .content = content.items }, }; var lines = std.ArrayListUnmanaged([]const u8).empty; defer freeLines(testing.allocator, &lines); const truncated = try grepFiles(testing.allocator, &lines, &files, "needle"); try testing.expect(truncated); try testing.expectEqual(max_grep_lines, lines.items.len); } test "isBinaryContent: NUL within the probe window" { try testing.expect(isBinaryContent("text\x00more")); try testing.expect(!isBinaryContent("plain text\n")); try testing.expect(!isBinaryContent("")); } test "GrepModel: corpus search fills rows from a disk tree" { var temp_directory = testing.tmpDir(.{ .iterate = true }); defer temp_directory.cleanup(); const test_input_output = testing.io; try temp_directory.dir.createDir(test_input_output, "sub", .fromMode(0o755)); try input_output.writeFile( test_input_output, temp_directory.dir, "sub/notes.txt", "hello\nfind the needle\n", 0o644, ); try input_output.writeFile( test_input_output, temp_directory.dir, "binary.bin", "a\x00b needle\n", 0o644, ); var model = try GrepModel.init(test_input_output, testing.allocator, &.{}, defaultTheme()); defer model.deinit(); const root = try walker.openWalkDir(test_input_output, temp_directory.dir); try model.loadCorpus(root); try testing.expectEqual(GrepState.done, model.state); try testing.expectEqual(@as(usize, 1), model.corpus.items.len); const truncated = try model.runSearch("needle"); try testing.expect(!truncated); try testing.expectEqual(@as(usize, 1), model.lines.items.len); const target = splitGrepLine(model.lines.items[0]); try testing.expectEqualStrings("sub/notes.txt", target.file); try testing.expectEqual(@as(usize, 2), target.line); try testing.expectEqual(@as(usize, 10), target.column); try testing.expectEqual(@as(?u32, 1), model.list_view.item_count); // Rows are styled on demand for the frame being drawn. const widget = GrepModel.widgetBuilder(model, 0, 0) orelse return error.TestUnexpectedResult; const rich: *vxfw.RichText = @ptrCast(@alignCast(widget.userdata)); try testing.expectEqual(@as(usize, 1), rich.text.len); try testing.expectEqualStrings(model.lines.items[0], rich.text[0].text); try testing.expectEqual(@as(u8, 8), rich.text[0].style.bg.index); const plain_widget = GrepModel.widgetBuilder( model, 0, 1, ) orelse return error.TestUnexpectedResult; const plain: *vxfw.RichText = @ptrCast(@alignCast(plain_widget.userdata)); try testing.expectEqualStrings(model.lines.items[0], plain.text[0].text); try testing.expect(plain.text[0].style.bg == .default); try testing.expect(GrepModel.widgetBuilder(model, 1, 0) == null); } test "GrepModel: files above the size limit are skipped" { var temp_directory = testing.tmpDir(.{ .iterate = true }); defer temp_directory.cleanup(); const test_input_output = testing.io; const big_content = try testing.allocator.alloc(u8, max_grep_file_bytes + 1); defer testing.allocator.free(big_content); @memset(big_content, 'x'); @memcpy(big_content[0..7], "needle\n"); try input_output.writeFile( test_input_output, temp_directory.dir, "big.txt", big_content, 0o644, ); try input_output.writeFile( test_input_output, temp_directory.dir, "small.txt", "needle\n", 0o644, ); var model = try GrepModel.init(test_input_output, testing.allocator, &.{}, defaultTheme()); defer model.deinit(); const root = try walker.openWalkDir(test_input_output, temp_directory.dir); try model.loadCorpus(root); try testing.expectEqual(GrepState.done, model.state); try testing.expectEqual(@as(usize, 1), model.corpus.items.len); try testing.expectEqualStrings("small.txt", model.corpus.items[0].path); const truncated = try model.runSearch("needle"); try testing.expect(!truncated); try testing.expectEqual(@as(usize, 1), model.lines.items.len); const target = splitGrepLine(model.lines.items[0]); try testing.expectEqualStrings("small.txt", target.file); } test "GrepModel: empty corpus searches cleanly" { var temp_directory = testing.tmpDir(.{ .iterate = true }); defer temp_directory.cleanup(); const test_input_output = testing.io; var model = try GrepModel.init(test_input_output, testing.allocator, &.{}, defaultTheme()); defer model.deinit(); const root = try walker.openWalkDir(test_input_output, temp_directory.dir); try model.loadCorpus(root); try testing.expectEqual(GrepState.done, model.state); try testing.expectEqual(@as(usize, 0), model.corpus.items.len); const truncated = try model.runSearch("needle"); try testing.expect(!truncated); try testing.expectEqual(@as(usize, 0), model.lines.items.len); } test "GrepModel: file cap stops the walk early" { var temp_directory = testing.tmpDir(.{ .iterate = true }); defer temp_directory.cleanup(); const test_input_output = testing.io; for ([_][]const u8{ "a.txt", "b.txt", "c.txt" }) |name| { try input_output.writeFile( test_input_output, temp_directory.dir, name, "needle\n", 0o644, ); } var model = try GrepModel.init(test_input_output, testing.allocator, &.{}, defaultTheme()); defer model.deinit(); const root = try walker.openWalkDir(test_input_output, temp_directory.dir); model.openLoader(root); try testing.expectEqual(GrepState.loading, model.state); const more = try model.loadCorpusStep(std.math.maxInt(usize), std.math.maxInt(i96), 2); // The corpus filled up, so the step asked the walk to stop early. try testing.expect(!more); try testing.expectEqual(GrepState.capped, model.state); try testing.expectEqual(@as(usize, 2), model.corpus.items.len); try testing.expect(model.loader == null); } test "GrepModel: paused walk resumes when the query changes" { var temp_directory = testing.tmpDir(.{ .iterate = true }); defer temp_directory.cleanup(); const test_input_output = testing.io; var model = try GrepModel.init(test_input_output, testing.allocator, &.{}, defaultTheme()); defer model.deinit(); const root = try walker.openWalkDir(test_input_output, temp_directory.dir); model.openLoader(root); // The row list filled while files were still queued. model.state = .paused; model.truncated = true; var ctx: vxfw.EventContext = .{ .io = test_input_output, .alloc = testing.allocator, .cmds = .empty, }; defer ctx.cmds.deinit(testing.allocator); try GrepModel.onChange(model, &ctx, "narrow"); try testing.expectEqual(GrepState.loading, model.state); // Resuming must schedule the walk again. try testing.expectEqual(@as(usize, 1), ctx.cmds.items.len); // A repeated change while loading does not stack another tick. try GrepModel.onChange(model, &ctx, "narrowish"); try testing.expectEqual(@as(usize, 1), ctx.cmds.items.len); } test "excerptFromContent: window around the target line" { var content = std.ArrayListUnmanaged(u8).empty; defer content.deinit(testing.allocator); var number: usize = 1; while (number <= 30) : (number += 1) { const line = try std.fmt.allocPrint(testing.allocator, "line{d}\n", .{number}); defer testing.allocator.free(line); try content.appendSlice(testing.allocator, line); } const excerpt = try excerptFromContent(testing.allocator, content.items, 10); defer testing.allocator.free(excerpt); try testing.expect(std.mem.indexOf(u8, excerpt, "> line10\n") != null); try testing.expect(std.mem.indexOf(u8, excerpt, " line5\n") != null); try testing.expect(std.mem.indexOf(u8, excerpt, " line25\n") != null); try testing.expect(std.mem.indexOf(u8, excerpt, "line26\n") == null); } test "excerptFromContent: line past the end yields empty" { const excerpt = try excerptFromContent(testing.allocator, "only\n", 99); defer testing.allocator.free(excerpt); try testing.expectEqual(@as(usize, 0), excerpt.len); } test "excerptFromContent: big buffers are fine" { var content = std.ArrayListUnmanaged(u8).empty; defer content.deinit(testing.allocator); var number: usize = 1; while (number <= 4000) : (number += 1) { const line = try std.fmt.allocPrint( testing.allocator, "a fairly long line {d} with some padding text to grow the buffer\n", .{number}, ); defer testing.allocator.free(line); try content.appendSlice(testing.allocator, line); } try testing.expect(content.items.len > 64 * 1024); const excerpt = try excerptFromContent(testing.allocator, content.items, 2000); defer testing.allocator.free(excerpt); try testing.expect(std.mem.indexOf(u8, excerpt, "> a fairly long line 2000 ") != null); }