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
//! Simple modal mouse event handling (Help, `VirusTotalSetup`, News).

use crate::state::AppState;
use crossterm::event::{MouseEvent, MouseEventKind};

/// What: Calculate scroll offset to keep the selected item in the middle of the viewport.
///
/// Inputs:
/// - `selected`: Currently selected item index
/// - `total_items`: Total number of items in the list
/// - `visible_height`: Height of the visible content area (in lines)
///
/// Output:
/// - Scroll offset (lines) that centers the selected item
///
/// Details:
/// - Calculates scroll so selected item is in the middle of visible area
/// - Ensures scroll doesn't go negative or past the end
fn calculate_news_scroll_for_selection(
    selected: usize,
    total_items: usize,
    visible_height: u16,
) -> u16 {
    if total_items == 0 || visible_height == 0 {
        return 0;
    }

    // Clamp values to u16::MAX to prevent overflow in calculations.
    // Note: If selected or total_items exceeds u16::MAX, the scroll calculation will be
    // performed for the clamped values, which may not match the actual selected item.
    // This is acceptable since u16::MAX (65535) is far beyond practical UI list sizes.
    let selected_line = u16::try_from(selected).unwrap_or(u16::MAX);
    let total_lines = u16::try_from(total_items).unwrap_or(u16::MAX);
    // Ensure selected doesn't exceed total after clamping to maintain valid calculations
    let selected_line = selected_line.min(total_lines);

    // Calculate middle position: we want selected item to be at visible_height / 2
    let middle_offset = visible_height / 2;

    // Calculate desired scroll to center the selection
    let desired_scroll = selected_line.saturating_sub(middle_offset);

    // Calculate maximum scroll (when last item is at the bottom)
    let max_scroll = total_lines.saturating_sub(visible_height);

    // Clamp scroll to valid range
    desired_scroll.min(max_scroll)
}

/// Handle mouse events for the Help modal.
///
/// What: Process mouse interactions within the Help modal dialog.
///
/// Inputs:
/// - `m`: Mouse event including position, button, and modifiers
/// - `mx`: Mouse X coordinate (column)
/// - `my`: Mouse Y coordinate (row)
/// - `is_left_down`: Whether the left mouse button is pressed
/// - `app`: Mutable application state containing modal state and UI rectangles
///
/// Output:
/// - `false` if the event was handled
///
/// Details:
/// - Supports scrolling within content area.
/// - Closes modal on outside click.
/// - Consumes all mouse events while Help is open.
pub(super) fn handle_help_modal(
    m: MouseEvent,
    mx: u16,
    my: u16,
    is_left_down: bool,
    app: &mut AppState,
) -> bool {
    // Scroll within Help content area
    if let Some((x, y, w, h)) = app.help_rect
        && mx >= x
        && mx < x + w
        && my >= y
        && my < y + h
    {
        match m.kind {
            MouseEventKind::ScrollUp => {
                app.help_scroll = app.help_scroll.saturating_sub(1);
                return false;
            }
            MouseEventKind::ScrollDown => {
                app.help_scroll = app.help_scroll.saturating_add(1);
                return false;
            }
            _ => {}
        }
    }
    // Clicking outside closes the Help modal
    if is_left_down {
        if let Some((x, y, w, h)) = app.help_rect {
            // Outer rect includes borders around inner help rect
            let outer_x = x.saturating_sub(1);
            let outer_y = y.saturating_sub(1);
            let outer_w = w.saturating_add(2);
            let outer_h = h.saturating_add(2);
            if mx < outer_x || mx >= outer_x + outer_w || my < outer_y || my >= outer_y + outer_h {
                app.modal = crate::state::Modal::None;
            }
        } else {
            // Fallback: close on any click if no rect is known
            app.modal = crate::state::Modal::None;
        }
        return false;
    }
    // Consume remaining mouse events while Help is open
    false
}

