mouser-commander 0.1.5

Mouser's commander mode as a plugin: the shell's folder above the prompt, with previews and the media player
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
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
//! Commander mode (MODES.md Phase 1): a listing of the shell's working
//! directory shown above the prompt as a list, a grid or a carousel. This is
//! the model; the app builds the view from it and the renderer draws it.

use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};
use std::time::SystemTime;

/// What a file is, for its preview.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Kind {
    Dir,
    Image,
    Video,
    Audio,
    Text,
    Other,
}

impl Kind {
    pub fn label(self) -> &'static str {
        match self {
            Kind::Dir => "folder",
            Kind::Image => "image",
            Kind::Video => "video",
            Kind::Audio => "audio",
            Kind::Text => "text",
            Kind::Other => "file",
        }
    }
}

/// Kind by name (directories are found from the metadata).
pub fn kind_of(name: &str) -> Kind {
    let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default();
    match ext.as_str() {
        "png" | "jpg" | "jpeg" | "gif" | "webp" | "bmp" => Kind::Image,
        "mp4" | "mkv" | "webm" | "mov" | "avi" | "m4v" => Kind::Video,
        "mp3" | "flac" | "ogg" | "opus" | "wav" | "m4a" | "aac" => Kind::Audio,
        "txt" | "md" | "rs" | "toml" | "json" | "yaml" | "yml" | "sh" | "py" | "js" | "ts" | "c" | "h" | "cpp" | "go" | "html" | "css" | "log"
        | "conf" | "ini" | "lock" | "xml" | "csv" => Kind::Text,
        _ if !name.contains('.') || name.starts_with('.') && !name[1..].contains('.') => Kind::Text,
        _ => Kind::Other,
    }
}

/// The small type badge on a grid tile or carousel item (docs/modes.md).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Badge {
    Folder,
    Image,
    Video,
    Audio,
    Text,
    Code,
    Markdown,
    Pdf,
    Archive,
    Binary,
    Config,
    Font,
    Document,
    Generic,
}

impl Badge {
    pub const ALL: [Badge; 14] = [
        Badge::Folder,
        Badge::Image,
        Badge::Video,
        Badge::Audio,
        Badge::Text,
        Badge::Code,
        Badge::Markdown,
        Badge::Pdf,
        Badge::Archive,
        Badge::Binary,
        Badge::Config,
        Badge::Font,
        Badge::Document,
        Badge::Generic,
    ];

    /// The short mark drawn on the badge (at most 3 characters; the folder
    /// is drawn as a shape instead).
    pub fn mark(self) -> &'static str {
        match self {
            Badge::Folder => "",
            Badge::Image => "IMG",
            Badge::Video => "VID",
            Badge::Audio => "AUD",
            Badge::Text => "TXT",
            Badge::Code => "</>",
            Badge::Markdown => "MD",
            Badge::Pdf => "PDF",
            Badge::Archive => "ZIP",
            Badge::Binary => "BIN",
            Badge::Config => "{}",
            Badge::Font => "Aa",
            Badge::Document => "DOC",
            Badge::Generic => "…",
        }
    }

    /// Badge colour (0xRRGGBB), one per type.
    pub fn color(self) -> u32 {
        match self {
            Badge::Folder => 0x4F9DDE,
            Badge::Image => 0x3FB27F,
            Badge::Video => 0xE0566B,
            Badge::Audio => 0xB46EE0,
            Badge::Text => 0x8A96A3,
            Badge::Code => 0x2FB8C9,
            Badge::Markdown => 0x5B7BE0,
            Badge::Pdf => 0xD9443A,
            Badge::Archive => 0xC9902B,
            Badge::Binary => 0x6B7280,
            Badge::Config => 0xE0A93A,
            Badge::Font => 0xD0679E,
            Badge::Document => 0x3A7BD5,
            Badge::Generic => 0x7C8794,
        }
    }

    pub fn index(self) -> u8 {
        Badge::ALL.iter().position(|b| *b == self).unwrap_or(13) as u8
    }

    pub fn from_index(i: u8) -> Badge {
        Badge::ALL.get(i as usize).copied().unwrap_or(Badge::Generic)
    }
}

