kraal 0.3.0

A terminal workspace manager for SSH fleets and coding agents
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
//! A two-panel file manager pane in the style of Midnight Commander.
//!
//! Each panel shows a local directory or a directory on a server reached over
//! SSH. Listings run on background threads and are applied by
//! [`FilesPane::poll`], so the pane never blocks the server. File operations
//! are not performed here: keys return [`FilesAction`]s that the server
//! carries out (with `kraal cp` semantics) before calling
//! [`FilesPane::refresh`]. Errors are rendered inside the panels; nothing
//! panics or draws outside the given area, whatever the input or size.

use std::collections::{HashMap, HashSet};
use std::fmt;
use std::mem;
use std::path::PathBuf;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, PoisonError};
use std::thread;

use ratatui::buffer::Buffer;
use ratatui::layout::Rect;

#[cfg(test)]
mod fuzz;
mod listing;
#[cfg(test)]
mod tests;
mod view;

pub(crate) use listing::remote_dir_arg;
use listing::{Listing, Ssh, home_dir, list};
use view::{Geometry, buffer_rows, footer_layout, geometry};

/// Viewport assumed before the first render.
const DEFAULT_VIEW: (u16, u16) = (80, 24);

/// Where a panel points.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Location {
    /// A directory on this machine.
    Local(PathBuf),
    /// A directory on a server, listed over SSH.
    Remote(Remote),
}

/// A directory on a server.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Remote {
    /// Display name of the server (e.g. "edge-proxy").
    pub server: String,
    /// Arguments for `ssh` that reach the server, destination last,
    /// e.g. `["-p", "2222", "-o", "ControlPath=…", "user@host"]`.
    pub ssh_args: Vec<String>,
    /// Absolute path, or "~" / "~/x" before the first listing resolves it.
    pub path: String,
}

impl Location {
    /// The child entry `name` of this directory.
    pub fn join(&self, name: &str) -> Location {
        match self {
            Location::Local(path) => Location::Local(path.join(name)),
            Location::Remote(remote) => Location::Remote(remote.with_path(join_remote(&remote.path, name))),
        }
    }

    /// The parent directory, or `None` at the root (and at an unresolved `~`).
    fn parent(&self) -> Option<Location> {
        match self {
            Location::Local(path) => {
                path.parent().filter(|p| !p.as_os_str().is_empty()).map(|p| Location::Local(p.to_path_buf()))
            }
            Location::Remote(remote) => {
                parent_remote(&remote.path).map(|path| Location::Remote(remote.with_path(path)))
            }
        }
    }

    /// "edge-proxy:/var/log" or "/home/me": the syntax of `kraal cp`.
    pub fn display(&self) -> String {
        match self {
            Location::Local(path) => path.display().to_string(),
            Location::Remote(remote) => format!("{}:{}", remote.server, remote.path),
        }
    }

    /// [`Location::display`], unless a local path is not valid UTF-8: shown approximately, it
    /// could name another file, so nothing is done with it.
    pub fn exact_display(&self) -> Option<String> {
        match self {
            Location::Local(path) => path.to_str().map(str::to_owned),
            Location::Remote(_) => Some(self.display()),
        }
    }

    /// Like [`Location::display`], with the home directory shown as `~`.
    fn short_display(&self) -> String {
        match self {
            Location::Local(path) => match home_dir().and_then(|home| path.strip_prefix(home).ok()) {
                Some(rest) if rest.as_os_str().is_empty() => "~".to_owned(),
                Some(rest) => format!("~/{}", rest.display()),
                None => path.display().to_string(),
            },
            Location::Remote(_) => self.display(),
        }
    }

    /// The last path component: this directory's name in its parent.
    pub fn name(&self) -> Option<String> {
        match self {
            Location::Local(path) => path.file_name().map(|n| n.to_string_lossy().into_owned()),
            Location::Remote(remote) => {
                let trimmed = remote.path.trim_end_matches('/');
                if trimmed.is_empty() || (trimmed.starts_with('~') && !trimmed.contains('/')) {
                    return None;
                }
                trimmed.rsplit('/').next().map(str::to_owned)
            }
        }
    }
}

impl Remote {
    fn with_path(&self, path: String) -> Remote {
        Remote { server: self.server.clone(), ssh_args: self.ssh_args.clone(), path }
    }
}

