pacsea 0.8.2

A fast, friendly TUI for browsing and installing Arch and AUR packages with built-in news and security scanning
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
//! Global shortcuts and dropdown menu handling.

use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use tokio::sync::mpsc;

use crate::app::{apply_settings_to_app_state, initialize_locale_system};
use crate::events::mouse::menus::{handle_mode_toggle, handle_news_age_toggle};
use crate::events::utils;
use crate::state::{AppState, PackageItem, PkgbuildCheckRequest};
use crate::theme::{reload_theme, settings};

/// What: Close all open dropdown menus when ESC is pressed.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - `true` if menus were closed, `false` otherwise
///
/// Details:
/// - Closes sort, options, panels, config, and filter dropdown menus.
#[allow(clippy::missing_const_for_fn)]
fn close_all_dropdowns(app: &mut AppState) -> bool {
    let any_open = app.sort_menu_open
        || app.options_menu_open
        || app.panels_menu_open
        || app.config_menu_open
        || app.artix_filter_menu_open
        || app.custom_repos_filter_menu_open;
    if any_open {
        app.sort_menu_open = false;
        app.sort_menu_auto_close_at = None;
        app.options_menu_open = false;
        app.panels_menu_open = false;
        app.config_menu_open = false;
        app.artix_filter_menu_open = false;
        app.custom_repos_filter_menu_open = false;
        true
    } else {
        false
    }
}

/// What: Handle installed-only mode toggle from options menu.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `details_tx`: Channel to request package details
///
/// Details:
/// - Toggles between showing all packages and only explicitly installed packages.
/// - When enabling, saves installed packages list to config directory.
fn handle_options_installed_only_toggle(
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
) {
    use std::collections::HashSet;
    if app.installed_only_mode {
        if let Some(prev) = app.results_backup_for_toggle.take() {
            app.all_results = prev;
        }
        app.installed_only_mode = false;
        app.right_pane_focus = crate::state::RightPaneFocus::Install;
        crate::logic::apply_filters_and_sort_preserve_selection(app);
        utils::refresh_selected_details(app, details_tx);
    } else {
        app.results_backup_for_toggle = Some(app.all_results.clone());
        let explicit = crate::index::explicit_names();
        let mut items: Vec<crate::state::PackageItem> = crate::index::all_official()
            .into_iter()
            .filter(|p| explicit.contains(&p.name))
            .collect();
        let official_names: HashSet<String> = items.iter().map(|p| p.name.clone()).collect();
        for name in explicit {
            if !official_names.contains(&name) {
                let is_eos = crate::index::is_eos_name(&name);
                let src = if is_eos {
                    crate::state::Source::Official {
                        repo: "EOS".to_string(),
                        arch: String::new(),
                    }
                } else {
                    crate::state::Source::Aur
                };
                items.push(crate::state::PackageItem {
                    name: name.clone(),
                    version: String::new(),
                    description: String::new(),
                    source: src,
                    popularity: None,
                    out_of_date: None,
                    orphaned: false,
                });
            }
        }
        app.all_results = items;
        app.installed_only_mode = true;
        app.right_pane_focus = crate::state::RightPaneFocus::Remove;
        crate::logic::apply_filters_and_sort_preserve_selection(app);
        utils::refresh_selected_details(app, details_tx);
        let path = crate::theme::config_dir().join("installed_packages.txt");
        // Query pacman directly with current mode to ensure file reflects the setting
        let names = crate::index::query_explicit_packages_sync(app.installed_packages_mode);
        let body = names.join("\n");
        let _ = std::fs::write(path, body);
    }
}

/// What: Handle system update option from options menu.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Details:
/// - Opens `SystemUpdate` modal with default settings.
fn handle_options_system_update(app: &mut AppState) {
    let countries = vec![
        "Worldwide".to_string(),
        "Germany".to_string(),
        "United States".to_string(),
        "United Kingdom".to_string(),
        "France".to_string(),
        "Netherlands".to_string(),
        "Sweden".to_string(),
        "Canada".to_string(),
        "Australia".to_string(),
        "Japan".to_string(),
    ];
    let prefs = crate::theme::settings();
    let initial_country_idx = {
        let sel = prefs
            .selected_countries
            .split(',')
            .next()
            .map_or_else(|| "Worldwide".to_string(), |s| s.trim().to_string());
        countries.iter().position(|c| c == &sel).unwrap_or(0)
    };
    app.modal = crate::state::Modal::SystemUpdate {
        do_mirrors: false,
        do_pacman: true,
        force_sync: false,
        do_aur: true,
        do_cache: false,
        country_idx: initial_country_idx,
        countries,
        mirror_count: prefs.mirror_count,
        cursor: 0,
    };
}