/// The badge for an entry: from its extension (the same names [`kind_of`]
/// knows, plus documents, archives, fonts, PDFs), else its kind; files with
/// an execute bit and no known type are binaries.
pub fn badge_of(name: &str, kind: Kind, mode: &str) -> Badge {
    if kind == Kind::Dir {
        return Badge::Folder;
    }
    let ext = name.rsplit_once('.').map(|(_, e)| e.to_ascii_lowercase()).unwrap_or_default();
    let by_ext = match ext.as_str() {
        "md" | "markdown" => Some(Badge::Markdown),
        "pdf" => Some(Badge::Pdf),
        "zip" | "tar" | "gz" | "tgz" | "xz" | "zst" | "bz2" | "7z" | "rar" | "deb" | "rpm" => Some(Badge::Archive),
        "json" | "toml" | "yaml" | "yml" | "ini" | "conf" | "cfg" | "lock" | "xml" | "env" => Some(Badge::Config),
        "ttf" | "otf" | "woff" | "woff2" => Some(Badge::Font),
        "doc" | "docx" | "odt" | "rtf" | "xls" | "xlsx" | "ods" | "csv" | "ppt" | "pptx" | "odp" => Some(Badge::Document),
        "rs" | "sh" | "py" | "js" | "ts" | "c" | "h" | "cpp" | "go" | "html" | "css" | "java" | "rb" | "lua" | "zig" | "swift" | "kt" => {
            Some(Badge::Code)
        }
        "exe" | "dll" | "so" | "dylib" | "bin" | "o" | "a" | "wasm" => Some(Badge::Binary),
        _ => None,
    };
    if let Some(b) = by_ext {
        return b;
    }
    let exec = mode.len() == 10 && mode[1..].contains('x');
    match kind {
        Kind::Image => Badge::Image,
        Kind::Video => Badge::Video,
        Kind::Audio => Badge::Audio,
        _ if exec => Badge::Binary,
        Kind::Text => Badge::Text,
        _ => Badge::Generic,
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Entry {
    pub name: String,
    pub path: PathBuf,
    pub kind: Kind,
    /// `ls -l` style, e.g. `drwxr-xr-x`.
    pub mode: String,
    pub size: u64,
    pub modified: Option<SystemTime>,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Sort {
    #[default]
    Name,
    Modified,
    Size,
}

/// `ls` flags: `-a`, `-h`, sort. Default `-lah` (all, human sizes).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Flags {
    pub all: bool,
    pub human: bool,
    pub sort: Sort,
    pub reverse: bool,
}

impl Default for Flags {
    fn default() -> Self {
        Self { all: true, human: true, sort: Sort::Name, reverse: false }
    }
}

impl Flags {
    /// The equivalent `ls` options, e.g. `-lah`.
    pub fn ls(&self) -> String {
        let mut s = String::from("-l");
        if self.all {
            s.push('a');
        }
        if self.human {
            s.push('h');
        }
        match self.sort {
            Sort::Name => {}
            Sort::Modified => s.push('t'),
            Sort::Size => s.push('S'),
        }
        if self.reverse {
            s.push('r');
        }
        s
    }
}

#[cfg(unix)]
pub fn mode_string(m: &std::fs::Metadata) -> String {
    use std::os::unix::fs::PermissionsExt;
    let p = m.permissions().mode();
    let t = if m.file_type().is_symlink() {
        'l'
    } else if m.is_dir() {
        'd'
    } else {
        '-'
    };
    let mut s = String::from(t);
    for (i, c) in "rwxrwxrwx".chars().enumerate() {
        s.push(if p & (1 << (8 - i)) != 0 { c } else { '-' });
    }
    s
}

#[cfg(not(unix))]
pub fn mode_string(m: &std::fs::Metadata) -> String {
    let d = if m.is_dir() { 'd' } else { '-' };
    let w = if m.permissions().readonly() { '-' } else { 'w' };
    format!("{d}r{w}-r--r--")
}

fn entry(name: String, path: PathBuf) -> Entry {
    let meta = std::fs::symlink_metadata(&path).ok();
    let target_dir = std::fs::metadata(&path).is_ok_and(|m| m.is_dir());
    let kind = if target_dir { Kind::Dir } else { kind_of(&name) };
    Entry {
        mode: meta.as_ref().map(mode_string).unwrap_or_else(|| "?---------".into()),
        size: meta.as_ref().map_or(0, |m| m.len()),
        modified: meta.as_ref().and_then(|m| m.modified().ok()),
        name,
        path,
        kind,
    }
}

/// The directory's entries like `ls` with `flags`. `.` and `..` are never
/// listed: going up is the back control (alt+p, alt+Backspace, the header).
pub fn list_dir(dir: &Path, flags: &Flags) -> std::io::Result<Vec<Entry>> {
    let v: Vec<Entry> = std::fs::read_dir(dir)?.flatten().map(|e| entry(e.file_name().to_string_lossy().into_owned(), e.path())).collect();
    Ok(arrange(v, flags))
}

/// Dotfiles (unless `-a`), sort and reverse, like `ls`.
pub fn arrange(v: Vec<Entry>, flags: &Flags) -> Vec<Entry> {
    let mut v: Vec<Entry> = v.into_iter().filter(|e| flags.all || !e.name.starts_with('.')).filter(|e| e.name != "." && e.name != "..").collect();
    match flags.sort {
        Sort::Name => v.sort_by_key(|e| e.name.to_lowercase()),
        Sort::Modified => v.sort_by_key(|e| std::cmp::Reverse(e.modified)),
        Sort::Size => v.sort_by_key(|e| std::cmp::Reverse(e.size)),
    }
    if flags.reverse {
        v.reverse();
    }
    v
}

/// `ls -h` size.
pub fn human_size(n: u64) -> String {
    let units = ["", "K", "M", "G", "T"];
    let mut v = n as f64;
    let mut i = 0;
    while v >= 1024.0 && i < units.len() - 1 {
        v /= 1024.0;
        i += 1;
    }
    if i == 0 {
        n.to_string()
    } else if v < 10.0 {
        format!("{v:.1}{}", units[i])
    } else {
        format!("{v:.0}{}", units[i])
    }
}

/// `Oct 31 02:02` in local time.
pub fn format_time(t: SystemTime) -> String {
    let secs = t.duration_since(SystemTime::UNIX_EPOCH).map_or(0, |d| d.as_secs() as i64);
    let (mon, day, h, m) = local_parts(secs);
    const M: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    format!("{} {day:2} {h:02}:{m:02}", M[mon.min(11)])
}

#[cfg(unix)]
fn local_parts(secs: i64) -> (usize, u32, u32, u32) {
    // SAFETY: localtime_r writes only into `tm`.
    unsafe {
        let t = secs as libc::time_t;
        let mut tm: libc::tm = std::mem::zeroed();
        libc::localtime_r(&t, &mut tm);
        (tm.tm_mon as usize, tm.tm_mday as u32, tm.tm_hour as u32, tm.tm_min as u32)
    }
}

#[cfg(not(unix))]
fn local_parts(secs: i64) -> (usize, u32, u32, u32) {
    let dt = time::OffsetDateTime::from_unix_timestamp(secs).unwrap_or(time::OffsetDateTime::UNIX_EPOCH);
    (u8::from(dt.month()) as usize - 1, dt.day() as u32, dt.hour() as u32, dt.minute() as u32)
}

/// List / grid / carousel (mouser-views, shared with other modes).
pub use mouser_views::Layout as View;

/// Grid tile sizes (larger tiles: fewer per row).
pub const TILE_SIZES: [i32; 4] = [96, 128, 176, 240];

/// Commander's actions; each is a [`crate::modes::Binding`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Action {
    SwitchView,
    Search,
    Up,
    Down,
    Left,
    Right,
    Open,
    Bigger,
    Smaller,
    Hidden,
    Options,
    Man,
    PageUp,
    PageDown,
    First,
    Last,
    Parent,
    Close,
    Mark,
    MarkAll,
    Pipe,
}

/// Default bindings: plain keys, live only while commander has the keyboard
/// (the focus toggle, `mouser_core::modes::DEFAULT_FOCUS_KEY`); otherwise every
/// key goes to the shell. Remap them in `modes.toml`.
pub const BINDINGS: &[crate::modes::Binding] = &[
    b("switch_view", "v", "switch view (list / grid / carousel)"),
    b("search", "/", "search this folder"),
    b("sync", "s", "sync: move the shell to commander's folder (silently, at its next prompt if busy)"),
    b("up", "up", "previous row"),
    b("down", "down", "next row"),
    b("left", "left", "previous item"),
    b("right", "right", "next item"),
    b("open", "enter", "open (folder: cd into it; file: full-width view)"),
    b("bigger", "z", "larger grid tiles"),
    b("smaller", "x", "smaller grid tiles"),
    b("hidden", "h", "show / hide dotfiles (ls -a)"),
    b("options", "o", "options window"),
    b("man", "m", "manual for commander mode"),
    b("page_up", "pageup", "page up"),
    b("page_down", "pagedown", "page down"),
    b("first", "home", "first item"),
    b("last", "end", "last item"),
    b("parent", "u", "back: where you came from, else the parent folder"),
    b("back", "backspace", "back: where you came from, else the parent folder"),
    b("close", "q", "close the file view / window"),
    b("mark", "space", "mark / unmark the item (for pipe)"),
    b("mark_all", "*", "mark all / clear marks"),
    b("pipe", "|", "pipe the marked (or selected) paths into a command"),
    b("play_pause", "k", "player: play / pause"),
    b("seek_back", "j", "player: back 10 s"),
    b("seek_forward", "l", "player: forward 10 s"),
    b("volume_down", "-", "player: volume down"),
    b("volume_up", "=", "player: volume up"),
    b("zoom_in", "=", "image view: zoom in (same key as volume up in the player)"),
    b("zoom_out", "-", "image view: zoom out (same key as volume down in the player)"),
    b("zoom_fit", "0", "image view: fit"),
    b("zoom_actual", "1", "image view: 100% (actual pixels)"),
    b(
        "fullscreen",
        "f",
        "image / player: fullscreen, the whole window; eases from the thumbnail (Esc or the same key leaves; appearance.reduce_motion skips the motion)",
    ),
    b("menu", "i", "header overflow menu (\u{2022}\u{2022}\u{2022}) when the window is narrow"),
    // Views: each one directly (v cycles them).
    b("view_list", "L", "list view"),
    b("view_grid", "G", "grid view"),
    b("view_carousel", "C", "carousel view"),
    // Every other option (the context menu's too) has a key.
    b("open_fullscreen", "O", "open: play / view fullscreen"),
    b("sync_item", "e", "sync the shell into the selected folder"),
    b("copy", "y", "copy the marked (or selected) items, to paste in another folder"),
    b("paste", "p", "paste the copied items here (into the selected folder when on one)"),
    b("copy_to", "c", "copy to\u{2026} (asks where; Tab completes)"),
    b("move_to", "M", "move to\u{2026} (asks where; Tab completes)"),
    b("rename", "r", "rename\u{2026} (Tab completes)"),
    b("delete", "d", "delete\u{2026} (asks first)"),
    b("new_folder", "n", "new folder\u{2026} (Tab completes)"),
    b("copy_path", "Y", "copy the path to the clipboard"),
    b("copy_text", "T", "text view: copy the text"),
    b("sort_name", "N", "sort by name"),
    b("sort_modified", "D", "sort by modified (date)"),
    b("sort_size", "S", "sort by size"),
    b("reverse", "R", "reverse the order"),
    // Keyboard help: every key and what it does (this table, live).
    b("keys", "?", "keyboard help: all keys and what they do"),
    b("help", "f1", "keyboard help (same as ?)"),
];

const fn b(id: &'static str, key: &'static str, describe: &'static str) -> crate::modes::Binding {
    crate::modes::Binding { id, key, describe }
}

impl Action {
    pub fn from_id(id: &str) -> Option<Self> {
        Some(match id {
            "switch_view" => Action::SwitchView,
            "search" => Action::Search,
            "up" => Action::Up,
            "down" => Action::Down,
            "left" => Action::Left,
            "right" => Action::Right,
            "open" => Action::Open,
            "bigger" => Action::Bigger,
            "smaller" => Action::Smaller,
            "hidden" => Action::Hidden,
            "options" => Action::Options,
            "man" => Action::Man,
            "page_up" => Action::PageUp,
            "page_down" => Action::PageDown,
            "first" => Action::First,
            "last" => Action::Last,
            "parent" | "back" => Action::Parent,
            "close" => Action::Close,
            "mark" => Action::Mark,
            "mark_all" => Action::MarkAll,
            "pipe" => Action::Pipe,
            _ => return None,
        })
    }
}

/// Floating windows of the mode.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Overlay {
    Options,
    Man,
    /// Full-width view of a file.
    Preview(PathBuf),
}

