vle 1.19.3

Very Little Editor - an exercise in minimalist text editing
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
// Copyright 2026 Brian Langenberger
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use crate::buffer::Source;
use crate::editor::DirTarget;
#[cfg(feature = "ssh")]
use crate::editor::RemoteError;
use crate::prompt::TextField;
use ratatui::widgets::StatefulWidget;
use std::collections::BTreeSet;
use std::path::{Path, PathBuf};

/// Width of text box, in characters
const TEXT_WIDTH: u16 = 30;

/// Size of each page, in rows
const PAGE_SIZE: usize = 10;

pub trait ChooserSource: Clone + std::fmt::Display {
    type Error: std::fmt::Display;

    fn current_dir(&self) -> Result<PathBuf, Self::Error>;

    fn read_dir(&self, dir: &Path, show_hidden: bool) -> Result<Vec<Entry>, Self::Error>;

    fn open(&self, path: PathBuf) -> Source;

    fn target(&self) -> DirTarget;

    /// Returns whether target can be toggled
    fn toggleable(&self) -> bool {
        false
    }

    /// Returns new target, if any
    fn toggle_source(&mut self) -> DirTarget {
        // nothing else to switch to by default
        self.target()
    }
}

#[derive(Clone, Default)]
pub struct LocalSource;

impl std::fmt::Display for LocalSource {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        "Local Files".fmt(f)
    }
}

impl ChooserSource for LocalSource {
    type Error = std::io::Error;

    fn current_dir(&self) -> std::io::Result<PathBuf> {
        std::env::current_dir()
    }

    fn read_dir(&self, dir: &Path, show_hidden: bool) -> std::io::Result<Vec<Entry>> {
        dir.read_dir()
            .and_then(|entries| {
                entries
                    .map(|e| e.and_then(Entry::try_from))
                    .filter_map(|e| {
                        if show_hidden {
                            Some(e)
                        } else {
                            match e {
                                Ok(e) if e.is_hidden() => None,
                                Ok(e) => Some(Ok(e)),
                                Err(e) => Some(Err(e)),
                            }
                        }
                    })
                    .collect()
            })
            .map(|mut entries: Vec<Entry>| {
                entries.sort_unstable_by(|x, y| {
                    x.is_dir.cmp(&y.is_dir).reverse().then(x.path.cmp(&y.path))
                });
                entries
            })
    }

    fn open(&self, path: PathBuf) -> Source {
        Source::Local(path)
    }

    fn target(&self) -> DirTarget {
        DirTarget::Local
    }
}

#[cfg(feature = "ssh")]
#[derive(Clone)]
pub struct SshSource {
    label: String,
    remote: std::rc::Rc<ssh2::Sftp>,
}

#[cfg(feature = "ssh")]
impl SshSource {
    pub fn open(label: String, remote: std::rc::Rc<ssh2::Sftp>) -> Self {
        Self { label, remote }
    }
}

#[cfg(feature = "ssh")]
impl std::fmt::Display for SshSource {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        self.label.fmt(f)
    }
}

#[cfg(feature = "ssh")]
impl ChooserSource for SshSource {
    type Error = ssh2::Error;

    fn current_dir(&self) -> Result<PathBuf, Self::Error> {
        self.remote.realpath(Path::new("."))
    }

    fn read_dir(&self, dir: &Path, show_hidden: bool) -> Result<Vec<Entry>, Self::Error> {
        self.remote
            .readdir(dir)
            .map(|entries| {
                entries
                    .into_iter()
                    .map(|(pb, _)| {
                        Entry::from((
                            self.remote.stat(&pb).map(|s| s.is_dir()).unwrap_or(false),
                            pb,
                        ))
                    })
                    .filter_map(|e| (show_hidden || !e.is_hidden()).then_some(e))
                    .collect()
            })
            .map(|mut entries: Vec<Entry>| {
                entries.sort_unstable_by(|x, y| {
                    x.is_dir.cmp(&y.is_dir).reverse().then(x.path.cmp(&y.path))
                });
                entries
            })
    }

    fn open(&self, path: PathBuf) -> Source {
        Source::Ssh {
            sftp: std::rc::Rc::clone(&self.remote),
            path,
        }
    }

    fn target(&self) -> DirTarget {
        DirTarget::Ssh
    }
}

