Skip to main content

pacsea/app/runtime/
init.rs

1use std::{collections::HashMap, fs, path::Path, time::Instant};
2
3use crate::index as pkgindex;
4use crate::state::{AppState, PackageDetails, PackageItem};
5
6use super::super::deps_cache;
7use super::super::files_cache;
8use super::super::sandbox_cache;
9use super::super::services_cache;
10
11/// What: Initialize the locale system: resolve locale, load translations, set up fallbacks.
12///
13/// Inputs:
14/// - `app`: Application state to populate with locale and translations
15/// - `locale_pref`: Locale preference from `settings.conf` (empty = auto-detect)
16/// - `_prefs`: Settings struct (unused but kept for future use)
17///
18/// Output:
19/// - Populates `app.locale`, `app.translations`, and `app.translations_fallback`
20///
21/// Details:
22/// - Resolves locale using fallback chain (settings -> system -> default)
23/// - Loads English fallback translations first (required)
24/// - Loads primary locale translations if different from English
25/// - Handles errors gracefully: falls back to English if locale file missing/invalid
26/// - Logs warnings for missing files but continues execution
27pub fn initialize_locale_system(
28    app: &mut AppState,
29    locale_pref: &str,
30    _prefs: &crate::theme::Settings,
31) {
32    // Get paths - try both development and installed locations
33    let locales_dir = crate::i18n::find_locales_dir().unwrap_or_else(|| {
34        std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))
35            .join("config")
36            .join("locales")
37    });
38    let Some(i18n_config_path) = crate::i18n::find_config_file("i18n.yml") else {
39        tracing::error!(
40            "i18n config file not found in development or installed locations. Using default locale 'en-US'."
41        );
42        app.locale = "en-US".to_string();
43        app.translations = std::collections::HashMap::new();
44        app.translations_fallback = std::collections::HashMap::new();
45        return;
46    };
47
48    // Resolve locale
49    let resolver = crate::i18n::LocaleResolver::new(&i18n_config_path);
50    let resolved_locale = resolver.resolve(locale_pref);
51
52    tracing::info!(
53        "Resolved locale: '{}' (from settings: '{}')",
54        &resolved_locale,
55        if locale_pref.trim().is_empty() {
56            "<auto-detect>"
57        } else {
58            locale_pref
59        }
60    );
61    app.locale.clone_from(&resolved_locale);
62
63    // Load translations
64    let mut loader = crate::i18n::LocaleLoader::new(locales_dir);
65
66    // Load fallback (English) translations first - this is required
67    match loader.load("en-US") {
68        Ok(fallback) => {
69            let key_count = fallback.len();
70            app.translations_fallback = fallback;
71            tracing::debug!("Loaded English fallback translations ({} keys)", key_count);
72        }
73        Err(e) => {
74            tracing::error!(
75                "Failed to load English fallback translations: {}. Application may show untranslated keys.",
76                e
77            );
78            app.translations_fallback = std::collections::HashMap::new();
79        }
80    }
81
82    // Load primary locale translations
83    if resolved_locale == "en-US" {
84        // Already loaded English as fallback, use it as primary too
85        app.translations = app.translations_fallback.clone();
86        tracing::debug!("Using English as primary locale");
87    } else {
88        match loader.load(&resolved_locale) {
89            Ok(translations) => {
90                let key_count = translations.len();
91                app.translations = translations;
92                tracing::info!(
93                    "Loaded translations for locale '{}' ({} keys)",
94                    resolved_locale,
95                    key_count
96                );
97                // Debug: Check if specific keys exist
98                let test_keys = [
99                    "app.details.footer.search_hint",
100                    "app.details.footer.confirm_installation",
101                ];
102                for key in &test_keys {
103                    if app.translations.contains_key(*key) {
104                        tracing::debug!("  ✓ Key '{}' found in translations", key);
105                    } else {
106                        tracing::debug!("  ✗ Key '{}' NOT found in translations", key);
107                    }
108                }
109            }
110            Err(e) => {
111                tracing::warn!(
112                    "Failed to load translations for locale '{}': {}. Using English fallback.",
113                    resolved_locale,
114                    e
115                );
116                // Use empty map - translate_with_fallback will use English fallback
117                app.translations = std::collections::HashMap::new();
118            }
119        }
120    }
121}
122
123/// What: Run startup config preflight exactly once and return resolved settings.
124///
125/// Inputs:
126/// - None.
127///
128/// Output:
129/// - Returns the current `Settings` after legacy migration and key ensure operations.
130///
131/// Details:
132/// - Migrates legacy config layout into split config files when needed.
133/// - Ensures `theme.conf` and `settings.conf` include all known keys.
134/// - Reads and returns settings from disk after preflight so downstream initialization
135///   can reuse the same resolved snapshot.
136pub fn run_startup_config_preflight() -> crate::theme::Settings {
137    crate::theme::maybe_migrate_legacy_confs();
138    crate::theme::ensure_theme_keys_present();
139    let prefs = crate::theme::settings();
140    crate::theme::ensure_settings_keys_present(&prefs);
141    prefs
142}
143
144/// What: Initialize application state: load settings, caches, and persisted data.
145///
146/// Inputs:
147/// - `app`: Application state to initialize
148/// - `dry_run_flag`: When `true`, install/remove/downgrade actions are displayed but not executed
149/// - `headless`: When `true`, skip terminal-dependent operations
150///
151/// Output:
152/// - Returns flags indicating which caches need background resolution
153///
154/// Details:
155/// - Migrates legacy configs and loads settings
156/// - Loads persisted caches (details, recent, install list, dependencies, files, services, sandbox)
157/// - Initializes locale system
158/// - Checks for GNOME terminal if on GNOME desktop
159#[allow(clippy::struct_excessive_bools)]
160pub struct InitFlags {
161    /// Whether dependency resolution is needed (cache missing or invalid).
162    pub needs_deps_resolution: bool,
163    /// Whether file analysis is needed (cache missing or invalid).
164    pub needs_files_resolution: bool,
165    /// Whether service analysis is needed (cache missing or invalid).
166    pub needs_services_resolution: bool,
167    /// Whether sandbox analysis is needed (cache missing or invalid).
168    pub needs_sandbox_resolution: bool,
169}
170
171/// What: Load a cache with signature validation, returning whether resolution is needed.
172///
173/// Inputs:
174/// - `install_list`: Current install list to compute signature from
175/// - `cache_path`: Path to the cache file
176/// - `compute_signature`: Function to compute signature from install list
177/// - `load_cache`: Function to load cache from path and signature
178/// - `cache_name`: Name of the cache for logging
179///
180/// Output:
181/// - `(Option<T>, bool)` where first is the loaded cache (if valid) and second indicates if resolution is needed
182///
183/// Details:
184/// - Returns `(None, true)` if install list is empty or cache is missing/invalid
185/// - Returns `(Some(cache), false)` if cache is valid
186fn load_cache_with_signature<T>(
187    install_list: &[crate::state::PackageItem],
188    cache_path: &std::path::PathBuf,
189    compute_signature: impl Fn(&[crate::state::PackageItem]) -> Vec<String>,
190    load_cache: impl Fn(&std::path::PathBuf, &[String]) -> Option<T>,
191    cache_name: &str,
192) -> (Option<T>, bool) {
193    if install_list.is_empty() {
194        return (None, false);
195    }
196
197    let signature = compute_signature(install_list);
198    load_cache(cache_path, &signature).map_or_else(
199        || {
200            tracing::info!(
201                "{} cache missing or invalid, will trigger background resolution",
202                cache_name
203            );
204            (None, true)
205        },
206        |cached| (Some(cached), false),
207    )
208}
209
210/// What: Ensure cache directories exist before writing placeholder files.
211///
212/// Inputs:
213/// - `path`: Target cache file path whose parent directory should exist.
214///
215/// Output:
216/// - Parent directory is created if missing; logs a warning on failure.
217///
218/// Details:
219/// - No-op when the path has no parent.
220fn ensure_cache_parent_dir(path: &Path) {
221    if let Some(parent) = path.parent()
222        && let Err(error) = fs::create_dir_all(parent)
223    {
224        tracing::warn!(
225            path = %parent.display(),
226            %error,
227            "[Init] Failed to create cache directory"
228        );
229    }
230}
231
232/// What: Create empty cache files at startup so they always exist on disk.
233///
234/// Inputs:
235/// - `app`: Application state providing cache paths.
236///
237/// Output:
238/// - Writes empty dependency, file, service, and sandbox caches if the files are missing.
239///
240/// Details:
241/// - Uses empty signatures and payloads; leaves existing files untouched.
242/// - Ensures parent directories exist before writing.
243fn initialize_cache_files(app: &AppState) {
244    let empty_signature: Vec<String> = Vec::new();
245
246    if !app.deps_cache_path.exists() {
247        ensure_cache_parent_dir(&app.deps_cache_path);
248        deps_cache::save_cache(&app.deps_cache_path, &empty_signature, &[]);
249        tracing::debug!(
250            path = %app.deps_cache_path.display(),
251            "[Init] Created empty dependency cache"
252        );
253    }
254
255    if !app.files_cache_path.exists() {
256        ensure_cache_parent_dir(&app.files_cache_path);
257        files_cache::save_cache(&app.files_cache_path, &empty_signature, &[]);
258        tracing::debug!(
259            path = %app.files_cache_path.display(),
260            "[Init] Created empty file cache"
261        );
262    }
263
264    if !app.services_cache_path.exists() {
265        ensure_cache_parent_dir(&app.services_cache_path);
266        services_cache::save_cache(&app.services_cache_path, &empty_signature, &[]);
267        tracing::debug!(
268            path = %app.services_cache_path.display(),
269            "[Init] Created empty service cache"
270        );
271    }
272
273    if !app.sandbox_cache_path.exists() {
274        ensure_cache_parent_dir(&app.sandbox_cache_path);
275        sandbox_cache::save_cache(&app.sandbox_cache_path, &empty_signature, &[]);
276        tracing::debug!(
277            path = %app.sandbox_cache_path.display(),
278            "[Init] Created empty sandbox cache"
279        );
280    }
281}
282
283/// What: Apply settings from configuration to application state.
284///
285/// Inputs:
286/// - `app`: Application state to update
287/// - `prefs`: Settings to apply
288///
289/// Output: None (modifies app state in place)
290///
291/// Details:
292/// - Applies layout percentages, keymap, sort mode, package marker, and pane visibility
293pub fn apply_settings_to_app_state(app: &mut AppState, prefs: &crate::theme::Settings) {
294    app.layout_left_pct = prefs.layout_left_pct;
295    app.layout_center_pct = prefs.layout_center_pct;
296    app.layout_right_pct = prefs.layout_right_pct;
297    app.main_pane_order = prefs.main_pane_order;
298    app.vertical_layout_limits = crate::state::VerticalLayoutLimits::from_u16s(
299        prefs.vertical_min_results,
300        prefs.vertical_max_results,
301        prefs.vertical_min_middle,
302        prefs.vertical_max_middle,
303        prefs.vertical_min_package_info,
304    );
305    app.keymap = prefs.keymap.clone();
306    app.sort_mode = prefs.sort_mode;
307    app.package_marker = prefs.package_marker;
308    app.show_recent_pane = prefs.show_recent_pane;
309    app.show_install_pane = prefs.show_install_pane;
310    app.show_keybinds_footer = prefs.show_keybinds_footer;
311    app.search_normal_mode = prefs.search_startup_mode;
312    app.fuzzy_search_enabled = prefs.fuzzy_search;
313    app.installed_packages_mode = prefs.installed_packages_mode;
314    app.app_mode = if prefs.start_in_news {
315        crate::state::types::AppMode::News
316    } else {
317        crate::state::types::AppMode::Package
318    };
319    app.news_filter_show_arch_news = prefs.news_filter_show_arch_news;
320    app.news_filter_show_advisories = prefs.news_filter_show_advisories;
321    app.news_filter_show_pkg_updates = prefs.news_filter_show_pkg_updates;
322    app.news_filter_show_aur_updates = prefs.news_filter_show_aur_updates;
323    app.news_filter_show_aur_comments = prefs.news_filter_show_aur_comments;
324    app.news_filter_installed_only = prefs.news_filter_installed_only;
325    app.news_max_age_days = prefs.news_max_age_days;
326    // Recompute news results with loaded filters/age
327    app.refresh_news_results();
328    crate::logic::repos::refresh_dynamic_filters_in_app(app, prefs);
329}
330
331/// What: Check if GNOME terminal is needed and set modal if required.
332///
333/// Inputs:
334/// - `app`: Application state to update
335/// - `headless`: When `true`, skip the check
336///
337/// Output: None (modifies app state in place)
338///
339/// Details:
340/// - Checks if running on GNOME desktop without `gnome-terminal` or `gnome-console`/`kgx`
341/// - Sets modal to `GnomeTerminalPrompt` if terminal is missing
342fn check_gnome_terminal(app: &mut AppState, headless: bool) {
343    if headless {
344        return;
345    }
346
347    let is_gnome =
348        std::env::var("XDG_CURRENT_DESKTOP").is_ok_and(|v| v.to_uppercase().contains("GNOME"));
349
350    if !is_gnome {
351        return;
352    }
353
354    let has_gterm = crate::install::command_on_path("gnome-terminal");
355    let has_gconsole =
356        crate::install::command_on_path("gnome-console") || crate::install::command_on_path("kgx");
357
358    if !(has_gterm || has_gconsole) {
359        app.modal = crate::state::Modal::GnomeTerminalPrompt;
360    }
361}
362
363/// What: Load details cache from disk.
364///
365/// Inputs:
366/// - `app`: Application state to update
367///
368/// Output: None (modifies app state in place)
369///
370/// Details:
371/// - Attempts to deserialize details cache from JSON file
372fn load_details_cache(app: &mut AppState) {
373    if let Ok(s) = std::fs::read_to_string(&app.cache_path)
374        && let Ok(map) = serde_json::from_str::<HashMap<String, PackageDetails>>(&s)
375    {
376        app.details_cache = map;
377        tracing::info!(path = %app.cache_path.display(), "loaded details cache");
378    }
379}
380
381/// What: Load recent searches from disk.
382///
383/// Inputs:
384/// - `app`: Application state to update
385///
386/// Output: None (modifies app state in place)
387///
388/// Details:
389/// - Attempts to deserialize recent searches list from JSON file
390/// - Selects first item if list is not empty
391fn load_recent_searches(app: &mut AppState) {
392    if let Ok(s) = std::fs::read_to_string(&app.recent_path)
393        && let Ok(list) = serde_json::from_str::<Vec<String>>(&s)
394    {
395        let count = list.len();
396        app.load_recent_items(&list);
397        if count > 0 {
398            app.history_state.select(Some(0));
399        }
400        tracing::info!(
401            path = %app.recent_path.display(),
402            count = count,
403            "loaded recent searches"
404        );
405    }
406}
407
408/// What: Load install list from disk.
409///
410/// Inputs:
411/// - `app`: Application state to update
412///
413/// Output: None (modifies app state in place)
414///
415/// Details:
416/// - Attempts to deserialize install list from JSON file
417/// - Selects first item if list is not empty
418fn load_install_list(app: &mut AppState) {
419    if let Ok(s) = std::fs::read_to_string(&app.install_path)
420        && let Ok(list) = serde_json::from_str::<Vec<PackageItem>>(&s)
421    {
422        app.install_list = list;
423        if !app.install_list.is_empty() {
424            app.install_state.select(Some(0));
425        }
426        tracing::info!(
427            path = %app.install_path.display(),
428            count = app.install_list.len(),
429            "loaded install list"
430        );
431    }
432}
433
434/// What: Load news read URLs from disk.
435///
436/// Inputs:
437/// - `app`: Application state to update
438///
439/// Output: None (modifies app state in place)
440///
441/// Details:
442/// - Attempts to deserialize news read URLs set from JSON file
443fn load_news_read_urls(app: &mut AppState) {
444    if let Ok(s) = std::fs::read_to_string(&app.news_read_path)
445        && let Ok(set) = serde_json::from_str::<std::collections::HashSet<String>>(&s)
446    {
447        app.news_read_urls = set;
448        tracing::info!(
449            path = %app.news_read_path.display(),
450            count = app.news_read_urls.len(),
451            "loaded read news urls"
452        );
453    }
454}
455
456/// What: Load news read IDs from disk (feed-level tracking).
457///
458/// Inputs:
459/// - `app`: Application state to update
460///
461/// Output: None (modifies app state in place)
462///
463/// Details:
464/// - Attempts to deserialize news read IDs set from JSON file.
465/// - If no IDs file is found, falls back to populated `news_read_urls` for migration.
466fn load_news_read_ids(app: &mut AppState) {
467    if let Ok(s) = std::fs::read_to_string(&app.news_read_ids_path)
468        && let Ok(set) = serde_json::from_str::<std::collections::HashSet<String>>(&s)
469    {
470        app.news_read_ids = set;
471        tracing::info!(
472            path = %app.news_read_ids_path.display(),
473            count = app.news_read_ids.len(),
474            "loaded read news ids"
475        );
476        return;
477    }
478
479    if app.news_read_ids.is_empty() && !app.news_read_urls.is_empty() {
480        app.news_read_ids.extend(app.news_read_urls.iter().cloned());
481        tracing::info!(
482            copied = app.news_read_ids.len(),
483            "seeded news read ids from legacy URL set"
484        );
485        app.news_read_ids_dirty = true;
486    }
487}
488
489/// What: Load announcement read IDs from disk.
490///
491/// Inputs:
492/// - `app`: Application state to update
493///
494/// Output: None (modifies app state in place)
495///
496/// Details:
497/// - Attempts to deserialize announcement read IDs set from JSON file
498/// - Handles both old format (single hash) and new format (set of IDs) for migration
499fn load_announcement_state(app: &mut AppState) {
500    // Try old format for migration ({ "hash": "..." })
501    /// What: Legacy announcement read state structure.
502    ///
503    /// Inputs: Deserialized from old announcement read file.
504    ///
505    /// Output: Old state structure for migration.
506    ///
507    /// Details: Used for migrating from old announcement read state format.
508    #[derive(serde::Deserialize)]
509    struct OldAnnouncementReadState {
510        /// Announcement hash if read.
511        hash: Option<String>,
512    }
513    if let Ok(s) = std::fs::read_to_string(&app.announcement_read_path) {
514        // Try new format first (HashSet<String>)
515        if let Ok(ids) = serde_json::from_str::<std::collections::HashSet<String>>(&s) {
516            app.announcements_read_ids = ids;
517            tracing::info!(
518                path = %app.announcement_read_path.display(),
519                count = app.announcements_read_ids.len(),
520                "loaded announcement read IDs"
521            );
522            return;
523        }
524        if let Ok(old_state) = serde_json::from_str::<OldAnnouncementReadState>(&s)
525            && let Some(hash) = old_state.hash
526        {
527            app.announcements_read_ids.insert(format!("hash:{hash}"));
528            app.announcement_dirty = true; // Mark dirty to migrate to new format
529            tracing::info!(
530                path = %app.announcement_read_path.display(),
531                "migrated old announcement read state"
532            );
533        }
534    }
535}
536
537/// What: Check for version-embedded announcement and show modal if not read.
538///
539/// Inputs:
540/// - `app`: Application state to update
541///
542/// Output: None (modifies app state in place)
543///
544/// Details:
545/// - Checks embedded announcements for current app version
546/// - If version announcement exists and hasn't been marked as read, shows modal
547fn check_version_announcement(app: &mut AppState) {
548    const CURRENT_VERSION: &str = env!("CARGO_PKG_VERSION");
549
550    // Extract base version (X.X.X) from current version, ignoring suffixes
551    let current_base_version = crate::announcements::extract_base_version(CURRENT_VERSION);
552
553    // Find announcement matching the base version (compares only X.X.X part)
554    if let Some(announcement) = crate::announcements::VERSION_ANNOUNCEMENTS
555        .iter()
556        .find(|a| {
557            let announcement_base_version = crate::announcements::extract_base_version(a.version);
558            announcement_base_version == current_base_version
559        })
560    {
561        // Use full current version (including suffix) for the ID
562        // This ensures announcements show again when suffix changes (e.g., 0.6.0-pr#85 -> 0.6.0-pr#86)
563        let version_id = format!("v{CURRENT_VERSION}");
564
565        // Check if this version announcement has been marked as read
566        if app.announcements_read_ids.contains(&version_id) {
567            tracing::info!(
568                current_version = CURRENT_VERSION,
569                base_version = %current_base_version,
570                "version announcement already marked as read"
571            );
572            return;
573        }
574
575        if matches!(app.modal, crate::state::Modal::None) {
576            // Show version announcement modal immediately.
577            app.modal = crate::state::Modal::Announcement {
578                title: announcement.title.to_string(),
579                content: announcement.content.to_string(),
580                id: version_id,
581                scroll: 0,
582            };
583            tracing::info!(
584                current_version = CURRENT_VERSION,
585                base_version = %current_base_version,
586                announcement_version = announcement.version,
587                "showing version announcement modal"
588            );
589        } else {
590            // Keep first-run/setup modal flow intact and defer version announcement.
591            app.pending_announcements
592                .push(crate::announcements::RemoteAnnouncement {
593                    id: version_id,
594                    title: announcement.title.to_string(),
595                    content: announcement.content.to_string(),
596                    min_version: None,
597                    max_version: None,
598                    expires: None,
599                });
600            tracing::info!(
601                current_version = CURRENT_VERSION,
602                base_version = %current_base_version,
603                announcement_version = announcement.version,
604                queue_size = app.pending_announcements.len(),
605                "queued version announcement modal because another modal is open"
606            );
607        }
608    }
609    // Note: Remote announcements will be queued if they arrive while embedded is showing
610    // and will be shown when embedded is dismissed via show_next_pending_announcement()
611}
612
613/// What: Initialize application state by loading settings, caches, and persisted data.
614///
615/// Inputs:
616/// - `app`: Mutable application state to initialize
617/// - `dry_run_flag`: Whether to enable dry-run mode for this session
618/// - `headless`: Whether running in headless/test mode
619/// - `prefs`: Preflighted settings snapshot to apply during initialization
620///
621/// Output:
622/// - Returns `InitFlags` indicating which caches need background resolution
623///
624/// Details:
625/// - Applies startup settings that were preflighted before runtime initialization
626/// - Initializes locale system and translations
627/// - Loads persisted data: recent searches, install list, details cache, dependency/file/service/sandbox caches
628/// - Loads news read URLs and announcement state
629/// - Loads official package index from disk
630/// - Checks for version-embedded announcements
631pub fn initialize_app_state(
632    app: &mut AppState,
633    dry_run_flag: bool,
634    headless: bool,
635    prefs: &crate::theme::Settings,
636) -> InitFlags {
637    app.dry_run = if dry_run_flag {
638        true
639    } else {
640        prefs.app_dry_run_default
641    };
642    app.last_input_change = Instant::now();
643
644    // Log resolved configuration/state file locations at startup
645    tracing::info!(
646        recent = %app.recent_path.display(),
647        install = %app.install_path.display(),
648        details_cache = %app.cache_path.display(),
649        index = %app.official_index_path.display(),
650        news_read = %app.news_read_path.display(),
651        news_read_ids = %app.news_read_ids_path.display(),
652        announcement_read = %app.announcement_read_path.display(),
653        "resolved state file paths"
654    );
655
656    crate::logic::repos::load_repos_config_into_app(app, crate::theme::resolve_repos_config_path());
657    apply_settings_to_app_state(app, prefs);
658
659    // Initialize locale system
660    initialize_locale_system(app, &prefs.locale, prefs);
661
662    check_gnome_terminal(app, headless);
663
664    // Show startup setup selector modal on first launch if startup news is not configured.
665    if !headless && !prefs.startup_news_configured {
666        // Only show if no other modal is already set (e.g., GnomeTerminalPrompt)
667        if matches!(app.modal, crate::state::Modal::None) {
668            let ssh_command = crate::theme::settings().aur_vote_ssh_command;
669            app.pending_aur_ssh_help_check_result = Some(
670                crate::logic::ssh_setup::spawn_aur_ssh_help_check(ssh_command),
671            );
672            app.aur_ssh_help_ready = None;
673            app.modal = crate::state::Modal::StartupSetupSelector {
674                cursor: 0,
675                selected: std::collections::HashSet::new(),
676                active_privilege_tool: crate::logic::privilege::active_tool().ok(),
677            };
678        }
679    } else if !headless && prefs.startup_news_configured {
680        // Always fetch fresh news in background (using last startup timestamp for incremental updates)
681        // Show loading toast while fetching, but cached items will be displayed immediately
682        app.news_loading = true;
683        app.toast_message = Some(crate::i18n::t(app, "app.news_button.loading"));
684        app.toast_expires_at = None; // No expiration - toast stays until news loading completes
685    }
686
687    // Check faillock status at startup
688    if !headless {
689        let username = std::env::var("USER").unwrap_or_else(|_| "user".to_string());
690        let (is_locked, lockout_until, remaining_minutes) =
691            crate::logic::faillock::get_lockout_info(&username);
692        app.faillock_locked = is_locked;
693        app.faillock_lockout_until = lockout_until;
694        app.faillock_remaining_minutes = remaining_minutes;
695    }
696
697    load_details_cache(app);
698    load_recent_searches(app);
699    load_install_list(app);
700    initialize_cache_files(app);
701
702    // Load dependency cache after install list is loaded (but before channels are created)
703    let (deps_cache, needs_deps_resolution) = load_cache_with_signature(
704        &app.install_list,
705        &app.deps_cache_path,
706        deps_cache::compute_signature,
707        deps_cache::load_cache,
708        "dependency",
709    );
710    if let Some(cached_deps) = deps_cache {
711        app.install_list_deps = cached_deps;
712        tracing::info!(
713            path = %app.deps_cache_path.display(),
714            count = app.install_list_deps.len(),
715            "loaded dependency cache"
716        );
717    }
718
719    // Load file cache after install list is loaded (but before channels are created)
720    let (files_cache, needs_files_resolution) = load_cache_with_signature(
721        &app.install_list,
722        &app.files_cache_path,
723        files_cache::compute_signature,
724        files_cache::load_cache,
725        "file",
726    );
727    if let Some(cached_files) = files_cache {
728        app.install_list_files = cached_files;
729        tracing::info!(
730            path = %app.files_cache_path.display(),
731            count = app.install_list_files.len(),
732            "loaded file cache"
733        );
734    }
735
736    // Load service cache after install list is loaded (but before channels are created)
737    let (services_cache, needs_services_resolution) = load_cache_with_signature(
738        &app.install_list,
739        &app.services_cache_path,
740        services_cache::compute_signature,
741        services_cache::load_cache,
742        "service",
743    );
744    if let Some(cached_services) = services_cache {
745        app.install_list_services = cached_services;
746        tracing::info!(
747            path = %app.services_cache_path.display(),
748            count = app.install_list_services.len(),
749            "loaded service cache"
750        );
751    }
752
753    // Load sandbox cache after install list is loaded (but before channels are created)
754    let (sandbox_cache, needs_sandbox_resolution) = load_cache_with_signature(
755        &app.install_list,
756        &app.sandbox_cache_path,
757        sandbox_cache::compute_signature,
758        sandbox_cache::load_cache,
759        "sandbox",
760    );
761    if let Some(cached_sandbox) = sandbox_cache {
762        app.install_list_sandbox = cached_sandbox;
763        tracing::info!(
764            path = %app.sandbox_cache_path.display(),
765            count = app.install_list_sandbox.len(),
766            "loaded sandbox cache"
767        );
768    }
769
770    load_news_read_urls(app);
771    load_news_read_ids(app);
772    load_announcement_state(app);
773
774    pkgindex::load_from_disk(&app.official_index_path);
775
776    // Check for version-embedded announcement after loading state
777    check_version_announcement(app);
778    tracing::info!(
779        path = %app.official_index_path.display(),
780        "attempted to load official index from disk"
781    );
782
783    InitFlags {
784        needs_deps_resolution,
785        needs_files_resolution,
786        needs_services_resolution,
787        needs_sandbox_resolution,
788    }
789}
790
791/// What: Trigger initial background resolution for caches that were missing or invalid.
792///
793/// Inputs:
794/// - `app`: Application state
795/// - `flags`: Initialization flags indicating which caches need resolution
796/// - `deps_req_tx`: Channel sender for dependency resolution requests
797/// - `files_req_tx`: Channel sender for file resolution requests (with action)
798/// - `services_req_tx`: Channel sender for service resolution requests
799/// - `sandbox_req_tx`: Channel sender for sandbox resolution requests
800///
801/// Output:
802/// - Sets resolution flags and sends requests to background workers
803///
804/// Details:
805/// - Only triggers resolution if cache was missing/invalid and install list is not empty
806pub fn trigger_initial_resolutions(
807    app: &mut AppState,
808    flags: &InitFlags,
809    deps_req_tx: &tokio::sync::mpsc::UnboundedSender<(
810        Vec<PackageItem>,
811        crate::state::modal::PreflightAction,
812    )>,
813    files_req_tx: &tokio::sync::mpsc::UnboundedSender<(
814        Vec<PackageItem>,
815        crate::state::modal::PreflightAction,
816    )>,
817    services_req_tx: &tokio::sync::mpsc::UnboundedSender<(
818        Vec<PackageItem>,
819        crate::state::modal::PreflightAction,
820    )>,
821    sandbox_req_tx: &tokio::sync::mpsc::UnboundedSender<Vec<PackageItem>>,
822) {
823    if flags.needs_deps_resolution && !app.install_list.is_empty() {
824        app.deps_resolving = true;
825        // Initial resolution is always for Install action (install_list)
826        let _ = deps_req_tx.send((
827            app.install_list.clone(),
828            crate::state::modal::PreflightAction::Install,
829        ));
830    }
831
832    if flags.needs_files_resolution && !app.install_list.is_empty() {
833        app.files_resolving = true;
834        // Initial resolution is always for Install action (install_list)
835        let _ = files_req_tx.send((
836            app.install_list.clone(),
837            crate::state::modal::PreflightAction::Install,
838        ));
839    }
840
841    if flags.needs_services_resolution && !app.install_list.is_empty() {
842        app.services_resolving = true;
843        let _ = services_req_tx.send((
844            app.install_list.clone(),
845            crate::state::modal::PreflightAction::Install,
846        ));
847    }
848
849    if flags.needs_sandbox_resolution && !app.install_list.is_empty() {
850        app.sandbox_resolving = true;
851        let _ = sandbox_req_tx.send(app.install_list.clone());
852    }
853}
854
855#[cfg(test)]
856mod tests {
857    use super::*;
858    use crate::app::runtime::background::Channels;
859
860    /// What: Provide a baseline `AppState` for initialization tests.
861    ///
862    /// Inputs: None
863    /// Output: Fresh `AppState` with default values
864    fn new_app() -> AppState {
865        AppState::default()
866    }
867
868    #[test]
869    /// What: Verify that `initialize_locale_system` sets default locale when config file is missing.
870    ///
871    /// Inputs:
872    /// - App state with default locale
873    /// - Empty locale preference
874    ///
875    /// Output:
876    /// - Locale is set to "en-US" when config file is missing
877    /// - Translations maps are initialized (may be empty)
878    ///
879    /// Details:
880    /// - Tests graceful fallback when i18n config is not found
881    fn initialize_locale_system_fallback_when_config_missing() {
882        let mut app = new_app();
883        let prefs = crate::theme::Settings::default();
884
885        // This will fall back to en-US if config file is missing
886        initialize_locale_system(&mut app, "", &prefs);
887
888        // Locale should be set (either resolved or default)
889        assert_ne!(app.locale, "");
890        // Translations maps should be initialized
891        assert!(app.translations.is_empty() || !app.translations.is_empty());
892        assert!(app.translations_fallback.is_empty() || !app.translations_fallback.is_empty());
893    }
894
895    #[test]
896    /// What: Verify that `initialize_app_state` sets `dry_run` flag correctly.
897    ///
898    /// Inputs:
899    /// - `AppState`
900    /// - `dry_run_flag` = true
901    /// - headless = false
902    ///
903    /// Output:
904    /// - `app.dry_run` is set to true
905    /// - `InitFlags` are returned
906    ///
907    /// Details:
908    /// - Tests that `dry_run` flag is properly initialized
909    fn initialize_app_state_sets_dry_run_flag() {
910        let mut app = new_app();
911        let prefs = crate::theme::settings();
912        let flags = initialize_app_state(&mut app, true, false, &prefs);
913
914        assert!(app.dry_run);
915        // Flags should be returned (InitFlags struct is created)
916        // The actual values depend on cache state, so we just verify flags exist
917        let _ = flags;
918    }
919
920    #[test]
921    /// What: Verify that `initialize_app_state` loads settings correctly.
922    ///
923    /// Inputs:
924    /// - `AppState`
925    /// - `dry_run_flag` = false
926    /// - headless = false
927    ///
928    /// Output:
929    /// - `AppState` has layout percentages set
930    /// - Keymap is set
931    /// - Sort mode is set
932    ///
933    /// Details:
934    /// - Tests that settings are properly applied to app state
935    fn initialize_app_state_loads_settings() {
936        let mut app = new_app();
937        let prefs = crate::theme::settings();
938        let _flags = initialize_app_state(&mut app, false, false, &prefs);
939
940        // Settings should be loaded (values depend on config, but should be set)
941        assert!(app.layout_left_pct > 0);
942        assert!(app.layout_center_pct > 0);
943        assert!(app.layout_right_pct > 0);
944        // Keymap should be initialized (it's a struct, not a string)
945        // Just verify it's not the default empty state by checking a field
946        // (KeyMap has many fields, we just verify it's been set)
947    }
948
949    #[test]
950    /// What: Verify first startup shows startup setup selector modal.
951    fn initialize_app_state_shows_startup_selector_when_news_unconfigured() {
952        let mut app = new_app();
953        let mut prefs = crate::theme::settings();
954        prefs.startup_news_configured = false;
955        let _flags = initialize_app_state(&mut app, false, false, &prefs);
956        assert!(matches!(
957            app.modal,
958            crate::state::Modal::StartupSetupSelector { .. }
959        ));
960    }
961
962    #[test]
963    /// What: Verify version announcement is queued when another startup modal is already open.
964    ///
965    /// Inputs:
966    /// - `AppState` with `StartupSetupSelector` already open.
967    ///
968    /// Output:
969    /// - Existing modal remains `StartupSetupSelector`.
970    /// - Version announcement is pushed into `pending_announcements`.
971    ///
972    /// Details:
973    /// - Prevents first-run setup flow from being overwritten by version announcement display.
974    fn check_version_announcement_queues_when_modal_already_open() {
975        let mut app = new_app();
976        app.modal = crate::state::Modal::StartupSetupSelector {
977            cursor: 0,
978            selected: std::collections::HashSet::new(),
979            active_privilege_tool: None,
980        };
981        let pending_before = app.pending_announcements.len();
982
983        check_version_announcement(&mut app);
984
985        assert!(matches!(
986            app.modal,
987            crate::state::Modal::StartupSetupSelector { .. }
988        ));
989        assert_eq!(
990            app.pending_announcements.len(),
991            pending_before.saturating_add(1)
992        );
993    }
994
995    #[test]
996    /// What: Verify that `initialize_cache_files` creates placeholder cache files when missing.
997    ///
998    /// Inputs:
999    /// - `AppState` with cache paths pointed to temporary locations that do not yet exist.
1000    ///
1001    /// Output:
1002    /// - Empty dependency, file, service, and sandbox cache files are created.
1003    ///
1004    /// Details:
1005    /// - Validates that startup eagerly materializes cache files instead of delaying until first use.
1006    fn initialize_cache_files_creates_empty_placeholders() {
1007        let mut app = new_app();
1008        let mut deps_path = std::env::temp_dir();
1009        deps_path.push(format!(
1010            "pacsea_init_deps_cache_{}_{}.json",
1011            std::process::id(),
1012            std::time::SystemTime::now()
1013                .duration_since(std::time::UNIX_EPOCH)
1014                .expect("System time is before UNIX epoch")
1015                .as_nanos()
1016        ));
1017        let mut files_path = deps_path.clone();
1018        files_path.set_file_name("pacsea_init_files_cache.json");
1019        let mut services_path = deps_path.clone();
1020        services_path.set_file_name("pacsea_init_services_cache.json");
1021        let mut sandbox_path = deps_path.clone();
1022        sandbox_path.set_file_name("pacsea_init_sandbox_cache.json");
1023
1024        app.deps_cache_path = deps_path.clone();
1025        app.files_cache_path = files_path.clone();
1026        app.services_cache_path = services_path.clone();
1027        app.sandbox_cache_path = sandbox_path.clone();
1028
1029        // Ensure paths are clean
1030        let _ = std::fs::remove_file(&app.deps_cache_path);
1031        let _ = std::fs::remove_file(&app.files_cache_path);
1032        let _ = std::fs::remove_file(&app.services_cache_path);
1033        let _ = std::fs::remove_file(&app.sandbox_cache_path);
1034
1035        initialize_cache_files(&app);
1036
1037        let deps_body = std::fs::read_to_string(&app.deps_cache_path)
1038            .expect("Dependency cache file should exist");
1039        let deps_cache: crate::app::deps_cache::DependencyCache =
1040            serde_json::from_str(&deps_body).expect("Dependency cache should parse");
1041        assert_eq!(deps_cache.install_list_signature, [] as [String; 0]);
1042        assert!(deps_cache.dependencies.is_empty());
1043
1044        let files_body =
1045            std::fs::read_to_string(&app.files_cache_path).expect("File cache file should exist");
1046        let files_cache: crate::app::files_cache::FileCache =
1047            serde_json::from_str(&files_body).expect("File cache should parse");
1048        assert_eq!(files_cache.install_list_signature, [] as [String; 0]);
1049        assert!(files_cache.files.is_empty());
1050
1051        let services_body = std::fs::read_to_string(&app.services_cache_path)
1052            .expect("Service cache file should exist");
1053        let services_cache: crate::app::services_cache::ServiceCache =
1054            serde_json::from_str(&services_body).expect("Service cache should parse");
1055        assert_eq!(services_cache.install_list_signature, [] as [String; 0]);
1056        assert!(services_cache.services.is_empty());
1057
1058        let sandbox_body = std::fs::read_to_string(&app.sandbox_cache_path)
1059            .expect("Sandbox cache file should exist");
1060        let sandbox_cache: crate::app::sandbox_cache::SandboxCache =
1061            serde_json::from_str(&sandbox_body).expect("Sandbox cache should parse");
1062        assert_eq!(sandbox_cache.install_list_signature, [] as [String; 0]);
1063        assert!(sandbox_cache.sandbox_info.is_empty());
1064
1065        let _ = std::fs::remove_file(&app.deps_cache_path);
1066        let _ = std::fs::remove_file(&app.files_cache_path);
1067        let _ = std::fs::remove_file(&app.services_cache_path);
1068        let _ = std::fs::remove_file(&app.sandbox_cache_path);
1069    }
1070
1071    #[tokio::test]
1072    /// What: Verify that `trigger_initial_resolutions` skips when install list is empty.
1073    ///
1074    /// Inputs:
1075    /// - `AppState` with empty install list
1076    /// - `InitFlags` with `needs_deps_resolution` = true
1077    /// - Channel senders
1078    ///
1079    /// Output:
1080    /// - No requests sent when install list is empty
1081    ///
1082    /// Details:
1083    /// - Tests that resolution is only triggered when install list is not empty
1084    async fn trigger_initial_resolutions_skips_when_install_list_empty() {
1085        let mut app = new_app();
1086        app.install_list.clear();
1087
1088        let flags = InitFlags {
1089            needs_deps_resolution: true,
1090            needs_files_resolution: true,
1091            needs_services_resolution: true,
1092            needs_sandbox_resolution: true,
1093        };
1094
1095        // Create channels (we only need the senders)
1096        let channels =
1097            Channels::new(std::path::PathBuf::from("/tmp")).expect("channels should construct");
1098
1099        // Should not panic even with empty install list
1100        trigger_initial_resolutions(
1101            &mut app,
1102            &flags,
1103            &channels.deps_req_tx,
1104            &channels.files_req_tx,
1105            &channels.services_req_tx,
1106            &channels.sandbox_req_tx,
1107        );
1108
1109        // Flags should not be set when install list is empty
1110        assert!(!app.deps_resolving);
1111        assert!(!app.files_resolving);
1112        assert!(!app.services_resolving);
1113        assert!(!app.sandbox_resolving);
1114    }
1115
1116    #[tokio::test]
1117    /// What: Verify that `trigger_initial_resolutions` sets flags and sends requests when needed.
1118    ///
1119    /// Inputs:
1120    /// - `AppState` with non-empty install list
1121    /// - `InitFlags` with `needs_deps_resolution` = true
1122    /// - Channel senders
1123    ///
1124    /// Output:
1125    /// - `deps_resolving` flag is set
1126    /// - Request is sent to `deps_req_tx`
1127    ///
1128    /// Details:
1129    /// - Tests that resolution is properly triggered when conditions are met
1130    async fn trigger_initial_resolutions_triggers_when_needed() {
1131        let mut app = new_app();
1132        app.install_list.push(crate::state::PackageItem {
1133            name: "test-package".to_string(),
1134            version: "1.0.0".to_string(),
1135            description: "Test".to_string(),
1136            source: crate::state::Source::Aur,
1137            popularity: None,
1138            out_of_date: None,
1139            orphaned: false,
1140        });
1141
1142        let flags = InitFlags {
1143            needs_deps_resolution: true,
1144            needs_files_resolution: false,
1145            needs_services_resolution: false,
1146            needs_sandbox_resolution: false,
1147        };
1148
1149        let channels =
1150            Channels::new(std::path::PathBuf::from("/tmp")).expect("channels should construct");
1151
1152        trigger_initial_resolutions(
1153            &mut app,
1154            &flags,
1155            &channels.deps_req_tx,
1156            &channels.files_req_tx,
1157            &channels.services_req_tx,
1158            &channels.sandbox_req_tx,
1159        );
1160
1161        // Flag should be set
1162        assert!(app.deps_resolving);
1163        // Other flags should not be set
1164        assert!(!app.files_resolving);
1165        assert!(!app.services_resolving);
1166        assert!(!app.sandbox_resolving);
1167    }
1168}