/// What an action asks the app to do beyond changing the model.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Effect {
    None,
    /// Type `cd -- <path>` into the shell.
    Cd(PathBuf),
    /// Hand a file to the desktop's player/opener (video, audio).
    External(PathBuf),
    /// Run this command line in the shell, keeping what is typed (pipe).
    Run(String),
}

/// A place on the navigation stack: the folder as the user saw it (the
/// logical path, symlinks kept), with the selection and scroll there.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Place {
    pub path: PathBuf,
    pub selected: usize,
    pub selected_name: Option<String>,
    pub scroll: usize,
}

#[derive(Debug, Default)]
pub struct Commander {
    /// pushd/popd-style history: entering a folder or file pushes where you
    /// were; back pops it and restores it exactly (docs/usage.md).
    pub nav: Vec<Place>,
    /// Where a `cd` this mode asked for is going (logical path), and the
    /// place to restore when it arrives (back).
    pending: Option<(PathBuf, Option<Place>)>,
    pub view: View,
    /// Index into [`TILE_SIZES`].
    pub tile: usize,
    pub flags: Flags,
    pub cwd: Option<PathBuf>,
    pub entries: Vec<Entry>,
    stamp: Option<(PathBuf, Option<SystemTime>, Flags)>,
    pub error: Option<String>,
    pub filter: String,
    pub searching: bool,
    /// Index into [`Commander::visible`].
    pub selected: usize,
    /// First list row shown.
    pub scroll: usize,
    pub overlay: Option<Overlay>,
    /// Scroll of the man page / text preview.
    pub overlay_scroll: usize,
    /// Items per page (set by the view each frame).
    pub page: usize,
    /// Marked paths (multi-select for pipe).
    pub marks: std::collections::BTreeSet<PathBuf>,
    /// The pipe prompt has focus; its text.
    pub piping: bool,
    pub pipe_cmd: String,
    /// `user@host` while the shell is on another machine (entries are remote
    /// paths; files are not read locally).
    pub remote: Option<String>,
    /// A one-line message in the header (e.g. why a remote file did not open).
    pub notice: Option<String>,
    /// The remote listing as received (re-arranged when the flags change).
    remote_raw: Vec<Entry>,
}

impl Commander {
    pub fn new() -> Self {
        Self { tile: 1, ..Default::default() }
    }

    /// Leaving the mode: back to a plain state (the directory is kept).
    pub fn reset(&mut self) {
        self.searching = false;
        self.filter.clear();
        self.overlay = None;
        self.overlay_scroll = 0;
        self.piping = false;
        self.pipe_cmd.clear();
    }

    /// Follow the shell to `dir`; re-list when it, its mtime or the flags change.
    pub fn set_cwd(&mut self, dir: Option<PathBuf>) {
        let Some(dir) = dir else { return };
        let dir = self.logical(dir, false);
        let mtime = std::fs::metadata(&dir).and_then(|m| m.modified()).ok();
        let stamp = (dir.clone(), mtime, self.flags);
        if self.remote.is_some() {
            self.remote = None;
            self.stamp = None;
        }
        if self.stamp.as_ref() == Some(&stamp) {
            return;
        }
        let listing = list_dir(&dir, &self.flags).map_err(|e| format!("{}: {e}", dir.display()));
        self.load(dir, listing);
        self.stamp = Some(stamp);
    }