#[cfg(feature = "ssh")]
#[derive(Clone)]
pub enum EitherSource {
    /// No SSH connection specified, only local files possible
    Local(LocalSource),
    /// Either remote or local files are possible
    Ssh {
        local: LocalSource,
        ssh: SshSource,
        active: DirTarget,
    },
}

#[cfg(feature = "ssh")]
impl EitherSource {
    pub fn local() -> Self {
        Self::Local(LocalSource)
    }

    pub fn ssh(ssh: SshSource, active: DirTarget) -> Self {
        Self::Ssh {
            local: LocalSource,
            ssh,
            active,
        }
    }
}

#[cfg(feature = "ssh")]
impl std::fmt::Display for EitherSource {
    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
        match self {
            Self::Local(local)
            | Self::Ssh {
                local,
                active: DirTarget::Local,
                ..
            } => local.fmt(f),
            Self::Ssh {
                ssh,
                active: DirTarget::Ssh,
                ..
            } => ssh.fmt(f),
        }
    }
}

#[cfg(feature = "ssh")]
impl ChooserSource for EitherSource {
    type Error = RemoteError;

    fn current_dir(&self) -> Result<PathBuf, Self::Error> {
        match self {
            Self::Local(local)
            | Self::Ssh {
                local,
                active: DirTarget::Local,
                ..
            } => local.current_dir().map_err(RemoteError::Io),
            Self::Ssh {
                ssh,
                active: DirTarget::Ssh,
                ..
            } => ssh.current_dir().map_err(RemoteError::Ssh),
        }
    }

    fn read_dir(&self, dir: &Path, show_hidden: bool) -> Result<Vec<Entry>, Self::Error> {
        match self {
            Self::Local(local)
            | Self::Ssh {
                local,
                active: DirTarget::Local,
                ..
            } => local.read_dir(dir, show_hidden).map_err(RemoteError::Io),
            Self::Ssh {
                ssh,
                active: DirTarget::Ssh,
                ..
            } => ssh.read_dir(dir, show_hidden).map_err(RemoteError::Ssh),
        }
    }

    fn open(&self, path: PathBuf) -> Source {
        match self {
            Self::Local(local)
            | Self::Ssh {
                local,
                active: DirTarget::Local,
                ..
            } => local.open(path),
            Self::Ssh {
                ssh,
                active: DirTarget::Ssh,
                ..
            } => ssh.open(path),
        }
    }

    fn target(&self) -> DirTarget {
        match self {
            Self::Local(local)
            | Self::Ssh {
                local,
                active: DirTarget::Local,
                ..
            } => local.target(),
            Self::Ssh {
                ssh,
                active: DirTarget::Ssh,
                ..
            } => ssh.target(),
        }
    }

    fn toggleable(&self) -> bool {
        matches!(self, Self::Ssh { .. })
    }

    fn toggle_source(&mut self) -> DirTarget {
        match self {
            Self::Local(_) => DirTarget::Local,
            Self::Ssh {
                active: active @ DirTarget::Local,
                ..
            } => {
                *active = DirTarget::Ssh;
                DirTarget::Ssh
            }
            Self::Ssh {
                active: active @ DirTarget::Ssh,
                ..
            } => {
                *active = DirTarget::Local;
                DirTarget::Local
            }
        }
    }
}

pub struct FileChooser<S: ChooserSource> {
    phantom: std::marker::PhantomData<S>,
}

impl<S: ChooserSource> Default for FileChooser<S> {
    fn default() -> Self {
        Self {
            phantom: std::marker::PhantomData,
        }
    }
}

impl<S: ChooserSource> StatefulWidget for FileChooser<S> {
    type State = FileChooserState<S>;

