peter-commander 0.9.1

A terminal file manager
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
mod app;
mod bulk_rename;
mod fs_ops;
mod job;
mod logging;
mod menu;
mod pane;
mod preview;
mod state;
mod ui;

use std::env;
use std::io;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;

use anyhow::{Context, Result};
use crossterm::ExecutableCommand;
use crossterm::event::{
    self, DisableMouseCapture, EnableMouseCapture, Event, KeyCode, KeyEventKind, KeyModifiers,
    MouseButton, MouseEvent, MouseEventKind,
};
use crossterm::terminal::{
    EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode,
};
use ratatui::Terminal;
use ratatui::backend::CrosstermBackend;
use ratatui::layout::Position;
use signal_hook::consts::TERM_SIGNALS;
use signal_hook::flag;

use app::{App, Dialog, ExternalRequest, SettingItem, StartDirs};
use menu::{Action, FN_KEYS, MENU_BAR};

fn restore_terminal() {
    let _ = disable_raw_mode();
    let _ = io::stdout().execute(DisableMouseCapture);
    let _ = io::stdout().execute(LeaveAlternateScreen);
}

/// What the command line asks for, before any terminal setup.
#[derive(Debug, PartialEq, Eq)]
enum CliRequest {
    /// Start the UI, optionally in the given left/right pane directories
    /// (as typed; checked by `resolve_dir` once parsing is done).
    Run {
        left: Option<String>,
        right: Option<String>,
    },
    Version,
    Help,
    /// A usage mistake, reported with the usage text and exit code 2.
    Invalid(String),
}

/// `-V`/`-v`/`--version`/`-version` and `-h`/`--help` win wherever they
/// appear; otherwise up to two directories, for the left and right pane.
/// A bare `version` is a directory name like any other, so `pc version`
/// opens it.
fn parse_args<I: IntoIterator<Item = String>>(args: I) -> CliRequest {
    let mut dirs = Vec::new();
    let mut invalid = None;
    for arg in args {
        match arg.as_str() {
            "-V" | "-v" | "--version" | "-version" => return CliRequest::Version,
            "-h" | "--help" => return CliRequest::Help,
            option if option.len() > 1 && option.starts_with('-') => {
                invalid.get_or_insert(format!("unknown option '{option}'"));
            }
            _ => dirs.push(arg),
        }
    }
    if let Some(message) = invalid {
        return CliRequest::Invalid(message);
    }
    if dirs.len() > 2 {
        return CliRequest::Invalid(format!(
            "too many directories: expected at most 2 (left and right pane), got {}",
            dirs.len()
        ));
    }
    let mut dirs = dirs.into_iter();
    CliRequest::Run {
        left: dirs.next(),
        right: dirs.next(),
    }
}

/// Turns a directory argument into an absolute path, or says why it can't
/// be opened — checked before the terminal switches to the UI, so the
/// message lands in the shell the user typed the command in.
fn resolve_dir(arg: &str) -> std::result::Result<PathBuf, String> {
    let path = Path::new(arg);
    let resolved = path
        .canonicalize()
        .map_err(|err| format!("cannot open '{arg}': {err}"))?;
    if !resolved.is_dir() {
        return Err(format!("'{arg}' is not a directory"));
    }
    Ok(resolved)
}

fn version_text() -> String {
    format!("{} {}", env!("CARGO_PKG_NAME"), env!("CARGO_PKG_VERSION"))
}

fn usage_text() -> String {
    let name = env!("CARGO_PKG_NAME");
    format!(
        "{}\n{}\n\n\
         Usage:\n  \
         {name}                      Start with the panes as usual (below)\n  \
         {name} LEFT_DIR             Open the left pane in LEFT_DIR\n  \
         {name} LEFT_DIR RIGHT_DIR   Open the left and right pane\n  \
         {name} -h, --help           Print this help\n  \
         {name} -V, -v, --version    Print the version (-version works too)\n\n\
         As usual, the left pane starts in the current directory, or\n\
         where you left it with \"Restore last session\" (Options > Settings);\n\
         the right pane starts where you left it. First run: both in the\n\
         current directory.\n",
        version_text(),
        env!("CARGO_PKG_DESCRIPTION"),
    )
}