/// Handle mouse events for the `VirusTotalSetup` modal.
///
/// What: Process mouse interactions within the `VirusTotalSetup` modal dialog.
///
/// Inputs:
/// - `_m`: Mouse event including position, button, and modifiers (unused but kept for signature consistency)
/// - `mx`: Mouse X coordinate (column)
/// - `my`: Mouse Y coordinate (row)
/// - `is_left_down`: Whether the left mouse button is pressed
/// - `app`: Mutable application state containing modal state and UI rectangles
///
/// Output:
/// - `false` if the event was handled
///
/// Details:
/// - Opens URL when clicking the link area.
/// - Consumes all mouse events while `VirusTotal` setup modal is open.
pub(super) fn handle_virustotal_modal(
    _m: MouseEvent,
    mx: u16,
    my: u16,
    is_left_down: bool,
    app: &AppState,
) -> bool {
    if is_left_down
        && let Some((x, y, w, h)) = app.vt_url_rect
        && mx >= x
        && mx < x + w
        && my >= y
        && my < y + h
    {
        let url = "https://www.virustotal.com/gui/my-apikey";
        std::thread::spawn(move || {
            let _ = std::process::Command::new("xdg-open")
                .arg(url)
                .stdin(std::process::Stdio::null())
                .stdout(std::process::Stdio::null())
                .stderr(std::process::Stdio::null())
                .spawn();
        });
    }
    // Consume all mouse events while VirusTotal setup modal is open
    false
}

/// Handle mouse events for the News modal.
///
/// What: Process mouse interactions within the News modal dialog.
///
/// Inputs:
/// - `m`: Mouse event including position, button, and modifiers
/// - `mx`: Mouse X coordinate (column)
/// - `my`: Mouse Y coordinate (row)
/// - `is_left_down`: Whether the left mouse button is pressed
/// - `app`: Mutable application state containing modal state and UI rectangles
///
/// Output:
/// - `Some(false)` if the event was handled, `None` if not handled.
///
/// Details:
/// - Handles item selection and URL opening.
/// - Handles scroll navigation.
/// - Closes modal on outside click.
pub(super) fn handle_announcement_modal(
    m: MouseEvent,
    mx: u16,
    my: u16,
    is_left_down: bool,
    app: &mut AppState,
) -> Option<bool> {
    if let crate::state::Modal::Announcement { scroll, .. } = &mut app.modal {
        // Left click: check for URL click first, then close on outside
        if is_left_down {
            // Check if click matches any URL position
            for (url_x, url_y, url_width, url) in &app.announcement_urls {
                if mx >= *url_x && mx < url_x.saturating_add(*url_width) && my == *url_y {
                    crate::util::open_url(url);
                    return Some(false);
                }
            }

            // Click outside closes the modal (dismiss temporarily)
            if let Some((x, y, w, h)) = app.announcement_rect
                && (mx < x || mx >= x + w || my < y || my >= y + h)
            {
                // Click outside closes the modal (dismiss temporarily)
                app.modal = crate::state::Modal::None;
            }
            return Some(false);
        }
        // Scroll within modal: scroll content
        match m.kind {
            MouseEventKind::ScrollUp => {
                if *scroll > 0 {
                    *scroll -= 1;
                }
                return Some(false);
            }
            MouseEventKind::ScrollDown => {
                *scroll = scroll.saturating_add(1);
                return Some(false);
            }
            _ => {}
        }
        // If modal is open and event wasn't handled above, consume it
        return Some(false);
    }
    None
}