    fn render(
        self,
        area: ratatui::layout::Rect,
        buf: &mut ratatui::buffer::Buffer,
        state: &mut FileChooserState<S>,
    ) {
        use crate::buffer::{BufferMessage, render_message};
        use crate::help::{CREATE_FILE, OPEN_FILE, OPEN_FILE_TOGGLEABLE, render_help};
        use crate::scrollbar::{Scrollbar, ScrollbarState};
        use ratatui::{
            layout::{
                Constraint::{Length, Min},
                Layout,
            },
            style::{Modifier, Style},
            text::{Line, Span},
            widgets::{Block, BorderType, List, ListState, Paragraph, Widget},
        };
        use std::borrow::Cow;

        let block = Block::bordered()
            .border_type(BorderType::Thick)
            .title_top(Line::from(vec![
                Span::raw("\u{252b}"),
                Span::styled(state.dir.display().to_string(), Style::default().bold()),
                Span::raw("\u{2523}"),
            ]))
            .title_bottom(
                Line::from(vec![
                    Span::raw("\u{252b}"),
                    Span::styled(state.source.to_string(), Style::default().bold()),
                    Span::raw("\u{2523}"),
                ])
                .centered(),
            );

        ratatui::widgets::Clear.render(area, buf);

        let [top_area, list_area] = Layout::vertical([Length(3), Min(0)]).areas(block.inner(area));

        let [list_area, scrollbar_area] = Layout::horizontal([Min(0), Length(1)]).areas(list_area);

        block.render(area, buf);

        let [text_area, _] = Layout::horizontal([Length(TEXT_WIDTH + 2), Min(0)]).areas(top_area);

        match &state.chosen {
            Chosen::Default => Paragraph::new("")
                .block(
                    Block::bordered()
                        .border_type(BorderType::Rounded)
                        .title("Filename"),
                )
                .render(text_area, buf),
            Chosen::New(filename) => Paragraph::new(crate::truncate::line_start(
                filename.value().unwrap_or_default().into(),
                filename.cursor_column().saturating_sub(TEXT_WIDTH.into()),
            ))
            .block(
                Block::bordered()
                    .border_type(BorderType::Rounded)
                    .title("Filename"),
            )
            .render(text_area, buf),
            Chosen::Selected(items) => Paragraph::new(match items.len() {
                1 => Cow::Borrowed("1 File Selected"),
                n => Cow::Owned(format!("{n} Files Selected")),
            })
            .block(Block::bordered().border_type(BorderType::Rounded))
            .render(text_area, buf),
        }

        StatefulWidget::render(
            (match &state.chosen {
                Chosen::Default | Chosen::New(_) => List::new(state.dir_entries()),
                Chosen::Selected(selected) => List::new(state.contents.iter().map(|e| {
                    if selected.contains(&e.path) {
                        format!("* {}", e.name)
                    } else {
                        format!("  {}", e.name)
                    }
                })),
            })
            .highlight_style(Style::default().add_modifier(Modifier::REVERSED)),
            list_area,
            buf,
            &mut ListState::default()
                .with_selected(state.selected_entry())
                .with_offset(
                    state
                        .selected_entry()
                        .map(|s| s.saturating_sub(usize::from(list_area.height) / 2))
                        .unwrap_or_default(),
                ),
        );

        Scrollbar.render(
            scrollbar_area,
            buf,
            &mut ScrollbarState::new(state.contents.len())
                .viewport_content_length(list_area.height.into())
                .position(
                    state
                        .selected_entry()
                        .map(|s| s.saturating_sub(usize::from(list_area.height) / 2))
                        .unwrap_or_default(),
                ),
        );

        render_help(
            list_area,
            buf,
            match &state.chosen {
                Chosen::Default | Chosen::Selected(_) => {
                    if state.source.toggleable() {
                        OPEN_FILE_TOGGLEABLE
                    } else {
                        OPEN_FILE
                    }
                }
                Chosen::New(_) => CREATE_FILE,
            },
            |b| {
                if state.show_hidden {
                    b.title_top("Showing Hidden")
                } else {
                    b
                }
            },
        );

        if let Some(error) = state.error.take() {
            render_message(list_area, buf, BufferMessage::Error(error.into()));
        }
    }
}

pub struct FileChooserState<S: ChooserSource> {
    cwd: PathBuf,          // editor's current working directory
    dir: PathBuf,          // directory we've navigated to
    contents: Vec<Entry>,  // directory entry
    dir_count: usize,      // number of directories in contents
    index: Option<usize>,  // index in directory entries
    chosen: Chosen,        // either new file or chosen entries
    error: Option<String>, // error message
    source: S,             // file source
    show_hidden: bool,     // whether to display hidden files
}

impl<S: ChooserSource> FileChooserState<S> {
    /// May return an error if unable to get the current
    /// working directory or are unable to read it
    pub fn new(source: S, dir: Option<PathBuf>) -> Result<Self, S::Error> {
        let cwd = source.current_dir()?;
        let dir = dir.unwrap_or_else(|| cwd.clone());

        let contents = source.read_dir(&dir, false)?;

        Ok(Self {
            dir,
            dir_count: contents.iter().take_while(|e| e.is_dir).count(),
            contents,
            cwd,
            index: None,
            chosen: Chosen::default(),
            error: None,
            source,
            show_hidden: false,
        })
    }