/// Joins `/`-separated remote paths.
fn join_remote(base: &str, name: &str) -> String {
    if base.is_empty() {
        format!("~/{name}")
    } else if base.ends_with('/') {
        format!("{base}{name}")
    } else {
        format!("{base}/{name}")
    }
}

/// The parent of a `/`-separated remote path; relative paths are relative to `~`.
fn parent_remote(path: &str) -> Option<String> {
    let trimmed = path.trim_end_matches('/');
    if trimmed.is_empty() || (trimmed.starts_with('~') && !trimmed.contains('/')) {
        // The root, or `~` / `~user` before the listing resolved it.
        return None;
    }
    match trimmed.rfind('/') {
        None => Some("~".to_owned()),
        Some(index) => {
            let parent = trimmed[..index].trim_end_matches('/');
            Some(if parent.is_empty() { "/".to_owned() } else { parent.to_owned() })
        }
    }
}

/// One directory entry.
#[derive(Debug, Clone, PartialEq, Eq)]
struct Entry {
    name: String,
    /// A directory, or a symbolic link to one.
    is_dir: bool,
    is_link: bool,
    size: u64,
    /// unix seconds
    mtime: i64,
    /// `name` is the entry's real name. A name that is not UTF-8 is shown approximately, and
    /// nothing is done to such an entry: an approximate name could designate another file.
    exact: bool,
}

/// Keys the pane understands (the server maps its own key type to these).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FileKey {
    Up,
    Down,
    PageUp,
    PageDown,
    Home,
    End,
    Enter,
    Backspace,
    Tab,
    Esc,
    Delete,
    Insert,
    Char(char),
    F(u8),
}

/// What the server must do after a key or click.
#[derive(Debug, Clone, PartialEq)]
pub enum FilesAction {
    None,
    /// Copy the marked entries (or the one under the cursor) of the active panel into the other panel's directory.
    Copy {
        sources: Vec<Location>,
        dest: Location,
        /// Names already in the destination, which the copy replaces.
        replaces: Vec<String>,
    },
    /// Same, but move (the server asks for confirmation first).
    Move {
        sources: Vec<Location>,
        dest: Location,
        replaces: Vec<String>,
    },
    /// Delete (the server asks for confirmation first).
    Delete(Vec<Location>),
    /// Open a local file in a preview pane (Enter / F3 on a local file).
    Preview(PathBuf),
    /// Open the file under the cursor in the local editor (key `e`, F4); a server's file is
    /// saved back to it.
    Edit(Location),
    /// Open an SSH or local shell pane in this directory (key `s`).
    Shell(Location),
    /// Let the user pick a server for a panel (key `o` or `:`); the server answers with `set_location`.
    PickLocation(Side),
    Close,
    /// Nothing was done, and here is why (shown to the user).
    Refused(String),
}

const INEXACT: &str = "a name here is not valid UTF-8: kraal cannot point at it safely; use a shell (key s)";

/// One of the two panels.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Side {
    Left,
    Right,
}

impl Side {
    fn index(self) -> usize {
        match self {
            Side::Left => 0,
            Side::Right => 1,
        }
    }

    fn other(self) -> Side {
        match self {
            Side::Left => Side::Right,
            Side::Right => Side::Left,
        }
    }
}

/// A listing finished by a background thread.
struct Done {
    side: Side,
    request: u64,
    result: Listing,
}

/// A row of a panel listing.
#[derive(Clone, Copy)]
enum Row<'a> {
    Parent,
    Entry(&'a Entry),
}

/// One side of the pane: a directory listing with its cursor and marks.
struct Panel {
    location: Location,
    /// Every entry of the last listing, sorted.
    entries: Vec<Entry>,
    /// Indices into `entries` of the rows shown after the `..` row.
    shown: Vec<usize>,
    has_parent: bool,
    loading: bool,
    error: Option<String>,
    /// Names of the marked entries.
    marked: HashSet<String>,
    filter: String,
    /// Whether typed characters go to the filter.
    editing: bool,
    /// Row under the cursor; row 0 is `..` when `has_parent`.
    cursor: usize,
    /// First row shown, per client: each keeps its own view of the shared panel, and a click
    /// counts in what its client shows (a shorter one scrolls further to keep the cursor in
    /// sight). A client's entry goes when it detaches.
    offsets: HashMap<u32, usize>,
    /// Id of the latest listing request; older results are dropped.
    request: u64,
    cancel: Arc<AtomicBool>,
    /// Entry to put the cursor on when the pending listing arrives.
    select: Option<String>,
}

