scry-cli 0.3.0

grep for images: search by metadata, OCR text, and meaning
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
use std::{
    borrow::Cow,
    fmt::{self, Write as _},
    fs::File,
    io::{self, BufWriter, IsTerminal, Write},
    os::{
        fd::{AsFd, BorrowedFd, OwnedFd},
        unix::ffi::OsStrExt,
    },
    path::{Path, PathBuf},
    sync::{
        LazyLock,
        atomic::{AtomicUsize, Ordering::Relaxed},
        mpsc::{Receiver, RecvTimeoutError, TryRecvError},
    },
    time::Duration,
};

use anyhow::Result;
use indicatif::{HumanDuration, ProgressBar};
use ratatui::{
    backend::IntoCrossterm,
    buffer::Buffer,
    crossterm::{
        cursor::{MoveDown, MoveRight, MoveUp, RestorePosition, SavePosition},
        queue,
        style::{Colors, Print, ResetColor, SetColors, available_color_count},
        terminal,
    },
    layout::{Position, Rect, Size},
    style::Color,
    widgets::Widget,
};
use ratatui_image::{
    FontSize, Image, Resize,
    picker::{Picker, ProtocolType, cap_parser::QueryStdioOptions},
};
use rustix::{
    event::{PollFd, PollFlags, Timespec},
    fs::{OFlags, fcntl_getfl},
    stdio,
    termios::{self, OptionalActions, Termios},
};

use crate::{
    decode,
    search::{Hit, Progress, Search},
    walk::Skipped,
};

pub struct ListOpts {
    pub score: bool,
    pub preview: bool,
    pub end: End,
}

/// What ends each path on stdin and stdout.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum End {
    Newline,
    Nul,
}

impl End {
    pub fn byte(self) -> u8 {
        match self {
            End::Newline => b'\n',
            End::Nul => b'\0',
        }
    }
}

const THUMB_ROWS: u16 = 10;
const TICK: Duration = Duration::from_millis(100);

pub fn list(search: Search, opts: &ListOpts) -> Result<usize> {
    let mut out = Printer::stdout(opts.end);
    let preview = (opts.preview && out.tty).then(Preview::new).transpose()?;
    // A sorted search sees all images before the first hit, so progress shows until then.
    let spinner = ProgressBar::new_spinner();
    spinner.enable_steady_tick(TICK);
    let mut hit = next(
        &search.hits,
        || Ok(true),
        || {
            let left = time_left(&spinner, &search.progress);
            spinner.set_message(format!("{}{left}", search.status()));
        },
    )?;
    spinner.finish_and_clear();

    let mut printed = 0;
    while let Some(h) = hit {
        if let Some(preview) = &preview {
            preview.show(&mut out.out, &h.path)?;
        }
        if !out.record(h.score.filter(|_| opts.score), &h.path, &h.text)? {
            return Ok(printed);
        }
        printed += 1;
        hit = next(&search.hits, || out.flush(), || {})?;
    }
    out.flush()?;
    Ok(printed)
}

pub fn paths(paths: &[PathBuf], end: End) -> io::Result<()> {
    let mut out = Printer::stdout(end);
    for path in paths {
        if !out.record(None, path, &[])? {
            return Ok(());
        }
    }
    out.flush().map(drop)
}

/// The next hit, or None at the end or once nobody reads stdout. Runs `flush` before it waits,
/// so each hit shows as soon as it comes, and `tick` while it waits.
fn next(
    hits: &Receiver<Result<Hit>>,
    flush: impl FnOnce() -> io::Result<bool>,
    mut tick: impl FnMut(),
) -> Result<Option<Hit>> {
    match hits.try_recv() {
        Ok(hit) => return hit.map(Some),
        Err(TryRecvError::Disconnected) => return Ok(None),
        Err(TryRecvError::Empty) => {}
    }
    if !flush()? {
        return Ok(None);
    }
    loop {
        match hits.recv_timeout(TICK) {
            Ok(hit) => return hit.map(Some),
            Err(RecvTimeoutError::Disconnected) => return Ok(None),
            Err(RecvTimeoutError::Timeout) if closed(io::stdout()) => return Ok(None),
            Err(RecvTimeoutError::Timeout) => tick(),
        }
    }
}

