vig 0.14.0

Read-only TUI cockpit for busy repositories - git, GitHub PRs/CI/projects, containers and processes at a glance
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
//! The Files page: a yazi-like three-column file browser (parent / current /
//! preview) rooted at the repository working directory.

use crate::core::app::{AppContext, PageState};
use crate::core::browser;
use crate::core::config::{Config, LoadedPageConfig};
use crate::core::keymap::{Keymap, ViewAction};
use crate::core::layout::{split_page_frame, PageLayoutConfig};
use crate::core::page::{ExternalCommand, PageAction};
use crate::core::pane::{self, Pane, PaneEvent, PaneSet, PaneShared};
use crate::core::search::SearchState;
use crate::core::tab::Tab;
use crate::core::ui::status_bar;
use crate::files::domain::fs::DirEntry;
use crate::files::panes::dir_list::{DirListAction, DirListPane};
use crate::files::panes::parent_dir::ParentDirPane;
use crate::files::panes::preview::{PreviewAction, PreviewPane};
use anyhow::Result;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use ratatui::{layout::Rect, Frame};
use ratatui_image::picker::Picker;
use std::path::{Path, PathBuf};

/// Pane IDs resolved from the KDL config at construction time.
#[derive(Debug, Clone, Copy)]
pub struct FilesPaneIds {
    pub parent_dir: usize,
    pub dir_list: usize,
    pub preview: usize,
}

impl FilesPaneIds {
    fn from_config(cfg: &LoadedPageConfig) -> Self {
        Self {
            parent_dir: cfg.resolve_id_expect("parent_dir"),
            dir_list: cfg.resolve_id_expect("dir_list"),
            preview: cfg.resolve_id_expect("preview"),
        }
    }
}

pub type BrowseTab = Tab<DirListPane, PreviewPane>;

impl BrowseTab {
    /// Load the preview for the selected entry.
    pub fn sync_detail(&mut self) {
        self.detail.load(self.list.selected());
    }
}

pub struct FilesPanes {
    pub parent: ParentDirPane,
    pub tab: BrowseTab,
    pub ids: FilesPaneIds,
}

impl PaneSet for FilesPanes {
    fn get_mut(&mut self, idx: usize) -> Option<&mut dyn Pane<PaneEvent>> {
        if idx == self.ids.parent_dir {
            Some(&mut self.parent)
        } else {
            self.tab
                .get_pane_mut(self.ids.dir_list, self.ids.preview, idx)
        }
    }
}

/// One-line input for the `OpenWith` action (`O`): the application name to
/// open the selected entry with.
#[derive(Debug, Default)]
pub struct OpenWithPrompt {
    pub active: bool,
    pub input: String,
    /// Last confirmed application name; pre-filled the next time.
    last: String,
}

impl OpenWithPrompt {
    fn start(&mut self) {
        self.active = true;
        self.input = self.last.clone();
    }

    /// Handle a key while the prompt is active. Returns `Some(app)` when the
    /// user confirmed a non-empty application name.
    fn handle_key(&mut self, key: KeyEvent) -> Option<String> {
        match key.code {
            KeyCode::Enter => {
                self.active = false;
                let app = self.input.trim().to_string();
                if app.is_empty() {
                    return None;
                }
                self.last = app.clone();
                Some(app)
            }
            KeyCode::Esc => {
                self.active = false;
                None
            }
            KeyCode::Backspace => {
                self.input.pop();
                None
            }
            KeyCode::Char('u') if key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.input.clear();
                None
            }
            KeyCode::Char(c) if !key.modifiers.contains(KeyModifiers::CONTROL) => {
                self.input.push(c);
                None
            }
            _ => None,
        }
    }
}

pub struct FilesState {
    pub pane: PaneShared,
    pub panes: FilesPanes,
    pub open_with: OpenWithPrompt,
    /// Repository working directory; the header shows paths relative to it.
    pub root: PathBuf,
    layout_config: PageLayoutConfig,
    view_keymap: Keymap<ViewAction>,
}

impl pane::PageLayout for FilesState {
    type Panes = FilesPanes;
    fn page_parts_mut(
        &mut self,
    ) -> (
        &mut PaneShared,
        &mut Self::Panes,
        &Keymap<ViewAction>,
        &PageLayoutConfig,
    ) {
        (
            &mut self.pane,
            &mut self.panes,
            &self.view_keymap,
            &self.layout_config,
        )
    }
}

