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
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
//! Copying, moving, linking, comparing and changing attributes, from the keys.

use super::*;

/// Shift+F3 compares the file under the cursor with its namesake in the
/// other panel, or two selected in one; each side is the panel its file is
/// in. Files that are the same, or not text, are only spoken of.
#[test]
fn compare_files_from_the_keys() {
    let dir = std::env::temp_dir().join(format!("fm84-compare-files-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let (one, two) = (dir.join("one"), dir.join("two"));
    std::fs::create_dir_all(one.join("sub")).unwrap();
    std::fs::create_dir_all(&two).unwrap();
    std::fs::write(one.join("a.txt"), "same\nleft\nsame\n").unwrap();
    std::fs::write(one.join("b.txt"), "same\nb\nsame\n").unwrap();
    std::fs::write(two.join("a.txt"), "same\nright\nsame\nextra\n").unwrap();
    std::fs::write(two.join("copy.txt"), "same\nleft\nsame\n").unwrap();
    let mut app_state = AppState::new();
    app_state.open_dir(Side::Right, two.clone(), Some("copy.txt".as_ref()));
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, one.clone(), Some("a.txt".as_ref()));
    let compare = |app_state: &mut AppState| handle_key(app_state, KeyEvent::new(KeyCode::F(3), KeyModifiers::SHIFT));
    let sides = |app_state: &AppState| match &app_state.screen {
        Screen::Diff(state) => (state.left_path.clone(), state.right_path.clone()),
        _ => panic!("not comparing"),
    };

    // The namesake, not the other panel's cursor.
    compare(&mut app_state);
    assert_eq!(sides(&app_state), (one.join("a.txt"), two.join("a.txt")));
    let Screen::Diff(state) = &app_state.screen else { unreachable!() };
    assert_eq!(state.hunks.len(), 2);

    // Drawn side by side, with the marks between, and its own keys.
    let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
    crate::ui::render_ui(&mut terminal, &mut app_state);
    let screen: String = terminal.backend().buffer().content().iter().map(|cell| cell.symbol()).collect();
    for shown in [" | ", " > ", "left", "right", "extra", "Difference 1/2", "F3 Next"] {
        assert!(screen.contains(shown), "{shown} not drawn");
    }
    press(&mut app_state, KeyCode::F(3));
    let Screen::Diff(state) = &app_state.screen else { unreachable!() };
    assert_eq!(state.current, Some(1));
    press(&mut app_state, KeyCode::Esc);
    assert!(matches!(app_state.screen, Screen::Panels));

    // = does the same, for a terminal that cannot send Shift+F3.
    press(&mut app_state, KeyCode::Char('='));
    assert_eq!(sides(&app_state), (one.join("a.txt"), two.join("a.txt")));
    press(&mut app_state, KeyCode::Esc);

    // From the right panel, the left file is still on the left.
    app_state.active_side = Side::Right;
    app_state.open_dir(Side::Right, two.clone(), Some("a.txt".as_ref()));
    compare(&mut app_state);
    assert_eq!(sides(&app_state), (one.join("a.txt"), two.join("a.txt")));
    press(&mut app_state, KeyCode::Esc);

    // No namesake: the other panel's cursor, here a file the same.
    app_state.open_dir(Side::Right, two.clone(), Some("copy.txt".as_ref()));
    compare(&mut app_state);
    assert!(matches!(app_state.screen, Screen::Panels));
    assert_eq!(app_state.find_note.as_deref(), Some("The files are identical"));

    // Two selected in one panel.
    app_state.active_side = Side::Left;
    app_state.left.selected.insert("a.txt".into());
    app_state.left.selected.insert("b.txt".into());
    compare(&mut app_state);
    assert_eq!(sides(&app_state), (one.join("a.txt"), one.join("b.txt")));
    press(&mut app_state, KeyCode::Esc);
    app_state.left.selected.clear();

    // A directory is not a file to compare.
    app_state.open_dir(Side::Left, one.clone(), Some("sub".as_ref()));
    compare(&mut app_state);
    assert!(app_state.error.as_deref().is_some_and(|error| error.starts_with("Put the cursor on a file")));
    let _ = std::fs::remove_dir_all(&dir);
}

/// Ctrl+Shift+F5 links the entry under the cursor into the other panel,
/// under its own name or one typed; several selected get one each, and one
/// already there is named while the rest are still made.
#[cfg(unix)]
#[test]
fn symlinks_from_the_keys() {
    let dir = std::env::temp_dir().join(format!("fm84-symlink-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let (src, dst) = (dir.join("src"), dir.join("dst"));
    std::fs::create_dir_all(src.join("sub")).unwrap();
    std::fs::create_dir_all(&dst).unwrap();
    for name in ["a.txt", "b.txt"] {
        std::fs::write(src.join(name), name).unwrap();
    }
    let mut app_state = AppState::new();
    app_state.open_dir(Side::Right, dst.clone(), None);
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, src.clone(), Some("a.txt".as_ref()));
    let link = |app_state: &mut AppState| handle_key(app_state, KeyEvent::new(KeyCode::F(5), KeyModifiers::CONTROL | KeyModifiers::SHIFT));
    let typed = |app_state: &mut AppState| app_state.dialog_input().unwrap().text.clone();

    link(&mut app_state);
    assert_eq!(typed(&mut app_state), dst.join("a.txt").to_string_lossy());
    press(&mut app_state, KeyCode::Enter);
    assert!(app_state.dialog.is_none() && app_state.error.is_none());
    assert_eq!(std::fs::read_link(dst.join("a.txt")).unwrap(), src.join("a.txt"));
    let cursor = app_state.right.state.selected().map(|index| app_state.right.children[index].name_os.clone());
    assert_eq!(cursor.as_deref(), Some("a.txt".as_ref()), "the other panel lands on the new link");

    // Again: refused, nothing written over.
    link(&mut app_state);
    press(&mut app_state, KeyCode::Enter);
    assert!(app_state.error.as_deref().is_some_and(|error| error.starts_with("Cannot link") && error.contains("already exists")));
    app_state.error = None;

    // A bare name is made beside the original.
    link(&mut app_state);
    app_state.dialog_input().unwrap().set("alias".to_string());
    press(&mut app_state, KeyCode::Enter);
    assert_eq!(std::fs::read_link(src.join("alias")).unwrap(), src.join("a.txt"));

    // A lone directory is named, not gone into.
    app_state.open_dir(Side::Left, src.clone(), Some("sub".as_ref()));
    link(&mut app_state);
    assert_eq!(typed(&mut app_state), dst.join("sub").to_string_lossy());
    press(&mut app_state, KeyCode::Enter);
    assert_eq!(std::fs::read_link(dst.join("sub")).unwrap(), src.join("sub"));

    // Several: into the directory, one already there passed over.
    app_state.left.selected.insert("a.txt".into());
    app_state.left.selected.insert("b.txt".into());
    link(&mut app_state);
    assert!(typed(&mut app_state).ends_with(std::path::MAIN_SEPARATOR));
    press(&mut app_state, KeyCode::Enter);
    assert!(app_state.error.as_deref().is_some_and(|error| error.starts_with("Could not link 1 of 2")));
    assert_eq!(std::fs::read_link(dst.join("b.txt")).unwrap(), src.join("b.txt"));

    // Esc leaves it be.
    app_state.error = None;
    app_state.left.selected.clear();
    app_state.open_dir(Side::Left, src.clone(), Some("b.txt".as_ref()));
    link(&mut app_state);
    app_state.dialog_input().unwrap().set("never".to_string());
    press(&mut app_state, KeyCode::Esc);
    assert!(app_state.dialog.is_none() && !crate::fs_ops::path_exists(&src.join("never")));

    // Alt+F5 does the same.
    handle_key(&mut app_state, KeyEvent::new(KeyCode::F(5), KeyModifiers::ALT));
    assert!(matches!(app_state.dialog, Some(Dialog::Symlink { .. })));
    press(&mut app_state, KeyCode::Esc);

    // Ctrl+F5 alone still sorts.
    handle_key(&mut app_state, KeyEvent::new(KeyCode::F(5), KeyModifiers::CONTROL));
    assert!(app_state.dialog.is_none());
    let _ = std::fs::remove_dir_all(&dir);
}

/// Tab turns Alt+F5's symbolic link into a hard link: another name for the
/// same file, which outlives the original. A directory is refused and named,
/// and the files beside it are still linked.
#[cfg(unix)]
#[test]
fn tab_makes_a_hard_link_instead() {
    use std::os::unix::fs::MetadataExt;
    let dir = std::env::temp_dir().join(format!("fm84-hard-link-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let (src, dst) = (dir.join("src"), dir.join("dst"));
    std::fs::create_dir_all(src.join("sub")).unwrap();
    std::fs::create_dir_all(&dst).unwrap();
    for name in ["a.txt", "b.txt"] {
        std::fs::write(src.join(name), name).unwrap();
    }
    let mut app_state = AppState::new();
    app_state.open_dir(Side::Right, dst.clone(), None);
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, src.clone(), Some("a.txt".as_ref()));
    let link = |app_state: &mut AppState| handle_key(app_state, KeyEvent::new(KeyCode::F(5), KeyModifiers::ALT));
    let hard = |app_state: &AppState| matches!(app_state.dialog, Some(Dialog::Symlink { hard: true, .. }));
    let inode = |path: &std::path::Path| std::fs::symlink_metadata(path).unwrap().ino();

    link(&mut app_state);
    assert!(!hard(&app_state));
    press(&mut app_state, KeyCode::Tab);
    assert!(hard(&app_state));
    press(&mut app_state, KeyCode::Enter);
    assert!(app_state.dialog.is_none() && app_state.error.is_none());
    assert!(!std::fs::symlink_metadata(dst.join("a.txt")).unwrap().file_type().is_symlink());
    assert_eq!(inode(&dst.join("a.txt")), inode(&src.join("a.txt")));
    std::fs::remove_file(src.join("a.txt")).unwrap();
    assert_eq!(std::fs::read_to_string(dst.join("a.txt")).unwrap(), "a.txt");

    // Tab again goes back to a symbolic link, and each dialog starts as one.
    link(&mut app_state);
    press(&mut app_state, KeyCode::Tab);
    press(&mut app_state, KeyCode::Tab);
    assert!(!hard(&app_state));
    press(&mut app_state, KeyCode::Esc);

    // A directory among files: passed over and named.
    app_state.reload_panel(Side::Left, None);
    app_state.left.selected.insert("b.txt".into());
    app_state.left.selected.insert("sub".into());
    link(&mut app_state);
    press(&mut app_state, KeyCode::Tab);
    press(&mut app_state, KeyCode::Enter);
    assert!(app_state.error.as_deref().is_some_and(|error| error.starts_with("Could not link 1 of 2") && error.contains("directory")), "{:?}", app_state.error);
    assert_eq!(inode(&dst.join("b.txt")), inode(&src.join("b.txt")));
    assert!(!crate::fs_ops::path_exists(&dst.join("sub")));

    // Of a relative symlink: the file it points at, not a second symlink
    // that would point at nothing from where it is.
    std::fs::create_dir_all(src.join("sub")).unwrap();
    std::os::unix::fs::symlink("../b.txt", src.join("sub/to-b")).unwrap();
    crate::fs_ops::create_hard_link(&src.join("sub/to-b"), &dst.join("to-b"), false).unwrap();
    assert!(!std::fs::symlink_metadata(dst.join("to-b")).unwrap().file_type().is_symlink());
    assert_eq!(inode(&dst.join("to-b")), inode(&src.join("b.txt")));
    // One that points at nothing is refused.
    std::os::unix::fs::symlink("gone", src.join("dangling")).unwrap();
    assert!(crate::fs_ops::create_hard_link(&src.join("dangling"), &dst.join("dangling"), false).is_err());
    assert!(!crate::fs_ops::path_exists(&dst.join("dangling")));
    let _ = std::fs::remove_dir_all(&dir);
}

/// Alt+A opens on what the entries have in common; what is typed over it
/// is applied to each, and what cannot be read leaves the form open.
#[cfg(unix)]
#[test]
fn attributes_change_from_the_keys() {
    use std::os::unix::fs::PermissionsExt;
    let dir = std::env::temp_dir().join(format!("fm84-alt-a-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    for (name, mode) in [("a.txt", 0o644), ("b.txt", 0o600)] {
        std::fs::write(dir.join(name), "").unwrap();
        std::fs::set_permissions(dir.join(name), std::fs::Permissions::from_mode(mode)).unwrap();
    }
    let mode = |name: &str| std::fs::metadata(dir.join(name)).unwrap().permissions().mode() & 0o7777;
    let mut app_state = AppState::new();
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, dir.clone(), Some("a.txt".as_ref()));
    let alt_a = |app_state: &mut AppState| handle_key(app_state, KeyEvent::new(KeyCode::Char('a'), KeyModifiers::ALT));
    let fields = |app_state: &AppState| match &app_state.dialog {
        Some(Dialog::Attributes(form)) => form.fields.iter().map(|field| field.input.text.clone()).collect::<Vec<_>>(),
        _ => panic!("not open"),
    };
    let retype = |app_state: &mut AppState, text: &str| {
        app_state.dialog_input().unwrap().set(text.to_string());
    };

    alt_a(&mut app_state);
    let opened = fields(&app_state);
    assert_eq!(opened[0], "644");
    assert_eq!(opened[1], crate::fs_ops::user_name(unsafe { libc::getuid() }));
    retype(&mut app_state, "u+x");
    press(&mut app_state, KeyCode::Enter);
    assert!(app_state.dialog.is_none() && app_state.error.is_none());
    assert_eq!(mode("a.txt"), 0o744);

    // Two that differ: the mode opens empty, and stays as it is.
    app_state.left.selected.insert("a.txt".into());
    app_state.left.selected.insert("b.txt".into());
    alt_a(&mut app_state);
    assert_eq!(fields(&app_state)[0], "");
    press(&mut app_state, KeyCode::BackTab);
    retype(&mut app_state, "2001-02-03 04:05:06");
    press(&mut app_state, KeyCode::Enter);
    let then = crate::attributes::parse_time("2001-02-03 04:05:06").unwrap();
    for name in ["a.txt", "b.txt"] {
        assert_eq!(std::fs::metadata(dir.join(name)).unwrap().modified().unwrap(), then);
    }
    assert_eq!((mode("a.txt"), mode("b.txt")), (0o744, 0o600));

    // A click on a field takes the keys there, the cursor where it
    // landed; one on the rest of the popup does nothing.
    alt_a(&mut app_state);
    let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
    crate::ui::render_ui(&mut terminal, &mut app_state);
    let click = |app_state: &mut AppState, column, row| {
        crate::input::mouse_to(
            app_state,
            crossterm::event::MouseEvent {
                kind: crossterm::event::MouseEventKind::Down(crossterm::event::MouseButton::Left),
                column,
                row,
                modifiers: KeyModifiers::NONE,
            },
        );
    };
    let (group_row, text_x) = app_state.drawn.attribute_rows[2];
    click(&mut app_state, text_x + 1, group_row.y);
    let focus = |app_state: &AppState| match &app_state.dialog {
        Some(Dialog::Attributes(form)) => (form.focus, form.fields[form.focus].input.cursor),
        _ => panic!("not open"),
    };
    assert_eq!(focus(&app_state), (2, 1));
    let (modified_row, _) = app_state.drawn.attribute_rows[3];
    click(&mut app_state, modified_row.right() - 1, modified_row.y);
    assert_eq!(focus(&app_state), (3, "2001-02-03 04:05:06".len()));
    // Above the first field: the line naming what is changed, or a blank
    // row, whichever the popup's width leaves there.
    let (mode_row, _) = app_state.drawn.attribute_rows[0];
    click(&mut app_state, mode_row.x, mode_row.y - 1);
    assert_eq!(focus(&app_state).0, 3);
    press(&mut app_state, KeyCode::Esc);

    // Not a mode: said so, and the form is still there to fix.
    alt_a(&mut app_state);
    retype(&mut app_state, "u+q");
    press(&mut app_state, KeyCode::Enter);
    assert!(app_state.error.is_some() && matches!(app_state.dialog, Some(Dialog::Attributes(_))));
    press(&mut app_state, KeyCode::Esc);
    // Drawn, then put away.
    let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
    crate::ui::render_ui(&mut terminal, &mut app_state);
    press(&mut app_state, KeyCode::Esc);
    assert!(app_state.dialog.is_none());

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

#[test]
fn a_typed_path_starts_from_the_panel_or_from_home() {
    let base = std::path::Path::new("/panel/dir");
    let home = std::env::home_dir().unwrap_or_default();
    assert_eq!(crate::input::typed_path("/abs/x", base), std::path::Path::new("/abs/x"));
    assert_eq!(crate::input::typed_path("x", base), base.join("x"));
    assert_eq!(crate::input::typed_path("sub/x", base), base.join("sub/x"));
    assert_eq!(crate::input::typed_path("~", base), home);
    assert_eq!(crate::input::typed_path("~/x", base), home.join("x"));
    // Only a `~` that stands for home: one starting a name is the name.
    assert_eq!(crate::input::typed_path("~x", base), base.join("~x"));
}

/// F5 and F6 go where the field says. A single file opens on its path in
/// the other panel, anything else on the other panel's directory, and
/// either goes there when it is left as it opened. A name edited in
/// renames it on the way, and a bare one puts it beside the original. Y
/// and N are typed, not taken for an answer.
#[test]
fn copy_and_move_go_where_the_destination_says() {
    let dir = std::env::temp_dir().join(format!("fm84-dest-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let (left, right) = (dir.join("left"), dir.join("right"));
    std::fs::create_dir_all(&left).unwrap();
    std::fs::create_dir_all(&right).unwrap();
    std::fs::write(left.join("a.txt"), "a").unwrap();
    std::fs::write(left.join("z.txt"), "z").unwrap();
    std::fs::create_dir(left.join("sub")).unwrap();

    let mut app_state = AppState::new();
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Right, right.clone(), None);
    let on_a = |app_state: &mut AppState| {
        app_state.open_dir(Side::Left, left.clone(), Some("a.txt".as_ref()));
    };
    let finish = |app_state: &mut AppState| {
        let started = std::time::Instant::now();
        while app_state.workers.job.is_some() {
            assert!(started.elapsed() < std::time::Duration::from_secs(10), "the job never finished");
            std::thread::sleep(std::time::Duration::from_millis(5));
            app_state.poll_transfer();
        }
    };
    let type_in = |app_state: &mut AppState, text: &str| {
        app_state.dialog_input().unwrap().set(text.to_string());
        press(app_state, KeyCode::Enter);
    };

    // A single file opens on its path in the other panel, and Enter alone
    // copies it there.
    on_a(&mut app_state);
    press(&mut app_state, KeyCode::F(5));
    assert_eq!(std::path::PathBuf::from(&app_state.dialog_input().unwrap().text), right.join("a.txt"));
    press(&mut app_state, KeyCode::Enter);
    finish(&mut app_state);
    assert_eq!(std::fs::read_to_string(right.join("a.txt")).unwrap(), "a");

    // Again, onto the copy now there: the job stops to ask about it, and
    // Esc leaves it as it was.
    on_a(&mut app_state);
    press(&mut app_state, KeyCode::F(5));
    press(&mut app_state, KeyCode::Enter);
    let started = std::time::Instant::now();
    while !app_state.workers.job.as_ref().is_some_and(|job| job.clash.is_some()) {
        assert!(started.elapsed() < std::time::Duration::from_secs(10), "never asked");
        std::thread::sleep(std::time::Duration::from_millis(5));
        app_state.poll_transfer();
    }
    press(&mut app_state, KeyCode::Esc);
    finish(&mut app_state);
    assert!(app_state.error.as_deref().is_some_and(|error| error.starts_with("Copy cancelled")), "{:?}", app_state.error);
    assert_eq!(std::fs::read_to_string(right.join("a.txt")).unwrap(), "a");
    app_state.reset_error();

    // Again, and K keeps both: the question offers it, and the copy goes in
    // beside the one there.
    std::fs::write(right.join("a.txt"), "theirs").unwrap();
    on_a(&mut app_state);
    press(&mut app_state, KeyCode::F(5));
    press(&mut app_state, KeyCode::Enter);
    let started = std::time::Instant::now();
    while !app_state.workers.job.as_ref().is_some_and(|job| job.clash.is_some()) {
        assert!(started.elapsed() < std::time::Duration::from_secs(10), "never asked");
        std::thread::sleep(std::time::Duration::from_millis(5));
        app_state.poll_transfer();
    }
    // Drawn once the job has run long enough to be worth showing.
    app_state.workers.job.as_mut().unwrap().started -= std::time::Duration::from_secs(5);
    let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(120, 40)).unwrap();
    crate::ui::render_ui(&mut terminal, &mut app_state);
    let screen: String = terminal.backend().buffer().content().iter().map(|cell| cell.symbol()).collect();
    assert!(screen.contains("K - Keep both") && screen.contains("B - Keep both all"), "not offered");
    press(&mut app_state, KeyCode::Char('k'));
    finish(&mut app_state);
    assert_eq!(app_state.error, None);
    assert_eq!(std::fs::read_to_string(right.join("a.txt")).unwrap(), "theirs");
    assert_eq!(std::fs::read_to_string(right.join("a (2).txt")).unwrap(), "a");
    std::fs::remove_file(right.join("a (2).txt")).unwrap();
    std::fs::write(right.join("a.txt"), "a").unwrap();

    // The name edited, one key at a time.
    on_a(&mut app_state);
    press(&mut app_state, KeyCode::F(5));
    for _ in "a.txt".chars() {
        press(&mut app_state, KeyCode::Backspace);
    }
    for c in "b.txt".chars() {
        press(&mut app_state, KeyCode::Char(c));
    }
    press(&mut app_state, KeyCode::Enter);
    finish(&mut app_state);
    assert!(right.join("b.txt").exists());

    // N is typed into the field, and Esc leaves it.
    on_a(&mut app_state);
    press(&mut app_state, KeyCode::F(5));
    press(&mut app_state, KeyCode::Char('n'));
    assert!(app_state.dialog_input().unwrap().text.ends_with('n'));
    press(&mut app_state, KeyCode::Esc);
    assert!(app_state.dialog.is_none() && app_state.workers.job.is_none());

    // A bare name is beside the original.
    on_a(&mut app_state);
    press(&mut app_state, KeyCode::F(5));
    type_in(&mut app_state, "dup.txt");
    finish(&mut app_state);
    assert_eq!(std::fs::read_to_string(left.join("dup.txt")).unwrap(), "a");

    // F6 to a new name in the same place is a rename.
    on_a(&mut app_state);
    press(&mut app_state, KeyCode::F(6));
    type_in(&mut app_state, "moved.txt");
    finish(&mut app_state);
    assert!(!left.join("a.txt").exists() && left.join("moved.txt").exists());

    // A directory in the way of a file is refused, not copied into, when
    // the field is left as it opened.
    std::fs::create_dir(right.join("z.txt")).unwrap();
    app_state.open_dir(Side::Left, left.clone(), Some("z.txt".as_ref()));
    press(&mut app_state, KeyCode::F(5));
    press(&mut app_state, KeyCode::Enter);
    assert!(app_state.error.as_deref().is_some_and(|error| error.contains("Cannot replace directory")), "{:?}", app_state.error);
    assert!(!right.join("z.txt").join("z.txt").exists());
    app_state.reset_error();

    // A directory, and several entries, open on the other panel's
    // directory alone.
    let opened_on_directory = |app_state: &mut AppState| {
        let text = app_state.dialog_input().unwrap().text.clone();
        std::path::Path::new(&text) == right && text.ends_with(std::path::MAIN_SEPARATOR)
    };
    app_state.open_dir(Side::Left, left.clone(), Some("sub".as_ref()));
    press(&mut app_state, KeyCode::F(5));
    assert!(opened_on_directory(&mut app_state));
    press(&mut app_state, KeyCode::Esc);
    app_state.open_dir(Side::Left, left.clone(), None);
    app_state.left.selected.extend(["dup.txt".into(), "z.txt".into()]);
    press(&mut app_state, KeyCode::F(5));
    assert!(opened_on_directory(&mut app_state));

    // And several cannot share one name.
    type_in(&mut app_state, "one.txt");
    assert!(app_state.error.as_deref().is_some_and(|error| error.contains("2 items need a directory")), "{:?}", app_state.error);
    assert!(!left.join("one.txt").exists());

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

/// The other panel on its way to a directory slow to read: F5 offers the
/// one it is going to, not the one it is leaving.
#[test]
fn a_copy_goes_where_the_other_panel_is_going() {
    let dir = std::env::temp_dir().join(format!("fm84-copy-pending-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    for sub in ["from", "leaving", "going"] {
        std::fs::create_dir_all(dir.join(sub)).unwrap();
    }
    std::fs::write(dir.join("from").join("a.txt"), "").unwrap();
    let mut app_state = AppState::new();
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, dir.join("from"), Some("a.txt".as_ref()));
    app_state.open_dir(Side::Right, dir.join("leaving"), None);
    app_state.right.listing = Some(crate::app::PendingListing::going_to(dir.join("going")));

    press(&mut app_state, KeyCode::F(5));
    assert_eq!(std::path::PathBuf::from(&app_state.dialog_input().unwrap().text), dir.join("going").join("a.txt"));
    std::fs::remove_dir_all(&dir).unwrap();
}

/// Tab on the pack dialog: whatever case the ending is in, and whatever
/// comes before it, even a character whose lower case is shorter.
#[test]
fn the_pack_format_goes_round_by_its_ending() {
    use super::super::file_ops::next_pack_format;
    assert_eq!(next_pack_format("a.ZIP"), "a.7z");
    assert_eq!(next_pack_format("a.TAR.GZ"), "a.tar.xz");
    assert_eq!(next_pack_format("a.tar"), "a.zip");
    assert_eq!(next_pack_format("plain"), "plain.zip");
    // The Kelvin sign is three bytes, and its lower case one.
    assert_eq!(next_pack_format("\u{212A}.zip"), "\u{212A}.7z");
    assert_eq!(next_pack_format("x\u{212A}"), "x\u{212A}.zip");
}

/// Alt+H works out a file's SHA-256 and shows it; C copies the checksum
/// alone, Tab goes on to SHA-512 - drawn whole, however long - and W writes
/// it beside the file and lands there. On a selection it writes SHA256SUMS,
/// and on that, checks it - saying what fails.
#[test]
fn alt_h_works_out_writes_and_checks_checksums() {
    use crate::app::ChecksumView;
    use crate::checksum::Report;
    let dir = std::env::temp_dir().join(format!("fm84-alt-h-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(dir.join("photos")).unwrap();
    std::fs::write(dir.join("notes.txt"), "abc").unwrap();
    std::fs::write(dir.join("photos/a.jpg"), "a").unwrap();
    let mut app_state = AppState::new();
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, dir.clone(), Some("notes.txt".as_ref()));
    let alt_h = |app_state: &mut AppState| handle_key(app_state, KeyEvent::new(KeyCode::Char('h'), KeyModifiers::ALT));
    let finish = |app_state: &mut AppState| {
        let started = std::time::Instant::now();
        while app_state.workers.job.is_some() {
            assert!(started.elapsed() < std::time::Duration::from_secs(10), "the job never finished");
            std::thread::sleep(std::time::Duration::from_millis(5));
            app_state.poll_transfer();
        }
    };
    fn report(app_state: &AppState) -> &ChecksumView {
        match &app_state.dialog {
            Some(Dialog::Checksums(view)) => view,
            _ => panic!("no report: {:?}", app_state.error),
        }
    }

    alt_h(&mut app_state);
    finish(&mut app_state);
    assert_eq!(report(&app_state).report.lines(), ["ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad  notes.txt"]);
    press(&mut app_state, KeyCode::Char('c'));
    assert_eq!(app_state.clipboard, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");

    // All worked out already: Tab changes what is shown in place, with no
    // job and the same popup, and Shift+Tab or Left goes back.
    press(&mut app_state, KeyCode::Tab);
    assert!(app_state.workers.job.is_none());
    press(&mut app_state, KeyCode::BackTab);
    assert_eq!(report(&app_state).report.shown(), Some(crate::checksum::Algorithm::Sha256));
    press(&mut app_state, KeyCode::Left);
    assert_eq!(report(&app_state).report.shown(), Some(crate::checksum::Algorithm::Md5));
    press(&mut app_state, KeyCode::Char('c'));
    assert_eq!(app_state.clipboard, "900150983cd24fb0d6963f7d28e17f72");
    press(&mut app_state, KeyCode::Right);
    press(&mut app_state, KeyCode::Tab);
    let sha512 = "ddaf35a193617abacc417349ae20413112e6fa4e89a97ea20a9eeee64b55d39a2192992a274fc1a836ba3c23a3feebbd454d4423643ce80e2a9ac94fa54ca49f";
    assert!(matches!(
        &report(&app_state).report,
        Report::Computed {
            algorithm: crate::checksum::Algorithm::Sha512,
            ..
        }
    ));
    let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
    crate::ui::render_ui(&mut terminal, &mut app_state);
    let screen: String = terminal.backend().buffer().content().iter().map(|cell| cell.symbol()).collect();
    // Wrapped at the popup's width - 60% of 100 columns, less its border
    // and margin - and drawn whole, a piece to a row.
    for piece in sha512.as_bytes().chunks(56) {
        assert!(screen.contains(std::str::from_utf8(piece).unwrap()), "{} not drawn", std::str::from_utf8(piece).unwrap());
    }
    for part in [" SHA-256 ", " SHA-512 ", " MD5 ", "Enter - Write", "Tab - Algorithm", "Esc - Close"] {
        assert!(screen.contains(part), "{part} not drawn");
    }
    // One size whatever is shown: as wide as every popup, as tall as the
    // larger ones - the same with SHA-512's long rows as with MD5's short
    // ones, and with one file as with several.
    fn popup_box(app_state: &mut AppState) -> (u16, u16, u16, u16) {
        let mut terminal = ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 30)).unwrap();
        crate::ui::render_ui(&mut terminal, app_state);
        let buffer = terminal.backend().buffer();
        let row = |y: u16| (0..100).map(|x| buffer[(x, y)].symbol().to_string()).collect::<String>();
        let top = (0..30).find(|&y| row(y).contains(" Checksums ")).expect("no popup");
        let left = (1..100).find(|&x| buffer[(x, top)].symbol() == "┌").unwrap();
        let right = (left..100).find(|&x| buffer[(x, top)].symbol() == "┐").unwrap();
        let bottom = (top..30).find(|&y| buffer[(left, y)].symbol() == "└").unwrap();
        (left, top, right - left + 1, bottom - top + 1)
    }
    let sized = popup_box(&mut app_state);
    assert_eq!(sized.2, 60, "not the width every popup has");
    assert_eq!(sized.3, 30 * 60 / 100);
    for _ in 0..3 {
        press(&mut app_state, KeyCode::Tab);
        assert_eq!(popup_box(&mut app_state), sized);
    }
    press(&mut app_state, KeyCode::Enter);
    assert!(app_state.dialog.is_none());
    assert_eq!(std::fs::read_to_string(dir.join("notes.txt.sha512")).unwrap(), format!("{sha512}  notes.txt\n"));
    assert_eq!(app_state.left.children[app_state.left.state.selected().unwrap()].name_full, "notes.txt.sha512");

    // Several, a directory's files among them: SHA256SUMS, checked after.
    app_state.left.selected.extend(["notes.txt", "photos"].map(std::ffi::OsString::from));
    alt_h(&mut app_state);
    finish(&mut app_state);
    assert_eq!(report(&app_state).report.summary(), "2 files");
    assert_eq!(popup_box(&mut app_state), sized);
    press(&mut app_state, KeyCode::Enter);
    app_state.left.selected.clear();
    alt_h(&mut app_state);
    finish(&mut app_state);
    assert_eq!(report(&app_state).report.summary(), "2 OK");
    press(&mut app_state, KeyCode::Esc);
    std::fs::write(dir.join("photos/a.jpg"), "changed").unwrap();
    alt_h(&mut app_state);
    finish(&mut app_state);
    assert_eq!(report(&app_state).report.summary(), "1 OK, 1 FAILED");
    assert_eq!(report(&app_state).report.lines()[0], "FAILED   photos/a.jpg");
    // A check has nothing to write: Enter only closes it.
    let before: Vec<_> = std::fs::read_dir(&dir).unwrap().map(|entry| entry.unwrap().file_name()).collect();
    press(&mut app_state, KeyCode::Enter);
    assert!(app_state.dialog.is_none());
    assert_eq!(std::fs::read_dir(&dir).unwrap().count(), before.len());
    std::fs::remove_dir_all(&dir).unwrap();
}

/// Alt+M's commands run in the shell on what is chosen, every name reaching
/// them whole - spaces, quotes, a dollar sign - in the panel's directory.
/// One that names an entry is refused with nothing to name.
#[cfg(unix)]
#[test]
fn user_menu_commands_get_every_name_whole() {
    let dir = std::env::temp_dir().join(format!("fm84-user-menu-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    let (here, other) = (dir.join("here"), dir.join("other side"));
    std::fs::create_dir_all(&here).unwrap();
    std::fs::create_dir_all(&other).unwrap();
    let awkward = ["it's a file.txt", "$HOME and \"quotes\"", "-n"];
    for name in awkward {
        std::fs::write(here.join(name), "").unwrap();
    }
    let mut app_state = AppState::new();
    app_state.open_dir(Side::Right, other.clone(), None);
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, here.clone(), Some(awkward[0].as_ref()));
    let menu = |command: &str| {
        Dialog::UserMenu(Box::new(crate::app::UserMenu {
            entries: vec![crate::options::MenuEntry {
                label: "Test".to_string(),
                command: command.to_string(),
            }],
            index: 0,
            file: None,
        }))
    };
    let run = |app_state: &mut AppState, key: KeyCode| {
        press(app_state, key);
        let mut command = app_state.user_command.take().expect("nothing to run");
        assert!(command.process.status().unwrap().success());
    };
    let out = dir.join("out");

    for name in &awkward[1..] {
        app_state.left.selected.insert((*name).into());
    }
    app_state.dialog = Some(menu(&format!(
        "for f in {{files}}; do printf '%s\\n' \"$f\"; done > '{}'; printf '%s|%s|%s|%s' {{name}} {{dir}} {{other}} $PWD >> '{}'",
        out.display(),
        out.display()
    )));
    run(&mut app_state, KeyCode::Enter);
    let written = std::fs::read_to_string(&out).unwrap();
    let mut lines: Vec<&str> = written.lines().collect();
    let last = lines.pop().unwrap();
    let mut chosen: Vec<String> = lines.iter().map(|line| line.to_string()).collect();
    chosen.sort();
    let mut expected: Vec<String> = awkward[1..].iter().map(|name| here.join(name).display().to_string()).collect();
    expected.sort();
    assert_eq!(chosen, expected);
    assert_eq!(last, format!("{}|{}|{}|{}", awkward[0], here.display(), other.display(), here.display()));

    // 1 to 9 run one straight away.
    app_state.dialog = Some(menu(&format!("touch {{file}}.done && mv {{file}}.done '{}'", out.display())));
    run(&mut app_state, KeyCode::Char('1'));
    assert!(out.exists() && !here.join(format!("{}.done", awkward[0])).exists());

    // On .. with nothing selected, there is no entry to name.
    app_state.left.selected.clear();
    app_state.left.state.select(Some(0));
    app_state.dialog = Some(menu("echo {file}"));
    press(&mut app_state, KeyCode::Enter);
    assert!(app_state.user_command.is_none());
    assert!(app_state.error.as_deref().is_some_and(|error| error.contains("Nothing chosen")));
    app_state.error = None;
    // A command that names none runs anywhere.
    app_state.dialog = Some(menu("true"));
    run(&mut app_state, KeyCode::Enter);
    // {} is the shell's, as find -exec has it, and stands for no file.
    app_state.dialog = Some(menu(&format!("printf '%s' {{}} > '{}'", out.display())));
    run(&mut app_state, KeyCode::Enter);
    assert_eq!(std::fs::read_to_string(&out).unwrap(), "{}");
    std::fs::remove_dir_all(&dir).unwrap();
}

#[cfg(unix)]
#[test]
fn alt_o_opens_a_file_with_the_program_picked() {
    use crate::opener::{Launch, Opener};
    let dir = std::env::temp_dir().join(format!("fm84-open-with-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    let name = "it's a \"file\".txt";
    let file = dir.join(name);
    std::fs::write(&file, "").unwrap();
    let out = dir.join("out");
    let mut app_state = AppState::new();
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, dir.clone(), Some(name.as_ref()));
    let alt_o = |app_state: &mut AppState| handle_key(app_state, KeyEvent::new(KeyCode::Char('o'), KeyModifiers::ALT));

    // The chooser ends with the system's own choice.
    alt_o(&mut app_state);
    let Some(Dialog::OpenWith(menu)) = &app_state.dialog else { panic!("no chooser") };
    assert_eq!(menu.path, file);
    assert_eq!(menu.openers.last().map(|opener| &opener.launch), Some(&Launch::Default));
    press(&mut app_state, KeyCode::Esc);
    assert!(app_state.dialog.is_none());

    let chooser = |openers: Vec<Opener>| Dialog::OpenWith(Box::new(crate::app::OpenWith { path: file.clone(), openers, index: 0 }));
    let shell = |command: String, terminal: bool| Opener {
        label: "Test".to_string(),
        detail: command.clone(),
        launch: Launch::Shell(command),
        terminal,
    };

    // In the terminal: handed to the main loop, which waits only on a failure.
    // The file goes on the end of a command that does not say where.
    app_state.dialog = Some(chooser(vec![shell(format!("printf '%s' > '{}'", out.display()), true)]));
    press(&mut app_state, KeyCode::Enter);
    let mut command = app_state.user_command.take().expect("nothing to run");
    assert!(!command.pause);
    assert!(command.process.status().unwrap().success());
    assert_eq!(std::fs::read_to_string(&out).unwrap(), file.display().to_string());

    // A desktop entry's Exec, with its field codes - and %% for a % of its own.
    std::fs::remove_file(&out).unwrap();
    let words = ["sh", "-c", &format!("printf '%%s|%%s' \"$1\" \"$2\" > '{}'", out.display()), "sh", "%c", "%f"].map(String::from).to_vec();
    let desktop = Opener {
        label: "Viewer".to_string(),
        detail: String::new(),
        launch: Launch::Desktop {
            words,
            name: "Viewer".to_string(),
            icon: None,
            entry: dir.join("viewer.desktop"),
        },
        terminal: true,
    };
    app_state.dialog = Some(chooser(vec![shell("false".to_string(), true), desktop]));
    press(&mut app_state, KeyCode::Char('2'));
    let mut command = app_state.user_command.take().expect("nothing to run");
    assert!(command.process.status().unwrap().success());
    assert_eq!(std::fs::read_to_string(&out).unwrap(), format!("Viewer|{}", file.display()));

    // In a window of its own: started, and not waited for.
    std::fs::remove_file(&out).unwrap();
    app_state.dialog = Some(chooser(vec![shell(format!("cp {{file}} '{}'", out.display()), false)]));
    press(&mut app_state, KeyCode::Enter);
    assert!(app_state.user_command.is_none() && app_state.error.is_none());
    let start = std::time::Instant::now();
    while !out.exists() && start.elapsed() < std::time::Duration::from_secs(5) {
        std::thread::sleep(std::time::Duration::from_millis(10));
    }
    assert!(out.exists());

    // Nothing for the parent entry.
    app_state.left.state.select(Some(0));
    alt_o(&mut app_state);
    assert!(app_state.dialog.is_none());
    std::fs::remove_dir_all(&dir).unwrap();
}

#[test]
fn f2_on_a_selection_renames_every_name_by_a_pattern() {
    let dir = std::env::temp_dir().join(format!("fm84-multi-rename-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&dir);
    std::fs::create_dir_all(&dir).unwrap();
    for (name, body) in [("1.txt", "one"), ("2.txt", "two"), ("3.txt", "three"), ("keep.md", "")] {
        std::fs::write(dir.join(name), body).unwrap();
    }
    let mut app_state = AppState::new();
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, dir.clone(), Some("2.txt".as_ref()));
    let select = |app_state: &mut AppState, names: &[&str]| {
        app_state.left.selected = names.iter().map(|name| std::ffi::OsString::from(*name)).collect();
    };
    let set = |app_state: &mut AppState, field: usize, text: &str| {
        let Some(Dialog::MultiRename(rename)) = &mut app_state.dialog else { panic!("no dialog") };
        rename.fields[field].set(text.to_string());
    };
    let read = |name: &str| std::fs::read_to_string(dir.join(name)).ok();

    // Each one up by one: 3 to 4 has to go first, or 1 would land on 2.
    select(&mut app_state, &["1.txt", "2.txt", "3.txt"]);
    press(&mut app_state, KeyCode::F(2));
    assert!(matches!(app_state.dialog, Some(Dialog::MultiRename(_))));
    set(&mut app_state, 0, "[C2].[E]");
    press(&mut app_state, KeyCode::Enter);
    assert!(app_state.dialog.is_none() && app_state.error.is_none(), "{:?}", app_state.error);
    assert_eq!((read("1.txt"), read("2.txt"), read("3.txt"), read("4.txt")), (None, Some("one".into()), Some("two".into()), Some("three".into())));
    assert!(app_state.left.selected.is_empty());
    // The cursor followed its file, from 2.txt to 3.txt.
    let cursor = app_state.left.state.selected().and_then(|index| app_state.left.children.get(index)).unwrap();
    assert_eq!(cursor.name_os, "3.txt");

    // Find and replace, after the pattern.
    select(&mut app_state, &["2.txt", "3.txt"]);
    press(&mut app_state, KeyCode::F(2));
    set(&mut app_state, 0, "[N]");
    set(&mut app_state, 1, "2");
    set(&mut app_state, 2, "x");
    let Some(Dialog::MultiRename(rename)) = &app_state.dialog else { panic!() };
    assert_eq!(rename.preview().iter().map(|(name, _)| name.as_str()).collect::<Vec<_>>(), ["x", "3"]);
    press(&mut app_state, KeyCode::Esc);

    // Onto a name something not being renamed has: refused, nothing moved,
    // the dialog left open to fix it.
    select(&mut app_state, &["3.txt", "4.txt"]);
    press(&mut app_state, KeyCode::F(2));
    set(&mut app_state, 0, "[N]");
    set(&mut app_state, 1, "4");
    set(&mut app_state, 2, "keep.md");
    {
        let Some(Dialog::MultiRename(rename)) = &app_state.dialog else { panic!() };
        let problems: Vec<_> = rename.preview().into_iter().map(|(_, problem)| problem).collect();
        assert_eq!(problems, [None, Some(crate::app::RenameProblem::Taken)]);
    }
    press(&mut app_state, KeyCode::Enter);
    assert!(app_state.error.is_some() && matches!(app_state.dialog, Some(Dialog::MultiRename(_))));
    assert_eq!(read("4.txt"), Some("three".into()));
    app_state.error = None;

    // Both to one name.
    set(&mut app_state, 0, "same");
    set(&mut app_state, 1, "");
    {
        let Some(Dialog::MultiRename(rename)) = &app_state.dialog else { panic!() };
        assert!(rename.preview().iter().all(|(_, problem)| *problem == Some(crate::app::RenameProblem::Twice)));
    }

    // The case, from its own row: Up from the name goes round to it.
    set(&mut app_state, 0, "[N].[E]");
    press(&mut app_state, KeyCode::Up);
    press(&mut app_state, KeyCode::Right);
    press(&mut app_state, KeyCode::Right);
    press(&mut app_state, KeyCode::Enter);
    assert!(app_state.error.is_none(), "{:?}", app_state.error);
    assert_eq!((read("3.TXT"), read("4.TXT")), (Some("two".into()), Some("three".into())));

    // Without a selection F2 still renames in place.
    app_state.left.selected.clear();
    press(&mut app_state, KeyCode::F(2));
    assert!(matches!(app_state.dialog, Some(Dialog::Rename(_))));
    std::fs::remove_dir_all(&dir).unwrap();
}

/// Alt+S compares the panels all the way down, offers each difference the
/// way its newer side says, takes changes to the plan, and runs it as one
/// job - asking a second Enter before it deletes.
#[test]
fn alt_s_synchronizes_the_panels() {
    use crate::app::SyncAction;
    use std::time::{Duration, SystemTime};
    let root = std::env::temp_dir().join(format!("fm84-sync-keys-{}", std::process::id()));
    let _ = std::fs::remove_dir_all(&root);
    let (left, right) = (root.join("left"), root.join("right"));
    let write = |path: std::path::PathBuf, body: &str, age: u64| {
        std::fs::create_dir_all(path.parent().unwrap()).unwrap();
        std::fs::write(&path, body).unwrap();
        std::fs::File::options().write(true).open(&path).unwrap().set_modified(SystemTime::now() - Duration::from_secs(age)).unwrap();
    };
    write(left.join("a.txt"), "new left", 10);
    write(right.join("a.txt"), "old right", 1000);
    write(left.join("sub/b.txt"), "old left", 1000);
    write(right.join("sub/b.txt"), "new right", 10);
    write(left.join("only-left/c.txt"), "c", 10);
    write(right.join("only-right.txt"), "r", 10);
    write(right.join("stray.txt"), "s", 10);
    write(left.join("same-age.txt"), "four", 50);
    write(right.join("same-age.txt"), "three", 50);

    let mut app_state = AppState::new();
    app_state.options = crate::options::Options {
        delete_to_trash: false,
        confirm_delete: true,
        ..crate::options::Options::default()
    };
    app_state.open_dir(Side::Right, right.clone(), None);
    app_state.active_side = Side::Left;
    app_state.open_dir(Side::Left, left.clone(), None);
    let alt_s = |app_state: &mut AppState| handle_key(app_state, KeyEvent::new(KeyCode::Char('s'), KeyModifiers::ALT));
    let wait = |app_state: &mut AppState| {
        let started = std::time::Instant::now();
        while !matches!(&app_state.dialog, Some(Dialog::Sync(plan)) if plan.done) {
            app_state.poll_sync();
            assert!(started.elapsed() < Duration::from_secs(10), "the compare never finished");
            std::thread::sleep(Duration::from_millis(5));
        }
    };
    let plan = |app_state: &AppState| -> Vec<(String, SyncAction)> {
        let Some(Dialog::Sync(plan)) = &app_state.dialog else { panic!("no plan") };
        plan.entries.iter().map(|entry| (entry.difference.path.to_string_lossy().replace('\\', "/"), entry.action)).collect()
    };

    alt_s(&mut app_state);
    wait(&mut app_state);
    use SyncAction::*;
    assert_eq!(
        plan(&app_state),
        [
            ("a.txt".to_string(), ToRight),
            ("only-left".into(), ToRight),
            ("only-right.txt".into(), ToLeft),
            ("same-age.txt".into(), Skip),
            ("stray.txt".into(), ToLeft),
            ("sub/b.txt".into(), ToLeft)
        ]
    );

    // On same-age.txt: ← takes the right one; on stray.txt, Delete deletes
    // it from the right, the side that has it; a file cannot be deleted
    // from both sides at once, so a.txt stays as it was.
    press(&mut app_state, KeyCode::Down);
    press(&mut app_state, KeyCode::Down);
    press(&mut app_state, KeyCode::Down);
    press(&mut app_state, KeyCode::Left);
    press(&mut app_state, KeyCode::Delete);
    press(&mut app_state, KeyCode::Home);
    press(&mut app_state, KeyCode::Delete);
    let actions: Vec<SyncAction> = plan(&app_state).into_iter().map(|(_, action)| action).collect();
    assert_eq!(actions, [ToRight, ToRight, ToLeft, ToLeft, DeleteRight, ToLeft]);

    // > mirrors the left onto the right, R puts the plan back.
    press(&mut app_state, KeyCode::Char('>'));
    let actions: Vec<SyncAction> = plan(&app_state).into_iter().map(|(_, action)| action).collect();
    assert_eq!(actions, [ToRight, ToRight, DeleteRight, ToRight, DeleteRight, ToRight]);
    press(&mut app_state, KeyCode::Char('r'));
    assert_eq!(plan(&app_state)[3].1, Skip);
    press(&mut app_state, KeyCode::End);
    press(&mut app_state, KeyCode::Up);
    press(&mut app_state, KeyCode::Delete);

    // A plan that deletes asks again; another key takes the first back.
    press(&mut app_state, KeyCode::Enter);
    assert!(matches!(&app_state.dialog, Some(Dialog::Sync(plan)) if plan.armed));
    press(&mut app_state, KeyCode::Up);
    assert!(matches!(&app_state.dialog, Some(Dialog::Sync(plan)) if !plan.armed));
    press(&mut app_state, KeyCode::Enter);
    press(&mut app_state, KeyCode::Enter);
    assert!(app_state.dialog.is_none());
    let started = std::time::Instant::now();
    while app_state.workers.job.is_some() {
        app_state.poll_transfer();
        assert!(started.elapsed() < Duration::from_secs(10), "the job never finished");
        std::thread::sleep(Duration::from_millis(5));
    }
    assert!(app_state.error.is_none(), "{:?}", app_state.error);
    let read = |path: std::path::PathBuf| std::fs::read_to_string(path).ok();
    assert_eq!(read(right.join("a.txt")).as_deref(), Some("new left"));
    assert_eq!(read(left.join("sub/b.txt")).as_deref(), Some("new right"));
    assert_eq!(read(right.join("only-left/c.txt")).as_deref(), Some("c"));
    assert_eq!(read(left.join("only-right.txt")).as_deref(), Some("r"));
    assert!(read(right.join("stray.txt")).is_none() && read(left.join("stray.txt")).is_none());
    assert_eq!((read(left.join("same-age.txt")).as_deref(), read(right.join("same-age.txt")).as_deref()), (Some("four"), Some("three")));

    // Compared again: only the one left as it was still differs.
    alt_s(&mut app_state);
    wait(&mut app_state);
    assert_eq!(plan(&app_state), [("same-age.txt".to_string(), Skip)]);
    press(&mut app_state, KeyCode::Esc);

    // Not with one directory inside the other.
    app_state.open_dir(Side::Right, left.join("sub"), None);
    alt_s(&mut app_state);
    assert!(app_state.dialog.is_none() && app_state.error.as_deref().is_some_and(|error| error.contains("inside")));
    // Nor when it is only through a link that it is.
    #[cfg(unix)]
    {
        app_state.error = None;
        std::os::unix::fs::symlink(left.join("sub"), root.join("link")).unwrap();
        app_state.open_dir(Side::Right, root.join("link"), None);
        alt_s(&mut app_state);
        assert!(app_state.dialog.is_none() && app_state.error.as_deref().is_some_and(|error| error.contains("inside")));
    }
    std::fs::remove_dir_all(&root).unwrap();
}