/// The kernel flags a pipe once its reader is gone, before a write fails. macOS flags it only
/// for a poll that asks for POLLOUT. Without this check, `scry -t x | head -1` would read every
/// image after head exits.
fn closed(out: impl AsFd) -> bool {
    let mut fds = [PollFd::new(&out, PollFlags::OUT)];
    rustix::event::poll(&mut fds, Some(&Timespec::default()))
        .is_ok_and(|_| fds[0].revents().intersects(PollFlags::ERR | PollFlags::HUP))
}

/// Tells why images are missing from the output.
pub fn notes(progress: &Progress, skipped: Option<Skipped>) {
    let count = |n: &AtomicUsize| n.load(Relaxed);
    let files = |n| if n == 1 { "file" } else { "files" };
    let (found, unsupported, errors) = (
        count(&progress.found),
        count(&progress.unsupported),
        count(&progress.errors),
    );
    let mut notes = String::new();
    if unsupported > 0 {
        notes += &format!(
            "scry: skipped {unsupported} {} {}: scry cannot read these formats yet\n",
            decode::UNSUPPORTED,
            files(unsupported)
        );
    }
    if errors > 0 {
        notes += &format!("scry: skipped {errors} unreadable {}\n", files(errors));
    }
    if found + unsupported == 0 {
        notes += "scry: found no image files\n";
        if let Some(skipped) = skipped {
            notes += &skip_tip(skipped);
        }
    }
    // stderr is unbuffered: one write keeps the lines whole next to stdout.
    let _ = io::stderr().write_all(notes.as_bytes());
}

fn skip_tip(skipped: Skipped) -> String {
    let (what, flags) = match skipped {
        Skipped::Hidden => ("hidden files", "--hidden"),
        Skipped::Ignored => ("the paths in .gitignore files", "--no-ignore"),
        Skipped::Both => (
            "hidden files and the paths in .gitignore files",
            "--hidden and --no-ignore",
        ),
    };
    format!("tip: scry skips {what}. Use {flags} to search them.\n")
}

/// Feeds the progress to the estimate in `bar`, and returns text like ", about 3 minutes left"
/// once the estimate has enough data.
pub fn time_left(bar: &ProgressBar, progress: &Progress) -> String {
    let (done, found) = (progress.done.load(Relaxed), progress.found.load(Relaxed));
    bar.set_length(found as u64);
    bar.set_position(done as u64);
    if done == 0 || done == found || bar.elapsed() < Duration::from_secs(3) {
        return String::new();
    }
    format!(", about {} left", HumanDuration(bar.eta()))
}

/// Asks the terminal which image protocol it supports. Kitty can read images from shared memory,
/// so the pixels do not go through the terminal and tmux as text.
pub fn picker() -> Result<Picker> {
    let options = QueryStdioOptions {
        kitty_shared_memory_object: QueryStdioOptions::probe_kitty_smo(),
        ..Default::default()
    };
    Ok(Picker::from_query_stdio_with_options(options)?)
}

/// Gives half blocks the nearest xterm colors if the terminal has no 24-bit color, as Terminal.app
/// before macOS 26. A terminal with 24-bit color tells it in COLORTERM.
pub fn fit_colors(buf: &mut Buffer, area: Rect) {
    static TRUECOLOR: LazyLock<bool> = LazyLock::new(|| available_color_count() == u16::MAX);
    if *TRUECOLOR {
        return;
    }
    for pos in area.intersection(buf.area).positions() {
        let cell = &mut buf[pos];
        cell.fg = xterm(cell.fg);
        cell.bg = xterm(cell.bg);
    }
}

/// The nearest color in the 6 x 6 x 6 cube of xterm, whose levels are 0, 95, 135, 175, 215 and 255.
fn xterm(color: Color) -> Color {
    let Color::Rgb(r, g, b) = color else {
        return color;
    };
    let level = |v: u8| match v {
        0..48 => 0,
        48..115 => 1,
        _ => (v - 35) / 40,
    };
    Color::Indexed(16 + 36 * level(r) + 6 * level(g) + level(b))
}