    /// The shell is on `label` (user@host) in `dir` (`None`: unknown), with
    /// this listing (`None`: still loading, `Some(Err)`: failed). `.` and `..`
    /// are dropped; the flags (`-a`, sort, reverse) apply as locally.
    pub fn set_remote(&mut self, label: String, dir: Option<PathBuf>, listing: Option<Result<Vec<Entry>, String>>) {
        let label_changed = self.remote.as_ref() != Some(&label);
        self.remote = Some(label.clone());
        self.stamp = None;
        let Some(dir) = dir else {
            self.entries.clear();
            if label_changed || self.cwd.is_some() {
                self.marks.clear();
                self.selected = 0;
            }
            self.cwd = None;
            self.error = Some(format!(
                "remote ({label}): no directory info. The remote shell does not report its folder (OSC 7) or there is no ssh side channel; see docs/modes.md"
            ));
            return;
        };
        let listing = match listing {
            Some(r) => r.map(|v| {
                self.remote_raw = v.clone();
                arrange(v, &self.flags)
            }),
            None if self.cwd.as_ref() == Some(&dir) && self.error.is_none() && !label_changed => return,
            None => Ok(Vec::new()),
        };
        let dir = self.logical(dir, true);
        self.load(dir, listing);
    }

    /// The folder the shell reports, as the user sees it. A `cd` this mode
    /// asked for keeps its logical path (a symlink stays a symlink) even when
    /// the shell reports the resolved one; the same folder reported again keeps
    /// the current logical path; anywhere else (a typed `cd`) starts a new
    /// history.
    fn logical(&mut self, reported: PathBuf, remote: bool) -> PathBuf {
        let same =
            |a: &Path, b: &Path| a == b || (!remote && std::fs::canonicalize(a).ok().is_some_and(|x| std::fs::canonicalize(b).ok() == Some(x)));
        if let Some((want, _)) = &self.pending {
            if same(want, &reported) {
                return want.clone();
            }
            // Still on the old folder (the cd hasn't landed yet).
            if self.cwd.as_ref().is_some_and(|c| same(c, &reported)) {
                return self.cwd.clone().unwrap_or(reported);
            }
            self.pending = None;
        }
        if let Some(c) = &self.cwd
            && same(c, &reported)
        {
            return c.clone();
        }
        if self.cwd.is_some() {
            self.nav.clear();
        }
        reported
    }

    fn here(&self) -> Option<Place> {
        let path = self.cwd.clone()?;
        Some(Place { path, selected: self.selected, selected_name: self.selected_entry().map(|e| e.name.clone()), scroll: self.scroll })
    }

    /// `cd` to `dir` (logical) from this mode, remembering the place to restore.
    fn go(&mut self, dir: PathBuf, restore: Option<Place>) -> Effect {
        self.pending = Some((dir.clone(), restore));
        Effect::Cd(dir)
    }

    /// Back: pop the stack (the exact place you came from), else the parent of
    /// the logical path. The file view closes first (see the view).
    pub fn back(&mut self) -> Effect {
        if let Some(p) = self.nav.pop() {
            if self.cwd.as_ref() == Some(&p.path) {
                // Leaving a file: same folder, restore the selection.
                self.restore(&p);
                return Effect::None;
            }
            let path = p.path.clone();
            return self.go(path, Some(p));
        }
        match self.cwd.as_ref().and_then(|d| d.parent()) {
            Some(p) => {
                let p = p.to_path_buf();
                self.go(p, None)
            }
            None => Effect::None,
        }
    }

    /// The file view closed by back: drop the place its opening pushed (the
    /// same folder) and restore the selection there.
    pub fn close_file(&mut self) {
        if let Some(p) = self.nav.last().cloned()
            && self.cwd.as_ref() == Some(&p.path)
        {
            self.nav.pop();
            self.restore(&p);
        }
    }

    /// A jump that isn't a step (a path typed in the breadcrumb, a search
    /// result, a bookmark): a new history.
    pub fn jump(&mut self, dir: PathBuf) -> Effect {
        self.nav.clear();
        self.go(dir, None)
    }

    fn restore(&mut self, p: &Place) {
        self.selected = p.selected_name.as_ref().and_then(|n| self.visible().iter().position(|e| &e.name == n)).unwrap_or(p.selected);
        self.scroll = p.scroll;
        self.clamp();
    }

    /// List again after the flags changed (local: re-read; remote: re-sort).
    pub fn relist(&mut self) {
        if self.remote.is_some() {
            if let Some(d) = self.cwd.clone()
                && self.error.is_none()
            {
                let v = arrange(self.remote_raw.clone(), &self.flags);
                self.load(d, Ok(v));
            }
        } else {
            let d = self.cwd.clone();
            self.set_cwd(d);
        }
    }

    fn load(&mut self, dir: PathBuf, listing: Result<Vec<Entry>, String>) {
        let came_from =
            self.cwd.as_ref().filter(|old| **old != dir).and_then(|old| {
                old.strip_prefix(&dir).ok().and_then(|r| r.components().next()).map(|c| c.as_os_str().to_string_lossy().into_owned())
            });
        if self.cwd.as_ref() != Some(&dir) {
            self.selected = 0;
            self.scroll = 0;
            self.filter.clear();
            self.marks.clear();
        }
        match listing {
            Ok(v) => {
                self.entries = v;
                self.error = None;
            }
            Err(e) => {
                self.entries.clear();
                self.error = Some(e);
            }
        }
        // Going up selects the folder you came from.
        if let Some(name) = came_from
            && let Some(i) = self.visible().iter().position(|e| e.name == name)
        {
            self.selected = i;
        }
        let arrived = self.pending.as_ref().is_some_and(|(w, _)| *w == dir);
        self.cwd = Some(dir);
        self.clamp();
        if arrived && let Some((_, Some(p))) = self.pending.take() {
            self.restore(&p);
        }
    }

    /// Entries matching the search (case-insensitive substring).
    pub fn visible(&self) -> Vec<&Entry> {
        let f = self.filter.to_lowercase();
        self.entries.iter().filter(|e| f.is_empty() || e.name.to_lowercase().contains(&f)).collect()
    }

    fn clamp(&mut self) {
        let n = self.visible().len();
        self.selected = self.selected.min(n.saturating_sub(1));
    }

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

    /// Keep the selected list row inside `rows` visible rows.
    pub fn follow(&mut self, rows: usize) {
        let rows = rows.max(1);
        if self.selected < self.scroll {
            self.scroll = self.selected;
        } else if self.selected >= self.scroll + rows {
            self.scroll = self.selected + 1 - rows;
        }
    }

    /// Typed text while the pipe prompt has focus: Enter runs, Esc cancels.
    pub fn pipe_key(&mut self, bytes: &[u8]) -> Option<Effect> {
        if !self.piping {
            return None;
        }
        match bytes {
            b"\r" => {
                self.piping = false;
                let cmd = std::mem::take(&mut self.pipe_cmd);
                if cmd.trim().is_empty() {
                    return Some(Effect::None);
                }
                return Some(Effect::Run(pipe_line(&self.pipe_paths(), &cmd)));
            }
            b"\x1b" => {
                self.piping = false;
                self.pipe_cmd.clear();
            }
            b"\x7f" | b"\x08" => {
                self.pipe_cmd.pop();
            }
            _ => {
                if let Ok(t) = std::str::from_utf8(bytes)
                    && !t.chars().any(char::is_control)
                {
                    self.pipe_cmd.push_str(t);
                }
            }
        }
        Some(Effect::None)
    }