/// What: Handle mouse events in the News modal.
///
/// Inputs:
/// - `m`: Mouse event
/// - `mx`: Mouse X coordinate
/// - `my`: Mouse Y coordinate
/// - `is_left_down`: Whether left mouse button is pressed
/// - `app`: Mutable application state
///
/// Output:
/// - `Some(true)` if application should exit
/// - `Some(false)` if event was handled
/// - `None` if event was not handled
///
/// Details:
/// - Handles left clicks to select/open news items or close modal on outside click
/// - Handles scrolling in the news list
pub(super) fn handle_news_modal(
    m: MouseEvent,
    mx: u16,
    my: u16,
    is_left_down: bool,
    app: &mut AppState,
) -> Option<bool> {
    if let crate::state::Modal::News {
        items,
        selected,
        scroll,
    } = &mut app.modal
    {
        // Left click: select/open or close on outside
        if is_left_down {
            if let Some((x, y, w, h)) = app.news_list_rect
                && mx >= x
                && mx < x + w
                && my >= y
                && my < y + h
            {
                // Calculate clicked row accounting for scroll offset
                let relative_y = my.saturating_sub(y);
                let clicked_row = (relative_y as usize).saturating_add(*scroll as usize);
                // Only open if clicking on an actual news item line (not empty space)
                if clicked_row < items.len() {
                    *selected = clicked_row;
                    // Update scroll to keep selection centered
                    *scroll = calculate_news_scroll_for_selection(*selected, items.len(), h);
                    if let Some(it) = items.get(*selected)
                        && let Some(url) = &it.url
                    {
                        crate::util::open_url(url);
                    }
                }
            } else if let Some((x, y, w, h)) = app.news_rect
                && (mx < x || mx >= x + w || my < y || my >= y + h)
            {
                // Click outside closes the modal
                app.modal = crate::state::Modal::None;
            }
            return Some(false);
        }
        // Scroll within modal: move selection
        match m.kind {
            MouseEventKind::ScrollUp => {
                if *selected > 0 {
                    *selected -= 1;
                    // Update scroll to keep selection centered
                    if let Some((_, _, _, visible_h)) = app.news_list_rect {
                        *scroll =
                            calculate_news_scroll_for_selection(*selected, items.len(), visible_h);
                    }
                }
                return Some(false);
            }
            MouseEventKind::ScrollDown => {
                if *selected + 1 < items.len() {
                    *selected += 1;
                    // Update scroll to keep selection centered
                    if let Some((_, _, _, visible_h)) = app.news_list_rect {
                        *scroll =
                            calculate_news_scroll_for_selection(*selected, items.len(), visible_h);
                    }
                }
                return Some(false);
            }
            _ => {}
        }
        // If modal is open and event wasn't handled above, consume it
        return Some(false);
    }
    None
}

