cyberterm 0.4.0

A GPU terminal for developers: splits and sessions, command blocks, searchable history, AI help, inline images and Lua scripting
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
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
// src/app/blocks.rs
//
// Command blocks in the window: the gutter bar and exit/duration badge on
// each block, the block actions (copy, rerun, watch, diff, show output),
// saving finished commands to history, and notifying when a long command
// finishes out of sight.

use super::*;
use crate::blocks::{self as blk, BlockSpan};
use crate::history;
use crate::layout::Direction;
use crate::shell::BlockMeta;

/// Where a block action came from: a pane and the block's mark.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BlockRef {
    pub pane: PaneId,
    pub mark: u64,
}

pub(super) fn shell_name(program: Option<&str>) -> String {
    program
        .map(str::to_string)
        .or_else(|| std::env::var("SHELL").ok())
        .and_then(|p| p.rsplit('/').next().map(str::to_string))
        .unwrap_or_else(|| "sh".into())
}

impl App {
    // ------------------------------------------------------------------
    // Drawing
    // ------------------------------------------------------------------

    /// Adds a pane's block gutter bars and badges to its frame.
    pub(super) fn decorate_blocks(
        &self,
        pane: &Pane,
        frame: &mut Frame,
        rect: Rect,
        overlays: &mut Vec<Overlay>,
    ) {
        if !self.config.blocks.decorations {
            return;
        }
        let Some(gpu) = &self.gpu else { return };
        let (_, ch) = gpu.renderer.cell_size();
        let term = pane.session.term.lock();
        let shell = pane.session.shell.lock();
        if shell.prompts == 0 {
            return;
        }
        let offset = term.grid().display_offset() as i32;
        let rows = frame.rows as i32;
        let (top, bottom) = (-offset, rows - 1 - offset);
        let scale = gpu.window.scale_factor() as f32;
        let bar_w = (2.0 * scale).round().max(1.0);
        let bar_x = rect.x - (self.padding(gpu).min(3.0 * scale)).max(bar_w);

        for span in blk::spans_in(&*term, top, bottom) {
            let Some(meta) = blk::meta(&shell, span.mark) else {
                continue;
            };
            let color = self.block_color(meta);
            let first = span.prompt.max(top);
            let last = (span.end - 1).min(bottom);
            if first <= last {
                overlays.push(Overlay {
                    rect: Rect {
                        x: bar_x,
                        y: rect.y + (first + offset) as f32 * ch,
                        w: bar_w,
                        h: (last - first + 1) as f32 * ch,
                    },
                    color,
                    alpha: 0.9,
                });
            }
            let badge_row = span.command_end + offset;
            if (0..rows).contains(&badge_row) {
                self.draw_badge(frame, badge_row as usize, meta, color);
            }
        }
    }

    fn block_color(&self, meta: &BlockMeta) -> [u8; 3] {
        let ansi = |i: usize| frame::hex_to_rgb(self.palette.ansi[i]);
        match (meta.running(), meta.exit) {
            (true, _) => ansi(3),
            (false, Some(0)) => ansi(2),
            (false, Some(_)) => ansi(1),
            (false, None) => ansi(8),
        }
    }

    /// `✓ 1.2s` / `✗ 2 · 3.4s` / `… 12s`, right-aligned on the command row
    /// when those cells are empty.
    fn draw_badge(&self, frame: &mut Frame, row: usize, meta: &BlockMeta, color: [u8; 3]) {
        let duration = meta
            .duration_ms()
            .map(blk::format_duration)
            .unwrap_or_default();
        let text = match (meta.running(), meta.exit) {
            (true, _) => format!(" … {duration} "),
            (false, Some(0)) => format!(" ✓ {duration} "),
            (false, Some(code)) => format!(" ✗ {code} · {duration} "),
            (false, None) => return,
        };
        let len = text.chars().count();
        let cols = frame.cols;
        if cols < len + 4 {
            return;
        }
        let start = cols - len - 1;
        let cells = &mut frame.cells[row * cols..(row + 1) * cols];
        if cells[start..]
            .iter()
            .any(|c| c.ch != ' ' || c.bg != frame.bg)
        {
            return;
        }
        for (i, ch) in text.chars().enumerate() {
            let cell = &mut cells[start + i];
            cell.ch = ch;
            cell.fg = color;
        }
    }

