peter-commander 0.9.1

A terminal file manager
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
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::time::SystemTime;

use anyhow::Result;

/// Whether `path` counts as "executable" — the same thing Enter checks to
/// decide whether to run it. On Unix this is the permission bit; Windows
/// has no such bit, so it goes by extension instead (the same signal the
/// shell itself uses, via `PATHEXT`).
#[cfg(unix)]
fn is_executable_file(_path: &Path, metadata: &fs::Metadata) -> bool {
    use std::os::unix::fs::PermissionsExt;
    metadata.permissions().mode() & 0o111 != 0
}

#[cfg(windows)]
fn is_executable_file(path: &Path, _metadata: &fs::Metadata) -> bool {
    path.extension()
        .and_then(|ext| ext.to_str())
        .is_some_and(|ext| matches!(ext.to_lowercase().as_str(), "exe" | "bat" | "cmd" | "com"))
}

/// Whether "hide hidden files" should skip this entry. Unix hides by
/// dotfile-naming convention only. Windows keeps that (dotfiles like
/// `.gitignore` are common even there) but additionally hides via the
/// Hidden file attribute — this is also how Windows marks the legacy
/// localized-name compatibility junctions in the user profile (e.g. "Moje
/// Dokumenty" alongside the real "Documents"), which additionally deny
/// direct access (`ERROR_ACCESS_DENIED`) if entered, so hiding them by
/// convention avoids a dead end in the listing rather than just a cosmetic
/// duplicate.
#[cfg(windows)]
fn is_hidden_entry(name: &str, metadata: &fs::Metadata) -> bool {
    use std::os::windows::fs::MetadataExt;
    const FILE_ATTRIBUTE_HIDDEN: u32 = 0x2;
    name.starts_with('.') || metadata.file_attributes() & FILE_ATTRIBUTE_HIDDEN != 0
}

#[cfg(unix)]
fn is_hidden_entry(name: &str, _metadata: &fs::Metadata) -> bool {
    name.starts_with('.')
}

#[derive(Debug, Clone)]
pub struct Entry {
    pub name: String,
    pub is_dir: bool,
    pub size: u64,
    pub modified: Option<SystemTime>,
    /// Whether this is a file with an executable permission bit set — the
    /// same thing Enter checks to decide whether to run it.
    pub is_executable: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum SortKey {
    Name,
    Extension,
    Size,
    Modified,
}

impl SortKey {
    /// Size and date read most usefully biggest/newest first (as in Norton
    /// and Total Commander); name and extension A→Z.
    fn descending_by_default(self) -> bool {
        matches!(self, SortKey::Size | SortKey::Modified)
    }

    pub const ALL: [SortKey; 4] = [
        SortKey::Name,
        SortKey::Extension,
        SortKey::Size,
        SortKey::Modified,
    ];

    /// Stable identifier for the saved state file, independent of `label`.
    pub fn key(self) -> &'static str {
        match self {
            SortKey::Name => "name",
            SortKey::Extension => "extension",
            SortKey::Size => "size",
            SortKey::Modified => "modified",
        }
    }

    pub fn from_key(key: &str) -> Option<SortKey> {
        SortKey::ALL.into_iter().find(|sort| sort.key() == key)
    }

    pub fn label(self) -> &'static str {
        match self {
            SortKey::Name => "Name",
            SortKey::Extension => "Type",
            SortKey::Size => "Size",
            SortKey::Modified => "Date",
        }
    }
}

/// Shell-style wildcard match: `*` is any run of characters (including
/// none), `?` exactly one.
fn wildcard_match(pattern: &str, name: &str) -> bool {
    let pattern: Vec<char> = pattern.chars().collect();
    let name: Vec<char> = name.chars().collect();
    let (mut p, mut n) = (0, 0);
    // Where the last `*` was, and how much of the name it has swallowed.
    let mut star: Option<(usize, usize)> = None;
    while n < name.len() {
        if p < pattern.len() && (pattern[p] == '?' || pattern[p] == name[n]) {
            p += 1;
            n += 1;
        } else if p < pattern.len() && pattern[p] == '*' {
            star = Some((p, n));
            p += 1;
        } else if let Some((star_p, star_n)) = star {
            p = star_p + 1;
            n = star_n + 1;
            star = Some((star_p, star_n + 1));
        } else {
            return false;
        }
    }
    pattern[p..].iter().all(|&c| c == '*')
}