/// The controlling terminal. A copy of a stdio fd comes first, because macOS cannot poll an open
/// /dev/tty. A copy also needs no access to the device file, which after `su` belongs to another
/// user.
pub fn tty() -> io::Result<OwnedFd> {
    let stdio = [stdio::stdin(), stdio::stdout(), stdio::stderr()];
    if let Some(fd) = stdio.into_iter().find(|&fd| controls(fd)) {
        return fd.try_clone_to_owned();
    }
    if cfg!(target_os = "macos") {
        return Err(io::Error::other(
            "on macOS, stdin, stdout or stderr must be the terminal",
        ));
    }
    let tty = File::options().read(true).write(true).open("/dev/tty")?;
    Ok(tty.into())
}

/// True if `fd` is the controlling terminal, open to read and write. Not tcgetsid: macOS returns
/// a session for a terminal that is not the controlling terminal.
fn controls(fd: BorrowedFd) -> bool {
    termios::tcgetpgrp(fd).is_ok()
        && fcntl_getfl(fd).is_ok_and(|flags| flags & OFlags::RWMODE == OFlags::RDWR)
}

/// Writes one record per hit: the score, the path and the text, separated by tabs. Pipes get
/// raw bytes. A terminal gets clean text, and paths without the `./` that the walk puts before
/// paths in the current directory. In a pipe, the `./` keeps a name like `-x.jpg` from passing
/// as an option.
struct Printer<W> {
    out: W,
    tty: bool,
    end: End,
}

impl Printer<BufWriter<io::StdoutLock<'static>>> {
    fn stdout(end: End) -> Self {
        Self {
            out: BufWriter::new(io::stdout().lock()),
            tty: io::stdout().is_terminal(),
            end,
        }
    }
}

impl<W: Write> Printer<W> {
    /// False once nobody reads the output.
    fn record(&mut self, score: Option<f32>, path: &Path, text: &[String]) -> io::Result<bool> {
        has_reader(self.write(score, path, text))
    }

    fn flush(&mut self) -> io::Result<bool> {
        has_reader(self.out.flush())
    }

    fn write(&mut self, score: Option<f32>, path: &Path, text: &[String]) -> io::Result<()> {
        if let Some(score) = score {
            write!(self.out, "{}\t", format_score(score))?;
        }
        if self.tty {
            write!(
                self.out,
                "{}",
                clean_path(path.strip_prefix("./").unwrap_or(path))
            )?;
        } else {
            self.out.write_all(path.as_os_str().as_bytes())?;
        }
        for field in text {
            self.out.write_all(b"\t")?;
            if self.tty {
                write!(self.out, "{}", clean(field))?;
            } else {
                self.out.write_all(field.as_bytes())?;
            }
        }
        self.out.write_all(&[self.end.byte()])
    }
}

/// A broken pipe is the normal end of `scry ... | head`.
fn has_reader(written: io::Result<()>) -> io::Result<bool> {
    match written {
        Ok(()) => Ok(true),
        Err(e) if e.kind() == io::ErrorKind::BrokenPipe => Ok(false),
        Err(e) => Err(e),
    }
}

/// A file name or other untrusted text, made safe to show in a terminal.
pub struct Clean<'a>(Cow<'a, str>);

pub fn clean(s: &str) -> Clean<'_> {
    Clean(Cow::Borrowed(s))
}

pub fn clean_path(path: &Path) -> Clean<'_> {
    Clean(path.to_string_lossy())
}

impl fmt::Display for Clean<'_> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        for (i, part) in self.0.split(control).enumerate() {
            if i > 0 {
                f.write_char('?')?;
            }
            f.write_str(part)?;
        }
        Ok(())
    }
}

/// A terminal acts on control characters, so a name could send escape sequences. Bidi
/// controls can make the text around them read in another order.
pub fn control(c: char) -> bool {
    c.is_control() || matches!(c, '\u{202a}'..='\u{202e}' | '\u{2066}'..='\u{2069}')
}