    /// Marked paths in listing order, else the selected one.
    pub fn pipe_paths(&self) -> Vec<PathBuf> {
        if self.marks.is_empty() {
            self.selected_entry().map(|e| e.path.clone()).into_iter().collect()
        } else {
            let v: Vec<PathBuf> = self.entries.iter().filter(|e| self.marks.contains(&e.path)).map(|e| e.path.clone()).collect();
            v
        }
    }

    /// Typed text while the search field has focus; false when not searching.
    pub fn search_key(&mut self, bytes: &[u8]) -> bool {
        if !self.searching {
            return false;
        }
        match bytes {
            b"\r" | b"\x1b" => self.searching = false,
            b"\x7f" | b"\x08" => {
                self.filter.pop();
            }
            _ => {
                if let Ok(s) = std::str::from_utf8(bytes)
                    && !s.starts_with('\x1b')
                    && !s.chars().any(char::is_control)
                {
                    self.filter.push_str(s);
                    self.selected = 0;
                    self.scroll = 0;
                }
            }
        }
        self.clamp();
        true
    }

    /// Do `a`; `per_row` is the grid's items per row (1 in the list).
    pub fn apply(&mut self, a: Action, per_row: usize) -> Effect {
        self.notice = None;
        let n = self.visible().len();
        let per_row = if self.view == View::Grid { per_row.max(1) } else { 1 };
        match a {
            Action::SwitchView => self.view = self.view.next(),
            Action::Search => self.searching = !self.searching,
            Action::Up => self.selected = self.selected.saturating_sub(per_row),
            Action::Down => {
                if self.selected + per_row < n {
                    self.selected += per_row
                }
            }
            Action::Left => self.selected = self.selected.saturating_sub(1),
            Action::Right => self.selected = (self.selected + 1).min(n.saturating_sub(1)),
            Action::Bigger => self.tile = (self.tile + 1).min(TILE_SIZES.len() - 1),
            Action::Smaller => self.tile = self.tile.saturating_sub(1),
            Action::Hidden => self.flags.all = !self.flags.all,
            Action::Options => self.overlay = if self.overlay == Some(Overlay::Options) { None } else { Some(Overlay::Options) },
            Action::Man => {
                self.overlay = if self.overlay == Some(Overlay::Man) { None } else { Some(Overlay::Man) };
                self.overlay_scroll = 0;
            }
            Action::Open => return self.open_selected(),
            Action::PageUp => self.selected = self.selected.saturating_sub(self.page.max(1)),
            Action::PageDown => self.selected = (self.selected + self.page.max(1)).min(n.saturating_sub(1)),
            Action::First => self.selected = 0,
            Action::Last => self.selected = n.saturating_sub(1),
            Action::Parent => return self.back(),
            Action::Close => {
                self.overlay = None;
                self.piping = false;
            }
            Action::Mark => {
                if let Some(e) = self.selected_entry().map(|e| e.path.clone())
                    && !self.marks.remove(&e)
                {
                    self.marks.insert(e);
                }
                if self.view != View::Grid || per_row == 1 {
                    self.selected = (self.selected + 1).min(n.saturating_sub(1));
                }
            }
            Action::MarkAll => {
                if self.marks.is_empty() {
                    let all: Vec<PathBuf> = self.visible().iter().map(|e| e.path.clone()).collect();
                    self.marks.extend(all);
                } else {
                    self.marks.clear();
                }
            }
            Action::Pipe => {
                self.piping = !self.piping;
                self.searching = false;
            }
        }
        self.clamp();
        Effect::None
    }

    pub fn open_selected(&mut self) -> Effect {
        let Some(e) = self.selected_entry().cloned() else { return Effect::None };
        let here = self.here();
        self.nav.extend(here);
        match e.kind {
            Kind::Dir => self.go(e.path, None),
            // Remote files open like local ones (fetched by `fetch`).
            Kind::Video | Kind::Audio => Effect::External(e.path),
            _ => {
                self.overlay = Some(Overlay::Preview(e.path));
                self.overlay_scroll = 0;
                Effect::None
            }
        }
    }

    /// Items whose previews should be loaded now: the visible grid tiles, or
    /// the carousel's three (focused + its two neighbours). Everything else
    /// is not loaded.
    pub fn wanted_previews(&self, first: usize, count: usize) -> Vec<PathBuf> {
        let vis = self.visible();
        let range = match self.view {
            View::List => 0..0,
            View::Grid => first.min(vis.len())..(first + count).min(vis.len()),
            View::Carousel => self.selected.saturating_sub(1)..(self.selected + 2).min(vis.len()),
        };
        vis[range].iter().filter(|e| e.kind == Kind::Image).map(|e| e.path.clone()).collect()
    }
}

/// POSIX single-quoting (`'` becomes `'\\''`).
pub fn shell_quote(s: &str) -> String {
    format!("'{}'", s.replace('\'', "'\\''"))
}

/// `printf '%s\n' 'a' 'b' | cmd` (run with [`crate::modes::keep_line`]).
pub fn pipe_line(paths: &[PathBuf], cmd: &str) -> String {
    let args: Vec<String> = paths.iter().map(|p| shell_quote(&p.to_string_lossy())).collect();
    format!("printf '%s\\n' {} | {}", args.join(" "), cmd.trim())
}

/// The manual shown by the mode's `man` button.
pub fn manual(k: &crate::modes::Keymap) -> Vec<String> {
    let mut v = vec![
        "COMMANDER MODE (the default mode)".to_string(),
        String::new(),
        "Shows the shell's working directory above the prompt and follows every cd.".into(),
        "It takes no key from the shell: type commands as usual. ctrl+alt+k (the".into(),
        "focus toggle) or a click gives commander the keyboard; then the plain keys".into(),
        "below work and nothing typed reaches the shell. Esc, q with nothing open,".into(),
        "or the toggle again give the keyboard back. esc : c turns modes off / on.".into(),
        String::new(),
        "KEYS (while commander has the keyboard)".into(),
    ];
    for (id, _, d) in &k.keys {
        v.push(format!("  {:<12} {d}", k.label(id)));
    }
    v.extend([
        String::new(),
        "  ? or F1      keyboard help: every key, live from this table".into(),
        "  ctrl+shift+k the same window from anywhere     ctrl+shift+m  modes".into(),
        String::new(),
        "REMAPPING".into(),
        format!("  {}:", crate::modes::modes_path().display()),
        "    [focus]".into(),
        "    key = \"ctrl+alt+k\"   # alt+<key> or ctrl+alt+<letter>".into(),
        "    [commander.keys]".into(),
        "    switch_view = \"t\"".into(),
        "  On Windows Ctrl+Alt is AltGr: remap the toggle if AltGr+K types a".into(),
        "  character on your layout.".into(),
    ]);
    v
}