/// Handle mouse events for Updates modal.
///
/// What: Process mouse interactions within the Updates modal (scroll, selection, close).
///
/// Inputs:
/// - `m`: Mouse event
/// - `mx`: Mouse X coordinate
/// - `my`: Mouse Y coordinate
/// - `is_left_down`: Whether left button is pressed
/// - `app`: Mutable application state
///
/// Output:
/// - `Some(false)` if handled, `None` otherwise
///
/// Details:
/// - Handles row selection on click.
/// - Handles scroll navigation (updates selection to match scroll position).
/// - Closes modal on outside click.
pub(super) fn handle_updates_modal(
    m: MouseEvent,
    mx: u16,
    my: u16,
    is_left_down: bool,
    app: &mut AppState,
) -> Option<bool> {
    let entry_line_starts = app.updates_modal_entry_line_starts.clone();
    let total_lines = app.updates_modal_total_lines;

    if let crate::state::Modal::Updates {
        ref mut scroll,
        ref entries,
        ref mut selected,
        filter_active,
        ref filter_query,
        ref mut last_selected_pkg_name,
        ref mut filtered_indices,
        ..
    } = app.modal
    {
        if filtered_indices.is_empty() && (!filter_active || filter_query.trim().is_empty()) {
            *filtered_indices = (0..entries.len()).collect();
        }
        // Left click: select row or close on outside
        if is_left_down {
            if let Some((x, y, w, h)) = app.updates_modal_content_rect
                && mx >= x
                && mx < x + w
                && my >= y
                && my < y + h
            {
                let relative_y = my.saturating_sub(y);
                let clicked_render_line = (relative_y as usize).saturating_add(*scroll as usize);
                let clicked_row = map_render_line_to_entry(
                    clicked_render_line,
                    &entry_line_starts,
                    filtered_indices.len(),
                );
                if let Some(&original_idx) = filtered_indices.get(clicked_row) {
                    *selected = original_idx;
                    if let Some((name, _, _)) = entries.get(*selected) {
                        *last_selected_pkg_name = Some(name.clone());
                    }
                    let visible_selected = filtered_indices
                        .iter()
                        .position(|&idx| idx == *selected)
                        .unwrap_or(0);
                    *scroll = crate::events::utils::compute_updates_modal_scroll_for_selection(
                        &entry_line_starts,
                        total_lines,
                        app.updates_modal_content_rect,
                        visible_selected,
                        filtered_indices.len(),
                        *scroll,
                    );
                }
            } else if let Some((x, y, w, h)) = app.updates_modal_rect {
                // Click outside modal closes it
                if mx < x || mx >= x + w || my < y || my >= y + h {
                    app.modal = crate::state::Modal::None;
                    return Some(false); // Return immediately after closing
                }
            }
            return Some(false);
        }

        // Handle scroll within modal: update selection to match scroll position
        match m.kind {
            crossterm::event::MouseEventKind::ScrollUp => {
                if let Some(visible) = filtered_indices.iter().position(|&idx| idx == *selected)
                    && visible > 0
                {
                    *selected = filtered_indices[visible - 1];
                }
                if let Some((name, _, _)) = entries.get(*selected) {
                    *last_selected_pkg_name = Some(name.clone());
                }
                // Auto-scroll to keep selected item visible
                let visible_selected = filtered_indices
                    .iter()
                    .position(|&idx| idx == *selected)
                    .unwrap_or(0);
                *scroll = crate::events::utils::compute_updates_modal_scroll_for_selection(
                    &entry_line_starts,
                    total_lines,
                    app.updates_modal_content_rect,
                    visible_selected,
                    filtered_indices.len(),
                    *scroll,
                );
                return Some(false);
            }
            crossterm::event::MouseEventKind::ScrollDown => {
                if let Some(visible) = filtered_indices.iter().position(|&idx| idx == *selected)
                    && visible + 1 < filtered_indices.len()
                {
                    *selected = filtered_indices[visible + 1];
                }
                if let Some((name, _, _)) = entries.get(*selected) {
                    *last_selected_pkg_name = Some(name.clone());
                }
                // Auto-scroll to keep selected item visible
                let visible_selected = filtered_indices
                    .iter()
                    .position(|&idx| idx == *selected)
                    .unwrap_or(0);
                *scroll = crate::events::utils::compute_updates_modal_scroll_for_selection(
                    &entry_line_starts,
                    total_lines,
                    app.updates_modal_content_rect,
                    visible_selected,
                    filtered_indices.len(),
                    *scroll,
                );
                return Some(false);
            }
            _ => {}
        }

        // Consume all mouse events while Updates modal is open
        return Some(false);
    }
    None
}