/// What: Handle optional deps option from options menu.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Details:
/// - Builds optional dependencies rows and opens `OptionalDeps` modal.
fn handle_options_optional_deps(app: &mut AppState) {
    let rows = crate::events::mouse::menu_options::build_optional_deps_rows(app);
    app.modal = crate::state::Modal::OptionalDeps {
        rows,
        selected: 0,
        selected_pkg_names: std::collections::HashSet::new(),
    };
    let ssh_command = crate::theme::settings().aur_vote_ssh_command;
    app.pending_aur_ssh_help_check_result = Some(
        crate::logic::ssh_setup::spawn_aur_ssh_help_check(ssh_command),
    );
}

/// What: Open the read-only Repositories modal from the options menu.
///
/// Inputs:
/// - `app`: Mutable application state.
///
/// Output:
/// - None (sets `app.modal`).
///
/// Details:
/// - Loads `repos.conf` from the resolved path and scans `/etc/pacman.conf` for section headers.
/// - On non-Linux targets, shows the same unsupported-platform alert as the mouse menu path.
fn handle_options_repositories(app: &mut AppState) {
    #[cfg(not(target_os = "linux"))]
    {
        app.modal = crate::state::Modal::Alert {
            message: crate::i18n::t(app, "app.modals.repositories.unsupported_platform"),
        };
        return;
    }
    #[cfg(target_os = "linux")]
    {
        let (rows, repos_conf_error, pacman_warnings) =
            crate::logic::repos::build_repositories_modal_fields_default();
        app.modal = crate::state::Modal::Repositories {
            rows,
            selected: 0,
            scroll: 0,
            repos_conf_error,
            pacman_warnings,
        };
    }
}

/// What: Handle panels menu numeric selection.
///
/// Inputs:
/// - `idx`: Selected menu index (0=recent, 1=install, 2=keybinds)
/// - `app`: Mutable application state
///
/// Details:
/// - Toggles visibility of recent pane, install pane, or keybinds footer.
fn handle_panels_menu_selection(idx: usize, app: &mut AppState) {
    let news_mode = matches!(app.app_mode, crate::state::types::AppMode::News);
    if news_mode {
        match idx {
            0 => {
                app.show_news_history_pane = !app.show_news_history_pane;
                if !app.show_news_history_pane && matches!(app.focus, crate::state::Focus::Recent) {
                    app.focus = crate::state::Focus::Search;
                }
            }
            1 => {
                app.show_news_bookmarks_pane = !app.show_news_bookmarks_pane;
                if !app.show_news_bookmarks_pane
                    && matches!(app.focus, crate::state::Focus::Install)
                {
                    app.focus = crate::state::Focus::Search;
                }
            }
            2 => {
                app.show_keybinds_footer = !app.show_keybinds_footer;
                crate::theme::save_show_keybinds_footer(app.show_keybinds_footer);
            }
            _ => {}
        }
    } else {
        match idx {
            0 => {
                app.show_recent_pane = !app.show_recent_pane;
                if !app.show_recent_pane && matches!(app.focus, crate::state::Focus::Recent) {
                    app.focus = crate::state::Focus::Search;
                }
                crate::theme::save_show_recent_pane(app.show_recent_pane);
            }
            1 => {
                app.show_install_pane = !app.show_install_pane;
                if !app.show_install_pane && matches!(app.focus, crate::state::Focus::Install) {
                    app.focus = crate::state::Focus::Search;
                }
                crate::theme::save_show_install_pane(app.show_install_pane);
            }
            2 => {
                app.show_keybinds_footer = !app.show_keybinds_footer;
                crate::theme::save_show_keybinds_footer(app.show_keybinds_footer);
            }
            _ => {}
        }
    }
}

/// What: Normalize `BackTab` modifiers so that `SHIFT` modifier does not affect matching across terminals.
///
/// Inputs:
/// - `ke`: Key event from crossterm
///
/// Output:
/// - Normalized modifiers (empty for `BackTab`, original modifiers otherwise)
///
/// Details:
/// - `BackTab` normalization ensures consistent keybind matching across different terminal emulators.
const fn normalize_key_modifiers(ke: &KeyEvent) -> KeyModifiers {
    if matches!(ke.code, KeyCode::BackTab) {
        KeyModifiers::empty()
    } else {
        ke.modifiers
    }
}

/// What: Create a normalized key chord from a key event for keybind matching.
///
/// Inputs:
/// - `ke`: Key event from crossterm
///
/// Output:
/// - Tuple of (`KeyCode`, `KeyModifiers`) suitable for matching against `KeyChord` lists
///
/// Details:
/// - Normalizes `BackTab` modifiers before creating the chord.
const fn create_key_chord(ke: &KeyEvent) -> (KeyCode, KeyModifiers) {
    (ke.code, normalize_key_modifiers(ke))
}