impl Panel {
    fn new(location: Location) -> Panel {
        Panel {
            has_parent: location.parent().is_some(),
            location,
            entries: Vec::new(),
            shown: Vec::new(),
            loading: false,
            error: None,
            marked: HashSet::new(),
            filter: String::new(),
            editing: false,
            cursor: 0,
            offsets: HashMap::new(),
            request: 0,
            cancel: Arc::new(AtomicBool::new(false)),
            select: None,
        }
    }

    /// Starts a new request, cancelling the previous one.
    fn supersede(&mut self) -> (u64, Arc<AtomicBool>) {
        self.cancel.store(true, Ordering::Relaxed);
        self.cancel = Arc::new(AtomicBool::new(false));
        self.request = self.request.wrapping_add(1);
        self.loading = true;
        (self.request, Arc::clone(&self.cancel))
    }

    /// Points the panel at `location`, forgetting the old listing.
    fn reset(&mut self, location: Location, select: Option<String>) {
        self.has_parent = location.parent().is_some();
        self.location = location;
        self.entries.clear();
        self.shown.clear();
        self.error = None;
        self.marked.clear();
        self.filter.clear();
        self.editing = false;
        self.cursor = 0;
        self.offsets.clear();
        self.select = select;
    }

    fn apply(&mut self, result: Listing, show_hidden: bool) {
        self.loading = false;
        match result {
            Ok((location, mut entries)) => {
                sort_entries(&mut entries);
                let keep = self.select.take().or_else(|| self.current().map(|e| e.name.clone()));
                self.has_parent = location.parent().is_some();
                self.location = location;
                let names: HashSet<&str> = entries.iter().map(|e| e.name.as_str()).collect();
                self.marked.retain(|name| names.contains(name.as_str()));
                self.entries = entries;
                self.error = None;
                self.update_shown(show_hidden);
                self.restore_cursor(keep.as_deref());
            }
            Err(message) => {
                self.entries.clear();
                self.marked.clear();
                self.select = None;
                self.error = Some(message);
                self.update_shown(show_hidden);
                self.restore_cursor(None);
            }
        }
    }

    fn rows_len(&self) -> usize {
        usize::from(self.has_parent) + self.shown.len()
    }

    fn row(&self, index: usize) -> Option<Row<'_>> {
        if self.has_parent && index == 0 {
            return Some(Row::Parent);
        }
        let index = index.checked_sub(usize::from(self.has_parent))?;
        self.shown.get(index).and_then(|&i| self.entries.get(i)).map(Row::Entry)
    }

    /// The entry under the cursor (not `..`).
    fn current(&self) -> Option<&Entry> {
        match self.row(self.cursor)? {
            Row::Entry(entry) => Some(entry),
            Row::Parent => None,
        }
    }

    fn shown_entries(&self) -> impl Iterator<Item = &Entry> {
        self.shown.iter().filter_map(|&i| self.entries.get(i))
    }

    /// Marked entries that are currently shown, in display order.
    fn marked_entries(&self) -> Vec<&Entry> {
        self.shown_entries().filter(|e| self.marked.contains(&e.name)).collect()
    }

    fn row_of(&self, name: &str) -> Option<usize> {
        let index = self.shown.iter().position(|&i| self.entries.get(i).is_some_and(|e| e.name == name))?;
        Some(index + usize::from(self.has_parent))
    }

    /// The first row that is an entry (or `..` when there is none).
    fn first_entry_row(&self) -> usize {
        if self.shown.is_empty() { 0 } else { usize::from(self.has_parent) }
    }

    fn update_shown(&mut self, show_hidden: bool) {
        let filter = self.filter.to_lowercase();
        self.shown = self
            .entries
            .iter()
            .enumerate()
            .filter(|(_, e)| show_hidden || !e.name.starts_with('.'))
            .filter(|(_, e)| filter.is_empty() || e.name.to_lowercase().contains(&filter))
            .map(|(i, _)| i)
            .collect();
    }

    /// Recomputes the shown rows, keeping the cursor on the same entry when possible.
    fn refilter(&mut self, show_hidden: bool) {
        let keep = self.current().map(|e| e.name.clone());
        self.update_shown(show_hidden);
        self.restore_cursor(keep.as_deref());
    }

    /// Changes the filter; the cursor stays on its entry if it still matches.
    fn set_filter(&mut self, filter: String, show_hidden: bool) {
        let keep = self.current().map(|e| e.name.clone());
        self.filter = filter;
        self.update_shown(show_hidden);
        self.cursor = keep.and_then(|name| self.row_of(&name)).unwrap_or_else(|| self.first_entry_row());
    }

    fn restore_cursor(&mut self, name: Option<&str>) {
        if let Some(row) = name.and_then(|name| self.row_of(name)) {
            self.cursor = row;
        } else {
            self.cursor = self.cursor.min(self.rows_len().saturating_sub(1));
        }
    }

    /// Remember what client `viewer` shows.
    fn set_offset(&mut self, viewer: u32, offset: usize) {
        self.offsets.insert(viewer, offset);
    }

    fn move_by(&mut self, delta: isize) {
        let target = self.cursor.saturating_add_signed(delta);
        self.cursor = target.min(self.rows_len().saturating_sub(1));
    }

    /// The first row client `viewer` shows in a list of `height` rows, the cursor in sight.
    fn scroll_offset(&self, viewer: u32, height: usize) -> usize {
        let rows = self.rows_len();
        let mut offset = self.offsets.get(&viewer).copied().unwrap_or(0);
        if height == 0 {
            return offset.min(rows.saturating_sub(1));
        }
        if self.cursor < offset {
            offset = self.cursor;
        } else if self.cursor >= offset.saturating_add(height) {
            offset = self.cursor + 1 - height;
        }
        offset.min(rows.saturating_sub(height))
    }
}