/// Handle mouse events for `OptionalDeps` modal.
///
/// What: Start startup setup wizard when clicking the top-right `Wizard` button; wheel scroll moves
/// selection inside the modal bounds.
///
/// Inputs:
/// - `m`: Mouse event including wheel deltas.
/// - `mx` / `my`: Pointer coordinates.
/// - `is_left_down`: Primary button pressed.
/// - `app`: Application state and cached modal rectangles.
///
/// Output:
/// - `Some(false)` while this modal is open (events are consumed).
///
/// Details:
/// - Wheel handling matches Up/Down keys in [`crate::events::modals::optional_deps::handle_optional_deps`].
pub(super) fn handle_optional_deps_modal(
    m: MouseEvent,
    mx: u16,
    my: u16,
    is_left_down: bool,
    app: &mut AppState,
) -> Option<bool> {
    if let crate::state::Modal::OptionalDeps { rows, selected, .. } = &mut app.modal {
        if is_left_down
            && let Some((x, y, w, h)) = app.optional_deps_wizard_rect
            && mx >= x
            && mx < x + w
            && my >= y
            && my < y + h
        {
            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),
            );
            app.aur_ssh_help_ready = None;
            app.modal = crate::state::Modal::StartupSetupSelector {
                cursor: 0,
                selected: std::collections::HashSet::new(),
                active_privilege_tool: crate::logic::privilege::active_tool().ok(),
            };
            return Some(false);
        }

        if let Some((x, y, w, h)) = app.optional_deps_modal_rect
            && mx >= x
            && mx < x + w
            && my >= y
            && my < y + h
        {
            match m.kind {
                MouseEventKind::ScrollUp => {
                    if *selected > 0 {
                        *selected -= 1;
                    }
                    return Some(false);
                }
                MouseEventKind::ScrollDown => {
                    if *selected + 1 < rows.len() {
                        *selected += 1;
                    }
                    return Some(false);
                }
                _ => {}
            }
        }
        return Some(false);
    }
    None
}

/// Handle mouse events for the System Update modal.
///
/// What: Move the option cursor with the scroll wheel when the pointer is inside the modal.
///
/// Inputs:
/// - `m`: Mouse event.
/// - `mx` / `my`: Pointer coordinates.
/// - `is_left_down`: Primary button pressed (reserved; no click actions yet).
/// - `app`: Application state.
///
/// Output:
/// - `Some(false)` while the modal is open.
///
/// Details:
/// - Cursor range matches keyboard navigation (`0..=4`).
pub(super) fn handle_system_update_modal(
    m: MouseEvent,
    mx: u16,
    my: u16,
    _is_left_down: bool,
    app: &mut AppState,
) -> Option<bool> {
    if let crate::state::Modal::SystemUpdate { cursor, .. } = &mut app.modal {
        let in_modal = app
            .system_update_modal_rect
            .is_some_and(|(x, y, w, h)| mx >= x && mx < x + w && my >= y && my < y + h);
        if in_modal {
            match m.kind {
                MouseEventKind::ScrollUp => {
                    if *cursor > 0 {
                        *cursor -= 1;
                    }
                    return Some(false);
                }
                MouseEventKind::ScrollDown => {
                    let max_cursor = 4;
                    if *cursor < max_cursor {
                        *cursor += 1;
                    }
                    return Some(false);
                }
                _ => {}
            }
        }
        return Some(false);
    }
    None
}

/// Handle mouse events for the Repositories modal.
///
/// What: Scroll the repository list with the wheel when the pointer is inside the modal.
///
/// Inputs:
/// - `m`: Mouse event.
/// - `mx` / `my`: Pointer coordinates.
/// - `is_left_down`: Primary button pressed (unused; keyboard/Enter drive apply).
/// - `app`: Application state.
///
/// Output:
/// - `Some(false)` while the modal is open.
///
/// Details:
/// - Delegates row steps to [`crate::events::modals::repositories_modal_wheel_step`].
pub(super) fn handle_repositories_modal(
    m: MouseEvent,
    mx: u16,
    my: u16,
    _is_left_down: bool,
    app: &mut AppState,
) -> Option<bool> {
    if let crate::state::Modal::Repositories {
        selected,
        scroll,
        rows,
        ..
    } = &mut app.modal
    {
        let row_count = rows.len();
        let in_modal = app
            .repositories_modal_rect
            .is_some_and(|(x, y, w, h)| mx >= x && mx < x + w && my >= y && my < y + h);
        if in_modal {
            match m.kind {
                MouseEventKind::ScrollUp => {
                    crate::events::modals::repositories_modal_wheel_step(
                        row_count, selected, scroll, false,
                    );
                    return Some(false);
                }
                MouseEventKind::ScrollDown => {
                    crate::events::modals::repositories_modal_wheel_step(
                        row_count, selected, scroll, true,
                    );
                    return Some(false);
                }
                _ => {}
            }
        }
        return Some(false);
    }
    None
}

