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
//! Details pane mouse event handling (URL, PKGBUILD buttons, scroll).

use crossterm::event::{MouseButton, MouseEvent, MouseEventKind};
use crossterm::execute;
use tokio::sync::mpsc;

use crate::state::{AppState, PackageItem, PkgbuildCheckRequest};

/// Check if a point is within a rectangle.
///
/// What: Determines if coordinates (mx, my) fall within the bounds of a rectangle.
///
/// Inputs:
/// - `mx`: Mouse X coordinate (column)
/// - `my`: Mouse Y coordinate (row)
/// - `rect`: Optional rectangle as (x, y, width, height)
///
/// Output:
/// - `true` if the point is within the rectangle, `false` otherwise.
const fn is_point_in_rect(mx: u16, my: u16, rect: Option<(u16, u16, u16, u16)>) -> bool {
    if let Some((x, y, w, h)) = rect {
        mx >= x && mx < x + w && my >= y && my < y + h
    } else {
        false
    }
}

/// Handle URL button click with Ctrl+Shift modifier.
///
/// What: Opens the package URL when Ctrl+Shift+LeftClick is performed on the URL button.
///
/// Inputs:
/// - `mx`: Mouse X coordinate (column)
/// - `my`: Mouse Y coordinate (row)
/// - `app`: Mutable application state
///
/// Output:
/// - `true` if the click was handled, `false` otherwise.
fn handle_url_click(m: MouseEvent, mx: u16, my: u16, app: &mut AppState) -> bool {
    // Only log if click is near the URL area to avoid spam
    if let Some((_, ry, _, _)) = app.url_button_rect
        && my >= ry.saturating_sub(2)
        && my <= ry.saturating_add(2)
    {
        tracing::info!(
            mx,
            my,
            rect = ?app.url_button_rect,
            url = %app.details.url,
            in_rect = is_point_in_rect(mx, my, app.url_button_rect),
            "URL click check"
        );
    }
    if is_point_in_rect(mx, my, app.url_button_rect)
        && !app.details.url.is_empty()
        && matches!(m.kind, MouseEventKind::Down(MouseButton::Left))
    {
        tracing::info!(url = %app.details.url, "opening URL via Ctrl+Shift+Click");
        app.mouse_disabled_in_details = false;
        crate::util::open_url(&app.details.url);
        true
    } else {
        false
    }
}

/// Handle PKGBUILD toggle button click.
///
/// What: Opens or closes the PKGBUILD viewer and requests content when opening.
///
/// Inputs:
/// - `mx`: Mouse X coordinate (column)
/// - `my`: Mouse Y coordinate (row)
/// - `app`: Mutable application state
/// - `pkgb_tx`: Channel to request PKGBUILD content
///
/// Output:
/// - `true` if the click was handled, `false` otherwise.
fn handle_pkgb_toggle_click(
    mx: u16,
    my: u16,
    app: &mut AppState,
    pkgb_tx: &mpsc::UnboundedSender<PackageItem>,
) -> bool {
    if !is_point_in_rect(mx, my, app.pkgb_button_rect) {
        return false;
    }

    app.mouse_disabled_in_details = false;
    if app.pkgb_visible {
        // Close if already open
        app.pkgb_visible = false;
        app.pkgb_text = None;
        app.pkgb_package_name = None;
        app.pkgb_scroll = 0;
        app.pkgb_rect = None;
    } else {
        // Open and (re)load
        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);
        }
    }
    true
}

/// Handle comments toggle button click.
///
/// What: Opens or closes the comments viewer and requests content when opening.
///
/// Inputs:
/// - `mx`: Mouse X coordinate (column)
/// - `my`: Mouse Y coordinate (row)
/// - `app`: Mutable application state
/// - `comments_tx`: Channel to request comments content
///
/// Output:
/// - `true` if the click was handled, `false` otherwise.
fn handle_comments_toggle_click(
    mx: u16,
    my: u16,
    app: &mut AppState,
    comments_tx: &mpsc::UnboundedSender<String>,
) -> bool {
    if !is_point_in_rect(mx, my, app.comments_button_rect) {
        return false;
    }

    // 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;
    }

    app.mouse_disabled_in_details = false;
    if app.comments_visible {
        // Close if already open
        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 {
        // Open and (re)load
        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 true;
            }
            // 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());
        }
    }
    true
}

