// search.zig — inline 18-line TUI widget, no alternate screen // Raw terminal mode for interactive key handling. Linux-only (NixOS target). const std = @import("std"); const builtin = @import("builtin"); const types = @import("types.zig"); const output = @import("output.zig"); const api = @import("api.zig"); const WIDGET_LINES: usize = 18; const RESULT_ROWS: usize = 5; const STDIN_FD = std.posix.STDIN_FILENO; // Debounce window: a keystroke defers the nix search until typing pauses this // long. Without it, every character fired a full `nix search`, stalling mid-word. const DEBOUNCE_MS: i64 = 250; // Milliseconds elapsed since `since` on the monotonic (awake) clock. std has no // milliTimestamp in 0.16; this mirrors the Io.Clock pattern used in apply(). fn elapsedMs(io: std.Io, since: std.Io.Timestamp) i64 { const ns = @max(0, since.untilNow(io, .awake).toNanoseconds()); return @intCast(@divFloor(ns, 1_000_000)); } pub fn run( gpa: std.mem.Allocator, io: std.Io, initial_query: []const u8, mode: Mode, ) !?types.SearchResult { // Non-interactive fallback: when stdin isn't a terminal (piped, scripted, // CI), print plain results and return instead of the raw-mode widget, which // needs a real tty and would block waiting for keys. if (!stdinIsTty(io)) return runPlain(gpa, io, initial_query, mode); var saved: std.posix.termios = undefined; try rawModeEnable(STDIN_FD, &saved); defer rawModeDisable(STDIN_FD, saved); var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); var query_buf: [256]u8 = undefined; var query_len: usize = @min(initial_query.len, query_buf.len - 1); @memcpy(query_buf[0..query_len], initial_query[0..query_len]); var packages: []types.NixPackage = &.{}; var opts: []api.NixOption = &.{}; var selection: usize = 0; // Initial search _ = arena.reset(.free_all); packages = doSearch(arena.allocator(), io, query_buf[0..query_len], mode, &opts); // Initial render (prints WIDGET_LINES lines) renderWidget(query_buf[0..query_len], packages, opts, selection, mode); output.flush(); // Key loop with debounced search. A keystroke marks the query dirty and // stamps the time; the nix search fires only once typing pauses for // DEBOUNCE_MS. Stale results stay on screen until the new search returns, so // there is no blank flash mid-typing. var chosen: ?types.SearchResult = null; var query_dirty = false; var query_changed_at = std.Io.Clock.awake.now(io); loop: while (true) { // Block until a key arrives, unless a search is pending — then wake when // the debounce window closes so we can fire it. var timeout_ms: i32 = -1; if (query_dirty) { const remaining = DEBOUNCE_MS - elapsedMs(io, query_changed_at); timeout_ms = if (remaining <= 0) 0 else @intCast(remaining); } var pfd = [_]std.posix.pollfd{.{ .fd = STDIN_FD, .events = std.posix.POLL.IN, .revents = 0 }}; const ready = std.posix.poll(&pfd, timeout_ms) catch 0; if (ready == 0) { // Poll timed out: typing has paused long enough — run the search now. if (query_dirty and elapsedMs(io, query_changed_at) >= DEBOUNCE_MS) { query_dirty = false; _ = arena.reset(.free_all); packages = doSearch(arena.allocator(), io, query_buf[0..query_len], mode, &opts); output.cursorUp(WIDGET_LINES); renderWidget(query_buf[0..query_len], packages, opts, selection, mode); output.flush(); } continue; } var buf: [4]u8 = undefined; const n = std.posix.read(STDIN_FD, &buf) catch break; if (n == 0) break; if (n >= 3 and buf[0] == 0x1b and buf[1] == '[') { switch (buf[2]) { 'A' => if (selection > 0) { selection -= 1; }, // up 'B' => if (selection + 1 < resultCount(packages, opts, mode)) { selection += 1; }, // down else => {}, } } else switch (buf[0]) { 'k' => if (selection > 0) { selection -= 1; }, 'j' => if (selection + 1 < resultCount(packages, opts, mode)) { selection += 1; }, 0x1b, 'q' => break :loop, 'i', '\r' => { if (mode == .packages and packages.len > selection) { chosen = .{ .package = packages[selection], .action = .profile }; } break :loop; }, 's' => { if (mode == .packages and packages.len > selection) { chosen = .{ .package = packages[selection], .action = .system }; } break :loop; }, 't' => { if (mode == .packages and packages.len > selection) { chosen = .{ .package = packages[selection], .action = .profile }; // flag: try mode — caller handles } break :loop; }, 'c' => { // Copy attr to clipboard (best-effort via pbcopy/xclip/xsel) if (mode == .packages and packages.len > selection) { copyToClipboard(gpa, io, packages[selection].attr); } }, 127 => { // backspace if (query_len > 0) { query_len -= 1; query_dirty = true; query_changed_at = std.Io.Clock.awake.now(io); selection = 0; } }, else => |ch| { if (ch >= 32 and ch < 127 and query_len < query_buf.len - 1) { query_buf[query_len] = ch; query_len += 1; query_dirty = true; query_changed_at = std.Io.Clock.awake.now(io); selection = 0; } }, } // Redraw immediately so the query line and selection feel responsive; the // search itself is deferred to the debounce tick above. output.cursorUp(WIDGET_LINES); renderWidget(query_buf[0..query_len], packages, opts, selection, mode); output.flush(); } // Clear the widget area output.cursorUp(WIDGET_LINES); var i: usize = 0; while (i < WIDGET_LINES) : (i += 1) { output.raw(output.C_CLEAR_EOL ++ "\n"); } output.cursorUp(WIDGET_LINES); output.flush(); return chosen; } pub const Mode = enum { packages, options }; fn doSearch(arena: std.mem.Allocator, io: std.Io, query: []const u8, mode: Mode, opts: *[]api.NixOption) []types.NixPackage { switch (mode) { .packages => return api.searchPackages(arena, io, query) catch &.{}, .options => { opts.* = api.searchOptions(arena, io, query) catch &.{}; return &.{}; }, } } fn resultCount(packages: []types.NixPackage, opts: []api.NixOption, mode: Mode) usize { return switch (mode) { .packages => packages.len, .options => opts.len, }; } fn stdinIsTty(io: std.Io) bool { return std.Io.File.stdin().isTty(io) catch false; } // Plain, non-interactive rendering for non-tty stdin. Same pink :: header and // result count the widget shows, then one line per result; no cursor control. fn runPlain(gpa: std.mem.Allocator, io: std.Io, query: []const u8, mode: Mode) !?types.SearchResult { // An empty query matches the entire catalog (100k+ rows); refuse it cleanly. if (std.mem.trim(u8, query, " \t").len == 0) { output.searchEmptyQuery(); output.flush(); return null; } var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); var opts: []api.NixOption = &.{}; const packages = doSearch(arena.allocator(), io, query, mode, &opts); const count = resultCount(packages, opts, mode); const mode_str = if (mode == .packages) "nixpkgs" else "options"; output.searchPlainHeader(mode_str, query, count); if (count == 0) { output.searchPlainNoResults(); output.flush(); return null; } switch (mode) { // unfree=false: per-result meta.unfree would need an eval per package (too // slow for the list); the TUI detail pane is the place to surface it. .packages => for (packages) |pkg| output.searchPlainPackage(pkg.pname, pkg.version, pkg.description, false), .options => for (opts) |opt| output.searchPlainOption(opt.name, opt.type_str), } output.flush(); return null; } // A key hint with dim brackets and a pink letter: dim '[', pink label, dim ']'. // Comptime-built so it's a plain string literal — the widget always renders raw // ANSI (it only runs on a real tty). fn keyHint(comptime label: []const u8) []const u8 { return output.C_DIM ++ "[" ++ output.C_RESET ++ output.C_PINK ++ label ++ output.C_RESET ++ output.C_DIM ++ "]" ++ output.C_RESET; } fn renderWidget(query: []const u8, packages: []types.NixPackage, opts: []api.NixOption, selection: usize, mode: Mode) void { const count = resultCount(packages, opts, mode); const CLR = output.C_CLEAR_EOL; const RST = output.C_RESET; const PKN = output.C_PINK; const BLD = output.C_BOLD; const DIM = output.C_DIM; const CYN = output.C_CYAN; // Line 1: header output.raw(CLR); const mode_str = if (mode == .packages) "nixpkgs" else "options"; output.p("{s}:: {s}search {s} {s} {s}{d} results{s}\n", .{ PKN, RST, mode_str, query, DIM, count, RST, }); // Line 2: blank output.raw(CLR ++ "\n"); // Lines 3-7: results (up to RESULT_ROWS), scrolled so selection stays visible const scroll: usize = if (selection >= RESULT_ROWS) selection - RESULT_ROWS + 1 else 0; var i: usize = 0; while (i < RESULT_ROWS) : (i += 1) { const idx = scroll + i; output.raw(CLR); if (idx < count) { const selected = (idx == selection); switch (mode) { .packages => { const pkg = packages[idx]; const marker = if (selected) PKN ++ "> " ++ RST else " "; const name_pre = if (selected) PKN ++ BLD else ""; const name_suf = if (selected) RST else ""; output.p(" {s}{s}{s}{s} {s}{s}{s} {s}\n", .{ marker, name_pre, pkg.pname, name_suf, CYN, pkg.version, RST, pkg.description }); }, .options => { const opt = opts[idx]; const marker = if (selected) PKN ++ "> " ++ RST else " "; output.p(" {s}{s} {s}{s}{s}\n", .{ marker, opt.name, DIM, opt.type_str, RST }); }, } } else { output.raw("\n"); } } // Line 8: blank output.raw(CLR ++ "\n"); // Lines 9-12: selected package detail if (count > 0 and mode == .packages) { const pkg = packages[selection]; output.raw(CLR); output.p(" {s}{s}{s}{s} {s}{s}{s}\n", .{ PKN, BLD, pkg.pname, RST, CYN, pkg.version, RST }); output.raw(CLR); output.p(" {s}\n", .{pkg.description}); output.raw(CLR ++ "\n"); output.raw(CLR); output.p(" {s}attr{s} {s}{s}{s}\n", .{ DIM, RST, CYN, pkg.attr, RST }); } else if (count > 0 and mode == .options) { const opt = opts[selection]; output.raw(CLR); output.p(" {s} {s}{s}{s}\n", .{ opt.name, DIM, opt.type_str, RST }); output.raw(CLR); output.p(" {s}\n", .{opt.description}); output.raw(CLR ++ "\n"); output.raw(CLR ++ "\n"); } else { output.raw(CLR ++ "\n"); output.raw(CLR ++ "\n"); output.raw(CLR ++ "\n"); output.raw(CLR ++ "\n"); } // Line 13: blank output.raw(CLR ++ "\n"); // Lines 14-17: controls + padding to reach WIDGET_LINES output.raw(CLR); if (mode == .packages) { output.p(" {s} profile {s} system {s} try {s} copy {s}[up/down]{s} nav {s} exit\n", .{ keyHint("i"), keyHint("s"), keyHint("t"), keyHint("c"), DIM, RST, keyHint("esc"), }); } else { output.p(" {s} insert {s}[up/down]{s} nav {s} exit\n", .{ keyHint("i"), DIM, RST, keyHint("esc") }); } // Padding to reach WIDGET_LINES (18) var pad: usize = 14; while (pad < WIDGET_LINES) : (pad += 1) { output.raw(CLR ++ "\n"); } } fn copyToClipboard(gpa: std.mem.Allocator, io: std.Io, text: []const u8) void { _ = gpa; // Try common clipboard tools const tools = [_][]const u8{ "pbcopy", "xclip", "xsel" }; for (tools) |tool| { var child = std.process.spawn(io, .{ .argv = &.{tool}, .stdin = .pipe, .stdout = .ignore, .stderr = .ignore, }) catch continue; if (child.stdin) |stdin| { stdin.writeStreamingAll(io, text) catch {}; stdin.close(io); } _ = child.wait(io) catch {}; return; } } fn rawModeEnable(fd: std.posix.fd_t, saved: *std.posix.termios) !void { var tio = try std.posix.tcgetattr(fd); saved.* = tio; if (comptime builtin.os.tag == .linux) { tio.lflag.ECHO = false; tio.lflag.ICANON = false; tio.lflag.ISIG = false; tio.lflag.IEXTEN = false; tio.iflag.ICRNL = false; tio.iflag.IXON = false; tio.cc[@intFromEnum(std.posix.V.MIN)] = 1; tio.cc[@intFromEnum(std.posix.V.TIME)] = 0; } // On non-Linux, terminal will not be in raw mode (TUI requires Linux) try std.posix.tcsetattr(fd, .FLUSH, tio); } fn rawModeDisable(fd: std.posix.fd_t, saved: std.posix.termios) void { std.posix.tcsetattr(fd, .FLUSH, saved) catch {}; }