/// Directories first, then by name ignoring case.
fn sort_entries(entries: &mut [Entry]) {
    entries.sort_by_cached_key(|e| (!e.is_dir, e.name.to_lowercase(), e.name.clone()));
}

/// A two-panel file manager.
pub struct FilesPane {
    panels: [Panel; 2],
    active: Side,
    show_hidden: bool,
    /// Size of the last rendered area, if any.
    view: Option<(u16, u16)>,
    /// The client drawing the pane, or whose key or click is being handled: offsets are its own.
    viewer: u32,
    /// Listings finished by background threads, applied by `poll`.
    done: Arc<Mutex<Vec<Done>>>,
    wake: Arc<dyn Fn() + Send + Sync>,
    ssh: Ssh,
}

impl fmt::Debug for FilesPane {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FilesPane")
            .field("left", &self.panels[0].location)
            .field("right", &self.panels[1].location)
            .field("active", &self.active)
            .field("view", &self.view)
            .finish_non_exhaustive()
    }
}

impl Drop for FilesPane {
    fn drop(&mut self) {
        // Kills listings still running.
        for panel in &self.panels {
            panel.cancel.store(true, Ordering::Relaxed);
        }
    }
}

impl FilesPane {
    /// `wake` is called from background threads when a listing finished, so the server redraws.
    pub fn new(left: Location, right: Location, wake: Arc<dyn Fn() + Send + Sync>) -> FilesPane {
        FilesPane::with_ssh(left, right, wake, Ssh::default())
    }

    fn with_ssh(left: Location, right: Location, wake: Arc<dyn Fn() + Send + Sync>, ssh: Ssh) -> FilesPane {
        let mut pane = FilesPane {
            panels: [Panel::new(left), Panel::new(right)],
            active: Side::Left,
            show_hidden: false,
            view: None,
            viewer: 0,
            done: Arc::new(Mutex::new(Vec::new())),
            wake,
            ssh,
        };
        pane.load(Side::Left);
        pane.load(Side::Right);
        pane
    }

    /// E.g. "files · ~/Dev ⇄ edge-proxy:/var/log".
    pub fn title(&self) -> String {
        let [left, right] = &self.panels;
        format!("files · {} ⇄ {}", left.location.short_display(), right.location.short_display())
    }

    pub fn location(&self, side: Side) -> &Location {
        &self.panel(side).location
    }

    /// Points a panel at `loc` and lists it.
    pub fn set_location(&mut self, side: Side, loc: Location) {
        self.navigate(side, loc, None);
    }

    /// Reloads both panels, keeping cursors and marks where the names still exist.
    pub fn refresh(&mut self) {
        self.load(Side::Left);
        self.load(Side::Right);
    }