/// What: Check if a key event matches any chord in a list of keybinds.
///
/// Inputs:
/// - `ke`: Key event from crossterm
/// - `chords`: List of configured key chords to match against
///
/// Output:
/// - `true` if the key event matches any chord in the list, `false` otherwise
///
/// Details:
/// - Normalizes `BackTab` modifiers before matching.
fn matches_keybind(ke: &KeyEvent, chords: &[crate::theme::KeyChord]) -> bool {
    let chord = create_key_chord(ke);
    chords.iter().any(|c| (c.code, c.mods) == chord)
}

/// What: Handle escape key press - closes dropdown menus.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - `Some(false)` if menus were closed, `None` otherwise
///
/// Details:
/// - Closes all open dropdown menus when ESC is pressed.
fn handle_escape(app: &mut AppState) -> Option<bool> {
    if close_all_dropdowns(app) {
        Some(false)
    } else {
        None
    }
}

/// What: Handle help overlay keybind.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - `false` if help was opened
///
/// Details:
/// - Opens the Help modal when the help overlay keybind is pressed.
fn handle_help_overlay(app: &mut AppState) -> bool {
    app.modal = crate::state::Modal::Help;
    false
}

/// What: Handle configuration reload keybind.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `query_tx`: Channel sender for query input (to refresh results when installed mode changes)
///
/// Output:
/// - `false` if config was reloaded
///
/// Details:
/// - Reloads theme, settings, keybinds, and locale configuration from disk.
/// - Shows a toast message on success or error modal on failure.
/// - Updates app state with new settings and reloads translations if locale changed.
/// - If `installed_packages_mode` changed, refreshes the explicit cache in the background
///   and triggers a query refresh after the cache refresh completes (to avoid race conditions).
fn handle_reload_config(
    app: &mut AppState,
    query_tx: &mpsc::UnboundedSender<crate::state::QueryInput>,
) -> bool {
    let mut errors = Vec::new();

    // Reload settings first so theme resolution sees updated use_terminal_theme
    let new_settings = settings();
    let old_locale = app.locale.clone();

    // Reload theme (uses settings for use_terminal_theme)
    if let Err(msg) = reload_theme() {
        errors.push(format!("Theme reload failed: {msg}"));
    }

    crate::logic::repos::load_repos_config_into_app(app, crate::theme::resolve_repos_config_path());
    // Apply settings to app state
    let old_installed_mode = app.installed_packages_mode;
    apply_settings_to_app_state(app, &new_settings);

    // Reload locale if it changed
    if new_settings.locale != old_locale {
        initialize_locale_system(app, &new_settings.locale, &new_settings);
    }

    // Refresh explicit cache if installed packages mode changed
    if app.installed_packages_mode != old_installed_mode {
        let new_mode = app.installed_packages_mode;
        tracing::info!(
            "[Config] installed_packages_mode changed from {:?} to {:?}, refreshing cache",
            old_installed_mode,
            new_mode
        );
        // Prepare query input before spawning (to avoid race condition)
        let id = app.next_query_id;
        app.next_query_id += 1;
        app.latest_query_id = id;
        let query_input = crate::state::QueryInput {
            id,
            text: app.input.clone(),
            fuzzy: app.fuzzy_search_enabled,
        };
        // Clone query_tx to send query after cache refresh completes
        let query_tx_clone = query_tx.clone();
        tokio::spawn(async move {
            // Refresh cache first
            crate::index::refresh_explicit_cache(new_mode).await;
            // Then send query to ensure results use the refreshed cache
            let _ = query_tx_clone.send(query_input);
        });
    }

    // Show result
    if errors.is_empty() {
        app.toast_message = Some(crate::i18n::t(app, "app.toasts.config_reloaded"));
        app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(3));
    } else {
        app.modal = crate::state::Modal::Alert {
            message: errors.join("\n"),
        };
    }
    false
}

/// What: Handle exit keybind.
///
/// Inputs:
/// - None (uses closure pattern)
///
/// Output:
/// - `true` to signal exit
///
/// Details:
/// - Returns exit signal when exit keybind is pressed.
const fn handle_exit() -> bool {
    true
}

/// What: Handle PKGBUILD viewer toggle keybind.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `pkgb_tx`: Channel to request PKGBUILD content
///
/// Output:
/// - `false` if PKGBUILD was toggled
///
/// Details:
/// - Toggles PKGBUILD viewer visibility and requests content if opening.
fn handle_toggle_pkgbuild(
    app: &mut AppState,
    pkgb_tx: &mpsc::UnboundedSender<PackageItem>,
) -> bool {
    if app.pkgb_visible {
        app.pkgb_visible = false;
        app.pkgb_text = None;
        app.pkgb_package_name = None;
        app.pkgb_scroll = 0;
        app.pkgb_section_cycle = 0;
        app.pkgb_rect = None;
    } else {
        app.pkgb_visible = true;
        app.pkgb_text = None;
        app.pkgb_package_name = None;
        if let Some(item) = app.results.get(app.selected).cloned() {
            let _ = pkgb_tx.send(item);
        }
    }
    false
}

