search.zig

17.7 KB · raw

1// search.zig — inline 18-line TUI widget, no alternate screen2// Raw terminal mode for interactive key handling. Linux-only (NixOS target).3const std = @import("std");4const builtin = @import("builtin");5const types = @import("types.zig");6const output = @import("output.zig");7const api = @import("api.zig");89const WIDGET_LINES: usize = 18;10const RESULT_ROWS: usize = 5;11const STDIN_FD = std.posix.STDIN_FILENO;1213// Debounce window: a keystroke defers the nix search until typing pauses this14// long. nix search is synchronous and blocks the widget for ~1s, so the window15// must be long enough that a normal between-keystroke pause doesn't trigger it —16// it should only fire once you've actually stopped typing.17const DEBOUNCE_MS: i64 = 500;1819// Milliseconds elapsed since `since` on the monotonic (awake) clock. std has no20// milliTimestamp in 0.16; this mirrors the Io.Clock pattern used in apply().21fn elapsedMs(io: std.Io, since: std.Io.Timestamp) i64 {22    const ns = @max(0, since.untilNow(io, .awake).toNanoseconds());23    return @intCast(@divFloor(ns, 1_000_000));24}2526// What the detail pane shows for the selected package. Tab toggles between the27// collapsed (description) view and the expanded meta view; the latter is fetched28// on demand, so it passes through loading and (on eval failure) unavailable.29const Detail = union(enum) {30    collapsed,31    loading,32    unavailable,33    meta: api.PkgMeta,34};3536pub fn run(37    gpa: std.mem.Allocator,38    io: std.Io,39    initial_query: []const u8,40    mode: Mode,41) !?types.NixPackage {42    // Non-interactive fallback: when stdin isn't a terminal (piped, scripted,43    // CI), print plain results and return instead of the raw-mode widget, which44    // needs a real tty and would block waiting for keys.45    if (!stdinIsTty(io)) return runPlain(gpa, io, initial_query, mode);4647    var saved: std.posix.termios = undefined;48    try rawModeEnable(STDIN_FD, &saved);49    defer rawModeDisable(STDIN_FD, saved);5051    var arena = std.heap.ArenaAllocator.init(gpa);52    defer arena.deinit();5354    var query_buf: [256]u8 = undefined;55    var query_len: usize = @min(initial_query.len, query_buf.len - 1);56    @memcpy(query_buf[0..query_len], initial_query[0..query_len]);5758    var packages: []types.NixPackage = &.{};59    var opts: []api.NixOption = &.{};60    var selection: usize = 0;6162    // Expanded detail (Tab): the selected package's meta, fetched on demand into63    // its own arena and cached by attr so re-visiting is instant. Kept separate64    // from the search arena, which is reset on every new search.65    var expanded = false;66    var meta_arena = std.heap.ArenaAllocator.init(gpa);67    defer meta_arena.deinit();68    var meta: ?api.PkgMeta = null;69    var meta_attr: []const u8 = "";7071    // Initial search72    _ = arena.reset(.free_all);73    packages = doSearch(arena.allocator(), io, query_buf[0..query_len], mode, &opts);7475    // Initial render (prints WIDGET_LINES lines)76    renderWidget(query_buf[0..query_len], packages, opts, selection, mode, false, .collapsed);77    output.flush();7879    // Key loop with debounced search. A keystroke marks the query dirty and80    // stamps the time; the nix search fires only once typing pauses for81    // DEBOUNCE_MS. Stale results stay on screen until the new search returns, so82    // there is no blank flash mid-typing.83    var chosen: ?types.NixPackage = null;84    var query_dirty = false;85    var query_changed_at = std.Io.Clock.awake.now(io);86    loop: while (true) {87        // Block until a key arrives, unless a search is pending — then wake when88        // the debounce window closes so we can fire it.89        var timeout_ms: i32 = -1;90        if (query_dirty) {91            const remaining = DEBOUNCE_MS - elapsedMs(io, query_changed_at);92            timeout_ms = if (remaining <= 0) 0 else @intCast(remaining);93        }9495        var pfd = [_]std.posix.pollfd{.{ .fd = STDIN_FD, .events = std.posix.POLL.IN, .revents = 0 }};96        const ready = std.posix.poll(&pfd, timeout_ms) catch 0;9798        if (ready == 0) {99            // Poll timed out. If no search is pending, nothing changed — keep waiting.100            if (!(query_dirty and elapsedMs(io, query_changed_at) >= DEBOUNCE_MS)) continue;101            query_dirty = false;102            // Paint "searching..." over the stale results before the blocking nix103            // search, so the ~1s pause reads as progress, not a freeze.104            output.cursorUp(WIDGET_LINES);105            renderWidget(query_buf[0..query_len], packages, opts, selection, mode, true, .collapsed);106            output.flush();107108            _ = arena.reset(.free_all);109            packages = doSearch(arena.allocator(), io, query_buf[0..query_len], mode, &opts);110            // New result set: reset to the top and drop cached meta (it belonged to111            // the previous results). Navigating during the window could otherwise112            // leave selection past the new end and renderWidget would index OOB.113            selection = 0;114            meta = null;115            // fall through to the common render below116        } else {117            var buf: [4]u8 = undefined;118            const n = std.posix.read(STDIN_FD, &buf) catch break;119            if (n == 0) break;120121            // The query is a live text field, so every printable key types into it —122            // single-letter actions would collide with package names (the 'i' in123            // "ripgrep" must not trigger install). Only non-text keys act: Enter124            // selects, Tab expands detail, arrows navigate, Esc cancels.125            if (n >= 3 and buf[0] == 0x1b and buf[1] == '[') {126                switch (buf[2]) {127                    'A' => if (selection > 0) { selection -= 1; }, // up128                    'B' => if (selection + 1 < resultCount(packages, opts, mode)) { selection += 1; }, // down129                    else => {},130                }131            } else switch (buf[0]) {132                0x1b => break :loop, // Esc: cancel (chosen stays null)133                '\t' => expanded = !expanded, // Tab: toggle package detail134                '\r', '\n' => { // Enter: select the highlighted package135                    if (mode == .packages and packages.len > selection) {136                        chosen = packages[selection];137                    }138                    break :loop;139                },140                127, 8 => { // backspace141                    if (query_len > 0) {142                        query_len -= 1;143                        query_dirty = true;144                        query_changed_at = std.Io.Clock.awake.now(io);145                        selection = 0;146                    }147                },148                else => |ch| {149                    if (ch >= 32 and ch < 127 and query_len < query_buf.len - 1) {150                        query_buf[query_len] = ch;151                        query_len += 1;152                        query_dirty = true;153                        query_changed_at = std.Io.Clock.awake.now(io);154                        selection = 0;155                    }156                },157            }158        }159160        // Common render after a search or a key. When expanded, resolve the detail161        // pane by fetching the selected package's meta on demand (blocking eval),162        // painting a "loading" frame first and caching by attr so re-visiting is163        // instant.164        const count = resultCount(packages, opts, mode);165        const sel = if (count == 0) 0 else @min(selection, count - 1);166        var detail: Detail = .collapsed;167        if (expanded and mode == .packages and count > 0) {168            const cur = packages[sel].attr;169            if (meta == null or !std.mem.eql(u8, meta_attr, cur)) {170                output.cursorUp(WIDGET_LINES);171                renderWidget(query_buf[0..query_len], packages, opts, selection, mode, false, .loading);172                output.flush();173                _ = meta_arena.reset(.free_all);174                meta_attr = meta_arena.allocator().dupe(u8, cur) catch "";175                meta = api.packageMeta(meta_arena.allocator(), io, cur);176            }177            detail = if (meta) |mm| Detail{ .meta = mm } else Detail.unavailable;178        }179        output.cursorUp(WIDGET_LINES);180        renderWidget(query_buf[0..query_len], packages, opts, selection, mode, false, detail);181        output.flush();182    }183184    // Clear the widget area185    output.cursorUp(WIDGET_LINES);186    var i: usize = 0;187    while (i < WIDGET_LINES) : (i += 1) {188        output.raw(output.C_CLEAR_EOL ++ "\n");189    }190    output.cursorUp(WIDGET_LINES);191    output.flush();192193    // The chosen package's strings live in the search arena, which deinits as this194    // function returns — dupe into the caller's allocator so it survives.195    if (chosen) |pkg| return dupePackage(gpa, pkg);196    return null;197}198199fn dupePackage(gpa: std.mem.Allocator, pkg: types.NixPackage) types.NixPackage {200    return .{201        .attr = gpa.dupe(u8, pkg.attr) catch "",202        .pname = gpa.dupe(u8, pkg.pname) catch "",203        .version = gpa.dupe(u8, pkg.version) catch "",204        .description = gpa.dupe(u8, pkg.description) catch "",205    };206}207208pub const Mode = enum { packages, options };209210fn doSearch(arena: std.mem.Allocator, io: std.Io, query: []const u8, mode: Mode, opts: *[]api.NixOption) []types.NixPackage {211    // An empty query matches the entire catalog (100k+ rows) — a multi-second212    // fetch that would freeze the widget. Show nothing until there's a query.213    if (std.mem.trim(u8, query, " \t").len == 0) {214        opts.* = &.{};215        return &.{};216    }217    switch (mode) {218        .packages => return api.searchPackages(arena, io, query) catch &.{},219        .options => {220            opts.* = api.searchOptions(arena, io, query) catch &.{};221            return &.{};222        },223    }224}225226fn resultCount(packages: []types.NixPackage, opts: []api.NixOption, mode: Mode) usize {227    return switch (mode) {228        .packages => packages.len,229        .options => opts.len,230    };231}232233fn stdinIsTty(io: std.Io) bool {234    return std.Io.File.stdin().isTty(io) catch false;235}236237// Plain, non-interactive rendering for non-tty stdin. Same pink :: header and238// result count the widget shows, then one line per result; no cursor control.239fn runPlain(gpa: std.mem.Allocator, io: std.Io, query: []const u8, mode: Mode) !?types.NixPackage {240    // An empty query matches the entire catalog (100k+ rows); refuse it cleanly.241    if (std.mem.trim(u8, query, " \t").len == 0) {242        output.searchEmptyQuery();243        output.flush();244        return null;245    }246    var arena = std.heap.ArenaAllocator.init(gpa);247    defer arena.deinit();248    var opts: []api.NixOption = &.{};249    const packages = doSearch(arena.allocator(), io, query, mode, &opts);250    const count = resultCount(packages, opts, mode);251    const mode_str = if (mode == .packages) "nixpkgs" else "options";252    output.searchPlainHeader(mode_str, query, count);253    if (count == 0) {254        output.searchPlainNoResults();255        output.flush();256        return null;257    }258    switch (mode) {259        // unfree=false: per-result meta.unfree would need an eval per package (too260        // slow for the list); the TUI detail pane is the place to surface it.261        .packages => for (packages) |pkg| output.searchPlainPackage(pkg.pname, pkg.version, pkg.description, false),262        .options => for (opts) |opt| output.searchPlainOption(opt.name, opt.type_str),263    }264    output.flush();265    return null;266}267268// A key hint with dim brackets and a pink letter: dim '[', pink label, dim ']'.269// Comptime-built so it's a plain string literal — the widget always renders raw270// ANSI (it only runs on a real tty).271fn keyHint(comptime label: []const u8) []const u8 {272    return output.C_DIM ++ "[" ++ output.C_RESET ++ output.C_PINK ++ label ++ output.C_RESET ++ output.C_DIM ++ "]" ++ output.C_RESET;273}274275fn renderWidget(query: []const u8, packages: []types.NixPackage, opts: []api.NixOption, selection: usize, mode: Mode, searching: bool, detail: Detail) void {276    const count = resultCount(packages, opts, mode);277    const CLR = output.C_CLEAR_EOL;278    const RST = output.C_RESET;279    const PKN = output.C_PINK;280    const BLD = output.C_BOLD;281    const DIM = output.C_DIM;282    const CYN = output.C_CYAN;283284    // Clamp to the current result count: a caller could hand us a selection from a285    // larger, now-replaced result set. Never index past the end.286    const sel = if (count == 0) 0 else @min(selection, count - 1);287288    // Line 1: header. While the (blocking) search runs, show "searching..." so the289    // pause reads as work-in-progress, not a frozen widget.290    output.raw(CLR);291    const mode_str = if (mode == .packages) "nixpkgs" else "options";292    if (searching) {293        output.p("{s}:: {s}search {s} {s}  {s}searching...{s}\n", .{294            PKN, RST, mode_str, query, DIM, RST,295        });296    } else {297        output.p("{s}:: {s}search {s} {s}  {s}{d} results{s}\n", .{298            PKN, RST, mode_str, query, DIM, count, RST,299        });300    }301302    // Line 2: blank303    output.raw(CLR ++ "\n");304305    // Lines 3-7: results (up to RESULT_ROWS), scrolled so selection stays visible306    const scroll: usize = if (sel >= RESULT_ROWS) sel - RESULT_ROWS + 1 else 0;307    var i: usize = 0;308    while (i < RESULT_ROWS) : (i += 1) {309        const idx = scroll + i;310        output.raw(CLR);311        if (idx < count) {312            const selected = (idx == sel);313            switch (mode) {314                .packages => {315                    const pkg = packages[idx];316                    const marker = if (selected) PKN ++ "> " ++ RST else "  ";317                    const name_pre = if (selected) PKN ++ BLD else "";318                    const name_suf = if (selected) RST else "";319                    output.p("   {s}{s}{s}{s}   {s}{s}{s}   {s}\n", .{ marker, name_pre, pkg.pname, name_suf, CYN, pkg.version, RST, pkg.description });320                },321                .options => {322                    const opt = opts[idx];323                    const marker = if (selected) PKN ++ "> " ++ RST else "  ";324                    output.p("   {s}{s}   {s}{s}{s}\n", .{ marker, opt.name, DIM, opt.type_str, RST });325                },326            }327        } else {328            output.raw("\n");329        }330    }331332    // Line 8: blank333    output.raw(CLR ++ "\n");334335    // Lines 9-12: selected package detail. Line 9 (name+version) is shared; the336    // next three lines depend on `detail`. Every arm emits exactly 3 lines so the337    // widget stays WIDGET_LINES tall.338    if (count > 0 and mode == .packages) {339        const pkg = packages[sel];340        output.raw(CLR);341        output.p("   {s}{s}{s}{s}  {s}{s}{s}\n", .{ PKN, BLD, pkg.pname, RST, CYN, pkg.version, RST });342        switch (detail) {343            .collapsed => {344                output.raw(CLR);345                output.p("   {s}\n", .{pkg.description});346                output.raw(CLR ++ "\n");347                output.raw(CLR);348                output.p("   {s}attr{s}  {s}{s}{s}\n", .{ DIM, RST, CYN, pkg.attr, RST });349            },350            .loading => {351                output.raw(CLR);352                output.p("   {s}loading details...{s}\n", .{ DIM, RST });353                output.raw(CLR ++ "\n");354                output.raw(CLR);355                output.p("   {s}attr{s}  {s}{s}{s}\n", .{ DIM, RST, CYN, pkg.attr, RST });356            },357            .unavailable => {358                output.raw(CLR);359                output.p("   {s}details unavailable{s}\n", .{ DIM, RST });360                output.raw(CLR ++ "\n");361                output.raw(CLR);362                output.p("   {s}attr{s}  {s}{s}{s}\n", .{ DIM, RST, CYN, pkg.attr, RST });363            },364            .meta => |m| {365                const home = if (m.homepage.len > 0) m.homepage else "—";366                const lic = if (m.license.len > 0) m.license else "—";367                output.raw(CLR);368                output.p("   {s}{s:<8}{s}{s}{s}{s}\n", .{ DIM, "home", RST, CYN, home, RST });369                output.raw(CLR);370                output.p("   {s}{s:<8}{s}{s}\n", .{ DIM, "license", RST, lic });371                output.raw(CLR);372                output.p("   {s}{s:<8}{s}{s}{s}{s}\n", .{ DIM, "attr", RST, CYN, pkg.attr, RST });373            },374        }375    } else if (count > 0 and mode == .options) {376        const opt = opts[sel];377        output.raw(CLR);378        output.p("   {s}  {s}{s}{s}\n", .{ opt.name, DIM, opt.type_str, RST });379        output.raw(CLR);380        output.p("   {s}\n", .{opt.description});381        output.raw(CLR ++ "\n");382        output.raw(CLR ++ "\n");383    } else {384        output.raw(CLR ++ "\n");385        output.raw(CLR ++ "\n");386        output.raw(CLR ++ "\n");387        output.raw(CLR ++ "\n");388    }389390    // Line 13: blank391    output.raw(CLR ++ "\n");392393    // Lines 14-17: controls + padding to reach WIDGET_LINES394    output.raw(CLR);395    if (mode == .packages) {396        output.p("   {s} install  {s} info  {s}[up/down]{s} nav  {s} cancel\n", .{397            keyHint("enter"), keyHint("tab"), DIM, RST, keyHint("esc"),398        });399    } else {400        output.p("   {s}[up/down]{s} nav  {s} cancel\n", .{ DIM, RST, keyHint("esc") });401    }402    // Padding to reach WIDGET_LINES (18)403    var pad: usize = 14;404    while (pad < WIDGET_LINES) : (pad += 1) {405        output.raw(CLR ++ "\n");406    }407}408409fn rawModeEnable(fd: std.posix.fd_t, saved: *std.posix.termios) !void {410    var tio = try std.posix.tcgetattr(fd);411    saved.* = tio;412    if (comptime builtin.os.tag == .linux) {413        tio.lflag.ECHO = false;414        tio.lflag.ICANON = false;415        tio.lflag.ISIG = false;416        tio.lflag.IEXTEN = false;417        tio.iflag.ICRNL = false;418        tio.iflag.IXON = false;419        tio.cc[@intFromEnum(std.posix.V.MIN)] = 1;420        tio.cc[@intFromEnum(std.posix.V.TIME)] = 0;421    }422    // On non-Linux, terminal will not be in raw mode (TUI requires Linux)423    try std.posix.tcsetattr(fd, .FLUSH, tio);424}425426fn rawModeDisable(fd: std.posix.fd_t, saved: std.posix.termios) void {427    std.posix.tcsetattr(fd, .FLUSH, saved) catch {};428}