fm84 0.44.1

A synthwave dual-pane TUI 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
//! Keys in the panels: names to the clipboard, swapping, sorting, going places.

use super::*;

/// Ctrl+C copies full paths and Alt+C names: of the selection, of the
/// entry under the cursor, or on the parent entry of the panel itself.
#[test]
fn copy_paths_and_names_from_a_panel() {
    let dir = std::env::temp_dir().join(format!("fm84-copy-names-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("a.txt"), "").unwrap();
    std::fs::write(dir.join("b.txt"), "").unwrap();
    let mut app_state = AppState::new();
    app_state.options = crate::options::Options::default();
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, dir.clone(), Some("b.txt".as_ref()));
    let chord = |app_state: &mut AppState, modifiers| handle_key(app_state, KeyEvent::new(KeyCode::Char('c'), modifiers));

    chord(&mut app_state, KeyModifiers::CONTROL);
    assert_eq!(app_state.clipboard, dir.join("b.txt").to_string_lossy());
    assert!(app_state.find_note.as_deref().unwrap().starts_with("Copied path: "));
    chord(&mut app_state, KeyModifiers::ALT);
    assert_eq!(app_state.clipboard, "b.txt");

    app_state.left.selected.insert("a.txt".into());
    app_state.left.selected.insert("b.txt".into());
    chord(&mut app_state, KeyModifiers::ALT);
    assert_eq!(app_state.clipboard, "a.txt\nb.txt");
    assert_eq!(app_state.find_note.as_deref(), Some("Copied 2 names"));
    // The note goes with the next key.
    press(&mut app_state, KeyCode::Down);
    assert!(app_state.find_note.is_none());

    app_state.left.selected.clear();
    app_state.left.state.select(Some(0));
    chord(&mut app_state, KeyModifiers::CONTROL);
    assert_eq!(app_state.clipboard, dir.to_string_lossy());

    std::fs::remove_dir_all(&dir).unwrap();
}

/// Ctrl+U swaps the panels, tabs, cursors and selections with them, and
/// the focus goes along; Alt+I sends the other panel here.
#[test]
fn swap_the_panels_and_send_the_other_one_here() {
    let dir = std::env::temp_dir().join(format!("fm84-swap-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    for name in ["one", "two", "three"] {
        std::fs::create_dir_all(dir.join(name)).unwrap();
    }
    std::fs::write(dir.join("one").join("a.txt"), "").unwrap();
    std::fs::write(dir.join("one").join("b.txt"), "").unwrap();
    let mut app_state = AppState::new();
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, dir.join("one"), Some("b.txt".as_ref()));
    app_state.left.selected.insert("a.txt".into());
    app_state.open_dir(Side::Right, dir.join("two"), None);
    app_state.active_side = Side::Right;
    app_state.new_tab();
    app_state.open_dir(Side::Right, dir.join("three"), None);
    app_state.active_side = Side::Left;
    let chord = |app_state: &mut AppState, c, modifiers| handle_key(app_state, KeyEvent::new(KeyCode::Char(c), modifiers));
    let cursor = |app_state: &AppState, side: Side| {
        let panel = app_state.panel(side);
        let (children, state) = (&panel.children, &panel.state);
        children[state.selected().unwrap()].name_full.clone()
    };

    chord(&mut app_state, 'u', KeyModifiers::CONTROL);
    assert_eq!((app_state.left.dir.clone(), app_state.right.dir.clone()), (dir.join("three"), dir.join("one")));
    assert_eq!((app_state.left.tabs.list.len(), app_state.left.tabs.active, app_state.right.tabs.list.len()), (2, 1, 1));
    assert_eq!(app_state.active_side, Side::Right);
    assert_eq!(cursor(&app_state, Side::Right), "b.txt");
    assert!(app_state.right.selected.contains(std::ffi::OsStr::new("a.txt")) && app_state.left.selected.is_empty());
    // The other tab went across too, as it was.
    app_state.select_tab(Side::Left, 0);
    assert_eq!(app_state.left.dir, dir.join("two"));

    chord(&mut app_state, 'i', KeyModifiers::ALT);
    assert_eq!(app_state.left.dir, dir.join("one"));
    assert_eq!(cursor(&app_state, Side::Left), "b.txt");
    assert_eq!(app_state.active_side, Side::Right);

    std::fs::remove_dir_all(&dir).unwrap();
}

/// After Ctrl+U each panel still sees its directory change on disk: what is
/// made there afterwards shows up, on whichever side it went to.
#[test]
fn swapped_panels_still_see_changes() {
    let dir = std::env::temp_dir().join(format!("fm84-swap-watch-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    for name in ["one", "two"] {
        std::fs::create_dir_all(dir.join(name)).unwrap();
    }
    let mut app_state = AppState::new();
    // Watchers that look every few milliseconds, so a change is seen
    // inside the test.
    app_state.workers.watch_interval = std::time::Duration::from_millis(5);
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, dir.join("one"), None);
    app_state.open_dir(Side::Right, dir.join("two"), None);
    handle_key(&mut app_state, KeyEvent::new(KeyCode::Char('u'), KeyModifiers::CONTROL));
    assert_eq!((app_state.left.dir.clone(), app_state.right.dir.clone()), (dir.join("two"), dir.join("one")));

    std::fs::write(dir.join("one").join("new.txt"), "").unwrap();
    std::fs::write(dir.join("two").join("new.txt"), "").unwrap();
    let shows = |app_state: &AppState, side: Side| app_state.panel(side).children.iter().any(|item| item.name_os == "new.txt");
    for _ in 0..200 {
        if shows(&app_state, Side::Left) && shows(&app_state, Side::Right) {
            break;
        }
        std::thread::sleep(std::time::Duration::from_millis(5));
        app_state.poll_watchers();
        app_state.refresh_stale_panels();
    }
    assert!(shows(&app_state, Side::Left), "the left panel missed its change");
    assert!(shows(&app_state, Side::Right), "the right panel missed its change");

    std::fs::remove_dir_all(&dir).unwrap();
}

/// Ctrl+F3 to Ctrl+F6 and a click on a heading sort both panels.
#[test]
fn sort_from_the_keys_and_the_headings() {
    use crate::options::{Options, SortKey};
    use crossterm::event::{MouseButton, MouseEvent, MouseEventKind};
    let dir = std::env::temp_dir().join(format!("fm84-sort-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    std::fs::write(dir.join("a.txt"), "a long one").unwrap();
    std::fs::write(dir.join("b.rs"), "short").unwrap();
    std::fs::write(dir.join("c.md"), "mid size").unwrap();
    let mut app_state = AppState::new();
    app_state.options = Options::default();
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, dir.clone(), Some("b.rs".as_ref()));
    let names = |app_state: &AppState| app_state.left.children.iter().skip(1).map(|item| item.name_full.clone()).collect::<Vec<_>>();
    let control = |app_state: &mut AppState, n| handle_key(app_state, KeyEvent::new(KeyCode::F(n), KeyModifiers::CONTROL));

    // Ctrl+F3 sorts by name, and again turns it round, the cursor
    // staying on the entry it was on.
    control(&mut app_state, 3);
    assert_eq!(names(&app_state), ["a.txt", "b.rs", "c.md"]);
    control(&mut app_state, 3);
    assert!(app_state.options.sort_descending);
    assert_eq!(names(&app_state), ["c.md", "b.rs", "a.txt"]);
    control(&mut app_state, 4);
    assert_eq!((app_state.options.sort_key, app_state.options.sort_descending), (SortKey::Extension, false));
    assert_eq!(names(&app_state), ["c.md", "b.rs", "a.txt"]);
    let cursor = app_state.left.state.selected().unwrap();
    assert_eq!(app_state.left.children[cursor].name_full, "b.rs");

    // A click on the Size heading sorts by size, arrow and all.
    let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 30)).unwrap();
    crate::ui::render_ui(&mut terminal, &mut app_state);
    let (cell, _) = *app_state.drawn.sort_headers.iter().find(|(_, key)| *key == SortKey::Size).unwrap();
    let click = MouseEvent {
        kind: MouseEventKind::Down(MouseButton::Left),
        column: cell.x,
        row: cell.y,
        modifiers: KeyModifiers::NONE,
    };
    crate::input::handle_mouse(&mut app_state, click);
    assert_eq!(app_state.options.sort_key, SortKey::Size);
    assert_eq!(names(&app_state), ["b.rs", "c.md", "a.txt"]);
    crate::ui::render_ui(&mut terminal, &mut app_state);
    let heading: String = (cell.x..cell.x + cell.width).map(|x| terminal.backend().buffer()[(x, cell.y)].symbol().to_string()).collect();
    assert_eq!(heading.trim_end(), "Size ↑");

    std::fs::remove_dir_all(&dir).unwrap();
}