/// What: Handle PKGBUILD checks keybind.
fn handle_run_pkgbuild_checks(
    app: &mut AppState,
    pkgb_check_tx: &mpsc::UnboundedSender<PkgbuildCheckRequest>,
) -> bool {
    let Some(text) = app.pkgb_text.clone() else {
        app.toast_message = Some(crate::i18n::t(app, "app.toasts.pkgbuild_not_loaded"));
        app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(3));
        return false;
    };
    let package_name = app
        .results
        .get(app.selected)
        .map_or_else(String::new, |item| item.name.clone());
    app.pkgb_check_last_package_name = Some(package_name.clone());
    app.pkgb_check_status = crate::state::app_state::PkgbuildCheckStatus::Running;
    app.pkgb_check_findings.clear();
    app.pkgb_check_raw_results.clear();
    app.pkgb_check_missing_tools.clear();
    app.pkgb_check_last_error = None;
    app.pkgb_check_scroll = 0;
    app.pkgb_check_raw_scroll = 0;
    // Jump toward the bottom so the appended checks section is immediately visible.
    app.pkgb_scroll = u16::MAX;
    app.toast_message = Some("Running PKGBUILD checks...".to_string());
    app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(2));
    if let Err(err) = pkgb_check_tx.send(PkgbuildCheckRequest {
        package_name,
        pkgbuild_text: text,
        dry_run: app.dry_run,
    }) {
        app.pkgb_check_status = crate::state::app_state::PkgbuildCheckStatus::Complete;
        app.pkgb_check_last_error = Some(format!("failed to queue PKGBUILD checks: {err}"));
        app.toast_message = Some("Failed to start PKGBUILD checks".to_string());
        app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(3));
    }
    false
}

/// What: Cycle PKGBUILD viewer scroll between body, `ShellCheck`, and `Namcap` subsections.
///
/// Inputs:
/// - `app`: Mutable application state (requires [`AppState::pkgb_visible`])
///
/// Output:
/// - `false` (does not exit the app)
///
/// Details:
/// - Delegates to [`crate::ui::cycle_pkgbuild_view_section`].
fn handle_cycle_pkgbuild_sections(app: &mut AppState) -> bool {
    if !app.pkgb_visible {
        return false;
    }
    crate::ui::cycle_pkgbuild_view_section(app);
    false
}

/// What: Handle comments toggle keybind.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `comments_tx`: Channel to request comments content
///
/// Output:
/// - `false` (doesn't exit app)
///
/// Details:
/// - Toggles comments viewer visibility
/// - Clears comments when closing
/// - Sends request via channel when opening (only if AUR package)
fn handle_toggle_comments(app: &mut AppState, comments_tx: &mpsc::UnboundedSender<String>) -> bool {
    // Only allow for AUR packages
    let is_aur = app
        .results
        .get(app.selected)
        .is_some_and(|item| matches!(item.source, crate::state::Source::Aur));

    if !is_aur {
        return false;
    }

    if app.comments_visible {
        app.comments_visible = false;
        app.comments.clear();
        app.comments_package_name = None;
        app.comments_fetched_at = None;
        app.comments_scroll = 0;
        app.comments_rect = None;
        app.comments_loading = false;
        app.comments_error = None;
    } else {
        app.comments_visible = true;
        app.comments_scroll = 0;
        app.comments_error = None;
        if let Some(item) = app.results.get(app.selected) {
            // Check if we have cached comments for this package
            if app
                .comments_package_name
                .as_ref()
                .is_some_and(|cached_name| cached_name == &item.name && !app.comments.is_empty())
            {
                // Use cached comments
                app.comments_loading = false;
                return false;
            }
            // Request new comments
            app.comments.clear();
            app.comments_package_name = None;
            app.comments_fetched_at = None;
            app.comments_loading = true;
            let _ = comments_tx.send(item.name.clone());
        }
    }
    false
}

