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
use ratatui::{
    style::{Modifier, Style},
    text::{Line, Span},
    widgets::ListItem,
};

use crate::state::{AppState, PackageItem, Source};
use crate::theme::{PackageMarker, Theme};

/// What: Check if a package is in any of the install/remove/downgrade lists.
///
/// Inputs:
/// - `package`: Package to check
/// - `app`: Application state containing the lists
///
/// Output:
/// - Struct containing boolean flags for each list type
///
/// Details:
/// - Performs case-insensitive name matching against all three lists.
pub struct PackageListStatus {
    /// Whether the package is in the install list.
    pub in_install: bool,
    /// Whether the package is in the remove list.
    pub in_remove: bool,
    /// Whether the package is in the downgrade list.
    pub in_downgrade: bool,
}

/// What: Check if a package is in any of the install/remove/downgrade lists.
///
/// Inputs:
/// - `package`: Package to check
/// - `app`: Application state containing the lists
///
/// Output:
/// - `PackageListStatus` struct with boolean flags for each list type
///
/// Details:
/// - Performs case-insensitive name matching against all three lists.
pub fn check_package_in_lists(package: &PackageItem, app: &AppState) -> PackageListStatus {
    let in_install = app
        .install_list
        .iter()
        .any(|it| it.name.eq_ignore_ascii_case(&package.name));
    let in_remove = app
        .remove_list
        .iter()
        .any(|it| it.name.eq_ignore_ascii_case(&package.name));
    let in_downgrade = app
        .downgrade_list
        .iter()
        .any(|it| it.name.eq_ignore_ascii_case(&package.name));

    PackageListStatus {
        in_install,
        in_remove,
        in_downgrade,
    }
}

/// What: Determine the source label and color for a package.
///
/// Inputs:
/// - `source`: Package source (Official or AUR)
/// - `package_name`: Name of the package
/// - `app`: Application state for accessing details cache
/// - `theme`: Theme for color values
///
/// Output:
/// - Tuple of (label: String, color: Color)
///
/// Details:
/// - For official packages, determines label from repo/owner and selects color
///   based on dynamic repo mapping (mauve), optional repos (sapphire), or standard (green).
/// - For AUR packages, returns "AUR" with yellow color.
pub fn determine_source_label_and_color(
    source: &Source,
    package_name: &str,
    app: &AppState,
    theme: &Theme,
) -> (String, ratatui::style::Color) {
    match source {
        Source::Official { repo, .. } => {
            let owner = app
                .details_cache
                .get(package_name)
                .map(|d| d.owner.clone())
                .unwrap_or_default();
            let label = crate::logic::distro::label_for_official(repo, package_name, &owner);
            let repo_lower = repo.to_lowercase();
            let color = if app.repo_results_filter_by_name.contains_key(&repo_lower) {
                theme.mauve
            } else if label == "EOS"
                || label == "CachyOS"
                || label == "Artix"
                || label == "OMNI"
                || label == "UNI"
                || label == "LIB32"
                || label == "GALAXY"
                || label == "WORLD"
                || label == "SYSTEM"
                || label == "Manjaro"
            {
                theme.sapphire
            } else {
                theme.green
            };
            (label, color)
        }
        Source::Aur => ("AUR".to_string(), theme.yellow),
    }
}

/// What: Build a `ListItem` with package marker styling applied.
///
/// Inputs:
/// - `segs`: Vector of spans representing the package information
/// - `marker_type`: Type of marker to apply (`FullLine`, `Front`, or `End`)
/// - `label`: Marker label text (e.g., "[+]", "[-]", "[↓]")
/// - `color`: Color for the marker
/// - `in_install`: Whether package is in install list (affects `FullLine` background)
/// - `theme`: Theme for additional color values
///
/// Output:
/// - `ListItem` with marker styling applied
///
/// Details:
/// - `FullLine`: Colors the entire line background with dimmed color for installs
/// - Front: Adds marker at the beginning of the line
/// - End: Adds marker at the end of the line
pub fn build_package_marker_item(
    segs: Vec<Span<'static>>,
    marker_type: PackageMarker,
    label: &str,
    color: ratatui::style::Color,
    in_install: bool,
    theme: &Theme,
) -> ListItem<'static> {
    match marker_type {
        PackageMarker::FullLine => {
            let mut item = ListItem::new(Line::from(segs));
            let bgc = if in_install {
                if let ratatui::style::Color::Rgb(r, g, b) = color {
                    ratatui::style::Color::Rgb(
                        u8::try_from((u16::from(r) * 85) / 100).unwrap_or(255),
                        u8::try_from((u16::from(g) * 85) / 100).unwrap_or(255),
                        u8::try_from((u16::from(b) * 85) / 100).unwrap_or(255),
                    )
                } else {
                    color
                }
            } else {
                color
            };
            item = item.style(Style::default().fg(theme.crust).bg(bgc));
            item
        }
        PackageMarker::Front => {
            let mut new_segs: Vec<Span> = Vec::new();
            new_segs.push(Span::styled(
                label.to_string(),
                Style::default()
                    .fg(theme.crust)
                    .bg(color)
                    .add_modifier(Modifier::BOLD),
            ));
            new_segs.push(Span::raw(" "));
            new_segs.extend(segs);
            ListItem::new(Line::from(new_segs))
        }
        PackageMarker::End => {
            let mut new_segs = segs.clone();
            new_segs.push(Span::raw(" "));
            new_segs.push(Span::styled(
                label.to_string(),
                Style::default()
                    .fg(theme.crust)
                    .bg(color)
                    .add_modifier(Modifier::BOLD),
            ));
            ListItem::new(Line::from(new_segs))
        }
    }
}