    /// Applies finished background listings; true if something changed.
    pub fn poll(&mut self) -> bool {
        let done = mem::take(&mut *self.done.lock().unwrap_or_else(PoisonError::into_inner));
        let mut changed = false;
        for item in done {
            if self.panel(item.side).request == item.request {
                let show_hidden = self.show_hidden;
                self.panel_mut(item.side).apply(item.result, show_hidden);
                changed = true;
            }
        }
        changed
    }

    /// Fills `area` of `buf` with both panels and the key hints. Never writes outside `area`.
    pub fn render(&mut self, area: Rect, buf: &mut Buffer) {
        let area = area.intersection(buf.area);
        self.view = Some((area.width, area.height));
        let height = usize::from(geometry(area, self.active).list.1);
        let viewer = self.viewer;
        for panel in &mut self.panels {
            let offset = panel.scroll_offset(viewer, height);
            panel.set_offset(viewer, offset);
        }
        self.draw(area, buf);
    }

    /// The client about to draw the pane: what it shows is remembered as its own.
    pub fn set_viewer(&mut self, viewer: u32) {
        self.viewer = viewer;
    }

    /// A client went away: what it showed is forgotten.
    pub fn forget_viewer(&mut self, viewer: u32) {
        for panel in &mut self.panels {
            panel.offsets.remove(&viewer);
        }
    }

    /// Text of what is shown, for tests and the CLI `read` command.
    ///
    /// Uses the last rendered size (80×24 before the first render).
    pub fn visible_text(&self) -> String {
        let (width, height) = self.view.unwrap_or(DEFAULT_VIEW);
        let area = Rect::new(0, 0, width, height);
        let mut buf = Buffer::empty(area);
        self.draw(area, &mut buf);
        buffer_rows(&buf, area).join("\n")
    }

    /// Handles a key; the returned action is for the server to carry out.
    pub fn key(&mut self, key: FileKey) -> FilesAction {
        let side = self.active;
        let show_hidden = self.show_hidden;
        if self.panel(side).editing {
            let panel = self.panel_mut(side);
            match key {
                FileKey::Char(c) => {
                    let mut filter = panel.filter.clone();
                    filter.push(c);
                    panel.set_filter(filter, show_hidden);
                    return FilesAction::None;
                }
                FileKey::Backspace => {
                    let mut filter = panel.filter.clone();
                    if filter.pop().is_none() {
                        panel.editing = false;
                    }
                    panel.set_filter(filter, show_hidden);
                    return FilesAction::None;
                }
                FileKey::Esc => {
                    panel.editing = false;
                    panel.set_filter(String::new(), show_hidden);
                    return FilesAction::None;
                }
                FileKey::Enter => {
                    panel.editing = false;
                    return FilesAction::None;
                }
                // Navigation keys keep working while typing.
                _ => {}
            }
        }
        let page = isize::try_from(self.list_height().saturating_sub(1).max(1)).unwrap_or(1);
        match key {
            FileKey::Up | FileKey::Char('k') => self.panel_mut(side).move_by(-1),
            FileKey::Down | FileKey::Char('j') => self.panel_mut(side).move_by(1),
            FileKey::PageUp => self.panel_mut(side).move_by(-page),
            FileKey::PageDown => self.panel_mut(side).move_by(page),
            FileKey::Home => self.panel_mut(side).cursor = 0,
            FileKey::End => {
                let panel = self.panel_mut(side);
                panel.cursor = panel.rows_len().saturating_sub(1);
            }
            FileKey::Enter | FileKey::F(3) => return self.open(side),
            FileKey::Backspace => self.go_up(side),
            FileKey::Tab => {
                self.panel_mut(side).editing = false;
                self.active = side.other();
            }
            FileKey::Char(' ') | FileKey::Insert => {
                let panel = self.panel_mut(side);
                if let Some(name) = panel.current().map(|e| e.name.clone())
                    && !panel.marked.remove(&name)
                {
                    panel.marked.insert(name);
                }
                panel.move_by(1);
            }
            FileKey::Char('*') => {
                let panel = self.panel_mut(side);
                let names: Vec<String> = panel.shown_entries().map(|e| e.name.clone()).collect();
                if names.iter().all(|name| panel.marked.contains(name)) {
                    for name in &names {
                        panel.marked.remove(name);
                    }
                } else {
                    panel.marked.extend(names);
                }
            }
            FileKey::Char('c') | FileKey::F(5) => return self.transfer(side, false),
            FileKey::Char('m') | FileKey::F(6) => return self.transfer(side, true),
            FileKey::Char('d') | FileKey::Delete | FileKey::F(8) => {
                return match self.sources(side) {
                    Ok(sources) if sources.is_empty() => FilesAction::None,
                    Ok(sources) => FilesAction::Delete(sources),
                    Err(why) => FilesAction::Refused(why),
                };
            }
            FileKey::Char('e') | FileKey::F(4) => return self.edit(side),
            FileKey::Char('s') => return FilesAction::Shell(self.panel(side).location.clone()),
            FileKey::Char('o' | ':') => return FilesAction::PickLocation(side),
            FileKey::Char('r') => self.refresh(),
            FileKey::Char('.') => {
                self.show_hidden = !self.show_hidden;
                for panel in &mut self.panels {
                    panel.refilter(self.show_hidden);
                }
            }
            FileKey::Char('/') => {
                let panel = self.panel_mut(side);
                panel.editing = true;
            }
            FileKey::Esc if !self.panel(side).filter.is_empty() => {
                self.panel_mut(side).set_filter(String::new(), show_hidden);
            }
            FileKey::Char('q') | FileKey::Esc | FileKey::F(10) => return FilesAction::Close,
            _ => {}
        }
        FilesAction::None
    }