/// What: Handle sort mode change keybind.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `details_tx`: Channel to request package details
///
/// Output:
/// - `false` if sort mode was changed
///
/// Details:
/// - In News mode: cycles through news sort modes and refreshes news results.
/// - In Package mode: cycles through package sort modes, persists preference, re-sorts results.
fn handle_change_sort(app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>) -> bool {
    if matches!(app.app_mode, crate::state::types::AppMode::News) {
        // News mode: cycle through news sort modes
        use crate::state::types::NewsSortMode;
        app.news_sort_mode = match app.news_sort_mode {
            NewsSortMode::DateDesc => NewsSortMode::DateAsc,
            NewsSortMode::DateAsc => NewsSortMode::Title,
            NewsSortMode::Title => NewsSortMode::SourceThenTitle,
            NewsSortMode::SourceThenTitle => NewsSortMode::SeverityThenDate,
            NewsSortMode::SeverityThenDate => NewsSortMode::UnreadThenDate,
            NewsSortMode::UnreadThenDate => NewsSortMode::DateDesc,
        };
        app.refresh_news_results();
    } else {
        // Package mode: cycle through package sort modes in fixed order
        app.sort_mode = match app.sort_mode {
            crate::state::SortMode::RepoThenName => {
                crate::state::SortMode::AurPopularityThenOfficial
            }
            crate::state::SortMode::AurPopularityThenOfficial => {
                crate::state::SortMode::BestMatches
            }
            crate::state::SortMode::BestMatches => crate::state::SortMode::RepoThenName,
        };
        // Persist preference and apply immediately
        crate::theme::save_sort_mode(app.sort_mode);
        crate::logic::sort_results_preserve_selection(app);
        // Jump selection to top and refresh details
        if app.results.is_empty() {
            app.list_state.select(None);
        } else {
            app.selected = 0;
            app.list_state.select(Some(0));
            utils::refresh_selected_details(app, details_tx);
        }
    }
    // Show the dropdown so the user sees the current option with a check mark
    app.sort_menu_open = true;
    false
}

/// What: Handle numeric menu selection for options menu.
///
/// Inputs:
/// - `idx`: Selected menu index (0-based, where '1' key maps to idx 0)
/// - `app`: Mutable application state
/// - `details_tx`: Channel to request package details
///
/// Output:
/// - `Some(false)` if selection was handled, `None` otherwise
///
/// Details:
/// - Package mode display order: List installed (1), Update system (2), TUI Optional Deps (3), Repositories (4), News management (5)
/// - News mode display order: Update system (1), TUI Optional Deps (2), Repositories (3), Package mode (4)
/// - Closes the options menu when a selection is handled.
/// - Note: News age toggle (idx 5 in News mode) is not displayed in menu but handler remains for compatibility.
fn handle_options_menu_numeric(
    idx: usize,
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
) -> Option<bool> {
    let news_mode = matches!(app.app_mode, crate::state::types::AppMode::News);
    let handled = if news_mode {
        // News mode display order: Update system (1), TUI Optional Deps (2), Repositories (3), Package mode (4)
        match idx {
            0 => {
                handle_options_system_update(app);
                true
            }
            1 => {
                handle_options_optional_deps(app);
                true
            }
            2 => {
                handle_options_repositories(app);
                true
            }
            3 => {
                handle_mode_toggle(app, details_tx);
                true
            }
            4 => {
                handle_news_age_toggle(app);
                true
            }
            _ => false,
        }
    } else {
        // Package mode display order: List installed (1), Update system (2), TUI Optional Deps (3), Repositories (4), News management (5)
        match idx {
            0 => {
                handle_options_installed_only_toggle(app, details_tx);
                true
            }
            1 => {
                handle_options_system_update(app);
                true
            }
            2 => {
                handle_options_optional_deps(app);
                true
            }
            3 => {
                handle_options_repositories(app);
                true
            }
            4 => {
                handle_mode_toggle(app, details_tx);
                true
            }
            _ => false,
        }
    };

    if handled {
        app.options_menu_open = false;
        Some(false)
    } else {
        None
    }
}

/// What: Handle numeric menu selection for panels menu.
///
/// Inputs:
/// - `idx`: Selected menu index (0=recent, 1=install, 2=keybinds)
/// - `app`: Mutable application state
///
/// Output:
/// - `false` if selection was handled
///
/// Details:
/// - Routes numeric selection to panels menu handler and keeps menu open.
fn handle_panels_menu_numeric(idx: usize, app: &mut AppState) -> bool {
    handle_panels_menu_selection(idx, app);
    // Keep menu open after toggling panels
    false
}

/// What: Handle numeric menu selection for config menu.
///
/// Inputs:
/// - `idx`: Selected menu index (0=settings, 1=theme, 2=keybinds, 3=install, 4=installed, 5=recent)
/// - `app`: Mutable application state
///
/// Output:
/// - `false` if selection was handled
///
/// Details:
/// - Routes numeric selection to config menu handler.
fn handle_config_menu_numeric(idx: usize, app: &mut AppState) -> bool {
    handle_config_menu_selection(idx, app);
    false
}

/// What: Handle numeric key press when dropdown menus are open.
///
/// Inputs:
/// - `ch`: Character pressed (must be '1'-'9')
/// - `app`: Mutable application state
/// - `details_tx`: Channel to request package details
///
/// Output:
/// - `Some(false)` if a menu selection was handled, `None` otherwise
///
/// Details:
/// - Routes numeric keys to the appropriate open menu handler.
fn handle_menu_numeric_selection(
    ch: char,
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
) -> Option<bool> {
    let idx = (ch as u8 - b'1') as usize; // '1' -> 0
    if app.options_menu_open {
        handle_options_menu_numeric(idx, app, details_tx)
    } else if app.panels_menu_open {
        Some(handle_panels_menu_numeric(idx, app))
    } else if app.config_menu_open {
        Some(handle_config_menu_numeric(idx, app))
    } else {
        None
    }
}