/// What: Handle mouse clicks on the AUR SSH setup modal copy row.
///
/// Inputs:
/// - `mx`: Mouse column coordinate.
/// - `my`: Mouse row coordinate.
/// - `is_left_down`: Whether the primary button was pressed.
/// - `app`: Application state (`ssh_setup_copy_key_rect` and `SshAurSetup` status lines).
///
/// Output:
/// - `Some(false)` when the copy action ran and the toast was updated.
/// - `None` when the click missed the copy row or no public key line is available.
///
/// Details:
/// - Uses `wl-copy` or `xclip` via `try_copy_aur_ssh_public_key_from_status_lines`, matching the `C` shortcut.
pub(super) fn handle_ssh_aur_setup_modal(
    _m: MouseEvent,
    mx: u16,
    my: u16,
    is_left_down: bool,
    app: &mut AppState,
) -> Option<bool> {
    if !is_left_down {
        return None;
    }
    let (x, y, w, h) = app.ssh_setup_copy_key_rect?;
    if mx < x || mx >= x.saturating_add(w) || my < y || my >= y.saturating_add(h) {
        return None;
    }
    let status_lines = match &app.modal {
        crate::state::Modal::SshAurSetup { status_lines, .. } => status_lines.as_slice(),
        _ => return None,
    };
    match crate::logic::ssh_setup::try_copy_aur_ssh_public_key_from_status_lines(status_lines) {
        None => None,
        Some(Ok(())) => {
            app.toast_message = Some(crate::i18n::t(app, "app.toasts.copied_to_clipboard"));
            app.toast_expires_at =
                Some(std::time::Instant::now() + std::time::Duration::from_secs(3));
            Some(false)
        }
        Some(Err(msg)) => {
            app.toast_message = Some(msg);
            app.toast_expires_at =
                Some(std::time::Instant::now() + std::time::Duration::from_secs(5));
            Some(false)
        }
    }
}

/// What: Resolve a rendered line index to the owning updates entry index.
///
/// Inputs:
/// - `render_line`: Absolute rendered line index within the wrapped list
/// - `entry_line_starts`: Entry index to first rendered line mapping
/// - `entry_count`: Total number of entries
///
/// Output:
/// - Entry index owning `render_line`, clamped to list bounds
///
/// Details:
/// - Uses partition-point semantics to find the latest start <= `render_line`.
fn map_render_line_to_entry(
    render_line: usize,
    entry_line_starts: &[u16],
    entry_count: usize,
) -> usize {
    if entry_count == 0 {
        return 0;
    }
    let line = u16::try_from(render_line).unwrap_or(u16::MAX);
    let idx = entry_line_starts.partition_point(|&start| start <= line);
    idx.saturating_sub(1).min(entry_count.saturating_sub(1))
}

#[cfg(test)]
mod tests {
    use super::{
        handle_optional_deps_modal, handle_repositories_modal, handle_system_update_modal,
        handle_updates_modal, map_render_line_to_entry,
    };
    use crate::state::types::{
        OptionalDepRow, RepositoryKeyTrust, RepositoryModalRow, RepositoryPacmanStatus,
    };
    use crate::state::{AppState, Modal};
    use crossterm::event::{KeyModifiers, MouseEvent, MouseEventKind};
    use std::collections::HashSet;