/// What: Build optional inline vote-state spans for AUR package rows.
///
/// Inputs:
/// - `package`: Package currently rendered in results list.
/// - `app`: Application state containing vote-state cache.
/// - `theme`: Theme colors.
///
/// Output:
/// - Optional vector of spans to append when package is AUR.
///
/// Details:
/// - Renders compact states: `Loading`, `Voted`, `Not voted`, `Error`.
fn aur_vote_state_spans(
    package: &PackageItem,
    app: &AppState,
    theme: &Theme,
) -> Option<Vec<Span<'static>>> {
    if !matches!(package.source, Source::Aur) {
        return None;
    }
    let state = app
        .aur_vote_state_by_pkgbase
        .get(&package.name)
        .unwrap_or(&crate::state::app_state::AurVoteStateUi::Unknown);
    let (label, color, bold) = match state {
        crate::state::app_state::AurVoteStateUi::Unknown => return None,
        crate::state::app_state::AurVoteStateUi::Loading => {
            ("[Vote: loading]", theme.overlay1, false)
        }
        crate::state::app_state::AurVoteStateUi::Voted => ("[Vote: voted]", theme.green, true),
        crate::state::app_state::AurVoteStateUi::NotVoted => {
            ("[Vote: not voted]", theme.overlay1, false)
        }
        crate::state::app_state::AurVoteStateUi::Error(_) => ("[Vote: error]", theme.red, true),
    };
    let style = if bold {
        Style::default().fg(color).add_modifier(Modifier::BOLD)
    } else {
        Style::default().fg(color)
    };
    Some(vec![
        Span::raw("  "),
        Span::styled(label.to_string(), style),
    ])
}