/// What: Handle global keybinds (help, theme reload, exit, PKGBUILD, comments, sort).
///
/// Inputs:
/// - `ke`: Key event from crossterm
/// - `app`: Mutable application state
/// - `details_tx`: Channel to request package details
/// - `pkgb_tx`: Channel to request PKGBUILD content
/// - `comments_tx`: Channel to request comments content
/// - `query_tx`: Channel to send search queries
///
/// Output:
/// - `Some(true)` for exit, `Some(false)` if handled, `None` if not matched
///
/// Details:
/// - Checks key event against all global keybinds using a dispatch pattern.
/// - When a modal is open (except None), only exit keybind works globally.
/// - Other global keybinds are blocked to let modals handle their own keys.
fn handle_global_keybinds(
    ke: &KeyEvent,
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
    pkgb_tx: &mpsc::UnboundedSender<PackageItem>,
    comments_tx: &mpsc::UnboundedSender<String>,
    query_tx: &mpsc::UnboundedSender<crate::state::QueryInput>,
    pkgb_check_tx: &mpsc::UnboundedSender<PkgbuildCheckRequest>,
) -> Option<bool> {
    let km = &app.keymap;

    // Exit should always work, even in modals (Ctrl+C to quit the app)
    if matches_keybind(ke, &km.exit) {
        return Some(handle_exit());
    }

    // When a modal is open, block most global keybinds to let the modal handle keys
    // Exceptions: Modal::None (no modal), Preflight (has complex interaction with globals)
    if !matches!(
        app.modal,
        crate::state::Modal::None | crate::state::Modal::Preflight { .. }
    ) {
        return None; // Let modal handler process the key
    }

    // Log Ctrl+T specifically for debugging
    if ke.code == KeyCode::Char('t') && ke.modifiers.contains(KeyModifiers::CONTROL) {
        tracing::debug!(
            "[Keybind] Ctrl+T detected: code={:?}, mods={:?}, keybind_match={}, comments_toggle_keybinds={:?}",
            ke.code,
            ke.modifiers,
            matches_keybind(ke, &km.comments_toggle),
            km.comments_toggle
        );
    }

    // Comments toggle - check FIRST before other keybinds to ensure it's not intercepted
    if matches_keybind(ke, &km.comments_toggle) {
        tracing::debug!("[Keybind] Comments toggle matched, calling handle_toggle_comments");
        return Some(handle_toggle_comments(app, comments_tx));
    }

    // Help overlay (only if no modal is active, except Preflight which handles its own help)
    if !matches!(app.modal, crate::state::Modal::Preflight { .. })
        && matches_keybind(ke, &km.help_overlay)
    {
        return Some(handle_help_overlay(app));
    }

    // Configuration reload (only if no modal is active - modals should handle their own keys)
    if matches!(app.modal, crate::state::Modal::None) && matches_keybind(ke, &km.reload_config) {
        return Some(handle_reload_config(app, query_tx));
    }

    // Exit (always works, even in modals)
    if matches_keybind(ke, &km.exit) {
        return Some(handle_exit());
    }

    // PKGBUILD toggle (only if no modal is active - modals should handle their own keys)
    if matches!(app.modal, crate::state::Modal::None) && matches_keybind(ke, &km.show_pkgbuild) {
        return Some(handle_toggle_pkgbuild(app, pkgb_tx));
    }
    if matches!(app.modal, crate::state::Modal::None)
        && matches_keybind(ke, &km.run_pkgbuild_checks)
    {
        return Some(handle_run_pkgbuild_checks(app, pkgb_check_tx));
    }
    if matches!(app.modal, crate::state::Modal::None)
        && matches_keybind(ke, &km.cycle_pkgbuild_sections)
    {
        return Some(handle_cycle_pkgbuild_sections(app));
    }

    // Sort change (only if no modal is active - modals should handle their own keys)
    if matches!(app.modal, crate::state::Modal::None) && matches_keybind(ke, &km.change_sort) {
        return Some(handle_change_sort(app, details_tx));
    }

    None
}