/// Like printf's `%.3g`: 3 significant digits, with an exponent below 0.0001. Most `-q` scores
/// are tiny, and a fixed number of decimals prints them all as 0.
fn format_score(score: f32) -> String {
    // The exponent after rounding to 3 digits, so 0.99999 prints as 1.
    let sci = format!("{score:.2e}");
    let (mantissa, exp) = sci.split_once('e').expect("{:e} has an exponent");
    let exp: i32 = exp.parse().expect("{:e} has an integer exponent");
    if exp < -4 {
        return format!("{}e{exp}", trim_zeros(mantissa));
    }
    trim_zeros(&format!("{score:.*}", (2 - exp).max(0) as usize)).into()
}

fn trim_zeros(s: &str) -> &str {
    if s.contains('.') {
        s.trim_end_matches('0').trim_end_matches('.')
    } else {
        s
    }
}

struct Preview {
    picker: Picker,
    _mode: TtyMode,
}

impl Preview {
    fn new() -> Result<Self> {
        // The terminal answers capability queries on stdin, which may be the piped path list.
        // The walker reads that list from its own duplicate of fd 0.
        if !io::stdin().is_terminal() {
            stdio::dup2_stdin(tty()?)?;
        }
        let mode = TtyMode(termios::tcgetattr(io::stdin())?);
        Ok(Self {
            picker: picker()?,
            _mode: mode,
        })
    }

    /// An image that fails to decode gets no thumbnail.
    fn show(&self, out: &mut impl Write, path: &Path) -> Result<()> {
        let cells = Size::new(terminal::size()?.0, THUMB_ROWS);
        let side = pixel_side(cells, self.picker.font_size());
        let Ok(img) = decode::load(path, side) else {
            return Ok(());
        };
        let thumb = self.picker.new_protocol(img, cells, Resize::Fit(None))?;
        let area = Rect::from((Position::ORIGIN, thumb.size()));
        let mut buf = Buffer::empty(area);
        Image::new(&thumb).render(area, &mut buf);
        if self.picker.protocol_type() == ProtocolType::Halfblocks {
            fit_colors(&mut buf, area);
        }
        Ok(draw(out, &buf)?)
    }
}

/// The capability query turns off echo and line editing. If the terminal does not answer in
/// time, the query returns before it turns them on again. This puts the saved mode back.
struct TtyMode(Termios);

impl Drop for TtyMode {
    fn drop(&mut self) {
        let _ = termios::tcsetattr(io::stdin(), OptionalActions::Now, &self.0);
    }
}

/// An image shrunk to fit a square of this side still fills `cells` at `font`, in either
/// orientation.
pub fn pixel_side(cells: Size, font: FontSize) -> u32 {
    (u32::from(cells.width) * u32::from(font.width))
        .max(u32::from(cells.height) * u32::from(font.height))
}

/// Draws `buf` below the cursor without knowing the cursor's screen position, so no terminal
/// round trip is needed. Image protocols put their escape sequence in the first cell and mark the
/// cells it covers as skipped. The buffer diff leaves those out.
fn draw(out: &mut impl Write, buf: &Buffer) -> io::Result<()> {
    let rows = buf.area.height;
    // Reserve the rows first so that drawing never scrolls.
    queue!(
        out,
        Print("\n".repeat(rows.into())),
        MoveUp(rows),
        SavePosition
    )?;
    let mut next = None;
    for (x, y, cell) in Buffer::empty(buf.area).diff(buf) {
        if next != Some((x, y)) {
            queue!(out, RestorePosition)?;
            if y > 0 {
                queue!(out, MoveDown(y))?;
            }
            if x > 0 {
                queue!(out, MoveRight(x))?;
            }
        }
        next = Some((x + 1, y));
        let colors = Colors::new(cell.fg.into_crossterm(), cell.bg.into_crossterm());
        queue!(out, SetColors(colors), Print(cell.symbol()))?;
    }
    queue!(out, ResetColor, RestorePosition, MoveDown(rows))
}

#[cfg(test)]
mod tests {
    use std::os::unix::ffi::OsStringExt;

    use super::*;

    fn printed(tty: bool, end: End, score: Option<f32>, path: &[u8], text: &[String]) -> Vec<u8> {
        let mut printer = Printer {
            out: Vec::new(),
            tty,
            end,
        };
        let path = PathBuf::from(std::ffi::OsString::from_vec(path.to_vec()));
        assert!(printer.record(score, &path, text).unwrap());
        printer.out
    }