fn main() -> Result<()> {
    let start_dirs = match parse_args(env::args().skip(1)) {
        CliRequest::Run { left, right } => {
            let resolve = |arg: Option<String>| arg.as_deref().map(resolve_dir).transpose();
            match resolve(left).and_then(|left| {
                Ok(StartDirs {
                    left,
                    right: resolve(right)?,
                })
            }) {
                Ok(dirs) => dirs,
                Err(message) => {
                    eprintln!("error: {message}");
                    std::process::exit(2);
                }
            }
        }
        CliRequest::Version => {
            println!("{}", version_text());
            return Ok(());
        }
        CliRequest::Help => {
            print!("{}", usage_text());
            return Ok(());
        }
        CliRequest::Invalid(message) => {
            eprint!("error: {message}\n\n{}", usage_text());
            std::process::exit(2);
        }
    };

    let default_panic_hook = std::panic::take_hook();
    std::panic::set_hook(Box::new(move |info| {
        restore_terminal();
        logging::log_error(&format!("panic: {info}"));
        default_panic_hook(info);
    }));

    let should_exit = Arc::new(AtomicBool::new(false));
    // TERM_SIGNALS is itself platform-appropriate: no SIGHUP/SIGQUIT on
    // Windows, since those don't exist there.
    for &signal in TERM_SIGNALS {
        flag::register(signal, Arc::clone(&should_exit))?;
    }

    // Read directly rather than via App::new() (which happens later, inside
    // run()) so the very first frame already has mouse capture in the
    // state the user last left it in, instead of always starting enabled.
    let mouse_capture_enabled = state::load_settings()
        .get(SettingItem::MouseCapture.key())
        .copied()
        .unwrap_or(true);

    enable_raw_mode().context("enable_raw_mode")?;
    let mut stdout = io::stdout();
    stdout
        .execute(EnterAlternateScreen)
        .context("EnterAlternateScreen")?;
    if mouse_capture_enabled {
        stdout
            .execute(EnableMouseCapture)
            .context("EnableMouseCapture")?;
    }
    let backend = CrosstermBackend::new(stdout);
    let mut terminal = Terminal::new(backend).context("Terminal::new")?;

    let result = run(
        &mut terminal,
        &should_exit,
        mouse_capture_enabled,
        start_dirs,
    );

    restore_terminal();

    if let Err(err) = &result {
        logging::log_error(&format!("fatal: {err:?}"));
    }

    result
}

fn run(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    should_exit: &AtomicBool,
    mouse_capture_enabled: bool,
    start_dirs: StartDirs,
) -> Result<()> {
    let mut app = App::with_start_dirs(start_dirs)?;
    // Tracks what's actually been sent to the terminal, so a change to the
    // live "Capture mouse" setting (toggled in the Settings dialog) can be
    // applied the moment it happens, not just at the next TUI suspend.
    let mut mouse_capture_applied = mouse_capture_enabled;

    while !app.should_quit && !should_exit.load(Ordering::Relaxed) {
        if app.mouse_capture != mouse_capture_applied {
            set_mouse_capture(app.mouse_capture)?;
            mouse_capture_applied = app.mouse_capture;
        }

        terminal.draw(|frame| ui::draw(frame, &mut app))?;

        // Redraw more often while a Copy/Move is running, so its progress
        // bar moves smoothly.
        let poll_timeout = if app.job.is_some() { 100 } else { 200 };
        if event::poll(Duration::from_millis(poll_timeout))? {
            match event::read()? {
                Event::Key(key) if key.kind == KeyEventKind::Press => {
                    handle_key(&mut app, key.code, key.modifiers)?;
                }
                Event::Mouse(mouse) => handle_mouse(&mut app, mouse)?,
                _ => {}
            }
        }
        app.sync_preview_scroll();
        app.reap_finished_children();
        app.poll_job()?;

        if let Some(request) = app.external_request.take() {
            run_external(terminal, request, &mut app)?;
            // The suspend/resume path below re-applies mouse capture to
            // match `app.mouse_capture` on its own; keep this in sync so
            // the check above doesn't redundantly re-toggle it.
            mouse_capture_applied = app.mouse_capture;
        }
    }

    app.cancel_job_and_wait();
    app.save_state();
    Ok(())
}