    // ------------------------------------------------------------------
    // Lookup
    // ------------------------------------------------------------------

    /// The command block under a viewport row of the focused pane.
    pub(super) fn block_under(&self, row: usize) -> Option<(BlockRef, BlockMeta)> {
        let pane = self.focused_pane()?;
        let term = pane.session.term.lock();
        let line = row as i32 - term.grid().display_offset() as i32;
        let span = blk::block_at(&*term, line)?;
        let shell = pane.session.shell.lock();
        let meta = blk::meta(&shell, span.mark)?.clone();
        Some((
            BlockRef {
                pane: pane.id,
                mark: span.mark,
            },
            meta,
        ))
    }

    /// The newest finished command in the focused pane.
    fn last_finished(&self) -> Option<(BlockRef, BlockMeta)> {
        let pane = self.focused_pane()?;
        let shell = pane.session.shell.lock();
        let meta = shell
            .blocks
            .iter()
            .rev()
            .find(|b| b.is_command() && b.finished_ms.is_some())?
            .clone();
        Some((
            BlockRef {
                pane: pane.id,
                mark: meta.mark,
            },
            meta,
        ))
    }

    pub(super) fn span_and_output(&self, block: BlockRef) -> Option<(BlockSpan, String)> {
        let pane = self.pane(block.pane)?;
        let term = pane.session.term.lock();
        let span = blk::span_of(&*term, block.mark)?;
        let text = blk::output_text(&*term, &span);
        Some((span, text))
    }

    /// The output of the previous run of the same command: an earlier block
    /// in the same pane, else the history database.
    pub(super) fn previous_output(&self, block: BlockRef, meta: &BlockMeta) -> Option<String> {
        let command = meta.command.as_deref()?;
        if let Some(pane) = self.pane(block.pane) {
            let earlier: Option<u64> = pane
                .session
                .shell
                .lock()
                .blocks
                .iter()
                .rev()
                .filter(|b| b.mark < block.mark && b.command.as_deref() == Some(command))
                .map(|b| b.mark)
                .next();
            if let Some(mark) = earlier {
                let term = pane.session.term.lock();
                if let Some(span) = blk::span_of(&*term, mark) {
                    return Some(blk::output_text(&*term, &span));
                }
            }
        }
        if !self.config.history.enabled {
            return None;
        }
        let store = history::Store::open(&history::default_path()).ok()?;
        let cwd = meta.cwd.as_ref().map(|p| p.to_string_lossy().into_owned());
        store
            .previous_output(command, cwd.as_deref(), meta.started_ms.unwrap_or(u64::MAX))
            .ok()
            .flatten()
    }

    // ------------------------------------------------------------------
    // Actions
    // ------------------------------------------------------------------

    pub(super) fn copy_block_output(&mut self, block: BlockRef) {
        if let Some((_, text)) = self.span_and_output(block) {
            if let Some(clipboard) = &mut self.clipboard {
                clipboard.set(
                    ClipKind::Clipboard,
                    &text,
                    self.config.clipboard.clean_box_drawing,
                );
            }
        }
    }

    pub(super) fn copy_last_output(&mut self) {
        if let Some((block, _)) = self.last_finished() {
            self.copy_block_output(block);
        }
    }

    pub(super) fn copy_text(&mut self, text: &str) {
        if let Some(clipboard) = &mut self.clipboard {
            clipboard.set(ClipKind::Clipboard, text, false);
        }
    }

    /// Runs a command again in its pane, or in a new pane if that one is
    /// busy.
    pub(super) fn rerun(&mut self, block: BlockRef, command: &str) {
        let busy = self
            .pane(block.pane)
            .is_none_or(|p| p.session.shell.lock().command_running);
        if busy {
            self.run_in_split(Direction::Right, command, None);
            return;
        }
        if let Some(pane) = self.pane(block.pane) {
            pane.session.term.lock().scroll_display(Scroll::Bottom);
            pane.session.write(format!("{command}\r").into_bytes());
        }
        self.focus_pane(block.pane);
    }