/// What: Handle config menu numeric selection.
///
/// Inputs:
/// - `idx`: Selected menu index (0=settings, 1=theme, 2=keybinds, 3=repos.conf)
/// - `app`: Mutable application state
///
/// Details:
/// - Opens the selected config file in a terminal editor.
fn handle_config_menu_selection(idx: usize, app: &mut AppState) {
    let settings_path = crate::theme::config_dir().join("settings.conf");
    let theme_path = crate::theme::config_dir().join("theme.conf");
    let keybinds_path = crate::theme::config_dir().join("keybinds.conf");
    let repos_path = crate::theme::config_dir().join("repos.conf");
    let target = match idx {
        0 => settings_path,
        1 => theme_path,
        2 => keybinds_path,
        3 => repos_path,
        _ => {
            app.config_menu_open = false;
            app.artix_filter_menu_open = false;
            app.custom_repos_filter_menu_open = false;
            return;
        }
    };
    #[cfg(target_os = "windows")]
    {
        crate::util::open_file(&target);
    }
    #[cfg(not(target_os = "windows"))]
    {
        let editor_cmd = crate::install::editor_open_config_command(&target);
        let cmds = vec![editor_cmd];
        std::thread::spawn(move || {
            crate::install::spawn_shell_commands_in_terminal(&cmds);
        });
    }
    app.config_menu_open = false;
    app.artix_filter_menu_open = false;
    app.custom_repos_filter_menu_open = false;
}

/// What: Handle global shortcuts plus dropdown menus and optionally stop propagation.
///
/// Inputs:
/// - `ke`: Key event received from crossterm (code + modifiers)
/// - `app`: Mutable application state shared across panes and modals
/// - `details_tx`: Channel used to request package detail refreshes
/// - `pkgb_tx`: Channel used to request PKGBUILD content for the focused result
/// - `comments_tx`: Channel used to request comments content for the focused result
/// - `query_tx`: Channel to send search queries
///
/// Output:
/// - `Some(true)` when the caller should exit (e.g., global exit keybind triggered)
/// - `Some(false)` when a global keybind was handled (key should not be processed further)
/// - `None` when the key was not handled by global shortcuts
///
/// Details:
/// - Gives precedence to closing dropdown menus on `Esc` before other bindings.
/// - Routes configured global chords (help overlay, theme reload, exit, PKGBUILD toggle, comments toggle, sort cycle).
/// - When sort mode changes it persists the preference, re-sorts results, and refreshes details.
/// - Supports menu number shortcuts (1-9) for Options/Panels/Config dropdowns while they are open.
pub(super) fn handle_global_key(
    ke: KeyEvent,
    app: &mut AppState,
    details_tx: &mpsc::UnboundedSender<PackageItem>,
    pkgb_tx: &mpsc::UnboundedSender<PackageItem>,
    comments_tx: &mpsc::UnboundedSender<String>,
    query_tx: &mpsc::UnboundedSender<crate::state::QueryInput>,
    pkgb_check_tx: &mpsc::UnboundedSender<PkgbuildCheckRequest>,
) -> Option<bool> {
    // First: handle ESC to close dropdown menus
    if ke.code == KeyCode::Esc
        && let Some(result) = handle_escape(app)
    {
        return Some(result);
    }

    // Second: handle global keybinds (help, theme reload, exit, PKGBUILD, comments, sort)
    if let Some(result) = handle_global_keybinds(
        &ke,
        app,
        details_tx,
        pkgb_tx,
        comments_tx,
        query_tx,
        pkgb_check_tx,
    ) {
        return Some(result);
    }

    // Third: handle numeric menu selection when dropdowns are open
    // Note: menu toggles (Shift+C/O/P) handled in Search Normal mode and not globally
    if let KeyCode::Char(ch) = ke.code
        && ch.is_ascii_digit()
        && ch != '0'
        && let Some(result) = handle_menu_numeric_selection(ch, app, details_tx)
    {
        return Some(result);
    }

    None // Key not handled by global shortcuts
}

#[cfg(test)]
mod tests {
    use super::*;
    use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    fn new_app() -> AppState {
        AppState::default()
    }

    #[test]
    /// What: Confirm pressing `Esc` while dropdowns are open closes them without exiting.
    ///
    /// Inputs:
    /// - App state with Options and Sort menus flagged open.
    /// - Synthetic `Esc` key event.
    ///
    /// Output:
    /// - Handler returns `false` and menu flags reset to `false`.
    ///
    /// Details:
    /// - Ensures the early escape branch short-circuits before other global shortcuts.
    fn global_escape_closes_dropdowns() {
        let mut app = new_app();
        app.sort_menu_open = true;
        app.options_menu_open = true;
        app.panels_menu_open = true;
        app.config_menu_open = true;

        let (details_tx, _details_rx) = mpsc::unbounded_channel::<PackageItem>();
        let (pkgb_tx, _pkgb_rx) = mpsc::unbounded_channel::<PackageItem>();
        let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>();
        let (query_tx, _query_rx) = mpsc::unbounded_channel::<crate::state::QueryInput>();
        let (pkgb_check_tx, _pkgb_check_rx) =
            mpsc::unbounded_channel::<crate::state::PkgbuildCheckRequest>();

        let exit = handle_global_key(
            KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()),
            &mut app,
            &details_tx,
            &pkgb_tx,
            &comments_tx,
            &query_tx,
            &pkgb_check_tx,
        );