fn set_mouse_capture(enabled: bool) -> Result<()> {
    if enabled {
        io::stdout()
            .execute(EnableMouseCapture)
            .context("EnableMouseCapture")?;
    } else {
        // Best-effort, like restore_terminal()'s disable: on Windows,
        // crossterm errors ("Initial console modes not set") disabling
        // mouse capture that was never enabled in this session (e.g.
        // "Capture mouse" was already off at startup) — there's nothing to
        // actually undo in that case, and it shouldn't be fatal.
        let _ = io::stdout().execute(DisableMouseCapture);
    }
    Ok(())
}

/// Suspends the TUI, runs an external program (pager/editor/shell command),
/// and restores the TUI once it exits.
fn run_external(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    request: ExternalRequest,
    app: &mut App,
) -> Result<()> {
    match request {
        ExternalRequest::View(path) => {
            let default_pager = if cfg!(windows) { "notepad" } else { "less" };
            run_pager_or_editor(terminal, "PAGER", default_pager, &path, app).map(|_| ())
        }
        ExternalRequest::Edit(path) => {
            run_pager_or_editor(terminal, "EDITOR", default_editor(), &path, app).map(|_| ())
        }
        ExternalRequest::RenameSelected {
            list_file,
            dir,
            names,
        } => {
            let editor_ok =
                run_pager_or_editor(terminal, "EDITOR", default_editor(), &list_file, app)?;
            app.finish_bulk_rename(&list_file, dir, &names, editor_ok);
            Ok(())
        }
        ExternalRequest::Shell { command, cwd } => run_shell_command(terminal, &command, &cwd, app),
        ExternalRequest::RevealTerminal => reveal_terminal(terminal, app),
    }
}

fn default_editor() -> &'static str {
    if cfg!(windows) { "notepad" } else { "vi" }
}

/// Returns whether the program ran and exited successfully.
fn run_pager_or_editor(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    env_var: &str,
    default_program: &str,
    path: &Path,
    app: &mut App,
) -> Result<bool> {
    // $EDITOR/$PAGER may be a full command line (e.g. "omarchy-launch-editor
    // --inline"), not just a bare program name, so parse it like a shell would.
    let command_line = env::var(env_var).unwrap_or_else(|_| default_program.to_string());
    let mut parts =
        shell_words::split(&command_line).unwrap_or_else(|_| vec![command_line.clone()]);
    if parts.is_empty() {
        parts.push(default_program.to_string());
    }
    let program = parts.remove(0);
    let args = parts;

    restore_terminal();
    let status = Command::new(&program).args(&args).arg(path).status();
    enable_raw_mode().context("enable_raw_mode")?;
    io::stdout()
        .execute(EnterAlternateScreen)
        .context("EnterAlternateScreen")?;
    set_mouse_capture(app.mouse_capture)?;
    terminal.clear()?;

    let succeeded = matches!(&status, Ok(status) if status.success());
    match status {
        Ok(status) if !status.success() => {
            app.set_error(format!("{program} exited with {status}"));
        }
        Err(err) => {
            app.set_error(format!("Failed to launch {program}: {err}"));
        }
        Ok(_) => {}
    }

    app.left.reload()?;
    app.right.reload()?;
    Ok(succeeded)
}