impl FilesState {
    pub fn new(root: &Path, cfg: &Config, picker: Option<Picker>) -> Result<Self> {
        let page_cfg = cfg.files_page()?;
        let theme = cfg.theme()?;
        let icons = cfg.icons()?;
        let markdown = cfg.markdown_preview()?;
        let ids = FilesPaneIds::from_config(&page_cfg);
        // Validates the bind declarations (dir_list → preview).
        let _ = page_cfg.resolve_select_bindings();

        let dir_list_km = page_cfg.keymap::<DirListAction>("dir_list")?;
        let preview_km = page_cfg.keymap::<PreviewAction>("preview")?;
        let view_km = page_cfg.keymap::<ViewAction>("view")?;

        let mut list = DirListPane::new(ids.dir_list, ids.preview, root, icons);
        list.set_keymap(dir_list_km);
        let mut preview =
            PreviewPane::new(ids.preview, ids.dir_list, &theme, icons, picker, markdown);
        preview.set_keymap(preview_km);
        let parent = ParentDirPane::new(ids.parent_dir, root, icons);

        let mut state = Self {
            pane: PaneShared {
                focused_pane: ids.dir_list,
                previous_pane: ids.dir_list,
                search: SearchState::new(),
            },
            panes: FilesPanes {
                parent,
                tab: Tab {
                    list,
                    detail: preview,
                },
                ids,
            },
            open_with: OpenWithPrompt::default(),
            root: root.to_path_buf(),
            layout_config: page_cfg.layout,
            view_keymap: view_km,
        };
        state.panes.tab.sync_detail();
        Ok(state)
    }

    /// Current directory shown relative to the repository root (`.` at the root).
    pub fn cwd_display(&self) -> String {
        let cwd = &self.panes.tab.list.cwd;
        match cwd.strip_prefix(&self.root) {
            Ok(rel) if rel.as_os_str().is_empty() => ".".to_string(),
            Ok(rel) => rel.to_string_lossy().into_owned(),
            Err(_) => cwd.to_string_lossy().into_owned(),
        }
    }

    pub fn selected(&self) -> Option<&DirEntry> {
        self.panes.tab.list.selected()
    }

    fn on_dir_changed(&mut self) {
        let cwd = self.panes.tab.list.cwd.clone();
        self.panes.parent.update(&cwd);
        self.panes.tab.sync_detail();
    }

    /// Open the selected entry with the OS default application, or with
    /// `app`. Directories open in the system file manager (Finder,
    /// Explorer, ...) because that is what `open` / `explorer` /
    /// `xdg-open` do with a directory path.
    fn open_selected(&self, ctx: &mut AppContext, app: Option<&str>) {
        let Some(entry) = self.selected() else {
            ctx.status_message = Some("No entry selected".to_string());
            return;
        };
        let result = match app {
            Some(app) => browser::open_path_with(app, &entry.path),
            None => browser::open_path(&entry.path),
        };
        ctx.status_message = Some(match result {
            Ok(()) => match app {
                Some(app) => format!("Opening with {app}..."),
                None => "Opening...".to_string(),
            },
            Err(e) => e,
        });
    }

    /// Forward the preview pane's full-redraw request to the app.
    fn propagate_full_redraw(&mut self, ctx: &mut AppContext) {
        if self.panes.tab.detail.take_full_redraw() {
            ctx.needs_full_redraw = true;
        }
    }

    /// Re-read the current directory (fs change, refresh, editor return).
    fn reload(&mut self) {
        self.panes.tab.list.reload();
        self.on_dir_changed();
    }

    fn process_events(
        &mut self,
        ctx: &mut AppContext,
        events: Vec<PaneEvent>,
    ) -> Result<PageAction> {
        for event in events {
            if pane::process_common_event(&mut self.pane, ctx, &event) {
                continue;
            }
            match event {
                PaneEvent::SelectionChanged => self.panes.tab.sync_detail(),
                PaneEvent::DirChanged => self.on_dir_changed(),
                PaneEvent::JumpToMatch(forward) => {
                    let jumped = self
                        .pane
                        .jump_to_search_match(&mut self.panes, ctx, forward);
                    // A file-name search moved the list: reload the preview.
                    // A content search jumped inside the preview: keep it.
                    if jumped == Some(self.panes.ids.dir_list) {
                        self.panes.tab.sync_detail();
                    }
                }
                _ => {}
            }
        }
        Ok(PageAction::None)
    }

    fn handle_key_inner(&mut self, ctx: &mut AppContext, key: KeyEvent) -> Result<PageAction> {
        if self.open_with.active {
            if let Some(app) = self.open_with.handle_key(key) {
                self.open_selected(ctx, Some(&app));
            }
            return Ok(PageAction::None);
        }
        if self.pane.handle_search_input(&mut self.panes, ctx, key) {
            // Incremental search moves the list selection without emitting
            // an event, so keep the preview in sync here.
            if self.pane.search.origin == self.panes.ids.dir_list {
                self.panes.tab.sync_detail();
            }
            return Ok(PageAction::None);
        }
        self.handle_view_key(ctx, key)
    }