    /// Opens a split in `cwd` (default: the focused shell's) running
    /// `command`.
    pub(super) fn run_in_split(&mut self, dir: Direction, command: &str, cwd: Option<PathBuf>) {
        let cwd = cwd
            .filter(|c| c.is_dir())
            .or_else(|| self.focused_pane().and_then(|p| p.session.cwd()));
        match self.split_with(dir, cwd) {
            Ok(id) => self.run_in(id, Some(command)),
            Err(e) => eprintln!("cyberterm: couldn't open a pane: {e}"),
        }
    }

    /// A pane that reruns the command every two seconds.
    pub(super) fn watch(&mut self, command: &str, cwd: Option<PathBuf>) {
        let looped = if shell_name(self.config.shell.program.as_deref()) == "fish" {
            format!("while true; clear; {command}; sleep 2; end")
        } else {
            format!("while true; do clear; {command}; sleep 2; done")
        };
        self.run_in_split(Direction::Down, &looped, cwd);
    }

    /// Opens a pane showing `diff -u` between the previous run's output and
    /// this one's.
    pub(super) fn diff_with_previous(&mut self, block: BlockRef, meta: &BlockMeta) {
        let (Some(previous), Some((_, current))) = (
            self.previous_output(block, meta),
            self.span_and_output(block),
        ) else {
            return;
        };
        let Some((old, new)) = write_temp_pair(block, &previous, &current) else {
            return;
        };
        let label = meta.command.clone().unwrap_or_default().replace('\'', "");
        // The leading space keeps viewer commands out of history (ours and
        // the shell's ignorespace convention).
        let command = format!(
            " diff -u --color=always --label 'previous: {label}' --label 'this run' '{}' '{}' | less -R",
            old.display(),
            new.display()
        );
        self.run_in_split(Direction::Down, &command, meta.cwd.clone());
    }

    pub(super) fn block_output_is_json(&self, block: BlockRef) -> bool {
        self.span_and_output(block)
            .is_some_and(|(_, text)| crate::json_viewer::looks_like_json(&text))
    }

    /// Opens a block's JSON output in `cyberterm +json`, in a split.
    pub(super) fn view_json(&mut self, block: BlockRef) {
        let Some((_, text)) = self.span_and_output(block) else {
            return;
        };
        let (Some((_, file)), Ok(exe)) =
            (write_temp_pair(block, "", &text), std::env::current_exe())
        else {
            return;
        };
        let command = format!(
            " {} +json {}",
            shell_quote(&exe.to_string_lossy()),
            shell_quote(&file.to_string_lossy())
        );
        self.run_in_split(Direction::Down, &command, None);
    }

    /// The newest finished command's output in a pager, in a split.
    pub(super) fn show_last_output(&mut self) {
        let Some((block, _)) = self.last_finished() else {
            return;
        };
        let Some((_, text)) = self.span_and_output(block) else {
            return;
        };
        self.show_text_in_pager_for(block, &text);
    }

    /// Saved output (e.g. from history) in a pager pane.
    pub(super) fn show_text_in_pager(&mut self, text: &str, id: i64) {
        let block = BlockRef {
            pane: u32::MAX,
            mark: id as u64,
        };
        self.show_text_in_pager_for(block, text);
    }

    fn show_text_in_pager_for(&mut self, block: BlockRef, text: &str) {
        let Some((_, file)) = write_temp_pair(block, "", text) else {
            return;
        };
        self.run_in_split(
            Direction::Down,
            &format!(" less -R '{}'", file.display()),
            None,
        );
    }

    // ------------------------------------------------------------------
    // History and notifications
    // ------------------------------------------------------------------