/// Runs a shell command line (Norton Commander's built-in command prompt),
/// pausing for a keypress afterward so the user can read its output before
/// the TUI redraws over it.
fn run_shell_command(
    terminal: &mut Terminal<CrosstermBackend<io::Stdout>>,
    command: &str,
    cwd: &Path,
    app: &mut App,
) -> Result<()> {
    let (shell, shell_flag) = if cfg!(windows) {
        (
            env::var("COMSPEC").unwrap_or_else(|_| "cmd.exe".to_string()),
            "/C",
        )
    } else {
        (
            env::var("SHELL").unwrap_or_else(|_| "/bin/sh".to_string()),
            "-c",
        )
    };
    let wait = app.wait_after_shell_command;

    restore_terminal();
    println!("$ {command}");
    let mut cmd = Command::new(&shell);
    cmd.arg(shell_flag);
    #[cfg(windows)]
    {
        // cmd.exe parses its own quotes out of the raw command line, so the
        // quotes app.rs puts around an executable name must reach it
        // untouched. `.arg()` would otherwise backslash-escape them for
        // CreateProcess, leaving cmd.exe looking at `\"name\"` and failing
        // to find the program.
        use std::os::windows::process::CommandExt;
        cmd.raw_arg(command);
    }
    #[cfg(not(windows))]
    {
        cmd.arg(command);
    }
    let status = cmd.current_dir(cwd).status();

    if wait {
        match &status {
            Ok(status) if !status.success() => println!("\n[exited with {status}]"),
            Err(err) => println!("\n[failed to launch {shell}: {err}]"),
            Ok(_) => {}
        }
        println!("\nPress Enter to continue...");
        let mut discard = String::new();
        let _ = io::stdin().read_line(&mut discard);
    }

    enable_raw_mode().context("enable_raw_mode")?;
    io::stdout()
        .execute(EnterAlternateScreen)
        .context("EnterAlternateScreen")?;
    set_mouse_capture(app.mouse_capture)?;
    terminal.clear()?;

    match status {
        Ok(status) if !status.success() => {
            app.set_error(format!("Command exited with {status}"));
        }
        Err(err) => {
            app.set_error(format!("Failed to launch {shell}: {err}"));
        }
        Ok(_) => {}
    }

    app.left.reload()?;
    app.right.reload()?;
    Ok(())
}

/// Ctrl+O: reveals the real terminal underneath the panels — the same
/// screen that one-off shell commands print to — so its scrollback is
/// visible again, without spawning anything. Pressing Ctrl+O (or Esc)
/// again toggles back. Raw mode stays on throughout, so this is just an
/// alternate-screen flip, not a full terminal suspend/resume.
///
/// Deliberately draws nothing here: anything printed to this (primary)
/// screen becomes permanent scrollback once later output scrolls past it,
/// so even a "toast" hint ends up baked in as a stray line per use. Classic
/// Norton Commander doesn't overlay anything on the revealed screen either.
fn reveal_terminal(terminal: &mut Terminal<CrosstermBackend<io::Stdout>>, app: &App) -> Result<()> {
    // Mouse capture would otherwise intercept the wheel instead of letting
    // the terminal scroll its own native scrollback, defeating the point.
    // Best-effort, like set_mouse_capture()'s disable branch: on Windows,
    // crossterm errors disabling mouse capture that was never enabled in
    // this session, which isn't fatal — it's already off either way.
    let _ = io::stdout().execute(DisableMouseCapture);
    io::stdout()
        .execute(LeaveAlternateScreen)
        .context("LeaveAlternateScreen")?;

    loop {
        if let Event::Key(key) = event::read()?
            && key.kind == KeyEventKind::Press
        {
            let is_ctrl_o =
                key.code == KeyCode::Char('o') && key.modifiers.contains(KeyModifiers::CONTROL);
            if is_ctrl_o || key.code == KeyCode::Esc {
                break;
            }
        }
    }

    io::stdout()
        .execute(EnterAlternateScreen)
        .context("EnterAlternateScreen")?;
    set_mouse_capture(app.mouse_capture)?;
    terminal.clear()?;
    Ok(())
}

/// Which pane (if any) a screen position falls in, based on the areas
/// recorded during the last drawn frame.
fn side_at(app: &App, column: u16, row: u16) -> Option<app::Side> {
    let pos = Position::new(column, row);
    if app.left_pane_area.contains(pos) {
        Some(app::Side::Left)
    } else if app.right_pane_area.contains(pos) {
        Some(app::Side::Right)
    } else {
        None
    }
}