        assert_eq!(exit, Some(false));
        assert!(!app.sort_menu_open);
        assert!(!app.options_menu_open);
        assert!(!app.panels_menu_open);
        assert!(!app.config_menu_open);
    }

    #[test]
    /// What: Verify the help overlay shortcut activates the Help modal.
    ///
    /// Inputs:
    /// - Default keymap (F1 assigned to help overlay).
    /// - `F1` key event with no modifiers.
    ///
    /// Output:
    /// - Handler returns `false` and sets `app.modal` to `Modal::Help`.
    ///
    /// Details:
    /// - Confirms `BackTab` normalization does not interfere with regular function keys.
    fn global_help_overlay_opens_modal() {
        let mut app = new_app();
        let (details_tx, _details_rx) = mpsc::unbounded_channel::<PackageItem>();
        let (pkgb_tx, _pkgb_rx) = mpsc::unbounded_channel::<PackageItem>();
        let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>();
        let (query_tx, _query_rx) = mpsc::unbounded_channel::<crate::state::QueryInput>();
        let (pkgb_check_tx, _pkgb_check_rx) =
            mpsc::unbounded_channel::<crate::state::PkgbuildCheckRequest>();

        let exit = handle_global_key(
            KeyEvent::new(KeyCode::F(1), KeyModifiers::empty()),
            &mut app,
            &details_tx,
            &pkgb_tx,
            &comments_tx,
            &query_tx,
            &pkgb_check_tx,
        );

        assert_eq!(exit, Some(false));
        assert!(matches!(app.modal, crate::state::Modal::Help));
    }

    #[test]
    /// What: Ensure the PKGBUILD toggle opens the viewer and requests content.
    ///
    /// Inputs:
    /// - App state with a single selected result.
    /// - `Ctrl+X` key event matching the default `show_pkgbuild` chord.
    ///
    /// Output:
    /// - Handler returns `false`, sets `pkgb_visible`, and sends the selected item through `pkgb_tx`.
    ///
    /// Details:
    /// - Provides regression coverage for the channel send branch when the viewer becomes visible.
    fn global_show_pkgbuild_requests_content() {
        let mut app = new_app();
        app.results = vec![PackageItem {
            name: "ripgrep".into(),
            version: "14.0".into(),
            description: "fast search".into(),
            source: crate::state::Source::Aur,
            popularity: None,
            out_of_date: None,
            orphaned: false,
        }];
        app.selected = 0;

        let (details_tx, _details_rx) = mpsc::unbounded_channel::<PackageItem>();
        let (pkgb_tx, mut pkgb_rx) = mpsc::unbounded_channel::<PackageItem>();
        let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>();
        let (query_tx, _query_rx) = mpsc::unbounded_channel::<crate::state::QueryInput>();
        let (pkgb_check_tx, _pkgb_check_rx) =
            mpsc::unbounded_channel::<crate::state::PkgbuildCheckRequest>();

        let exit = handle_global_key(
            KeyEvent::new(KeyCode::Char('x'), KeyModifiers::CONTROL),
            &mut app,
            &details_tx,
            &pkgb_tx,
            &comments_tx,
            &query_tx,
            &pkgb_check_tx,
        );

        assert_eq!(exit, Some(false));
        assert!(app.pkgb_visible);
        let sent = pkgb_rx.try_recv().expect("pkgb request dispatched");
        assert_eq!(sent.name, "ripgrep");
    }

    #[test]
    /// What: Validate the exit key chord signals the application loop to terminate.
    ///
    /// Inputs:
    /// - Default keymap with `Ctrl+C` bound to exit.
    /// - `Ctrl+C` key event routed through the handler.
    ///
    /// Output:
    /// - Handler returns `true`, indicating the caller should stop processing events.
    ///
    /// Details:
    /// - Provides regression coverage so global exit handling keeps matching the configured chord.
    fn global_exit_chord_requests_shutdown() {
        let mut app = new_app();
        let (details_tx, _details_rx) = mpsc::unbounded_channel::<PackageItem>();
        let (pkgb_tx, _pkgb_rx) = mpsc::unbounded_channel::<PackageItem>();
        let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>();
        let (query_tx, _query_rx) = mpsc::unbounded_channel::<crate::state::QueryInput>();
        let (pkgb_check_tx, _pkgb_check_rx) =
            mpsc::unbounded_channel::<crate::state::PkgbuildCheckRequest>();

        let exit = handle_global_key(
            KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL),
            &mut app,
            &details_tx,
            &pkgb_tx,
            &comments_tx,
            &query_tx,
            &pkgb_check_tx,
        );

        assert_eq!(exit, Some(true));
    }
}