/// What: Build a `ListItem` for a package in the results list.
///
/// Inputs:
/// - `package`: Package to render
/// - `app`: Application state for accessing cache and lists
/// - `theme`: Theme for styling
/// - `prefs`: Theme preferences including package marker type
/// - `in_viewport`: Whether this item is in the visible viewport
///
/// Output:
/// - `ListItem` ready for rendering
///
/// Details:
/// - Returns empty item if not in viewport for performance.
/// - Builds spans for popularity, source label, name, version, description, and installed status.
/// - Applies package markers if package is in install/remove/downgrade lists.
pub fn build_list_item(
    package: &PackageItem,
    app: &AppState,
    theme: &Theme,
    prefs: &crate::theme::Settings,
    in_viewport: bool,
) -> ListItem<'static> {
    // For rows outside the viewport, render a cheap empty item
    if !in_viewport {
        return ListItem::new(Line::raw(""));
    }

    let (src, color) = determine_source_label_and_color(&package.source, &package.name, app, theme);

    let desc = if package.description.is_empty() {
        app.details_cache
            .get(&package.name)
            .map(|d| d.description.clone())
            .unwrap_or_default()
    } else {
        package.description.clone()
    };

    let installed = crate::index::is_installed(&package.name);

    // Build the main content spans
    let mut segs: Vec<Span<'static>> = Vec::new();
    if let Some(pop) = package.popularity {
        segs.push(Span::styled(
            format!("Pop: {pop:.2} "),
            Style::default().fg(theme.overlay1),
        ));
    }
    segs.push(Span::styled(format!("{src} "), Style::default().fg(color)));
    // Add AUR status markers (out-of-date and orphaned) for AUR packages
    if matches!(package.source, Source::Aur) {
        if package.out_of_date.is_some() {
            segs.push(Span::styled(
                "[OOD] ",
                Style::default().fg(theme.red).add_modifier(Modifier::BOLD),
            ));
        }
        if package.orphaned {
            segs.push(Span::styled(
                "[ORPHAN] ",
                Style::default().fg(theme.red).add_modifier(Modifier::BOLD),
            ));
        }
    }
    segs.push(Span::styled(
        package.name.clone(),
        Style::default().fg(theme.text).add_modifier(Modifier::BOLD),
    ));
    segs.push(Span::styled(
        format!("  {}", package.version),
        Style::default().fg(theme.overlay1),
    ));
    if !desc.is_empty() {
        segs.push(Span::raw("  - "));
        segs.push(Span::styled(desc, Style::default().fg(theme.overlay2)));
    }
    if installed {
        segs.push(Span::raw("  "));
        segs.push(Span::styled(
            "[Installed]",
            Style::default()
                .fg(theme.green)
                .add_modifier(Modifier::BOLD),
        ));
    }
    if let Some(vote_spans) = aur_vote_state_spans(package, app, theme) {
        segs.extend(vote_spans);
    }

    // Check if package is in any lists and apply markers if needed
    let list_status = check_package_in_lists(package, app);
    if list_status.in_install || list_status.in_remove || list_status.in_downgrade {
        let (label, marker_color) = if list_status.in_remove {
            ("[-]", theme.red)
        } else if list_status.in_downgrade {
            ("[↓]", theme.yellow)
        } else {
            ("[+]", theme.green)
        };
        build_package_marker_item(
            segs,
            prefs.package_marker,
            label,
            marker_color,
            list_status.in_install,
            theme,
        )
    } else {
        ListItem::new(Line::from(segs))
    }
}

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

    #[test]
    fn test_check_package_in_lists() {
        let mut app = crate::state::AppState::default();
        let package = PackageItem {
            name: "test-pkg".to_string(),
            version: "1.0".to_string(),
            description: String::new(),
            source: Source::Aur,
            popularity: None,
            out_of_date: None,
            orphaned: false,
        };

        // Initially not in any list
        let status = check_package_in_lists(&package, &app);
        assert!(!status.in_install);
        assert!(!status.in_remove);
        assert!(!status.in_downgrade);

        // Add to install list
        app.install_list.push(crate::state::PackageItem {
            name: "TEST-PKG".to_string(), // Test case-insensitive
            version: "1.0".to_string(),
            description: String::new(),
            source: Source::Aur,
            popularity: None,
            out_of_date: None,
            orphaned: false,
        });
        let status = check_package_in_lists(&package, &app);
        assert!(status.in_install);
        assert!(!status.in_remove);
        assert!(!status.in_downgrade);
    }

    #[test]
    fn test_determine_source_label_and_color_aur() {
        let app = crate::state::AppState::default();
        let theme = crate::theme::theme();
        let source = Source::Aur;

        let (label, color) = determine_source_label_and_color(&source, "test-pkg", &app, &theme);
        assert_eq!(label, "AUR");
        assert_eq!(color, theme.yellow);
    }

    #[test]
    fn test_determine_source_label_and_color_official() {
        let app = crate::state::AppState::default();
        let theme = crate::theme::theme();
        let source = Source::Official {
            repo: "core".to_string(),
            arch: "x86_64".to_string(),
        };

        let (label, color) = determine_source_label_and_color(&source, "test-pkg", &app, &theme);
        assert_eq!(label, "core");
        assert_eq!(color, theme.green);
    }

    #[test]
    fn test_determine_source_label_and_color_dynamic_repo_is_mauve() {
        let mut app = crate::state::AppState::default();
        app.repo_results_filter_by_name
            .insert("core".to_string(), "my-core".to_string());
        let theme = crate::theme::theme();
        let source = Source::Official {
            repo: "core".to_string(),
            arch: "x86_64".to_string(),
        };

        let (label, color) = determine_source_label_and_color(&source, "test-pkg", &app, &theme);
        assert_eq!(label, "core");
        assert_eq!(color, theme.mauve);
    }

    #[test]
    fn test_build_list_item_not_in_viewport() {
        let app = crate::state::AppState::default();
        let theme = crate::theme::theme();
        let prefs = crate::theme::settings();
        let package = PackageItem {
            name: "test-pkg".to_string(),
            version: "1.0".to_string(),
            description: "Test description".to_string(),
            source: Source::Aur,
            popularity: None,
            out_of_date: None,
            orphaned: false,
        };

        let item = build_list_item(&package, &app, &theme, &prefs, false);
        // Verify that the item is created (not in viewport returns empty item)
        let _ = item;
    }

    #[test]
    fn test_build_list_item_in_viewport() {
        let app = crate::state::AppState::default();
        let theme = crate::theme::theme();
        let prefs = crate::theme::settings();
        let package = PackageItem {
            name: "test-pkg".to_string(),
            version: "1.0".to_string(),
            description: "Test description".to_string(),
            source: Source::Aur,
            popularity: Some(1.5),
            out_of_date: None,
            orphaned: false,
        };

        let item = build_list_item(&package, &app, &theme, &prefs, true);
        // Verify that the item is created (in viewport returns populated item)
        let _ = item;
    }
}