/// Mouse support: wheel scrolls a pane (or the quick-view preview, if that's
/// what's showing under the pointer) by exactly one row per notch, and
/// clicking an F-key bar tile does whatever pressing that key would do.
/// Ignored while a dialog, the pulldown menu, or help is open, matching how
/// `handle_key` gates those same keyboard shortcuts.
fn handle_mouse(app: &mut App, mouse: MouseEvent) -> Result<()> {
    if app.error_dialog.is_some()
        || app.job_visible
        || app.help_open
        || app.logs_open
        || app.about_open
        || app.dialog_is_text_input()
        || app.dialog_is_settings()
        || !matches!(app.dialog, Dialog::None)
    {
        return Ok(());
    }

    match mouse.kind {
        // Only the active pane has a visible highlight, so scrolling the
        // inactive one would move its selection with no visible feedback.
        // Blocked while the menu is open too, same as the keyboard's
        // arrows are repurposed for menu navigation in that state.
        MouseEventKind::ScrollUp | MouseEventKind::ScrollDown if !app.menu_open => {
            if app.debounced_scroll() {
                return Ok(());
            }
            if let Some(side) = side_at(app, mouse.column, mouse.row) {
                // The active side always shows the file list (whether or
                // not quick_view is on); when quick_view is on, the other
                // side shows the preview instead of a second list.
                let is_preview_side = app.quick_view && side != app.active;
                let is_list_side = side == app.active;
                let scroll_up = mouse.kind == MouseEventKind::ScrollUp;
                // Text scrolls faster per notch than the file list — 1 row
                // per click feels sluggish for reading, matching the usual
                // "a few lines per wheel click" convention.
                const WHEEL_PREVIEW_LINES: usize = 3;
                match (is_preview_side, is_list_side, scroll_up) {
                    (true, _, true) => {
                        for _ in 0..WHEEL_PREVIEW_LINES {
                            app.scroll_preview_up();
                        }
                    }
                    (true, _, false) => {
                        for _ in 0..WHEEL_PREVIEW_LINES {
                            app.scroll_preview_down();
                        }
                    }
                    (false, true, true) => app.pane_mut(side).move_up(),
                    (false, true, false) => app.pane_mut(side).move_down(),
                    (false, false, _) => {}
                }
            }
        }
        MouseEventKind::Down(MouseButton::Left) => {
            handle_mouse_click(app, mouse.column, mouse.row)?
        }
        _ => {}
    }
    Ok(())
}

fn handle_mouse_click(app: &mut App, column: u16, row: u16) -> Result<()> {
    let pos = Position::new(column, row);

    // A menu bar label is clickable whether or not the menu is already
    // open — either opens it fresh on that category, or switches to it.
    let bar_category = app
        .menu_bar_tiles
        .iter()
        .find(|(rect, _)| rect.contains(pos))
        .map(|&(_, category)| category);
    if let Some(category) = bar_category {
        app.open_menu_at(category);
        return Ok(());
    }

    if app.menu_open {
        let item = app
            .menu_item_tiles
            .iter()
            .find(|(rect, _)| rect.contains(pos))
            .map(|&(_, idx)| idx);
        if let Some(idx) = item {
            let action = MENU_BAR[app.menu_category].items[idx];
            if app.action_enabled(action) {
                app.menu_item = idx;
                app.confirm_menu_selection()?;
            }
        } else {
            // Clicked outside the bar and the dropdown: dismiss it, same
            // as clicking away from a menu does in any GUI.
            app.close_menu();
        }
        return Ok(());
    }

    let clicked = app
        .fn_key_tiles
        .iter()
        .find(|(rect, _)| rect.contains(pos))
        .map(|(_, action)| *action);
    if let Some(clicked_action) = clicked {
        match clicked_action {
            Some(action) => app.run_action(action)?,
            None => app.open_menu(),
        }
    }
    Ok(())
}