    /// Mouse: click selects the panel and the entry (double click = Enter); wheel scrolls.
    ///
    /// `col` and `row` are relative to the area last passed to [`FilesPane::render`].
    /// A click on a key hint presses that key.
    pub fn click(&mut self, col: u16, row: u16, double: bool) -> FilesAction {
        let geo = self.geometry();
        if geo.footer == Some(row) {
            let hints = self.hints();
            let hit =
                footer_layout(&hints, geo.area.width).into_iter().find(|&(start, end, _)| (start..end).contains(&col));
            return match hit.and_then(|(_, _, index)| hints.get(index)).and_then(|hint| hint.key) {
                Some(key) => self.key(key),
                None => FilesAction::None,
            };
        }
        let Some(side) = geo.side_at(col) else {
            return FilesAction::None;
        };
        if side != self.active {
            self.panel_mut(self.active).editing = false;
            self.active = side;
        }
        let (list_y, list_height) = geo.list;
        if row < list_y || row - list_y >= list_height {
            return FilesAction::None;
        }
        let viewer = self.viewer;
        let panel = self.panel_mut(side);
        let index = panel.scroll_offset(viewer, usize::from(list_height)).saturating_add(usize::from(row - list_y));
        if index >= panel.rows_len() {
            return FilesAction::None;
        }
        panel.cursor = index;
        if double { self.open(side) } else { FilesAction::None }
    }

    /// The client the next key or click comes from, and the size it is counted in: what that
    /// client shows of the pane (clients with smaller terminals show less of it).
    pub fn set_view(&mut self, viewer: u32, width: u16, height: u16) {
        self.viewer = viewer;
        self.view = Some((width, height));
    }

    /// Scrolls the active panel by `delta` rows (negative is up): keyboard scrolling.
    pub fn scroll_active(&mut self, delta: i32) {
        let side = self.active;
        self.scroll_side(side, delta);
    }

    /// Scrolls the panel under column `col` by `delta` rows (negative is up).
    /// The cursor is kept within the visible rows.
    pub fn scroll(&mut self, col: u16, delta: i32) {
        let side = self.geometry().side_at(col).unwrap_or(self.active);
        self.scroll_side(side, delta);
    }

    fn scroll_side(&mut self, side: Side, delta: i32) {
        let height = usize::from(self.geometry().list.1).max(1);
        let viewer = self.viewer;
        let panel = self.panel_mut(side);
        let rows = panel.rows_len();
        let max_offset = rows.saturating_sub(height);
        let delta = isize::try_from(delta).unwrap_or(0);
        let offset = panel.scroll_offset(viewer, height).saturating_add_signed(delta).min(max_offset);
        panel.set_offset(viewer, offset);
        let last_visible = (offset + height - 1).min(rows.saturating_sub(1));
        panel.cursor = panel.cursor.clamp(offset.min(last_visible), last_visible);
    }

    fn panel(&self, side: Side) -> &Panel {
        &self.panels[side.index()]
    }

    fn panel_mut(&mut self, side: Side) -> &mut Panel {
        &mut self.panels[side.index()]
    }