    fn written(path: &[u8], score: Option<f32>, tty: bool, end: End) -> Vec<u8> {
        printed(tty, end, score, path, &[])
    }

    #[test]
    fn terminal_output_is_clean() {
        assert_eq!(
            written(b"a\x1b[2Jb.jpg", None, true, End::Newline),
            b"a?[2Jb.jpg\n"
        );
        assert_eq!(
            written("x\u{9b}y.png".as_bytes(), None, true, End::Nul),
            b"x?y.png\0"
        );
        assert_eq!(
            written(b"a\x1b\xff.jpg", None, false, End::Nul),
            b"a\x1b\xff.jpg\0"
        );
        assert_eq!(
            written("ok/čaj.jpg".as_bytes(), None, true, End::Newline),
            "ok/čaj.jpg\n".as_bytes()
        );
        assert_eq!(
            written("evil\u{202e}gpj.exe".as_bytes(), None, true, End::Newline),
            b"evil?gpj.exe\n"
        );
        assert_eq!(clean("tab\there\u{2066}").to_string(), "tab?here?");
    }

    #[test]
    fn dot_slash_stays_in_pipes() {
        assert_eq!(
            written(b"./-x.jpg", None, false, End::Newline),
            b"./-x.jpg\n"
        );
        assert_eq!(written(b"./-x.jpg", None, true, End::Newline), b"-x.jpg\n");
        assert_eq!(
            written(b"../a.jpg", None, true, End::Newline),
            b"../a.jpg\n"
        );
    }

    #[test]
    fn scores() {
        assert_eq!(
            written(b"a.jpg", Some(0.00012), false, End::Newline),
            b"0.00012\ta.jpg\n"
        );
        assert_eq!(
            written(b"a.jpg", Some(-0.5), false, End::Nul),
            b"-0.5\ta.jpg\0"
        );
        let cases = [
            (0.1287, "0.129"),
            (0.1284, "0.128"),
            (0.005812, "0.00581"),
            (0.9296, "0.93"),
            (1.0, "1"),
            (0.99999, "1"),
            (0.0, "0"),
            (-0.0512, "-0.0512"),
            (0.0001, "0.0001"),
            (1.234e-5, "1.23e-5"),
            (2.0e-9, "2e-9"),
            (2.6e-37, "2.6e-37"),
        ];
        for (score, want) in cases {
            assert_eq!(format_score(score), want, "{score}");
            let back: f32 = want.parse().unwrap();
            assert!(
                (back - score).abs() <= score.abs() * 0.005,
                "{want} parses back"
            );
        }
    }

    #[test]
    fn text_fields_follow_the_path() {
        let text = ["INV-2041".to_string(), "Total \x1b[2J".to_string()];
        assert_eq!(
            printed(true, End::Newline, Some(0.5), b"a.png", &text),
            b"0.5\ta.png\tINV-2041\tTotal ?[2J\n"
        );
    }

    #[test]
    fn xterm_colors_are_nearest() {
        let cube = |r: u8, g: u8, b: u8| Color::Indexed(16 + 36 * r + 6 * g + b);
        assert_eq!(xterm(Color::Rgb(0, 0, 0)), cube(0, 0, 0));
        assert_eq!(xterm(Color::Rgb(255, 0, 0)), cube(5, 0, 0));
        assert_eq!(xterm(Color::Rgb(47, 48, 114)), cube(0, 1, 1));
        assert_eq!(xterm(Color::Rgb(115, 154, 255)), cube(2, 2, 5));
        assert_eq!(xterm(Color::Yellow), Color::Yellow);
    }

    #[test]
    fn pipe_without_reader_is_closed() {
        let (reader, writer) = io::pipe().unwrap();
        assert!(!closed(&writer));
        drop(reader);
        assert!(closed(&writer));
    }

    #[test]
    fn broken_pipe_ends_the_output() {
        let broken = io::Error::from(io::ErrorKind::BrokenPipe);
        assert!(!has_reader(Err(broken)).unwrap());
        assert!(has_reader(Err(io::ErrorKind::Other.into())).is_err());
    }
}