    fn handle_view_key(&mut self, ctx: &mut AppContext, key: KeyEvent) -> Result<PageAction> {
        if let Some(action) = self.view_keymap.lookup(key) {
            if let Some(page_action) = pane::execute_common_view_action(ctx, *action) {
                return Ok(page_action);
            }
            match action {
                ViewAction::Refresh => {
                    self.reload();
                    return Ok(PageAction::None);
                }
                ViewAction::OpenEditor => {
                    if let Some(entry) = self.selected().filter(|e| !e.is_dir) {
                        let editor = std::env::var("EDITOR")
                            .or_else(|_| std::env::var("VISUAL"))
                            .unwrap_or_else(|_| "vi".to_string());
                        return Ok(PageAction::Suspend(ExternalCommand {
                            program: editor,
                            args: vec![entry.path.clone().into()],
                        }));
                    }
                    return Ok(PageAction::None);
                }
                ViewAction::OpenDefault => {
                    self.open_selected(ctx, None);
                    return Ok(PageAction::None);
                }
                ViewAction::ToggleMarkdown => {
                    self.panes.tab.detail.toggle_markdown();
                    return Ok(PageAction::None);
                }
                ViewAction::OpenWith => {
                    if self.selected().is_some() {
                        self.open_with.start();
                    } else {
                        ctx.status_message = Some("No entry selected".to_string());
                    }
                    return Ok(PageAction::None);
                }
                _ => {}
            }
        }
        let events = pane::dispatch_page_key(self, key);
        self.process_events(ctx, events)
    }
}

impl PageState for FilesState {
    fn id(&self) -> &'static str {
        "files"
    }

    fn label(&self) -> &'static str {
        "Files"
    }

    fn help_bindings(&self) -> Vec<(String, String)> {
        use crate::core::keymap::help_section;
        let mut entries = self.view_keymap.help_entries();
        entries.extend(help_section("Files"));
        entries.extend(self.panes.tab.list.keymap().help_entries());
        entries.extend(help_section("Preview"));
        entries.extend(self.panes.tab.detail.keymap().help_entries());
        entries
    }

    fn handle_key(&mut self, ctx: &mut AppContext, key: KeyEvent) -> Result<PageAction> {
        let action = self.handle_key_inner(ctx, key);
        self.propagate_full_redraw(ctx);
        action
    }

    fn render(&mut self, f: &mut Frame, ctx: &AppContext, area: Rect) {
        let frame = split_page_frame(area);
        status_bar::render_files_header(f, ctx, self, frame.header);
        pane::render_page_content(self, f, ctx, frame.content);
        status_bar::render_files_status_bar(f, ctx, self, frame.status_bar);
    }

    fn intercepts_all_keys(&self) -> bool {
        self.pane.search.active || self.open_with.active
    }

    fn on_fs_change(&mut self, ctx: &mut AppContext) -> Result<()> {
        self.reload();
        self.propagate_full_redraw(ctx);
        Ok(())
    }

    fn on_suspend_return(
        &mut self,
        ctx: &mut AppContext,
        _status: std::io::Result<std::process::ExitStatus>,
    ) -> Result<()> {
        self.reload();
        self.propagate_full_redraw(ctx);
        Ok(())
    }
}

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

    fn key(code: KeyCode) -> KeyEvent {
        KeyEvent::new(code, KeyModifiers::NONE)
    }

    fn ctrl(c: char) -> KeyEvent {
        KeyEvent::new(KeyCode::Char(c), KeyModifiers::CONTROL)
    }

    fn type_str(p: &mut OpenWithPrompt, s: &str) {
        for c in s.chars() {
            assert_eq!(p.handle_key(key(KeyCode::Char(c))), None);
        }
    }

    #[test]
    fn open_with_prompt_confirms_trimmed_name_and_remembers_it() {
        let mut p = OpenWithPrompt::default();
        p.start();
        assert!(p.active);
        assert_eq!(p.input, "");
        type_str(&mut p, " Preview ");
        assert_eq!(
            p.handle_key(key(KeyCode::Enter)),
            Some("Preview".to_string())
        );
        assert!(!p.active);

        // The last name is pre-filled next time and can be cleared with Ctrl+u.
        p.start();
        assert_eq!(p.input, "Preview");
        assert_eq!(p.handle_key(ctrl('u')), None);
        assert_eq!(p.input, "");
        type_str(&mut p, "Xcode");
        assert_eq!(p.handle_key(key(KeyCode::Backspace)), None);
        assert_eq!(p.input, "Xcod");
    }

    #[test]
    fn open_with_prompt_esc_and_empty_enter_cancel() {
        let mut p = OpenWithPrompt::default();
        p.start();
        type_str(&mut p, "abc");
        assert_eq!(p.handle_key(key(KeyCode::Esc)), None);
        assert!(!p.active);

        p.start();
        assert_eq!(p.handle_key(key(KeyCode::Enter)), None);
        assert!(!p.active);
        assert_eq!(p.last, "");
    }
}