fn extension_of(name: &str) -> String {
    Path::new(name)
        .extension()
        .map(|ext| ext.to_string_lossy().to_lowercase())
        .unwrap_or_default()
}

/// Only the sort key itself is flipped by `descending`; ties always fall
/// back to A→Z by name, so e.g. directories (all "equal" under a size sort)
/// stay alphabetical whichever way sizes run.
fn compare_entries(a: &Entry, b: &Entry, key: SortKey, descending: bool) -> std::cmp::Ordering {
    let by_name = || a.name.to_lowercase().cmp(&b.name.to_lowercase());
    let primary = match key {
        SortKey::Name => by_name(),
        SortKey::Extension => extension_of(&a.name).cmp(&extension_of(&b.name)),
        // A directory's own metadata length isn't its content size, so
        // directories stay alphabetical under a size sort.
        SortKey::Size if a.is_dir && b.is_dir => std::cmp::Ordering::Equal,
        SortKey::Size => a.size.cmp(&b.size),
        SortKey::Modified => a.modified.cmp(&b.modified),
    };
    let primary = if descending {
        primary.reverse()
    } else {
        primary
    };
    primary.then_with(by_name)
}

#[derive(Debug)]
pub struct Pane {
    pub cwd: PathBuf,
    pub entries: Vec<Entry>,
    pub selected: usize,
    /// Whether dotfiles (names starting with `.`) are filtered out of the
    /// listing. The ".." pseudo-entry is always shown regardless.
    pub hide_hidden: bool,
    /// Names tagged with Insert, independent of the cursor position — F5/
    /// F6/F8 act on this whole set when it's non-empty, instead of just the
    /// entry under the cursor. Never contains "..".
    pub marked: HashSet<String>,
    pub sort_key: SortKey,
    /// Flips `sort_key`'s natural direction (see
    /// `SortKey::descending_by_default`).
    pub sort_reversed: bool,
}

impl Pane {
    pub fn new(cwd: PathBuf, hide_hidden: bool) -> Result<Self> {
        let mut pane = Pane {
            cwd,
            entries: Vec::new(),
            selected: 0,
            hide_hidden,
            marked: HashSet::new(),
            sort_key: SortKey::Name,
            sort_reversed: false,
        };
        pane.reload()?;
        Ok(pane)
    }

    pub fn reload(&mut self) -> Result<()> {
        let mut entries = Vec::new();

        if self.cwd.parent().is_some() {
            entries.push(Entry {
                name: "..".to_string(),
                is_dir: true,
                size: 0,
                modified: None,
                is_executable: false,
            });
        }

        let mut dirs = Vec::new();
        let mut files = Vec::new();
        for entry in fs::read_dir(&self.cwd)? {
            // Skip entries we can't stat (e.g. broken symlinks, permission
            // issues on a single item) instead of failing the whole listing.
            let Ok(entry) = entry else { continue };
            let name = entry.file_name().to_string_lossy().to_string();
            // The hidden check always uses the entry's own (non-following)
            // metadata: a reparse point like a Windows compatibility
            // junction transparently forwards a followed stat to its
            // target's attributes, losing the junction's own Hidden flag.
            let Ok(link_metadata) = entry.metadata() else {
                continue;
            };
            if self.hide_hidden && is_hidden_entry(&name, &link_metadata) {
                continue;
            }
            // Follow symlinks for classification (so a symlink to a
            // directory is treated as a directory, matching `ls -L`);
            // fall back to the link's own metadata for broken symlinks.
            let metadata = fs::metadata(entry.path()).unwrap_or(link_metadata);
            let is_dir = metadata.is_dir();
            let item = Entry {
                name,
                is_dir,
                size: metadata.len(),
                modified: metadata.modified().ok(),
                is_executable: !is_dir && is_executable_file(&entry.path(), &metadata),
            };
            if item.is_dir {
                dirs.push(item);
            } else {
                files.push(item);
            }
        }
        let key = self.sort_key;
        let descending = key.descending_by_default() != self.sort_reversed;
        dirs.sort_by(|a, b| compare_entries(a, b, key, descending));
        files.sort_by(|a, b| compare_entries(a, b, key, descending));

        entries.extend(dirs);
        entries.extend(files);

        self.entries = entries;
        if self.selected >= self.entries.len() {
            self.selected = self.entries.len().saturating_sub(1);
        }
        if !self.marked.is_empty() {
            let names: HashSet<&str> = self.entries.iter().map(|e| e.name.as_str()).collect();
            self.marked.retain(|m| names.contains(m.as_str()));
        }
        Ok(())
    }