/// Ctrl+L goes where it is told - a directory, or a file to land on -
/// and Alt+Left and Alt+Right step back and forth through where the tab
/// has been, landing on the entry the cursor was on.
#[test]
fn go_to_a_path_and_back_and_forward() {
    let dir = std::env::temp_dir().join(format!("fm84-go-to-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("sub/deeper")).unwrap();
    std::fs::write(dir.join("a.txt"), "text").unwrap();
    let mut app_state = AppState::new();
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, dir.clone(), Some("sub".as_ref()));
    let alt = |app_state: &mut AppState, code: KeyCode| handle_key(app_state, KeyEvent::new(code, KeyModifiers::ALT));
    let ctrl_l = |app_state: &mut AppState| handle_key(app_state, KeyEvent::new(KeyCode::Char('l'), KeyModifiers::CONTROL));
    let cursor = |app_state: &AppState| {
        let index = app_state.left.state.selected().unwrap();
        app_state.left.children[index].name.clone()
    };
    let type_in = |app_state: &mut AppState, text: &str| {
        let Some(Dialog::Prompt(PromptKind::GoTo, input)) = &mut app_state.dialog else { panic!("no prompt") };
        input.set(text.to_string());
    };

    // It opens on where the panel is, ready to have a name typed on.
    ctrl_l(&mut app_state);
    let Some(Dialog::Prompt(PromptKind::GoTo, input)) = &app_state.dialog else { panic!("no prompt") };
    assert_eq!(input.text, format!("{}{}", dir.display(), std::path::MAIN_SEPARATOR));
    // Tab fills out the name, and Enter goes there.
    press(&mut app_state, KeyCode::Char('s'));
    press(&mut app_state, KeyCode::Tab);
    press(&mut app_state, KeyCode::Char('d'));
    press(&mut app_state, KeyCode::Tab);
    press(&mut app_state, KeyCode::Enter);
    assert_eq!(app_state.left.dir, dir.join("sub/deeper"));

    // A path from the panel, `..` and all, to a file: landed on, in the
    // directory it is in.
    ctrl_l(&mut app_state);
    type_in(&mut app_state, "../../a.txt");
    press(&mut app_state, KeyCode::Enter);
    assert_eq!((app_state.left.dir.clone(), cursor(&app_state)), (dir.clone(), "a".to_string()));

    // Somewhere that is not there is said to be, and the panel stays.
    ctrl_l(&mut app_state);
    type_in(&mut app_state, "nowhere");
    press(&mut app_state, KeyCode::Enter);
    assert!(app_state.error.take().unwrap().contains("nowhere"));
    assert_eq!(app_state.left.dir, dir);

    // Back the way it came, onto what the cursor was on, and forward.
    alt(&mut app_state, KeyCode::Left);
    assert_eq!(app_state.left.dir, dir.join("sub/deeper"));
    alt(&mut app_state, KeyCode::Left);
    assert_eq!((app_state.left.dir.clone(), cursor(&app_state)), (dir.clone(), "sub".to_string()));
    alt(&mut app_state, KeyCode::Right);
    assert_eq!(app_state.left.dir, dir.join("sub/deeper"));

    // A step somewhere new drops what was ahead.
    press(&mut app_state, KeyCode::Backspace);
    assert_eq!(app_state.left.dir, dir.join("sub"));
    alt(&mut app_state, KeyCode::Right);
    assert_eq!(app_state.left.dir, dir.join("sub"));
    alt(&mut app_state, KeyCode::Left);
    assert_eq!(app_state.left.dir, dir.join("sub/deeper"));

    // A directory gone since is passed over, rather than stuck on: from
    // sub, back to deeper climbs out of it to sub again, and on to dir.
    std::fs::remove_dir(dir.join("sub/deeper")).unwrap();
    alt(&mut app_state, KeyCode::Right);
    assert_eq!(app_state.left.dir, dir.join("sub"));
    alt(&mut app_state, KeyCode::Left);
    assert_eq!(app_state.left.dir, dir, "the gone one was passed over");
    alt(&mut app_state, KeyCode::Right);
    assert_eq!(app_state.left.dir, dir.join("sub"));
    std::fs::remove_dir_all(&dir).unwrap();
}

/// Alt+Shift+Enter sizes every directory in the panel - Alt+Enter too -
/// a few at a time with the rest waiting their turn, and not through a link
/// to a directory, which could lead anywhere. Waiting shows as "…" in the
/// Size column until each is counted.
#[cfg(unix)]
#[test]
fn alt_shift_enter_sizes_every_directory() {
    let dir = std::env::temp_dir().join(format!("fm84-size-all-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let count = crate::constants::SIZE_WORKERS * 2 + 1;
    for n in 0..count {
        let sub = dir.join(format!("dir{n:02}"));
        std::fs::create_dir_all(sub.join("inner")).unwrap();
        std::fs::write(sub.join("a.bin"), vec![0u8; n]).unwrap();
        std::fs::write(sub.join("inner").join("b.bin"), vec![0u8; 100]).unwrap();
    }
    std::fs::write(dir.join("file.txt"), "not a directory").unwrap();
    std::os::unix::fs::symlink(&dir, dir.join("loop")).unwrap();

    for modifiers in [KeyModifiers::ALT | KeyModifiers::SHIFT, KeyModifiers::ALT] {
        let mut app_state = AppState::new();
        app_state.options = crate::options::Options::default();
        app_state.active_side = Side::Left;
        app_state.open_dir(Side::Left, dir.clone(), None);
        handle_key(&mut app_state, KeyEvent::new(KeyCode::Enter, modifiers));
        assert_eq!(app_state.left.dir, dir, "it sizes, and does not go in");

        // A few at once, the rest waiting, and shown as waiting.
        assert_eq!(app_state.workers.dir_sizing.len(), crate::constants::SIZE_WORKERS);
        assert_eq!(app_state.workers.dir_size_queue.len(), count - crate::constants::SIZE_WORKERS);
        assert_eq!(app_state.dir_size_so_far(app_state.workers.dir_size_queue.back().unwrap()), Some(0));

        let started = std::time::Instant::now();
        while !app_state.workers.dir_sizing.is_empty() || !app_state.workers.dir_size_queue.is_empty() {
            assert!(started.elapsed() < std::time::Duration::from_secs(10), "sizing never finished");
            assert!(app_state.workers.dir_sizing.len() <= crate::constants::SIZE_WORKERS);
            std::thread::sleep(std::time::Duration::from_millis(2));
            app_state.poll_dir_sizes();
        }
        for n in 0..count {
            assert_eq!(app_state.dir_sizes.get(&dir.join(format!("dir{n:02}"))), Some(&(n as u64 + 100)), "dir{n:02}");
        }
        assert_eq!(app_state.dir_sizes.len(), count, "neither the link nor the file");
    }

    // Esc stops what is running and what is waiting.
    let mut app_state = AppState::new();
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, dir.clone(), None);
    handle_key(&mut app_state, KeyEvent::new(KeyCode::Enter, KeyModifiers::ALT | KeyModifiers::SHIFT));
    press(&mut app_state, KeyCode::Esc);
    assert!(app_state.workers.dir_sizing.is_empty() && app_state.workers.dir_size_queue.is_empty());
    std::fs::remove_dir_all(&dir).unwrap();
}

/// Space on a directory while a panel's worth are waiting is sized next,
/// ahead of them, since it was asked for on its own.
#[test]
fn a_directory_sized_on_its_own_goes_ahead_of_those_waiting() {
    let mut app_state = AppState::new();
    // Every worker busy, so nothing more starts, and the order shows.
    for n in 0..crate::constants::SIZE_WORKERS {
        app_state.start_dir_size(std::path::PathBuf::from(format!("/nonexistent/fm84/busy{n}")));
    }
    let waiting: Vec<std::path::PathBuf> = (0..3).map(|n| std::path::PathBuf::from(format!("/nonexistent/fm84/{n}"))).collect();
    app_state.workers.dir_size_queue.extend(waiting.iter().cloned());
    app_state.start_dir_size(waiting[2].clone());
    assert_eq!(app_state.workers.dir_size_queue.front(), Some(&waiting[2]));
    assert_eq!(app_state.workers.dir_size_queue.len(), 3, "moved, not added again");
    app_state.cancel_dir_sizes();
}

/// Leaving a directory stops sizing what is in it, running and waiting -
/// nothing shows those sizes any more - unless the other panel is in it too.
/// Sizes already counted are kept, for coming back.
#[test]
fn leaving_a_directory_stops_sizing_what_is_in_it() {
    let dir = std::env::temp_dir().join(format!("fm84-size-leave-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    for n in 0..crate::constants::SIZE_WORKERS * 2 {
        std::fs::create_dir_all(dir.join(format!("d{n}"))).unwrap();
    }
    let elsewhere = std::env::temp_dir();
    let size_all = |app_state: &mut AppState| handle_key(app_state, KeyEvent::new(KeyCode::Enter, KeyModifiers::ALT | KeyModifiers::SHIFT));

    let mut app_state = AppState::new();
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, dir.clone(), None);
    app_state.open_dir(Side::Right, elsewhere.clone(), None);
    app_state.dir_sizes.insert(dir.join("d0"), 42);
    size_all(&mut app_state);
    assert!(!app_state.workers.dir_sizing.is_empty() && !app_state.workers.dir_size_queue.is_empty());
    app_state.open_dir(Side::Left, elsewhere.clone(), None);
    assert!(app_state.workers.dir_sizing.is_empty(), "running ones stopped");
    assert!(app_state.workers.dir_size_queue.is_empty(), "waiting ones dropped");
    assert_eq!(app_state.dir_sizes.get(&dir.join("d0")), Some(&42), "a size counted before is kept");

    // The other panel still in it: they go on, for that panel to show.
    let mut app_state = AppState::new();
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, dir.clone(), None);
    app_state.open_dir(Side::Right, dir.clone(), None);
    size_all(&mut app_state);
    let asked = app_state.workers.dir_sizing.len() + app_state.workers.dir_size_queue.len();
    app_state.open_dir(Side::Left, elsewhere.clone(), None);
    assert_eq!(app_state.workers.dir_sizing.len() + app_state.workers.dir_size_queue.len(), asked);
    app_state.cancel_dir_sizes();
    std::fs::remove_dir_all(&dir).unwrap();
}

/// Ctrl+S narrows the panel as the pattern is typed, keeping the parent
/// entry and letting go of what is selected but no longer shown. Esc puts
/// back the filter there was, Enter keeps it; a reread is narrowed too,
/// and going somewhere else drops it.
#[test]
fn ctrl_s_filters_the_panel_as_it_is_typed() {
    let dir = std::env::temp_dir().join(format!("fm84-filter-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("reports")).unwrap();
    for name in ["report.txt", "notes.md", "main.rs"] {
        std::fs::write(dir.join(name), "").unwrap();
    }
    let mut app_state = AppState::new();
    app_state.options = crate::options::Options::default();
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, dir.clone(), Some("notes.md".as_ref()));
    app_state.left.selected.insert("main.rs".into());
    app_state.left.selected.insert("report.txt".into());
    // In order of name, whatever F11 sorts by.
    let names = |app_state: &AppState| {
        let mut names: Vec<String> = app_state.left.children.iter().map(|item| item.name_full.clone()).collect();
        names.sort();
        names
    };
    let shown = names(&app_state);
    let ctrl_s = |app_state: &mut AppState| handle_key(app_state, KeyEvent::new(KeyCode::Char('s'), KeyModifiers::CONTROL));

    ctrl_s(&mut app_state);
    assert!(matches!(app_state.dialog, Some(Dialog::Prompt(PromptKind::Filter, _))));
    for c in "rep".chars() {
        press(&mut app_state, KeyCode::Char(c));
    }
    assert_eq!(names(&app_state), ["..", "report.txt", "reports"]);
    // The cursor's entry went, so it is on the first match.
    assert_eq!(app_state.left.state.selected(), Some(1));
    assert!(!app_state.left.children[1].is_parent());
    assert_eq!(app_state.left.selected, std::collections::HashSet::from(["report.txt".into()]));

    // Esc puts back what there was before: nothing.
    press(&mut app_state, KeyCode::Esc);
    assert!(app_state.dialog.is_none() && app_state.left.filter.is_none());
    assert_eq!(names(&app_state), shown);

    ctrl_s(&mut app_state);
    for c in "*.md;*.rs".chars() {
        press(&mut app_state, KeyCode::Char(c));
    }
    press(&mut app_state, KeyCode::Enter);
    assert_eq!(names(&app_state), ["..", "main.rs", "notes.md"]);
    assert_eq!(app_state.left.filter.as_ref().map(|filter| filter.text.as_str()), Some("*.md;*.rs"));

    // Opened again, it starts from the filter in place, which Esc keeps.
    ctrl_s(&mut app_state);
    press(&mut app_state, KeyCode::Backspace);
    assert_eq!(names(&app_state), ["..", "notes.md"]);
    press(&mut app_state, KeyCode::Esc);
    assert_eq!(names(&app_state), ["..", "main.rs", "notes.md"]);

    // A file arriving is narrowed as everything else is.
    std::fs::write(dir.join("lib.rs"), "").unwrap();
    std::fs::write(dir.join("todo.txt"), "").unwrap();
    app_state.reload_panel(Side::Left, None);
    assert_eq!(names(&app_state), ["..", "lib.rs", "main.rs", "notes.md"]);

    // Somewhere else, and it is gone - also on coming back.
    app_state.open_dir(Side::Left, dir.join("reports"), None);
    assert!(app_state.left.filter.is_none());
    app_state.open_dir(Side::Left, dir.clone(), None);
    assert_eq!(app_state.left.children.len(), shown.len() + 2);

    std::fs::remove_dir_all(&dir).unwrap();
}

/// Alt+Down lists where the panels have been, across tabs and both sides,
/// newest first and each once, opening on the newest that is not here.
/// Words typed narrow it; Enter goes to the one highlighted, and one gone
/// since is said to be.
#[test]
fn alt_down_goes_back_anywhere_that_has_been() {
    let dir = std::env::temp_dir().join(format!("fm84-history-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    for name in ["music/jazz", "music/rock", "photos", "gone"] {
        std::fs::create_dir_all(dir.join(name)).unwrap();
    }
    let mut app_state = AppState::new();
    app_state.options = crate::options::Options::default();
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, dir.clone(), None);
    app_state.open_dir(Side::Left, dir.join("music/jazz"), None);
    app_state.new_tab();
    app_state.open_dir(Side::Left, dir.join("photos"), None);
    app_state.open_dir(Side::Right, dir.join("music/rock"), None);
    app_state.open_dir(Side::Left, dir.join("gone"), None);
    app_state.open_dir(Side::Left, dir.join("music/jazz"), None);
    let shown = |app_state: &AppState| match &app_state.dialog {
        Some(Dialog::History(list)) => (list.shown.iter().map(|path| path.strip_prefix(&dir).unwrap_or(path).to_path_buf()).collect::<Vec<_>>(), list.index),
        _ => panic!("not open"),
    };
    let alt_down = |app_state: &mut AppState| handle_key(app_state, KeyEvent::new(KeyCode::Down, KeyModifiers::ALT));

    alt_down(&mut app_state);
    let (list, index) = shown(&app_state);
    let names: Vec<&str> = list.iter().map(|path| path.to_str().unwrap()).collect();
    assert_eq!(&names[..5], ["music/jazz", "gone", "music/rock", "photos", ""]);
    assert_eq!(index, 1, "on the newest that is not where the panel is");

    // Each word, anywhere in the path; Backspace widens it again.
    for c in "mus k".chars() {
        press(&mut app_state, KeyCode::Char(c));
    }
    assert_eq!(shown(&app_state).0, [std::path::PathBuf::from("music/rock")]);
    press(&mut app_state, KeyCode::Backspace);
    press(&mut app_state, KeyCode::Backspace);
    assert_eq!(shown(&app_state).0, [std::path::PathBuf::from("music/jazz"), std::path::PathBuf::from("music/rock")]);
    press(&mut app_state, KeyCode::Down);
    press(&mut app_state, KeyCode::Enter);
    assert!(app_state.dialog.is_none());
    assert_eq!(app_state.left.dir, dir.join("music/rock"));

    // Gone since: said so, and the panel stays.
    std::fs::remove_dir(dir.join("gone")).unwrap();
    alt_down(&mut app_state);
    for c in "gone".chars() {
        press(&mut app_state, KeyCode::Char(c));
    }
    press(&mut app_state, KeyCode::Enter);
    assert!(app_state.error.is_some());
    assert_eq!(app_state.left.dir, dir.join("music/rock"));
    std::fs::remove_dir_all(&dir).unwrap();
}

/// Ctrl+B lists every file under the panel's directory by its path from
/// there - not the directories, nor what is hidden when F11 hides it - and
/// sorted by size it finds the biggest. F2 renames a file where it is; Ctrl+B
/// again goes back, onto what holds the file the cursor was on, and going
/// anywhere else drops it.
#[test]
fn ctrl_b_lists_every_file_below() {
    let dir = std::env::temp_dir().join(format!("fm84-flat-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("sub/deep")).unwrap();
    std::fs::create_dir_all(dir.join(".secret")).unwrap();
    std::fs::write(dir.join("a.txt"), "a").unwrap();
    std::fs::write(dir.join("sub/b.bin"), "b".repeat(100)).unwrap();
    std::fs::write(dir.join("sub/deep/c.txt"), "c".repeat(10)).unwrap();
    std::fs::write(dir.join(".secret/key"), "").unwrap();
    #[cfg(unix)]
    std::os::unix::fs::symlink(dir.join("sub"), dir.join("again")).unwrap();
    let mut app_state = AppState::new();
    app_state.options = crate::options::Options::default();
    app_state.options.show_hidden = false;
    app_state.options.sort_key = crate::options::SortKey::Name;
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, dir.clone(), Some("sub".as_ref()));
    let names = |app_state: &AppState| app_state.left.children.iter().map(|item| item.name_full.clone()).collect::<Vec<_>>();
    let cursor = |app_state: &AppState| app_state.left.children[app_state.left.state.selected().unwrap()].name_full.clone();
    let ctrl_b = |app_state: &mut AppState| handle_key(app_state, KeyEvent::new(KeyCode::Char('b'), KeyModifiers::CONTROL));
    let sep = std::path::MAIN_SEPARATOR;

    ctrl_b(&mut app_state);
    assert_eq!(app_state.left.flat.as_ref().map(|flat| &flat.dir), Some(&dir));
    assert_eq!(names(&app_state), ["..".to_string(), "a.txt".to_string(), format!("sub{sep}b.bin"), format!("sub{sep}deep{sep}c.txt")]);
    let deep = app_state.left.children.iter().find(|item| item.name_full.ends_with("c.txt")).unwrap();
    assert_eq!((deep.name.as_str(), deep.extension.as_str()), (format!("sub{sep}deep{sep}c").as_str(), "txt"));

    // Sorted by size, the biggest last.
    handle_key(&mut app_state, KeyEvent::new(KeyCode::F(6), KeyModifiers::CONTROL));
    assert_eq!(names(&app_state)[1..], ["a.txt".to_string(), format!("sub{sep}deep{sep}c.txt"), format!("sub{sep}b.bin")]);
    assert!(app_state.left.flat.is_some(), "a reread keeps it");

    // F2 offers the file's own name, and renames it where it is.
    let at = app_state.left.children.iter().position(|item| item.name_full.ends_with("c.txt")).unwrap();
    app_state.left.state.select(Some(at));
    press(&mut app_state, KeyCode::F(2));
    assert_eq!(app_state.dialog_input().unwrap().text, "c.txt");
    app_state.dialog_input().unwrap().set("d.txt".to_string());
    press(&mut app_state, KeyCode::Enter);
    assert!(dir.join("sub/deep/d.txt").exists() && app_state.error.is_none());
    assert_eq!(cursor(&app_state), format!("sub{sep}deep{sep}d.txt"));

    // Back to the directory, on what holds that file.
    ctrl_b(&mut app_state);
    assert!(app_state.left.flat.is_none());
    assert_eq!(cursor(&app_state), "sub");

    // Somewhere else and back, and it is not flat any more.
    ctrl_b(&mut app_state);
    press(&mut app_state, KeyCode::Backspace);
    assert!(app_state.left.flat.is_none());
    app_state.open_dir(Side::Left, dir.clone(), None);
    assert!(names(&app_state).contains(&"sub".to_string()));
    std::fs::remove_dir_all(&dir).unwrap();
}

/// A flat walk nobody wants any more stops.
#[test]
fn a_flat_walk_stops_when_told() {
    let stop = std::sync::atomic::AtomicBool::new(true);
    let options = crate::options::Options::default();
    let walked = crate::fs_ops::load_flat_rows(&std::env::temp_dir(), &options, &stop);
    assert!(walked.is_err_and(|e| e.kind() == std::io::ErrorKind::Interrupted) || std::fs::read_dir(std::env::temp_dir()).unwrap().next().is_none());
}