/// Copy PKGBUILD text to clipboard using wl-copy or xclip.
///
/// What: Attempts to copy text to clipboard using Wayland (wl-copy) or X11 (xclip) tools.
///
/// Inputs:
/// - `text`: The text to copy
///
/// Output:
/// - `String` with success/error message.
fn copy_to_clipboard(text: String) -> String {
    let suffix = {
        let s = crate::theme::settings().clipboard_suffix;
        if s.trim().is_empty() {
            String::new()
        } else {
            format!("\n\n{s}\n")
        }
    };
    let payload = if suffix.is_empty() {
        text
    } else {
        format!("{text}{suffix}")
    };

    // Try wl-copy on Wayland
    if std::env::var("WAYLAND_DISPLAY").is_ok()
        && let Ok(mut child) = std::process::Command::new("wl-copy")
            .stdin(std::process::Stdio::piped())
            .stdout(std::process::Stdio::null())
            .stderr(std::process::Stdio::null())
            .spawn()
    {
        if let Some(mut sin) = child.stdin.take() {
            let _ = std::io::Write::write_all(&mut sin, payload.as_bytes());
        }
        let _ = child.wait();
        return "PKGBUILD is added to the Clipboard".to_string();
    }

    // Try xclip as a generic fallback on X11
    if let Ok(mut child) = std::process::Command::new("xclip")
        .args(["-selection", "clipboard"])
        .stdin(std::process::Stdio::piped())
        .stdout(std::process::Stdio::null())
        .stderr(std::process::Stdio::null())
        .spawn()
    {
        if let Some(mut sin) = child.stdin.take() {
            let _ = std::io::Write::write_all(&mut sin, payload.as_bytes());
        }
        let _ = child.wait();
        return "PKGBUILD is added to the Clipboard".to_string();
    }

    // Neither wl-copy nor xclip worked — report guidance
    if std::env::var("WAYLAND_DISPLAY").is_ok() {
        "Clipboard tool not found. Please install 'wl-clipboard' (provides wl-copy) or 'xclip'."
            .to_string()
    } else {
        "Clipboard tool not found. Please install 'xclip' or 'wl-clipboard' (wl-copy).".to_string()
    }
}

/// Handle copy PKGBUILD button click.
///
/// What: Copies PKGBUILD text to clipboard in a background thread and shows toast notification.
///
/// Inputs:
/// - `mx`: Mouse X coordinate (column)
/// - `my`: Mouse Y coordinate (row)
/// - `app`: Mutable application state
///
/// Output:
/// - `true` if the click was handled, `false` otherwise.
fn handle_copy_pkgb_click(mx: u16, my: u16, app: &mut AppState) -> bool {
    if !is_point_in_rect(mx, my, app.pkgb_check_button_rect) {
        return false;
    }

    app.mouse_disabled_in_details = false;
    if let Some(text) = app.pkgb_text.clone() {
        let (tx_msg, rx_msg) = std::sync::mpsc::channel::<Option<String>>();
        std::thread::spawn(move || {
            let result = copy_to_clipboard(text);
            let _ = tx_msg.send(Some(result));
        });
        // Default optimistic toast; overwritten by worker if needed
        app.toast_message = Some(crate::i18n::t(app, "app.toasts.copying_pkgbuild"));
        app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(3));
        // Try to receive the result quickly without blocking UI long
        if let Ok(Some(msg)) = rx_msg.recv_timeout(std::time::Duration::from_millis(50)) {
            app.toast_message = Some(msg);
            app.toast_expires_at =
                Some(std::time::Instant::now() + std::time::Duration::from_secs(4));
        }
    } 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));
    }
    true
}

/// Handle reload PKGBUILD button click.
///
/// What: Schedules a debounced reload of the PKGBUILD content.
///
/// Inputs:
/// - `mx`: Mouse X coordinate (column)
/// - `my`: Mouse Y coordinate (row)
/// - `app`: Mutable application state
///
/// Output:
/// - `true` if the click was handled, `false` otherwise.
fn handle_reload_pkgb_click(mx: u16, my: u16, app: &mut AppState) -> bool {
    if !is_point_in_rect(mx, my, app.pkgb_reload_button_rect) {
        return false;
    }

    app.mouse_disabled_in_details = false;
    if let Some(item) = app.results.get(app.selected).cloned() {
        app.pkgb_reload_requested_at = Some(std::time::Instant::now());
        app.pkgb_reload_requested_for = Some(item.name);
        app.pkgb_text = None; // Clear old PKGBUILD while loading
        app.pkgb_package_name = None;
    }
    true
}

/// Handle run PKGBUILD checks button click.
fn handle_run_pkgb_checks_click(
    mx: u16,
    my: u16,
    app: &mut AppState,
    pkgb_check_tx: &mpsc::UnboundedSender<PkgbuildCheckRequest>,
) -> bool {
    if !is_point_in_rect(mx, my, app.pkgb_run_checks_button_rect) {
        return false;
    }
    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 true;
    };
    let package_name = app
        .results
        .get(app.selected)
        .map_or_else(String::new, |item| item.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));
    }
    true
}