    /// Command > Sort by ...: picking the key already in use flips its
    /// direction instead, as in Midnight Commander. The cursor stays on the
    /// same entry rather than the same row.
    pub fn set_sort(&mut self, key: SortKey) -> Result<()> {
        let reversed = self.sort_key == key && !self.sort_reversed;
        self.apply_sort(key, reversed)
    }

    /// Sorts by exactly `key`/`reversed` (e.g. restoring the last
    /// session's sort), keeping the cursor on the same entry.
    pub fn apply_sort(&mut self, key: SortKey, reversed: bool) -> Result<()> {
        self.sort_key = key;
        self.sort_reversed = reversed;
        let selected_name = self.selected_entry().map(|e| e.name.clone());
        self.reload()?;
        if let Some(name) = selected_name {
            self.select_name(&name);
        }
        Ok(())
    }

    /// Select/Unselect Files: marks (or unmarks) every file whose name
    /// matches any of the space- or comma-separated wildcard patterns
    /// (`*`, `?`, case-insensitive). Like Norton Commander, only files —
    /// directories are left as they are. Returns how many changed.
    pub fn mark_matching(&mut self, patterns: &str, select: bool) -> usize {
        let patterns: Vec<String> = patterns
            .split([' ', ','])
            .filter(|p| !p.is_empty())
            .map(str::to_lowercase)
            .collect();
        let mut changed = 0;
        for entry in self.entries.iter().filter(|e| !e.is_dir) {
            let name = entry.name.to_lowercase();
            if !patterns
                .iter()
                .any(|pattern| wildcard_match(pattern, &name))
            {
                continue;
            }
            let did_change = if select {
                self.marked.insert(entry.name.clone())
            } else {
                self.marked.remove(&entry.name)
            };
            if did_change {
                changed += 1;
            }
        }
        changed
    }

    /// Invert Selection: flips the mark on every file (directories, as in
    /// Norton Commander, are left alone). Returns how many end up marked.
    pub fn invert_marks(&mut self) -> usize {
        for entry in self.entries.iter().filter(|e| !e.is_dir) {
            if !self.marked.remove(&entry.name) {
                self.marked.insert(entry.name.clone());
            }
        }
        self.marked.len()
    }

    /// Moves the cursor onto the entry called `name`, if it's listed.
    pub fn select_name(&mut self, name: &str) {
        if let Some(idx) = self.entries.iter().position(|e| e.name == name) {
            self.selected = idx;
        }
    }

    /// Whether the current sort runs high-to-low (Z→A, biggest/newest
    /// first).
    pub fn sort_descending(&self) -> bool {
        self.sort_key.descending_by_default() != self.sort_reversed
    }

    /// How the listing is sorted, for the pane title — e.g. "Size↓".
    pub fn sort_indicator(&self) -> String {
        let arrow = if self.sort_descending() {
            '\u{2193}'
        } else {
            '\u{2191}'
        };
        format!("{}{arrow}", self.sort_key.label())
    }

    /// Quick search: the first entry at or after `start` (wrapping around,
    /// or going backwards with `forward == false`) whose name contains
    /// `query`, ignoring case. ".." never matches.
    pub fn find_match(&self, query: &str, start: usize, forward: bool) -> Option<usize> {
        let len = self.entries.len();
        if len == 0 || query.is_empty() {
            return None;
        }
        let query = query.to_lowercase();
        (0..len)
            .map(|step| {
                if forward {
                    (start + step) % len
                } else {
                    (start + len - step % len) % len
                }
            })
            .find(|&idx| {
                let name = &self.entries[idx].name;
                name != ".." && name.to_lowercase().contains(&query)
            })
    }

    pub fn selected_entry(&self) -> Option<&Entry> {
        self.entries.get(self.selected)
    }