    #[test]
    /// What: Ensure render-line hit testing maps wrapped lines to the correct entry.
    ///
    /// Inputs:
    /// - Synthetic entry line starts with mixed entry heights.
    ///
    /// Output:
    /// - Returns the owning entry index for each tested rendered line.
    ///
    /// Details:
    /// - Protects click hit-testing correctness in the updates modal.
    fn map_render_line_to_entry_resolves_wrapped_ranges() {
        let starts = vec![0, 3, 5];
        assert_eq!(map_render_line_to_entry(0, &starts, 3), 0);
        assert_eq!(map_render_line_to_entry(2, &starts, 3), 0);
        assert_eq!(map_render_line_to_entry(3, &starts, 3), 1);
        assert_eq!(map_render_line_to_entry(4, &starts, 3), 1);
        assert_eq!(map_render_line_to_entry(5, &starts, 3), 2);
        assert_eq!(map_render_line_to_entry(999, &starts, 3), 2);
    }

    #[test]
    /// What: Keep an empty filtered result set empty when the filter is active.
    ///
    /// Inputs:
    /// - Updates modal with `filter_active = true`, non-empty query, and `filtered_indices = []`.
    /// - A mouse wheel event routed through `handle_updates_modal`.
    ///
    /// Output:
    /// - `filtered_indices` remains empty after handling.
    ///
    /// Details:
    /// - Prevents mouse handling from treating legitimate "0 matches" as uninitialized state.
    fn updates_modal_mouse_preserves_empty_active_filter_result_set() {
        let mut app = AppState {
            modal: Modal::Updates {
                entries: vec![
                    ("alpha".to_string(), "1".to_string(), "2".to_string()),
                    ("bravo".to_string(), "1".to_string(), "2".to_string()),
                ],
                scroll: 0,
                selected: 0,
                filter_active: true,
                filter_query: "zzz".to_string(),
                filter_caret: 3,
                last_selected_pkg_name: None,
                filtered_indices: Vec::new(),
                selected_pkg_names: HashSet::new(),
            },
            ..AppState::default()
        };

        let mouse_event = MouseEvent {
            kind: MouseEventKind::ScrollDown,
            column: 0,
            row: 0,
            modifiers: KeyModifiers::empty(),
        };

        let handled = handle_updates_modal(mouse_event, 0, 0, false, &mut app);
        assert_eq!(handled, Some(false));

        if let Modal::Updates {
            filtered_indices, ..
        } = &app.modal
        {
            assert!(
                filtered_indices.is_empty(),
                "active non-empty filter must preserve an empty match set"
            );
        } else {
            panic!("updates modal should remain open");
        }
    }

    #[test]
    /// What: Verify wheel down inside the System Update modal moves the cursor.
    ///
    /// Inputs:
    /// - `SystemUpdate` at cursor 0 with a populated `system_update_modal_rect`.
    /// - `ScrollDown` at coordinates inside the rectangle.
    ///
    /// Output:
    /// - Cursor becomes 1.
    ///
    /// Details:
    /// - Ensures modal mouse routing applies to the update dialog.
    fn system_update_wheel_inside_moves_cursor() {
        let mut app = AppState {
            modal: Modal::SystemUpdate {
                do_mirrors: false,
                do_pacman: false,
                force_sync: false,
                do_aur: false,
                do_cache: false,
                country_idx: 0,
                countries: vec!["Worldwide".to_string()],
                mirror_count: 10,
                cursor: 0,
            },
            system_update_modal_rect: Some((10, 10, 40, 14)),
            ..AppState::default()
        };
        let m = MouseEvent {
            kind: MouseEventKind::ScrollDown,
            column: 15,
            row: 12,
            modifiers: KeyModifiers::empty(),
        };
        let _ = handle_system_update_modal(m, 15, 12, false, &mut app);
        match &app.modal {
            Modal::SystemUpdate { cursor, .. } => assert_eq!(*cursor, 1),
            _ => panic!("expected SystemUpdate"),
        }
    }