    /// Layout of the last rendered size, relative to the rendered area.
    fn geometry(&self) -> Geometry {
        let (width, height) = self.view.unwrap_or(DEFAULT_VIEW);
        geometry(Rect::new(0, 0, width, height), self.active)
    }

    fn list_height(&self) -> usize {
        usize::from(self.geometry().list.1)
    }

    fn navigate(&mut self, side: Side, location: Location, select: Option<String>) {
        self.panel_mut(side).reset(location, select);
        self.load(side);
    }

    /// Lists the panel's location on a background thread.
    fn load(&mut self, side: Side) {
        let panel = self.panel_mut(side);
        let (request, cancel) = panel.supersede();
        let location = panel.location.clone();
        let (done, wake, ssh) = (Arc::clone(&self.done), Arc::clone(&self.wake), self.ssh.clone());
        let spawned = thread::Builder::new().name("kraal-files".to_owned()).spawn(move || {
            let result = list(&location, &ssh, &cancel);
            if cancel.load(Ordering::Relaxed) {
                return;
            }
            done.lock().unwrap_or_else(PoisonError::into_inner).push(Done { side, request, result });
            wake();
        });
        if let Err(err) = spawned {
            let show_hidden = self.show_hidden;
            self.panel_mut(side).apply(Err(format!("cannot start listing: {err}")), show_hidden);
        }
    }

    /// Enter: opens the directory under the cursor, or previews a local file.
    fn open(&mut self, side: Side) -> FilesAction {
        let panel = self.panel(side);
        match panel.row(panel.cursor) {
            Some(Row::Parent) => self.go_up(side),
            Some(Row::Entry(entry)) if !entry.exact => return FilesAction::Refused(INEXACT.into()),
            Some(Row::Entry(entry)) if entry.is_dir => {
                let target = panel.location.join(&entry.name);
                self.navigate(side, target, None);
            }
            Some(Row::Entry(entry)) => {
                if let Location::Local(path) = panel.location.join(&entry.name) {
                    return FilesAction::Preview(path);
                }
            }
            None => {}
        }
        FilesAction::None
    }

    /// `e`: the file under the cursor, to edit.
    fn edit(&self, side: Side) -> FilesAction {
        let panel = self.panel(side);
        match panel.current() {
            None => FilesAction::None,
            Some(entry) if !entry.exact => FilesAction::Refused(INEXACT.into()),
            Some(entry) if entry.is_dir => {
                FilesAction::Refused(format!("{} is a directory: e edits a file", entry.name))
            }
            Some(entry) => FilesAction::Edit(panel.location.join(&entry.name)),
        }
    }

    /// Goes to the parent directory, with the cursor on the directory left.
    fn go_up(&mut self, side: Side) {
        let location = &self.panel(side).location;
        if let Some(parent) = location.parent() {
            let name = location.name();
            self.navigate(side, parent, name);
        }
    }

    /// The marked entries, or else the one under the cursor; never `..`. Refused when one of
    /// them has a name kraal cannot represent exactly.
    fn sources(&self, side: Side) -> Result<Vec<Location>, String> {
        let panel = self.panel(side);
        let marked = panel.marked_entries();
        let entries = if marked.is_empty() { panel.current().into_iter().collect() } else { marked };
        if entries.iter().any(|e| !e.exact) {
            return Err(INEXACT.into());
        }
        Ok(entries.into_iter().map(|e| panel.location.join(&e.name)).collect())
    }

    fn transfer(&mut self, side: Side, is_move: bool) -> FilesAction {
        let sources = match self.sources(side) {
            Ok(s) => s,
            Err(why) => return FilesAction::Refused(why),
        };
        let target = self.panel(side.other());
        let dest = target.location.clone();
        if sources.is_empty() || dest == self.panel(side).location {
            return FilesAction::None;
        }
        // What the other panel lists is what the copy would overwrite.
        let replaces: Vec<String> = sources
            .iter()
            .filter_map(Location::name)
            .filter(|n| !target.loading && target.entries.iter().any(|e| &e.name == n))
            .collect();
        if is_move {
            FilesAction::Move { sources, dest, replaces }
        } else {
            // Marks are dropped once a copy is under way; moved or deleted
            // entries lose theirs when the listing is refreshed.
            self.panel_mut(side).marked.clear();
            FilesAction::Copy { sources, dest, replaces }
        }
    }

    // -----------------------------------------------------------------------
    // Drawing
}