/// The `MENU_BAR` category whose title starts with `letter` (case
/// insensitive), if any — used for the Alt+F/O/C mnemonic shortcuts.
fn menu_category_for(letter: char) -> Option<usize> {
    let lower = letter.to_ascii_lowercase();
    MENU_BAR
        .iter()
        .position(|category| category.title.to_ascii_lowercase().starts_with(lower))
}

fn handle_key(app: &mut App, code: KeyCode, modifiers: KeyModifiers) -> Result<()> {
    if app.error_dialog.is_some() {
        app.error_dialog = None;
        return Ok(());
    }

    // The Copy/Move progress window sits on top of everything until it's
    // sent to the background (Esc, or its Background button).
    if app.job_visible {
        match code {
            KeyCode::Esc => app.hide_job(),
            KeyCode::Left | KeyCode::Right | KeyCode::Tab => app.toggle_job_focus(),
            KeyCode::Enter => app.activate_job_button(),
            _ => {}
        }
        return Ok(());
    }

    if app.help_open {
        match code {
            KeyCode::Left => app.help_page = app.help_page.saturating_sub(1),
            KeyCode::Right => app.help_page = (app.help_page + 1).min(ui::HELP_PAGE_COUNT - 1),
            _ => app.help_open = false,
        }
        return Ok(());
    }

    if app.logs_open {
        app.logs_open = false;
        return Ok(());
    }

    if app.about_open {
        app.about_open = false;
        return Ok(());
    }

    if app.dialog_is_text_input() {
        match code {
            KeyCode::Enter => {
                if app.dialog_cancel_focused {
                    app.cancel_dialog();
                } else {
                    app.confirm_dialog()?;
                }
            }
            KeyCode::Esc => app.cancel_dialog(),
            KeyCode::Left | KeyCode::Right => app.toggle_dialog_focus(),
            KeyCode::Backspace => app.text_input_backspace(),
            KeyCode::Char(c) => app.text_input_push(c),
            _ => {}
        }
        return Ok(());
    }

    if app.dialog_is_settings() {
        match code {
            KeyCode::Up => app.settings_move_up(),
            KeyCode::Down => app.settings_move_down(),
            KeyCode::Char(' ') => app.settings_toggle_selected(),
            KeyCode::Left => app.settings_select_left(),
            KeyCode::Right => app.settings_select_right(),
            KeyCode::Enter => app.settings_save(),
            KeyCode::Esc | KeyCode::F(9) => app.settings_cancel(),
            _ => {}
        }
        return Ok(());
    }

    if !matches!(app.dialog, Dialog::None) {
        match code {
            KeyCode::Esc => app.cancel_dialog(),
            KeyCode::Left | KeyCode::Right => app.toggle_dialog_focus(),
            KeyCode::Enter => {
                if app.dialog_cancel_focused {
                    app.cancel_dialog();
                } else {
                    app.confirm_dialog()?;
                }
            }
            _ => {}
        }
        return Ok(());
    }

    if app.menu_open {
        match code {
            KeyCode::Esc => app.close_menu(),
            KeyCode::Left => app.menu_left(),
            KeyCode::Right => app.menu_right(),
            KeyCode::Up => app.menu_up(),
            KeyCode::Down => app.menu_down(),
            KeyCode::Enter => app.confirm_menu_selection()?,
            KeyCode::F(9) => app.close_menu(),
            // The mnemonic letter switches category even while the menu
            // is already open (with or without Alt still held), so Alt+F
            // then Alt+O jumps straight from File to Options.
            KeyCode::Char(c) => {
                if let Some(idx) = menu_category_for(c) {
                    app.open_menu_at(idx);
                }
            }
            _ => {}
        }
        return Ok(());
    }

    if app.quick_search.is_some() {
        match code {
            KeyCode::Char(c)
                if !modifiers.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) =>
            {
                app.quick_search_push(c);
                return Ok(());
            }
            KeyCode::Backspace => {
                app.quick_search_backspace();
                return Ok(());
            }
            KeyCode::Up => {
                app.quick_search_step(false);
                return Ok(());
            }
            KeyCode::Down => {
                app.quick_search_step(true);
                return Ok(());
            }
            KeyCode::Esc | KeyCode::Enter => {
                app.end_quick_search();
                return Ok(());
            }
            // Anything else ends the search and then does what it normally
            // does (e.g. F5 copies the entry just found).
            _ => app.end_quick_search(),
        }
    }

    match code {
        KeyCode::Tab => {
            if app.quick_view {
                app.toggle_preview_focus();
            } else {
                app.toggle_active();
            }
        }
        KeyCode::Up if app.quick_view && app.preview_focus => app.scroll_preview_up(),
        KeyCode::Down if app.quick_view && app.preview_focus => app.scroll_preview_down(),
        KeyCode::Up => app.active_pane().move_up(),
        KeyCode::Down => app.active_pane().move_down(),
        // Classic Norton Commander: Insert tags the entry under the cursor
        // for F5/F6/F8 to act on as a batch, and steps down so repeated
        // presses sweep through a run of files.
        KeyCode::Insert => app.active_pane().toggle_mark_selected(),
        KeyCode::Home if app.quick_view && app.preview_focus => app.scroll_preview_to_top(),
        KeyCode::End if app.quick_view && app.preview_focus => app.scroll_preview_to_bottom(),
        KeyCode::PageUp if app.quick_view && app.preview_focus => app.scroll_preview_page_up(),
        KeyCode::PageDown if app.quick_view && app.preview_focus => app.scroll_preview_page_down(),
        KeyCode::Home => app.active_pane().move_to_top(),
        KeyCode::End => app.active_pane().move_to_bottom(),
        KeyCode::PageUp => {
            let page = app.pane_visible_lines;
            app.active_pane().move_page_up(page);
        }
        KeyCode::PageDown => {
            let page = app.pane_visible_lines;
            app.active_pane().move_page_down(page);
        }
        KeyCode::Backspace => app.command_line_backspace(),
        KeyCode::Esc => app.command_line_clear(),
        // Classic Norton Commander: Enter runs whatever is typed on the
        // command line, or opens the selected entry if nothing was typed —
        // unless keyboard focus is on the quick-view preview, which has
        // nothing of its own to open.
        KeyCode::Enter => {
            let preview_has_focus = app.quick_view && app.preview_focus;
            if !app.submit_command_line() && !preview_has_focus {
                app.open_selected()?;
            }
        }
        KeyCode::F(4) if modifiers.contains(KeyModifiers::SHIFT) => {
            app.run_action(Action::NewFile)?;
        }
        KeyCode::F(8) if modifiers.contains(KeyModifiers::SHIFT) => {
            app.run_action(Action::DeletePermanently)?;
        }
        KeyCode::F(1) if modifiers.contains(KeyModifiers::ALT) => {
            app.sync_left_to_right_dir()?;
        }
        KeyCode::F(2) if modifiers.contains(KeyModifiers::ALT) => {
            app.sync_right_to_left_dir()?;
        }
        // Alt+<first letter> jumps straight to that menu category — Alt+F
        // for File, Alt+O for Options, Alt+C for Command — matching each
        // category's title rather than hardcoding the letters, so this
        // stays correct if MENU_BAR is ever relabeled.
        KeyCode::Char(c) if modifiers.contains(KeyModifiers::ALT) => {
            if let Some(idx) = menu_category_for(c) {
                app.open_menu_at(idx);
            }
        }
        KeyCode::Char('o') if modifiers.contains(KeyModifiers::CONTROL) => {
            app.request_reveal_terminal();
        }
        KeyCode::Char('l') if modifiers.contains(KeyModifiers::CONTROL) => {
            app.run_action(Action::ShowLogs)?;
        }
        KeyCode::Char('f') if modifiers.contains(KeyModifiers::CONTROL) => {
            app.run_action(Action::QuickSearch)?;
        }
        KeyCode::Char('b') if modifiers.contains(KeyModifiers::CONTROL) => {
            app.run_action(Action::ShowProgress)?;
        }
        KeyCode::Char('s') if modifiers.contains(KeyModifiers::CONTROL) => {
            app.run_action(Action::Settings)?;
        }
        // Some terminals (e.g. GNOME/ptyxis) intercept F10 for their own
        // menu and never forward it to us, leaving F10-only Quit
        // unreachable there. Ctrl+Q is a widely recognized "quit" shortcut
        // and gives those users a way out.
        KeyCode::Char('q') if modifiers.contains(KeyModifiers::CONTROL) => {
            app.run_action(Action::Quit)?;
        }
        KeyCode::F(n) => {
            if let Some(fn_key) = FN_KEYS.iter().find(|k| k.key == format!("F{n}")) {
                match fn_key.action {
                    Some(action) => app.run_action(action)?,
                    None => app.open_menu(),
                }
            }
        }
        // Any other printable character is typed straight into the
        // always-visible command line, same as classic Norton Commander.
        KeyCode::Char(c) => app.command_line_push(c),
        _ => {}
    }
    Ok(())
}

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

    fn args(list: &[&str]) -> Vec<String> {
        list.iter().map(|s| s.to_string()).collect()
    }

    fn run(left: Option<&str>, right: Option<&str>) -> CliRequest {
        CliRequest::Run {
            left: left.map(String::from),
            right: right.map(String::from),
        }
    }

    #[test]
    fn no_arguments_starts_the_ui() {
        assert_eq!(parse_args(args(&[])), run(None, None));
    }

    #[test]
    fn version_and_help_flags_are_recognised() {
        for flag in ["-V", "-v", "--version", "-version"] {
            assert_eq!(parse_args(args(&[flag])), CliRequest::Version, "{flag}");
        }
        assert_eq!(parse_args(args(&["-h"])), CliRequest::Help);
        assert_eq!(parse_args(args(&["--help"])), CliRequest::Help);
    }

    #[test]
    fn flags_win_over_directories() {
        assert_eq!(parse_args(args(&["~/a", "-v"])), CliRequest::Version);
        assert_eq!(parse_args(args(&["--nope", "-h"])), CliRequest::Help);
    }

    #[test]
    fn bare_version_is_a_directory() {
        assert_eq!(parse_args(args(&["version"])), run(Some("version"), None));
    }

    #[test]
    fn up_to_two_directories_fill_left_then_right() {
        assert_eq!(parse_args(args(&["."])), run(Some("."), None));
        assert_eq!(parse_args(args(&["a", "b"])), run(Some("a"), Some("b")));
        assert!(matches!(
            parse_args(args(&["a", "b", "c"])),
            CliRequest::Invalid(_)
        ));
    }

    #[test]
    fn unknown_options_are_rejected() {
        assert_eq!(
            parse_args(args(&["-x"])),
            CliRequest::Invalid("unknown option '-x'".into())
        );
        // A lone "-" isn't an option; it's treated as a (nonexistent) dir.
        assert_eq!(parse_args(args(&["-"])), run(Some("-"), None));
    }

    #[test]
    fn resolve_dir_accepts_directories_only() {
        let tmp = std::env::temp_dir().join(format!("pc-resolve-{}", std::process::id()));
        std::fs::create_dir_all(&tmp).unwrap();
        let file = tmp.join("file.txt");
        std::fs::write(&file, "x").unwrap();

        assert_eq!(
            resolve_dir(tmp.to_str().unwrap()),
            Ok(tmp.canonicalize().unwrap())
        );
        assert!(
            resolve_dir(file.to_str().unwrap())
                .unwrap_err()
                .contains("is not a directory")
        );
        assert!(
            resolve_dir(tmp.join("missing").to_str().unwrap())
                .unwrap_err()
                .starts_with("cannot open")
        );

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

    #[test]
    fn version_text_matches_the_package() {
        assert_eq!(
            version_text(),
            format!("peter-commander {}", env!("CARGO_PKG_VERSION"))
        );
    }
}