    #[test]
    /// What: Verify wheel outside the System Update modal rect does not move the cursor.
    ///
    /// Inputs:
    /// - Same modal and rect as the inside test; pointer at (0, 0).
    ///
    /// Output:
    /// - Cursor stays 0.
    ///
    /// Details:
    /// - Prevents stray wheel events from changing focus when the pointer is elsewhere.
    fn system_update_wheel_outside_rect_ignores_scroll() {
        let mut app = AppState {
            modal: Modal::SystemUpdate {
                do_mirrors: false,
                do_pacman: false,
                force_sync: false,
                do_aur: false,
                do_cache: false,
                country_idx: 0,
                countries: vec!["Worldwide".to_string()],
                mirror_count: 10,
                cursor: 0,
            },
            system_update_modal_rect: Some((10, 10, 40, 14)),
            ..AppState::default()
        };
        let m = MouseEvent {
            kind: MouseEventKind::ScrollDown,
            column: 0,
            row: 0,
            modifiers: KeyModifiers::empty(),
        };
        let _ = handle_system_update_modal(m, 0, 0, false, &mut app);
        match &app.modal {
            Modal::SystemUpdate { cursor, .. } => assert_eq!(*cursor, 0),
            _ => panic!("expected SystemUpdate"),
        }
    }

    fn sample_repo_row(name: &str) -> RepositoryModalRow {
        RepositoryModalRow {
            pacman_section_name: name.to_string(),
            results_filter_display: String::new(),
            pacman_status: RepositoryPacmanStatus::Absent,
            source_hint: None,
            key_trust: RepositoryKeyTrust::NotApplicable,
        }
    }

    #[test]
    /// What: Verify wheel down in the Repositories modal advances selection and scroll.
    ///
    /// Inputs:
    /// - Two repository rows, `repositories_modal_rect` covering the pointer.
    ///
    /// Output:
    /// - Selected index is 1 after `ScrollDown`.
    ///
    /// Details:
    /// - Uses the same scroll clamping as keyboard navigation.
    fn repositories_wheel_moves_selection() {
        let rows = vec![sample_repo_row("a"), sample_repo_row("b")];
        let mut app = AppState {
            modal: Modal::Repositories {
                rows,
                selected: 0,
                scroll: 0,
                repos_conf_error: None,
                pacman_warnings: Vec::new(),
            },
            repositories_modal_rect: Some((5, 5, 60, 20)),
            ..AppState::default()
        };
        let m = MouseEvent {
            kind: MouseEventKind::ScrollDown,
            column: 10,
            row: 10,
            modifiers: KeyModifiers::empty(),
        };
        let _ = handle_repositories_modal(m, 10, 10, false, &mut app);
        match &app.modal {
            Modal::Repositories { selected, .. } => assert_eq!(*selected, 1),
            _ => panic!("expected Repositories"),
        }
    }

    #[test]
    /// What: Verify wheel down in the Optional Deps modal advances the selected row.
    ///
    /// Inputs:
    /// - Two optional-dep rows and `optional_deps_modal_rect` around the pointer.
    ///
    /// Output:
    /// - Selected index becomes 1.
    ///
    /// Details:
    /// - Complements wizard click handling on the same modal.
    fn optional_deps_wheel_moves_selection() {
        let rows = vec![
            OptionalDepRow {
                label: "a".to_string(),
                package: "pkg-a".to_string(),
                installed: false,
                selectable: true,
                note: None,
            },
            OptionalDepRow {
                label: "b".to_string(),
                package: "pkg-b".to_string(),
                installed: false,
                selectable: true,
                note: None,
            },
        ];
        let mut app = AppState {
            modal: Modal::OptionalDeps {
                rows,
                selected: 0,
                selected_pkg_names: HashSet::new(),
            },
            optional_deps_modal_rect: Some((8, 8, 50, 18)),
            ..AppState::default()
        };
        let m = MouseEvent {
            kind: MouseEventKind::ScrollDown,
            column: 20,
            row: 12,
            modifiers: KeyModifiers::empty(),
        };
        let _ = handle_optional_deps_modal(m, 20, 12, false, &mut app);
        match &app.modal {
            Modal::OptionalDeps { selected, .. } => assert_eq!(*selected, 1),
            _ => panic!("expected OptionalDeps"),
        }
    }
}