    /// Insert: tags/untags the entry under the cursor (a no-op on "..",
    /// which can never be marked, but — matching the original NC — still
    /// steps the cursor down like any other entry) and moves the cursor
    /// down, so repeated presses sweep down through a run of files.
    pub fn toggle_mark_selected(&mut self) {
        let Some(entry) = self.selected_entry() else {
            return;
        };
        if entry.name != ".." {
            let name = entry.name.clone();
            if !self.marked.remove(&name) {
                self.marked.insert(name);
            }
        }
        self.move_down();
    }

    /// The marked entries as `(name, full path)` pairs, in listing order.
    /// Empty when nothing is tagged — callers fall back to the entry under
    /// the cursor in that case.
    pub fn marked_items(&self) -> Vec<(String, PathBuf)> {
        self.entries
            .iter()
            .filter(|e| self.marked.contains(&e.name))
            .map(|e| (e.name.clone(), self.cwd.join(&e.name)))
            .collect()
    }

    pub fn clear_marks(&mut self) {
        self.marked.clear();
    }

    /// `(count, total bytes)` of the marked entries, for the pane's status
    /// line — `None` when nothing is tagged, so the caller falls back to
    /// showing the plain file/dir totals instead. Directory sizes aren't
    /// summed in (a directory's raw metadata length isn't its content
    /// size), matching how the listing itself never shows a byte size for
    /// directories either.
    pub fn marked_summary(&self) -> Option<(usize, u64)> {
        if self.marked.is_empty() {
            return None;
        }
        let mut count = 0usize;
        let mut bytes = 0u64;
        for entry in &self.entries {
            if self.marked.contains(&entry.name) {
                count += 1;
                if !entry.is_dir {
                    bytes += entry.size;
                }
            }
        }
        Some((count, bytes))
    }

    /// `(files, dirs)` in the listing, excluding the ".." pseudo-entry —
    /// the pane's status line default when nothing is marked.
    pub fn totals(&self) -> (usize, usize) {
        let mut files = 0usize;
        let mut dirs = 0usize;
        for entry in &self.entries {
            if entry.name == ".." {
                continue;
            }
            if entry.is_dir {
                dirs += 1;
            } else {
                files += 1;
            }
        }
        (files, dirs)
    }

    /// The filesystem path of the selected entry, or `None` for the ".." pseudo-entry.
    pub fn selected_path(&self) -> Option<PathBuf> {
        let entry = self.selected_entry()?;
        if entry.name == ".." {
            None
        } else {
            Some(self.cwd.join(&entry.name))
        }
    }

    /// The filesystem path the quick-view preview should show for the
    /// current selection: the parent directory for "..", otherwise the
    /// selected entry itself. Unlike `selected_path`, this resolves ".."
    /// instead of returning `None`, since the preview always has something
    /// to point at.
    pub fn preview_target(&self) -> Option<PathBuf> {
        let entry = self.selected_entry()?;
        if entry.name == ".." {
            Some(self.cwd.parent().unwrap_or(&self.cwd).to_path_buf())
        } else {
            Some(self.cwd.join(&entry.name))
        }
    }

    pub fn move_up(&mut self) {
        if self.selected > 0 {
            self.selected -= 1;
        }
    }

    pub fn move_down(&mut self) {
        if self.selected + 1 < self.entries.len() {
            self.selected += 1;
        }
    }

    pub fn move_to_top(&mut self) {
        self.selected = 0;
    }

    pub fn move_to_bottom(&mut self) {
        self.selected = self.entries.len().saturating_sub(1);
    }

    /// PgUp: moves up roughly one screenful (`page` rows).
    pub fn move_page_up(&mut self, page: usize) {
        self.selected = self.selected.saturating_sub(page);
    }

    /// PgDown: moves down roughly one screenful (`page` rows).
    pub fn move_page_down(&mut self, page: usize) {
        let last = self.entries.len().saturating_sub(1);
        self.selected = (self.selected + page).min(last);
    }

    /// Switches to `new_path`. Returns `Ok(Some(message))` and leaves the
    /// current directory unchanged if it couldn't be entered (e.g.
    /// permission denied), instead of propagating a fatal error.
    fn set_cwd(&mut self, new_path: PathBuf) -> Result<Option<String>> {
        self.set_cwd_selecting(new_path, None)
    }

