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
//! Action key handlers for Preflight modal.

use std::collections::HashMap;

use crate::state::AppState;
use crate::state::modal::ServiceRestartDecision;

use super::context::{EnterOrSpaceContext, PreflightKeyContext};
use super::tab_handlers::handle_enter_or_space;
use crate::events::preflight::modal::close_preflight_modal;

/// What: Handle Esc key - close the Preflight modal.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - Always returns `false` to continue event processing.
///
/// Details:
/// - Closes the preflight modal but keeps the TUI open.
pub(super) fn handle_esc_key(app: &mut AppState) -> bool {
    let service_info = if let crate::state::Modal::Preflight { service_info, .. } = &app.modal {
        service_info.clone()
    } else {
        Vec::new()
    };
    close_preflight_modal(app, &service_info);
    // Return false to keep TUI open - modal is closed but app continues
    false
}

/// What: Handle Enter key - execute Enter/Space action.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - Always returns `false` to continue event processing.
///
/// Details:
/// - May close the modal if action requires it, but TUI remains open.
pub(super) fn handle_enter_key(app: &mut AppState) -> bool {
    let should_close = if let crate::state::Modal::Preflight {
        tab,
        items,
        dependency_info,
        dep_selected,
        dep_tree_expanded,
        file_info,
        file_selected,
        file_tree_expanded,
        sandbox_info,
        sandbox_selected,
        sandbox_tree_expanded,
        selected_optdepends,
        service_info,
        service_selected,
        ..
    } = &mut app.modal
    {
        handle_enter_or_space(EnterOrSpaceContext {
            tab,
            items,
            dependency_info,
            dep_selected: *dep_selected,
            dep_tree_expanded,
            file_info,
            file_selected: *file_selected,
            file_tree_expanded,
            sandbox_info,
            sandbox_selected: *sandbox_selected,
            sandbox_tree_expanded,
            selected_optdepends,
            service_info,
            service_selected: *service_selected,
        })
    } else {
        false
    };

    if should_close {
        // Use the same flow as "p" key - delegate to handle_proceed functions
        // This ensures reinstall check and batch update check happen before password prompt
        let (items_clone, action_clone, header_chips_clone, cascade_mode) =
            if let crate::state::Modal::Preflight {
                items,
                action,
                header_chips,
                cascade_mode,
                ..
            } = &app.modal
            {
                (items.clone(), *action, header_chips.clone(), *cascade_mode)
            } else {
                // Not a Preflight modal, just close it
                let service_info =
                    if let crate::state::Modal::Preflight { service_info, .. } = &app.modal {
                        service_info.clone()
                    } else {
                        Vec::new()
                    };
                close_preflight_modal(app, &service_info);
                return false;
            };

        // Get service info before closing modal
        let service_info = if let crate::state::Modal::Preflight { service_info, .. } = &app.modal {
            service_info.clone()
        } else {
            Vec::new()
        };
        close_preflight_modal(app, &service_info);

        // Use the same proceed handlers as "p" key to ensure consistent flow
        match action_clone {
            crate::state::PreflightAction::Install => {
                use super::command_keys;
                command_keys::handle_proceed_install(app, items_clone, header_chips_clone);
            }
            crate::state::PreflightAction::Remove => {
                use super::command_keys;
                command_keys::handle_proceed_remove(
                    app,
                    items_clone,
                    cascade_mode,
                    header_chips_clone,
                );
            }
            crate::state::PreflightAction::Downgrade => {
                // Downgrade operations always need sudo (downgrade tool requires sudo)
                // Check faillock status before showing password prompt
                let username = std::env::var("USER").unwrap_or_else(|_| "user".to_string());
                if let Some(lockout_msg) =
                    crate::logic::faillock::get_lockout_message_if_locked(&username, app)
                {
                    // User is locked out - show warning and don't show password prompt
                    app.modal = crate::state::Modal::Alert {
                        message: lockout_msg,
                    };
                    return false;
                }
                let settings = crate::theme::settings();
                if crate::logic::password::should_use_interactive_auth_handoff(&settings) {
                    crate::events::spawn_downgrade_in_terminal(app, &items_clone);
                } else {
                    app.modal = crate::state::Modal::PasswordPrompt {
                        purpose: crate::state::modal::PasswordPurpose::Downgrade,
                        items: items_clone,
                        input: crate::state::SecureString::default(),
                        cursor: 0,
                        error: None,
                    };
                    app.pending_exec_header_chips = Some(header_chips_clone);
                }
            }
        }
        // Return false to keep TUI open - modal is closed but app continues
        return false;
    }
    false
}