    /// After new output in a pane: save finished commands (for panes this
    /// window owns; the daemon saves its own) and notify about long ones.
    pub(super) fn blocks_changed(&mut self, index: usize) {
        let pane = &self.panes[index];
        if let (Some(recorder), false) = (&self.history, pane.session.is_remote()) {
            let records = {
                let term = pane.session.term.lock();
                let mut shell = pane.session.shell.lock();
                history::collect(&*term, &mut shell, "local", &self.history_policy)
            };
            recorder.record(records);
        }

        // Lua: commands that started since last time.
        let started: Vec<BlockMeta> = {
            let pane = &self.panes[index];
            let shell = pane.session.shell.lock();
            shell
                .blocks
                .iter()
                .filter(|b| b.mark > pane.started_mark && b.is_command() && b.started_ms.is_some())
                .cloned()
                .collect()
        };
        if let Some(newest) = started.iter().map(|b| b.mark).max() {
            let id = self.panes[index].id;
            self.panes[index].started_mark = newest;
            for b in &started {
                self.lua_emit("command_started", block_event(id, b));
            }
        }
        let pane = &self.panes[index];

        let threshold = self.config.notify.long_command_seconds;
        let finished: Vec<BlockMeta> = {
            let shell = pane.session.shell.lock();
            shell
                .blocks
                .iter()
                .filter(|b| {
                    b.mark > pane.notified_mark && b.is_command() && b.finished_ms.is_some()
                })
                .cloned()
                .collect()
        };
        let Some(newest) = finished.iter().map(|b| b.mark).max() else {
            return;
        };
        let (id, seen) = (pane.id, self.pane_in_view(pane.id));
        self.panes[index].notified_mark = newest;
        for b in &finished {
            self.lua_emit("command_finished", block_event(id, b));
        }
        if threshold == 0 || seen {
            return;
        }
        for b in finished {
            if b.duration_ms().unwrap_or(0) >= threshold * 1000 {
                notify_finished(&b, id);
            }
        }
    }

    /// Whether the user is looking at this pane right now.
    fn pane_in_view(&self, id: PaneId) -> bool {
        self.window_focused && id == self.focused
    }
}

/// `$XDG_RUNTIME_DIR/cyberterm/block-<pid>-<pane>-<mark>-{a,b}.txt`.
/// A command block as a Lua event.
fn block_event(pane: PaneId, b: &BlockMeta) -> serde_json::Value {
    serde_json::json!({
        "pane": pane,
        "command": b.command,
        "cwd": b.cwd,
        "exit": b.exit,
        "started_ms": b.started_ms,
        "finished_ms": b.finished_ms,
        "duration_ms": b.duration_ms(),
    })
}

fn write_temp_pair(block: BlockRef, a: &str, b: &str) -> Option<(PathBuf, PathBuf)> {
    let dir = crate::control::prepare_socket_dir().ok()?;
    let stem = format!("block-{}-{}-{}", std::process::id(), block.pane, block.mark);
    let (pa, pb) = (
        dir.join(format!("{stem}-a.txt")),
        dir.join(format!("{stem}-b.txt")),
    );
    std::fs::write(&pa, format!("{a}\n")).ok()?;
    std::fs::write(&pb, format!("{b}\n")).ok()?;
    Some((pa, pb))
}

fn notify_finished(b: &BlockMeta, _pane: PaneId) {
    let command = b.command.clone().unwrap_or_default();
    let short: String = command.chars().take(60).collect();
    let duration = b
        .duration_ms()
        .map(blk::format_duration)
        .unwrap_or_default();
    let (title, body) = match b.exit {
        Some(0) => (format!("✓ {short}"), format!("finished in {duration}")),
        Some(code) => (
            format!("✗ {short}"),
            format!("exit {code} after {duration}"),
        ),
        None => (short, format!("finished in {duration}")),
    };
    let body = match &b.cwd {
        Some(cwd) => format!("{body} · {}", cwd.display()),
        None => body,
    };
    spawn_detached(
        Command::new("notify-send")
            .arg("--app-name=Cyberterm")
            .arg(title)
            .arg(body),
    );
}

impl App {
    /// Opens a file reference in the user's editor at its line.
    pub(super) fn open_file(&mut self, file: &FileTarget) {
        let (argv, in_pane) = editor_command(
            self.config.links.editor.as_deref(),
            self.config.links.editor_in_pane,
            file,
        );
        if argv.is_empty() {
            return;
        }
        if in_pane {
            let line = argv
                .iter()
                .map(|a| shell_quote(a))
                .collect::<Vec<_>>()
                .join(" ");
            let dir = file.path.parent().map(PathBuf::from);
            self.run_in_split(Direction::Right, &format!(" {line}"), dir);
        } else {
            let mut command = Command::new(&argv[0]);
            command.args(&argv[1..]);
            spawn_detached(&mut command);
        }
    }
}