/// Handle mouse scroll events in the details pane.
///
/// What: Updates details scroll position when mouse wheel is used within the details rectangle.
///
/// Inputs:
/// - `m`: Mouse event including scroll kind
/// - `mx`: Mouse X coordinate (column)
/// - `my`: Mouse Y coordinate (row)
/// - `app`: Mutable application state
///
/// Output:
/// - `true` if the scroll was handled, `false` otherwise.
#[allow(clippy::missing_const_for_fn)]
fn handle_details_scroll(m: MouseEvent, mx: u16, my: u16, app: &mut AppState) -> bool {
    if !is_point_in_rect(mx, my, app.details_rect) {
        return false;
    }

    match m.kind {
        MouseEventKind::ScrollUp => {
            if matches!(app.app_mode, crate::state::types::AppMode::News) {
                app.news_content_scroll = app.news_content_scroll.saturating_sub(1);
            } else {
                app.details_scroll = app.details_scroll.saturating_sub(1);
            }
            true
        }
        MouseEventKind::ScrollDown => {
            if matches!(app.app_mode, crate::state::types::AppMode::News) {
                app.news_content_scroll = app.news_content_scroll.saturating_add(1);
            } else {
                app.details_scroll = app.details_scroll.saturating_add(1);
            }
            true
        }
        _ => false,
    }
}

/// Handle text selection blocking in details pane.
///
/// What: Ignores clicks within details pane when text selection is enabled, ensuring mouse capture stays enabled.
///
/// Inputs:
/// - `mx`: Mouse X coordinate (column)
/// - `my`: Mouse Y coordinate (row)
/// - `app`: Mutable application state
///
/// Output:
/// - `true` if the click should be blocked, `false` otherwise.
fn handle_text_selection_block(mx: u16, my: u16, app: &mut AppState) -> bool {
    if !app.mouse_disabled_in_details {
        return false;
    }

    if !is_point_in_rect(mx, my, app.details_rect) {
        return false;
    }

    // Ensure terminal mouse capture stays enabled globally, while app ignores clicks here
    if !app.mouse_capture_enabled {
        // Skip mouse capture in headless/test mode to prevent escape sequences in test output
        if std::env::var("PACSEA_TEST_HEADLESS").ok().as_deref() != Some("1") {
            let _ = execute!(std::io::stdout(), crossterm::event::EnableMouseCapture);
        }
        app.mouse_capture_enabled = true;
    }
    true
}

/// Handle URL click in comments.
///
/// What: Opens a URL from comments when clicked.
///
/// Inputs:
/// - `mx`: Mouse X coordinate (column)
/// - `my`: Mouse Y coordinate (row)
/// - `app`: Mutable application state
///
/// Output:
/// - `true` if a URL was clicked and opened, `false` otherwise.
fn handle_comment_url_click(mx: u16, my: u16, app: &AppState) -> bool {
    // Check if click is within comments area
    if !is_point_in_rect(mx, my, app.comments_rect) {
        return false;
    }

    // Check if click matches any URL position
    for (url_x, url_y, url_width, url) in &app.comments_urls {
        if mx >= *url_x && mx < url_x.saturating_add(*url_width) && my == *url_y {
            crate::util::open_url(url);
            return true;
        }
    }

    false
}

/// Handle author name click in comments.
///
/// What: Opens the AUR profile page for the clicked author.
///
/// Inputs:
/// - `mx`: Mouse X coordinate (column)
/// - `my`: Mouse Y coordinate (row)
/// - `app`: Application state
///
/// Output:
/// - `true` if an author was clicked and profile opened, `false` otherwise.
fn handle_comment_author_click(mx: u16, my: u16, app: &AppState) -> bool {
    // Check if click is within comments area
    if !is_point_in_rect(mx, my, app.comments_rect) {
        return false;
    }

    // Check if click matches any author position
    for (author_x, author_y, author_width, username) in &app.comments_authors {
        if mx >= *author_x && mx < author_x.saturating_add(*author_width) && my == *author_y {
            let profile_url = format!("https://aur.archlinux.org/account/{username}");
            crate::util::open_url(&profile_url);
            return true;
        }
    }

    false
}