/// A text file for the full-width view: up to 5000 lines of the first
/// 1 MiB; `(lines, error)`.
/// Lines of `b` for the file view (`more`: there is more after it).
pub fn text_from_bytes(b: &[u8], more: bool, name: &str) -> (Vec<String>, Option<String>) {
    if b.contains(&0) {
        return (Vec::new(), Some(format!("{name}: binary file")));
    }
    let mut v: Vec<String> = String::from_utf8_lossy(b).lines().take(5000).map(String::from).collect();
    if more || v.len() == 5000 {
        v.push("[…]".into());
    }
    (v, None)
}

pub fn text_preview(p: &Path) -> (Vec<String>, Option<String>) {
    const MAX: u64 = 1 << 20;
    let read = std::fs::File::open(p).and_then(|f| {
        let mut b = Vec::new();
        std::io::Read::read_to_end(&mut std::io::Read::take(f, MAX), &mut b)?;
        Ok(b)
    });
    match read {
        Ok(b) if b.contains(&0) => (Vec::new(), Some(format!("{}: binary file", p.display()))),
        Ok(b) => {
            let mut v: Vec<String> = String::from_utf8_lossy(&b).lines().take(5000).map(String::from).collect();
            if b.len() as u64 >= MAX || v.len() == 5000 {
                v.push("[…]".into());
            }
            (v, None)
        }
        Err(e) => (Vec::new(), Some(format!("{}: {e}", p.display()))),
    }
}

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

    pub(super) fn tree() -> tempfile::TempDir {
        let t = tempfile::tempdir().unwrap();
        std::fs::create_dir(t.path().join("sub")).unwrap();
        std::fs::write(t.path().join("b.png"), b"x").unwrap();
        std::fs::write(t.path().join("a.txt"), b"hello").unwrap();
        std::fs::write(t.path().join(".hidden"), b"").unwrap();
        std::fs::write(t.path().join("clip.mp4"), vec![0; 3000]).unwrap();
        t
    }

    #[test]
    fn lists_like_ls_lah() {
        let t = tree();
        let v = list_dir(t.path(), &Flags::default()).unwrap();
        let names: Vec<_> = v.iter().map(|e| e.name.as_str()).collect();
        assert_eq!(names, [".hidden", "a.txt", "b.png", "clip.mp4", "sub"], "no . or .. even with -a");
        assert_eq!(v[4].kind, Kind::Dir);
        assert!(v[4].mode.starts_with('d'));
        assert_eq!((v[2].kind, v[3].kind, v[1].kind), (Kind::Image, Kind::Video, Kind::Text));
        let no_dot = list_dir(t.path(), &Flags { all: false, ..Default::default() }).unwrap();
        assert!(no_dot.iter().all(|e| !e.name.starts_with('.')));
        let by_size = list_dir(t.path(), &Flags { all: false, sort: Sort::Size, ..Default::default() }).unwrap();
        assert_eq!(by_size.iter().find(|e| e.kind != Kind::Dir).unwrap().name, "clip.mp4");
        assert_eq!(Flags::default().ls(), "-lah");
        assert_eq!(human_size(1536), "1.5K");
        assert_eq!(human_size(900), "900");
        assert_eq!(format_time(SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(86400 * 40)).len(), 12);
    }

    #[test]
    fn follows_cwd_search_and_navigation() {
        let t = tree();
        let mut c = Commander::new();
        c.set_cwd(Some(t.path().to_path_buf()));
        assert_eq!(c.visible().len(), 5);
        c.searching = true;
        for b in [&b"p"[..], b"n", b"g"] {
            assert!(c.search_key(b));
        }
        assert_eq!(c.visible().iter().map(|e| e.name.as_str()).collect::<Vec<_>>(), ["b.png"]);
        c.search_key(b"\x7f");
        c.search_key(b"\x7f");
        assert_eq!(c.filter, "p");
        c.search_key(b"\r");
        assert!(!c.searching && !c.search_key(b"q"));
        c.filter.clear();
        c.apply(Action::Down, 1);
        assert_eq!(c.selected, 1);
        c.view = View::Grid;
        c.apply(Action::Down, 3);
        assert_eq!(c.selected, 4);
        c.apply(Action::Down, 3);
        assert_eq!(c.selected, 4, "no row below");
        c.apply(Action::Up, 3);
        assert_eq!(c.selected, 1);
        c.apply(Action::SwitchView, 1);
        assert_eq!(c.view, View::Carousel);
        c.apply(Action::SwitchView, 1);
        assert_eq!(c.view, View::List);
        // A new directory re-lists and resets the selection.
        c.set_cwd(Some(t.path().join("sub")));
        assert_eq!((c.selected, c.visible().len()), (0, 0), "empty folder: no . or ..");
        std::fs::write(t.path().join("sub/.dot"), b"").unwrap();
        // Filesystems with coarse timestamps may keep the folder's mtime:
        // move it on, as a later change would.
        #[cfg(unix)]
        std::fs::File::open(t.path().join("sub")).unwrap().set_modified(SystemTime::now() + std::time::Duration::from_secs(2)).unwrap();
        c.set_cwd(Some(t.path().join("sub")));
        assert_eq!(c.visible().len(), 1);
        c.apply(Action::Hidden, 1);
        c.set_cwd(Some(t.path().join("sub")));
        assert_eq!(c.visible().len(), 0);
    }

    #[test]
    fn open_by_kind() {
        let t = tree();
        let mut c = Commander::new();
        c.set_cwd(Some(t.path().to_path_buf()));
        let at = |c: &Commander, n: &str| c.visible().iter().position(|e| e.name == n).unwrap();
        c.selected = at(&c, "sub");
        assert_eq!(c.apply(Action::Open, 1), Effect::Cd(t.path().join("sub")));
        c.selected = at(&c, "clip.mp4");
        assert_eq!(c.apply(Action::Open, 1), Effect::External(t.path().join("clip.mp4")));
        c.selected = at(&c, "b.png");
        assert_eq!(c.apply(Action::Open, 1), Effect::None);
        assert_eq!(c.overlay, Some(Overlay::Preview(t.path().join("b.png"))));
    }

    #[test]
    fn previews_only_for_what_is_visible() {
        let t = tempfile::tempdir().unwrap();
        for i in 0..10 {
            std::fs::write(t.path().join(format!("p{i}.png")), b"x").unwrap();
        }
        let mut c = Commander::new();
        c.flags.all = false;
        c.set_cwd(Some(t.path().to_path_buf()));
        assert!(c.wanted_previews(0, 10).is_empty(), "list view loads none");
        c.view = View::Grid;
        let w = c.wanted_previews(4, 3);
        assert_eq!(w, (4..7).map(|i| t.path().join(format!("p{i}.png"))).collect::<Vec<_>>());
        c.view = View::Carousel;
        c.selected = 5;
        assert_eq!(c.wanted_previews(0, 99), (4..7).map(|i| t.path().join(format!("p{i}.png"))).collect::<Vec<_>>(), "focused + two neighbours");
        c.selected = 0;
        assert_eq!(c.wanted_previews(0, 99).len(), 2, "first item has one neighbour");
    }

    #[test]
    fn bindings_cover_every_action() {
        for b in BINDINGS.iter().filter(|b| {
            !matches!(
                b.id,
                "play_pause"
                    | "seek_back"
                    | "seek_forward"
                    | "volume_down"
                    | "volume_up"
                    | "zoom_in"
                    | "zoom_out"
                    | "zoom_fit"
                    | "zoom_actual"
                    | "menu"
                    | "fullscreen"
                    | "sync"
                    // The view's own (menu actions, one key per view / sort, help).
                    | "view_list"
                    | "view_grid"
                    | "view_carousel"
                    | "open_fullscreen"
                    | "sync_item"
                    | "copy"
                    | "paste"
                    | "copy_to"
                    | "move_to"
                    | "rename"
                    | "delete"
                    | "new_folder"
                    | "copy_path"
                    | "copy_text"
                    | "sort_name"
                    | "sort_modified"
                    | "sort_size"
                    | "reverse"
                    | "keys"
                    | "help"
            )
        }) {
            assert!(Action::from_id(b.id).is_some(), "{}", b.id);
        }
        let k = crate::modes::Keymap::new(BINDINGS);
        assert!(manual(&k).iter().any(|l| l.contains("  v ") && l.contains("switch view")));
    }

    #[test]
    fn paging_parent_marks_and_pipe() {
        let t = tree();
        let mut c = Commander::new();
        c.set_cwd(Some(t.path().to_path_buf()));
        c.page = 3;
        c.apply(Action::PageDown, 1);
        assert_eq!(c.selected, 3);
        c.apply(Action::Last, 1);
        assert_eq!(c.selected, 4);
        c.apply(Action::PageUp, 1);
        assert_eq!(c.selected, 1);
        c.apply(Action::First, 1);
        assert_eq!(c.selected, 0);
        assert_eq!(c.apply(Action::Parent, 1), Effect::Cd(t.path().parent().unwrap().to_path_buf()));
        // No marks: the selection is piped.
        c.selected = 1;
        c.apply(Action::Pipe, 1);
        for b in [&b"w"[..], b"c", b" ", b"-", b"l"] {
            c.pipe_key(b);
        }
        let Some(Effect::Run(line)) = c.pipe_key(b"\r") else { panic!() };
        assert_eq!(line, format!("printf '%s\\n' '{}' | wc -l", t.path().join("a.txt").display()));
        // Marks: several files, in listing order (no . or .. to skip any more).
        c.selected = 0;
        c.apply(Action::Mark, 1);
        assert_eq!(c.marks.len(), 1, "the first entry is a real file");
        c.selected = 0;
        c.apply(Action::Mark, 1);
        assert!(c.marks.is_empty());
        c.selected = 2;
        c.apply(Action::Mark, 1);
        c.selected = 1;
        c.apply(Action::Mark, 1);
        assert_eq!(c.pipe_paths(), [t.path().join("a.txt"), t.path().join("b.png")]);
        c.apply(Action::MarkAll, 1);
        assert!(c.marks.is_empty(), "mark-all with marks clears them");
        c.apply(Action::MarkAll, 1);
        assert_eq!(c.marks.len(), 5);
        assert_eq!(shell_quote("it's"), r"'it'\''s'");
        c.apply(Action::Pipe, 1);
        c.pipe_key(b"x");
        assert_eq!(c.pipe_key(b"\x1b"), Some(Effect::None));
        assert!(!c.piping && c.pipe_cmd.is_empty());
        c.set_cwd(Some(t.path().join("sub")));
        assert!(c.marks.is_empty(), "marks are per folder");
    }

    #[test]
    fn back_selects_the_folder_you_came_from() {
        let t = tree();
        std::fs::create_dir_all(t.path().join("sub/deep/er")).unwrap();
        let mut c = Commander::new();
        c.set_cwd(Some(t.path().join("sub/deep/er")));
        assert_eq!(c.apply(Action::Parent, 1), Effect::Cd(t.path().join("sub/deep")));
        // The shell went up: the folder we left is selected.
        c.set_cwd(Some(t.path().join("sub")));
        assert_eq!(c.selected_entry().unwrap().name, "deep");
        c.set_cwd(Some(t.path().to_path_buf()));
        assert_eq!(c.selected_entry().unwrap().name, "sub");
        // Going down starts at the top.
        c.set_cwd(Some(t.path().join("sub")));
        assert_eq!(c.selected, 0);
        // u and Backspace are both back, both remappable.
        let k = crate::modes::Keymap::new(BINDINGS);
        assert!(manual(&k).iter().any(|l| l.contains("backspace") && l.contains("back")), "{:?}", manual(&k));
        assert_eq!(Action::from_id("back"), Some(Action::Parent));
        assert_eq!(crate::modes::key_bytes("backspace").unwrap()[0], b"\x7f");
        // At / there is no parent.
        c.set_cwd(Some(PathBuf::from("/")));
        assert_eq!(c.apply(Action::Parent, 1), Effect::None);
    }

    #[test]
    fn grid_moves_in_2d_and_carousel_by_item() {
        let t = tree();
        let mut c = Commander::new();
        c.set_cwd(Some(t.path().to_path_buf()));
        c.view = View::Grid;
        c.apply(Action::Right, 3);
        c.apply(Action::Down, 3);
        assert_eq!(c.selected, 4);
        c.apply(Action::Left, 3);
        c.apply(Action::Up, 3);
        assert_eq!(c.selected, 0);
        c.view = View::Carousel;
        c.apply(Action::Right, 3);
        c.apply(Action::Right, 3);
        assert_eq!(c.selected, 2);
        c.apply(Action::Left, 3);
        assert_eq!(c.selected, 1);
    }
}

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

    fn e(name: &str, dir: bool) -> Entry {
        Entry {
            name: name.into(),
            path: PathBuf::from(format!("/srv/{name}")),
            kind: if dir { Kind::Dir } else { kind_of(name) },
            mode: if dir { "drwxr-xr-x".into() } else { "-rw-r--r--".into() },
            size: 1,
            modified: None,
        }
    }

    /// The shell reports where a `cd` landed; the tests pass the resolved path
    /// as a shell reading /proc would.
    fn land(c: &mut Commander, e: &Effect) {
        if let Effect::Cd(p) = e {
            c.set_cwd(Some(std::fs::canonicalize(p).unwrap()));
        }
    }

    #[cfg(unix)]
    #[test]
    fn a_symlink_round_trip_comes_back_to_the_link_not_the_targets_parent() {
        let t = tests::tree();
        let real = t.path().join("deep/real/target");
        std::fs::create_dir_all(&real).unwrap();
        for n in ["x1", "x2", "x3", "x4"] {
            std::fs::write(real.join(n), b"").unwrap();
        }
        std::os::unix::fs::symlink(&real, t.path().join("sub/link")).unwrap();
        let sub = std::fs::canonicalize(t.path().join("sub")).unwrap();
        let mut c = Commander::new();
        c.set_cwd(Some(sub.clone()));
        c.selected = c.visible().iter().position(|e| e.name == "link").unwrap();
        let go = c.open_selected();
        assert_eq!(go, Effect::Cd(sub.join("link")));
        land(&mut c, &go);
        // Inside the link: the logical path, not the target's.
        assert_eq!(c.cwd.as_deref(), Some(sub.join("link").as_path()));
        // Open a file there, back out of it, then back to sub.
        c.selected = 2;
        c.scroll = 1;
        c.open_selected();
        c.close_file();
        assert_eq!((c.selected, c.scroll), (2, 1));
        let back = c.apply(Action::Parent, 1);
        assert_eq!(back, Effect::Cd(sub.clone()), "never the target's real parent");
        land(&mut c, &back);
        assert_eq!(c.cwd.as_deref(), Some(sub.as_path()));
        assert_eq!(c.selected_entry().unwrap().name, "link");
        assert!(c.nav.is_empty());
        // With an empty stack, back from the link goes to the link's parent.
        let mut d = Commander::new();
        d.set_cwd(Some(sub.join("link")));
        assert_eq!(d.apply(Action::Parent, 1), Effect::Cd(sub.clone()));
        assert_ne!(d.apply(Action::Parent, 1), Effect::Cd(real.parent().unwrap().to_path_buf()));
    }

    #[test]
    fn back_restores_the_selection_and_scroll_and_a_typed_cd_starts_over() {
        let t = tests::tree();
        let root = std::fs::canonicalize(t.path()).unwrap();
        std::fs::create_dir(root.join("sub/inner")).unwrap();
        let mut c = Commander::new();
        c.set_cwd(Some(root.clone()));
        c.selected = c.visible().iter().position(|e| e.name == "sub").unwrap();
        c.scroll = 2;
        let (sel, sc) = (c.selected, c.scroll);
        let go = c.open_selected();
        land(&mut c, &go);
        let go = c.open_selected(); // sub/inner
        land(&mut c, &go);
        assert_eq!(c.nav.len(), 2);
        let b = c.apply(Action::Parent, 1);
        land(&mut c, &b);
        let b = c.apply(Action::Parent, 1);
        land(&mut c, &b);
        assert_eq!((c.cwd.as_deref(), c.selected, c.scroll), (Some(root.as_path()), sel, sc));
        // A cd typed in the shell (or a breadcrumb jump) is a new history.
        let go = c.open_selected();
        land(&mut c, &go);
        c.set_cwd(Some(root.join("sub/inner")));
        assert!(c.nav.is_empty());
        assert_eq!(c.apply(Action::Parent, 1), Effect::Cd(root.join("sub")));
        assert_eq!(c.jump(root.clone()), Effect::Cd(root.clone()));
        assert!(c.nav.is_empty());
    }

    #[test]
    fn remote_folders_use_the_same_stack() {
        let mut c = Commander::new();
        c.set_remote("me@web1".into(), Some("/srv".into()), Some(Ok(vec![e("b.png", false), e("app", true)])));
        c.selected = c.visible().iter().position(|e| e.name == "app").unwrap();
        let sel = c.selected;
        assert_eq!(c.open_selected(), Effect::Cd("/srv/app".into()));
        c.set_remote("me@web1".into(), Some("/srv/app".into()), Some(Ok(vec![])));
        assert_eq!(c.apply(Action::Parent, 1), Effect::Cd("/srv".into()));
        c.set_remote("me@web1".into(), Some("/srv".into()), Some(Ok(vec![e("b.png", false), e("app", true)])));
        assert_eq!((c.selected, c.nav.len()), (sel, 0));
    }

    #[test]
    fn remote_listing_unknown_dir_and_back_to_local() {
        let mut c = Commander::new();
        c.set_remote("me@web1".into(), None, None);
        assert!(c.entries.is_empty() && c.error.as_deref().unwrap().starts_with("remote (me@web1): no directory info"));
        c.set_remote("me@web1".into(), Some("/srv".into()), None);
        assert!(c.entries.is_empty() && c.error.is_none(), "loading: nothing stale");
        c.set_remote("me@web1".into(), Some("/srv".into()), Some(Ok(vec![e("b.png", false), e(".env", false), e("app", true)])));
        assert_eq!(c.visible().iter().map(|e| e.name.as_str()).collect::<Vec<_>>(), [".env", "app", "b.png"]);
        c.flags.all = false;
        c.relist();
        assert_eq!(c.visible().len(), 2, "flags re-sort the remote listing, no local read");
        // Folders cd (over the PTY), files open in the viewer like local ones.
        c.selected = 0;
        assert_eq!(c.open_selected(), Effect::Cd("/srv/app".into()));
        c.selected = 1;
        assert_eq!(c.open_selected(), Effect::None);
        assert_eq!(c.overlay, Some(Overlay::Preview("/srv/b.png".into())));
        c.overlay = None;
        // Up on the remote side selects where we came from.
        c.set_remote("me@web1".into(), Some("/srv/app/x".into()), Some(Ok(vec![])));
        c.set_remote("me@web1".into(), Some("/srv/app".into()), None);
        c.set_remote("me@web1".into(), Some("/srv".into()), Some(Ok(vec![e("app", true), e("zz", true)])));
        assert_eq!(c.selected_entry().unwrap().name, "app");
        // Back home: local listing again.
        let t = tempfile::tempdir().unwrap();
        std::fs::write(t.path().join("local.txt"), b"").unwrap();
        c.set_cwd(Some(t.path().to_path_buf()));
        assert!(c.remote.is_none());
        assert_eq!(c.visible()[0].name, "local.txt");
    }
}

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

    #[test]
    fn every_type_has_its_badge() {
        let b = |n: &str| badge_of(n, kind_of(n), "-rw-r--r--");
        assert_eq!(badge_of("src", Kind::Dir, "drwxr-xr-x"), Badge::Folder);
        for (n, want) in [
            ("a.png", Badge::Image),
            ("a.mkv", Badge::Video),
            ("a.flac", Badge::Audio),
            ("notes.txt", Badge::Text),
            ("main.rs", Badge::Code),
            ("README.md", Badge::Markdown),
            ("paper.PDF", Badge::Pdf),
            ("x.tar.gz", Badge::Archive),
            ("app.exe", Badge::Binary),
            ("Cargo.toml", Badge::Config),
            ("a.json", Badge::Config),
            ("Inter.ttf", Badge::Font),
            ("sheet.xlsx", Badge::Document),
            ("a.csv", Badge::Document),
            ("thing.qqq", Badge::Generic),
        ] {
            assert_eq!(b(n), want, "{n}");
        }
        // An executable with no known type is a binary; a plain one is text.
        assert_eq!(badge_of("mouser", kind_of("mouser"), "-rwxr-xr-x"), Badge::Binary);
        assert_eq!(badge_of("Makefile", kind_of("Makefile"), "-rw-r--r--"), Badge::Text);
        for x in Badge::ALL {
            assert_eq!(Badge::from_index(x.index()), x);
            assert!(x.mark().chars().count() <= 3);
        }
    }
}