    /// Like `set_cwd`, but if `select_name` is given and found among the
    /// reloaded entries, selects it instead of defaulting to the top. Used
    /// when navigating up so the cursor lands back on the folder just left,
    /// instead of resetting to the top of the parent listing.
    fn set_cwd_selecting(
        &mut self,
        new_path: PathBuf,
        select_name: Option<&str>,
    ) -> Result<Option<String>> {
        let previous_cwd = self.cwd.clone();
        let previous_selected = self.selected;
        // Marks belong to the listing they were made in — carrying them by
        // name into a different directory would tag an unrelated file that
        // happens to share a name (e.g. every directory's own ".gitignore"),
        // and silently drop the rest. So a real directory change starts
        // from a clean slate, same as the fresh `Pane` the app boots with.
        let previous_marked = std::mem::take(&mut self.marked);
        self.cwd = new_path;
        self.selected = 0;

        if let Err(err) = self.reload() {
            self.cwd = previous_cwd;
            self.selected = previous_selected;
            self.marked = previous_marked;
            return Ok(Some(format!("Cannot open directory: {err}")));
        }

        if let Some(name) = select_name
            && let Some(index) = self.entries.iter().position(|e| e.name == name)
        {
            self.selected = index;
        }
        Ok(None)
    }

    /// Enters the selected directory (see `set_cwd` for failure handling).
    pub fn enter_selected(&mut self) -> Result<Option<String>> {
        let Some(entry) = self.selected_entry() else {
            return Ok(None);
        };
        if !entry.is_dir {
            return Ok(None);
        }

        if entry.name == ".." {
            let left_name = self
                .cwd
                .file_name()
                .map(|n| n.to_string_lossy().to_string());
            let new_path = self
                .cwd
                .parent()
                .map(Path::to_path_buf)
                .unwrap_or_else(|| self.cwd.clone());
            return self.set_cwd_selecting(new_path, left_name.as_deref());
        }

        let new_path = self.cwd.join(&entry.name);
        self.set_cwd(new_path)
    }

    /// Changes directory to `target` (absolute, or relative to the current
    /// directory), resolving `.`/`..`/symlinks where possible. Used by the
    /// command line's built-in `cd` handling (see `set_cwd` for failure
    /// handling).
    pub fn change_dir(&mut self, target: &Path) -> Result<Option<String>> {
        let candidate = if target.is_absolute() {
            target.to_path_buf()
        } else {
            self.cwd.join(target)
        };
        let new_path = fs::canonicalize(&candidate)
            .map(strip_verbatim_prefix)
            .unwrap_or(candidate);
        self.set_cwd(new_path)
    }
}

/// `fs::canonicalize` on Windows always returns a `\\?\`-prefixed "verbatim"
/// path (e.g. `\\?\C:\Users\Piotr`) — harmless to Win32 APIs, but ugly in
/// the prompt and not understood by every external program `cd` might hand
/// the path to. This strips that prefix back to the ordinary form, same as
/// what a plain (non-canonicalized) path would look like. A no-op on other
/// platforms, where `canonicalize` doesn't add such a prefix.
#[cfg(windows)]
pub fn strip_verbatim_prefix(path: PathBuf) -> PathBuf {
    let s = path.to_string_lossy();
    if let Some(rest) = s.strip_prefix(r"\\?\UNC\") {
        PathBuf::from(format!(r"\\{rest}"))
    } else if let Some(rest) = s.strip_prefix(r"\\?\") {
        PathBuf::from(rest)
    } else {
        path
    }
}

#[cfg(not(windows))]
pub fn strip_verbatim_prefix(path: PathBuf) -> PathBuf {
    path
}

#[cfg(test)]
mod tests {
    use super::*;
    #[cfg(unix)]
    use std::os::unix::fs::PermissionsExt;