/// What: Start command execution by transitioning to `PreflightExec` and storing `ExecutorRequest`.
///
/// Inputs:
/// - `app`: Mutable application state
/// - `items`: Packages to install/remove
/// - `action`: Install or Remove action
/// - `header_chips`: Header chip metrics
/// - `password`: Optional password (if already obtained from password prompt)
///
/// Details:
/// - Transitions to `PreflightExec` modal and stores `ExecutorRequest` for processing in tick handler
#[allow(clippy::needless_pass_by_value)] // header_chips is consumed in modal creation
pub fn start_execution(
    app: &mut AppState,
    items: &[crate::state::PackageItem],
    action: crate::state::PreflightAction,
    header_chips: crate::state::modal::PreflightHeaderChips,
    password: Option<crate::state::SecureString>,
) {
    use crate::install::ExecutorRequest;

    // Note: Reinstall check is now done in handle_proceed_install BEFORE password prompt
    // This function is called after reinstall confirmation (if needed) and password prompt (if needed)

    tracing::debug!(
        action = ?action,
        item_count = items.len(),
        header_chips = ?header_chips,
        has_password = password.is_some(),
        "[Preflight] Transitioning modal: Preflight -> PreflightExec"
    );

    // Transition to PreflightExec modal
    app.modal = crate::state::Modal::PreflightExec {
        items: items.to_vec(),
        action,
        tab: crate::state::PreflightTab::Summary,
        verbose: false,
        log_lines: Vec::new(),
        abortable: false,
        header_chips,
        success: None,
    };

    // Store executor request for processing in tick handler
    app.pending_executor_request = Some(match action {
        crate::state::PreflightAction::Install => ExecutorRequest::Install {
            items: items.to_vec(),
            password,
            dry_run: app.dry_run,
        },
        crate::state::PreflightAction::Remove => {
            let names: Vec<String> = items.iter().map(|p| p.name.clone()).collect();
            ExecutorRequest::Remove {
                names,
                password,
                cascade: app.remove_cascade_mode,
                dry_run: app.dry_run,
            }
        }
        crate::state::PreflightAction::Downgrade => {
            let names: Vec<String> = items.iter().map(|p| p.name.clone()).collect();
            ExecutorRequest::Downgrade {
                names,
                password,
                dry_run: app.dry_run,
            }
        }
    });
}

/// What: Handle Space key - toggle expand/collapse.
///
/// Inputs:
/// - `ctx`: Preflight key context
///
/// Output:
/// - Always returns `false`.
pub(super) fn handle_space_key(ctx: &mut PreflightKeyContext<'_>) -> bool {
    handle_enter_or_space(EnterOrSpaceContext {
        tab: ctx.tab,
        items: ctx.items,
        dependency_info: ctx.dependency_info,
        dep_selected: *ctx.dep_selected,
        dep_tree_expanded: ctx.dep_tree_expanded,
        file_info: ctx.file_info,
        file_selected: *ctx.file_selected,
        file_tree_expanded: ctx.file_tree_expanded,
        sandbox_info: ctx.sandbox_info,
        sandbox_selected: *ctx.sandbox_selected,
        sandbox_tree_expanded: ctx.sandbox_tree_expanded,
        selected_optdepends: ctx.selected_optdepends,
        service_info: ctx.service_info,
        service_selected: *ctx.service_selected,
    });
    false
}

/// What: Handle Shift+R key - re-run all analyses.
///
/// Inputs:
/// - `app`: Mutable application state
///
/// Output:
/// - Always returns `false`.
pub(super) fn handle_shift_r_key(app: &mut AppState) -> bool {
    tracing::info!("Shift+R pressed: Re-running all preflight analyses");

    let (items, action) = if let crate::state::Modal::Preflight { items, action, .. } = &app.modal {
        (items.clone(), *action)
    } else {
        return false;
    };

    // Clear all cached data in the modal
    if let crate::state::Modal::Preflight {
        dependency_info,
        deps_error,
        file_info,
        files_error,
        service_info,
        services_error,
        services_loaded,
        sandbox_info,
        sandbox_error,
        sandbox_loaded,
        summary,
        dep_selected,
        file_selected,
        service_selected,
        sandbox_selected,
        dep_tree_expanded,
        file_tree_expanded,
        sandbox_tree_expanded,
        ..
    } = &mut app.modal
    {
        *dependency_info = Vec::new();
        *deps_error = None;
        *file_info = Vec::new();
        *files_error = None;
        *service_info = Vec::new();
        *services_error = None;
        *services_loaded = false;
        *sandbox_info = Vec::new();
        *sandbox_error = None;
        *sandbox_loaded = false;
        *summary = None;

        *dep_selected = 0;
        *file_selected = 0;
        *service_selected = 0;
        *sandbox_selected = 0;

        dep_tree_expanded.clear();
        file_tree_expanded.clear();
        sandbox_tree_expanded.clear();
    }

    // Reset cancellation flag
    app.preflight_cancelled
        .store(false, std::sync::atomic::Ordering::Relaxed);

    // Queue all stages for background resolution (same as opening modal)
    app.preflight_summary_items = Some((items.clone(), action));
    app.preflight_summary_resolving = true;

    if matches!(action, crate::state::PreflightAction::Install) {
        app.preflight_deps_items = Some((items.clone(), crate::state::PreflightAction::Install));
        app.preflight_deps_resolving = true;

        app.preflight_files_items = Some(items.clone());
        app.preflight_files_resolving = true;

        app.preflight_services_items = Some(items.clone());
        app.preflight_services_resolving = true;

        // Only queue sandbox for AUR packages
        let aur_items: Vec<_> = items
            .iter()
            .filter(|p| matches!(p.source, crate::state::Source::Aur))
            .cloned()
            .collect();
        if aur_items.is_empty() {
            app.preflight_sandbox_items = None;
            app.preflight_sandbox_resolving = false;
            if let crate::state::Modal::Preflight { sandbox_loaded, .. } = &mut app.modal {
                *sandbox_loaded = true;
            }
        } else {
            app.preflight_sandbox_items = Some(aur_items);
            app.preflight_sandbox_resolving = true;
        }
    }

    app.toast_message = Some("Re-running all preflight analyses...".to_string());
    app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(3));
    false
}

