search.zig

13.6 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. Without it, every character fired a full `nix search`, stalling mid-word.15const DEBOUNCE_MS: i64 = 250;1617// Milliseconds elapsed since `since` on the monotonic (awake) clock. std has no18// milliTimestamp in 0.16; this mirrors the Io.Clock pattern used in apply().19fn elapsedMs(io: std.Io, since: std.Io.Timestamp) i64 {20    const ns = @max(0, since.untilNow(io, .awake).toNanoseconds());21    return @intCast(@divFloor(ns, 1_000_000));22}2324pub fn run(25    gpa: std.mem.Allocator,26    io: std.Io,27    initial_query: []const u8,28    mode: Mode,29) !?types.SearchResult {30    // Non-interactive fallback: when stdin isn't a terminal (piped, scripted,31    // CI), print plain results and return instead of the raw-mode widget, which32    // needs a real tty and would block waiting for keys.33    if (!stdinIsTty(io)) return runPlain(gpa, io, initial_query, mode);3435    var saved: std.posix.termios = undefined;36    try rawModeEnable(STDIN_FD, &saved);37    defer rawModeDisable(STDIN_FD, saved);3839    var arena = std.heap.ArenaAllocator.init(gpa);40    defer arena.deinit();4142    var query_buf: [256]u8 = undefined;43    var query_len: usize = @min(initial_query.len, query_buf.len - 1);44    @memcpy(query_buf[0..query_len], initial_query[0..query_len]);4546    var packages: []types.NixPackage = &.{};47    var opts: []api.NixOption = &.{};48    var selection: usize = 0;4950    // Initial search51    _ = arena.reset(.free_all);52    packages = doSearch(arena.allocator(), io, query_buf[0..query_len], mode, &opts);5354    // Initial render (prints WIDGET_LINES lines)55    renderWidget(query_buf[0..query_len], packages, opts, selection, mode);56    output.flush();5758    // Key loop with debounced search. A keystroke marks the query dirty and59    // stamps the time; the nix search fires only once typing pauses for60    // DEBOUNCE_MS. Stale results stay on screen until the new search returns, so61    // there is no blank flash mid-typing.62    var chosen: ?types.SearchResult = null;63    var query_dirty = false;64    var query_changed_at = std.Io.Clock.awake.now(io);65    loop: while (true) {66        // Block until a key arrives, unless a search is pending — then wake when67        // the debounce window closes so we can fire it.68        var timeout_ms: i32 = -1;69        if (query_dirty) {70            const remaining = DEBOUNCE_MS - elapsedMs(io, query_changed_at);71            timeout_ms = if (remaining <= 0) 0 else @intCast(remaining);72        }7374        var pfd = [_]std.posix.pollfd{.{ .fd = STDIN_FD, .events = std.posix.POLL.IN, .revents = 0 }};75        const ready = std.posix.poll(&pfd, timeout_ms) catch 0;7677        if (ready == 0) {78            // Poll timed out: typing has paused long enough — run the search now.79            if (query_dirty and elapsedMs(io, query_changed_at) >= DEBOUNCE_MS) {80                query_dirty = false;81                _ = arena.reset(.free_all);82                packages = doSearch(arena.allocator(), io, query_buf[0..query_len], mode, &opts);83                output.cursorUp(WIDGET_LINES);84                renderWidget(query_buf[0..query_len], packages, opts, selection, mode);85                output.flush();86            }87            continue;88        }8990        var buf: [4]u8 = undefined;91        const n = std.posix.read(STDIN_FD, &buf) catch break;92        if (n == 0) break;9394        if (n >= 3 and buf[0] == 0x1b and buf[1] == '[') {95            switch (buf[2]) {96                'A' => if (selection > 0) { selection -= 1; }, // up97                'B' => if (selection + 1 < resultCount(packages, opts, mode)) { selection += 1; }, // down98                else => {},99            }100        } else switch (buf[0]) {101            'k' => if (selection > 0) { selection -= 1; },102            'j' => if (selection + 1 < resultCount(packages, opts, mode)) { selection += 1; },103            0x1b, 'q' => break :loop,104            'i', '\r' => {105                if (mode == .packages and packages.len > selection) {106                    chosen = .{ .package = packages[selection], .action = .profile };107                }108                break :loop;109            },110            's' => {111                if (mode == .packages and packages.len > selection) {112                    chosen = .{ .package = packages[selection], .action = .system };113                }114                break :loop;115            },116            't' => {117                if (mode == .packages and packages.len > selection) {118                    chosen = .{ .package = packages[selection], .action = .profile };119                    // flag: try mode — caller handles120                }121                break :loop;122            },123            'c' => {124                // Copy attr to clipboard (best-effort via pbcopy/xclip/xsel)125                if (mode == .packages and packages.len > selection) {126                    copyToClipboard(gpa, io, packages[selection].attr);127                }128            },129            127 => { // backspace130                if (query_len > 0) {131                    query_len -= 1;132                    query_dirty = true;133                    query_changed_at = std.Io.Clock.awake.now(io);134                    selection = 0;135                }136            },137            else => |ch| {138                if (ch >= 32 and ch < 127 and query_len < query_buf.len - 1) {139                    query_buf[query_len] = ch;140                    query_len += 1;141                    query_dirty = true;142                    query_changed_at = std.Io.Clock.awake.now(io);143                    selection = 0;144                }145            },146        }147148        // Redraw immediately so the query line and selection feel responsive; the149        // search itself is deferred to the debounce tick above.150        output.cursorUp(WIDGET_LINES);151        renderWidget(query_buf[0..query_len], packages, opts, selection, mode);152        output.flush();153    }154155    // Clear the widget area156    output.cursorUp(WIDGET_LINES);157    var i: usize = 0;158    while (i < WIDGET_LINES) : (i += 1) {159        output.raw(output.C_CLEAR_EOL ++ "\n");160    }161    output.cursorUp(WIDGET_LINES);162    output.flush();163164    return chosen;165}166167pub const Mode = enum { packages, options };168169fn doSearch(arena: std.mem.Allocator, io: std.Io, query: []const u8, mode: Mode, opts: *[]api.NixOption) []types.NixPackage {170    switch (mode) {171        .packages => return api.searchPackages(arena, io, query) catch &.{},172        .options => {173            opts.* = api.searchOptions(arena, io, query) catch &.{};174            return &.{};175        },176    }177}178179fn resultCount(packages: []types.NixPackage, opts: []api.NixOption, mode: Mode) usize {180    return switch (mode) {181        .packages => packages.len,182        .options => opts.len,183    };184}185186fn stdinIsTty(io: std.Io) bool {187    return std.Io.File.stdin().isTty(io) catch false;188}189190// Plain, non-interactive rendering for non-tty stdin. Same pink :: header and191// result count the widget shows, then one line per result; no cursor control.192fn runPlain(gpa: std.mem.Allocator, io: std.Io, query: []const u8, mode: Mode) !?types.SearchResult {193    // An empty query matches the entire catalog (100k+ rows); refuse it cleanly.194    if (std.mem.trim(u8, query, " \t").len == 0) {195        output.searchEmptyQuery();196        output.flush();197        return null;198    }199    var arena = std.heap.ArenaAllocator.init(gpa);200    defer arena.deinit();201    var opts: []api.NixOption = &.{};202    const packages = doSearch(arena.allocator(), io, query, mode, &opts);203    const count = resultCount(packages, opts, mode);204    const mode_str = if (mode == .packages) "nixpkgs" else "options";205    output.searchPlainHeader(mode_str, query, count);206    if (count == 0) {207        output.searchPlainNoResults();208        output.flush();209        return null;210    }211    switch (mode) {212        // unfree=false: per-result meta.unfree would need an eval per package (too213        // slow for the list); the TUI detail pane is the place to surface it.214        .packages => for (packages) |pkg| output.searchPlainPackage(pkg.pname, pkg.version, pkg.description, false),215        .options => for (opts) |opt| output.searchPlainOption(opt.name, opt.type_str),216    }217    output.flush();218    return null;219}220221// A key hint with dim brackets and a pink letter: dim '[', pink label, dim ']'.222// Comptime-built so it's a plain string literal — the widget always renders raw223// ANSI (it only runs on a real tty).224fn keyHint(comptime label: []const u8) []const u8 {225    return output.C_DIM ++ "[" ++ output.C_RESET ++ output.C_PINK ++ label ++ output.C_RESET ++ output.C_DIM ++ "]" ++ output.C_RESET;226}227228fn renderWidget(query: []const u8, packages: []types.NixPackage, opts: []api.NixOption, selection: usize, mode: Mode) void {229    const count = resultCount(packages, opts, mode);230    const CLR = output.C_CLEAR_EOL;231    const RST = output.C_RESET;232    const PKN = output.C_PINK;233    const BLD = output.C_BOLD;234    const DIM = output.C_DIM;235    const CYN = output.C_CYAN;236237    // Line 1: header238    output.raw(CLR);239    const mode_str = if (mode == .packages) "nixpkgs" else "options";240    output.p("{s}:: {s}search {s} {s}  {s}{d} results{s}\n", .{241        PKN, RST, mode_str, query, DIM, count, RST,242    });243244    // Line 2: blank245    output.raw(CLR ++ "\n");246247    // Lines 3-7: results (up to RESULT_ROWS), scrolled so selection stays visible248    const scroll: usize = if (selection >= RESULT_ROWS) selection - RESULT_ROWS + 1 else 0;249    var i: usize = 0;250    while (i < RESULT_ROWS) : (i += 1) {251        const idx = scroll + i;252        output.raw(CLR);253        if (idx < count) {254            const selected = (idx == selection);255            switch (mode) {256                .packages => {257                    const pkg = packages[idx];258                    const marker = if (selected) PKN ++ "> " ++ RST else "  ";259                    const name_pre = if (selected) PKN ++ BLD else "";260                    const name_suf = if (selected) RST else "";261                    output.p("   {s}{s}{s}{s}   {s}{s}{s}   {s}\n", .{ marker, name_pre, pkg.pname, name_suf, CYN, pkg.version, RST, pkg.description });262                },263                .options => {264                    const opt = opts[idx];265                    const marker = if (selected) PKN ++ "> " ++ RST else "  ";266                    output.p("   {s}{s}   {s}{s}{s}\n", .{ marker, opt.name, DIM, opt.type_str, RST });267                },268            }269        } else {270            output.raw("\n");271        }272    }273274    // Line 8: blank275    output.raw(CLR ++ "\n");276277    // Lines 9-12: selected package detail278    if (count > 0 and mode == .packages) {279        const pkg = packages[selection];280        output.raw(CLR);281        output.p("   {s}{s}{s}{s}  {s}{s}{s}\n", .{ PKN, BLD, pkg.pname, RST, CYN, pkg.version, RST });282        output.raw(CLR);283        output.p("   {s}\n", .{pkg.description});284        output.raw(CLR ++ "\n");285        output.raw(CLR);286        output.p("   {s}attr{s}  {s}{s}{s}\n", .{ DIM, RST, CYN, pkg.attr, RST });287    } else if (count > 0 and mode == .options) {288        const opt = opts[selection];289        output.raw(CLR);290        output.p("   {s}  {s}{s}{s}\n", .{ opt.name, DIM, opt.type_str, RST });291        output.raw(CLR);292        output.p("   {s}\n", .{opt.description});293        output.raw(CLR ++ "\n");294        output.raw(CLR ++ "\n");295    } else {296        output.raw(CLR ++ "\n");297        output.raw(CLR ++ "\n");298        output.raw(CLR ++ "\n");299        output.raw(CLR ++ "\n");300    }301302    // Line 13: blank303    output.raw(CLR ++ "\n");304305    // Lines 14-17: controls + padding to reach WIDGET_LINES306    output.raw(CLR);307    if (mode == .packages) {308        output.p("   {s} profile  {s} system  {s} try  {s} copy  {s}[up/down]{s} nav  {s} exit\n", .{309            keyHint("i"), keyHint("s"), keyHint("t"), keyHint("c"), DIM, RST, keyHint("esc"),310        });311    } else {312        output.p("   {s} insert  {s}[up/down]{s} nav  {s} exit\n", .{ keyHint("i"), DIM, RST, keyHint("esc") });313    }314    // Padding to reach WIDGET_LINES (18)315    var pad: usize = 14;316    while (pad < WIDGET_LINES) : (pad += 1) {317        output.raw(CLR ++ "\n");318    }319}320321fn copyToClipboard(gpa: std.mem.Allocator, io: std.Io, text: []const u8) void {322    _ = gpa;323    // Try common clipboard tools324    const tools = [_][]const u8{ "pbcopy", "xclip", "xsel" };325    for (tools) |tool| {326        var child = std.process.spawn(io, .{327            .argv = &.{tool},328            .stdin = .pipe,329            .stdout = .ignore,330            .stderr = .ignore,331        }) catch continue;332        if (child.stdin) |stdin| {333            stdin.writeStreamingAll(io, text) catch {};334            stdin.close(io);335        }336        _ = child.wait(io) catch {};337        return;338    }339}340341fn rawModeEnable(fd: std.posix.fd_t, saved: *std.posix.termios) !void {342    var tio = try std.posix.tcgetattr(fd);343    saved.* = tio;344    if (comptime builtin.os.tag == .linux) {345        tio.lflag.ECHO = false;346        tio.lflag.ICANON = false;347        tio.lflag.ISIG = false;348        tio.lflag.IEXTEN = false;349        tio.iflag.ICRNL = false;350        tio.iflag.IXON = false;351        tio.cc[@intFromEnum(std.posix.V.MIN)] = 1;352        tio.cc[@intFromEnum(std.posix.V.TIME)] = 0;353    }354    // On non-Linux, terminal will not be in raw mode (TUI requires Linux)355    try std.posix.tcsetattr(fd, .FLUSH, tio);356}357358fn rawModeDisable(fd: std.posix.fd_t, saved: std.posix.termios) void {359    std.posix.tcsetattr(fd, .FLUSH, saved) catch {};360}