    // Permission bits and symlink creation without elevated privileges are
    // Unix-specific; these three tests don't have a Windows equivalent.
    #[cfg(unix)]
    #[test]
    fn entering_unreadable_directory_shows_message_without_moving() {
        let base = std::env::temp_dir().join("pc_test_pane_noaccess");
        let _ = fs::remove_dir_all(&base);
        fs::create_dir_all(&base).unwrap();
        let locked = base.join("locked");
        fs::create_dir(&locked).unwrap();
        fs::set_permissions(&locked, fs::Permissions::from_mode(0o000)).unwrap();

        let mut pane = Pane::new(base.clone(), false).unwrap();
        pane.selected = pane
            .entries
            .iter()
            .position(|e| e.name == "locked")
            .unwrap();

        let result = pane.enter_selected().unwrap();

        assert!(result.is_some(), "expected a friendly error message");
        assert_eq!(pane.cwd, base, "cwd must not change on failed entry");

        fs::set_permissions(&locked, fs::Permissions::from_mode(0o755)).unwrap();
        fs::remove_dir_all(&base).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn symlink_to_directory_is_classified_as_a_directory() {
        let base = std::env::temp_dir().join("pc_test_pane_symlink");
        let _ = fs::remove_dir_all(&base);
        fs::create_dir_all(base.join("real_dir")).unwrap();
        std::os::unix::fs::symlink(base.join("real_dir"), base.join("link_to_dir")).unwrap();

        let pane = Pane::new(base.clone(), false).unwrap();
        let entry = pane
            .entries
            .iter()
            .find(|e| e.name == "link_to_dir")
            .unwrap();

        assert!(
            entry.is_dir,
            "a symlink to a directory must be classified as a directory"
        );

        fs::remove_dir_all(&base).unwrap();
    }

    #[cfg(unix)]
    #[test]
    fn broken_symlink_is_still_listed() {
        let base = std::env::temp_dir().join("pc_test_pane_broken_symlink");
        let _ = fs::remove_dir_all(&base);
        fs::create_dir_all(&base).unwrap();
        std::os::unix::fs::symlink(base.join("does_not_exist"), base.join("dangling")).unwrap();

        let pane = Pane::new(base.clone(), false).unwrap();
        assert!(
            pane.entries.iter().any(|e| e.name == "dangling"),
            "a broken symlink should still show up in the listing"
        );

        fs::remove_dir_all(&base).unwrap();
    }

    #[test]
    fn change_dir_moves_to_relative_and_absolute_targets() {
        let base = std::env::temp_dir().join("pc_test_pane_change_dir");
        let _ = fs::remove_dir_all(&base);
        fs::create_dir_all(base.join("sub")).unwrap();

        let mut pane = Pane::new(base.clone(), false).unwrap();

        let result = pane.change_dir(Path::new("sub")).unwrap();
        assert!(result.is_none());
        assert_eq!(
            pane.cwd,
            strip_verbatim_prefix(base.join("sub").canonicalize().unwrap())
        );

        let result = pane.change_dir(&base).unwrap();
        assert!(result.is_none());
        assert_eq!(
            pane.cwd,
            strip_verbatim_prefix(base.canonicalize().unwrap())
        );

        fs::remove_dir_all(&base).unwrap();
    }

    #[test]
    fn change_dir_to_missing_path_reports_error_without_moving() {
        let base = std::env::temp_dir().join("pc_test_pane_change_dir_missing");
        let _ = fs::remove_dir_all(&base);
        fs::create_dir_all(&base).unwrap();

        let mut pane = Pane::new(base.clone(), false).unwrap();
        let previous_cwd = pane.cwd.clone();

        let result = pane.change_dir(Path::new("does_not_exist")).unwrap();

        assert!(result.is_some());
        assert_eq!(pane.cwd, previous_cwd);

        fs::remove_dir_all(&base).unwrap();
    }

    #[test]
    fn hide_hidden_filters_dotfiles_but_keeps_dotdot() {
        let base = std::env::temp_dir().join("pc_test_pane_hidden");
        let _ = fs::remove_dir_all(&base);
        fs::create_dir_all(&base).unwrap();
        fs::write(base.join(".hidden_file"), "").unwrap();
        fs::write(base.join("visible_file"), "").unwrap();

        let pane = Pane::new(base.clone(), true).unwrap();
        assert!(!pane.entries.iter().any(|e| e.name == ".hidden_file"));
        assert!(pane.entries.iter().any(|e| e.name == "visible_file"));
        assert!(pane.entries.iter().any(|e| e.name == ".."));

        let pane = Pane::new(base.clone(), false).unwrap();
        assert!(pane.entries.iter().any(|e| e.name == ".hidden_file"));

        fs::remove_dir_all(&base).unwrap();
    }

    #[test]
    fn toggle_mark_selected_tags_and_steps_down_but_skips_dotdot() {
        let base = std::env::temp_dir().join("pc_test_pane_mark");
        let _ = fs::remove_dir_all(&base);
        fs::create_dir_all(&base).unwrap();
        fs::write(base.join("a.txt"), "").unwrap();
        fs::write(base.join("b.txt"), "").unwrap();

        let mut pane = Pane::new(base.clone(), false).unwrap();
        // Entries are ".." (dirs come first, and ".." is always first), then
        // the two files sorted by name.
        pane.selected = 0;
        pane.toggle_mark_selected();
        assert!(pane.marked.is_empty(), "\"..\" must never be markable");
        assert_eq!(
            pane.selected, 1,
            "but the cursor still steps down over it, like any other entry"
        );

        pane.toggle_mark_selected();
        assert!(pane.marked.contains("a.txt"));
        assert_eq!(pane.selected, 2, "marking steps the cursor down");

        pane.toggle_mark_selected();
        assert!(pane.marked.contains("a.txt"));
        assert!(pane.marked.contains("b.txt"));

        let items = pane.marked_items();
        assert_eq!(
            items,
            vec![
                ("a.txt".to_string(), base.join("a.txt")),
                ("b.txt".to_string(), base.join("b.txt")),
            ]
        );

        fs::remove_dir_all(&base).unwrap();
    }

    #[test]
    fn reload_drops_marks_for_entries_that_no_longer_exist() {
        let base = std::env::temp_dir().join("pc_test_pane_mark_reload");
        let _ = fs::remove_dir_all(&base);
        fs::create_dir_all(&base).unwrap();
        fs::write(base.join("a.txt"), "").unwrap();
        fs::write(base.join("b.txt"), "").unwrap();

        let mut pane = Pane::new(base.clone(), false).unwrap();
        pane.marked.insert("a.txt".to_string());
        pane.marked.insert("b.txt".to_string());

        fs::remove_file(base.join("a.txt")).unwrap();
        pane.reload().unwrap();

        assert!(!pane.marked.contains("a.txt"));
        assert!(pane.marked.contains("b.txt"));

        fs::remove_dir_all(&base).unwrap();
    }

    #[test]
    fn marked_summary_sums_bytes_of_marked_files_only() {
        let base = std::env::temp_dir().join("pc_test_pane_marked_summary");
        let _ = fs::remove_dir_all(&base);
        fs::create_dir_all(base.join("subdir")).unwrap();
        fs::write(base.join("a.txt"), "12345").unwrap();
        fs::write(base.join("b.txt"), "1234567890").unwrap();

        let mut pane = Pane::new(base.clone(), false).unwrap();
        assert_eq!(pane.marked_summary(), None, "nothing marked yet");

        pane.marked.insert("a.txt".to_string());
        pane.marked.insert("subdir".to_string());
        let (count, bytes) = pane.marked_summary().unwrap();
        assert_eq!(count, 2, "counts marked dirs too");
        assert_eq!(bytes, 5, "but only sums bytes of marked files");

        let (files, dirs) = pane.totals();
        assert_eq!((files, dirs), (2, 1), "totals() excludes \"..\"");

        fs::remove_dir_all(&base).unwrap();
    }

    #[test]
    fn changing_directory_clears_marks_even_when_the_other_dir_has_a_same_named_file() {
        let base = std::env::temp_dir().join("pc_test_pane_mark_dir_change");
        let _ = fs::remove_dir_all(&base);
        fs::create_dir_all(base.join("sub")).unwrap();
        fs::write(base.join(".gitignore"), "top").unwrap();
        fs::write(base.join("only_here.txt"), "").unwrap();
        // A same-named file in the other directory used to survive the
        // round trip and look "still marked" even though it's a completely
        // different file.
        fs::write(base.join("sub").join(".gitignore"), "nested").unwrap();

        let mut pane = Pane::new(base.clone(), false).unwrap();
        pane.marked.insert(".gitignore".to_string());
        pane.marked.insert("only_here.txt".to_string());

        pane.change_dir(Path::new("sub")).unwrap();
        assert!(
            pane.marked.is_empty(),
            "entering a different directory must not carry marks over by name"
        );

        pane.marked.insert(".gitignore".to_string());
        pane.change_dir(&base).unwrap();
        assert!(
            pane.marked.is_empty(),
            "leaving a directory must not leave stale marks behind either"
        );

        fs::remove_dir_all(&base).unwrap();
    }

    fn sort_test_dir(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(name);
        let _ = fs::remove_dir_all(&dir);
        fs::create_dir_all(dir.join("zdir")).unwrap();
        fs::create_dir_all(dir.join("adir")).unwrap();
        fs::write(dir.join("b.txt"), "12345").unwrap();
        fs::write(dir.join("a.rs"), "1").unwrap();
        fs::write(dir.join("c.md"), "123").unwrap();
        dir
    }

    fn names(pane: &Pane) -> Vec<&str> {
        pane.entries.iter().map(|e| e.name.as_str()).collect()
    }

    #[test]
    fn sorts_by_size_biggest_first_and_flips_when_picked_again() {
        let dir = sort_test_dir("pc_test_sort_size");
        let mut pane = Pane::new(dir.clone(), false).unwrap();
        pane.select_name("c.md");

        pane.set_sort(SortKey::Size).unwrap();
        assert_eq!(
            names(&pane),
            ["..", "adir", "zdir", "b.txt", "c.md", "a.rs"]
        );
        assert_eq!(pane.selected_entry().unwrap().name, "c.md");
        assert_eq!(pane.sort_indicator(), "Size\u{2193}");

        pane.set_sort(SortKey::Size).unwrap();
        assert_eq!(
            names(&pane),
            ["..", "adir", "zdir", "a.rs", "c.md", "b.txt"]
        );
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn sorts_by_extension_then_name() {
        let dir = sort_test_dir("pc_test_sort_ext");
        let mut pane = Pane::new(dir.clone(), false).unwrap();
        pane.set_sort(SortKey::Extension).unwrap();
        assert_eq!(
            names(&pane),
            ["..", "adir", "zdir", "c.md", "a.rs", "b.txt"]
        );
        pane.set_sort(SortKey::Name).unwrap();
        assert_eq!(
            names(&pane),
            ["..", "adir", "zdir", "a.rs", "b.txt", "c.md"]
        );
        assert_eq!(pane.sort_indicator(), "Name\u{2191}");
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn find_match_wraps_skips_dotdot_and_goes_both_ways() {
        let dir = sort_test_dir("pc_test_find_match");
        let pane = Pane::new(dir.clone(), false).unwrap();
        // ["..", "adir", "zdir", "a.rs", "b.txt", "c.md"]
        assert_eq!(pane.find_match("DIR", 0, true), Some(1));
        assert_eq!(pane.find_match("dir", 2, true), Some(2));
        assert_eq!(pane.find_match("dir", 3, true), Some(1));
        assert_eq!(pane.find_match("dir", 0, false), Some(2));
        assert_eq!(pane.find_match(".", 0, true), Some(3));
        assert_eq!(pane.find_match("nope", 0, true), None);
        fs::remove_dir_all(&dir).unwrap();
    }

    #[test]
    fn wildcards_match_like_a_shell() {
        assert!(wildcard_match("*", "anything.txt"));
        assert!(wildcard_match("*.txt", "a.txt"));
        assert!(!wildcard_match("*.txt", "a.txt.bak"));
        assert!(wildcard_match("a?c*", "abcdef"));
        assert!(!wildcard_match("a?c", "ac"));
        assert!(wildcard_match("*a*b*", "xxaxxbxx"));
        assert!(wildcard_match("", ""));
    }

    #[test]
    fn select_unselect_and_invert_touch_files_only() {
        let dir = sort_test_dir("pc_test_select_group");
        let mut pane = Pane::new(dir.clone(), false).unwrap();
        // files: a.rs, b.txt, c.md; dirs: adir, zdir
        assert_eq!(pane.mark_matching("*.TXT, *.md", true), 2);
        let mut marked: Vec<_> = pane.marked.iter().cloned().collect();
        marked.sort();
        assert_eq!(marked, ["b.txt", "c.md"]);
        assert_eq!(pane.mark_matching("*.md", false), 1);
        assert_eq!(pane.invert_marks(), 2);
        let mut marked: Vec<_> = pane.marked.iter().cloned().collect();
        marked.sort();
        assert_eq!(marked, ["a.rs", "c.md"]);
        assert_eq!(pane.mark_matching("*", true), 1);
        assert!(!pane.marked.contains("adir"));
        fs::remove_dir_all(&dir).unwrap();
    }
}