    pub fn update_dir(&mut self, new_dir: PathBuf) {
        match self.source.read_dir(&new_dir, self.show_hidden) {
            Ok(contents) => {
                self.dir_count = contents.iter().take_while(|e| e.is_dir).count();
                self.contents = contents;
                self.index = None;
                self.dir = new_dir;
            }
            Err(err) => {
                self.error = Some(err.to_string());
            }
        }
    }

    pub fn toggle_show_hidden(&mut self) {
        self.show_hidden = !self.show_hidden;
        let dir = std::mem::take(&mut self.dir);
        self.update_dir(dir);
    }

    pub fn dir_entries(&self) -> impl Iterator<Item = &str> {
        self.contents.iter().map(|e| e.name.as_str())
    }

    pub fn selected_entry(&self) -> Option<usize> {
        self.index
    }

    pub fn selected_dir(&self) -> &Path {
        self.dir.as_path()
    }

    pub fn arrow_up(&mut self) {
        if matches!(self.chosen, Chosen::Default | Chosen::Selected(_)) {
            self.index = match self.index {
                None => max_index(&self.chosen, &self.contents, self.dir_count).checked_sub(1),
                Some(i) => i.checked_sub(1).or_else(|| {
                    max_index(&self.chosen, &self.contents, self.dir_count).checked_sub(1)
                }),
            }
        }
    }

    pub fn arrow_down(&mut self) {
        if matches!(self.chosen, Chosen::Default | Chosen::Selected(_)) {
            self.index = (match self.index {
                None => Some(0),
                Some(i) => Some(i + 1),
            })
            .and_then(|i| i.checked_rem(max_index(&self.chosen, &self.contents, self.dir_count)));
        }
    }

    pub fn page_up(&mut self) {
        if matches!(self.chosen, Chosen::Default | Chosen::Selected(_)) {
            self.index = (match self.index {
                None => Some(0),
                Some(idx) => Some(idx.saturating_sub(PAGE_SIZE)),
            })
            .filter(|i| *i < max_index(&self.chosen, &self.contents, self.dir_count))
        }
    }

    pub fn page_down(&mut self) {
        if matches!(self.chosen, Chosen::Default | Chosen::Selected(_)) {
            self.index = match max_index(&self.chosen, &self.contents, self.dir_count) {
                0 => None,
                max => match self.index {
                    None => Some(PAGE_SIZE.min(max - 1)),
                    Some(idx) => Some((idx + PAGE_SIZE).min(max - 1)),
                },
            }
        }
    }

    pub fn home(&mut self) {
        match &mut self.chosen {
            Chosen::New(filename) => {
                filename.cursor_home();
            }
            _ => {
                self.index = match max_index(&self.chosen, &self.contents, self.dir_count) {
                    0 => None,
                    _ => Some(0),
                }
            }
        }
    }

    pub fn end(&mut self) {
        match &mut self.chosen {
            Chosen::New(filename) => {
                filename.cursor_end();
            }
            _ => {
                self.index = max_index(&self.chosen, &self.contents, self.dir_count).checked_sub(1);
            }
        }
    }

    pub fn arrow_right(&mut self) {
        match &mut self.chosen {
            Chosen::New(filename) => {
                filename.cursor_forward();
            }
            _ => {
                if let Some(idx) = self.index
                    && let Some(Entry {
                        path, is_dir: true, ..
                    }) = self.contents.get(idx)
                {
                    self.update_dir(path.clone());
                }
            }
        }
    }

    pub fn arrow_left(&mut self) {
        match &mut self.chosen {
            Chosen::New(filename) => {
                filename.cursor_back();
            }
            _ => {
                if let Some(parent) = self.dir.parent()
                    && parent != Path::new("")
                {
                    self.update_dir(parent.to_path_buf());
                }
            }
        }
    }

    pub fn insert_char(&mut self, c: char) {
        match &mut self.chosen {
            Chosen::Default => {
                self.chosen = Chosen::New({
                    let mut filename = TextField::default();
                    filename.insert_char(c);
                    filename
                });
                self.index = None;
            }
            Chosen::New(prompt) => {
                prompt.insert_char(c);
                self.index = None;
            }
            Chosen::Selected(_) => { /* do nothing */ }
        }
    }

    pub fn backspace(&mut self) {
        if let Chosen::New(prompt) = &mut self.chosen {
            prompt.backspace();
            if prompt.is_empty() {
                self.chosen = Chosen::Default;
            }
        }
    }