/// What: Handle regular R key - retry resolution for current tab.
///
/// Inputs:
/// - `ctx`: Preflight key context
///
/// Output:
/// - Always returns `false`.
pub(super) fn handle_r_key(ctx: &mut PreflightKeyContext<'_>) -> bool {
    if *ctx.tab == crate::state::PreflightTab::Services && !ctx.service_info.is_empty() {
        // Toggle restart decision for selected service (only if no error)
        if *ctx.service_selected >= ctx.service_info.len() {
            *ctx.service_selected = ctx.service_info.len().saturating_sub(1);
        }
        if let Some(service) = ctx.service_info.get_mut(*ctx.service_selected) {
            service.restart_decision = ServiceRestartDecision::Restart;
        }
    } else if *ctx.tab == crate::state::PreflightTab::Deps
        && matches!(*ctx.action, crate::state::PreflightAction::Install)
    {
        // Retry dependency resolution
        *ctx.deps_error = None;
        *ctx.dependency_info = crate::logic::deps::resolve_dependencies(ctx.items);
        *ctx.dep_selected = 0;
    } else if *ctx.tab == crate::state::PreflightTab::Files {
        // Retry file resolution
        *ctx.files_error = None;
        *ctx.file_info = crate::logic::files::resolve_file_changes(ctx.items, *ctx.action);
        *ctx.file_selected = 0;
    } else if *ctx.tab == crate::state::PreflightTab::Services {
        // Retry service resolution
        *ctx.services_error = None;
        *ctx.services_loaded = false;
        *ctx.service_info = crate::logic::services::resolve_service_impacts(ctx.items, *ctx.action);
        *ctx.service_selected = 0;
        *ctx.services_loaded = true;
    }
    false
}

/// What: Handle D key - set service restart decision to Defer.
///
/// Inputs:
/// - `ctx`: Preflight key context
///
/// Output:
/// - Always returns `false`.
pub(super) fn handle_d_key(ctx: &mut PreflightKeyContext<'_>) -> bool {
    if *ctx.tab == crate::state::PreflightTab::Services && !ctx.service_info.is_empty() {
        if *ctx.service_selected >= ctx.service_info.len() {
            *ctx.service_selected = ctx.service_info.len().saturating_sub(1);
        }
        if let Some(service) = ctx.service_info.get_mut(*ctx.service_selected) {
            service.restart_decision = ServiceRestartDecision::Defer;
        }
    }
    false
}

/// What: Handle A key - expand/collapse all package groups.
///
/// Inputs:
/// - `ctx`: Preflight key context
///
/// Output:
/// - Always returns `false`.
pub(super) fn handle_a_key(ctx: &mut PreflightKeyContext<'_>) -> bool {
    if *ctx.tab == crate::state::PreflightTab::Deps && !ctx.dependency_info.is_empty() {
        let mut grouped: HashMap<String, Vec<&crate::state::modal::DependencyInfo>> =
            HashMap::new();
        for dep in ctx.dependency_info.iter() {
            for req_by in &dep.required_by {
                grouped.entry(req_by.clone()).or_default().push(dep);
            }
        }

        let all_expanded = ctx
            .items
            .iter()
            .all(|p| ctx.dep_tree_expanded.contains(&p.name));
        if all_expanded {
            // Collapse all
            ctx.dep_tree_expanded.clear();
        } else {
            // Expand all packages (even if they have no dependencies)
            for pkg_name in ctx.items.iter().map(|p| &p.name) {
                ctx.dep_tree_expanded.insert(pkg_name.clone());
            }
        }
    } else if *ctx.tab == crate::state::PreflightTab::Files && !ctx.file_info.is_empty() {
        // Expand/collapse all packages in Files tab
        let all_expanded = ctx
            .file_info
            .iter()
            .filter(|p| !p.files.is_empty())
            .all(|p| ctx.file_tree_expanded.contains(&p.name));
        if all_expanded {
            // Collapse all
            ctx.file_tree_expanded.clear();
        } else {
            // Expand all
            for pkg_info in ctx.file_info.iter() {
                if !pkg_info.files.is_empty() {
                    ctx.file_tree_expanded.insert(pkg_info.name.clone());
                }
            }
        }
    }
    false
}