/// Handle date click in comments.
///
/// What: Opens the URL associated with the clicked date.
///
/// Inputs:
/// - `mx`: Mouse X coordinate (column)
/// - `my`: Mouse Y coordinate (row)
/// - `app`: Application state (read-only)
///
/// Output:
/// - `true` if the click was handled, `false` otherwise.
fn handle_comment_date_click(mx: u16, my: u16, app: &AppState) -> bool {
    // Check if click is within comments area
    if !is_point_in_rect(mx, my, app.comments_rect) {
        return false;
    }

    // Check if click matches any date position
    for (date_x, date_y, date_width, url) in &app.comments_dates {
        if mx >= *date_x && mx < date_x.saturating_add(*date_width) && my == *date_y {
            crate::util::open_url(url);
            return true;
        }
    }

    false
}

/// Handle mouse events for the details pane.
///
/// What: Process mouse interactions within the package details pane, including URL clicks,
/// PKGBUILD viewer controls, and scroll handling.
///
/// 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
/// - `ctrl`: Whether the Control modifier is active
/// - `shift`: Whether the Shift modifier is active
/// - `app`: Mutable application state containing details pane state and UI rectangles
/// - `pkgb_tx`: Channel to request PKGBUILD content when opening the viewer
/// - `comments_tx`: Channel to request comments content when opening the viewer
///
/// Output:
/// - `Some(bool)` if the event was handled (consumed by details pane), `None` if not handled.
///   The boolean value indicates whether the application should exit (always `false` here).
///
/// Details:
/// - URL clicks: Ctrl+Shift+LeftClick on URL button opens the URL via `xdg-open`.
/// - Comment URL clicks: Left click on URLs in comments opens them in the default browser.
/// - Comment author clicks: Left click on author names in comments opens their AUR profile page.
/// - Comment date clicks: Left click on dates in comments opens the associated URL.
/// - PKGBUILD toggle: Left click on toggle button opens/closes the PKGBUILD viewer and requests content.
/// - Comments toggle: Left click on toggle button opens/closes the comments viewer and requests content (AUR only).
/// - Copy PKGBUILD: Left click on copy button copies PKGBUILD to clipboard (wl-copy/xclip).
/// - Reload PKGBUILD: Left click on reload button schedules a debounced reload.
/// - Scroll: Mouse wheel scrolls the details content when within the details rectangle.
/// - Text selection: When `mouse_disabled_in_details` is true, clicks are ignored to allow text selection.
#[allow(clippy::too_many_arguments)]
pub(super) fn handle_details_mouse(
    m: MouseEvent,
    mx: u16,
    my: u16,
    is_left_down: bool,
    ctrl: bool,
    shift: bool,
    app: &mut AppState,
    pkgb_tx: &mpsc::UnboundedSender<PackageItem>,
    comments_tx: &mpsc::UnboundedSender<String>,
    pkgb_check_tx: &mpsc::UnboundedSender<PkgbuildCheckRequest>,
) -> Option<bool> {
    // In news mode, allow simple left-click on URL (no Ctrl+Shift needed)
    if is_left_down
        && matches!(app.app_mode, crate::state::types::AppMode::News)
        && is_point_in_rect(mx, my, app.url_button_rect)
        && !app.details.url.is_empty()
    {
        tracing::info!(
            mx,
            my,
            url = %app.details.url,
            rect = ?app.url_button_rect,
            "News URL clicked"
        );
        crate::util::open_url(&app.details.url);
        return Some(false);
    }

    // Handle modifier-clicks in details first, even when selection is enabled (package mode)
    if is_left_down && ctrl && shift {
        tracing::info!(
            mx,
            my,
            url_button_rect = ?app.url_button_rect,
            details_rect = ?app.details_rect,
            url = %app.details.url,
            "Ctrl+Shift+Click in details area"
        );
        if handle_url_click(m, mx, my, app) {
            return Some(false);
        }
    }

    // Handle comment URL, author, and date clicks (before other button clicks)
    if is_left_down && handle_comment_url_click(mx, my, app) {
        return Some(false);
    }
    if is_left_down && handle_comment_author_click(mx, my, app) {
        return Some(false);
    }
    if is_left_down && handle_comment_date_click(mx, my, app) {
        return Some(false);
    }

    // Handle button clicks
    if is_left_down {
        if handle_pkgb_toggle_click(mx, my, app, pkgb_tx) {
            return Some(false);
        }
        if handle_comments_toggle_click(mx, my, app, comments_tx) {
            return Some(false);
        }
        if handle_copy_pkgb_click(mx, my, app) {
            return Some(false);
        }
        if handle_reload_pkgb_click(mx, my, app) {
            return Some(false);
        }
        if handle_run_pkgb_checks_click(mx, my, app, pkgb_check_tx) {
            return Some(false);
        }
    }

    // Handle scroll events (before click blocking)
    if handle_details_scroll(m, mx, my, app) {
        return Some(false);
    }

    // Handle text selection blocking
    if handle_text_selection_block(mx, my, app) {
        return Some(false);
    }

    None
}