    pub fn toggle_selected(&mut self) {
        if let Some(idx) = self.index
            && let Some(Entry {
                path,
                is_dir: false,
                ..
            }) = self.contents.get(idx)
        {
            match &mut self.chosen {
                Chosen::Default => {
                    self.chosen = Chosen::Selected(BTreeSet::from([path.clone()]));
                }
                // use Entry API in the future, whenever that stabilizes
                Chosen::Selected(selected) => {
                    if !selected.insert(path.clone()) {
                        selected.remove(path);
                        if selected.is_empty() {
                            self.chosen = Chosen::Default;
                        }
                    }
                }
                Chosen::New(_) => { /* this shouldn't be possible */ }
            }
        }
    }

    pub fn select(&mut self) -> Option<Vec<Source>> {
        fn strip_cwd(cwd: &Path, path: &Path) -> PathBuf {
            match path.strip_prefix(cwd) {
                Ok(stripped) => stripped.to_path_buf(),
                Err(_) => path.to_owned(),
            }
        }

        match std::mem::take(&mut self.chosen) {
            Chosen::Default => match self.contents.get(self.index?)? {
                Entry {
                    is_dir: true, path, ..
                } => {
                    self.update_dir(path.clone());
                    None
                }
                Entry {
                    is_dir: false,
                    path,
                    ..
                } => Some(vec![self.source.open(strip_cwd(&self.cwd, path))]),
            },
            Chosen::New(filename) => Some(vec![self.source.open(strip_cwd(
                &self.cwd,
                &self.dir.join(filename.value().expect("empty filename")),
            ))]),
            Chosen::Selected(selected) => Some(
                selected
                    .into_iter()
                    .map(|path| self.source.open(strip_cwd(&self.cwd, &path)))
                    .collect(),
            ),
        }
    }

    pub fn cursor_position(&self) -> (u16, u16) {
        match &self.chosen {
            Chosen::Default => (1, 1),
            Chosen::New(filename) => ((filename.cursor_column() as u16).min(TEXT_WIDTH) + 1, 1),
            Chosen::Selected(_) => (1, 1),
        }
    }

    pub fn target(&self) -> DirTarget {
        self.source.target()
    }

    pub fn toggle_source(&mut self, open_dir: &mut crate::editor::OpenDir) -> Result<(), S::Error> {
        if self.source.toggleable() {
            let target = self.source.toggle_source();
            *self = Self::new(self.source.clone(), open_dir[target].clone())?;
        }
        Ok(())
    }
}

fn max_index(chosen: &Chosen, contents: &[Entry], dir_count: usize) -> usize {
    match chosen {
        Chosen::Default | Chosen::Selected(_) => contents.len(),
        Chosen::New(_) => dir_count,
    }
}

pub struct Entry {
    name: String,  // user-visible name
    path: PathBuf, // actual path on disk
    is_dir: bool,  // whether item is directory
}

impl Entry {
    fn is_hidden(&self) -> bool {
        self.name.starts_with('.')
    }
}

impl TryFrom<std::fs::DirEntry> for Entry {
    type Error = std::io::Error;

    fn try_from(entry: std::fs::DirEntry) -> std::io::Result<Self> {
        let path = entry.path();
        let is_dir = std::fs::metadata(&path)
            .map(|m| m.is_dir())
            .unwrap_or(false);
        Ok(Self {
            name: match is_dir {
                false => entry.file_name().display().to_string(),
                true => format!(
                    "{}{}",
                    entry.file_name().display(),
                    std::path::MAIN_SEPARATOR,
                ),
            },
            is_dir,
            path,
        })
    }
}

#[cfg(feature = "ssh")]
impl From<(bool, PathBuf)> for Entry {
    fn from((is_dir, path): (bool, PathBuf)) -> Self {
        Self {
            name: match is_dir {
                false => path
                    .file_name()
                    .map(|n| n.display().to_string())
                    .unwrap_or_default(),
                true => format!(
                    "{}{}",
                    path.file_name()
                        .map(|n| n.display().to_string())
                        .unwrap_or_default(),
                    std::path::MAIN_SEPARATOR,
                ),
            },
            path,
            is_dir,
        }
    }
}

#[derive(Default)]
enum Chosen {
    #[default]
    Default, // nothing selected
    New(TextField),              // new file
    Selected(BTreeSet<PathBuf>), // selected existing file(s)
}