/// Editors that open their own window rather than running in a terminal.
const GUI_EDITORS: &[&str] = &[
    "code",
    "codium",
    "code-insiders",
    "cursor",
    "windsurf",
    "zed",
    "zeditor",
    "subl",
    "gedit",
    "kate",
];

/// The command line to open `file` at its line, and whether it runs in a
/// pane. `template` (config) wins; otherwise $VISUAL / $EDITOR, using each
/// editor's own line-number syntax.
fn editor_command(
    template: Option<&str>,
    in_pane: Option<bool>,
    file: &FileTarget,
) -> (Vec<String>, bool) {
    let path = file.path.to_string_lossy().into_owned();
    let (line, col) = (file.line.to_string(), file.col.unwrap_or(1).to_string());
    if let Some(t) = template.filter(|t| !t.trim().is_empty()) {
        let argv: Vec<String> = t
            .split_whitespace()
            .map(|w| {
                w.replace("{file}", &path)
                    .replace("{line}", &line)
                    .replace("{col}", &col)
            })
            .collect();
        let gui = argv
            .first()
            .is_some_and(|e| GUI_EDITORS.contains(&base_name(e)));
        return (argv, in_pane.unwrap_or(!gui));
    }
    let editor = std::env::var("VISUAL")
        .ok()
        .or_else(|| std::env::var("EDITOR").ok())
        .filter(|e| !e.trim().is_empty())
        .unwrap_or_else(|| "nano".into());
    let mut words: Vec<String> = editor.split_whitespace().map(str::to_string).collect();
    let name = base_name(&words[0]).to_string();
    let at = format!("{path}:{line}:{col}");
    let (args, gui): (Vec<String>, bool) = match name.as_str() {
        "code" | "codium" | "code-insiders" | "cursor" | "windsurf" => {
            (vec!["-g".into(), at], true)
        }
        "zed" | "zeditor" | "subl" => (vec![at], true),
        "hx" | "helix" => (vec![at], false),
        "kak" => (vec![format!("+{line}:{col}"), path], false),
        "nano" => (vec![format!("+{line},{col}"), path], false),
        "micro" => (vec![at], false),
        _ => (vec![format!("+{line}"), path], false),
    };
    words.extend(args);
    (words, in_pane.unwrap_or(!gui))
}

fn base_name(cmd: &str) -> &str {
    cmd.rsplit('/').next().unwrap_or(cmd)
}

fn shell_quote(s: &str) -> String {
    if s.chars()
        .all(|c| c.is_ascii_alphanumeric() || "/._+-:=@".contains(c))
    {
        s.to_string()
    } else {
        format!("'{}'", s.replace('\'', "'\\''"))
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn target() -> FileTarget {
        FileTarget {
            path: PathBuf::from("/src/my app/main.rs"),
            line: 42,
            col: Some(7),
        }
    }

    #[test]
    fn templates_fill_placeholders() {
        let (argv, pane) = editor_command(Some("nvim +{line} {file}"), None, &target());
        assert_eq!(argv, vec!["nvim", "+42", "/src/my app/main.rs"]);
        assert!(pane);
        let (argv, pane) = editor_command(Some("code -g {file}:{line}:{col}"), None, &target());
        assert_eq!(argv[2], "/src/my app/main.rs:42:7");
        assert!(!pane, "GUI editors get their own window");
        let (_, pane) = editor_command(Some("code -g {file}"), Some(true), &target());
        assert!(pane, "explicit editor_in_pane wins");
    }

    #[test]
    fn quoting_keeps_spaces_and_quotes_safe() {
        assert_eq!(shell_quote("/a/b.rs"), "/a/b.rs");
        assert_eq!(shell_quote("/my app/x"), "'/my app/x'");
        assert_eq!(shell_quote("it's"), "'it'\\''s'");
    }
}