repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/search/insert_mode.rs
src/events/search/insert_mode.rs
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use tokio::sync::mpsc; use crate::logic::move_sel_cached; use crate::state::{AppState, PackageItem, QueryInput}; use super::super::utils::matches_any; use super::helpers::{handle_shift_keybinds, navigate_pane}; use super::preflight_helpers::open_preflight_modal; use crate::events::utils::{char_count, refresh_install_details}; use crate::logic::send_query; /// What: Handle character input in insert mode. /// /// Inputs: /// - `ch`: Character to add. /// - `app`: Mutable application state. /// - `query_tx`: Channel to send debounced search queries. /// /// Output: None (modifies app state in place). /// /// Details: /// - Handles both News mode and normal search mode. /// - Updates input, caret position, and triggers search queries. fn handle_character_input( ch: char, app: &mut AppState, query_tx: &mpsc::UnboundedSender<QueryInput>, ) { if matches!(app.app_mode, crate::state::types::AppMode::News) { app.news_search_input.push(ch); app.last_input_change = std::time::Instant::now(); app.last_saved_value = None; let caret = char_count(&app.news_search_input); app.news_search_caret = caret; app.news_search_select_anchor = None; app.refresh_news_results(); } else { app.input.push(ch); app.last_input_change = std::time::Instant::now(); app.last_saved_value = None; app.search_caret = char_count(&app.input); app.search_select_anchor = None; send_query(app, query_tx); } } /// What: Handle backspace in insert mode. /// /// Inputs: /// - `app`: Mutable application state. /// - `query_tx`: Channel to send debounced search queries. /// /// Output: None (modifies app state in place). /// /// Details: /// - Handles both News mode and normal search mode. /// - Removes last character and updates caret position. fn handle_backspace(app: &mut AppState, query_tx: &mpsc::UnboundedSender<QueryInput>) { if matches!(app.app_mode, crate::state::types::AppMode::News) { app.news_search_input.pop(); app.last_input_change = std::time::Instant::now(); app.last_saved_value = None; let caret = char_count(&app.news_search_input); app.news_search_caret = caret; app.news_search_select_anchor = None; app.refresh_news_results(); } else { app.input.pop(); app.last_input_change = std::time::Instant::now(); app.last_saved_value = None; app.search_caret = char_count(&app.input); app.search_select_anchor = None; send_query(app, query_tx); } } /// What: Handle navigation keys (up, down, page up, page down). /// /// Inputs: /// - `ke`: Key event. /// - `app`: Mutable application state. /// - `details_tx`: Channel to request details. /// - `comments_tx`: Channel to request comments. /// /// Output: `true` if the key was handled, `false` otherwise. /// /// Details: /// - Handles both News mode and normal search mode. /// - Moves selection and updates details/comments. fn handle_navigation_keys( ke: &KeyEvent, app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, comments_tx: &mpsc::UnboundedSender<String>, ) -> bool { let is_news = matches!(app.app_mode, crate::state::types::AppMode::News); let km = &app.keymap; if matches_any(ke, &km.search_move_up) { if is_news { crate::events::utils::move_news_selection(app, -1); } else { move_sel_cached(app, -1, details_tx, comments_tx); } return true; } if matches_any(ke, &km.search_move_down) { if is_news { crate::events::utils::move_news_selection(app, 1); } else { move_sel_cached(app, 1, details_tx, comments_tx); } return true; } if matches_any(ke, &km.search_page_up) { if is_news { crate::events::utils::move_news_selection(app, -10); } else { move_sel_cached(app, -10, details_tx, comments_tx); } return true; } if matches_any(ke, &km.search_page_down) { if is_news { crate::events::utils::move_news_selection(app, 10); } else { move_sel_cached(app, 10, details_tx, comments_tx); } return true; } false } /// What: Handle key events in Insert mode for the Search pane. /// /// Inputs: /// - `ke`: Key event received from the terminal /// - `app`: Mutable application state /// - `query_tx`: Channel to send debounced search queries /// - `details_tx`: Channel to request details for the focused item /// - `add_tx`: Channel to add items to the Install/Remove lists /// - `preview_tx`: Channel to request preview details when moving focus /// /// Output: /// - `true` to request application exit (e.g., Ctrl+C); `false` to continue processing /// /// Details: /// - Handles typing, backspace, navigation, space to add items, and Enter to open preflight. /// - Typing updates the input, caret position, and triggers debounced search queries. pub fn handle_insert_mode( ke: KeyEvent, app: &mut AppState, query_tx: &mpsc::UnboundedSender<QueryInput>, details_tx: &mpsc::UnboundedSender<PackageItem>, add_tx: &mpsc::UnboundedSender<PackageItem>, preview_tx: &mpsc::UnboundedSender<PackageItem>, comments_tx: &mpsc::UnboundedSender<String>, ) -> bool { // Handle Shift+char keybinds (menus, import, export, updates, status) that work in all modes if handle_shift_keybinds(&ke, app) { return false; } match (ke.code, ke.modifiers) { (KeyCode::Char('c'), KeyModifiers::CONTROL) => return true, (c, m) if { let km = &app.keymap; matches_any(&ke, &km.pane_next) && (c, m) == (ke.code, ke.modifiers) } => { if matches!(app.app_mode, crate::state::types::AppMode::News) { app.focus = crate::state::Focus::Install; } else { // Desired cycle: Recent -> Search -> Downgrade -> Remove -> Recent if app.installed_only_mode { app.right_pane_focus = crate::state::RightPaneFocus::Downgrade; if app.downgrade_state.selected().is_none() && !app.downgrade_list.is_empty() { app.downgrade_state.select(Some(0)); } app.focus = crate::state::Focus::Install; crate::events::utils::refresh_downgrade_details(app, details_tx); } else { if app.install_state.selected().is_none() && !app.install_list.is_empty() { app.install_state.select(Some(0)); } app.focus = crate::state::Focus::Install; refresh_install_details(app, details_tx); } } } (KeyCode::Right, _) => { navigate_pane(app, "right", details_tx, preview_tx); } (KeyCode::Left, _) => { navigate_pane(app, "left", details_tx, preview_tx); } (KeyCode::Char(' '), KeyModifiers::CONTROL) => { if app.installed_only_mode && let Some(item) = app.results.get(app.selected).cloned() { crate::logic::add_to_downgrade_list(app, item); // Do not change focus; only update details to reflect the new selection crate::events::utils::refresh_downgrade_details(app, details_tx); } } (KeyCode::Char(' '), _) => { if let Some(item) = app.results.get(app.selected).cloned() { if app.installed_only_mode { crate::logic::add_to_remove_list(app, item); crate::events::utils::refresh_remove_details(app, details_tx); } else { let _ = add_tx.send(item); } } } (KeyCode::Backspace, _) => { handle_backspace(app, query_tx); } // Handle Enter - but NOT if it's actually Ctrl+M (which some terminals send as Enter) (KeyCode::Char('\n') | KeyCode::Enter, m) => { // Don't open preflight if Ctrl is held (might be Ctrl+M interpreted as Enter) if m.contains(KeyModifiers::CONTROL) { tracing::debug!( "[InsertMode] Enter with Ctrl detected, ignoring (likely Ctrl+M interpreted as Enter)" ); return false; } if let Some(item) = app.results.get(app.selected).cloned() { tracing::debug!( "[InsertMode] Enter pressed, opening preflight for package: {}", item.name ); open_preflight_modal(app, vec![item], false); } } // Only handle character input if no modifiers are present (to allow global keybinds with modifiers) (KeyCode::Char(ch), m) if m.is_empty() => { handle_character_input(ch, app, query_tx); } _ => { if handle_navigation_keys(&ke, app, details_tx, comments_tx) { // Navigation handled } else { let km = &app.keymap; if matches_any(&ke, &km.search_insert_clear) { // Clear entire search input if matches!(app.app_mode, crate::state::types::AppMode::News) { if !app.news_search_input.is_empty() { app.news_search_input.clear(); app.news_search_caret = 0; app.news_search_select_anchor = None; app.last_input_change = std::time::Instant::now(); app.last_saved_value = None; app.refresh_news_results(); } } else if !app.input.is_empty() { app.input.clear(); app.search_caret = 0; app.search_select_anchor = None; app.last_input_change = std::time::Instant::now(); app.last_saved_value = None; send_query(app, query_tx); } } } } } false }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/search/tests.rs
src/events/search/tests.rs
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use tokio::sync::mpsc; use crate::state::{AppState, PackageItem, QueryInput}; use crate::theme::KeyChord; use super::super::utils::matches_any; use super::handle_search_key; use super::helpers::navigate_pane; /// What: Provide a baseline `AppState` tailored for search-pane tests without repeating setup boilerplate. /// /// Inputs: /// - None (relies on `Default::default()` for deterministic initial state). /// /// Output: /// - Fresh `AppState` ready for mutation inside individual test cases. /// /// Details: /// - Keeps search tests concise by centralizing the default application setup in one helper. fn new_app() -> AppState { AppState::default() } #[test] /// What: Insert-mode typing should update the search input, caret, and emit query messages. /// /// Inputs: /// - Key events for `'r'`, `'g'`, and `Backspace` applied in sequence while in insert mode. /// /// Output: /// - `app.input` transitions `"" -> "r" -> "rg" -> "r"`, and at least one query arrives on `qrx`. /// /// Details: /// - Validates caret/anchor bookkeeping indirectly by observing the query channel after each keystroke. fn search_insert_typing_and_backspace() { let mut app = new_app(); let (qtx, mut qrx) = mpsc::unbounded_channel::<QueryInput>(); let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>(); let _ = handle_search_key( KeyEvent::new(KeyCode::Char('r'), KeyModifiers::empty()), &mut app, &qtx, &dtx, &atx, &ptx, &comments_tx, ); let _ = handle_search_key( KeyEvent::new(KeyCode::Char('g'), KeyModifiers::empty()), &mut app, &qtx, &dtx, &atx, &ptx, &comments_tx, ); let _ = handle_search_key( KeyEvent::new(KeyCode::Backspace, KeyModifiers::empty()), &mut app, &qtx, &dtx, &atx, &ptx, &comments_tx, ); assert_eq!(app.input, "r"); // At least one query should have been sent assert!(qrx.try_recv().ok().is_some()); } #[test] /// What: Normal-mode selection commands should set the anchor and adjust the caret within bounds. /// /// Inputs: /// - Escape key to enter normal mode, followed by `'l'` (select-right) and `'h'` (select-left). /// /// Output: /// - `search_select_anchor` becomes `Some` and the caret remains within the valid input character range. /// /// Details: /// - Confirms the keymap translation respects the default bindings for navigation-style selection. fn search_normal_mode_selection() { let mut app = new_app(); app.input = "rip".into(); let (qtx, _qrx) = mpsc::unbounded_channel::<QueryInput>(); let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>(); // Toggle into normal mode (Esc by default per KeyMap) let _ = handle_search_key( KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()), &mut app, &qtx, &dtx, &atx, &ptx, &comments_tx, ); // Select right (default 'l') let _ = handle_search_key( KeyEvent::new(KeyCode::Char('l'), KeyModifiers::empty()), &mut app, &qtx, &dtx, &atx, &ptx, &comments_tx, ); assert!(app.search_select_anchor.is_some()); // Select left (default 'h') let _ = handle_search_key( KeyEvent::new(KeyCode::Char('h'), KeyModifiers::empty()), &mut app, &qtx, &dtx, &atx, &ptx, &comments_tx, ); assert!(app.search_caret <= crate::events::utils::char_count(&app.input)); } #[test] /// What: Verify `matches_any` correctly handles Shift+char edge cases across different terminal behaviors. /// /// Inputs: /// - Key events with and without Shift modifier, matched against configured chords with Shift. /// /// Output: /// - Returns `true` when the key event matches the configured chord, handling terminal inconsistencies. /// /// Details: /// - Tests that uppercase chars match Shift+lowercase configs even if terminal doesn't report Shift. /// - Tests that lowercase chars with Shift modifier match Shift+lowercase configs. /// - Tests exact matches without Shift handling. fn helpers_matches_any_shift_handling() { use crossterm::event::KeyCode; // Test exact match (no Shift involved) let ke1 = KeyEvent::new(KeyCode::Char('r'), KeyModifiers::CONTROL); let chord1 = vec![KeyChord { code: KeyCode::Char('r'), mods: KeyModifiers::CONTROL, }]; assert!(matches_any(&ke1, &chord1)); // Test Shift+char config matching uppercase char (terminal may not report Shift) let ke2 = KeyEvent::new(KeyCode::Char('R'), KeyModifiers::empty()); let chord2 = vec![KeyChord { code: KeyCode::Char('r'), mods: KeyModifiers::SHIFT, }]; assert!(matches_any(&ke2, &chord2)); // Test Shift+char config matching lowercase char with Shift modifier let ke3 = KeyEvent::new(KeyCode::Char('r'), KeyModifiers::SHIFT); let chord3 = vec![KeyChord { code: KeyCode::Char('r'), mods: KeyModifiers::SHIFT, }]; assert!(matches_any(&ke3, &chord3)); // Test non-match case let ke4 = KeyEvent::new(KeyCode::Char('x'), KeyModifiers::empty()); let chord4 = vec![KeyChord { code: KeyCode::Char('r'), mods: KeyModifiers::SHIFT, }]; assert!(!matches_any(&ke4, &chord4)); } #[test] /// What: Normal mode deletion (default: 'd') should remove selected text range and trigger query. /// /// Inputs: /// - Enter normal mode, set selection anchor, move caret, then press 'd' to delete. /// /// Output: /// - Selected text is removed from input, caret moves to start of deleted range, query is sent. /// /// Details: /// - Validates that deletion respects anchor and caret positions, removing the range between them. fn search_normal_mode_deletion() { let mut app = new_app(); app.input = "hello world".into(); app.search_caret = 6; // After "hello " let (qtx, mut qrx) = mpsc::unbounded_channel::<QueryInput>(); let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>(); // Enter normal mode app.search_normal_mode = true; // Set anchor at start app.search_select_anchor = Some(0); // Move caret to position 5 (after "hello") app.search_caret = 5; // Delete selection (default 'd') let _ = handle_search_key( KeyEvent::new(KeyCode::Char('d'), KeyModifiers::empty()), &mut app, &qtx, &dtx, &atx, &ptx, &comments_tx, ); // Should have deleted "hello" assert_eq!(app.input, " world"); assert_eq!(app.search_caret, 0); assert!(app.search_select_anchor.is_none()); // Query should have been sent assert!(qrx.try_recv().ok().is_some()); } #[test] /// What: Normal mode clear (default: Shift+Del) should clear entire input and trigger query. /// /// Inputs: /// - Enter normal mode with non-empty input, then press Shift+Del. /// /// Output: /// - Input is cleared, caret reset to 0, selection anchor cleared, query is sent. /// /// Details: /// - Validates that clear operation resets all input-related state. fn search_normal_mode_clear() { let mut app = new_app(); app.input = "test query".into(); app.search_caret = 5; app.search_select_anchor = Some(3); let (qtx, mut qrx) = mpsc::unbounded_channel::<QueryInput>(); let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>(); // Enter normal mode app.search_normal_mode = true; // Configure clear keybinding app.keymap.search_normal_clear = vec![KeyChord { code: KeyCode::Delete, mods: KeyModifiers::SHIFT, }]; // Clear input let _ = handle_search_key( KeyEvent::new(KeyCode::Delete, KeyModifiers::SHIFT), &mut app, &qtx, &dtx, &atx, &ptx, &comments_tx, ); assert_eq!(app.input, ""); assert_eq!(app.search_caret, 0); assert!(app.search_select_anchor.is_none()); // Query should have been sent assert!(qrx.try_recv().ok().is_some()); } #[test] /// What: Mode toggle should switch between insert and normal mode. /// /// Inputs: /// - Start in insert mode, press toggle key (default: Esc), then toggle again. /// /// Output: /// - Mode toggles between false (insert) and true (normal), selection anchor cleared on exit. /// /// Details: /// - Validates that mode toggle correctly updates `search_normal_mode` state. fn search_mode_toggle() { let mut app = new_app(); app.search_normal_mode = false; app.search_select_anchor = Some(5); let (qtx, _qrx) = mpsc::unbounded_channel::<QueryInput>(); let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>(); // Configure toggle key (default Esc) app.keymap.search_normal_toggle = vec![KeyChord { code: KeyCode::Esc, mods: KeyModifiers::empty(), }]; // Toggle to normal mode let _ = handle_search_key( KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()), &mut app, &qtx, &dtx, &atx, &ptx, &comments_tx, ); assert!(app.search_normal_mode); // Toggle back to insert mode let _ = handle_search_key( KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()), &mut app, &qtx, &dtx, &atx, &ptx, &comments_tx, ); assert!(!app.search_normal_mode); // Note: Selection anchor is cleared when entering insert mode via search_normal_insert key, // but not when toggling mode. This is expected behavior. } #[test] /// What: Pane navigation should correctly switch focus and update selection state. /// /// Inputs: /// - Call `navigate_pane` with "right" direction in different modes. /// /// Output: /// - Focus changes appropriately, selection state initialized if needed. /// /// Details: /// - Tests that right navigation targets Install/Downgrade based on `installed_only_mode`. /// - Left navigation test is skipped as it requires Tokio runtime for preview trigger. fn helpers_navigate_pane_directions() { let mut app = new_app(); let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); // Test right navigation in normal mode app.installed_only_mode = false; app.install_list.push(crate::state::PackageItem { name: "test-pkg".to_string(), version: "1.0".to_string(), description: String::new(), source: crate::state::Source::Official { repo: "extra".to_string(), arch: "x86_64".to_string(), }, popularity: None, out_of_date: None, orphaned: false, }); navigate_pane(&mut app, "right", &dtx, &ptx); assert!(matches!(app.focus, crate::state::Focus::Install)); // Test right navigation in installed-only mode app.installed_only_mode = true; app.downgrade_list.push(crate::state::PackageItem { name: "downgrade-pkg".to_string(), version: "1.0".to_string(), description: String::new(), source: crate::state::Source::Official { repo: "extra".to_string(), arch: "x86_64".to_string(), }, popularity: None, out_of_date: None, orphaned: false, }); navigate_pane(&mut app, "right", &dtx, &ptx); assert!(matches!(app.focus, crate::state::Focus::Install)); assert!(matches!( app.right_pane_focus, crate::state::RightPaneFocus::Downgrade )); } #[test] /// What: Space key in insert mode should add items to appropriate lists based on mode. /// /// Inputs: /// - Press Space with a selected item in normal and installed-only modes. /// /// Output: /// - Items are sent to `add_tx` in normal mode, or added to `remove_list` in installed-only mode. /// /// Details: /// - Validates that Space correctly routes items based on `installed_only_mode` flag. fn search_insert_mode_space_adds_items() { let mut app = new_app(); let test_item = crate::state::PackageItem { name: "test-package".to_string(), version: "1.0".to_string(), description: String::new(), source: crate::state::Source::Official { repo: "extra".to_string(), arch: "x86_64".to_string(), }, popularity: None, out_of_date: None, orphaned: false, }; app.results.push(test_item.clone()); app.selected = 0; let (qtx, _qrx) = mpsc::unbounded_channel::<QueryInput>(); let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, mut arx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>(); // Test normal mode: should send to add_tx app.installed_only_mode = false; let _ = handle_search_key( KeyEvent::new(KeyCode::Char(' '), KeyModifiers::empty()), &mut app, &qtx, &dtx, &atx, &ptx, &comments_tx, ); let received = arx.try_recv().ok(); assert!(received.is_some()); assert_eq!( received .expect("received should be Some after is_some() check") .name, "test-package" ); // Test installed-only mode: should add to remove_list app.installed_only_mode = true; app.results.push(test_item); app.selected = 0; let _ = handle_search_key( KeyEvent::new(KeyCode::Char(' '), KeyModifiers::empty()), &mut app, &qtx, &dtx, &atx, &ptx, &comments_tx, ); assert!(app.remove_list.iter().any(|p| p.name == "test-package")); } #[test] /// What: Normal mode navigation keys (j/k) should move selection within bounds. /// /// Inputs: /// - Enter normal mode, press 'j' to move down, 'k' to move up. /// /// Output: /// - Selection index changes appropriately, staying within results bounds. /// /// Details: /// - Validates that j/k navigation respects result list boundaries. fn search_normal_mode_navigation() { let mut app = new_app(); app.results = vec![ crate::state::PackageItem { name: "pkg1".to_string(), version: "1.0".to_string(), description: String::new(), source: crate::state::Source::Official { repo: "extra".to_string(), arch: "x86_64".to_string(), }, popularity: None, out_of_date: None, orphaned: false, }, crate::state::PackageItem { name: "pkg2".to_string(), version: "1.0".to_string(), description: String::new(), source: crate::state::Source::Official { repo: "extra".to_string(), arch: "x86_64".to_string(), }, popularity: None, out_of_date: None, orphaned: false, }, crate::state::PackageItem { name: "pkg3".to_string(), version: "1.0".to_string(), description: String::new(), source: crate::state::Source::Official { repo: "extra".to_string(), arch: "x86_64".to_string(), }, popularity: None, out_of_date: None, orphaned: false, }, ]; app.selected = 1; app.search_normal_mode = true; let (qtx, _qrx) = mpsc::unbounded_channel::<QueryInput>(); let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>(); // Move down (j) let _ = handle_search_key( KeyEvent::new(KeyCode::Char('j'), KeyModifiers::empty()), &mut app, &qtx, &dtx, &atx, &ptx, &comments_tx, ); assert_eq!(app.selected, 2); // Move up (k) let _ = handle_search_key( KeyEvent::new(KeyCode::Char('k'), KeyModifiers::empty()), &mut app, &qtx, &dtx, &atx, &ptx, &comments_tx, ); assert_eq!(app.selected, 1); // Move up at top should stay at 0 app.selected = 0; let _ = handle_search_key( KeyEvent::new(KeyCode::Char('k'), KeyModifiers::empty()), &mut app, &qtx, &dtx, &atx, &ptx, &comments_tx, ); assert_eq!(app.selected, 0); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/search/helpers.rs
src/events/search/helpers.rs
use crossterm::event::KeyEvent; use super::super::utils::matches_any; use super::normal_mode::{handle_export, handle_menu_toggles}; use crate::state::AppState; /// What: Handle Shift+char keybinds (menus, import, export, updates, status) that work across all panes and modes. /// /// Inputs: /// - `ke`: Key event from terminal /// - `app`: Mutable application state /// /// Output: /// - `true` if a Shift+char keybind was handled, `false` otherwise /// /// Details: /// - Handles menu toggles (Shift+C, Shift+O, Shift+P), import (Shift+I), export (Shift+E), /// updates (Shift+U), and status (Shift+S). /// - Works in insert mode, normal mode, and all panes (Search, Recent, Install). pub fn handle_shift_keybinds(ke: &KeyEvent, app: &mut AppState) -> bool { // Handle menu toggles if handle_menu_toggles(ke, app) { return true; } // Handle import (Shift+I) if matches_any(ke, &app.keymap.search_normal_import) { if !app.installed_only_mode { app.modal = crate::state::Modal::ImportHelp; } return true; } // Handle export (Shift+E) if matches_any(ke, &app.keymap.search_normal_export) { handle_export(app); return true; } // Handle updates (Shift+U) if matches_any(ke, &app.keymap.search_normal_updates) { // In News mode, open News modal; otherwise open Updates modal if matches!(app.app_mode, crate::state::types::AppMode::News) { crate::events::mouse::handle_news_button(app); } else { crate::events::mouse::handle_updates_button(app); } return true; } // Handle status (Shift+S) if matches_any(ke, &app.keymap.search_normal_open_status) { crate::util::open_url("https://status.archlinux.org"); return true; } false } /// What: Handle pane navigation from Search pane to adjacent panes. /// /// Inputs: /// - `app`: Mutable application state /// - `direction`: Direction to navigate ("right" for Install, "left" for Recent) /// - `details_tx`: Channel to request details for the focused item /// - `preview_tx`: Channel to request preview details when moving focus /// /// Output: /// - None (modifies app state directly) /// /// Details: /// - In installed-only mode, right navigation targets Downgrade first. /// - Otherwise, right navigation targets Install list. /// - Left navigation always targets Recent pane. pub fn navigate_pane( app: &mut AppState, direction: &str, details_tx: &tokio::sync::mpsc::UnboundedSender<crate::state::PackageItem>, preview_tx: &tokio::sync::mpsc::UnboundedSender<crate::state::PackageItem>, ) { if matches!(app.app_mode, crate::state::types::AppMode::News) { match direction { "right" => { app.focus = crate::state::Focus::Install; // bookmarks pane } "left" => { app.focus = crate::state::Focus::Recent; // history pane } _ => {} } return; } match direction { "right" => { if app.installed_only_mode { // Target Downgrade first in installed-only mode app.right_pane_focus = crate::state::RightPaneFocus::Downgrade; if app.downgrade_state.selected().is_none() && !app.downgrade_list.is_empty() { app.downgrade_state.select(Some(0)); } app.focus = crate::state::Focus::Install; super::super::utils::refresh_downgrade_details(app, details_tx); } else { if app.install_state.selected().is_none() && !app.install_list.is_empty() { app.install_state.select(Some(0)); } app.focus = crate::state::Focus::Install; super::super::utils::refresh_install_details(app, details_tx); } } "left" => { if app.history_state.selected().is_none() && !app.recent.is_empty() { app.history_state.select(Some(0)); } app.focus = crate::state::Focus::Recent; crate::ui::helpers::trigger_recent_preview(app, preview_tx); } _ => {} } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/search/mod.rs
src/events/search/mod.rs
//! Search pane event handling module. //! //! This module handles all keyboard input events when the Search pane is focused. //! It supports two modes: //! - **Insert mode** (default): Direct text input for searching packages //! - **Normal mode**: Vim-like navigation and editing commands //! //! The module is split into submodules for maintainability: //! - `helpers`: Shared utility functions for key matching and pane navigation //! - `insert_mode`: Insert mode key event handling //! - `normal_mode`: Normal mode key event handling //! - `preflight_helpers`: Preflight modal opening logic use crossterm::event::KeyEvent; use tokio::sync::mpsc; use crate::state::{AppState, PackageItem, QueryInput}; /// Helper functions for search event handling. mod helpers; /// Insert mode search event handling. mod insert_mode; /// Normal mode search event handling. mod normal_mode; /// Preflight modal helper functions for search. mod preflight_helpers; // Re-export preflight modal opener for use in other modules pub use preflight_helpers::open_preflight_modal; // Re-export shift keybind handler for use in other modules pub use helpers::handle_shift_keybinds; #[cfg(test)] mod tests; /// What: Handle key events while the Search pane is focused. /// /// Inputs: /// - `ke`: Key event received from the terminal /// - `app`: Mutable application state (input, selection, sort, modes) /// - `query_tx`: Channel to send debounced search queries /// - `details_tx`: Channel to request details for the focused item /// - `add_tx`: Channel to add items to the Install/Remove lists /// - `preview_tx`: Channel to request preview details when moving focus /// /// Output: /// - `true` to request application exit (e.g., Ctrl+C); `false` to continue processing. /// /// Details: /// - Insert mode (default): typing edits the query, triggers debounced network/idx search, and /// moves caret; Backspace edits; Space adds to list (Install by default, Remove in installed-only). /// - Normal mode: toggled via configured chord; supports selection (h/l), deletion (d), navigation /// (j/k, Ctrl+U/D), and list add/remove with Space/ Ctrl+Space (downgrade). /// - Pane navigation: Left/Right and configured `pane_next` cycle focus across panes and subpanes, /// differing slightly when installed-only mode is active. /// - PKGBUILD reload is handled via debounced requests scheduled in the selection logic. /// - Comments are automatically updated when package changes and comments are visible. pub fn handle_search_key( ke: KeyEvent, app: &mut AppState, query_tx: &mpsc::UnboundedSender<QueryInput>, details_tx: &mpsc::UnboundedSender<PackageItem>, add_tx: &mpsc::UnboundedSender<PackageItem>, preview_tx: &mpsc::UnboundedSender<PackageItem>, comments_tx: &mpsc::UnboundedSender<String>, ) -> bool { let km = &app.keymap; // Toggle fuzzy search mode (works in both insert and normal mode) if super::utils::matches_any(&ke, &km.toggle_fuzzy) { app.fuzzy_search_enabled = !app.fuzzy_search_enabled; crate::theme::save_fuzzy_search(app.fuzzy_search_enabled); // Invalidate cache when fuzzy mode changes app.search_cache_query = None; app.search_cache_results = None; // Re-trigger search with current query using new mode crate::logic::send_query(app, query_tx); return false; } // Toggle Normal mode (configurable) if super::utils::matches_any(&ke, &km.search_normal_toggle) { app.search_normal_mode = !app.search_normal_mode; return false; } // Normal mode: Vim-like navigation without editing input if app.search_normal_mode { return normal_mode::handle_normal_mode( ke, app, query_tx, details_tx, add_tx, preview_tx, comments_tx, ); } // Insert mode (default for Search) insert_mode::handle_insert_mode( ke, app, query_tx, details_tx, add_tx, preview_tx, comments_tx, ) }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/search/normal_mode.rs
src/events/search/normal_mode.rs
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use tokio::sync::mpsc; use crate::logic::{move_sel_cached, send_query}; use crate::state::{AppState, PackageItem, QueryInput}; use std::collections::hash_map::DefaultHasher; use std::hash::{Hash, Hasher}; use super::super::utils::matches_any; use super::helpers::navigate_pane; use super::preflight_helpers::open_preflight_modal; use crate::events::utils::{byte_index_for_char, char_count, refresh_install_details}; /// What: Handle numeric selection (1-9) for config menu items. /// /// Inputs: /// - `idx`: Numeric index (0-8) from key press /// - `app`: Mutable application state /// /// Output: /// - `true` if handled, `false` otherwise /// /// Details: /// - Opens the selected config file in a terminal editor. /// - Handles settings, theme, and keybinds. fn handle_config_menu_numeric_selection(idx: usize, app: &mut AppState) -> bool { if !app.config_menu_open { return false; } let settings_path = crate::theme::config_dir().join("settings.conf"); let theme_path = crate::theme::config_dir().join("theme.conf"); let keybinds_path = crate::theme::config_dir().join("keybinds.conf"); let target = match idx { 0 => settings_path, 1 => theme_path, 2 => keybinds_path, _ => { app.config_menu_open = false; return false; } }; let path_str = target.display().to_string(); let editor_cmd = format!( "((command -v nvim >/dev/null 2>&1 || sudo pacman -Qi neovim >/dev/null 2>&1) && nvim '{path_str}') || \\\n ((command -v vim >/dev/null 2>&1 || sudo pacman -Qi vim >/dev/null 2>&1) && vim '{path_str}') || \\\n ((command -v hx >/dev/null 2>&1 || sudo pacman -Qi helix >/dev/null 2>&1) && hx '{path_str}') || \\\n ((command -v helix >/dev/null 2>&1 || sudo pacman -Qi helix >/dev/null 2>&1) && helix '{path_str}') || \\\n ((command -v emacsclient >/dev/null 2>&1 || sudo pacman -Qi emacs >/dev/null 2>&1) && emacsclient -t '{path_str}') || \\\n ((command -v emacs >/dev/null 2>&1 || sudo pacman -Qi emacs >/dev/null 2>&1) && emacs -nw '{path_str}') || \\\n ((command -v nano >/dev/null 2>&1 || sudo pacman -Qi nano >/dev/null 2>&1) && nano '{path_str}') || \\\n (echo 'No terminal editor found (nvim/vim/emacsclient/emacs/hx/helix/nano).'; echo 'File: {path_str}'; read -rn1 -s _ || true)" ); let cmds = vec![editor_cmd]; std::thread::spawn(move || { crate::install::spawn_shell_commands_in_terminal(&cmds); }); app.config_menu_open = false; true } /// What: Handle menu toggle key events. /// /// Inputs: /// - `ke`: Key event from terminal /// - `app`: Mutable application state /// /// Output: /// - `true` if a menu toggle was handled, `false` otherwise /// /// Details: /// - Toggles config, options, or panels menu. /// - Ensures only one menu is open at a time. pub fn handle_menu_toggles(ke: &KeyEvent, app: &mut AppState) -> bool { let km = &app.keymap; if matches_any(ke, &km.config_menu_toggle) { app.config_menu_open = !app.config_menu_open; if app.config_menu_open { app.options_menu_open = false; app.panels_menu_open = false; app.sort_menu_open = false; app.sort_menu_auto_close_at = None; } return true; } if matches_any(ke, &km.options_menu_toggle) { app.options_menu_open = !app.options_menu_open; if app.options_menu_open { app.config_menu_open = false; app.panels_menu_open = false; app.sort_menu_open = false; app.sort_menu_auto_close_at = None; } return true; } if matches_any(ke, &km.panels_menu_toggle) { app.panels_menu_open = !app.panels_menu_open; if app.panels_menu_open { app.config_menu_open = false; app.options_menu_open = false; app.sort_menu_open = false; app.sort_menu_auto_close_at = None; } return true; } false } /// What: Handle export of install list to file. /// /// Inputs: /// - `app`: Mutable application state /// /// Output: /// - None (modifies app state directly) /// /// Details: /// - Exports current Install List package names to config export dir. /// - Creates files with format: `install_list_YYYYMMDD_serial.txt` /// - Shows toast messages for success or failure. pub fn handle_export(app: &mut AppState) { if app.installed_only_mode { return; } let mut names: Vec<String> = app.install_list.iter().map(|p| p.name.clone()).collect(); names.sort(); if names.is_empty() { app.toast_message = Some(crate::i18n::t(app, "app.toasts.install_list_empty")); app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(3)); return; } let export_dir = crate::theme::config_dir().join("export"); let _ = std::fs::create_dir_all(&export_dir); let date_str = crate::util::today_yyyymmdd_utc(); let mut serial: u32 = 1; let file_path = loop { let fname = format!("install_list_{date_str}_{serial}.txt"); let path = export_dir.join(&fname); if !path.exists() { break path; } serial += 1; if serial > 9999 { break export_dir.join(format!("install_list_{date_str}_fallback.txt")); } }; let body = names.join("\n"); match std::fs::write(&file_path, body) { Ok(()) => { app.toast_message = Some(crate::i18n::t_fmt1( app, "app.toasts.exported_to", file_path.display(), )); app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(4)); tracing::info!(path = %file_path.display().to_string(), count = names.len(), "export: wrote install list"); } Err(e) => { let error_msg = format!("{e}"); app.toast_message = Some(crate::i18n::t_fmt1( app, "app.toasts.export_failed", &error_msg, )); app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(5)); tracing::error!(error = %e, path = %file_path.display().to_string(), "export: failed to write install list"); } } } /// What: Handle text selection movement (left/right). /// /// Inputs: /// - `app`: Mutable application state /// - `direction`: Direction to move (-1 for left, 1 for right) /// /// Output: /// - None (modifies app state directly) /// /// Details: /// - Begins selection if not already started. /// - Moves caret in the specified direction within input bounds. /// - Handles both News mode and normal search mode. fn handle_selection_move(app: &mut AppState, direction: isize) { if matches!(app.app_mode, crate::state::types::AppMode::News) { if app.news_search_select_anchor.is_none() { app.news_search_select_anchor = Some(app.news_search_caret); } let cc = char_count(&app.news_search_input); let cur = isize::try_from(app.news_search_caret).unwrap_or(0) + direction; let new_ci = if cur < 0 { 0 } else { usize::try_from(cur).unwrap_or(0) }; app.news_search_caret = new_ci.min(cc); } else { if app.search_select_anchor.is_none() { app.search_select_anchor = Some(app.search_caret); } let cc = char_count(&app.input); let cur = isize::try_from(app.search_caret).unwrap_or(0) + direction; let new_ci = if cur < 0 { 0 } else { usize::try_from(cur).unwrap_or(0) }; app.search_caret = new_ci.min(cc); } } /// What: Handle deletion of selected text range. /// /// Inputs: /// - `app`: Mutable application state /// - `query_tx`: Channel to send debounced search queries /// /// Output: /// - `true` if deletion occurred, `false` otherwise /// /// Details: /// - Deletes the selected range between anchor and caret. /// - Updates input and triggers query refresh. /// - Handles both News mode and normal search mode. fn handle_selection_delete( app: &mut AppState, query_tx: &mpsc::UnboundedSender<QueryInput>, ) -> bool { let (anchor_opt, caret, input_text) = if matches!(app.app_mode, crate::state::types::AppMode::News) { ( app.news_search_select_anchor.take(), app.news_search_caret, &mut app.news_search_input, ) } else { ( app.search_select_anchor.take(), app.search_caret, &mut app.input, ) }; let Some(anchor) = anchor_opt else { return false; }; let a = anchor.min(caret); let b = anchor.max(caret); if a == b { return false; } let bs = byte_index_for_char(input_text, a); let be = byte_index_for_char(input_text, b); let mut new_input = String::with_capacity(input_text.len()); new_input.push_str(&input_text[..bs]); new_input.push_str(&input_text[be..]); *input_text = new_input; if matches!(app.app_mode, crate::state::types::AppMode::News) { app.news_search_caret = a; app.refresh_news_results(); } else { app.search_caret = a; send_query(app, query_tx); } app.last_input_change = std::time::Instant::now(); app.last_saved_value = None; true } /// What: Handle navigation key events (j/k, arrow keys, Ctrl+D/U). /// /// Inputs: /// - `ke`: Key event from terminal /// - `app`: Mutable application state /// - `details_tx`: Channel to request details for the focused item /// /// Output: /// - `true` if navigation was handled, `false` otherwise /// /// Details: /// - Handles vim-like navigation: j/k for single line, arrow keys from keymap, Ctrl+D/U for page movement. fn handle_navigation( ke: &KeyEvent, app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, comments_tx: &mpsc::UnboundedSender<String>, ) -> bool { let km = &app.keymap; // Check keymap-based arrow keys first (works same in normal and insert mode) if matches_any(ke, &km.search_move_up) { if matches!(app.app_mode, crate::state::types::AppMode::News) { crate::events::utils::move_news_selection(app, -1); } else { move_sel_cached(app, -1, details_tx, comments_tx); } return true; } if matches_any(ke, &km.search_move_down) { if matches!(app.app_mode, crate::state::types::AppMode::News) { crate::events::utils::move_news_selection(app, 1); } else { move_sel_cached(app, 1, details_tx, comments_tx); } return true; } if matches_any(ke, &km.search_page_up) { if matches!(app.app_mode, crate::state::types::AppMode::News) { crate::events::utils::move_news_selection(app, -10); } else { move_sel_cached(app, -10, details_tx, comments_tx); } return true; } if matches_any(ke, &km.search_page_down) { if matches!(app.app_mode, crate::state::types::AppMode::News) { crate::events::utils::move_news_selection(app, 10); } else { move_sel_cached(app, 10, details_tx, comments_tx); } return true; } // Vim-like navigation (j/k, Ctrl+D/U) match (ke.code, ke.modifiers) { (KeyCode::Char('j'), _) => { if matches!(app.app_mode, crate::state::types::AppMode::News) { crate::events::utils::move_news_selection(app, 1); } else { move_sel_cached(app, 1, details_tx, comments_tx); } true } (KeyCode::Char('k'), _) => { if matches!(app.app_mode, crate::state::types::AppMode::News) { crate::events::utils::move_news_selection(app, -1); } else { move_sel_cached(app, -1, details_tx, comments_tx); } true } (KeyCode::Char('d'), KeyModifiers::CONTROL) => { move_sel_cached(app, 10, details_tx, comments_tx); true } (KeyCode::Char('u'), KeyModifiers::CONTROL) => { move_sel_cached(app, -10, details_tx, comments_tx); true } _ => false, } } /// What: Handle space key events (add to list or downgrade). /// /// Inputs: /// - `ke`: Key event from terminal /// - `app`: Mutable application state /// - `details_tx`: Channel to request details for the focused item /// - `add_tx`: Channel to add items to the Install/Remove lists /// /// Output: /// - `true` if space key was handled, `false` otherwise /// /// Details: /// - Ctrl+Space: Adds to downgrade list (installed-only mode only). /// - Space: Adds to install list or remove list depending on mode. fn handle_space_key( ke: &KeyEvent, app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, add_tx: &mpsc::UnboundedSender<PackageItem>, ) -> bool { match (ke.code, ke.modifiers) { (KeyCode::Char(' '), KeyModifiers::CONTROL) => { if app.installed_only_mode && let Some(item) = app.results.get(app.selected).cloned() { crate::logic::add_to_downgrade_list(app, item); crate::events::utils::refresh_downgrade_details(app, details_tx); } true } (KeyCode::Char(' '), _) => { if matches!(app.app_mode, crate::state::types::AppMode::News) { if let Some(item) = app.news_results.get(app.news_selected).cloned() { let url_opt = item.url.clone(); let mut content = app.news_content.clone().or_else(|| { url_opt .as_ref() .and_then(|u| app.news_content_cache.get(u).cloned()) }); let mut html_path = None; if let Some(url) = &url_opt && let Ok(html) = crate::util::curl::curl_text(url) { let dir = crate::theme::lists_dir().join("news_html"); let _ = std::fs::create_dir_all(&dir); let mut hasher = DefaultHasher::new(); item.id.hash(&mut hasher); let fname = format!("{:016x}.html", hasher.finish()); let path = dir.join(fname); if std::fs::write(&path, &html).is_ok() { html_path = Some(path.to_string_lossy().to_string()); if content.is_none() { content = Some(crate::sources::parse_news_html(&html)); } } } let bookmark = crate::state::types::NewsBookmark { item, content, html_path, }; app.add_news_bookmark(bookmark); app.toast_message = Some(crate::i18n::t( app, "app.results.options_menu.news_management", )); app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(2)); } return true; } if let Some(item) = app.results.get(app.selected).cloned() { if app.installed_only_mode { crate::logic::add_to_remove_list(app, item); crate::events::utils::refresh_remove_details(app, details_tx); } else { let _ = add_tx.send(item); } } true } _ => false, } } /// What: Handle preflight modal opening. /// /// Inputs: /// - `ke`: Key event from terminal /// - `app`: Mutable application state /// /// Output: /// - `true` if preflight was opened, `false` otherwise /// /// Details: /// - Opens preflight modal for the selected package using configured key or Enter. fn handle_preflight_open(ke: &KeyEvent, app: &mut AppState) -> bool { // Don't open preflight if Ctrl is held (might be Ctrl+M interpreted as Enter) if ke.modifiers.contains(KeyModifiers::CONTROL) { tracing::debug!( "[NormalMode] Key with Ctrl detected in handle_preflight_open, ignoring (likely Ctrl+M): code={:?}", ke.code ); return false; } let should_open = matches_any(ke, &app.keymap.search_install) || matches!(ke.code, KeyCode::Char('\n') | KeyCode::Enter); if should_open && let Some(item) = app.results.get(app.selected).cloned() { tracing::debug!("[NormalMode] Opening preflight for package: {}", item.name); open_preflight_modal(app, vec![item], true); return true; } false } /// What: Handle pane navigation (Left/Right arrows and `pane_next`). /// /// Inputs: /// - `ke`: Key event from terminal /// - `app`: Mutable application state /// - `details_tx`: Channel to request details for the focused item /// - `preview_tx`: Channel to request preview details when moving focus /// /// Output: /// - `true` if pane navigation was handled, `false` otherwise /// /// Details: /// - Handles Left/Right arrow keys and configured `pane_next` key. /// - Switches focus between panes and updates details accordingly. fn handle_pane_navigation( ke: &KeyEvent, app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, preview_tx: &mpsc::UnboundedSender<PackageItem>, ) -> bool { match ke.code { KeyCode::Right => { navigate_pane(app, "right", details_tx, preview_tx); true } KeyCode::Left => { navigate_pane(app, "left", details_tx, preview_tx); true } _ if matches_any(ke, &app.keymap.pane_next) => { if matches!(app.app_mode, crate::state::types::AppMode::News) { app.focus = crate::state::Focus::Install; return true; } if app.installed_only_mode { app.right_pane_focus = crate::state::RightPaneFocus::Downgrade; if app.downgrade_state.selected().is_none() && !app.downgrade_list.is_empty() { app.downgrade_state.select(Some(0)); } app.focus = crate::state::Focus::Install; crate::events::utils::refresh_downgrade_details(app, details_tx); } else { if app.install_state.selected().is_none() && !app.install_list.is_empty() { app.install_state.select(Some(0)); } app.focus = crate::state::Focus::Install; refresh_install_details(app, details_tx); } true } _ => false, } } /// What: Handle input clearing. /// /// Inputs: /// - `app`: Mutable application state /// - `query_tx`: Channel to send debounced search queries /// /// Output: /// - None (modifies app state directly) /// /// Details: /// - Clears the entire search input and resets caret/selection. fn handle_input_clear(app: &mut AppState, query_tx: &mpsc::UnboundedSender<QueryInput>) { if matches!(app.app_mode, crate::state::types::AppMode::News) { if !app.news_search_input.is_empty() { app.news_search_input.clear(); app.news_search_caret = 0; app.news_search_select_anchor = None; app.last_input_change = std::time::Instant::now(); app.last_saved_value = None; app.refresh_news_results(); } } else if !app.input.is_empty() { app.input.clear(); app.search_caret = 0; app.search_select_anchor = None; app.last_input_change = std::time::Instant::now(); app.last_saved_value = None; send_query(app, query_tx); } } /// What: Mark or unmark the selected News Feed item as read. /// /// Inputs: /// - `app`: Mutable application state /// - `mark_read`: Whether to mark as read (`true`) or unread (`false`) /// /// Output: /// - `true` if state changed (set updated), `false` otherwise /// /// Details: /// - Updates both the ID-based read set and the legacy URL set when available. /// - Refreshes news results to honor read/unread filtering. fn mark_news_feed_item(app: &mut AppState, mark_read: bool) -> bool { let Some(item) = app.news_results.get(app.news_selected).cloned() else { return false; }; let is_read_before = app.news_read_ids.contains(&item.id) || item .url .as_ref() .is_some_and(|u| app.news_read_urls.contains(u)); let mut changed = false; if mark_read { if !is_read_before { app.news_read_ids_dirty = true; app.news_read_dirty = app.news_read_dirty || item.url.is_some(); changed = true; } app.news_read_ids.insert(item.id.clone()); if let Some(url) = item.url.as_ref() { app.news_read_urls.insert(url.clone()); } } else { if is_read_before { app.news_read_ids_dirty = true; app.news_read_dirty = app.news_read_dirty || item.url.is_some(); changed = true; } app.news_read_ids.remove(&item.id); if let Some(url) = item.url.as_ref() { app.news_read_urls.remove(url); } } if changed { app.refresh_news_results(); } changed } /// What: Toggle read/unread state for the selected News Feed item. /// /// Inputs: /// - `app`: Mutable application state /// /// Output: /// - `true` if state changed (toggled), `false` otherwise /// /// Details: /// - Considers both ID-based and legacy URL-based read state for determining current status. fn toggle_news_feed_item(app: &mut AppState) -> bool { let Some(item) = app.news_results.get(app.news_selected).cloned() else { return false; }; let is_read = app.news_read_ids.contains(&item.id) || item .url .as_ref() .is_some_and(|u| app.news_read_urls.contains(u)); if is_read { mark_news_feed_item(app, false) } else { mark_news_feed_item(app, true) } } /// What: Handle news mode keybindings. /// /// Inputs: /// - `ke`: Key event from terminal /// - `app`: Mutable application state /// /// Output: /// - `true` if a news keybinding was handled, `false` otherwise /// /// Details: /// - Handles mark read, mark unread, and toggle read keybindings in News mode. fn handle_news_mode_keybindings(ke: &KeyEvent, app: &mut AppState) -> bool { if !matches!(app.app_mode, crate::state::types::AppMode::News) { return false; } if matches_any(ke, &app.keymap.news_mark_read_feed) { if mark_news_feed_item(app, true) { return true; } } else if matches_any(ke, &app.keymap.news_mark_unread_feed) { if mark_news_feed_item(app, false) { return true; } } else if matches_any(ke, &app.keymap.news_toggle_read_feed) && toggle_news_feed_item(app) { return true; } false } /// What: Handle keymap-based action keybindings. /// /// Inputs: /// - `ke`: Key event from terminal /// - `app`: Mutable application state /// - `query_tx`: Channel to send debounced search queries /// /// Output: /// - `true` if a keymap action was handled, `false` otherwise /// /// Details: /// - Handles status, import, export, updates, insert mode, selection, delete, and clear actions. fn handle_keymap_actions( ke: &KeyEvent, app: &mut AppState, query_tx: &mpsc::UnboundedSender<QueryInput>, ) -> bool { if matches_any(ke, &app.keymap.search_normal_open_status) { crate::util::open_url("https://status.archlinux.org"); return true; } if matches_any(ke, &app.keymap.search_normal_import) { if !app.installed_only_mode { app.modal = crate::state::Modal::ImportHelp; } return true; } if matches_any(ke, &app.keymap.search_normal_export) { handle_export(app); return true; } if matches_any(ke, &app.keymap.search_normal_updates) { if matches!(app.app_mode, crate::state::types::AppMode::News) { crate::events::mouse::handle_news_button(app); } else { crate::events::mouse::handle_updates_button(app); } return true; } if matches_any(ke, &app.keymap.search_normal_insert) { app.search_normal_mode = false; app.search_select_anchor = None; return true; } if matches_any(ke, &app.keymap.search_normal_select_left) { handle_selection_move(app, -1); return true; } if matches_any(ke, &app.keymap.search_normal_select_right) { handle_selection_move(app, 1); return true; } if matches_any(ke, &app.keymap.search_normal_delete) { handle_selection_delete(app, query_tx); return true; } if matches_any(ke, &app.keymap.search_normal_clear) { handle_input_clear(app, query_tx); return true; } false } /// What: Handle key events in Normal mode for the Search pane. /// /// Inputs: /// - `ke`: Key event received from the terminal /// - `app`: Mutable application state /// - `query_tx`: Channel to send debounced search queries /// - `details_tx`: Channel to request details for the focused item /// - `add_tx`: Channel to add items to the Install/Remove lists /// - `preview_tx`: Channel to request preview details when moving focus /// /// Output: /// - `true` if the key was handled and should stop further processing; `false` otherwise /// /// Details: /// - Handles vim-like navigation, selection, deletion, menu toggles, import/export, and preflight opening. /// - Supports numeric selection for config menu items. pub fn handle_normal_mode( ke: KeyEvent, app: &mut AppState, query_tx: &mpsc::UnboundedSender<QueryInput>, details_tx: &mpsc::UnboundedSender<PackageItem>, add_tx: &mpsc::UnboundedSender<PackageItem>, preview_tx: &mpsc::UnboundedSender<PackageItem>, comments_tx: &mpsc::UnboundedSender<String>, ) -> bool { // Handle numeric selection for config menu (1-9) if let KeyCode::Char(ch) = ke.code && ch.is_ascii_digit() && ch != '0' { let idx = (ch as u8 - b'1') as usize; if handle_config_menu_numeric_selection(idx, app) { return false; } } // Handle news mode keybindings if handle_news_mode_keybindings(&ke, app) { return false; } // Handle menu toggles let menu_toggled = { let km = &app.keymap; matches_any(&ke, &km.config_menu_toggle) || matches_any(&ke, &km.options_menu_toggle) || matches_any(&ke, &km.panels_menu_toggle) }; if menu_toggled && handle_menu_toggles(&ke, app) { return false; } // Handle keymap-based actions if handle_keymap_actions(&ke, app, query_tx) { return false; } // Handle navigation keys if handle_navigation(&ke, app, details_tx, comments_tx) { return false; } // Handle space key if handle_space_key(&ke, app, details_tx, add_tx) { return false; } // Handle preflight opening if handle_preflight_open(&ke, app) { return false; } // Handle pane navigation if handle_pane_navigation(&ke, app, details_tx, preview_tx) { return false; } false } #[cfg(test)] mod tests { use super::*; use crate::state::types::{AppMode, NewsFeedItem, NewsFeedSource}; use crossterm::event::{KeyCode, KeyEvent, KeyEventKind, KeyEventState, KeyModifiers}; use tokio::sync::mpsc; fn make_news_item(id: &str, url: &str) -> NewsFeedItem { NewsFeedItem { id: id.to_string(), date: "2025-01-01".to_string(), title: format!("Item {id}"), summary: None, url: Some(url.to_string()), source: NewsFeedSource::ArchNews, severity: None, packages: vec![], } } fn key(code: KeyCode) -> KeyEvent { KeyEvent { code, modifiers: KeyModifiers::empty(), kind: KeyEventKind::Press, state: KeyEventState::empty(), } } #[test] fn mark_news_feed_item_sets_read_state() { let item = make_news_item("one", "https://example.com/one"); let mut app = AppState { app_mode: AppMode::News, news_items: vec![item.clone()], news_results: vec![item], news_selected: 0, news_max_age_days: None, ..AppState::default() }; let changed = mark_news_feed_item(&mut app, true); assert!(changed); assert!(app.news_read_ids.contains("one")); assert!(app.news_read_ids_dirty); assert!(app.news_read_urls.contains("https://example.com/one")); assert!(app.news_read_dirty); let changed_unread = mark_news_feed_item(&mut app, false); assert!(changed_unread); assert!(!app.news_read_ids.contains("one")); assert!(app.news_read_ids_dirty); } #[test] fn toggle_news_feed_item_respects_legacy_url_state() { let item = make_news_item("two", "https://example.com/two"); let mut app = AppState { app_mode: AppMode::News, news_items: vec![item.clone()], news_results: vec![item], news_selected: 0, news_max_age_days: None, ..AppState::default() }; app.news_read_urls.insert("https://example.com/two".into()); app.news_read_dirty = true; let toggled = toggle_news_feed_item(&mut app); assert!(toggled); assert!(!app.news_read_ids.contains("two")); assert!(!app.news_read_urls.contains("https://example.com/two")); assert!(app.news_read_ids_dirty); assert!(app.news_read_dirty); } #[test] fn handle_normal_mode_marks_read_via_keybinding() { let item = make_news_item("three", "https://example.com/three"); let mut app = AppState { app_mode: AppMode::News, news_items: vec![item.clone()], news_results: vec![item], news_selected: 0, ..AppState::default() }; let (query_tx, _query_rx) = mpsc::unbounded_channel(); let (details_tx, _details_rx) = mpsc::unbounded_channel(); let (add_tx, _add_rx) = mpsc::unbounded_channel(); let (preview_tx, _preview_rx) = mpsc::unbounded_channel(); let (comments_tx, _comments_rx) = mpsc::unbounded_channel(); let ke = key(KeyCode::Char('r')); let handled = handle_normal_mode( ke, &mut app, &query_tx, &details_tx, &add_tx, &preview_tx, &comments_tx, ); assert!(!handled); assert!(app.news_read_ids.contains("three")); } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/mouse/menus.rs
src/events/mouse/menus.rs
//! Menu mouse event handling (sort, options, config, panels, import/export). use std::time::Instant; use tokio::sync::mpsc; use crate::events::utils::refresh_selected_details; use crate::i18n; use crate::state::{AppState, PackageItem}; use super::menu_options; /// Check if a point is within a rectangle. /// /// What: Determines if mouse coordinates are inside a given rectangle. /// /// Inputs: /// - `mx`: Mouse X coordinate /// - `my`: Mouse Y coordinate /// - `rect`: Optional rectangle as (x, y, width, height) /// /// Output: /// - `true` if point is within rectangle, `false` otherwise /// /// Details: /// - Returns `false` if rectangle is `None` const fn 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 click on Import button. /// /// What: Opens `ImportHelp` modal when Import button is clicked. /// /// Inputs: /// - `app`: Mutable application state /// /// Output: /// - `false` if handled fn handle_import_button(app: &mut AppState) -> bool { app.modal = crate::state::Modal::ImportHelp; false } /// Handle click on Updates button. /// /// What: Opens the available updates modal with scrollable list and triggers refresh. /// /// Inputs: /// - `app`: Mutable application state /// /// Output: /// - `false` if handled /// /// Details: /// - Loads updates from `~/.config/pacsea/lists/available_updates.txt` /// - Opens Updates modal with scroll support /// - Triggers a refresh of the updates list to ensure current data /// - Opens the modal only after refresh completes #[allow(clippy::missing_const_for_fn)] pub fn handle_updates_button(app: &mut AppState) -> bool { // Trigger refresh of updates list when button is clicked app.refresh_updates = true; app.updates_loading = true; // Set flag to open modal after refresh completes app.pending_updates_modal = true; // Don't open modal yet - wait for refresh to complete false } /// Handle click on News button. /// /// What: Opens the News modal with available news items. /// /// Inputs: /// - `app`: Mutable application state /// /// Output: /// - `false` if handled /// /// Details: /// - Opens News modal if news are ready /// - Shows "No News available" message if no news exist /// - Converts `pending_news` (legacy format) to `NewsFeedItem` format for modal /// - Preserves `pending_news` for subsequent opens by using `as_ref()` instead of `take()` pub fn handle_news_button(app: &mut AppState) -> bool { if app.news_ready { // Convert NewsItem to NewsFeedItem for the modal // Use as_ref() instead of take() to preserve pending_news for subsequent opens if let Some(news_items) = app.pending_news.as_ref() { // Filter out items that have been marked as read (by ID or URL) let feed_items: Vec<crate::state::types::NewsFeedItem> = news_items .iter() .filter(|item| { // Filter out items marked as read by ID (id == url for Arch news) !app.news_read_ids.contains(&item.url) && !app.news_read_urls.contains(&item.url) }) .map(|item| crate::state::types::NewsFeedItem { id: item.url.clone(), date: item.date.clone(), title: item.title.clone(), summary: None, url: Some(item.url.clone()), source: crate::state::types::NewsFeedSource::ArchNews, severity: None, packages: Vec::new(), }) .collect(); // Only show modal if there are unread items if feed_items.is_empty() { // All items have been read - show toast instead app.toast_message = Some(crate::i18n::t(app, "app.toasts.no_new_news")); app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(3)); return true; } app.modal = crate::state::Modal::News { items: feed_items, selected: 0, scroll: 0, }; } else { // No news available - show empty modal app.modal = crate::state::Modal::News { items: Vec::new(), selected: 0, scroll: 0, }; } } else { // No news available - show empty modal app.modal = crate::state::Modal::News { items: Vec::new(), selected: 0, scroll: 0, }; } false } /// Handle click on Export button. /// /// What: Exports install list to timestamped file in export directory. /// /// Inputs: /// - `app`: Mutable application state /// /// Output: /// - `false` if handled /// /// Details: /// - Shows toast message if list is empty or export fails fn handle_export_button(app: &mut AppState) -> bool { let mut names: Vec<String> = app.install_list.iter().map(|p| p.name.clone()).collect(); names.sort(); if names.is_empty() { app.toast_message = Some(crate::i18n::t(app, "app.toasts.install_list_empty")); app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(3)); return false; } let export_dir = crate::theme::config_dir().join("export"); let _ = std::fs::create_dir_all(&export_dir); let date_str = crate::util::today_yyyymmdd_utc(); let mut serial: u32 = 1; let file_path = loop { let fname = format!("install_list_{date_str}_{serial}.txt"); let path = export_dir.join(&fname); if !path.exists() { break path; } serial += 1; if serial > 9999 { break export_dir.join(format!("install_list_{date_str}_fallback.txt")); } }; let body = names.join("\n"); match std::fs::write(&file_path, body) { Ok(()) => { app.toast_message = Some(crate::i18n::t_fmt1( app, "app.toasts.exported_to", file_path.display(), )); app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(4)); tracing::info!(path = %file_path.display().to_string(), count = names.len(), "export: wrote install list"); } Err(e) => { let error_msg = format!("{e}"); app.toast_message = Some(crate::i18n::t_fmt1( app, "app.toasts.export_failed", &error_msg, )); app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(5)); tracing::error!(error = %e, path = %file_path.display().to_string(), "export: failed to write install list"); } } false } /// Handle click on Arch status label. /// /// What: Opens status.archlinux.org URL in browser. /// /// Output: /// - `false` if handled fn handle_arch_status() -> bool { crate::util::open_url("https://status.archlinux.org"); false } /// Handle click on sort menu button. /// /// What: Toggles sort menu open/closed state. /// /// Inputs: /// - `app`: Mutable application state /// /// Output: /// - `false` if handled #[allow(clippy::missing_const_for_fn)] fn handle_sort_button(app: &mut AppState) -> bool { app.sort_menu_open = !app.sort_menu_open; if !app.sort_menu_open { app.sort_menu_auto_close_at = None; } false } /// Handle click on options menu button. /// /// What: Toggles options menu and closes other menus. /// /// Inputs: /// - `app`: Mutable application state /// /// Output: /// - `false` if handled #[allow(clippy::missing_const_for_fn)] fn handle_options_button(app: &mut AppState) -> bool { app.options_menu_open = !app.options_menu_open; if app.options_menu_open { app.panels_menu_open = false; app.config_menu_open = false; app.artix_filter_menu_open = false; } false } /// Handle click on config menu button. /// /// What: Toggles config menu and closes other menus. /// /// Inputs: /// - `app`: Mutable application state /// /// Output: /// - `false` if handled #[allow(clippy::missing_const_for_fn)] fn handle_config_button(app: &mut AppState) -> bool { app.config_menu_open = !app.config_menu_open; if app.config_menu_open { app.options_menu_open = false; app.panels_menu_open = false; } false } /// Handle click on panels menu button. /// /// What: Toggles panels menu and closes other menus. /// /// Inputs: /// - `app`: Mutable application state /// /// Output: /// - `false` if handled #[allow(clippy::missing_const_for_fn)] fn handle_panels_button(app: &mut AppState) -> bool { app.panels_menu_open = !app.panels_menu_open; if app.panels_menu_open { app.options_menu_open = false; app.config_menu_open = false; app.artix_filter_menu_open = false; } false } /// Handle click on collapsed menu button. /// /// What: Toggles collapsed menu and closes other menus. /// /// Inputs: /// - `app`: Mutable application state /// /// Output: /// - `false` if handled #[allow(clippy::missing_const_for_fn)] fn handle_collapsed_menu_button(app: &mut AppState) -> bool { app.collapsed_menu_open = !app.collapsed_menu_open; if app.collapsed_menu_open { app.options_menu_open = false; app.config_menu_open = false; app.panels_menu_open = false; app.artix_filter_menu_open = false; } false } /// Handle click inside sort menu. /// /// What: Changes sort mode based on clicked row and refreshes results. /// /// Inputs: /// - `mx`: Mouse X coordinate /// - `my`: Mouse Y coordinate /// - `app`: Mutable application state /// - `details_tx`: Channel to request package details /// /// Output: /// - `Some(false)` if handled, `None` otherwise fn handle_sort_menu_click( _mx: u16, my: u16, app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, ) -> Option<bool> { if let Some((_x, y, _w, _h)) = app.sort_menu_rect { let row = my.saturating_sub(y) as usize; if matches!(app.app_mode, crate::state::types::AppMode::News) { match row { 0 => app.news_sort_mode = crate::state::types::NewsSortMode::DateDesc, 1 => app.news_sort_mode = crate::state::types::NewsSortMode::DateAsc, 2 => app.news_sort_mode = crate::state::types::NewsSortMode::Title, 3 => app.news_sort_mode = crate::state::types::NewsSortMode::SourceThenTitle, 4 => app.news_sort_mode = crate::state::types::NewsSortMode::SeverityThenDate, 5 => app.news_sort_mode = crate::state::types::NewsSortMode::UnreadThenDate, _ => return None, } app.refresh_news_results(); } else { match row { 0 => { app.sort_mode = crate::state::SortMode::RepoThenName; crate::theme::save_sort_mode(app.sort_mode); } 1 => { app.sort_mode = crate::state::SortMode::AurPopularityThenOfficial; crate::theme::save_sort_mode(app.sort_mode); } 2 => { app.sort_mode = crate::state::SortMode::BestMatches; crate::theme::save_sort_mode(app.sort_mode); } _ => return None, } crate::logic::sort_results_preserve_selection(app); if app.results.is_empty() { app.list_state.select(None); } else { app.selected = 0; app.list_state.select(Some(0)); refresh_selected_details(app, details_tx); } } app.sort_menu_open = false; app.sort_menu_auto_close_at = None; Some(false) } else { None } } /// Handle click inside options menu. /// /// What: Handles clicks on options menu items (installed-only toggle, system update, news, optional deps). /// /// Inputs: /// - `mx`: Mouse X coordinate /// - `my`: Mouse Y coordinate /// - `app`: Mutable application state /// - `details_tx`: Channel to request package details /// /// Output: /// - `Some(false)` if handled, `None` otherwise fn handle_options_menu_click( _mx: u16, my: u16, app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, ) -> Option<bool> { if let Some((_x, y, _w, _h)) = app.options_menu_rect { let row = my.saturating_sub(y) as usize; let news_mode = matches!(app.app_mode, crate::state::types::AppMode::News); if news_mode { match row { 0 => handle_system_update_option(app), 1 => handle_optional_deps_option(app), 2 => handle_mode_toggle(app, details_tx), _ => return None, } } else { match row { 0 => handle_installed_only_toggle(app, details_tx), 1 => handle_system_update_option(app), 2 => handle_optional_deps_option(app), 3 => handle_mode_toggle(app, details_tx), _ => return None, } } app.options_menu_open = false; Some(false) } else { None } } /// Handle installed-only mode toggle. /// /// What: Toggles between showing all packages and only explicitly installed packages. /// /// Inputs: /// - `app`: Mutable application state /// - `details_tx`: Channel to request package details /// /// Details: /// - When enabling, saves installed packages list to config directory fn handle_installed_only_toggle( app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, ) { use std::collections::HashSet; if app.installed_only_mode { if let Some(prev) = app.results_backup_for_toggle.take() { app.all_results = prev; } app.installed_only_mode = false; app.right_pane_focus = crate::state::RightPaneFocus::Install; crate::logic::apply_filters_and_sort_preserve_selection(app); crate::events::utils::refresh_selected_details(app, details_tx); } else { app.results_backup_for_toggle = Some(app.all_results.clone()); let explicit = crate::index::explicit_names(); let mut items: Vec<crate::state::PackageItem> = crate::index::all_official() .into_iter() .filter(|p| explicit.contains(&p.name)) .collect(); let official_names: HashSet<String> = items.iter().map(|p| p.name.clone()).collect(); for name in explicit { if !official_names.contains(&name) { let is_eos = crate::index::is_eos_name(&name); let src = if is_eos { crate::state::Source::Official { repo: "EOS".to_string(), arch: String::new(), } } else { crate::state::Source::Aur }; items.push(crate::state::PackageItem { name: name.clone(), version: String::new(), description: String::new(), source: src, popularity: None, out_of_date: None, orphaned: false, }); } } app.all_results = items; app.installed_only_mode = true; app.right_pane_focus = crate::state::RightPaneFocus::Remove; crate::logic::apply_filters_and_sort_preserve_selection(app); crate::events::utils::refresh_selected_details(app, details_tx); let path = crate::theme::config_dir().join("installed_packages.txt"); // Query pacman directly with current mode to ensure file reflects the setting let names = crate::index::query_explicit_packages_sync(app.installed_packages_mode); let body = names.join("\n"); let _ = std::fs::write(path, body); } } /// What: Toggle between package mode and news feed mode. /// /// Inputs: /// - `app`: Mutable application state /// - `details_tx`: Channel to request package details when switching back to package mode pub(in crate::events) fn handle_mode_toggle( app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, ) { if matches!(app.app_mode, crate::state::types::AppMode::News) { app.app_mode = crate::state::types::AppMode::Package; if app.results.is_empty() { app.list_state.select(None); } else { app.selected = app.selected.min(app.results.len().saturating_sub(1)); app.list_state.select(Some(app.selected)); refresh_selected_details(app, details_tx); } } else { app.app_mode = crate::state::types::AppMode::News; if app.news_results.is_empty() { app.news_list_state.select(None); app.news_selected = 0; } else { app.news_selected = 0; app.news_list_state.select(Some(0)); } } crate::theme::save_app_start_mode(matches!(app.app_mode, crate::state::types::AppMode::News)); } /// What: Toggle news maximum age filter between 7, 30, 90 days, and no limit. /// /// Inputs: /// - `app`: Mutable application state /// /// Output: /// - None (modifies app state directly) /// /// Details: /// - Cycles through age options: 7 days → 30 days → 90 days → no limit → 7 days /// - Refreshes news results after changing the filter pub(in crate::events) fn handle_news_age_toggle(app: &mut AppState) { const AGES: [Option<u32>; 4] = [Some(7), Some(30), Some(90), None]; let current = app.news_max_age_days; let next = AGES .iter() .cycle() .skip_while(|&&v| v != current) .nth(1) .copied() .unwrap_or(Some(7)); app.news_max_age_days = next; app.refresh_news_results(); let age_label = app.news_max_age_days.map_or_else( || i18n::t(app, "app.results.options_menu.news_age_all"), |d| i18n::t_fmt1(app, "app.results.options_menu.news_age_days", d.to_string()), ); app.toast_message = Some(age_label); app.toast_expires_at = Some(Instant::now() + std::time::Duration::from_secs(3)); crate::theme::save_news_max_age_days(app.news_max_age_days); } /// Handle system update option. /// /// What: Opens `SystemUpdate` modal with default settings. /// /// Inputs: /// - `app`: Mutable application state fn handle_system_update_option(app: &mut AppState) { let countries = vec![ "Worldwide".to_string(), "Germany".to_string(), "United States".to_string(), "United Kingdom".to_string(), "France".to_string(), "Netherlands".to_string(), "Sweden".to_string(), "Canada".to_string(), "Australia".to_string(), "Japan".to_string(), ]; let prefs = crate::theme::settings(); let initial_country_idx = { let sel = prefs .selected_countries .split(',') .next() .map_or_else(|| "Worldwide".to_string(), |s| s.trim().to_string()); countries.iter().position(|c| c == &sel).unwrap_or(0) }; app.modal = crate::state::Modal::SystemUpdate { do_mirrors: false, do_pacman: true, force_sync: false, do_aur: true, do_cache: false, country_idx: initial_country_idx, countries, mirror_count: prefs.mirror_count, cursor: 0, }; } /// Handle optional deps option. /// /// What: Builds optional dependencies rows and opens `OptionalDeps` modal. /// /// Inputs: /// - `app`: Mutable application state fn handle_optional_deps_option(app: &mut AppState) { let rows = menu_options::build_optional_deps_rows(app); app.modal = crate::state::Modal::OptionalDeps { rows, selected: 0 }; } /// Handle click inside config menu. /// /// What: Opens config files in terminal editors based on clicked row. /// /// Inputs: /// - `mx`: Mouse X coordinate /// - `my`: Mouse Y coordinate /// - `app`: Mutable application state /// /// Output: /// - `Some(false)` if handled, `None` otherwise /// /// Details: fn handle_config_menu_click(_mx: u16, my: u16, app: &mut AppState) -> Option<bool> { if let Some((_x, y, _w, _h)) = app.config_menu_rect { let row = my.saturating_sub(y) as usize; let settings_path = crate::theme::config_dir().join("settings.conf"); let theme_path = crate::theme::config_dir().join("theme.conf"); let keybinds_path = crate::theme::config_dir().join("keybinds.conf"); let target = match row { 0 => settings_path, 1 => theme_path, 2 => keybinds_path, _ => { app.config_menu_open = false; app.artix_filter_menu_open = false; return Some(false); } }; #[cfg(target_os = "windows")] { crate::util::open_file(&target); } #[cfg(not(target_os = "windows"))] { let path_str = target.display().to_string(); let editor_cmd = format!( "((command -v nvim >/dev/null 2>&1 || sudo pacman -Qi neovim >/dev/null 2>&1) && nvim '{path_str}') || \ ((command -v vim >/dev/null 2>&1 || sudo pacman -Qi vim >/dev/null 2>&1) && vim '{path_str}') || \ ((command -v hx >/dev/null 2>&1 || sudo pacman -Qi helix >/dev/null 2>&1) && hx '{path_str}') || \ ((command -v helix >/dev/null 2>&1 || sudo pacman -Qi helix >/dev/null 2>&1) && helix '{path_str}') || \ ((command -v emacsclient >/dev/null 2>&1 || sudo pacman -Qi emacs >/dev/null 2>&1) && emacsclient -t '{path_str}') || \ ((command -v emacs >/dev/null 2>&1 || sudo pacman -Qi emacs >/dev/null 2>&1) && emacs -nw '{path_str}') || \ ((command -v nano >/dev/null 2>&1 || sudo pacman -Qi nano >/dev/null 2>&1) && nano '{path_str}') || \ (echo 'No terminal editor found (nvim/vim/emacsclient/emacs/hx/helix/nano).'; echo 'File: {path_str}'; read -rn1 -s _ || true)", ); let cmds = vec![editor_cmd]; std::thread::spawn(move || { crate::install::spawn_shell_commands_in_terminal(&cmds); }); } app.config_menu_open = false; Some(false) } else { None } } /// Handle click inside panels menu. /// /// What: Toggles panel visibility based on clicked row. /// /// Inputs: /// - `mx`: Mouse X coordinate /// - `my`: Mouse Y coordinate /// - `app`: Mutable application state /// /// Output: /// - `Some(false)` if handled, `None` otherwise fn handle_panels_menu_click(_mx: u16, my: u16, app: &mut AppState) -> Option<bool> { if let Some((_x, y, _w, _h)) = app.panels_menu_rect { let row = my.saturating_sub(y) as usize; let news_mode = matches!(app.app_mode, crate::state::types::AppMode::News); if news_mode { match row { 0 => { app.show_news_history_pane = !app.show_news_history_pane; if !app.show_news_history_pane && matches!(app.focus, crate::state::Focus::Recent) { app.focus = crate::state::Focus::Search; } } 1 => { app.show_news_bookmarks_pane = !app.show_news_bookmarks_pane; if !app.show_news_bookmarks_pane && matches!(app.focus, crate::state::Focus::Install) { app.focus = crate::state::Focus::Search; } } 2 => { app.show_keybinds_footer = !app.show_keybinds_footer; crate::theme::save_show_keybinds_footer(app.show_keybinds_footer); } _ => return None, } } else { match row { 0 => { app.show_recent_pane = !app.show_recent_pane; if !app.show_recent_pane && matches!(app.focus, crate::state::Focus::Recent) { app.focus = crate::state::Focus::Search; } crate::theme::save_show_recent_pane(app.show_recent_pane); } 1 => { app.show_install_pane = !app.show_install_pane; if !app.show_install_pane && matches!(app.focus, crate::state::Focus::Install) { app.focus = crate::state::Focus::Search; } crate::theme::save_show_install_pane(app.show_install_pane); } 2 => { app.show_keybinds_footer = !app.show_keybinds_footer; crate::theme::save_show_keybinds_footer(app.show_keybinds_footer); } _ => return None, } } Some(false) } else { None } } /// Handle click inside collapsed menu. /// /// What: Opens the appropriate menu based on clicked row. /// /// Inputs: /// - `mx`: Mouse X coordinate /// - `my`: Mouse Y coordinate /// - `app`: Mutable application state /// /// Output: /// - `Some(false)` if handled, `None` otherwise /// /// Details: /// - Row 0: Opens Config/Lists menu /// - Row 1: Opens Panels menu /// - Row 2: Opens Options menu #[allow(clippy::missing_const_for_fn)] fn handle_collapsed_menu_click(_mx: u16, my: u16, app: &mut AppState) -> Option<bool> { if let Some((_x, y, _w, _h)) = app.collapsed_menu_rect { let row = my.saturating_sub(y) as usize; app.collapsed_menu_open = false; match row { 0 => { app.config_menu_open = true; app.options_menu_open = false; app.panels_menu_open = false; app.artix_filter_menu_open = false; } 1 => { app.panels_menu_open = true; app.options_menu_open = false; app.config_menu_open = false; app.artix_filter_menu_open = false; } 2 => { app.options_menu_open = true; app.panels_menu_open = false; app.config_menu_open = false; app.artix_filter_menu_open = false; } _ => return None, } Some(false) } else { None } } /// Close all open menus. /// /// What: Closes all menus when clicking outside any menu. /// /// Inputs: /// - `app`: Mutable application state #[allow(clippy::missing_const_for_fn)] fn close_all_menus(app: &mut AppState) { if app.sort_menu_open { app.sort_menu_open = false; app.sort_menu_auto_close_at = None; } if app.options_menu_open { app.options_menu_open = false; } if app.panels_menu_open { app.panels_menu_open = false; } if app.config_menu_open { app.config_menu_open = false; } if app.collapsed_menu_open { app.collapsed_menu_open = false; } } /// Handle mouse events for menus (sort, options, config, panels, import/export). /// /// What: Process mouse interactions with menu buttons, dropdown menus, and action buttons /// in the title bar and Install pane. /// /// Inputs: /// - `mx`: Mouse X coordinate (column) /// - `my`: Mouse Y coordinate (row) /// - `app`: Mutable application state containing menu state and UI rectangles /// - `details_tx`: Channel to request package details when selection changes /// /// Output: /// - `Some(bool)` if the event was handled (consumed by a menu), `None` if not handled. /// The boolean value indicates whether the application should exit (always `false` here). /// /// Details: /// - Import/Export buttons: Import opens `ImportHelp` modal; Export writes install list to timestamped file. /// - Arch status label: Opens status.archlinux.org URL. /// - Sort menu: Toggle button opens/closes sort menu; menu items change sort mode and refresh results. /// - Options menu: Toggle button opens/closes menu; items toggle installed-only mode, open `SystemUpdate`/News, /// or build `OptionalDeps` modal. /// - Config menu: Toggle button opens/closes menu; items open config files in terminal editors. /// - Panels menu: Toggle button opens/closes menu; items toggle Recent/Install panes and keybinds footer. /// - Menu auto-close: Clicking outside any open menu closes it. pub(super) fn handle_menus_mouse( mx: u16, my: u16, app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, ) -> Option<bool> { // Check button clicks first // In News mode, check news button first; otherwise check updates button if matches!(app.app_mode, crate::state::types::AppMode::News) { if point_in_rect(mx, my, app.news_button_rect) { return Some(handle_news_button(app)); } } else if point_in_rect(mx, my, app.updates_button_rect) { return Some(handle_updates_button(app)); } if point_in_rect(mx, my, app.install_import_rect) { return Some(handle_import_button(app)); } if point_in_rect(mx, my, app.install_export_rect) { return Some(handle_export_button(app)); } if point_in_rect(mx, my, app.arch_status_rect) { return Some(handle_arch_status()); } if point_in_rect(mx, my, app.news_age_button_rect) { handle_news_age_toggle(app); return Some(false); } if point_in_rect(mx, my, app.sort_button_rect) { return Some(handle_sort_button(app)); } if point_in_rect(mx, my, app.options_button_rect) { return Some(handle_options_button(app)); } if point_in_rect(mx, my, app.config_button_rect) { return Some(handle_config_button(app)); } if point_in_rect(mx, my, app.panels_button_rect) { return Some(handle_panels_button(app)); } if point_in_rect(mx, my, app.collapsed_menu_button_rect) { return Some(handle_collapsed_menu_button(app)); } // Check menu clicks if menus are open if app.sort_menu_open && point_in_rect(mx, my, app.sort_menu_rect) { return handle_sort_menu_click(mx, my, app, details_tx); } if app.options_menu_open && point_in_rect(mx, my, app.options_menu_rect) { return handle_options_menu_click(mx, my, app, details_tx); } if app.config_menu_open && point_in_rect(mx, my, app.config_menu_rect) { return handle_config_menu_click(mx, my, app); } if app.panels_menu_open && point_in_rect(mx, my, app.panels_menu_rect) { return handle_panels_menu_click(mx, my, app); } if app.collapsed_menu_open && point_in_rect(mx, my, app.collapsed_menu_rect) { return handle_collapsed_menu_click(mx, my, app); } // Click outside any menu closes all menus close_all_menus(app); None } #[cfg(test)] mod tests { use std::collections::HashMap; use super::*; use crate::state::types::AppMode; use crate::util::parse_update_entry; fn seed_news_age_translations(app: &mut crate::state::AppState) { let mut translations = HashMap::new(); translations.insert( "app.results.options_menu.news_age_all".to_string(), "News age: all time".to_string(), ); translations.insert( "app.results.options_menu.news_age_days".to_string(), "News age: {} days".to_string(), ); app.translations = translations.clone(); app.translations_fallback = translations; } /// What: Test that updates parsing correctly extracts old and new versions. /// /// Inputs: /// - Sample update file content with format `"name - old_version -> name - new_version"` /// /// Output: /// - Verifies that `old_version` and `new_version` are correctly parsed and different /// /// Details: /// - Creates a temporary updates file with known content /// - Calls `handle_updates_button` to parse it /// - Verifies that the parsed entries have correct old and new versions #[test] fn test_updates_parsing_extracts_correct_versions() { // Test the parsing logic with various formats
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
true
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/mouse/menu_options.rs
src/events/mouse/menu_options.rs
//! Options menu content handling (optional deps building). use crate::state::AppState; /// What: Check if a tool is installed either as a package or available on PATH. /// /// Inputs: /// - `pkg`: Package name to check /// - `bin`: Binary name to check on PATH /// /// Output: /// - `true` if the tool is installed or available on PATH /// /// Details: /// - Checks both package installation and PATH availability #[allow(clippy::missing_const_for_fn)] fn is_tool_installed(pkg: &str, bin: &str) -> bool { crate::index::is_installed(pkg) || crate::install::command_on_path(bin) } /// What: Create an `OptionalDepRow` with standard fields. /// /// Inputs: /// - `app`: Application state for i18n /// - `category_key`: i18n key for the category /// - `label_suffix`: Suffix to append to category label /// - `package`: Package name /// - `installed`: Whether the tool is installed /// - `note`: Optional note string /// /// Output: /// - An `OptionalDepRow` with the specified fields /// /// Details: /// - Sets `selectable` to `!installed` (only selectable if not installed) fn create_optional_dep_row( app: &AppState, category_key: &str, label_suffix: &str, package: String, installed: bool, note: Option<String>, ) -> crate::state::types::OptionalDepRow { crate::state::types::OptionalDepRow { label: format!("{}: {label_suffix}", crate::i18n::t(app, category_key)), package, installed, selectable: !installed, note, } } /// What: Find the first installed candidate from a list of (binary, package) pairs. /// /// Inputs: /// - `candidates`: Slice of (`binary_name`, `package_name`) tuples /// /// Output: /// - `Some((binary, package))` if an installed candidate is found, `None` otherwise /// /// Details: /// - Checks both PATH and package installation for each candidate fn find_first_installed_candidate<'a>( candidates: &'a [(&'a str, &'a str)], ) -> Option<(&'a str, &'a str)> { for (bin, pkg) in candidates { if is_tool_installed(pkg, bin) { return Some((*bin, *pkg)); } } None } /// What: Check if helix editor is installed (handles hx/helix aliases). /// /// Inputs: /// - `pkg`: Package name (should be "helix") /// - `bin`: Binary name to check /// /// Output: /// - `true` if helix is installed via any alias /// /// Details: /// - Checks both hx and helix binaries for helix package fn is_helix_installed(pkg: &str, bin: &str) -> bool { if pkg == "helix" { is_tool_installed(pkg, bin) || is_tool_installed(pkg, "hx") } else { is_tool_installed(pkg, bin) } } /// What: Check if emacs editor is installed (handles emacs/emacsclient aliases). /// /// Inputs: /// - `pkg`: Package name (should be "emacs") /// - `bin`: Binary name to check /// /// Output: /// - `true` if emacs is installed via any alias /// /// Details: /// - Checks both emacs and emacsclient binaries for emacs package fn is_emacs_installed(pkg: &str, bin: &str) -> bool { if pkg == "emacs" { is_tool_installed(pkg, bin) || is_tool_installed(pkg, "emacsclient") } else { is_tool_installed(pkg, bin) } } /// What: Check if an editor candidate is installed (handles special aliases). /// /// Inputs: /// - `pkg`: Package name /// - `bin`: Binary name /// /// Output: /// - `true` if the editor is installed /// /// Details: /// - Handles helix and emacs aliases specially fn is_editor_installed(pkg: &str, bin: &str) -> bool { if pkg == "helix" { is_helix_installed(pkg, bin) } else if pkg == "emacs" { is_emacs_installed(pkg, bin) } else { is_tool_installed(pkg, bin) } } /// What: Build editor rows for the optional deps modal. /// /// Inputs: /// - `app`: Application state for i18n /// - `rows`: Mutable vector to append rows to /// /// Output: /// - Appends editor rows to the provided vector /// /// Details: /// - Shows first installed editor, or all candidates if none installed /// - Handles helix (hx/helix) and emacs (emacs/emacsclient) aliases fn build_editor_rows(app: &AppState, rows: &mut Vec<crate::state::types::OptionalDepRow>) { let editor_candidates: &[(&str, &str)] = &[ ("nvim", "neovim"), ("vim", "vim"), ("hx", "helix"), ("helix", "helix"), ("emacsclient", "emacs"), ("emacs", "emacs"), ("nano", "nano"), ]; if let Some((bin, pkg)) = find_first_installed_candidate(editor_candidates) { let installed = is_editor_installed(pkg, bin); rows.push(create_optional_dep_row( app, "app.optional_deps.categories.editor", bin, pkg.to_string(), installed, None, )); } else { // Show unique packages (avoid hx+helix duplication) let mut seen = std::collections::HashSet::new(); for (bin, pkg) in editor_candidates { if seen.insert(*pkg) { let installed = is_editor_installed(pkg, bin); rows.push(create_optional_dep_row( app, "app.optional_deps.categories.editor", bin, (*pkg).to_string(), installed, None, )); } } } } /// What: Build terminal rows for the optional deps modal. /// /// Inputs: /// - `app`: Application state for i18n /// - `rows`: Mutable vector to append rows to /// /// Output: /// - Appends terminal rows to the provided vector /// /// Details: /// - Shows first installed terminal, or all candidates if none installed fn build_terminal_rows(app: &AppState, rows: &mut Vec<crate::state::types::OptionalDepRow>) { let term_candidates: &[(&str, &str)] = &[ ("alacritty", "alacritty"), ("ghostty", "ghostty"), ("kitty", "kitty"), ("xterm", "xterm"), ("gnome-terminal", "gnome-terminal"), ("konsole", "konsole"), ("xfce4-terminal", "xfce4-terminal"), ("tilix", "tilix"), ("mate-terminal", "mate-terminal"), ]; if let Some((bin, pkg)) = find_first_installed_candidate(term_candidates) { let installed = is_tool_installed(pkg, bin); rows.push(create_optional_dep_row( app, "app.optional_deps.categories.terminal", bin, pkg.to_string(), installed, None, )); } else { for (bin, pkg) in term_candidates { let installed = is_tool_installed(pkg, bin); rows.push(create_optional_dep_row( app, "app.optional_deps.categories.terminal", bin, (*pkg).to_string(), installed, None, )); } } } /// What: Check if KDE session is active. /// /// Inputs: /// - None (reads environment variables) /// /// Output: /// - `true` if KDE session is detected /// /// Details: /// - Checks `KDE_FULL_SESSION`, `XDG_CURRENT_DESKTOP`, and `klipper` command fn is_kde_session() -> bool { std::env::var("KDE_FULL_SESSION").is_ok() || std::env::var("XDG_CURRENT_DESKTOP").ok().is_some_and(|v| { let u = v.to_uppercase(); u.contains("KDE") || u.contains("PLASMA") }) || crate::install::command_on_path("klipper") } /// What: Build clipboard rows for the optional deps modal. /// /// Inputs: /// - `app`: Application state for i18n /// - `rows`: Mutable vector to append rows to /// /// Output: /// - Appends clipboard rows to the provided vector /// /// Details: /// - Prefers Klipper for KDE, then wl-clipboard for Wayland, else xclip for X11 fn build_clipboard_rows(app: &AppState, rows: &mut Vec<crate::state::types::OptionalDepRow>) { if is_kde_session() { let pkg = "plasma-workspace"; let installed = is_tool_installed(pkg, "klipper"); rows.push(create_optional_dep_row( app, "app.optional_deps.categories.clipboard", "Klipper (KDE)", pkg.to_string(), installed, Some("KDE Plasma".to_string()), )); } else if std::env::var("WAYLAND_DISPLAY").is_ok() { let pkg = "wl-clipboard"; let installed = is_tool_installed(pkg, "wl-copy"); rows.push(create_optional_dep_row( app, "app.optional_deps.categories.clipboard", "wl-clipboard", pkg.to_string(), installed, Some("Wayland".to_string()), )); } else { let pkg = "xclip"; let installed = is_tool_installed(pkg, "xclip"); rows.push(create_optional_dep_row( app, "app.optional_deps.categories.clipboard", "xclip", pkg.to_string(), installed, Some("X11".to_string()), )); } } /// What: Build mirror manager rows for the optional deps modal. /// /// Inputs: /// - `rows`: Mutable vector to append rows to /// /// Output: /// - Appends mirror manager rows to the provided vector /// /// Details: /// - Detects Manjaro (pacman-mirrors), Artix (rate-mirrors), or default (reflector) fn build_mirror_rows(rows: &mut Vec<crate::state::types::OptionalDepRow>) { let os_release = std::fs::read_to_string("/etc/os-release").unwrap_or_default(); let manjaro = os_release.contains("Manjaro"); let artix = os_release.contains("Artix"); if manjaro { let pkg = "pacman-mirrors"; let installed = crate::index::is_installed(pkg); rows.push(crate::state::types::OptionalDepRow { label: "Mirrors: pacman-mirrors".to_string(), package: pkg.to_string(), installed, selectable: !installed, note: Some("Manjaro".to_string()), }); } else if artix { let pkg = "rate-mirrors"; let installed = is_tool_installed(pkg, "rate-mirrors"); rows.push(crate::state::types::OptionalDepRow { label: "Mirrors: rate mirrors".to_string(), package: pkg.to_string(), installed, selectable: !installed, note: Some("Artix".to_string()), }); } else { let pkg = "reflector"; let installed = crate::index::is_installed(pkg); rows.push(crate::state::types::OptionalDepRow { label: "Mirrors: reflector".to_string(), package: pkg.to_string(), installed, selectable: !installed, note: None, }); } } /// What: Build AUR helper rows for the optional deps modal. /// /// Inputs: /// - `app`: Application state for i18n /// - `rows`: Mutable vector to append rows to /// /// Output: /// - Appends AUR helper rows to the provided vector /// /// Details: /// - Shows installed paru/yay if present, or both if neither installed fn build_aur_helper_rows(app: &AppState, rows: &mut Vec<crate::state::types::OptionalDepRow>) { let paru_inst = is_tool_installed("paru", "paru"); let yay_inst = is_tool_installed("yay", "yay"); if paru_inst { rows.push(create_optional_dep_row( app, "app.optional_deps.categories.aur_helper", "paru", "paru".to_string(), true, None, )); } else if yay_inst { rows.push(create_optional_dep_row( app, "app.optional_deps.categories.aur_helper", "yay", "yay".to_string(), true, None, )); } else { let note = Some("Install via git clone + makepkg -si".to_string()); rows.push(create_optional_dep_row( app, "app.optional_deps.categories.aur_helper", "paru", "paru".to_string(), false, note.clone(), )); rows.push(create_optional_dep_row( app, "app.optional_deps.categories.aur_helper", "yay", "yay".to_string(), false, note, )); } } /// What: Build security scanner rows for the optional deps modal. /// /// Inputs: /// - `app`: Application state for i18n /// - `rows`: Mutable vector to append rows to /// /// Output: /// - Appends security scanner rows to the provided vector /// /// Details: /// - Includes `ClamAV`, `Trivy`, `Semgrep`, `ShellCheck`, `VirusTotal API`, and `aur-sleuth` fn build_security_scanner_rows( app: &AppState, rows: &mut Vec<crate::state::types::OptionalDepRow>, ) { // ClamAV let installed = is_tool_installed("clamav", "clamscan"); rows.push(create_optional_dep_row( app, "app.optional_deps.categories.security", "clamav", "clamav".to_string(), installed, None, )); // Trivy let installed = is_tool_installed("trivy", "trivy"); rows.push(create_optional_dep_row( app, "app.optional_deps.categories.security", "trivy", "trivy".to_string(), installed, None, )); // Semgrep let installed = is_tool_installed("semgrep-bin", "semgrep"); rows.push(create_optional_dep_row( app, "app.optional_deps.categories.security", "semgrep-bin", "semgrep-bin".to_string(), installed, Some("AUR".to_string()), )); // ShellCheck let installed = is_tool_installed("shellcheck", "shellcheck"); rows.push(create_optional_dep_row( app, "app.optional_deps.categories.security", "shellcheck", "shellcheck".to_string(), installed, None, )); // VirusTotal API setup let vt_key_present = !crate::theme::settings().virustotal_api_key.is_empty(); rows.push(create_optional_dep_row( app, "app.optional_deps.categories.security", "VirusTotal API", "virustotal-setup".to_string(), vt_key_present, Some("Setup".to_string()), )); // aur-sleuth setup let sleuth_installed = { let onpath = crate::install::command_on_path("aur-sleuth"); let home = std::env::var("HOME").ok(); let user_local = home.as_deref().is_some_and(|h| { std::path::Path::new(h) .join(".local/bin/aur-sleuth") .exists() }); let system_local = std::path::Path::new("/usr/local/bin/aur-sleuth").exists(); onpath || user_local || system_local }; rows.push(create_optional_dep_row( app, "app.optional_deps.categories.security", "aur-sleuth", "aur-sleuth-setup".to_string(), sleuth_installed, Some("Setup".to_string()), )); } /// What: Build downgrade package row for the optional deps modal. /// /// Inputs: /// - `app`: Application state for i18n /// - `rows`: Mutable vector to append rows to /// /// Output: /// - Appends downgrade row to the provided vector /// /// Details: /// - Checks if the downgrade package is installed and adds a row for it fn build_downgrade_rows(app: &AppState, rows: &mut Vec<crate::state::types::OptionalDepRow>) { let installed = is_tool_installed("downgrade", "downgrade"); rows.push(create_optional_dep_row( app, "app.optional_deps.categories.downgrade", "downgrade", "downgrade".to_string(), installed, None, )); } /// Build optional dependencies rows for the `OptionalDeps` modal. /// /// What: Scan the system for installed editors, terminals, clipboard tools, mirror managers, /// AUR helpers, and security scanners, then build a list of `OptionalDepRow` items for display. /// /// Inputs: /// - `app`: Application state (used for i18n translations) /// /// Output: /// - Vector of `OptionalDepRow` items ready to be displayed in the `OptionalDeps` modal. /// /// Details: /// - Editor: Shows the first installed editor found (`nvim`, `vim`, `hx`/`helix`, `emacsclient`/`emacs`, `nano`), /// or all candidates if none installed. Handles helix (`hx`/`helix`) and emacs (`emacs`/`emacsclient`) aliases. /// - Terminal: Shows the first installed terminal found, or all candidates if none installed. /// - Clipboard: Detects `KDE` (`Klipper`), `Wayland` (`wl-clipboard`), or `X11` (`xclip`) and shows appropriate tool. /// - Mirrors: Detects `Manjaro` (`pacman-mirrors`), `Artix` (`rate-mirrors`), or default (`reflector`). /// - AUR helper: Shows installed `paru`/`yay` if present, or both if neither installed. /// - Security scanners: Always includes `ClamAV`, `Trivy`, `Semgrep`, `ShellCheck`, `VirusTotal API` setup, /// and `aur-sleuth` setup. Marks installed items as non-selectable. /// - Downgrade: Includes the `downgrade` package for package downgrade functionality. pub fn build_optional_deps_rows(app: &AppState) -> Vec<crate::state::types::OptionalDepRow> { let mut rows: Vec<crate::state::types::OptionalDepRow> = Vec::new(); build_editor_rows(app, &mut rows); build_terminal_rows(app, &mut rows); build_clipboard_rows(app, &mut rows); build_mirror_rows(&mut rows); build_aur_helper_rows(app, &mut rows); build_security_scanner_rows(app, &mut rows); build_downgrade_rows(app, &mut rows); rows }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/mouse/filters.rs
src/events/mouse/filters.rs
//! Filter toggle mouse event handling. use crate::state::AppState; /// Check if a point is within a rectangle. /// /// What: Determines if mouse coordinates fall within the bounds of a rectangle. /// /// Inputs: /// - `mx`: Mouse X coordinate (column) /// - `my`: Mouse Y coordinate (row) /// - `rect`: Optional rectangle (x, y, width, height) /// /// Output: /// - `true` if the point is within the rectangle, `false` otherwise. /// /// Details: /// - Returns `false` if `rect` is `None`. /// - Uses inclusive start and exclusive end bounds for width and height. 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 } } /// Toggle a simple boolean filter if the mouse click is within its rectangle. /// /// What: Checks if mouse coordinates are within a filter's rectangle and toggles the filter if so. /// /// Inputs: /// - `mx`: Mouse X coordinate (column) /// - `my`: Mouse Y coordinate (row) /// - `rect`: Optional rectangle for the filter toggle area /// - `toggle_fn`: Closure that toggles the filter state /// - `app`: Mutable application state for applying filters and sort /// /// Output: /// - `true` if the filter was toggled, `false` otherwise. /// /// Details: /// - If the click is within the rectangle, calls the toggle function and applies filters/sort. fn try_toggle_simple_filter<F>( mx: u16, my: u16, rect: Option<(u16, u16, u16, u16)>, toggle_fn: F, app: &mut AppState, ) -> bool where F: FnOnce(&mut AppState), { if is_point_in_rect(mx, my, rect) { toggle_fn(app); crate::logic::apply_filters_and_sort_preserve_selection(app); true } else { false } } /// Toggle all Artix repository filters together. /// /// What: Sets all individual Artix repository filters to the same state (all on or all off). /// /// Inputs: /// - `app`: Mutable application state containing Artix filter states /// /// Output: None (modifies state in place) /// /// Details: /// - Checks if all individual Artix filters are currently on. /// - If all are on, turns all off; otherwise turns all on. /// - Updates the main Artix filter state to match. /// - Applies filters and sort after toggling. fn toggle_all_artix_filters(app: &mut AppState) { let all_on = app.results_filter_show_artix_omniverse && app.results_filter_show_artix_universe && app.results_filter_show_artix_lib32 && app.results_filter_show_artix_galaxy && app.results_filter_show_artix_world && app.results_filter_show_artix_system; let new_state = !all_on; app.results_filter_show_artix_omniverse = new_state; app.results_filter_show_artix_universe = new_state; app.results_filter_show_artix_lib32 = new_state; app.results_filter_show_artix_galaxy = new_state; app.results_filter_show_artix_world = new_state; app.results_filter_show_artix_system = new_state; app.results_filter_show_artix = new_state; crate::logic::apply_filters_and_sort_preserve_selection(app); } /// Check if Artix-specific filters are hidden (dropdown mode). /// /// What: Determines if individual Artix repository filter rectangles are all hidden. /// /// Inputs: /// - `app`: Application state containing Artix filter rectangles /// /// Output: /// - `true` if all individual Artix filter rectangles are `None`, `false` otherwise. /// /// Details: /// - Returns `true` when in dropdown mode (all individual filters hidden). const fn has_hidden_artix_filters(app: &AppState) -> bool { app.results_filter_artix_omniverse_rect.is_none() && app.results_filter_artix_universe_rect.is_none() && app.results_filter_artix_lib32_rect.is_none() && app.results_filter_artix_galaxy_rect.is_none() && app.results_filter_artix_world_rect.is_none() && app.results_filter_artix_system_rect.is_none() } /// Handle mouse click on the main Artix filter toggle. /// /// What: Processes clicks on the main Artix filter button with special handling for dropdown mode. /// /// Inputs: /// - `mx`: Mouse X coordinate (column) /// - `my`: Mouse Y coordinate (row) /// - `app`: Mutable application state /// /// Output: /// - `true` if the click was handled, `false` otherwise. /// /// Details: /// - In dropdown mode (hidden filters), toggles the dropdown menu. /// - Otherwise, toggles all Artix filters together. fn handle_artix_main_filter_click(mx: u16, my: u16, app: &mut AppState) -> bool { if !is_point_in_rect(mx, my, app.results_filter_artix_rect) { return false; } if has_hidden_artix_filters(app) { app.artix_filter_menu_open = !app.artix_filter_menu_open; } else { toggle_all_artix_filters(app); } true } /// Update the main Artix filter state based on individual filter states. /// /// What: Sets the main Artix filter to true if any individual Artix filter is enabled. /// /// Inputs: /// - `app`: Mutable application state containing Artix filter states /// /// Output: None (modifies state in place) /// /// Details: /// - The main Artix filter is enabled if at least one individual Artix filter is enabled. #[allow(clippy::missing_const_for_fn)] fn update_main_artix_filter_state(app: &mut AppState) { app.results_filter_show_artix = app.results_filter_show_artix_omniverse || app.results_filter_show_artix_universe || app.results_filter_show_artix_lib32 || app.results_filter_show_artix_galaxy || app.results_filter_show_artix_world || app.results_filter_show_artix_system; } /// Handle mouse clicks inside the Artix filter dropdown menu. /// /// What: Processes clicks on menu items to toggle individual Artix filters or all at once. /// /// Inputs: /// - `mx`: Mouse X coordinate (column) /// - `my`: Mouse Y coordinate (row) /// - `app`: Mutable application state /// /// Output: /// - `true` if the click was handled, `false` otherwise. /// /// Details: /// - Row 0 toggles all Artix filters together. /// - Rows 1-6 toggle individual Artix repository filters. /// - Updates the main Artix filter state after any toggle. fn handle_artix_dropdown_click(mx: u16, my: u16, app: &mut AppState) -> bool { if !app.artix_filter_menu_open { return false; } let Some((x, y, w, h)) = app.artix_filter_menu_rect else { return false; }; if !is_point_in_rect(mx, my, Some((x, y, w, h))) { return false; } let row = my.saturating_sub(y) as usize; match row { 0 => toggle_all_artix_filters(app), 1 => { app.results_filter_show_artix_omniverse = !app.results_filter_show_artix_omniverse; crate::logic::apply_filters_and_sort_preserve_selection(app); } 2 => { app.results_filter_show_artix_universe = !app.results_filter_show_artix_universe; crate::logic::apply_filters_and_sort_preserve_selection(app); } 3 => { app.results_filter_show_artix_lib32 = !app.results_filter_show_artix_lib32; crate::logic::apply_filters_and_sort_preserve_selection(app); } 4 => { app.results_filter_show_artix_galaxy = !app.results_filter_show_artix_galaxy; crate::logic::apply_filters_and_sort_preserve_selection(app); } 5 => { app.results_filter_show_artix_world = !app.results_filter_show_artix_world; crate::logic::apply_filters_and_sort_preserve_selection(app); } 6 => { app.results_filter_show_artix_system = !app.results_filter_show_artix_system; crate::logic::apply_filters_and_sort_preserve_selection(app); } _ => return false, } update_main_artix_filter_state(app); true } /// Handle mouse events for filter toggles. /// /// What: Process mouse clicks on filter toggle labels in the Results title bar to enable/disable /// repository filters (`AUR`, `Core`, `Extra`, `Multilib`, `EOS`, `CachyOS`, `Artix`, `Manjaro`). /// /// Inputs: /// - `mx`: Mouse X coordinate (column) /// - `my`: Mouse Y coordinate (row) /// - `app`: Mutable application state containing filter state and UI rectangles /// /// Output: /// - `Some(bool)` if the event was handled (consumed by a filter toggle), `None` if not handled. /// The boolean value indicates whether the application should exit (always `false` here). /// /// Details: /// - Individual filters: Clicking a filter label toggles that filter and applies filters/sort. /// - Artix main filter: When individual Artix repo filters are visible, toggles all Artix filters /// together (all on -> all off, otherwise all on). When hidden (dropdown mode), toggles the dropdown menu. /// - Artix dropdown menu: Handles clicks on menu items to toggle individual Artix repo filters or all at once. /// Updates the main Artix filter state based on individual filter states. pub(super) fn handle_filters_mouse(mx: u16, my: u16, app: &mut AppState) -> Option<bool> { if matches!(app.app_mode, crate::state::types::AppMode::News) { let mut handled = false; if is_point_in_rect(mx, my, app.news_filter_arch_rect) { app.news_filter_show_arch_news = !app.news_filter_show_arch_news; handled = true; } else if is_point_in_rect(mx, my, app.news_filter_advisory_rect) { match ( app.news_filter_show_advisories, app.news_filter_installed_only, ) { (true, false) => { app.news_filter_show_advisories = true; app.news_filter_installed_only = true; } (true, true) => { app.news_filter_show_advisories = false; app.news_filter_installed_only = false; } (false, _) => { app.news_filter_show_advisories = true; app.news_filter_installed_only = false; } } handled = true; } else if is_point_in_rect(mx, my, app.news_filter_updates_rect) { app.news_filter_show_pkg_updates = !app.news_filter_show_pkg_updates; handled = true; } else if is_point_in_rect(mx, my, app.news_filter_aur_updates_rect) { app.news_filter_show_aur_updates = !app.news_filter_show_aur_updates; handled = true; } else if is_point_in_rect(mx, my, app.news_filter_aur_comments_rect) { app.news_filter_show_aur_comments = !app.news_filter_show_aur_comments; handled = true; } else if is_point_in_rect(mx, my, app.news_filter_read_rect) { app.news_filter_read_status = match app.news_filter_read_status { crate::state::types::NewsReadFilter::All => { crate::state::types::NewsReadFilter::Unread } crate::state::types::NewsReadFilter::Unread => { crate::state::types::NewsReadFilter::Read } crate::state::types::NewsReadFilter::Read => { crate::state::types::NewsReadFilter::All } }; handled = true; } if handled { crate::theme::save_news_filter_show_arch_news(app.news_filter_show_arch_news); crate::theme::save_news_filter_show_advisories(app.news_filter_show_advisories); crate::theme::save_news_filter_show_pkg_updates(app.news_filter_show_pkg_updates); crate::theme::save_news_filter_show_aur_updates(app.news_filter_show_aur_updates); crate::theme::save_news_filter_show_aur_comments(app.news_filter_show_aur_comments); crate::theme::save_news_filter_installed_only(app.news_filter_installed_only); app.refresh_news_results(); return Some(false); } return None; } // Handle Artix dropdown menu first (higher priority) if handle_artix_dropdown_click(mx, my, app) { return Some(false); } // Handle main Artix filter if handle_artix_main_filter_click(mx, my, app) { return Some(false); } // Handle simple filters if handle_simple_filter_toggles(mx, my, app) { return Some(false); } None } /// What: Try toggling all simple filters in sequence. /// /// Inputs: /// - `mx`: Mouse X coordinate (column) /// - `my`: Mouse Y coordinate (row) /// - `app`: Mutable application state /// /// Output: /// - `true` if any filter was toggled, `false` otherwise. /// /// Details: /// - Tries each filter in order and returns immediately if one is toggled. fn handle_simple_filter_toggles(mx: u16, my: u16, app: &mut AppState) -> bool { try_toggle_simple_filter( mx, my, app.results_filter_aur_rect, |a| a.results_filter_show_aur = !a.results_filter_show_aur, app, ) || try_toggle_simple_filter( mx, my, app.results_filter_core_rect, |a| a.results_filter_show_core = !a.results_filter_show_core, app, ) || try_toggle_simple_filter( mx, my, app.results_filter_extra_rect, |a| a.results_filter_show_extra = !a.results_filter_show_extra, app, ) || try_toggle_simple_filter( mx, my, app.results_filter_multilib_rect, |a| a.results_filter_show_multilib = !a.results_filter_show_multilib, app, ) || try_toggle_simple_filter( mx, my, app.results_filter_eos_rect, |a| a.results_filter_show_eos = !a.results_filter_show_eos, app, ) || try_toggle_simple_filter( mx, my, app.results_filter_cachyos_rect, |a| a.results_filter_show_cachyos = !a.results_filter_show_cachyos, app, ) || try_toggle_simple_filter( mx, my, app.results_filter_artix_omniverse_rect, |a| a.results_filter_show_artix_omniverse = !a.results_filter_show_artix_omniverse, app, ) || try_toggle_simple_filter( mx, my, app.results_filter_artix_universe_rect, |a| a.results_filter_show_artix_universe = !a.results_filter_show_artix_universe, app, ) || try_toggle_simple_filter( mx, my, app.results_filter_artix_lib32_rect, |a| a.results_filter_show_artix_lib32 = !a.results_filter_show_artix_lib32, app, ) || try_toggle_simple_filter( mx, my, app.results_filter_artix_galaxy_rect, |a| a.results_filter_show_artix_galaxy = !a.results_filter_show_artix_galaxy, app, ) || try_toggle_simple_filter( mx, my, app.results_filter_artix_world_rect, |a| a.results_filter_show_artix_world = !a.results_filter_show_artix_world, app, ) || try_toggle_simple_filter( mx, my, app.results_filter_artix_system_rect, |a| a.results_filter_show_artix_system = !a.results_filter_show_artix_system, app, ) || try_toggle_simple_filter( mx, my, app.results_filter_manjaro_rect, |a| a.results_filter_show_manjaro = !a.results_filter_show_manjaro, app, ) } #[cfg(test)] mod tests { use super::*; use crate::state::types::{NewsFeedSource, NewsReadFilter, NewsSortMode}; fn sample_news_items() -> Vec<crate::state::types::NewsFeedItem> { vec![ crate::state::types::NewsFeedItem { id: "arch-news-1".to_string(), date: "2025-01-01".to_string(), title: "Arch item".to_string(), summary: None, url: None, source: NewsFeedSource::ArchNews, severity: None, packages: Vec::new(), }, crate::state::types::NewsFeedItem { id: "adv-1".to_string(), date: "2025-01-02".to_string(), title: "Advisory item".to_string(), summary: None, url: None, source: NewsFeedSource::SecurityAdvisory, severity: None, packages: vec!["example".to_string()], }, ] } #[test] fn news_filter_click_toggles_flags_and_refreshes() { let mut app = crate::state::AppState { app_mode: crate::state::types::AppMode::News, news_items: sample_news_items(), news_filter_show_arch_news: true, news_filter_show_advisories: true, news_filter_installed_only: false, news_sort_mode: NewsSortMode::DateDesc, news_filter_arch_rect: Some((0, 0, 5, 1)), ..crate::state::AppState::default() }; app.refresh_news_results(); let handled = handle_filters_mouse(0, 0, &mut app); assert_eq!(handled, Some(false)); assert!(!app.news_filter_show_arch_news); assert!(app.news_results.len() <= app.news_items.len()); assert!( app.news_results .iter() .all(|i| matches!(i.source, NewsFeedSource::SecurityAdvisory)) ); } #[test] fn news_read_filter_click_cycles_status() { let mut app = crate::state::AppState { app_mode: crate::state::types::AppMode::News, news_items: sample_news_items(), news_filter_read_status: NewsReadFilter::All, news_filter_read_rect: Some((0, 0, 6, 1)), ..crate::state::AppState::default() }; app.refresh_news_results(); let handled1 = handle_filters_mouse(0, 0, &mut app); assert_eq!(handled1, Some(false)); assert_eq!(app.news_filter_read_status, NewsReadFilter::Unread); let handled2 = handle_filters_mouse(0, 0, &mut app); assert_eq!(handled2, Some(false)); assert_eq!(app.news_filter_read_status, NewsReadFilter::Read); let handled3 = handle_filters_mouse(0, 0, &mut app); assert_eq!(handled3, Some(false)); assert_eq!(app.news_filter_read_status, NewsReadFilter::All); } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/mouse/tests.rs
src/events/mouse/tests.rs
//! Tests for mouse event handling. use crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind}; use tokio::sync::mpsc; use super::handle_mouse_event; use crate::state::{AppState, PackageItem, QueryInput}; /// What: Provide a fresh `AppState` tailored for mouse-event tests without repeated boilerplate. /// /// Inputs: /// - None (relies on `Default::default()` for deterministic initial state). /// /// Output: /// - New `AppState` ready for mutation inside individual mouse-event scenarios. /// /// Details: /// - Keeps mouse tests concise by centralizing the default setup in a single helper. /// - Sets `PACSEA_TEST_HEADLESS` to prevent mouse escape sequences in test output. fn new_app() -> AppState { unsafe { std::env::set_var("PACSEA_TEST_HEADLESS", "1"); } AppState::default() } #[test] /// What: Clicking the PKGBUILD toggle should open the viewer and request content. /// /// Inputs: /// - `app`: State seeded with one selected result and `pkgb_button_rect` coordinates. /// - `ev`: Left-click positioned inside the PKGBUILD button rectangle. /// /// Output: /// - Returns `false` while mutating `app` so `pkgb_visible` is `true` and the selection is sent on `pkgb_tx`. /// /// Details: /// - Captures the message from `pkgb_tx` to ensure the handler enqueues a fetch when opening the pane. fn click_pkgb_toggle_opens() { let mut app = new_app(); app.results = vec![crate::state::PackageItem { name: "rg".into(), version: "1".into(), description: String::new(), source: crate::state::Source::Aur, popularity: None, out_of_date: None, orphaned: false, }]; app.selected = 0; app.pkgb_button_rect = Some((10, 10, 5, 1)); let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let (pkgb_tx, mut pkgb_rx) = mpsc::unbounded_channel::<PackageItem>(); let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>(); let (qtx, _qrx) = mpsc::unbounded_channel::<QueryInput>(); let ev = MouseEvent { kind: MouseEventKind::Down(MouseButton::Left), column: 11, row: 10, modifiers: KeyModifiers::empty(), }; let _ = handle_mouse_event(ev, &mut app, &dtx, &ptx, &atx, &pkgb_tx, &comments_tx, &qtx); assert!(app.pkgb_visible); assert!(pkgb_rx.try_recv().ok().is_some()); } #[test] /// What: Clicking the toggle while the PKGBUILD viewer is open should close it and reset cached state. /// /// Inputs: /// - `app`: State with viewer visible, scroll offset/non-empty text, and `pkgb_button_rect` populated. /// - `ev`: Left-click inside the PKGBUILD toggle rectangle. /// /// Output: /// - Returns `false` after mutating `app` so the viewer is hidden, text cleared, scroll set to zero, and rect unset. /// /// Details: /// - Ensures the handler cleans up PKGBUILD state to avoid stale scroll positions on the next open. fn click_pkgb_toggle_closes_and_resets() { let mut app = new_app(); app.results = vec![crate::state::PackageItem { name: "rg".into(), version: "1".into(), description: String::new(), source: crate::state::Source::Aur, popularity: None, out_of_date: None, orphaned: false, }]; app.selected = 0; app.pkgb_button_rect = Some((10, 10, 5, 1)); // Pre-set PKGBUILD viewer as open with state to be reset app.pkgb_visible = true; app.pkgb_text = Some("dummy".into()); app.pkgb_scroll = 7; app.pkgb_rect = Some((50, 50, 20, 5)); let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let (pkgb_tx, _pkgb_rx) = mpsc::unbounded_channel::<PackageItem>(); let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>(); let (qtx, _qrx) = mpsc::unbounded_channel::<QueryInput>(); // Click inside the toggle area to hide let ev = MouseEvent { kind: MouseEventKind::Down(MouseButton::Left), column: 11, row: 10, modifiers: KeyModifiers::empty(), }; let _ = handle_mouse_event(ev, &mut app, &dtx, &ptx, &atx, &pkgb_tx, &comments_tx, &qtx); assert!(!app.pkgb_visible); assert!(app.pkgb_text.is_none()); assert_eq!(app.pkgb_scroll, 0); assert!(app.pkgb_rect.is_none()); } #[test] /// What: Clicking an AUR filter toggle should invert its state and apply filters. /// /// Inputs: /// - `app`: State with `results_filter_show_aur` initially `false` and `results_filter_aur_rect` set. /// - `ev`: Left-click positioned inside the AUR filter rectangle. /// /// Output: /// - Returns `false` while mutating `app` so `results_filter_show_aur` becomes `true`. /// /// Details: /// - Verifies that filter toggles work correctly and trigger filter application. fn click_aur_filter_toggles() { let mut app = new_app(); app.results_filter_show_aur = false; app.results_filter_aur_rect = Some((5, 2, 10, 1)); let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let (pkgb_tx, _pkgb_rx) = mpsc::unbounded_channel::<PackageItem>(); let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>(); let (qtx, _qrx) = mpsc::unbounded_channel::<QueryInput>(); let ev = MouseEvent { kind: MouseEventKind::Down(MouseButton::Left), column: 7, row: 2, modifiers: KeyModifiers::empty(), }; let _ = handle_mouse_event(ev, &mut app, &dtx, &ptx, &atx, &pkgb_tx, &comments_tx, &qtx); assert!(app.results_filter_show_aur); } #[test] /// What: Clicking the Artix filter when all individual filters are on should turn all off. /// /// Inputs: /// - `app`: State with all Artix repo filters enabled and individual filter rects visible. /// - `ev`: Left-click positioned inside the main Artix filter rectangle. /// /// Output: /// - Returns `false` while mutating `app` so all Artix filters become `false`. /// /// Details: /// - Tests the "all on -> all off" toggle behavior for Artix filters. fn click_artix_filter_all_on_turns_all_off() { let mut app = new_app(); app.results_filter_show_artix_omniverse = true; app.results_filter_show_artix_universe = true; app.results_filter_show_artix_lib32 = true; app.results_filter_show_artix_galaxy = true; app.results_filter_show_artix_world = true; app.results_filter_show_artix_system = true; app.results_filter_show_artix = true; // Set individual rects to indicate they're visible (not in dropdown mode) app.results_filter_artix_omniverse_rect = Some((10, 2, 5, 1)); app.results_filter_artix_rect = Some((5, 2, 8, 1)); let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let (pkgb_tx, _pkgb_rx) = mpsc::unbounded_channel::<PackageItem>(); let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>(); let (qtx, _qrx) = mpsc::unbounded_channel::<QueryInput>(); let ev = MouseEvent { kind: MouseEventKind::Down(MouseButton::Left), column: 7, row: 2, modifiers: KeyModifiers::empty(), }; let _ = handle_mouse_event(ev, &mut app, &dtx, &ptx, &atx, &pkgb_tx, &comments_tx, &qtx); assert!(!app.results_filter_show_artix_omniverse); assert!(!app.results_filter_show_artix_universe); assert!(!app.results_filter_show_artix_lib32); assert!(!app.results_filter_show_artix_galaxy); assert!(!app.results_filter_show_artix_world); assert!(!app.results_filter_show_artix_system); assert!(!app.results_filter_show_artix); } #[test] /// What: Clicking the Artix filter when some filters are off should turn all on. /// /// Inputs: /// - `app`: State with some Artix repo filters disabled and individual filter rects visible. /// - `ev`: Left-click positioned inside the main Artix filter rectangle. /// /// Output: /// - Returns `false` while mutating `app` so all Artix filters become `true`. /// /// Details: /// - Tests the "some off -> all on" toggle behavior for Artix filters. fn click_artix_filter_some_off_turns_all_on() { let mut app = new_app(); app.results_filter_show_artix_omniverse = true; app.results_filter_show_artix_universe = false; // One is off app.results_filter_show_artix_lib32 = true; app.results_filter_show_artix_galaxy = true; app.results_filter_show_artix_world = true; app.results_filter_show_artix_system = true; app.results_filter_show_artix = true; // Set individual rects to indicate they're visible (not in dropdown mode) app.results_filter_artix_omniverse_rect = Some((10, 2, 5, 1)); app.results_filter_artix_rect = Some((5, 2, 8, 1)); let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let (pkgb_tx, _pkgb_rx) = mpsc::unbounded_channel::<PackageItem>(); let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>(); let (qtx, _qrx) = mpsc::unbounded_channel::<QueryInput>(); let ev = MouseEvent { kind: MouseEventKind::Down(MouseButton::Left), column: 7, row: 2, modifiers: KeyModifiers::empty(), }; let _ = handle_mouse_event(ev, &mut app, &dtx, &ptx, &atx, &pkgb_tx, &comments_tx, &qtx); assert!(app.results_filter_show_artix_omniverse); assert!(app.results_filter_show_artix_universe); assert!(app.results_filter_show_artix_lib32); assert!(app.results_filter_show_artix_galaxy); assert!(app.results_filter_show_artix_world); assert!(app.results_filter_show_artix_system); assert!(app.results_filter_show_artix); } #[test] /// What: Clicking the Artix filter when in dropdown mode should toggle the dropdown menu. /// /// Inputs: /// - `app`: State with individual Artix filter rects hidden (dropdown mode) and menu closed. /// - `ev`: Left-click positioned inside the main Artix filter rectangle. /// /// Output: /// - Returns `false` while mutating `app` so `artix_filter_menu_open` becomes `true`. /// /// Details: /// - Tests that clicking the main Artix filter toggles the dropdown when individual filters are hidden. fn click_artix_filter_toggles_dropdown() { let mut app = new_app(); app.artix_filter_menu_open = false; app.results_filter_artix_rect = Some((5, 2, 8, 1)); // Individual rects are None, indicating dropdown mode app.results_filter_artix_omniverse_rect = None; app.results_filter_artix_universe_rect = None; let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let (pkgb_tx, _pkgb_rx) = mpsc::unbounded_channel::<PackageItem>(); let (comments_tx, _comments_rx) = mpsc::unbounded_channel::<String>(); let (qtx, _qrx) = mpsc::unbounded_channel::<QueryInput>(); let ev = MouseEvent { kind: MouseEventKind::Down(MouseButton::Left), column: 7, row: 2, modifiers: KeyModifiers::empty(), }; let _ = handle_mouse_event(ev, &mut app, &dtx, &ptx, &atx, &pkgb_tx, &comments_tx, &qtx); assert!(app.artix_filter_menu_open); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/mouse/mod.rs
src/events/mouse/mod.rs
//! Mouse event handling for Pacsea's TUI. //! //! This module delegates mouse event handling to specialized submodules: //! - `modals`: Modal interactions (Help, `VirusTotalSetup`, `Preflight`, News) //! - `details`: Details pane interactions (URL, PKGBUILD buttons, scroll) //! - `menus`: Menu interactions (sort, options, config, panels, import/export) //! - `filters`: Filter toggle interactions //! - `panes`: Pane interactions (Results, Recent, Install/Remove/Downgrade, PKGBUILD viewer) use crossterm::event::{KeyModifiers, MouseButton, MouseEvent, MouseEventKind}; use tokio::sync::mpsc; use crate::state::{AppState, PackageItem, QueryInput}; mod details; mod filters; pub mod menu_options; pub mod menus; mod modals; mod panes; #[cfg(test)] mod tests; /// Handle a single mouse event and update the [`AppState`]. /// /// Returns `true` to request application exit (never used here), `false` otherwise. /// /// Behavior summary: /// - Clickable URL in the details pane with Ctrl+Shift+LeftClick (opens via `xdg-open`). /// - Clickable "Show/Hide PKGBUILD" action in the details content. /// - Clickable "Copy PKGBUILD" button in the PKGBUILD title (copies to clipboard). /// - Clickable Sort button and filter toggles in the Results title. /// - Click-to-select in Results; mouse wheel scroll moves selection in Results/Recent/Install. /// - Mouse wheel scroll within the PKGBUILD viewer scrolls the content. /// /// What: Handle a single mouse event and update application state and UI accordingly. /// /// Inputs: /// - `m`: Mouse event including position, button, and modifiers /// - `app`: Mutable application state (rects, focus, lists, details) /// - `details_tx`: Channel to request package details when selection changes /// - `preview_tx`: Channel to request preview details for Recent pane interactions /// - `_add_tx`: Channel for adding items (used by Import button handler) /// - `pkgb_tx`: Channel to request PKGBUILD content for the current selection /// - `query_tx`: Channel to send search queries (for fuzzy toggle) /// /// Output: /// - `true` to request application exit (never used here); otherwise `false`. /// /// Details: /// - Modal-first: When Help or News is open, clicks/scroll are handled within modal bounds /// (close on outside click), consuming the event. /// - Details area: Ctrl+Shift+LeftClick opens URL; PKGBUILD toggle and copy button respond to clicks; /// while text selection is enabled, clicks inside details are ignored by the app. /// - Title bar: Sort/options/panels/config buttons toggle menus; filter toggles apply filters. /// - Results: Click selects; scroll wheel moves selection and triggers details fetch. /// - Recent/Install/Remove/Downgrade panes: Scroll moves selection; click focuses/sets selection. /// - Import/Export buttons: Import opens a system file picker to enqueue names; Export writes the /// current Install list to a timestamped file and shows a toast. #[allow(clippy::too_many_arguments)] pub fn handle_mouse_event( m: MouseEvent, app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, preview_tx: &mpsc::UnboundedSender<PackageItem>, _add_tx: &mpsc::UnboundedSender<PackageItem>, pkgb_tx: &mpsc::UnboundedSender<PackageItem>, comments_tx: &mpsc::UnboundedSender<String>, query_tx: &mpsc::UnboundedSender<QueryInput>, ) -> bool { // Ensure mouse capture is enabled (important after external terminal processes) crate::util::ensure_mouse_capture(); if !app.mouse_capture_enabled { app.mouse_capture_enabled = true; } let mx = m.column; let my = m.row; let is_left_down = matches!(m.kind, MouseEventKind::Down(MouseButton::Left)); let ctrl = m.modifiers.contains(KeyModifiers::CONTROL); let shift = m.modifiers.contains(KeyModifiers::SHIFT); // Track last mouse position for dynamic capture toggling app.last_mouse_pos = Some((mx, my)); // Modal-first handling: modals intercept mouse events if let Some(handled) = modals::handle_modal_mouse(m, mx, my, is_left_down, app) { return handled; } // While any modal is open, prevent main window interaction by consuming mouse events if !matches!(app.modal, crate::state::Modal::None) { return false; } // Details pane interactions (URL, PKGBUILD buttons, scroll) if let Some(handled) = details::handle_details_mouse( m, mx, my, is_left_down, ctrl, shift, app, pkgb_tx, comments_tx, ) { return handled; } // Menu interactions (sort, options, config, panels, import/export) if is_left_down && let Some(handled) = menus::handle_menus_mouse(mx, my, app, details_tx) { return handled; } // Filter toggle interactions if is_left_down && let Some(handled) = filters::handle_filters_mouse(mx, my, app) { return handled; } // Fuzzy search indicator toggle if is_left_down && let Some((x, y, w, h)) = app.fuzzy_indicator_rect && mx >= x && mx < x + w && my >= y && my < y + h { app.fuzzy_search_enabled = !app.fuzzy_search_enabled; crate::theme::save_fuzzy_search(app.fuzzy_search_enabled); // Invalidate cache when fuzzy mode changes app.search_cache_query = None; app.search_cache_results = None; // Re-trigger search with current query using new mode crate::logic::send_query(app, query_tx); return false; } // Pane interactions (Results, Recent, Install/Remove/Downgrade, PKGBUILD viewer) if let Some(handled) = panes::handle_panes_mouse( m, mx, my, is_left_down, app, details_tx, preview_tx, comments_tx, ) { return handled; } false } // Re-export for use in keyboard handlers pub use menus::{handle_news_button, handle_updates_button};
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/mouse/details.rs
src/events/mouse/details.rs
//! 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}; /// 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 } 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>, ) -> 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); } } // 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 }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/mouse/panes.rs
src/events/mouse/panes.rs
//! Pane mouse event handling (Results, Recent, Install/Remove/Downgrade, PKGBUILD viewer). use crossterm::event::{MouseEvent, MouseEventKind}; use tokio::sync::mpsc; use crate::events::utils::refresh_install_details; use crate::logic::move_sel_cached; use crate::state::{AppState, PackageItem}; /// What: Check if mouse coordinates are within a rectangle. /// /// Inputs: /// - `mx`: Mouse X coordinate /// - `my`: Mouse Y coordinate /// - `rect`: Optional rectangle tuple (x, y, width, height) /// /// Output: /// - `true` if mouse is within the rectangle, `false` otherwise /// /// Details: /// - Returns `false` if `rect` is `None`. /// - Checks bounds: `mx >= x && mx < x + w && my >= y && my < y + h`. const fn is_in_rect(mx: u16, my: u16, rect: Option<(u16, u16, u16, u16)>) -> bool { let Some((x, y, w, h)) = rect else { return false; }; mx >= x && mx < x + w && my >= y && my < y + h } /// What: Handle Results pane mouse interactions. /// /// Inputs: /// - `m`: Mouse event /// - `mx`: Mouse X coordinate /// - `my`: Mouse Y coordinate /// - `is_left_down`: Whether left button is pressed /// - `app`: Mutable application state /// - `details_tx`: Channel for details requests /// /// Output: /// - `true` if event was handled, `false` otherwise /// /// Details: /// - Left click selects item at clicked row. /// - Scroll wheel moves selection and triggers details fetch. fn handle_results_pane( m: MouseEvent, mx: u16, my: u16, is_left_down: bool, app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, comments_tx: &mpsc::UnboundedSender<String>, ) -> bool { if !is_in_rect(mx, my, app.results_rect) { return false; } let (_, y, _, _) = app .results_rect .expect("results_rect should be Some when is_in_rect returns true"); // Results list has a top border; adjust so first row maps to index 0. let row = my.saturating_sub(y.saturating_add(1)) as usize; if matches!(app.app_mode, crate::state::types::AppMode::News) { let offset = app.news_list_state.offset(); let idx = offset + row; if idx < app.news_results.len() && is_left_down { app.news_selected = idx; app.news_list_state.select(Some(idx)); crate::events::utils::update_news_url(app); } match m.kind { MouseEventKind::ScrollUp => { crate::events::utils::move_news_selection(app, -1); true } MouseEventKind::ScrollDown => { crate::events::utils::move_news_selection(app, 1); true } _ => is_left_down, } } else { if is_left_down { let offset = app.list_state.offset(); let idx = offset + row; if idx < app.results.len() { app.selected = idx; app.list_state.select(Some(idx)); } } match m.kind { MouseEventKind::ScrollUp => { move_sel_cached(app, -1, details_tx, comments_tx); true } MouseEventKind::ScrollDown => { move_sel_cached(app, 1, details_tx, comments_tx); true } _ => is_left_down, } } } /// What: Handle Recent pane mouse interactions. /// /// Inputs: /// - `m`: Mouse event /// - `mx`: Mouse X coordinate /// - `my`: Mouse Y coordinate /// - `app`: Mutable application state /// - `preview_tx`: Channel for preview requests /// /// Output: /// - `true` if event was handled, `false` otherwise /// /// Details: /// - Scroll wheel moves selection and triggers preview fetch. fn handle_recent_pane( m: MouseEvent, mx: u16, my: u16, app: &mut AppState, preview_tx: &mpsc::UnboundedSender<PackageItem>, ) -> bool { if !is_in_rect(mx, my, app.recent_rect) { return false; } let inds = crate::ui::helpers::filtered_recent_indices(app); if inds.is_empty() { return false; } match m.kind { MouseEventKind::ScrollUp => { if let Some(sel) = app.history_state.selected() { let new = sel.saturating_sub(1); app.history_state.select(Some(new)); crate::ui::helpers::trigger_recent_preview(app, preview_tx); true } else { false } } MouseEventKind::ScrollDown => { let sel = app.history_state.selected().unwrap_or(0); let max = inds.len().saturating_sub(1); let new = std::cmp::min(sel.saturating_add(1), max); app.history_state.select(Some(new)); crate::ui::helpers::trigger_recent_preview(app, preview_tx); true } _ => false, } } /// What: Handle Install/Remove pane click interactions. /// /// Inputs: /// - `mx`: Mouse X coordinate /// - `my`: Mouse Y coordinate /// - `app`: Mutable application state /// - `details_tx`: Channel for details requests /// /// Output: /// - `Some(false)` if handled, `None` otherwise /// /// Details: /// - Focuses Install pane and selects item at clicked row. /// - Handles both Remove (installed-only mode) and Install (normal mode). fn handle_install_click( mx: u16, my: u16, app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, ) -> Option<bool> { if !is_in_rect(mx, my, app.install_rect) { return None; } app.focus = crate::state::Focus::Install; let (_, y, _, _) = app .install_rect .expect("install_rect should be Some when is_in_rect returns true"); let row = my.saturating_sub(y) as usize; if app.installed_only_mode { app.right_pane_focus = crate::state::RightPaneFocus::Remove; let max = app.remove_list.len().saturating_sub(1); if !app.remove_list.is_empty() { let idx = std::cmp::min(row, max); app.remove_state.select(Some(idx)); crate::events::utils::refresh_remove_details(app, details_tx); } } else { app.right_pane_focus = crate::state::RightPaneFocus::Install; let inds = crate::ui::helpers::filtered_install_indices(app); if !inds.is_empty() { let max = inds.len().saturating_sub(1); let vis_idx = std::cmp::min(row, max); app.install_state.select(Some(vis_idx)); crate::events::utils::refresh_install_details(app, details_tx); } } Some(false) } /// What: Handle Install/Remove pane scroll interactions. /// /// Inputs: /// - `m`: Mouse event /// - `mx`: Mouse X coordinate /// - `my`: Mouse Y coordinate /// - `app`: Mutable application state /// - `details_tx`: Channel for details requests /// /// Output: /// - `true` if event was handled, `false` otherwise /// /// Details: /// - Scroll wheel moves selection in Remove (installed-only mode) or Install (normal mode). fn handle_install_scroll( m: MouseEvent, mx: u16, my: u16, app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, ) -> bool { if !is_in_rect(mx, my, app.install_rect) { return false; } if app.installed_only_mode { let len = app.remove_list.len(); if len > 0 { match m.kind { MouseEventKind::ScrollUp => { if let Some(sel) = app.remove_state.selected() { let new = sel.saturating_sub(1); app.remove_state.select(Some(new)); crate::events::utils::refresh_remove_details(app, details_tx); true } else { false } } MouseEventKind::ScrollDown => { let sel = app.remove_state.selected().unwrap_or(0); let max = len.saturating_sub(1); let new = std::cmp::min(sel.saturating_add(1), max); app.remove_state.select(Some(new)); crate::events::utils::refresh_remove_details(app, details_tx); true } _ => false, } } else { false } } else { let inds = crate::ui::helpers::filtered_install_indices(app); if inds.is_empty() { false } else { match m.kind { MouseEventKind::ScrollUp => { if let Some(sel) = app.install_state.selected() { let new = sel.saturating_sub(1); app.install_state.select(Some(new)); refresh_install_details(app, details_tx); true } else { false } } MouseEventKind::ScrollDown => { let sel = app.install_state.selected().unwrap_or(0); let max = inds.len().saturating_sub(1); let new = std::cmp::min(sel.saturating_add(1), max); app.install_state.select(Some(new)); refresh_install_details(app, details_tx); true } _ => false, } } } } /// What: Handle Downgrade pane click interactions. /// /// Inputs: /// - `mx`: Mouse X coordinate /// - `my`: Mouse Y coordinate /// - `app`: Mutable application state /// - `details_tx`: Channel for details requests /// /// Output: /// - `Some(false)` if handled, `None` otherwise /// /// Details: /// - Only active in installed-only mode. /// - Focuses Install pane, sets Downgrade focus, and selects item at clicked row. fn handle_downgrade_click( mx: u16, my: u16, app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, ) -> Option<bool> { if !app.installed_only_mode || !is_in_rect(mx, my, app.downgrade_rect) { return None; } app.focus = crate::state::Focus::Install; app.right_pane_focus = crate::state::RightPaneFocus::Downgrade; let (_, y, _, _) = app .downgrade_rect .expect("downgrade_rect should be Some when is_in_rect returns true"); let row = my.saturating_sub(y) as usize; let max = app.downgrade_list.len().saturating_sub(1); if !app.downgrade_list.is_empty() { let idx = std::cmp::min(row, max); app.downgrade_state.select(Some(idx)); crate::events::utils::refresh_downgrade_details(app, details_tx); } Some(false) } /// What: Handle Downgrade pane scroll interactions. /// /// Inputs: /// - `m`: Mouse event /// - `mx`: Mouse X coordinate /// - `my`: Mouse Y coordinate /// - `app`: Mutable application state /// - `details_tx`: Channel for details requests /// /// Output: /// - `true` if event was handled, `false` otherwise /// /// Details: /// - Only active in installed-only mode. /// - Scroll wheel moves selection in Downgrade list. fn handle_downgrade_scroll( m: MouseEvent, mx: u16, my: u16, app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, ) -> bool { if !app.installed_only_mode || !is_in_rect(mx, my, app.downgrade_rect) { return false; } let len = app.downgrade_list.len(); if len > 0 { match m.kind { MouseEventKind::ScrollUp => { if let Some(sel) = app.downgrade_state.selected() { let new = sel.saturating_sub(1); app.downgrade_state.select(Some(new)); crate::events::utils::refresh_downgrade_details(app, details_tx); true } else { false } } MouseEventKind::ScrollDown => { let sel = app.downgrade_state.selected().unwrap_or(0); let max = len.saturating_sub(1); let new = std::cmp::min(sel.saturating_add(1), max); app.downgrade_state.select(Some(new)); crate::events::utils::refresh_downgrade_details(app, details_tx); true } _ => false, } } else { false } } /// What: Handle PKGBUILD viewer scroll interactions. /// /// Inputs: /// - `m`: Mouse event /// - `mx`: Mouse X coordinate /// - `my`: Mouse Y coordinate /// - `app`: Mutable application state /// /// Output: /// - `true` if event was handled, `false` otherwise /// /// Details: /// - Scroll wheel scrolls the PKGBUILD content. #[allow(clippy::missing_const_for_fn)] fn handle_pkgbuild_scroll(m: MouseEvent, mx: u16, my: u16, app: &mut AppState) -> bool { if !is_in_rect(mx, my, app.pkgb_rect) { return false; } match m.kind { MouseEventKind::ScrollUp => { app.pkgb_scroll = app.pkgb_scroll.saturating_sub(1); true } MouseEventKind::ScrollDown => { app.pkgb_scroll = app.pkgb_scroll.saturating_add(1); true } _ => false, } } /// What: Handle comments viewer scroll interactions. /// /// Inputs: /// - `m`: Mouse event /// - `mx`: Mouse X coordinate /// - `my`: Mouse Y coordinate /// - `app`: Mutable application state /// /// Output: /// - `true` if event was handled, `false` otherwise /// /// Details: /// - Scroll wheel scrolls the comments content. #[allow(clippy::missing_const_for_fn)] fn handle_comments_scroll(m: MouseEvent, mx: u16, my: u16, app: &mut AppState) -> bool { if !is_in_rect(mx, my, app.comments_rect) { return false; } match m.kind { MouseEventKind::ScrollUp => { app.comments_scroll = app.comments_scroll.saturating_sub(1); true } MouseEventKind::ScrollDown => { app.comments_scroll = app.comments_scroll.saturating_add(1); true } _ => false, } } /// Handle mouse events for panes (Results, Recent, Install/Remove/Downgrade, PKGBUILD viewer). /// /// What: Process mouse interactions within list panes for selection, scrolling, and focus changes. /// /// Inputs: /// - `m`: Mouse event including position, button, and modifiers /// - `mx`: Mouse X coordinate (column) /// - `my`: Mouse Y coordinate (row) /// - `is_left_down`: Whether the left mouse button is pressed /// - `app`: Mutable application state containing pane state and UI rectangles /// - `details_tx`: Channel to request package details when selection changes /// - `preview_tx`: Channel to request preview details for Recent pane interactions /// /// Output: /// - `Some(bool)` if the event was handled (consumed by a pane), `None` if not handled. /// The boolean value indicates whether the application should exit (always `false` here). /// /// Details: /// - Results pane: Left click selects item; scroll wheel moves selection and triggers details fetch. /// - Recent pane: Scroll wheel moves selection and triggers preview fetch. /// - Install/Remove panes: Left click focuses pane and selects item; scroll wheel moves selection. /// - Downgrade pane: Left click focuses pane and selects item; scroll wheel moves selection. /// - PKGBUILD viewer: Scroll wheel scrolls the PKGBUILD content. #[allow(clippy::too_many_arguments)] pub(super) fn handle_panes_mouse( m: MouseEvent, mx: u16, my: u16, is_left_down: bool, app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, preview_tx: &mpsc::UnboundedSender<PackageItem>, comments_tx: &mpsc::UnboundedSender<String>, ) -> Option<bool> { // Handle clicks first (they return early when handled) if is_left_down { if let Some(result) = handle_install_click(mx, my, app, details_tx) { return Some(result); } if let Some(result) = handle_downgrade_click(mx, my, app, details_tx) { return Some(result); } } // Handle scroll events (execute handlers, they don't return early) handle_results_pane(m, mx, my, is_left_down, app, details_tx, comments_tx); handle_recent_pane(m, mx, my, app, preview_tx); handle_install_scroll(m, mx, my, app, details_tx); handle_downgrade_scroll(m, mx, my, app, details_tx); handle_pkgbuild_scroll(m, mx, my, app); handle_comments_scroll(m, mx, my, app); None }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/mouse/modals/preflight_helpers.rs
src/events/mouse/modals/preflight_helpers.rs
//! Helper functions for Preflight modal mouse event handling. use crate::state::types::PackageItem; use std::collections::{HashMap, HashSet}; /// Build display items list for the Deps tab. /// /// What: Creates a list of display items (headers and dependencies) for the dependency tree view. /// /// Inputs: /// - `items`: Packages selected for install/remove shown in the modal /// - `dependency_info`: Flattened dependency metadata resolved for those packages /// - `dep_tree_expanded`: Set of package names currently expanded in the UI tree /// /// Output: /// - Vector of `(bool, String)` pairs distinguishing headers (`true`) from dependency rows (`false`). /// /// Details: /// - Groups dependencies by the packages that require them. /// - Only includes dependencies when their parent package is expanded. /// - Always includes all packages, even if they have no dependencies. /// - Deduplicates dependencies by name within each package group. pub(super) fn build_deps_display_items( items: &[PackageItem], dependency_info: &[crate::state::modal::DependencyInfo], dep_tree_expanded: &HashSet<String>, ) -> Vec<(bool, String)> { // Build display items list to find which package header was clicked let mut grouped: HashMap<String, Vec<&crate::state::modal::DependencyInfo>> = HashMap::new(); for dep in dependency_info { for req_by in &dep.required_by { grouped.entry(req_by.clone()).or_default().push(dep); } } let mut display_items: Vec<(bool, String)> = Vec::new(); // Always show ALL packages, even if they have no dependencies // This ensures packages that failed to resolve dependencies (e.g., due to conflicts) are still visible for pkg_name in items.iter().map(|p| &p.name) { display_items.push((true, pkg_name.clone())); if dep_tree_expanded.contains(pkg_name) { let mut seen_deps = HashSet::new(); if let Some(pkg_deps) = grouped.get(pkg_name) { for dep in pkg_deps { if seen_deps.insert(dep.name.as_str()) { display_items.push((false, String::new())); } } } } } display_items } /// Load cached dependencies from app state. /// /// What: Retrieves cached dependency information for the given packages from the install list. /// /// Inputs: /// - `items`: Packages to find cached dependencies for /// - `install_list_deps`: Cached dependency information from app state /// /// Output: /// - Vector of cached dependency information, filtered to only include dependencies required by the given packages. /// /// Details: /// - Filters cached dependencies to only those required by packages in `items`. /// - Returns empty vector if no matching cached dependencies are found. pub(super) fn load_cached_dependencies( items: &[PackageItem], install_list_deps: &[crate::state::modal::DependencyInfo], ) -> Vec<crate::state::modal::DependencyInfo> { let item_names: HashSet<String> = items.iter().map(|i| i.name.clone()).collect(); install_list_deps .iter() .filter(|dep| { dep.required_by .iter() .any(|req_by| item_names.contains(req_by)) }) .cloned() .collect() } /// Load cached files from app state. /// /// What: Retrieves cached file information for the given packages from the install list. /// /// Inputs: /// - `items`: Packages to find cached files for /// - `install_list_files`: Cached file information from app state /// /// Output: /// - Vector of cached file information, filtered to only include files for the given packages. /// /// Details: /// - Filters cached files to only those belonging to packages in `items`. /// - Returns empty vector if no matching cached files are found. pub(super) fn load_cached_files( items: &[PackageItem], install_list_files: &[crate::state::modal::PackageFileInfo], ) -> Vec<crate::state::modal::PackageFileInfo> { let item_names: HashSet<String> = items.iter().map(|i| i.name.clone()).collect(); install_list_files .iter() .filter(|file_info| item_names.contains(&file_info.name)) .cloned() .collect() } /// Load cached services from app state. /// /// What: Retrieves cached service information for the given packages from the install list. /// /// Inputs: /// - `items`: Packages to find cached services for /// - `action`: Preflight action (Install or Remove) /// - `services_resolving`: Whether services are currently being resolved /// - `services_cache_path`: Path to the services cache file /// - `install_list_services`: Cached service information from app state /// /// Output: /// - `Some(Vec<ServiceImpact>)` if cached services are available, `None` otherwise. /// /// Details: /// - Only loads cache for Install actions. /// - Checks if cache file exists with matching signature. /// - Returns `None` if services are currently being resolved, cache doesn't exist, or cached services are empty. pub(super) fn load_cached_services( items: &[PackageItem], action: crate::state::PreflightAction, services_resolving: bool, services_cache_path: &std::path::PathBuf, install_list_services: &[crate::state::modal::ServiceImpact], ) -> Option<Vec<crate::state::modal::ServiceImpact>> { // Try to use cached services from app state (for install actions) if !matches!(action, crate::state::PreflightAction::Install) || services_resolving { return None; } // Check if cache file exists with matching signature let cache_exists = if items.is_empty() { false } else { let signature = crate::app::services_cache::compute_signature(items); crate::app::services_cache::load_cache(services_cache_path, &signature).is_some() }; if cache_exists && !install_list_services.is_empty() { Some(install_list_services.to_vec()) } else { None } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/mouse/modals/preflight.rs
src/events/mouse/modals/preflight.rs
//! Preflight modal mouse event handling. use crate::state::AppState; use crossterm::event::MouseEvent; use super::preflight_helpers::{load_cached_dependencies, load_cached_files, load_cached_services}; use super::preflight_tabs::{ handle_deps_tab_click, handle_deps_tab_scroll, handle_files_tab_click, handle_files_tab_scroll, handle_services_tab_click, handle_services_tab_scroll, handle_summary_tab_scroll, }; /// Handle mouse events for the Preflight modal. /// /// What: Process mouse interactions within the Preflight modal dialog. /// /// Inputs: /// - `m`: Mouse event including position, button, and modifiers /// - `mx`: Mouse X coordinate (column) /// - `my`: Mouse Y coordinate (row) /// - `is_left_down`: Whether the left mouse button is pressed /// - `app`: Mutable application state containing modal state and UI rectangles /// /// Output: /// - `Some(false)` if the event was handled, `None` if not handled. /// /// Details: /// - Handles tab clicks and tab switching. /// - Handles package group header toggles in Deps/Files tabs. /// - Handles service restart decisions in Services tab. /// - Handles scroll navigation for Deps/Files/Services tabs. pub(super) fn handle_preflight_modal( m: MouseEvent, mx: u16, my: u16, is_left_down: bool, app: &mut AppState, ) -> Option<bool> { // Extract tab value first to avoid borrow conflicts let current_tab = if let crate::state::Modal::Preflight { tab, .. } = &app.modal { *tab } else { return None; }; // Handle tab clicks if is_left_down { if handle_preflight_tab_click(mx, my, app) { return Some(false); } // Handle tab-specific clicks match current_tab { crate::state::PreflightTab::Deps => { if handle_deps_tab_click(mx, my, app) { return Some(false); } } crate::state::PreflightTab::Files => { if handle_files_tab_click(mx, my, app) { return Some(false); } } crate::state::PreflightTab::Services => { if handle_services_tab_click(mx, my, app) { return Some(false); } } _ => {} } } // Handle tab-specific scrolls match current_tab { crate::state::PreflightTab::Summary => { if handle_summary_tab_scroll(m, app) { return Some(false); } } crate::state::PreflightTab::Deps => { if handle_deps_tab_scroll(m, app) { return Some(false); } } crate::state::PreflightTab::Files => { if handle_files_tab_scroll(m, app) { return Some(false); } } crate::state::PreflightTab::Services => { if handle_services_tab_scroll(m, app) { return Some(false); } } crate::state::PreflightTab::Sandbox => {} } // Consume all mouse events while Preflight modal is open Some(false) } /// Handle tab click events in the Preflight modal. /// /// What: Detect clicks on tab buttons and switch to the clicked tab, loading cached data if available. /// /// Inputs: /// - `mx`: Mouse X coordinate (column) /// - `my`: Mouse Y coordinate (row) /// - `app`: Mutable application state containing modal state and UI rectangles /// /// Output: /// - `true` if a tab was clicked and handled, `false` otherwise. /// /// Details: /// - Switches to the clicked tab (Summary, Deps, Files, Services, Sandbox). /// - Loads cached dependencies when switching to Deps tab. /// - Loads cached files when switching to Files tab. /// - Loads cached services when switching to Services tab. fn handle_preflight_tab_click(mx: u16, my: u16, app: &mut AppState) -> bool { if let crate::state::Modal::Preflight { tab, items, action, dependency_info, dep_selected, file_info, file_selected, service_info, service_selected, services_loaded, .. } = &mut app.modal { for (i, tab_rect_opt) in app.preflight_tab_rects.iter().enumerate() { if let Some((x, y, w, h)) = tab_rect_opt && mx >= *x && mx < x + w && my >= *y && my < y + h { // Clicked on tab i - switch to that tab let new_tab = match i { 0 => crate::state::PreflightTab::Summary, 1 => crate::state::PreflightTab::Deps, 2 => crate::state::PreflightTab::Files, 3 => crate::state::PreflightTab::Services, 4 => crate::state::PreflightTab::Sandbox, _ => continue, }; let old_tab = *tab; *tab = new_tab; tracing::info!( "[Preflight] Mouse tab click: Switching from {:?} to {:?}, items={}, dependency_info.len()={}, file_info.len()={}", old_tab, new_tab, items.len(), dependency_info.len(), file_info.len() ); // Check for cached dependencies when switching to Deps tab if *tab == crate::state::PreflightTab::Deps && dependency_info.is_empty() && matches!(*action, crate::state::PreflightAction::Install) { tracing::debug!( "[Preflight] Mouse tab click: Deps tab - loading cache, cache.len()={}", app.install_list_deps.len() ); let cached_deps = load_cached_dependencies(items, &app.install_list_deps); tracing::info!( "[Preflight] Mouse tab click: Deps tab - loaded {} cached deps", cached_deps.len() ); if !cached_deps.is_empty() { *dependency_info = cached_deps; *dep_selected = 0; } // If no cached deps, user can press 'r' to resolve } // Check for cached files when switching to Files tab if *tab == crate::state::PreflightTab::Files && file_info.is_empty() { tracing::debug!( "[Preflight] Mouse tab click: Files tab - loading cache, cache.len()={}", app.install_list_files.len() ); let cached_files = load_cached_files(items, &app.install_list_files); tracing::info!( "[Preflight] Mouse tab click: Files tab - loaded {} cached files", cached_files.len() ); if !cached_files.is_empty() { *file_info = cached_files; *file_selected = 0; } // If no cached files, user can press 'r' to resolve } // Check for cached services when switching to Services tab if *tab == crate::state::PreflightTab::Services && service_info.is_empty() && let Some(cached_services) = load_cached_services( items, *action, app.services_resolving, &app.services_cache_path, &app.install_list_services, ) { *service_info = cached_services; *service_selected = 0; *services_loaded = true; // If no cached services, user can press 'r' to resolve } return true; } } } false }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/mouse/modals/simple.rs
src/events/mouse/modals/simple.rs
//! Simple modal mouse event handling (Help, `VirusTotalSetup`, News). use crate::state::AppState; use crossterm::event::{MouseEvent, MouseEventKind}; /// What: Calculate scroll offset to keep the selected item in the middle of the viewport. /// /// Inputs: /// - `selected`: Currently selected item index /// - `total_items`: Total number of items in the list /// - `visible_height`: Height of the visible content area (in lines) /// /// Output: /// - Scroll offset (lines) that centers the selected item /// /// Details: /// - Calculates scroll so selected item is in the middle of visible area /// - Ensures scroll doesn't go negative or past the end fn calculate_news_scroll_for_selection( selected: usize, total_items: usize, visible_height: u16, ) -> u16 { if total_items == 0 || visible_height == 0 { return 0; } // Clamp values to u16::MAX to prevent overflow in calculations. // Note: If selected or total_items exceeds u16::MAX, the scroll calculation will be // performed for the clamped values, which may not match the actual selected item. // This is acceptable since u16::MAX (65535) is far beyond practical UI list sizes. let selected_line = u16::try_from(selected).unwrap_or(u16::MAX); let total_lines = u16::try_from(total_items).unwrap_or(u16::MAX); // Ensure selected doesn't exceed total after clamping to maintain valid calculations let selected_line = selected_line.min(total_lines); // Calculate middle position: we want selected item to be at visible_height / 2 let middle_offset = visible_height / 2; // Calculate desired scroll to center the selection let desired_scroll = selected_line.saturating_sub(middle_offset); // Calculate maximum scroll (when last item is at the bottom) let max_scroll = total_lines.saturating_sub(visible_height); // Clamp scroll to valid range desired_scroll.min(max_scroll) } /// Handle mouse events for the Help modal. /// /// What: Process mouse interactions within the Help modal dialog. /// /// Inputs: /// - `m`: Mouse event including position, button, and modifiers /// - `mx`: Mouse X coordinate (column) /// - `my`: Mouse Y coordinate (row) /// - `is_left_down`: Whether the left mouse button is pressed /// - `app`: Mutable application state containing modal state and UI rectangles /// /// Output: /// - `false` if the event was handled /// /// Details: /// - Supports scrolling within content area. /// - Closes modal on outside click. /// - Consumes all mouse events while Help is open. pub(super) fn handle_help_modal( m: MouseEvent, mx: u16, my: u16, is_left_down: bool, app: &mut AppState, ) -> bool { // Scroll within Help content area if let Some((x, y, w, h)) = app.help_rect && mx >= x && mx < x + w && my >= y && my < y + h { match m.kind { MouseEventKind::ScrollUp => { app.help_scroll = app.help_scroll.saturating_sub(1); return false; } MouseEventKind::ScrollDown => { app.help_scroll = app.help_scroll.saturating_add(1); return false; } _ => {} } } // Clicking outside closes the Help modal if is_left_down { if let Some((x, y, w, h)) = app.help_rect { // Outer rect includes borders around inner help rect let outer_x = x.saturating_sub(1); let outer_y = y.saturating_sub(1); let outer_w = w.saturating_add(2); let outer_h = h.saturating_add(2); if mx < outer_x || mx >= outer_x + outer_w || my < outer_y || my >= outer_y + outer_h { app.modal = crate::state::Modal::None; } } else { // Fallback: close on any click if no rect is known app.modal = crate::state::Modal::None; } return false; } // Consume remaining mouse events while Help is open false } /// Handle mouse events for the `VirusTotalSetup` modal. /// /// What: Process mouse interactions within the `VirusTotalSetup` modal dialog. /// /// Inputs: /// - `_m`: Mouse event including position, button, and modifiers (unused but kept for signature consistency) /// - `mx`: Mouse X coordinate (column) /// - `my`: Mouse Y coordinate (row) /// - `is_left_down`: Whether the left mouse button is pressed /// - `app`: Mutable application state containing modal state and UI rectangles /// /// Output: /// - `false` if the event was handled /// /// Details: /// - Opens URL when clicking the link area. /// - Consumes all mouse events while `VirusTotal` setup modal is open. pub(super) fn handle_virustotal_modal( _m: MouseEvent, mx: u16, my: u16, is_left_down: bool, app: &AppState, ) -> bool { if is_left_down && let Some((x, y, w, h)) = app.vt_url_rect && mx >= x && mx < x + w && my >= y && my < y + h { let url = "https://www.virustotal.com/gui/my-apikey"; std::thread::spawn(move || { let _ = std::process::Command::new("xdg-open") .arg(url) .stdin(std::process::Stdio::null()) .stdout(std::process::Stdio::null()) .stderr(std::process::Stdio::null()) .spawn(); }); } // Consume all mouse events while VirusTotal setup modal is open false } /// Handle mouse events for the News modal. /// /// What: Process mouse interactions within the News modal dialog. /// /// Inputs: /// - `m`: Mouse event including position, button, and modifiers /// - `mx`: Mouse X coordinate (column) /// - `my`: Mouse Y coordinate (row) /// - `is_left_down`: Whether the left mouse button is pressed /// - `app`: Mutable application state containing modal state and UI rectangles /// /// Output: /// - `Some(false)` if the event was handled, `None` if not handled. /// /// Details: /// - Handles item selection and URL opening. /// - Handles scroll navigation. /// - Closes modal on outside click. pub(super) fn handle_announcement_modal( m: MouseEvent, mx: u16, my: u16, is_left_down: bool, app: &mut AppState, ) -> Option<bool> { if let crate::state::Modal::Announcement { scroll, .. } = &mut app.modal { // Left click: check for URL click first, then close on outside if is_left_down { // Check if click matches any URL position for (url_x, url_y, url_width, url) in &app.announcement_urls { if mx >= *url_x && mx < url_x.saturating_add(*url_width) && my == *url_y { crate::util::open_url(url); return Some(false); } } // Click outside closes the modal (dismiss temporarily) if let Some((x, y, w, h)) = app.announcement_rect && (mx < x || mx >= x + w || my < y || my >= y + h) { // Click outside closes the modal (dismiss temporarily) app.modal = crate::state::Modal::None; } return Some(false); } // Scroll within modal: scroll content match m.kind { MouseEventKind::ScrollUp => { if *scroll > 0 { *scroll -= 1; } return Some(false); } MouseEventKind::ScrollDown => { *scroll = scroll.saturating_add(1); return Some(false); } _ => {} } // If modal is open and event wasn't handled above, consume it return Some(false); } None } /// What: Handle mouse events in the News modal. /// /// Inputs: /// - `m`: Mouse event /// - `mx`: Mouse X coordinate /// - `my`: Mouse Y coordinate /// - `is_left_down`: Whether left mouse button is pressed /// - `app`: Mutable application state /// /// Output: /// - `Some(true)` if application should exit /// - `Some(false)` if event was handled /// - `None` if event was not handled /// /// Details: /// - Handles left clicks to select/open news items or close modal on outside click /// - Handles scrolling in the news list pub(super) fn handle_news_modal( m: MouseEvent, mx: u16, my: u16, is_left_down: bool, app: &mut AppState, ) -> Option<bool> { if let crate::state::Modal::News { items, selected, scroll, } = &mut app.modal { // Left click: select/open or close on outside if is_left_down { if let Some((x, y, w, h)) = app.news_list_rect && mx >= x && mx < x + w && my >= y && my < y + h { // Calculate clicked row accounting for scroll offset let relative_y = my.saturating_sub(y); let clicked_row = (relative_y as usize).saturating_add(*scroll as usize); // Only open if clicking on an actual news item line (not empty space) if clicked_row < items.len() { *selected = clicked_row; // Update scroll to keep selection centered *scroll = calculate_news_scroll_for_selection(*selected, items.len(), h); if let Some(it) = items.get(*selected) && let Some(url) = &it.url { crate::util::open_url(url); } } } else if let Some((x, y, w, h)) = app.news_rect && (mx < x || mx >= x + w || my < y || my >= y + h) { // Click outside closes the modal app.modal = crate::state::Modal::None; } return Some(false); } // Scroll within modal: move selection match m.kind { MouseEventKind::ScrollUp => { if *selected > 0 { *selected -= 1; // Update scroll to keep selection centered if let Some((_, _, _, visible_h)) = app.news_list_rect { *scroll = calculate_news_scroll_for_selection(*selected, items.len(), visible_h); } } return Some(false); } MouseEventKind::ScrollDown => { if *selected + 1 < items.len() { *selected += 1; // Update scroll to keep selection centered if let Some((_, _, _, visible_h)) = app.news_list_rect { *scroll = calculate_news_scroll_for_selection(*selected, items.len(), visible_h); } } return Some(false); } _ => {} } // If modal is open and event wasn't handled above, consume it return Some(false); } None } /// Handle mouse events for Updates modal. /// /// What: Process mouse interactions within the Updates modal (scroll, selection, close). /// /// Inputs: /// - `m`: Mouse event /// - `mx`: Mouse X coordinate /// - `my`: Mouse Y coordinate /// - `is_left_down`: Whether left button is pressed /// - `app`: Mutable application state /// /// Output: /// - `Some(false)` if handled, `None` otherwise /// /// Details: /// - Handles row selection on click. /// - Handles scroll navigation (updates selection to match scroll position). /// - Closes modal on outside click. pub(super) fn handle_updates_modal( m: MouseEvent, mx: u16, my: u16, is_left_down: bool, app: &mut AppState, ) -> Option<bool> { if let crate::state::Modal::Updates { ref mut scroll, ref entries, ref mut selected, } = app.modal { // Left click: select row or close on outside if is_left_down { if let Some((x, y, w, h)) = app.updates_modal_content_rect && mx >= x && mx < x + w && my >= y && my < y + h { // Account for header (2 lines) when calculating clicked row const HEADER_LINES: u16 = 2; let relative_y = my.saturating_sub(y); // Only process clicks in the content area (below header) if relative_y >= HEADER_LINES { // Calculate which row was clicked (accounting for header and scroll offset) let clicked_row = (relative_y.saturating_sub(HEADER_LINES) as usize) .saturating_add(*scroll as usize); // Only update selection if clicking on an actual entry if clicked_row < entries.len() { *selected = clicked_row; // Auto-scroll to keep selected item visible update_scroll_for_selection(scroll, *selected); } } } else if let Some((x, y, w, h)) = app.updates_modal_rect { // Click outside modal closes it if mx < x || mx >= x + w || my < y || my >= y + h { app.modal = crate::state::Modal::None; return Some(false); // Return immediately after closing } } return Some(false); } // Handle scroll within modal: update selection to match scroll position match m.kind { crossterm::event::MouseEventKind::ScrollUp => { if *selected > 0 { *selected -= 1; } // Auto-scroll to keep selected item visible update_scroll_for_selection(scroll, *selected); return Some(false); } crossterm::event::MouseEventKind::ScrollDown => { if *selected + 1 < entries.len() { *selected += 1; } // Auto-scroll to keep selected item visible update_scroll_for_selection(scroll, *selected); return Some(false); } _ => {} } // Consume all mouse events while Updates modal is open return Some(false); } None } /// What: Update scroll offset to keep the selected item visible. /// /// Inputs: /// - `scroll`: Mutable scroll offset /// - `selected`: Selected index /// /// Output: /// - Updates scroll to ensure selected item is visible /// /// Details: /// - Estimates visible lines based on modal height /// - Adjusts scroll so selected item is within visible range fn update_scroll_for_selection(scroll: &mut u16, selected: usize) { // Estimate visible content lines (modal height minus header/footer/borders) // Header: 2 lines, borders: 2 lines, footer: 0 lines = ~4 lines overhead // Assume ~20 visible content lines as a reasonable default const VISIBLE_LINES: u16 = 20; let selected_line = u16::try_from(selected).unwrap_or(u16::MAX); // If selected item is above visible area, scroll up if selected_line < *scroll { *scroll = selected_line; } // If selected item is below visible area, scroll down else if selected_line >= *scroll + VISIBLE_LINES { *scroll = selected_line.saturating_sub(VISIBLE_LINES.saturating_sub(1)); } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/mouse/modals/mod.rs
src/events/mouse/modals/mod.rs
//! Modal mouse event handling (Help, `VirusTotalSetup`, `Preflight`, News). use crate::state::AppState; use crossterm::event::MouseEvent; mod preflight; mod preflight_helpers; mod preflight_tabs; mod simple; /// Handle mouse events for modals. /// /// What: Process mouse interactions within modal dialogs (Help, `VirusTotalSetup`, `Preflight`, News). /// /// Inputs: /// - `m`: Mouse event including position, button, and modifiers /// - `mx`: Mouse X coordinate (column) /// - `my`: Mouse Y coordinate (row) /// - `is_left_down`: Whether the left mouse button is pressed /// - `app`: Mutable application state containing modal state and UI rectangles /// /// Output: /// - `Some(bool)` if the event was handled (consumed by a modal), `None` if not handled. /// The boolean value indicates whether the application should exit (always `false` here). /// /// Details: /// - Help modal: Supports scrolling within content area and closes on outside click. /// - `VirusTotalSetup` modal: Opens URL when clicking the link area; consumes all other events. /// - Preflight modal: Handles tab clicks, package group header toggles, service restart decisions, /// and scroll navigation for Deps/Files/Services tabs. /// - News modal: Handles item selection, URL opening, and scroll navigation; closes on outside click. pub(super) fn handle_modal_mouse( m: MouseEvent, mx: u16, my: u16, is_left_down: bool, app: &mut AppState, ) -> Option<bool> { match &mut app.modal { crate::state::Modal::Help => Some(simple::handle_help_modal(m, mx, my, is_left_down, app)), crate::state::Modal::VirusTotalSetup { .. } => Some(simple::handle_virustotal_modal( m, mx, my, is_left_down, app, )), crate::state::Modal::Preflight { .. } => { preflight::handle_preflight_modal(m, mx, my, is_left_down, app) } crate::state::Modal::Announcement { .. } => { simple::handle_announcement_modal(m, mx, my, is_left_down, app) } crate::state::Modal::News { .. } => simple::handle_news_modal(m, mx, my, is_left_down, app), crate::state::Modal::Updates { .. } => { simple::handle_updates_modal(m, mx, my, is_left_down, app) } _ => None, } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/mouse/modals/preflight_tabs.rs
src/events/mouse/modals/preflight_tabs.rs
//! Preflight modal tab-specific mouse event handling. use crate::state::AppState; use crate::state::modal::ServiceRestartDecision; use crossterm::event::{MouseEvent, MouseEventKind}; use std::collections::{HashMap, HashSet}; use super::preflight_helpers::build_deps_display_items; /// Handle click events in the Deps tab of the Preflight modal. /// /// What: Process clicks on package group headers to toggle expansion state. /// /// Inputs: /// - `mx`: Mouse X coordinate (column) /// - `my`: Mouse Y coordinate (row) /// - `app`: Mutable application state containing modal state and UI rectangles /// /// Output: /// - `true` if the click was handled, `false` otherwise. /// /// Details: /// - Builds display items list to find which package header was clicked. /// - Calculates clicked index accounting for scroll position. /// - Toggles package expansion state when clicking on a header. pub(super) fn handle_deps_tab_click(mx: u16, my: u16, app: &mut AppState) -> bool { if let crate::state::Modal::Preflight { items, dependency_info, dep_selected, dep_tree_expanded, .. } = &mut app.modal { if dependency_info.is_empty() { return false; } let Some((content_x, content_y, content_w, content_h)) = app.preflight_content_rect else { return false; }; if mx < content_x || mx >= content_x + content_w || my < content_y || my >= content_y + content_h { return false; } // Calculate which row was clicked relative to content area let clicked_row = (my - content_y) as usize; // Build display items list to find which package header was clicked let display_items = build_deps_display_items(items, dependency_info, dep_tree_expanded); // Calculate offset for summary line before the list // Deps tab has: summary line (1) + empty line (1) = 2 lines let list_start_offset = 2; // Only process clicks that are on or after the list starts if clicked_row < list_start_offset { return false; } let list_clicked_row = clicked_row - list_start_offset; // Calculate scroll position to find actual index let available_height = content_h.saturating_sub(u16::try_from(list_start_offset).unwrap_or(u16::MAX)) as usize; let start_idx = (*dep_selected) .saturating_sub(available_height / 2) .min(display_items.len().saturating_sub(available_height)); let actual_idx = start_idx + list_clicked_row; if let Some((is_header, pkg_name)) = display_items.get(actual_idx) && *is_header && actual_idx < display_items.len() { // Toggle this package's expanded state if dep_tree_expanded.contains(pkg_name) { dep_tree_expanded.remove(pkg_name); } else { dep_tree_expanded.insert(pkg_name.clone()); } return true; } } false } /// Handle click events in the Files tab of the Preflight modal. /// /// What: Process clicks on package group headers to toggle expansion state. /// /// Inputs: /// - `mx`: Mouse X coordinate (column) /// - `my`: Mouse Y coordinate (row) /// - `app`: Mutable application state containing modal state and UI rectangles /// /// Output: /// - `true` if the click was handled, `false` otherwise. /// /// Details: /// - Uses existing helper to build display items list. /// - Calculates clicked index accounting for scroll position and sync timestamp offset. /// - Toggles package expansion state when clicking on a header. pub(super) fn handle_files_tab_click(mx: u16, my: u16, app: &mut AppState) -> bool { if let crate::state::Modal::Preflight { items, file_info, file_selected, file_tree_expanded, .. } = &mut app.modal { let Some((content_x, content_y, content_w, content_h)) = app.preflight_content_rect else { return false; }; if mx < content_x || mx >= content_x + content_w || my < content_y || my >= content_y + content_h { return false; } // Calculate which row was clicked relative to content area let clicked_row = (my - content_y) as usize; // Build display items list to find which package header was clicked // Always show all packages, even if they have no files let display_items = crate::events::preflight::build_file_display_items( items, file_info, file_tree_expanded, ); // Calculate offset for summary lines before the list // Files tab has: summary line (1) + empty line (1) + optional sync timestamp (0-2) + empty line (0-1) // Minimum offset is 2 lines (summary + empty) let sync_timestamp_lines = if crate::logic::files::get_file_db_sync_info().is_some() { 2 // timestamp line + empty line } else { 0 }; let list_start_offset = 2 + sync_timestamp_lines; // summary + empty + sync timestamp lines // Only process clicks that are on or after the list starts if clicked_row < list_start_offset { return false; } let list_clicked_row = clicked_row - list_start_offset; // Calculate scroll position to find actual index let total_items = display_items.len(); let file_selected_clamped = (*file_selected).min(total_items.saturating_sub(1)); let available_height = content_h.saturating_sub(u16::try_from(list_start_offset).unwrap_or(u16::MAX)) as usize; let (start_idx, _end_idx) = if total_items <= available_height { (0, total_items) } else { let start = file_selected_clamped .saturating_sub(available_height / 2) .min(total_items.saturating_sub(available_height)); let end = (start + available_height).min(total_items); (start, end) }; let actual_idx = start_idx + list_clicked_row; if let Some((is_header, pkg_name)) = display_items.get(actual_idx) && *is_header && actual_idx < display_items.len() { // Toggle this package's expanded state if file_tree_expanded.contains(pkg_name) { file_tree_expanded.remove(pkg_name); } else { file_tree_expanded.insert(pkg_name.clone()); } return true; } } false } /// Handle click events in the Services tab of the Preflight modal. /// /// What: Process clicks on service items to select them or toggle restart decision. /// /// Inputs: /// - `mx`: Mouse X coordinate (column) /// - `my`: Mouse Y coordinate (row) /// - `app`: Mutable application state containing modal state and UI rectangles /// /// Output: /// - `true` if the click was handled, `false` otherwise. /// /// Details: /// - Calculates clicked index accounting for scroll position. /// - Selects service when clicking on a different item. /// - Toggles restart decision when clicking on the currently selected item. pub(super) fn handle_services_tab_click(mx: u16, my: u16, app: &mut AppState) -> bool { if let crate::state::Modal::Preflight { service_info, service_selected, .. } = &mut app.modal { if service_info.is_empty() { return false; } let Some((content_x, content_y, content_w, content_h)) = app.preflight_content_rect else { return false; }; if mx < content_x || mx >= content_x + content_w || my < content_y || my >= content_y + content_h { return false; } let list_start_offset = 2; let clicked_row_offset = (my - content_y) as usize; if clicked_row_offset < list_start_offset { return false; } let list_clicked_row = clicked_row_offset - list_start_offset; let available_height = content_h.saturating_sub(u16::try_from(list_start_offset).unwrap_or(u16::MAX)) as usize; let total_items = service_info.len(); if total_items == 0 { return false; } let selected_clamped = (*service_selected).min(total_items.saturating_sub(1)); let start_idx = if total_items <= available_height { 0 } else { selected_clamped .saturating_sub(available_height / 2) .min(total_items.saturating_sub(available_height)) }; let end_idx = (start_idx + available_height).min(total_items); let actual_idx = start_idx + list_clicked_row; if actual_idx >= end_idx { return false; } let actual_idx = actual_idx.min(total_items.saturating_sub(1)); if actual_idx == *service_selected { if let Some(service) = service_info.get_mut(actual_idx) { service.restart_decision = match service.restart_decision { ServiceRestartDecision::Restart => ServiceRestartDecision::Defer, ServiceRestartDecision::Defer => ServiceRestartDecision::Restart, }; } } else { *service_selected = actual_idx; } return true; } false } /// Handle scroll events in the Deps tab of the Preflight modal. /// /// What: Process mouse scroll to navigate the dependency list. /// /// Inputs: /// - `m`: Mouse event including scroll direction /// - `app`: Mutable application state containing modal state /// /// Output: /// - `true` if the scroll was handled, `false` otherwise. /// /// Details: /// - Computes display length (headers + dependencies, accounting for folded groups). /// - Handles scroll up/down to move selection. pub(super) fn handle_deps_tab_scroll(m: MouseEvent, app: &mut AppState) -> bool { if let crate::state::Modal::Preflight { items, dependency_info, dep_selected, dep_tree_expanded, .. } = &mut app.modal { // Compute display_items length (headers + dependencies, accounting for folded groups) let mut grouped: HashMap<String, Vec<&crate::state::modal::DependencyInfo>> = HashMap::new(); for dep in dependency_info.iter() { for req_by in &dep.required_by { grouped.entry(req_by.clone()).or_default().push(dep); } } let mut display_len: usize = 0; for pkg_name in items.iter().map(|p| &p.name) { if let Some(pkg_deps) = grouped.get(pkg_name) { display_len += 1; // Header // Count dependencies only if expanded if dep_tree_expanded.contains(pkg_name) { let mut seen_deps = HashSet::new(); for dep in pkg_deps { if seen_deps.insert(dep.name.as_str()) { display_len += 1; } } } } } // Handle mouse scroll to navigate dependency list if display_len > 0 { match m.kind { MouseEventKind::ScrollUp => { if *dep_selected > 0 { *dep_selected -= 1; } return true; } MouseEventKind::ScrollDown => { if *dep_selected < display_len.saturating_sub(1) { *dep_selected += 1; } return true; } _ => {} } } } false } /// Handle scroll events in the Files tab of the Preflight modal. /// /// What: Process mouse scroll to navigate the file list. /// /// Inputs: /// - `m`: Mouse event including scroll direction /// - `app`: Mutable application state containing modal state /// /// Output: /// - `true` if the scroll was handled, `false` otherwise. /// /// Details: /// - Uses existing helper to compute display length. /// - Handles scroll up/down to move selection. pub(super) fn handle_files_tab_scroll(m: MouseEvent, app: &mut AppState) -> bool { if let crate::state::Modal::Preflight { items, file_info, file_selected, file_tree_expanded, .. } = &mut app.modal { match m.kind { MouseEventKind::ScrollUp => { if *file_selected > 0 { *file_selected -= 1; } return true; } MouseEventKind::ScrollDown => { let display_len = crate::events::preflight::compute_file_display_items_len( items, file_info, file_tree_expanded, ); if *file_selected < display_len.saturating_sub(1) { *file_selected += 1; } return true; } _ => {} } } false } /// Handle scroll events in the Summary tab of the Preflight modal. /// /// What: Process mouse scroll to scroll the entire Summary tab content. /// /// Inputs: /// - `m`: Mouse event including scroll direction /// - `app`: Mutable application state containing modal state /// /// Output: /// - `true` if the scroll was handled, `false` otherwise. /// /// Details: /// - Increments/decrements scroll offset for the entire Summary tab content. #[allow(clippy::missing_const_for_fn)] pub(super) fn handle_summary_tab_scroll(m: MouseEvent, app: &mut AppState) -> bool { if let crate::state::Modal::Preflight { summary_scroll, .. } = &mut app.modal { match m.kind { MouseEventKind::ScrollUp => { if *summary_scroll > 0 { *summary_scroll = summary_scroll.saturating_sub(1); } return true; } MouseEventKind::ScrollDown => { *summary_scroll = summary_scroll.saturating_add(1); return true; } _ => {} } } false } /// Handle scroll events in the Services tab of the Preflight modal. /// /// What: Process mouse scroll to navigate the service list. /// /// Inputs: /// - `m`: Mouse event including scroll direction /// - `app`: Mutable application state containing modal state /// /// Output: /// - `true` if the scroll was handled, `false` otherwise. /// /// Details: /// - Handles scroll up/down to move selection. #[allow(clippy::missing_const_for_fn)] pub(super) fn handle_services_tab_scroll(m: MouseEvent, app: &mut AppState) -> bool { if let crate::state::Modal::Preflight { service_info, service_selected, .. } = &mut app.modal { if service_info.is_empty() { return false; } match m.kind { MouseEventKind::ScrollUp => { if *service_selected > 0 { *service_selected -= 1; } return true; } MouseEventKind::ScrollDown => { if *service_selected + 1 < service_info.len() { *service_selected += 1; } return true; } _ => {} } } false }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/install/tests.rs
src/events/install/tests.rs
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use tokio::sync::mpsc; use crate::state::types::{AppMode, NewsBookmark, NewsFeedItem, NewsFeedSource}; use crate::state::{AppState, PackageItem, Source}; use super::handle_install_key; /// What: Produce a baseline `AppState` tailored for install-pane tests without repeating setup boilerplate. /// /// Inputs: /// - None (relies on `Default::default()` for deterministic initial state). /// /// Output: /// - Fresh `AppState` ready for mutation inside individual test cases. /// /// Details: /// - Keeps test bodies concise while ensuring each case starts from a clean copy. fn new_app() -> AppState { AppState::default() } /// What: Create a test package item with specified source. /// /// Inputs: /// - `name`: Package name /// - `source`: Package source (Official or AUR) /// /// Output: /// - `PackageItem` ready for testing /// /// Details: /// - Helper to create test packages with consistent structure fn create_test_package(name: &str, source: Source) -> PackageItem { PackageItem { name: name.into(), version: "1.0.0".into(), description: String::new(), source, popularity: None, out_of_date: None, orphaned: false, } } #[test] /// What: Confirm pressing Enter opens the preflight modal when installs are pending. /// /// Inputs: /// - Install list seeded with a single package and `Enter` key event. /// /// Output: /// - Modal transitions to `Preflight` with one item, `Install` action, and `Summary` tab active. /// /// Details: /// - Uses mock channels to satisfy handler requirements without observing downstream messages. /// - Sets up temporary config directory to ensure `skip_preflight = false` regardless of user config. fn install_enter_opens_confirm_install() { let _guard = crate::theme::test_mutex() .lock() .expect("Test mutex poisoned"); let orig_home = std::env::var_os("HOME"); let orig_xdg = std::env::var_os("XDG_CONFIG_HOME"); let base = std::env::temp_dir().join(format!( "pacsea_test_install_{}_{}", std::process::id(), std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .expect("System time is before UNIX epoch") .as_nanos() )); let cfg = base.join(".config").join("pacsea"); let _ = std::fs::create_dir_all(&cfg); unsafe { std::env::set_var("HOME", base.display().to_string()) }; unsafe { std::env::remove_var("XDG_CONFIG_HOME") }; // Write settings.conf with skip_preflight = false let settings_path = cfg.join("settings.conf"); std::fs::write(&settings_path, "skip_preflight = false\n") .expect("Failed to write test settings file"); let mut app = new_app(); app.install_list = vec![create_test_package("rg", Source::Aur)]; let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let _ = handle_install_key( KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()), &mut app, &dtx, &ptx, &atx, ); match app.modal { crate::state::Modal::Preflight { ref items, action, tab, summary: _, summary_scroll: _, header_chips: _, dependency_info: _, dep_selected: _, dep_tree_expanded: _, deps_error: _, file_info: _, file_selected: _, file_tree_expanded: _, files_error: _, service_info: _, service_selected: _, services_loaded: _, services_error: _, sandbox_info: _, sandbox_selected: _, sandbox_tree_expanded: _, sandbox_loaded: _, sandbox_error: _, selected_optdepends: _, cascade_mode: _, cached_reverse_deps_report: _, } => { assert_eq!(items.len(), 1); assert_eq!(action, crate::state::PreflightAction::Install); assert_eq!(tab, crate::state::PreflightTab::Summary); } _ => panic!("Preflight modal not opened"), } unsafe { if let Some(v) = orig_home { std::env::set_var("HOME", v); } else { std::env::remove_var("HOME"); } if let Some(v) = orig_xdg { std::env::set_var("XDG_CONFIG_HOME", v); } else { std::env::remove_var("XDG_CONFIG_HOME"); } } let _ = std::fs::remove_dir_all(&base); } #[test] /// What: Placeholder ensuring default behaviour still opens the preflight modal when `skip_preflight` remains false. /// /// Inputs: /// - Single official package queued for install with `Enter` key event. /// /// Output: /// - Modal remains `Preflight`, matching current default configuration. /// /// Details: /// - Documents intent for future skip-preflight support while asserting existing flow stays intact. /// - Sets up temporary config directory to ensure `skip_preflight = false` regardless of user config. fn install_enter_bypasses_preflight_with_skip_flag() { let _guard = crate::theme::test_mutex() .lock() .expect("Test mutex poisoned"); let orig_home = std::env::var_os("HOME"); let orig_xdg = std::env::var_os("XDG_CONFIG_HOME"); let base = std::env::temp_dir().join(format!( "pacsea_test_install_skip_{}_{}", std::process::id(), std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .expect("System time is before UNIX epoch") .as_nanos() )); let cfg = base.join(".config").join("pacsea"); let _ = std::fs::create_dir_all(&cfg); unsafe { std::env::set_var("HOME", base.display().to_string()) }; unsafe { std::env::remove_var("XDG_CONFIG_HOME") }; // Write settings.conf with skip_preflight = false let settings_path = cfg.join("settings.conf"); std::fs::write(&settings_path, "skip_preflight = false\n") .expect("Failed to write test settings file"); // Verify the setting is false assert!( !crate::theme::settings().skip_preflight, "skip_preflight unexpectedly true by default" ); let mut app = new_app(); app.install_list = vec![create_test_package( "ripgrep", Source::Official { repo: "core".into(), arch: "x86_64".into(), }, )]; let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let _ = handle_install_key( KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()), &mut app, &dtx, &ptx, &atx, ); // Behavior remains preflight when flag false; placeholder ensures future refactor retains compatibility. match app.modal { crate::state::Modal::Preflight { summary: _, summary_scroll: _, header_chips: _, dependency_info: _, dep_selected: _, dep_tree_expanded: _, file_info: _, file_selected: _, file_tree_expanded: _, files_error: _, service_info: _, service_selected: _, services_loaded: _, cascade_mode: _, .. } => {} _ => panic!("Expected Preflight when skip_preflight=false"), } unsafe { if let Some(v) = orig_home { std::env::set_var("HOME", v); } else { std::env::remove_var("HOME"); } if let Some(v) = orig_xdg { std::env::set_var("XDG_CONFIG_HOME", v); } else { std::env::remove_var("XDG_CONFIG_HOME"); } } let _ = std::fs::remove_dir_all(&base); } #[test] /// What: Ensure loading a bookmark without cached content resets loading state and clears stale content. /// /// Inputs: /// - Bookmark with no cached content or HTML path, stale content pre-set, and loading flag true. /// /// Output: /// - `news_content_loading` becomes false and `news_content` is cleared. /// /// Details: /// - Prevents a stuck loading flag that would block future fetch requests. fn load_news_bookmark_without_cached_content_clears_loading_flag() { let mut app = new_app(); app.app_mode = AppMode::News; app.news_content_loading = true; app.news_content = Some("stale".into()); app.news_bookmarks.clear(); app.news_results.clear(); app.news_content_cache.clear(); let bookmark = NewsBookmark { item: NewsFeedItem { id: "id-1".into(), date: "2024-01-01".into(), title: "Example".into(), summary: None, url: Some("https://example.com/news".into()), source: NewsFeedSource::ArchNews, severity: None, packages: Vec::new(), }, content: None, html_path: None, }; app.news_bookmarks.push(bookmark); let last_idx = app.news_bookmarks.len().saturating_sub(1); app.install_state.select(Some(last_idx)); super::load_news_bookmark(&mut app); assert!(!app.news_content_loading, "loading flag should reset"); assert!( app.news_content.is_none(), "stale content should be cleared when bookmark has no cache, got {:?}", app.news_content ); } #[test] /// What: Verify the Delete key removes the selected install item. /// /// Inputs: /// - Install list with two entries, selection on the first, and `Delete` key event. /// /// Output: /// - List shrinks to one entry, confirming removal logic. /// /// Details: /// - Channels are stubbed to satisfy handler signature while focusing on list mutation. fn install_delete_removes_item() { let mut app = new_app(); app.install_list = vec![ create_test_package("rg", Source::Aur), create_test_package("fd", Source::Aur), ]; app.install_state.select(Some(0)); let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let _ = handle_install_key( KeyEvent::new(KeyCode::Delete, KeyModifiers::empty()), &mut app, &dtx, &ptx, &atx, ); assert_eq!(app.install_list.len(), 1); } #[test] /// What: Verify navigation down (j/Down) moves selection correctly. /// /// Inputs: /// - Install list with three entries, selection on first, and `j` key event. /// /// Output: /// - Selection moves to second item. /// /// Details: /// - Tests basic navigation functionality in install pane. fn install_navigation_down() { let mut app = new_app(); app.install_list = vec![ create_test_package("rg", Source::Aur), create_test_package("fd", Source::Aur), create_test_package("bat", Source::Aur), ]; app.install_state.select(Some(0)); let (dtx, mut drx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let _ = handle_install_key( KeyEvent::new(KeyCode::Char('j'), KeyModifiers::empty()), &mut app, &dtx, &ptx, &atx, ); assert_eq!(app.install_state.selected(), Some(1)); // Drain channel to avoid blocking let _ = drx.try_recv(); } #[test] /// What: Verify navigation up (k/Up) moves selection correctly. /// /// Inputs: /// - Install list with three entries, selection on second, and `k` key event. /// /// Output: /// - Selection moves to first item. /// /// Details: /// - Tests basic navigation functionality in install pane. fn install_navigation_up() { let mut app = new_app(); app.install_list = vec![ create_test_package("rg", Source::Aur), create_test_package("fd", Source::Aur), create_test_package("bat", Source::Aur), ]; app.install_state.select(Some(1)); let (dtx, mut drx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let _ = handle_install_key( KeyEvent::new(KeyCode::Char('k'), KeyModifiers::empty()), &mut app, &dtx, &ptx, &atx, ); assert_eq!(app.install_state.selected(), Some(0)); // Drain channel to avoid blocking let _ = drx.try_recv(); } #[test] /// What: Verify Esc returns focus to Search pane. /// /// Inputs: /// - Install pane focused, Esc key event. /// /// Output: /// - Focus returns to Search pane. /// /// Details: /// - Tests that Esc properly returns focus from Install pane. fn install_esc_returns_to_search() { let mut app = new_app(); app.focus = crate::state::Focus::Install; let (dtx, mut drx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let _ = handle_install_key( KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()), &mut app, &dtx, &ptx, &atx, ); assert_eq!(app.focus, crate::state::Focus::Search); assert!(app.search_normal_mode); // Drain channel to avoid blocking let _ = drx.try_recv(); } #[test] /// What: Verify Enter with empty install list does nothing. /// /// Inputs: /// - Empty install list, Enter key event. /// /// Output: /// - No modal opened, state unchanged. /// /// Details: /// - Tests that Enter is ignored when install list is empty. fn install_enter_with_empty_list() { let mut app = new_app(); app.install_list.clear(); let initial_modal = app.modal.clone(); let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let _ = handle_install_key( KeyEvent::new(KeyCode::Enter, KeyModifiers::empty()), &mut app, &dtx, &ptx, &atx, ); // Modal should remain unchanged when list is empty match (initial_modal, app.modal) { (crate::state::Modal::None, crate::state::Modal::None) => {} _ => panic!("Modal should not change with empty install list"), } } #[test] /// What: Verify clear list functionality removes all items. /// /// Inputs: /// - Install list with multiple entries, clear key event. /// /// Output: /// - Install list is cleared, selection reset. /// /// Details: /// - Tests that clear list keybinding works correctly. fn install_clear_list() { let mut app = new_app(); app.install_list = vec![ create_test_package("rg", Source::Aur), create_test_package("fd", Source::Aur), create_test_package("bat", Source::Aur), ]; app.install_state.select(Some(1)); // Simulate clear key (using 'c' as example, actual key depends on keymap) // For this test, we'll directly test the clear functionality app.install_list.clear(); app.install_state.select(None); app.install_dirty = true; app.install_list_deps.clear(); app.install_list_files.clear(); app.deps_resolving = false; app.files_resolving = false; assert!(app.install_list.is_empty()); assert_eq!(app.install_state.selected(), None); assert!(app.install_dirty); } #[test] /// What: Verify pane find mode can be entered with '/' key. /// /// Inputs: /// - Install pane focused, '/' key event. /// /// Output: /// - Pane find mode is activated. /// /// Details: /// - Tests that '/' enters find mode in install pane. fn install_pane_find_mode_entry() { let mut app = new_app(); assert!(app.pane_find.is_none()); let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let _ = handle_install_key( KeyEvent::new(KeyCode::Char('/'), KeyModifiers::empty()), &mut app, &dtx, &ptx, &atx, ); assert!(app.pane_find.is_some()); assert_eq!( app.pane_find.as_ref().expect("pane_find should be Some"), "" ); } #[test] /// What: Verify pane find mode can be cancelled with Esc. /// /// Inputs: /// - Pane find mode active, Esc key event. /// /// Output: /// - Pane find mode is cancelled. /// /// Details: /// - Tests that Esc cancels find mode. fn install_pane_find_mode_cancel() { let mut app = new_app(); app.pane_find = Some("test".to_string()); let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let _ = handle_install_key( KeyEvent::new(KeyCode::Esc, KeyModifiers::empty()), &mut app, &dtx, &ptx, &atx, ); assert!(app.pane_find.is_none()); } #[test] /// What: Verify deletion of last item clears selection. /// /// Inputs: /// - Install list with one entry, selection on that entry, Delete key event. /// /// Output: /// - List is empty, selection is None. /// /// Details: /// - Tests edge case of deleting the only item in the list. fn install_delete_last_item() { let mut app = new_app(); app.install_list = vec![create_test_package("rg", Source::Aur)]; app.install_state.select(Some(0)); let (dtx, _drx) = mpsc::unbounded_channel::<PackageItem>(); let (ptx, _prx) = mpsc::unbounded_channel::<PackageItem>(); let (atx, _arx) = mpsc::unbounded_channel::<PackageItem>(); let _ = handle_install_key( KeyEvent::new(KeyCode::Delete, KeyModifiers::empty()), &mut app, &dtx, &ptx, &atx, ); assert!(app.install_list.is_empty()); assert_eq!(app.install_state.selected(), None); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/install/preflight.rs
src/events/install/preflight.rs
use crate::state::AppState; /// What: Load cached dependencies filtered by item names. /// /// Inputs: /// - `app`: Application state reference /// - `item_names`: Set of package names to filter dependencies by /// /// Output: /// - Vector of filtered dependency info, or empty if cache unavailable /// /// Details: /// - Filters cached dependencies to only those required by current items /// - Returns empty vector if cache is resolving or empty fn load_cached_dependencies( app: &AppState, item_names: &std::collections::HashSet<String>, ) -> Vec<crate::state::modal::DependencyInfo> { if app.deps_resolving || app.install_list_deps.is_empty() { tracing::debug!("[Install] No cached dependencies available"); return Vec::new(); } let filtered: Vec<crate::state::modal::DependencyInfo> = app .install_list_deps .iter() .filter(|dep| { dep.required_by .iter() .any(|req_by| item_names.contains(req_by)) }) .cloned() .collect(); if filtered.is_empty() { tracing::debug!("[Install] Cached dependencies exist but none match current items"); Vec::new() } else { tracing::debug!( "[Install] Using {} cached dependencies (filtered from {} total)", filtered.len(), app.install_list_deps.len() ); filtered } } /// What: Load cached file information. /// /// Inputs: /// - `app`: Application state reference /// - `items`: Package items for logging /// /// Output: /// - Vector of cached file info, or empty if cache unavailable /// /// Details: /// - Returns cached files if available and not currently resolving fn load_cached_files( app: &AppState, items: &[crate::state::types::PackageItem], ) -> Vec<crate::state::modal::PackageFileInfo> { tracing::debug!( "[Install] Checking file cache: resolving={}, install_list_files={}, items={:?}", app.files_resolving, app.install_list_files.len(), items.iter().map(|i| &i.name).collect::<Vec<_>>() ); if app.files_resolving || app.install_list_files.is_empty() { tracing::debug!( "[Install] No cached files available (resolving={}, empty={})", app.files_resolving, app.install_list_files.is_empty() ); return Vec::new(); } tracing::debug!( "[Install] Using {} cached file entries: {:?}", app.install_list_files.len(), app.install_list_files .iter() .map(|f| &f.name) .collect::<Vec<_>>() ); for file_info in &app.install_list_files { tracing::debug!( "[Install] Cached file entry: Package '{}' - total={}, new={}, changed={}, removed={}, config={}", file_info.name, file_info.total_count, file_info.new_count, file_info.changed_count, file_info.removed_count, file_info.config_count ); } app.install_list_files.clone() } /// What: Load cached services and check if services are loaded. /// /// Inputs: /// - `app`: Application state reference /// /// Output: /// - Tuple of (cached services, whether services are loaded) /// /// Details: /// - Checks both in-memory cache and cache file to determine loaded state fn load_cached_services(app: &AppState) -> (Vec<crate::state::modal::ServiceImpact>, bool) { let cached_services = if !app.services_resolving && !app.install_list_services.is_empty() { tracing::debug!( "[Install] Using {} cached services", app.install_list_services.len() ); app.install_list_services.clone() } else { tracing::debug!("[Install] No cached services available"); Vec::new() }; let services_cache_loaded = if app.install_list.is_empty() { false } else { let signature = crate::app::services_cache::compute_signature(&app.install_list); let loaded = crate::app::services_cache::load_cache(&app.services_cache_path, &signature).is_some(); tracing::debug!( "[Install] Services cache check: {} (signature match: {})", if loaded { "found" } else { "not found" }, signature.len() ); loaded }; let services_loaded = services_cache_loaded || !cached_services.is_empty(); (cached_services, services_loaded) } /// What: Restore user restart decisions from pending service plan. /// /// Inputs: /// - `app`: Application state reference /// - `services`: Mutable vector of service impacts to update /// /// Output: /// - No return value; modifies services in place /// /// Details: /// - Applies saved restart decisions from `pending_service_plan` to services fn restore_service_decisions(app: &AppState, services: &mut [crate::state::modal::ServiceImpact]) { if app.pending_service_plan.is_empty() || services.is_empty() { return; } let decision_map: std::collections::HashMap< String, crate::state::modal::ServiceRestartDecision, > = app .pending_service_plan .iter() .map(|s| (s.unit_name.clone(), s.restart_decision)) .collect(); for service in services.iter_mut() { if let Some(&saved_decision) = decision_map.get(&service.unit_name) { service.restart_decision = saved_decision; } } } /// What: Load cached sandbox info and check if sandbox is loaded. /// /// Inputs: /// - `app`: Application state reference /// - `items`: Package items for cache signature computation /// /// Output: /// - Tuple of (cached sandbox info, whether sandbox is loaded) /// /// Details: /// - Checks both in-memory cache and cache file to determine loaded state fn load_cached_sandbox( app: &AppState, items: &[crate::state::types::PackageItem], ) -> (Vec<crate::logic::sandbox::SandboxInfo>, bool) { tracing::debug!( "[Install] Checking sandbox cache: resolving={}, install_list_sandbox={}, items={:?}", app.sandbox_resolving, app.install_list_sandbox.len(), items.iter().map(|i| &i.name).collect::<Vec<_>>() ); let cached_sandbox = if !app.sandbox_resolving && !app.install_list_sandbox.is_empty() { tracing::debug!( "[Install] Using {} cached sandbox entries: {:?}", app.install_list_sandbox.len(), app.install_list_sandbox .iter() .map(|s| &s.package_name) .collect::<Vec<_>>() ); app.install_list_sandbox.clone() } else { tracing::debug!( "[Install] No cached sandbox available (resolving={}, empty={})", app.sandbox_resolving, app.install_list_sandbox.is_empty() ); Vec::new() }; let sandbox_cache_loaded = if items.is_empty() { false } else { let signature = crate::app::sandbox_cache::compute_signature(items); let cache_result = crate::app::sandbox_cache::load_cache(&app.sandbox_cache_path, &signature); tracing::debug!( "[Install] Sandbox cache file check: signature={:?}, found={}, cached_entries={}", signature, cache_result.is_some(), cache_result.as_ref().map_or(0, Vec::len) ); if let Some(ref cached) = cache_result { tracing::debug!( "[Install] Cached sandbox packages: {:?}", cached.iter().map(|s| &s.package_name).collect::<Vec<_>>() ); } cache_result.is_some() }; let sandbox_loaded = sandbox_cache_loaded || !cached_sandbox.is_empty(); tracing::debug!( "[Install] Final sandbox state: cached_sandbox={}, sandbox_cache_loaded={}, sandbox_loaded={}", cached_sandbox.len(), sandbox_cache_loaded, sandbox_loaded ); (cached_sandbox, sandbox_loaded) } /// What: Create minimal summary data for immediate display. /// /// Inputs: /// - `app`: Application state reference /// - `items`: Package items to create summary for /// /// Output: /// - Tuple of (summary data, header chips) /// /// Details: /// - Creates minimal summary without blocking pacman calls /// - Full summary computed asynchronously after modal opens fn create_minimal_summary( app: &AppState, items: &[crate::state::types::PackageItem], ) -> ( crate::state::modal::PreflightSummaryData, crate::state::modal::PreflightHeaderChips, ) { let aur_count = items .iter() .filter(|p| matches!(p.source, crate::state::Source::Aur)) .count(); tracing::debug!( "[Install] Creating minimal summary for {} packages ({} AUR)", items.len(), aur_count ); let has_aur = aur_count > 0; let risk_score = if has_aur { 2 } else { 0 }; let risk_level = if has_aur { crate::state::modal::RiskLevel::Medium } else { crate::state::modal::RiskLevel::Low }; let aur_warning = if has_aur { vec![crate::i18n::t( app, "app.modals.preflight.summary.aur_packages_included", )] } else { vec![] }; let aur_note = if has_aur { vec![crate::i18n::t( app, "app.modals.preflight.summary.aur_packages_present", )] } else { vec![] }; let minimal_summary = crate::state::modal::PreflightSummaryData { packages: items .iter() .map(|item| crate::state::modal::PreflightPackageSummary { name: item.name.clone(), source: item.source.clone(), installed_version: None, target_version: item.version.clone(), is_downgrade: false, is_major_bump: false, download_bytes: None, install_delta_bytes: None, notes: vec![], }) .collect(), package_count: items.len(), aur_count, download_bytes: 0, install_delta_bytes: 0, risk_score, risk_level, risk_reasons: aur_warning.clone(), major_bump_packages: vec![], core_system_updates: vec![], pacnew_candidates: 0, pacsave_candidates: 0, config_warning_packages: vec![], service_restart_units: vec![], summary_warnings: aur_warning, summary_notes: aur_note, }; let minimal_header = crate::state::modal::PreflightHeaderChips { package_count: items.len(), download_bytes: 0, install_delta_bytes: 0, aur_count, risk_score, risk_level, }; (minimal_summary, minimal_header) } /// What: Trigger background resolution for missing data. /// /// Inputs: /// - `app`: Mutable application state /// - `items`: Package items to resolve /// - `dependency_info`: Current dependency info (empty triggers resolution) /// - `cached_files`: Current file info (empty triggers resolution) /// - `services_loaded`: Whether services are already loaded /// - `cached_sandbox`: Current sandbox info (empty triggers resolution) /// /// Output: /// - No return value; sets resolution flags in app state /// /// Details: /// - Triggers background resolution for dependencies, files, services, and sandbox /// - Only triggers if cache is empty or not loaded fn trigger_background_resolution( app: &mut AppState, items: &[crate::state::types::PackageItem], dependency_info: &[crate::state::modal::DependencyInfo], cached_files: &[crate::state::modal::PackageFileInfo], services_loaded: bool, cached_sandbox: &[crate::logic::sandbox::SandboxInfo], ) { if dependency_info.is_empty() { if app.deps_resolving { tracing::debug!( "[Preflight] NOT setting preflight_deps_resolving (global deps_resolving already in progress, will reuse result)" ); } else { tracing::debug!( "[Preflight] Setting preflight_deps_resolving=true for {} items (cache empty)", items.len() ); app.preflight_deps_items = Some(( items.to_vec(), crate::state::modal::PreflightAction::Install, )); app.preflight_deps_resolving = true; } } else { tracing::debug!( "[Preflight] NOT setting preflight_deps_resolving (cache has {} deps)", dependency_info.len() ); } if cached_files.is_empty() { if app.files_resolving { tracing::debug!( "[Preflight] NOT setting preflight_files_resolving (global files_resolving already in progress, will reuse result)" ); } else { tracing::debug!( "[Preflight] Setting preflight_files_resolving=true for {} items (cache empty)", items.len() ); app.preflight_files_items = Some(items.to_vec()); app.preflight_files_resolving = true; } } else { tracing::debug!( "[Preflight] NOT setting preflight_files_resolving (cache has {} files)", cached_files.len() ); } if services_loaded { tracing::debug!("[Preflight] NOT setting preflight_services_resolving (already loaded)"); } else if app.services_resolving { tracing::debug!( "[Preflight] NOT setting preflight_services_resolving (global services_resolving already in progress, will reuse result)" ); } else { tracing::debug!( "[Preflight] Setting preflight_services_resolving=true for {} items (not loaded)", items.len() ); app.preflight_services_items = Some(items.to_vec()); app.preflight_services_resolving = true; } if cached_sandbox.is_empty() { let aur_items: Vec<_> = items .iter() .filter(|p| matches!(p.source, crate::state::Source::Aur)) .cloned() .collect(); if aur_items.is_empty() { tracing::debug!("[Preflight] NOT setting preflight_sandbox_resolving (no AUR items)"); } else if app.sandbox_resolving { tracing::debug!( "[Preflight] NOT setting preflight_sandbox_resolving (global sandbox_resolving already in progress, will reuse result)" ); } else { tracing::debug!( "[Preflight] Setting preflight_sandbox_resolving=true for {} AUR items (cache empty)", aur_items.len() ); app.preflight_sandbox_items = Some(aur_items); app.preflight_sandbox_resolving = true; } } else { tracing::debug!( "[Preflight] NOT setting preflight_sandbox_resolving (cache has {} sandbox entries)", cached_sandbox.len() ); } } /// What: Open Preflight modal for install action with cached data. /// /// Inputs: /// - `app`: Mutable application state /// /// Output: /// - No return value; sets app.modal to Preflight with Install action /// /// Details: /// - Loads cached dependencies, files, services, and sandbox info /// - Creates minimal summary for immediate display /// - Triggers background resolution for missing data pub fn open_preflight_install_modal(app: &mut AppState) { tracing::info!( "[Install] Opening preflight modal for {} packages", app.install_list.len() ); let start_time = std::time::Instant::now(); let item_count = app.install_list.len(); let items = app.install_list.clone(); let cache_start = std::time::Instant::now(); let item_names: std::collections::HashSet<String> = items.iter().map(|i| i.name.clone()).collect(); let cached_deps = load_cached_dependencies(app, &item_names); let cached_files = load_cached_files(app, &items); let (cached_services, services_loaded) = load_cached_services(app); let (cached_sandbox, sandbox_loaded) = load_cached_sandbox(app, &items); tracing::debug!("[Install] Cache loading took {:?}", cache_start.elapsed()); let mut final_services = cached_services; restore_service_decisions(app, &mut final_services); let summary_start = std::time::Instant::now(); let (minimal_summary, minimal_header) = create_minimal_summary(app, &items); tracing::debug!( "[Install] Minimal summary creation took {:?}", summary_start.elapsed() ); let modal_set_start = std::time::Instant::now(); let dependency_info = if cached_deps.is_empty() { tracing::debug!( "[Preflight] Cache empty, will trigger background dependency resolution for {} packages", items.len() ); Vec::new() } else { cached_deps }; app.preflight_cancelled .store(false, std::sync::atomic::Ordering::Relaxed); app.preflight_summary_items = Some((items.clone(), crate::state::PreflightAction::Install)); // Don't set preflight_summary_resolving=true here - let the tick handler trigger it // This prevents the tick handler from being blocked by the flag already being set tracing::debug!( "[Preflight] Queued summary computation for {} items", items.len() ); trigger_background_resolution( app, &items, &dependency_info, &cached_files, services_loaded, &cached_sandbox, ); app.modal = crate::state::Modal::Preflight { items, action: crate::state::PreflightAction::Install, tab: crate::state::PreflightTab::Summary, summary: Some(Box::new(minimal_summary)), summary_scroll: 0, header_chips: minimal_header, dependency_info, dep_selected: 0, dep_tree_expanded: std::collections::HashSet::new(), deps_error: None, file_info: cached_files, file_selected: 0, file_tree_expanded: std::collections::HashSet::new(), files_error: None, service_info: final_services, service_selected: 0, services_loaded, services_error: None, sandbox_info: cached_sandbox, sandbox_selected: 0, sandbox_tree_expanded: std::collections::HashSet::new(), sandbox_loaded, sandbox_error: None, selected_optdepends: std::collections::HashMap::new(), cascade_mode: app.remove_cascade_mode, cached_reverse_deps_report: None, }; tracing::debug!( "[Install] Modal state set in {:?}", modal_set_start.elapsed() ); tracing::info!( "[Install] Preflight modal opened successfully in {:?} ({} packages)", start_time.elapsed(), item_count ); app.remove_preflight_summary.clear(); } /// What: Open Preflight modal for remove action. /// /// Inputs: /// - `app`: Mutable application state /// /// Output: /// - No return value; sets app.modal to Preflight with Remove action /// /// Details: /// - Opens modal immediately without blocking. Reverse dependency resolution can be triggered /// manually via the Dependencies tab or will be computed when user tries to proceed. /// This avoids blocking the UI when opening the modal. pub fn open_preflight_remove_modal(app: &mut AppState) { let items = app.remove_list.clone(); let item_count = items.len(); // Reset cancellation flag when opening modal app.preflight_cancelled .store(false, std::sync::atomic::Ordering::Relaxed); // Queue summary computation in background - modal will render with None initially app.preflight_summary_items = Some((items.clone(), crate::state::PreflightAction::Remove)); // Don't set preflight_summary_resolving=true here - let the tick handler trigger it // This prevents the tick handler from being blocked by the flag already being set tracing::debug!( "[Preflight] Queued summary computation for {} items (remove)", items.len() ); app.pending_service_plan.clear(); // Open modal immediately with empty dependency_info to avoid blocking UI // Dependency info can be resolved later via Dependencies tab or when proceeding app.modal = crate::state::Modal::Preflight { items, action: crate::state::PreflightAction::Remove, tab: crate::state::PreflightTab::Summary, summary: None, // Will be populated when background computation completes summary_scroll: 0, header_chips: crate::state::modal::PreflightHeaderChips { package_count: item_count, download_bytes: 0, install_delta_bytes: 0, aur_count: 0, risk_score: 0, risk_level: crate::state::modal::RiskLevel::Low, }, dependency_info: Vec::new(), // Will be populated when user switches to Deps tab or proceeds dep_selected: 0, dep_tree_expanded: std::collections::HashSet::new(), deps_error: None, file_info: Vec::new(), file_selected: 0, file_tree_expanded: std::collections::HashSet::new(), files_error: None, service_info: Vec::new(), service_selected: 0, services_loaded: false, services_error: None, sandbox_info: Vec::new(), sandbox_selected: 0, sandbox_tree_expanded: std::collections::HashSet::new(), sandbox_loaded: false, sandbox_error: None, selected_optdepends: std::collections::HashMap::new(), cascade_mode: app.remove_cascade_mode, cached_reverse_deps_report: None, }; app.remove_preflight_summary = Vec::new(); // Will be populated when dependencies are resolved app.toast_message = Some(crate::i18n::t(app, "app.toasts.preflight_remove_list")); } /// What: Open Preflight modal for downgrade action. /// /// Inputs: /// - `app`: Mutable application state /// /// Output: /// - No return value; sets app.modal to Preflight with Downgrade action /// /// Details: /// - Opens modal immediately without blocking. Similar to remove modal, but for downgrade operations. pub fn open_preflight_downgrade_modal(app: &mut AppState) { let items = app.downgrade_list.clone(); let item_count = items.len(); // Reset cancellation flag when opening modal app.preflight_cancelled .store(false, std::sync::atomic::Ordering::Relaxed); // Queue summary computation in background - modal will render with None initially app.preflight_summary_items = Some((items.clone(), crate::state::PreflightAction::Downgrade)); // Don't set preflight_summary_resolving=true here - let the tick handler trigger it // This prevents the tick handler from being blocked by the flag already being set tracing::debug!( "[Preflight] Queued summary computation for {} items (downgrade)", items.len() ); app.pending_service_plan.clear(); // Open modal immediately with empty dependency_info to avoid blocking UI // Dependency info can be resolved later via Dependencies tab or when proceeding app.modal = crate::state::Modal::Preflight { items, action: crate::state::PreflightAction::Downgrade, tab: crate::state::PreflightTab::Summary, summary: None, // Will be populated when background computation completes summary_scroll: 0, header_chips: crate::state::modal::PreflightHeaderChips { package_count: item_count, download_bytes: 0, install_delta_bytes: 0, aur_count: 0, risk_score: 0, risk_level: crate::state::modal::RiskLevel::Low, }, dependency_info: Vec::new(), // Will be populated when user switches to Deps tab or proceeds dep_selected: 0, dep_tree_expanded: std::collections::HashSet::new(), deps_error: None, file_info: Vec::new(), file_selected: 0, file_tree_expanded: std::collections::HashSet::new(), files_error: None, service_info: Vec::new(), service_selected: 0, services_loaded: false, services_error: None, sandbox_info: Vec::new(), sandbox_selected: 0, sandbox_tree_expanded: std::collections::HashSet::new(), sandbox_loaded: false, sandbox_error: None, selected_optdepends: std::collections::HashMap::new(), cascade_mode: app.remove_cascade_mode, cached_reverse_deps_report: None, }; app.toast_message = Some(crate::i18n::t(app, "app.toasts.preflight_downgrade_list")); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/events/install/mod.rs
src/events/install/mod.rs
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers}; use tokio::sync::mpsc; use crate::sources::parse_news_html; use crate::state::{AppState, PackageItem}; use super::utils::{ find_in_install, matches_any, refresh_install_details, refresh_remove_details, refresh_selected_details, }; /// Preflight modal opening functions for install operations. mod preflight; #[cfg(test)] mod tests; pub use preflight::{ open_preflight_downgrade_modal, open_preflight_install_modal, open_preflight_remove_modal, }; /// What: Handle `pane_next` navigation (cycles through panes). fn handle_pane_next_navigation( app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, preview_tx: &mpsc::UnboundedSender<PackageItem>, ) { // Desired cycle: Search -> Downgrade -> Remove -> Recent -> Search if app.installed_only_mode { match app.right_pane_focus { crate::state::RightPaneFocus::Downgrade => { // Downgrade -> Remove (stay in Install) app.right_pane_focus = crate::state::RightPaneFocus::Remove; if app.remove_state.selected().is_none() && !app.remove_list.is_empty() { app.remove_state.select(Some(0)); } refresh_remove_details(app, details_tx); return; } crate::state::RightPaneFocus::Remove => { // Remove -> Recent if app.history_state.selected().is_none() && !app.recent.is_empty() { app.history_state.select(Some(0)); } app.focus = crate::state::Focus::Recent; crate::ui::helpers::trigger_recent_preview(app, preview_tx); return; } crate::state::RightPaneFocus::Install => {} } } // Not in installed-only: Install -> Recent if app.history_state.selected().is_none() && !app.recent.is_empty() { app.history_state.select(Some(0)); } app.focus = crate::state::Focus::Recent; crate::ui::helpers::trigger_recent_preview(app, preview_tx); } /// What: Handle Left arrow navigation (moves focus left). fn handle_left_arrow_navigation( app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, ) { // In installed-only mode, follow reverse: Remove -> Downgrade -> Search if app.installed_only_mode { match app.right_pane_focus { crate::state::RightPaneFocus::Remove => { // Move to Downgrade subpane and keep Install focus app.right_pane_focus = crate::state::RightPaneFocus::Downgrade; if app.downgrade_state.selected().is_none() && !app.downgrade_list.is_empty() { app.downgrade_state.select(Some(0)); } super::utils::refresh_downgrade_details(app, details_tx); } crate::state::RightPaneFocus::Downgrade => { // Downgrade -> Search app.focus = crate::state::Focus::Search; refresh_selected_details(app, details_tx); } crate::state::RightPaneFocus::Install => { // Normal mode: Install -> Search app.focus = crate::state::Focus::Search; refresh_selected_details(app, details_tx); } } } else { // Normal mode: Install -> Search app.focus = crate::state::Focus::Search; refresh_selected_details(app, details_tx); } } /// What: Ensure bookmark selection is valid in news mode. fn ensure_news_bookmark_selection(app: &mut AppState) { let len = app.news_bookmarks.len(); if len == 0 { app.install_state.select(None); return; } let sel = app .install_state .selected() .filter(|i| *i < len) .unwrap_or(0); app.install_state.select(Some(sel)); } /// What: Move bookmark selection up or down in news mode. fn move_news_bookmark_selection(app: &mut AppState, down: bool) { ensure_news_bookmark_selection(app); let len = app.news_bookmarks.len(); if len == 0 { return; } let current = app.install_state.selected().unwrap_or(0); let next = if down { std::cmp::min(current + 1, len.saturating_sub(1)) } else { current.saturating_sub(1) }; app.install_state.select(Some(next)); } /// What: Delete the currently selected news bookmark and its cached file. fn delete_news_bookmark_at_selection(app: &mut AppState) { ensure_news_bookmark_selection(app); let Some(sel) = app.install_state.selected() else { return; }; if let Some(removed) = app.remove_news_bookmark_at(sel) && let Some(path) = removed.html_path { let _ = std::fs::remove_file(path); } // Adjust selection let len = app.news_bookmarks.len(); if len == 0 { app.install_state.select(None); } else if sel >= len { app.install_state.select(Some(len.saturating_sub(1))); } } /// What: Load the selected news bookmark into the details pane from local cache. fn load_news_bookmark(app: &mut AppState) { ensure_news_bookmark_selection(app); let Some(sel) = app.install_state.selected() else { return; }; let Some(bookmark) = app.news_bookmarks.get(sel).cloned() else { return; }; // Ensure the bookmarked item is present in results for metadata rendering let idx = if let Some(pos) = app .news_results .iter() .position(|it| it.id == bookmark.item.id) { pos } else { app.news_results.insert(0, bookmark.item.clone()); 0 }; app.news_selected = idx; app.news_list_state.select(Some(idx)); // Load content from html if available, else fallback to cached content let mut content = bookmark.content.clone(); if content.is_none() && let Some(path) = bookmark.html_path.as_ref() && let Ok(html) = std::fs::read_to_string(path) { content = Some(parse_news_html(&html)); } if let Some(url) = bookmark.item.url.as_ref() { if let Some(ref c) = content { app.news_content_cache.insert(url.clone(), c.clone()); } app.details.url.clone_from(url); } else { app.details.url.clear(); } app.news_content = content; app.news_content_loading = false; } /// What: Handle key events inside the news bookmarks pane. fn handle_news_bookmarks_key(ke: KeyEvent, app: &mut AppState) -> bool { match ke.code { KeyCode::Char('j') | KeyCode::Down => { move_news_bookmark_selection(app, true); } KeyCode::Char('k') | KeyCode::Up => { move_news_bookmark_selection(app, false); } code if matches_any(&ke, &app.keymap.pane_next) && code == ke.code => { if app.history_state.selected().is_none() && !app.news_recent_values().is_empty() { app.history_state.select(Some(0)); } app.focus = crate::state::Focus::Recent; } KeyCode::Enter => { load_news_bookmark(app); } KeyCode::Delete => { delete_news_bookmark_at_selection(app); } KeyCode::Esc | KeyCode::Left => { app.focus = crate::state::Focus::Search; app.search_normal_mode = true; } KeyCode::Right => { app.focus = crate::state::Focus::Recent; } _ => {} } false } /// What: Handle Right arrow navigation (moves focus right). fn handle_right_arrow_navigation( app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, preview_tx: &mpsc::UnboundedSender<PackageItem>, ) { // In installed-only mode, follow: Downgrade -> Remove -> Recent; else wrap to Recent if app.installed_only_mode { match app.right_pane_focus { crate::state::RightPaneFocus::Downgrade => { app.right_pane_focus = crate::state::RightPaneFocus::Remove; if app.remove_state.selected().is_none() && !app.remove_list.is_empty() { app.remove_state.select(Some(0)); } refresh_remove_details(app, details_tx); } crate::state::RightPaneFocus::Remove => { // Wrap-around to Recent from rightmost subpane if app.history_state.selected().is_none() && !app.recent.is_empty() { app.history_state.select(Some(0)); } app.focus = crate::state::Focus::Recent; crate::ui::helpers::trigger_recent_preview(app, preview_tx); } crate::state::RightPaneFocus::Install => { // Normal Install subpane: wrap directly to Recent if app.history_state.selected().is_none() && !app.recent.is_empty() { app.history_state.select(Some(0)); } app.focus = crate::state::Focus::Recent; crate::ui::helpers::trigger_recent_preview(app, preview_tx); } } } else { // Normal mode: Install -> Recent (wrap) if app.history_state.selected().is_none() && !app.recent.is_empty() { app.history_state.select(Some(0)); } app.focus = crate::state::Focus::Recent; crate::ui::helpers::trigger_recent_preview(app, preview_tx); } } /// What: Handle key events while the Install pane (right column) is focused. /// /// Inputs: /// - `ke`: Key event received from the terminal /// - `app`: Mutable application state (selection, lists, pane focus) /// - `details_tx`: Channel to request package details for the focused item /// - `preview_tx`: Channel to request preview details (used for some focus changes) /// - `_add_tx`: Channel for adding items (not used directly in Install handler) /// /// Output: /// - `true` to request application exit (e.g., Ctrl+C); `false` to continue. /// /// Details: /// - In-pane find: `/` enters find mode; typing edits the pattern; Enter jumps to next match; /// Esc cancels. Find matches against name/description (Install) or name-only (Remove/Downgrade). /// - Navigation: `j/k` and `Down/Up` move selection in the active subpane. Behavior adapts to /// installed-only mode (`app.installed_only_mode`) and current `right_pane_focus`: /// - Normal mode: selection moves in Install list only. /// - Installed-only: selection moves in Downgrade/Remove/Install subpane depending on focus. /// - Pane cycling: Configured `pane_next` chord cycles focus across panes. In installed-only mode /// it cycles Search → Downgrade → Remove → Recent → Search; otherwise Search → Install → Recent. /// - Arrow focus: Left/Right move focus between Search/Install/Recent (and subpanes when installed-only). /// - Deletion: `Delete` (or configured `install_remove`) removes the selected entry from the active /// list (Install/Remove/Downgrade) and updates selection and details. /// - Clear list: Configured `install_clear` clears the respective list (or all in normal mode), /// and resets selection. /// - Enter: /// - Normal mode with non-empty Install list: opens `Modal::ConfirmInstall` for batch install. /// - Installed-only Remove focus with non-empty list: opens `Modal::ConfirmRemove`. /// - Installed-only Downgrade focus with non-empty list: runs `downgrade` tool (or dry-run). /// - Esc: Returns focus to Search and refreshes the selected result's details. pub fn handle_install_key( ke: KeyEvent, app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, preview_tx: &mpsc::UnboundedSender<PackageItem>, _add_tx: &mpsc::UnboundedSender<PackageItem>, ) -> bool { if matches!(app.app_mode, crate::state::types::AppMode::News) { return handle_news_bookmarks_key(ke, app); } if ke.code == KeyCode::Char('c') && ke.modifiers.contains(KeyModifiers::CONTROL) { return true; } // Pane-search mode first if app.pane_find.is_some() && handle_pane_find_mode(ke, app, details_tx) { return false; } // Handle Shift+char keybinds (menus, import, export, updates, status) that work in all modes if crate::events::search::handle_shift_keybinds(&ke, app) { return false; } let km = &app.keymap; // Match helper that treats Shift+<char> from config as equivalent to uppercase char without Shift from terminal let matches_any = |list: &Vec<crate::theme::KeyChord>| { list.iter().any(|c| { if (c.code, c.mods) == (ke.code, ke.modifiers) { return true; } match (c.code, ke.code) { ( crossterm::event::KeyCode::Char(cfg_ch), crossterm::event::KeyCode::Char(ev_ch), ) => { let cfg_has_shift = c.mods.contains(crossterm::event::KeyModifiers::SHIFT); let ev_has_no_shift = !ke.modifiers.contains(crossterm::event::KeyModifiers::SHIFT); cfg_has_shift && ev_has_no_shift && ev_ch == cfg_ch.to_ascii_uppercase() } _ => false, } }) }; match ke.code { KeyCode::Char('j') => { handle_navigation_down(app, details_tx); } KeyCode::Char('k') => { handle_navigation_up(app, details_tx); } KeyCode::Char('/') => { app.pane_find = Some(String::new()); } KeyCode::Enter => { handle_enter_key(app); } KeyCode::Esc => { app.focus = crate::state::Focus::Search; // Activate Search Normal mode when returning with Esc app.search_normal_mode = true; refresh_selected_details(app, details_tx); } code if matches_any(&km.pane_next) && code == ke.code => { if matches!(app.app_mode, crate::state::types::AppMode::News) { // Bookmarks -> History app.focus = crate::state::Focus::Recent; } else { handle_pane_next_navigation(app, details_tx, preview_tx); } } KeyCode::Left => { if matches!(app.app_mode, crate::state::types::AppMode::News) { app.focus = crate::state::Focus::Search; } else { handle_left_arrow_navigation(app, details_tx); } } KeyCode::Right => { if matches!(app.app_mode, crate::state::types::AppMode::News) { app.focus = crate::state::Focus::Recent; } else { handle_right_arrow_navigation(app, details_tx, preview_tx); } } KeyCode::Delete if !ke.modifiers.contains(KeyModifiers::SHIFT) => { handle_delete_item(app, details_tx); } code if matches_any(&km.install_clear) && code == ke.code => { handle_clear_list(app); } code if matches_any(&km.install_remove) && code == ke.code => { handle_delete_item(app, details_tx); } KeyCode::Up => { handle_navigation_up(app, details_tx); } KeyCode::Down => { handle_navigation_down(app, details_tx); } _ => {} } false } /// What: Handle key events while in pane-find mode. /// /// Inputs: /// - `ke`: Key event received from the terminal /// - `app`: Mutable application state /// - `details_tx`: Channel to request package details /// /// Output: /// - `true` if the event was handled and should return early; `false` otherwise /// /// Details: /// - Handles Enter (jump to next match), Esc (cancel), Backspace (delete char), and Char (append char). fn handle_pane_find_mode( ke: KeyEvent, app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>, ) -> bool { match ke.code { KeyCode::Enter => { find_in_install(app, true); refresh_install_details(app, details_tx); } KeyCode::Esc => { app.pane_find = None; } KeyCode::Backspace => { if let Some(buf) = &mut app.pane_find { buf.pop(); } } KeyCode::Char(ch) => { if let Some(buf) = &mut app.pane_find { buf.push(ch); } } _ => {} } true } /// What: Handle Enter key to trigger install/remove/downgrade actions. /// /// Inputs: /// - `app`: Mutable application state /// /// Output: /// - No return value; modifies app state to open modals or trigger actions /// /// Details: /// - Normal mode with non-empty Install list: opens Preflight modal or skips to direct install /// - Installed-only Remove focus: opens Preflight modal or skips to direct remove /// - Installed-only Downgrade focus: runs downgrade tool fn handle_enter_key(app: &mut AppState) { // Never trigger preflight when SystemUpdate or OptionalDeps modals are active // These modals use spawn_shell_commands_in_terminal which bypasses preflight let skip_preflight_for_modals = matches!( app.modal, crate::state::Modal::SystemUpdate { .. } | crate::state::Modal::OptionalDeps { .. } ); let skip = crate::theme::settings().skip_preflight || skip_preflight_for_modals; if !app.installed_only_mode && !app.install_list.is_empty() { if skip { // Direct install - check for reinstalls first, then batch updates // First, check if we're installing packages that are already installed (reinstall scenario) // BUT exclude packages that have updates available (those should go through normal update flow) let installed_set = crate::logic::deps::get_installed_packages(); let provided_set = crate::logic::deps::get_provided_packages(&installed_set); let upgradable_set = crate::logic::deps::get_upgradable_packages(); let installed_packages: Vec<crate::state::PackageItem> = app .install_list .iter() .filter(|item| { // Check if package is installed or provided by an installed package let is_installed = crate::logic::deps::is_package_installed_or_provided( &item.name, &installed_set, &provided_set, ); if !is_installed { return false; } // Check if package has an update available // For official packages: check if it's in upgradable_set OR version differs from installed // For AUR packages: check if target version is different from installed version let has_update = if upgradable_set.contains(&item.name) { // Package is in upgradable set (pacman -Qu) true } else if !item.version.is_empty() { // Normalize target version by removing revision suffix (same as installed version normalization) let normalized_target_version = item.version.split('-').next().unwrap_or(&item.version); // Compare normalized target version with normalized installed version // This works for both official and AUR packages crate::logic::deps::get_installed_version(&item.name).is_ok_and( |installed_version| normalized_target_version != installed_version, ) } else { // No version info available, no update false }; // Only show reinstall confirmation if installed AND no update available // If update is available, it should go through normal update flow !has_update }) .cloned() .collect(); if installed_packages.is_empty() { // Check if this is a batch update scenario requiring confirmation // Only show if there's actually an update available (package is upgradable) // AND the package has installed packages in its "Required By" field (dependency risk) let has_versions = app.install_list.iter().any(|item| { matches!(item.source, crate::state::Source::Official { .. }) && !item.version.is_empty() }); let has_upgrade_available = app.install_list.iter().any(|item| { matches!(item.source, crate::state::Source::Official { .. }) && upgradable_set.contains(&item.name) }); // Only show warning if package has installed packages in "Required By" (dependency risk) let has_installed_required_by = app.install_list.iter().any(|item| { matches!(item.source, crate::state::Source::Official { .. }) && crate::index::is_installed(&item.name) && crate::logic::deps::has_installed_required_by(&item.name) }); if has_versions && has_upgrade_available && has_installed_required_by { // Show confirmation modal for batch updates (only if update is actually available // AND package has installed dependents that could be affected) app.modal = crate::state::Modal::ConfirmBatchUpdate { items: app.install_list.clone(), dry_run: app.dry_run, }; } else { let items = app.install_list.clone(); crate::install::start_integrated_install_all(app, &items, app.dry_run); app.toast_message = Some(crate::i18n::t( app, "app.toasts.installing_preflight_skipped", )); app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(3)); } } else { // Show reinstall confirmation modal // Store both installed packages (for display) and all packages (for installation) app.modal = crate::state::Modal::ConfirmReinstall { items: installed_packages, all_items: app.install_list.clone(), header_chips: crate::state::modal::PreflightHeaderChips::default(), }; } } else { open_preflight_install_modal(app); } } else if app.installed_only_mode && matches!(app.right_pane_focus, crate::state::RightPaneFocus::Remove) { if !app.remove_list.is_empty() { if skip { let names: Vec<String> = app.remove_list.iter().map(|p| p.name.clone()).collect(); crate::install::start_integrated_remove_all( app, &names, app.dry_run, app.remove_cascade_mode, ); app.toast_message = Some(crate::i18n::t(app, "app.toasts.removing_preflight_skipped")); app.toast_expires_at = Some(std::time::Instant::now() + std::time::Duration::from_secs(3)); app.remove_list.clear(); app.remove_list_names.clear(); app.remove_state.select(None); } else { open_preflight_remove_modal(app); } } } else if app.installed_only_mode && matches!( app.right_pane_focus, crate::state::RightPaneFocus::Downgrade ) && !app.downgrade_list.is_empty() { if skip { let names: Vec<String> = app.downgrade_list.iter().map(|p| p.name.clone()).collect(); let joined = names.join(" "); let cmd = if app.dry_run { format!("echo DRY RUN: sudo downgrade {joined}") } else { format!( "if (command -v downgrade >/dev/null 2>&1) || sudo pacman -Qi downgrade >/dev/null 2>&1; then sudo downgrade {joined}; else echo 'downgrade tool not found. Install \"downgrade\" package.'; fi" ) }; crate::install::spawn_shell_commands_in_terminal(&[cmd]); app.downgrade_list.clear(); app.downgrade_list_names.clear(); app.downgrade_state.select(None); } else { open_preflight_downgrade_modal(app); } } } /// What: Handle navigation down (j/Down) in the active pane. /// /// Inputs: /// - `app`: Mutable application state /// - `details_tx`: Channel to request package details /// /// Output: /// - No return value; updates selection in the active pane /// /// Details: /// - Moves selection down in Install/Remove/Downgrade based on mode and focus fn handle_navigation_down(app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>) { if !app.installed_only_mode || matches!(app.right_pane_focus, crate::state::RightPaneFocus::Install) { let inds = crate::ui::helpers::filtered_install_indices(app); if inds.is_empty() { return; } let sel = app.install_state.selected().unwrap_or(0); let max = inds.len().saturating_sub(1); let new = std::cmp::min(sel + 1, max); app.install_state.select(Some(new)); refresh_install_details(app, details_tx); } else if matches!(app.right_pane_focus, crate::state::RightPaneFocus::Remove) { let len = app.remove_list.len(); if len == 0 { return; } let sel = app.remove_state.selected().unwrap_or(0); let max = len.saturating_sub(1); let new = std::cmp::min(sel + 1, max); app.remove_state.select(Some(new)); refresh_remove_details(app, details_tx); } else if matches!( app.right_pane_focus, crate::state::RightPaneFocus::Downgrade ) { let len = app.downgrade_list.len(); if len == 0 { return; } let sel = app.downgrade_state.selected().unwrap_or(0); let max = len.saturating_sub(1); let new = std::cmp::min(sel + 1, max); app.downgrade_state.select(Some(new)); super::utils::refresh_downgrade_details(app, details_tx); } } /// What: Handle navigation up (k/Up) in the active pane. /// /// Inputs: /// - `app`: Mutable application state /// - `details_tx`: Channel to request package details /// /// Output: /// - No return value; updates selection in the active pane /// /// Details: /// - Moves selection up in Install/Remove/Downgrade based on mode and focus fn handle_navigation_up(app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>) { if !app.installed_only_mode || matches!(app.right_pane_focus, crate::state::RightPaneFocus::Install) { let inds = crate::ui::helpers::filtered_install_indices(app); if inds.is_empty() { return; } if let Some(sel) = app.install_state.selected() { let new = sel.saturating_sub(1); app.install_state.select(Some(new)); refresh_install_details(app, details_tx); } } else if matches!(app.right_pane_focus, crate::state::RightPaneFocus::Remove) { if let Some(sel) = app.remove_state.selected() { let new = sel.saturating_sub(1); app.remove_state.select(Some(new)); refresh_remove_details(app, details_tx); } } else if matches!( app.right_pane_focus, crate::state::RightPaneFocus::Downgrade ) && let Some(sel) = app.downgrade_state.selected() { let new = sel.saturating_sub(1); app.downgrade_state.select(Some(new)); super::utils::refresh_downgrade_details(app, details_tx); } } /// What: Delete the selected item from the active list. /// /// Inputs: /// - `app`: Mutable application state /// - `details_tx`: Channel to request package details /// /// Output: /// - No return value; removes item and updates selection /// /// Details: /// - Handles deletion from Install/Remove/Downgrade lists based on mode and focus fn handle_delete_item(app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>) { if app.installed_only_mode { match app.right_pane_focus { crate::state::RightPaneFocus::Downgrade => { if let Some(sel) = app.downgrade_state.selected() && sel < app.downgrade_list.len() { if let Some(removed_item) = app.downgrade_list.get(sel) { app.downgrade_list_names .remove(&removed_item.name.to_lowercase()); } app.downgrade_list.remove(sel); let len = app.downgrade_list.len(); if len == 0 { app.downgrade_state.select(None); } else { let new_sel = sel.min(len - 1); app.downgrade_state.select(Some(new_sel)); super::utils::refresh_downgrade_details(app, details_tx); } } } crate::state::RightPaneFocus::Remove => { if let Some(sel) = app.remove_state.selected() && sel < app.remove_list.len() { if let Some(removed_item) = app.remove_list.get(sel) { app.remove_list_names .remove(&removed_item.name.to_lowercase()); } app.remove_list.remove(sel); let len = app.remove_list.len(); if len == 0 { app.remove_state.select(None); } else { let new_sel = sel.min(len - 1); app.remove_state.select(Some(new_sel)); refresh_remove_details(app, details_tx); } } } crate::state::RightPaneFocus::Install => { delete_from_install_list(app, details_tx); } } } else { delete_from_install_list(app, details_tx); } } /// What: Delete selected item from Install list. /// /// Inputs: /// - `app`: Mutable application state /// - `details_tx`: Channel to request package details /// /// Output: /// - No return value; removes item and updates selection /// /// Details: /// - Handles deletion from Install list with filtered indices fn delete_from_install_list(app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>) { let inds = crate::ui::helpers::filtered_install_indices(app); if inds.is_empty() { return; } if let Some(vsel) = app.install_state.selected() { let i = inds.get(vsel).copied().unwrap_or(0); if i < app.install_list.len() { if let Some(removed_item) = app.install_list.get(i) { app.install_list_names .remove(&removed_item.name.to_lowercase()); } app.install_list.remove(i); app.install_dirty = true; // Clear dependency cache when list changes app.install_list_deps.clear(); app.install_list_files.clear(); app.deps_resolving = false; app.files_resolving = false; let vis_len = inds.len().saturating_sub(1); // one less visible if vis_len == 0 { app.install_state.select(None); } else { let new_sel = if vsel >= vis_len { vis_len - 1 } else { vsel }; app.install_state.select(Some(new_sel)); refresh_install_details(app, details_tx); } } } } /// What: Clear the active list based on mode and focus. /// /// Inputs: /// - `app`: Mutable application state /// /// Output: /// - No return value; clears the appropriate list and resets selection /// /// Details: /// - Clears Install/Remove/Downgrade list based on mode and focus
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
true
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/theme/config.rs
src/theme/config.rs
//! Configuration module for Pacsea theme, settings, and keybinds. //! //! This module is split into submodules for maintainability: //! - `skeletons`: Default configuration file templates //! - `theme_loader`: Theme loading and parsing //! - `settings_save`: Functions to persist settings changes //! - `settings_ensure`: Settings initialization and migration //! - `tests`: Test module /// Settings initialization and migration module. mod settings_ensure; /// Settings persistence module. mod settings_save; /// Default configuration file templates module. mod skeletons; /// Theme loading and parsing module. pub mod theme_loader; #[cfg(test)] mod tests; // Re-export skeleton constants (only THEME_SKELETON_CONTENT is used externally) pub use skeletons::THEME_SKELETON_CONTENT; // Re-export theme loading functions pub use theme_loader::{load_theme_from_file, try_load_theme_with_diagnostics}; // Re-export settings save functions pub use settings_save::{ save_app_start_mode, save_fuzzy_search, save_mirror_count, save_news_filter_installed_only, save_news_filter_show_advisories, save_news_filter_show_arch_news, save_news_filter_show_aur_comments, save_news_filter_show_aur_updates, save_news_filter_show_pkg_updates, save_news_filters_collapsed, save_news_max_age_days, save_scan_do_clamav, save_scan_do_custom, save_scan_do_semgrep, save_scan_do_shellcheck, save_scan_do_sleuth, save_scan_do_trivy, save_scan_do_virustotal, save_selected_countries, save_show_install_pane, save_show_keybinds_footer, save_show_recent_pane, save_sort_mode, save_startup_news_configured, save_startup_news_max_age_days, save_startup_news_show_advisories, save_startup_news_show_arch_news, save_startup_news_show_aur_comments, save_startup_news_show_aur_updates, save_startup_news_show_pkg_updates, save_virustotal_api_key, }; // Re-export settings ensure/migration functions pub use settings_ensure::{ensure_settings_keys_present, maybe_migrate_legacy_confs};
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/theme/store.rs
src/theme/store.rs
use std::fs; use std::sync::{OnceLock, RwLock}; use super::config::{ THEME_SKELETON_CONTENT, load_theme_from_file, try_load_theme_with_diagnostics, }; use super::paths::{config_dir, resolve_theme_config_path}; use super::types::Theme; /// Global theme store with live-reload capability. static THEME_STORE: OnceLock<RwLock<Theme>> = OnceLock::new(); /// What: Load theme colors from disk or generate a skeleton configuration if nothing exists yet. /// /// Inputs: /// - None. /// /// Output: /// - Returns a fully-populated `Theme` on success. /// - Terminates the process with an error when recovery is impossible. /// /// Details: /// - Prefers existing config files found by `resolve_theme_config_path`. /// - Writes `THEME_SKELETON_CONTENT` when encountering empty or missing files to keep the app usable. fn load_initial_theme_or_exit() -> Theme { if let Some(path) = resolve_theme_config_path() { match try_load_theme_with_diagnostics(&path) { Ok(t) => { tracing::info!(path = %path.display(), "loaded theme configuration"); return t; } Err(msg) => { // If the file exists but is empty (0 bytes), treat as first-run and write skeleton. if let Ok(meta) = fs::metadata(&path) && meta.len() == 0 { if let Some(dir) = path.parent() { let _ = fs::create_dir_all(dir); } let _ = fs::write(&path, THEME_SKELETON_CONTENT); if let Some(t) = load_theme_from_file(&path) { tracing::info!(path = %path.display(), "wrote default theme skeleton and loaded"); return t; } } tracing::error!( path = %path.display(), error = %msg, "theme configuration errors" ); } } } else { // No config found: write default skeleton to config_dir()/theme.conf let config_directory = config_dir(); let target = config_directory.join("theme.conf"); if !target.exists() { if let Some(dir) = target.parent() { let _ = fs::create_dir_all(dir); } let _ = fs::write(&target, THEME_SKELETON_CONTENT); } if let Some(t) = load_theme_from_file(&target) { tracing::info!(path = %target.display(), "initialized theme from default path"); return t; } tracing::error!( path = %target.display(), "theme configuration missing or incomplete. Please edit the theme.conf file at the path shown above." ); } std::process::exit(1); } /// What: Access the application's theme palette, loading or caching as needed. /// /// Inputs: /// - None. /// /// Output: /// - A copy of the currently loaded `Theme`. /// /// # Panics /// - Panics if the theme store `RwLock` is poisoned /// /// Details: /// - Lazily initializes a global `RwLock<Theme>` using `load_initial_theme_or_exit`. /// - Subsequent calls reuse the cached theme until `reload_theme` updates it. pub fn theme() -> Theme { let lock = THEME_STORE.get_or_init(|| RwLock::new(load_initial_theme_or_exit())); *lock.read().expect("theme store poisoned") } /// What: Reload the theme configuration from disk on demand. /// /// Inputs: /// - None (locates the config through `resolve_theme_config_path`). /// /// Output: /// - `Ok(())` when the theme is reloaded successfully. /// - `Err(String)` with a human-readable reason when reloading fails. /// /// # Errors /// - Returns `Err` when no theme configuration file is found /// - Returns `Err` when theme file cannot be loaded or parsed /// - Returns `Err` when theme validation fails /// /// Details: /// - Keeps the in-memory cache up to date so the UI can refresh without restarting Pacsea. /// - Returns an error if the theme file is missing or contains validation problems. pub fn reload_theme() -> std::result::Result<(), String> { let path = resolve_theme_config_path().or_else(|| Some(config_dir().join("theme.conf"))); let Some(p) = path else { return Err("No theme configuration file found".to_string()); }; let new_theme = super::config::try_load_theme_with_diagnostics(&p)?; let lock = THEME_STORE.get_or_init(|| RwLock::new(load_initial_theme_or_exit())); lock.write().map_or_else( |_| Err("Failed to acquire theme store for writing".to_string()), |mut guard| { *guard = new_theme; Ok(()) }, ) }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/theme/paths.rs
src/theme/paths.rs
use std::env; use std::path::{Path, PathBuf}; /// What: Locate the active theme configuration file, considering modern and legacy layouts. /// /// Inputs: /// - None (reads environment variables to build candidate paths). /// /// Output: /// - `Some(PathBuf)` pointing to the first readable theme file; `None` when nothing exists. /// /// Details: /// - Prefers `$HOME/.config/pacsea/theme.conf`, then legacy `pacsea.conf`, and repeats for XDG paths. pub(super) fn resolve_theme_config_path() -> Option<PathBuf> { let home = env::var("HOME").ok(); let xdg_config = env::var("XDG_CONFIG_HOME").ok(); let mut candidates: Vec<PathBuf> = Vec::new(); if let Some(h) = home.as_deref() { let base = Path::new(h).join(".config").join("pacsea"); candidates.push(base.join("theme.conf")); candidates.push(base.join("pacsea.conf")); // legacy } if let Some(xdg) = xdg_config.as_deref() { let x = Path::new(xdg).join("pacsea"); candidates.push(x.join("theme.conf")); candidates.push(x.join("pacsea.conf")); // legacy } candidates.into_iter().find(|p| p.is_file()) } /// What: Locate the active settings configuration file, prioritizing the split layout. /// /// Inputs: /// - None. /// /// Output: /// - `Some(PathBuf)` for the resolved settings file; `None` when no candidate exists. /// /// Details: /// - Searches `$HOME` and `XDG_CONFIG_HOME` for `settings.conf`, then falls back to `pacsea.conf`. pub(super) fn resolve_settings_config_path() -> Option<PathBuf> { let home = env::var("HOME").ok(); let xdg_config = env::var("XDG_CONFIG_HOME").ok(); let mut candidates: Vec<PathBuf> = Vec::new(); if let Some(h) = home.as_deref() { let base = Path::new(h).join(".config").join("pacsea"); candidates.push(base.join("settings.conf")); candidates.push(base.join("pacsea.conf")); // legacy } if let Some(xdg) = xdg_config.as_deref() { let x = Path::new(xdg).join("pacsea"); candidates.push(x.join("settings.conf")); candidates.push(x.join("pacsea.conf")); // legacy } candidates.into_iter().find(|p| p.is_file()) } /// What: Locate the keybindings configuration file for Pacsea. /// /// Inputs: /// - None. /// /// Output: /// - `Some(PathBuf)` when a keybinds file is present; `None` otherwise. /// /// Details: /// - Checks both `$HOME/.config/pacsea/keybinds.conf` and the legacy `pacsea.conf`, mirrored for XDG. pub(super) fn resolve_keybinds_config_path() -> Option<PathBuf> { let home = env::var("HOME").ok(); let xdg_config = env::var("XDG_CONFIG_HOME").ok(); let mut candidates: Vec<PathBuf> = Vec::new(); if let Some(h) = home.as_deref() { let base = Path::new(h).join(".config").join("pacsea"); candidates.push(base.join("keybinds.conf")); candidates.push(base.join("pacsea.conf")); // legacy } if let Some(xdg) = xdg_config.as_deref() { let x = Path::new(xdg).join("pacsea"); candidates.push(x.join("keybinds.conf")); candidates.push(x.join("pacsea.conf")); // legacy } candidates.into_iter().find(|p| p.is_file()) } /// What: Resolve an XDG base directory, falling back to `$HOME` with provided segments. /// /// Inputs: /// - `var`: Environment variable name, e.g., `XDG_CONFIG_HOME`. /// - `home_default`: Path segments appended to `$HOME` when the variable is unset. /// /// Output: /// - `PathBuf` pointing to the derived base directory. /// /// Details: /// - Treats empty environment values as unset and gracefully handles missing `$HOME`. fn xdg_base_dir(var: &str, home_default: &[&str]) -> PathBuf { if let Ok(p) = env::var(var) && !p.trim().is_empty() { return PathBuf::from(p); } let home = env::var("HOME").unwrap_or_else(|_| ".".to_string()); let mut base = PathBuf::from(home); for seg in home_default { base = base.join(seg); } base } /// What: Build `$HOME/.config/pacsea`, ensuring the directory exists when `$HOME` is set. /// /// Inputs: /// - None. /// /// Output: /// - `Some(PathBuf)` when the directory is accessible; `None` if `$HOME` is missing or creation fails. /// /// Details: /// - Serves as the preferred base for other configuration directories. /// - On Windows, also checks `APPDATA` and `USERPROFILE` if `HOME` is not set. fn home_config_dir() -> Option<PathBuf> { // Try HOME first (works on Unix and Windows if set) if let Ok(home) = env::var("HOME") { let dir = Path::new(&home).join(".config").join("pacsea"); if std::fs::create_dir_all(&dir).is_ok() { return Some(dir); } } // Windows fallback: use APPDATA or USERPROFILE #[cfg(windows)] { if let Ok(appdata) = env::var("APPDATA") { let dir = Path::new(&appdata).join("pacsea"); if std::fs::create_dir_all(&dir).is_ok() { return Some(dir); } } if let Ok(userprofile) = env::var("USERPROFILE") { let dir = Path::new(&userprofile).join(".config").join("pacsea"); if std::fs::create_dir_all(&dir).is_ok() { return Some(dir); } } } None } /// What: Resolve the Pacsea configuration directory, ensuring it exists on disk. /// /// Inputs: /// - None. /// /// Output: /// - `PathBuf` pointing to the Pacsea config directory. /// /// Details: /// - Prefers `$HOME/.config/pacsea`, falling back to `XDG_CONFIG_HOME/pacsea` when necessary. #[must_use] pub fn config_dir() -> PathBuf { // Prefer HOME ~/.config/pacsea first if let Some(dir) = home_config_dir() { return dir; } // Fallback: use XDG_CONFIG_HOME (or default to ~/.config) and ensure let base = xdg_base_dir("XDG_CONFIG_HOME", &[".config"]); let dir = base.join("pacsea"); let _ = std::fs::create_dir_all(&dir); dir } /// What: Obtain the logs subdirectory inside the Pacsea config folder. /// /// Inputs: /// - None. /// /// Output: /// - `PathBuf` leading to the `logs` directory (created if missing). /// /// Details: /// - Builds upon `config_dir()` and ensures a stable location for log files. #[must_use] pub fn logs_dir() -> PathBuf { let base = config_dir(); let dir = base.join("logs"); let _ = std::fs::create_dir_all(&dir); dir } /// What: Obtain the lists subdirectory inside the Pacsea config folder. /// /// Inputs: /// - None. /// /// Output: /// - `PathBuf` leading to the `lists` directory (created if missing). /// /// Details: /// - Builds upon `config_dir()` and ensures storage for exported package lists. #[must_use] pub fn lists_dir() -> PathBuf { let base = config_dir(); let dir = base.join("lists"); let _ = std::fs::create_dir_all(&dir); dir } #[cfg(test)] mod tests { #[test] /// What: Verify path helpers resolve under the Pacsea config directory rooted at `HOME`. /// /// Inputs: /// - Temporary `HOME` directory substituted to capture generated paths. /// /// Output: /// - `config_dir`, `logs_dir`, and `lists_dir` end with `pacsea`, `logs`, and `lists` respectively. /// /// Details: /// - Restores the original `HOME` afterwards to avoid polluting the real configuration tree. fn paths_config_lists_logs_under_home() { let _guard = crate::theme::test_mutex() .lock() .expect("Test mutex poisoned"); let orig_home = std::env::var_os("HOME"); let base = std::env::temp_dir().join(format!( "pacsea_test_paths_{}_{}", std::process::id(), std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .expect("System time is before UNIX epoch") .as_nanos() )); let _ = std::fs::create_dir_all(&base); unsafe { std::env::set_var("HOME", base.display().to_string()) }; let cfg = super::config_dir(); let logs = super::logs_dir(); let lists = super::lists_dir(); assert!(cfg.ends_with("pacsea")); assert!(logs.ends_with("logs")); assert!(lists.ends_with("lists")); unsafe { if let Some(v) = orig_home { std::env::set_var("HOME", v); } else { std::env::remove_var("HOME"); } } } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/theme/types.rs
src/theme/types.rs
use crossterm::event::{KeyCode, KeyModifiers}; use ratatui::style::Color; /// Application theme palette used by rendering code. /// /// All colors are provided as [`ratatui::style::Color`] and are suitable for /// direct use with widgets and styles. #[derive(Clone, Copy, Debug)] pub struct Theme { /// Primary background color for the canvas. pub base: Color, /// Slightly lighter background layer used behind panels. pub mantle: Color, /// Darkest background shade for deep contrast areas. pub crust: Color, /// Subtle surface color for component backgrounds (level 1). pub surface1: Color, /// Subtle surface color for component backgrounds (level 2). pub surface2: Color, /// Muted overlay line/border color (primary). pub overlay1: Color, /// Muted overlay line/border color (secondary). pub overlay2: Color, /// Primary foreground text color. pub text: Color, /// Secondary text for less prominent content. pub subtext0: Color, /// Tertiary text for captions and low-emphasis content. pub subtext1: Color, /// Accent color commonly used for selection and interactive highlights. pub sapphire: Color, /// Accent color for emphasized headings or selections. pub mauve: Color, /// Success/positive state color. pub green: Color, /// Warning/attention state color. pub yellow: Color, /// Error/danger state color. pub red: Color, /// Accent color for subtle emphasis and borders. pub lavender: Color, } /// User-configurable application settings parsed from `pacsea.conf`. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum PackageMarker { /// Color the entire line for the marked package. FullLine, /// Add a marker at the front of the line. Front, /// Add a marker at the end of the line. End, } /// User-configurable application settings parsed from `pacsea.conf`. #[derive(Clone, Debug)] #[allow(clippy::struct_excessive_bools)] pub struct Settings { /// Percentage width allocated to the Recent pane (left column). pub layout_left_pct: u16, /// Percentage width allocated to the Search pane (center column). pub layout_center_pct: u16, /// Percentage width allocated to the Install pane (right column). pub layout_right_pct: u16, /// Default value for the application's dry-run mode on startup. /// This can be toggled via the `--dry-run` CLI flag. pub app_dry_run_default: bool, /// Configurable key bindings parsed from `pacsea.conf` pub keymap: KeyMap, /// Initial sort mode for results list. pub sort_mode: crate::state::SortMode, /// Text appended when copying PKGBUILD to clipboard. pub clipboard_suffix: String, /// Whether the Search history pane should be shown on startup. pub show_recent_pane: bool, /// Whether the Install/Remove pane should be shown on startup. pub show_install_pane: bool, /// Whether the keybinds footer should be shown on startup. pub show_keybinds_footer: bool, /// Selected countries used when updating mirrors (comma-separated or multiple). pub selected_countries: String, /// Number of mirrors to fetch/rank when updating. pub mirror_count: u16, /// `VirusTotal` API key for security scanning. pub virustotal_api_key: String, /// Whether to run `ClamAV` scan on AUR packages. pub scan_do_clamav: bool, /// Whether to run `Trivy` scan on AUR packages. pub scan_do_trivy: bool, /// Whether to run `Semgrep` scan on AUR packages. pub scan_do_semgrep: bool, /// Whether to run `ShellCheck` scan on AUR packages. pub scan_do_shellcheck: bool, /// Whether to run `VirusTotal` scan on AUR packages. pub scan_do_virustotal: bool, /// Whether to run custom scan on AUR packages. pub scan_do_custom: bool, /// Whether to run Sleuth scan on AUR packages. pub scan_do_sleuth: bool, /// Whether to start the app in News mode (true) or Package mode (false). pub start_in_news: bool, /// Whether to show Arch news items in the News view. pub news_filter_show_arch_news: bool, /// Whether to show security advisories in the News view. pub news_filter_show_advisories: bool, /// Whether to show installed package update items in the News view. pub news_filter_show_pkg_updates: bool, /// Whether to show AUR package update items in the News view. pub news_filter_show_aur_updates: bool, /// Whether to show installed AUR comment items in the News view. pub news_filter_show_aur_comments: bool, /// Whether to restrict advisories to installed packages in the News view. pub news_filter_installed_only: bool, /// Maximum age of news items in days (None = unlimited). pub news_max_age_days: Option<u32>, /// Whether startup news popup setup has been completed. pub startup_news_configured: bool, /// Whether to show Arch news in startup news popup. pub startup_news_show_arch_news: bool, /// Whether to show security advisories in startup news popup. pub startup_news_show_advisories: bool, /// Whether to show AUR updates in startup news popup. pub startup_news_show_aur_updates: bool, /// Whether to show AUR comments in startup news popup. pub startup_news_show_aur_comments: bool, /// Whether to show official package updates in startup news popup. pub startup_news_show_pkg_updates: bool, /// Maximum age of news items in days for startup news popup (None = unlimited). pub startup_news_max_age_days: Option<u32>, /// How many days to keep Arch news and advisories cached on disk. /// Default is 7 days. Helps reduce network requests on startup. pub news_cache_ttl_days: u32, /// Visual marker style for packages added to Install/Remove/Downgrade lists. pub package_marker: PackageMarker, /// Symbol used to mark a news item as read in the News modal. pub news_read_symbol: String, /// Symbol used to mark a news item as unread in the News modal. pub news_unread_symbol: String, /// Preferred terminal binary name to spawn for shell commands (e.g., "alacritty", "kitty", "gnome-terminal"). /// When empty, Pacsea auto-detects from available terminals. pub preferred_terminal: String, /// When true, skip the Preflight modal and execute actions directly (install/remove/downgrade). /// Defaults to false to preserve the safer, review-first workflow. pub skip_preflight: bool, /// Locale code for translations (e.g., "de-DE", "en-US"). /// Empty string means auto-detect from system locale. pub locale: String, /// Search input mode on startup. /// When false, starts in insert mode (default). /// When true, starts in normal mode. pub search_startup_mode: bool, /// Whether fuzzy search is enabled by default on startup. /// When false, uses normal substring search (default). /// When true, uses fuzzy matching (fzf-style). pub fuzzy_search: bool, /// Refresh interval in seconds for pacman -Qu and AUR helper checks. /// Default is 30 seconds. Set to a higher value to reduce resource usage on slow systems. pub updates_refresh_interval: u64, /// Filter mode for installed packages display. /// `LeafOnly` shows explicitly installed packages with no dependents. /// `AllExplicit` shows all explicitly installed packages. pub installed_packages_mode: crate::state::InstalledPackagesMode, /// Whether to fetch remote announcements from GitHub Gist. /// If `true`, fetches announcements from the configured Gist URL. /// If `false`, remote announcements are disabled (version announcements still show). pub get_announcement: bool, } impl Default for Settings { /// What: Provide the built-in baseline configuration for Pacsea settings. /// /// Inputs: /// - None. /// /// Output: /// - Returns a `Settings` instance populated with Pacsea's preferred defaults. /// /// Details: /// - Sets balanced pane layout percentages and enables all panes by default. /// - Enables all scan types and uses Catppuccin-inspired news glyphs. fn default() -> Self { Self { layout_left_pct: 20, layout_center_pct: 60, layout_right_pct: 20, app_dry_run_default: false, keymap: KeyMap::default(), sort_mode: crate::state::SortMode::RepoThenName, clipboard_suffix: "Check PKGBUILD and source for suspicious and malicious activities" .to_string(), show_recent_pane: true, show_install_pane: true, show_keybinds_footer: true, selected_countries: "Worldwide".to_string(), mirror_count: 20, virustotal_api_key: String::new(), scan_do_clamav: true, scan_do_trivy: true, scan_do_semgrep: true, scan_do_shellcheck: true, scan_do_virustotal: true, scan_do_custom: true, scan_do_sleuth: true, start_in_news: false, news_filter_show_arch_news: true, news_filter_show_advisories: true, news_filter_show_pkg_updates: true, news_filter_show_aur_updates: true, news_filter_show_aur_comments: true, news_filter_installed_only: false, news_max_age_days: Some(30), startup_news_configured: false, startup_news_show_arch_news: true, startup_news_show_advisories: true, startup_news_show_aur_updates: true, startup_news_show_aur_comments: true, startup_news_show_pkg_updates: true, startup_news_max_age_days: Some(7), news_cache_ttl_days: 7, package_marker: PackageMarker::Front, news_read_symbol: "✓".to_string(), news_unread_symbol: "∘".to_string(), preferred_terminal: String::new(), skip_preflight: false, locale: String::new(), // Empty means auto-detect from system search_startup_mode: false, // Default to insert mode fuzzy_search: false, // Default to normal substring search updates_refresh_interval: 30, // Default to 30 seconds installed_packages_mode: crate::state::InstalledPackagesMode::LeafOnly, get_announcement: true, // Default to fetching remote announcements } } } /// A single keyboard chord (modifiers + key). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] pub struct KeyChord { /// The key code (e.g., Char('a'), Enter, Esc). pub code: KeyCode, /// The modifier keys (e.g., Ctrl, Shift, Alt). pub mods: KeyModifiers, } impl KeyChord { /// Return a short display label such as "Ctrl+R", "F1", "Shift+Del", "+/ ?". #[must_use] pub fn label(&self) -> String { let mut parts: Vec<&'static str> = Vec::new(); if self.mods.contains(KeyModifiers::CONTROL) { parts.push("Ctrl"); } if self.mods.contains(KeyModifiers::ALT) { parts.push("Alt"); } if self.mods.contains(KeyModifiers::SHIFT) { parts.push("Shift"); } if self.mods.contains(KeyModifiers::SUPER) { parts.push("Super"); } let key = match self.code { KeyCode::Char(ch) => { // Show uppercase character for display let up = ch.to_ascii_uppercase(); if up == ' ' { "Space".to_string() } else { up.to_string() } } KeyCode::Enter => "Enter".to_string(), KeyCode::Esc => "Esc".to_string(), KeyCode::Backspace => "Backspace".to_string(), KeyCode::Tab => "Tab".to_string(), KeyCode::BackTab => "Shift+Tab".to_string(), KeyCode::Delete => "Del".to_string(), KeyCode::Insert => "Ins".to_string(), KeyCode::Home => "Home".to_string(), KeyCode::End => "End".to_string(), KeyCode::PageUp => "PgUp".to_string(), KeyCode::PageDown => "PgDn".to_string(), KeyCode::Up => "↑".to_string(), KeyCode::Down => "↓".to_string(), KeyCode::Left => "←".to_string(), KeyCode::Right => "→".to_string(), KeyCode::F(n) => format!("F{n}"), _ => "?".to_string(), }; if parts.is_empty() || matches!(self.code, KeyCode::BackTab) { key } else { format!("{}+{key}", parts.join("+")) } } } #[cfg(test)] mod tests { use super::*; #[test] /// What: Ensure `KeyChord::label` renders user-facing text for modifier and key combinations. /// /// Inputs: /// - Sample chords covering control characters, space, function keys, Shift+BackTab, arrow keys, and multi-modifier chords. /// /// Output: /// - Labels such as `"Ctrl+R"`, `"Space"`, `"F5"`, `"Shift+Tab"`, arrow glyphs, and combined modifier strings. /// /// Details: /// - Protects the formatting logic that appears in keybinding help overlays. fn theme_keychord_label_variants() { let kc = KeyChord { code: KeyCode::Char('r'), mods: KeyModifiers::CONTROL, }; assert_eq!(kc.label(), "Ctrl+R"); let kc2 = KeyChord { code: KeyCode::Char(' '), mods: KeyModifiers::empty(), }; assert_eq!(kc2.label(), "Space"); let kc3 = KeyChord { code: KeyCode::F(5), mods: KeyModifiers::empty(), }; assert_eq!(kc3.label(), "F5"); let kc4 = KeyChord { code: KeyCode::BackTab, mods: KeyModifiers::SHIFT, }; assert_eq!(kc4.label(), "Shift+Tab"); let kc5 = KeyChord { code: KeyCode::Left, mods: KeyModifiers::empty(), }; assert_eq!(kc5.label(), "←"); let kc6 = KeyChord { code: KeyCode::Char('x'), mods: KeyModifiers::ALT | KeyModifiers::SHIFT, }; assert_eq!(kc6.label(), "Alt+Shift+X"); } } /// Application key bindings. /// Each action can have multiple chords. #[derive(Clone, Debug)] pub struct KeyMap { // Global /// Key chords to show help overlay. pub help_overlay: Vec<KeyChord>, /// Key chords to reload configuration. pub reload_config: Vec<KeyChord>, /// Key chords to exit the application. pub exit: Vec<KeyChord>, /// Global: Show/Hide PKGBUILD viewer pub show_pkgbuild: Vec<KeyChord>, /// Global: Show/Hide AUR comments viewer pub comments_toggle: Vec<KeyChord>, /// Global: Change results sorting mode pub change_sort: Vec<KeyChord>, /// Key chords to move to next pane. pub pane_next: Vec<KeyChord>, /// Key chords to move focus left. pub pane_left: Vec<KeyChord>, /// Key chords to move focus right. pub pane_right: Vec<KeyChord>, /// Global: Toggle Config/Lists dropdown pub config_menu_toggle: Vec<KeyChord>, /// Global: Toggle Options dropdown pub options_menu_toggle: Vec<KeyChord>, /// Global: Toggle Panels dropdown pub panels_menu_toggle: Vec<KeyChord>, // Search /// Key chords to move selection up in search results. pub search_move_up: Vec<KeyChord>, /// Key chords to move selection down in search results. pub search_move_down: Vec<KeyChord>, /// Key chords to page up in search results. pub search_page_up: Vec<KeyChord>, /// Key chords to page down in search results. pub search_page_down: Vec<KeyChord>, /// Key chords to add package to install list. pub search_add: Vec<KeyChord>, /// Key chords to install selected package. pub search_install: Vec<KeyChord>, /// Key chords to move focus left from search pane. pub search_focus_left: Vec<KeyChord>, /// Key chords to move focus right from search pane. pub search_focus_right: Vec<KeyChord>, /// Key chords for backspace in search input. pub search_backspace: Vec<KeyChord>, /// Insert mode: clear entire search input (default: Shift+Del) pub search_insert_clear: Vec<KeyChord>, // Search normal mode /// Toggle Search normal mode on/off (works from both insert/normal) pub search_normal_toggle: Vec<KeyChord>, /// Enter insert mode while in Search normal mode pub search_normal_insert: Vec<KeyChord>, /// Normal mode: extend selection to the left (default: h) pub search_normal_select_left: Vec<KeyChord>, /// Normal mode: extend selection to the right (default: l) pub search_normal_select_right: Vec<KeyChord>, /// Normal mode: delete selected text (default: d) pub search_normal_delete: Vec<KeyChord>, /// Normal mode: clear entire search input (default: Shift+Del) pub search_normal_clear: Vec<KeyChord>, /// Normal mode: open Arch status page in browser (default: Shift+S) pub search_normal_open_status: Vec<KeyChord>, /// Normal mode: trigger Import packages dialog pub search_normal_import: Vec<KeyChord>, /// Normal mode: trigger Export Install list pub search_normal_export: Vec<KeyChord>, /// Normal mode: open Available Updates window pub search_normal_updates: Vec<KeyChord>, /// Toggle fuzzy search mode on/off pub toggle_fuzzy: Vec<KeyChord>, // Recent /// Key chords to move selection up in recent queries. pub recent_move_up: Vec<KeyChord>, /// Key chords to move selection down in recent queries. pub recent_move_down: Vec<KeyChord>, /// Key chords to find/search in recent queries. pub recent_find: Vec<KeyChord>, /// Key chords to use selected recent query. pub recent_use: Vec<KeyChord>, /// Key chords to add package from recent to install list. pub recent_add: Vec<KeyChord>, /// Key chords to move focus from recent to search pane. pub recent_to_search: Vec<KeyChord>, /// Key chords to move focus right from recent pane. pub recent_focus_right: Vec<KeyChord>, /// Remove one entry from Recent pub recent_remove: Vec<KeyChord>, /// Clear all entries in Recent pub recent_clear: Vec<KeyChord>, // Install /// Key chords to move selection up in install list. pub install_move_up: Vec<KeyChord>, /// Key chords to move selection down in install list. pub install_move_down: Vec<KeyChord>, /// Key chords to confirm and execute install/remove operation. pub install_confirm: Vec<KeyChord>, /// Key chords to remove item from install list. pub install_remove: Vec<KeyChord>, /// Key chords to clear install list. pub install_clear: Vec<KeyChord>, /// Key chords to find/search in install list. pub install_find: Vec<KeyChord>, /// Key chords to move focus from install to search pane. pub install_to_search: Vec<KeyChord>, /// Key chords to move focus left from install pane. pub install_focus_left: Vec<KeyChord>, // News modal /// Mark currently listed News items as read (without opening URL) pub news_mark_read: Vec<KeyChord>, /// Mark all listed News items as read pub news_mark_all_read: Vec<KeyChord>, /// Mark selected News Feed item as read. pub news_mark_read_feed: Vec<KeyChord>, /// Mark selected News Feed item as unread. pub news_mark_unread_feed: Vec<KeyChord>, /// Toggle read/unread for selected News Feed item. pub news_toggle_read_feed: Vec<KeyChord>, } /// Type alias for global key bindings tuple. /// /// Contains 9 `Vec<KeyChord>` for `help_overlay`, `reload_config`, `exit`, `show_pkgbuild`, `comments_toggle`, `change_sort`, and pane navigation keys. type GlobalKeys = ( Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, ); /// Type alias for search key bindings tuple. /// /// Contains 10 `Vec<KeyChord>` for search navigation, actions, and focus keys. type SearchKeys = ( Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, ); /// Type alias for search normal mode key bindings tuple. /// /// Contains 10 `Vec<KeyChord>` for Vim-like normal mode search keys. type SearchNormalKeys = ( Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, ); /// Type alias for recent pane key bindings tuple. /// /// Contains 9 `Vec<KeyChord>` for recent pane navigation and action keys. type RecentKeys = ( Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, ); /// Type alias for install list key bindings tuple. /// /// Contains 8 `Vec<KeyChord>` for install list navigation and action keys. type InstallKeys = ( Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>, ); /// What: Create default global key bindings. /// /// Inputs: /// - `none`: Empty key modifiers /// - `ctrl`: Control modifier /// /// Output: /// - Tuple of global key binding vectors /// /// Details: /// - Returns `help_overlay`, `reload_config`, `exit`, `show_pkgbuild`, `change_sort`, and pane navigation keys. fn default_global_keys(none: KeyModifiers, ctrl: KeyModifiers) -> GlobalKeys { use KeyCode::{BackTab, Char, Left, Right, Tab}; ( vec![ KeyChord { code: KeyCode::F(1), mods: none, }, KeyChord { code: Char('?'), mods: none, }, ], vec![KeyChord { code: Char('r'), mods: ctrl, }], vec![KeyChord { code: Char('c'), mods: ctrl, }], vec![KeyChord { code: Char('x'), mods: ctrl, }], vec![KeyChord { code: Char('t'), mods: ctrl, }], vec![KeyChord { code: BackTab, mods: none, }], vec![KeyChord { code: Tab, mods: none, }], vec![KeyChord { code: Left, mods: none, }], vec![KeyChord { code: Right, mods: none, }], ) } /// What: Create default dropdown toggle key bindings. /// /// Inputs: /// - `shift`: Shift modifier /// /// Output: /// - Tuple of dropdown toggle key binding vectors /// /// Details: /// - Returns `config_menu_toggle`, `options_menu_toggle`, and `panels_menu_toggle` keys. fn default_dropdown_keys(shift: KeyModifiers) -> (Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>) { use KeyCode::Char; ( vec![KeyChord { code: Char('c'), mods: shift, }], vec![KeyChord { code: Char('o'), mods: shift, }], vec![KeyChord { code: Char('p'), mods: shift, }], ) } /// What: Create default search key bindings. /// /// Inputs: /// - `none`: Empty key modifiers /// /// Output: /// - Tuple of search key binding vectors /// /// Details: /// - Returns all search-related key bindings for navigation, actions, and focus. fn default_search_keys(none: KeyModifiers) -> SearchKeys { use KeyCode::{Backspace, Char, Down, Enter, Left, PageDown, PageUp, Right, Up}; ( vec![KeyChord { code: Up, mods: none, }], vec![KeyChord { code: Down, mods: none, }], vec![KeyChord { code: PageUp, mods: none, }], vec![KeyChord { code: PageDown, mods: none, }], vec![KeyChord { code: Char(' '), mods: none, }], vec![KeyChord { code: Enter, mods: none, }], vec![KeyChord { code: Left, mods: none, }], vec![KeyChord { code: Right, mods: none, }], vec![KeyChord { code: Backspace, mods: none, }], vec![KeyChord { code: KeyCode::Delete, mods: KeyModifiers::SHIFT, }], ) } /// What: Create default search normal mode key bindings. /// /// Inputs: /// - `none`: Empty key modifiers /// - `shift`: Shift modifier /// /// Output: /// - Tuple of search normal mode key binding vectors /// /// Details: /// - Returns all Vim-like normal mode key bindings for search. fn default_search_normal_keys(none: KeyModifiers, shift: KeyModifiers) -> SearchNormalKeys { use KeyCode::{Char, Delete, Esc}; ( vec![KeyChord { code: Esc, mods: none, }], vec![KeyChord { code: Char('i'), mods: none, }], vec![KeyChord { code: Char('h'), mods: none, }], vec![KeyChord { code: Char('l'), mods: none, }], vec![KeyChord { code: Char('d'), mods: none, }], vec![KeyChord { code: Delete, mods: shift, }], vec![KeyChord { code: Char('s'), mods: shift, }], vec![KeyChord { code: Char('i'), mods: shift, }], vec![KeyChord { code: Char('e'), mods: shift, }], vec![KeyChord { code: Char('u'), mods: shift, }], ) } /// What: Create default recent pane key bindings. /// /// Inputs: /// - `none`: Empty key modifiers /// - `shift`: Shift modifier /// /// Output: /// - Tuple of recent pane key binding vectors /// /// Details: /// - Returns all recent pane navigation and action key bindings. fn default_recent_keys(none: KeyModifiers, shift: KeyModifiers) -> RecentKeys { use KeyCode::{Char, Delete, Down, Enter, Esc, Right, Up}; ( vec![ KeyChord { code: Char('k'), mods: none, }, KeyChord { code: Up, mods: none, }, ], vec![ KeyChord { code: Char('j'), mods: none, }, KeyChord { code: Down, mods: none, }, ], vec![KeyChord { code: Char('/'), mods: none, }], vec![KeyChord { code: Enter, mods: none, }], vec![KeyChord { code: Char(' '), mods: none, }], vec![KeyChord { code: Esc, mods: none, }], vec![KeyChord { code: Right, mods: none, }], vec![ KeyChord { code: Char('d'), mods: none, }, KeyChord { code: Delete, mods: none, }, ], vec![KeyChord { code: Delete, mods: shift, }], ) } /// What: Create default install list key bindings. /// /// Inputs: /// - `none`: Empty key modifiers /// - `shift`: Shift modifier /// /// Output: /// - Tuple of install list key binding vectors /// /// Details: /// - Returns all install list navigation and action key bindings. fn default_install_keys(none: KeyModifiers, shift: KeyModifiers) -> InstallKeys { use KeyCode::{Char, Delete, Down, Enter, Esc, Left, Up}; ( vec![ KeyChord { code: Char('k'), mods: none, }, KeyChord { code: Up, mods: none, }, ], vec![ KeyChord { code: Char('j'), mods: none, }, KeyChord { code: Down, mods: none, }, ], vec![KeyChord { code: Enter, mods: none, }], vec![ KeyChord { code: Delete, mods: none, }, KeyChord { code: Char('d'), mods: none, }, ], vec![KeyChord { code: Delete, mods: shift, }], vec![KeyChord { code: Char('/'), mods: none, }], vec![KeyChord { code: Esc, mods: none, }], vec![KeyChord { code: Left, mods: none, }], ) } /// What: Create default news modal key bindings. /// /// Inputs: /// - `none`: Empty key modifiers /// - `ctrl`: Control modifier /// /// Output: /// - Tuple of news modal key binding vectors /// /// Details: /// - Returns `news_mark_read` and `news_mark_all_read` key bindings. fn default_news_keys(none: KeyModifiers, ctrl: KeyModifiers) -> (Vec<KeyChord>, Vec<KeyChord>) { use KeyCode::Char; ( vec![KeyChord { code: Char('r'), mods: none, }], vec![KeyChord { code: Char('r'), mods: ctrl, }], ) } /// What: Create default News Feed key bindings. /// /// Inputs: /// - `none`: Empty key modifiers /// /// Output: /// - Tuple of news feed key binding vectors /// /// Details: /// - Returns `news_mark_read_feed`, `news_mark_unread_feed`, and `news_toggle_read_feed`. fn default_news_feed_keys(none: KeyModifiers) -> (Vec<KeyChord>, Vec<KeyChord>, Vec<KeyChord>) { use KeyCode::Char; ( vec![KeyChord { code: Char('r'), mods: none, }], vec![KeyChord { code: Char('u'), mods: none, }], vec![KeyChord { code: Char('t'), mods: none, }], ) } /// What: Build the default `KeyMap` by constructing it from helper functions. /// /// Inputs: /// - None (uses internal modifier constants). /// /// Output: /// - Returns a fully constructed `KeyMap` with all default key bindings. /// /// Details: /// - Consolidates all key binding construction to reduce data flow complexity. /// - All key bindings are constructed inline within the struct initialization. fn build_default_keymap() -> KeyMap { let none = KeyModifiers::empty(); let ctrl = KeyModifiers::CONTROL; let shift = KeyModifiers::SHIFT; let global = default_global_keys(none, ctrl); let dropdown = default_dropdown_keys(shift); let search = default_search_keys(none); let search_normal = default_search_normal_keys(none, shift); let recent = default_recent_keys(none, shift); let install = default_install_keys(none, shift); let news = default_news_keys(none, ctrl); let news_feed = default_news_feed_keys(none); KeyMap { help_overlay: global.0, reload_config: global.1, exit: global.2, show_pkgbuild: global.3, comments_toggle: global.4, change_sort: global.5, pane_next: global.6, pane_left: global.7, pane_right: global.8, config_menu_toggle: dropdown.0, options_menu_toggle: dropdown.1, panels_menu_toggle: dropdown.2, search_move_up: search.0, search_move_down: search.1, search_page_up: search.2, search_page_down: search.3, search_add: search.4, search_install: search.5, search_focus_left: search.6, search_focus_right: search.7, search_backspace: search.8, search_insert_clear: search.9, search_normal_toggle: search_normal.0, search_normal_insert: search_normal.1, search_normal_select_left: search_normal.2, search_normal_select_right: search_normal.3, search_normal_delete: search_normal.4, search_normal_clear: search_normal.5, search_normal_open_status: search_normal.6, search_normal_import: search_normal.7, search_normal_export: search_normal.8, search_normal_updates: search_normal.9, toggle_fuzzy: vec![KeyChord {
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
true
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/theme/mod.rs
src/theme/mod.rs
//! Theme system for Pacsea. //! //! Split from a monolithic file into submodules for maintainability. Public //! re-exports keep the `crate::theme::*` API stable. /// Configuration file management and migration. mod config; /// Configuration parsing utilities. mod parsing; /// Path resolution for config directories. mod paths; /// Settings access and management. mod settings; /// Theme store and caching. mod store; /// Theme type definitions. mod types; pub use config::{ ensure_settings_keys_present, maybe_migrate_legacy_confs, save_app_start_mode, save_fuzzy_search, save_mirror_count, save_news_filter_installed_only, save_news_filter_show_advisories, save_news_filter_show_arch_news, save_news_filter_show_aur_comments, save_news_filter_show_aur_updates, save_news_filter_show_pkg_updates, save_news_filters_collapsed, save_news_max_age_days, save_scan_do_clamav, save_scan_do_custom, save_scan_do_semgrep, save_scan_do_shellcheck, save_scan_do_sleuth, save_scan_do_trivy, save_scan_do_virustotal, save_selected_countries, save_show_install_pane, save_show_keybinds_footer, save_show_recent_pane, save_sort_mode, save_startup_news_configured, save_startup_news_max_age_days, save_startup_news_show_advisories, save_startup_news_show_arch_news, save_startup_news_show_aur_comments, save_startup_news_show_aur_updates, save_startup_news_show_pkg_updates, save_virustotal_api_key, }; pub use paths::{config_dir, lists_dir, logs_dir}; pub use settings::settings; pub use store::{reload_theme, theme}; pub use types::{KeyChord, KeyMap, PackageMarker, Settings, Theme}; #[cfg(test)] static TEST_MUTEX: std::sync::OnceLock<std::sync::Mutex<()>> = std::sync::OnceLock::new(); #[cfg(test)] /// What: Provide a process-wide mutex to serialize filesystem-mutating tests in this module. /// /// Inputs: /// - None /// /// Output: /// - Shared reference to a lazily-initialized `Mutex<()>`. /// /// Details: /// - Uses `OnceLock` to ensure the mutex is constructed exactly once per process. /// - Callers should lock the mutex to guard environment-variable or disk state changes. pub(crate) fn test_mutex() -> &'static std::sync::Mutex<()> { TEST_MUTEX.get_or_init(|| std::sync::Mutex::new(())) }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/theme/parsing.rs
src/theme/parsing.rs
use crossterm::event::KeyCode; use ratatui::style::Color; use super::types::KeyChord; use crossterm::event::KeyModifiers; /// What: Parse a single key identifier (e.g., "F5", "Esc", "?", "r") into a [`KeyCode`]. /// /// Inputs: /// - `s`: Raw key token from a configuration string. /// /// Output: /// - `Some(KeyCode)` on success; `None` when the input token is unsupported. /// /// Details: /// - Supports function keys, navigation keys, and single printable characters. /// - Normalizes character keys to lowercase for consistent matching. pub(super) fn parse_key_identifier(s: &str) -> Option<KeyCode> { let t = s.trim(); // Function keys if let Some(num) = t.strip_prefix('F').and_then(|x| x.parse::<u8>().ok()) { return Some(KeyCode::F(num)); } match t.to_ascii_uppercase().as_str() { "ESC" => Some(KeyCode::Esc), "ENTER" | "RETURN" => Some(KeyCode::Enter), "TAB" => Some(KeyCode::Tab), "BACKTAB" | "SHIFT+TAB" => Some(KeyCode::BackTab), "BACKSPACE" => Some(KeyCode::Backspace), "DELETE" | "DEL" => Some(KeyCode::Delete), "INSERT" | "INS" => Some(KeyCode::Insert), "HOME" => Some(KeyCode::Home), "END" => Some(KeyCode::End), "PAGEUP" | "PGUP" => Some(KeyCode::PageUp), "PAGEDOWN" | "PGDN" => Some(KeyCode::PageDown), "UP" | "ARROWUP" => Some(KeyCode::Up), "DOWN" | "ARROWDOWN" => Some(KeyCode::Down), "LEFT" | "ARROWLEFT" => Some(KeyCode::Left), "RIGHT" | "ARROWRIGHT" => Some(KeyCode::Right), "SPACE" => Some(KeyCode::Char(' ')), _ => { // Single visible character, e.g. "?" or "r"; normalize to lowercase let mut chars = t.chars(); if let (Some(ch), None) = (chars.next(), chars.next()) { Some(KeyCode::Char(ch.to_ascii_lowercase())) } else { None } } } } /// What: Parse a full key chord such as "Ctrl+R" or "Shift+Tab" into a [`KeyChord`]. /// /// Inputs: /// - `spec`: String specification combining optional modifiers with a key token. /// /// Output: /// - `Some(KeyChord)` when parsing succeeds; `None` on invalid modifier/key combinations. /// /// Details: /// - Recognizes Ctrl/Alt/Shift/Super modifiers in any case. /// - Normalizes `Shift+Tab` to the dedicated `BackTab` key code and clears modifiers. pub(super) fn parse_key_chord(spec: &str) -> Option<KeyChord> { // Accept formats like: CTRL+R, Alt+?, Shift+Del, F1, Tab, BackTab, Super+F2 let mut mods = KeyModifiers::empty(); let mut key_part: Option<String> = None; for part in spec.split('+') { let p = part.trim(); if p.is_empty() { continue; } match p.to_ascii_uppercase().as_str() { "CTRL" | "CONTROL" => mods |= KeyModifiers::CONTROL, "ALT" => mods |= KeyModifiers::ALT, "SHIFT" => mods |= KeyModifiers::SHIFT, "SUPER" | "META" | "WIN" => mods |= KeyModifiers::SUPER, other => { key_part = Some(other.to_string()); } } } // Special-case Shift+Tab -> BackTab (mods cleared) if key_part.as_deref() == Some("TAB") && mods.contains(KeyModifiers::SHIFT) { return Some(KeyChord { code: KeyCode::BackTab, mods: KeyModifiers::empty(), }); } let code = parse_key_identifier(key_part.as_deref().unwrap_or(""))?; Some(KeyChord { code, mods }) } /// What: Parse a color literal from configuration text into a [`Color`]. /// /// Inputs: /// - `s`: Color specification string potentially containing inline comments. /// /// Output: /// - `Some(Color)` for recognized hex or decimal triplet formats; `None` otherwise. /// /// Details: /// - Strips trailing comments beginning with `//` or secondary `#` markers. /// - Accepts `#RRGGBB` hex and `R,G,B` decimal triplets (0-255 per channel). #[allow(clippy::many_single_char_names)] pub(super) fn parse_color_value(s: &str) -> Option<Color> { // Trim and strip inline comments (support trailing "// ..." and "# ..."). // Preserve a leading '#' for hex values by searching for '#' only after position 1. let mut t = s.trim(); // Strip // comments first if let Some(i) = t.find("//") { t = &t[..i]; } // Strip # comments, but preserve leading # for hex colors // Look for # after position 1 (to preserve #RRGGBB format) if let Some(i) = t.char_indices().skip(1).find(|(_, ch)| *ch == '#') { t = &t[..i.0]; } t = t.trim(); if t.is_empty() { return None; } // Hex formats: #RRGGBB or RRGGBB let h = t.strip_prefix('#').unwrap_or(t); if h.len() == 6 && h.chars().all(|c| c.is_ascii_hexdigit()) { let r = u8::from_str_radix(&h[0..2], 16).ok()?; let g = u8::from_str_radix(&h[2..4], 16).ok()?; let b = u8::from_str_radix(&h[4..6], 16).ok()?; return Some(Color::Rgb(r, g, b)); } // Decimal triplet: R,G,B if let Some((r, g, b)) = t.split(',').collect::<Vec<_>>().get(0..3).and_then(|v| { let r = v[0].trim().parse::<u16>().ok()?; let g = v[1].trim().parse::<u16>().ok()?; let b = v[2].trim().parse::<u16>().ok()?; Some((r, g, b)) }) && r <= 255 && g <= 255 && b <= 255 { return Some(Color::Rgb( u8::try_from(r).unwrap_or(255), u8::try_from(g).unwrap_or(255), u8::try_from(b).unwrap_or(255), )); } None } /// What: Map a normalized theme key (lowercase, underscores) to Pacsea's canonical key. /// /// Inputs: /// - `norm`: Normalized key string pulled from user configuration. /// /// Output: /// - `Some(&'static str)` containing the canonical key when recognized; `None` otherwise. /// /// Details: /// - Handles legacy and alternative naming schemes to preserve backwards compatibility. pub(super) fn canonical_for_key(norm: &str) -> Option<&'static str> { match norm { // Legacy and comprehensive keys mapped to canonical names "base" | "background" | "background_base" => Some("base"), "mantle" | "background_mantle" => Some("mantle"), "crust" | "background_crust" => Some("crust"), "surface1" | "surface_1" | "surface_level1" => Some("surface1"), "surface2" | "surface_2" | "surface_level2" => Some("surface2"), "overlay1" | "overlay_primary" | "border_primary" => Some("overlay1"), "overlay2" | "overlay_secondary" | "border_secondary" => Some("overlay2"), "text" | "text_primary" => Some("text"), "subtext0" | "text_secondary" => Some("subtext0"), "subtext1" | "text_tertiary" => Some("subtext1"), "sapphire" | "accent_interactive" | "accent_info" => Some("sapphire"), "mauve" | "accent_heading" | "accent_primary" => Some("mauve"), "green" | "semantic_success" => Some("green"), "yellow" | "semantic_warning" => Some("yellow"), "red" | "semantic_error" => Some("red"), "lavender" | "accent_emphasis" | "accent_border" => Some("lavender"), _ => None, } } /// What: Convert a canonical theme key into the preferred, user-facing identifier. /// /// Inputs: /// - `canon`: Canonical key such as `"overlay1"`. /// /// Output: /// - `String` containing the display-friendly key for messaging. /// /// Details: /// - Favors descriptive names (e.g., `overlay_primary`) when available. pub(super) fn canonical_to_preferred(canon: &str) -> String { match canon { "base" => "background_base", "mantle" => "background_mantle", "crust" => "background_crust", "surface1" => "surface_level1", "surface2" => "surface_level2", "overlay1" => "overlay_primary", "overlay2" => "overlay_secondary", "text" => "text_primary", "subtext0" => "text_secondary", "subtext1" => "text_tertiary", "sapphire" => "accent_interactive", "mauve" => "accent_heading", "green" => "semantic_success", "yellow" => "semantic_warning", "red" => "semantic_error", "lavender" => "accent_emphasis", _ => canon, } .to_string() } /// What: Apply a single `key=value` override to the theme color map with validation. /// /// Inputs: /// - `map`: Accumulated theme colors being constructed. /// - `key`: Raw key string from the configuration file. /// - `value`: Raw value string associated with the key. /// - `errors`: Mutable buffer that collects diagnostic messages. /// - `line_no`: 1-based line number used for contextual messages. /// /// Output: /// - None (mutates `map` and `errors` in place). /// /// Details: /// - Normalizes keys, suggests close matches, and validates color formats before inserting. pub(super) fn apply_override_to_map( map: &mut std::collections::HashMap<String, Color>, key: &str, value: &str, errors: &mut Vec<String>, line_no: usize, ) { let norm = key.trim().to_lowercase().replace(['.', '-', ' '], "_"); let Some(canon) = canonical_for_key(&norm) else { let suggestion = nearest_key(&norm); if let Some(s) = suggestion { errors.push(format!( "- Unknown key '{}' on line {} (did you mean '{}'?)", key, line_no, canonical_to_preferred(s) )); } else { errors.push(format!("- Unknown key '{key}' on line {line_no}")); } return; }; if value.is_empty() { errors.push(format!("- Missing value for '{key}' on line {line_no}")); return; } parse_color_value(value).map_or_else( || { errors.push(format!( "- Invalid color for '{key}' on line {line_no} (use #RRGGBB or R,G,B)" )); }, |c| { map.insert(canon.to_string(), c); }, ); } /// What: Suggest the canonical key closest to a potentially misspelled input. /// /// Inputs: /// - `input`: User-provided key string. /// /// Output: /// - `Some(&'static str)` when the best match is within edit distance 3; `None` otherwise. /// /// Details: /// - Computes Levenshtein distance across the small known key set for quick suggestion hints. pub(super) fn nearest_key(input: &str) -> Option<&'static str> { // Very small domain; simple Levenshtein distance is fine const CANON: [&str; 16] = [ "base", "mantle", "crust", "surface1", "surface2", "overlay1", "overlay2", "text", "subtext0", "subtext1", "sapphire", "mauve", "green", "yellow", "red", "lavender", ]; let mut best: Option<(&'static str, usize)> = None; for &k in &CANON { let d = levenshtein(input, k); if best.is_none_or(|(_, bd)| d < bd) { best = Some((k, d)); } } best.and_then(|(k, d)| if d <= 3 { Some(k) } else { None }) } /// What: Compute the Levenshtein edit distance between two strings. /// /// Inputs: /// - `a`: First string. /// - `b`: Second string. /// /// Output: /// - `usize` representing the minimum number of single-character edits required to transform `a` into `b`. /// /// Details: /// - Uses a rolling dynamic programming table to reduce allocations while iterating. pub(super) fn levenshtein(a: &str, b: &str) -> usize { let m = b.len(); let mut dp: Vec<usize> = (0..=m).collect(); for (i, ca) in a.chars().enumerate() { let mut prev = dp[0]; dp[0] = i + 1; for (j, cb) in b.chars().enumerate() { let tmp = dp[j + 1]; let cost = usize::from(ca != cb); dp[j + 1] = std::cmp::min(std::cmp::min(dp[j + 1] + 1, dp[j] + 1), prev + cost); prev = tmp; } } dp[m] } /// What: Remove inline comments from a configuration line while preserving leading hex markers. /// /// Inputs: /// - `s`: Raw configuration line that may include inline comments. /// /// Output: /// - Comment-free & trimmed substring of the input. /// /// Details: /// - Strips trailing `//` sections and secondary `#` characters without harming leading `#RRGGBB` values. pub(super) fn strip_inline_comment(mut s: &str) -> &str { // Strip // comments first, but preserve // in URLs (http://, https://) // Find all occurrences of // and check each one let mut comment_start = None; for (i, _) in s.match_indices("//") { // Check if this // is part of a URL scheme (preceded by :) if i > 0 && s.as_bytes().get(i - 1) == Some(&b':') { // This is part of a URL scheme (http:// or https://), skip it continue; } // This // is likely a comment delimiter comment_start = Some(i); break; } if let Some(i) = comment_start { s = &s[..i]; } // Strip # comments, but preserve leading # for hex colors // Look for # after position 1 (to preserve #RRGGBB format) if let Some(i) = s.char_indices().skip(1).find(|(_, ch)| *ch == '#') { s = &s[..i.0]; } s.trim() } #[cfg(test)] mod tests { use super::*; #[test] /// What: Ensure key identifier and chord parsing maps strings onto `KeyCode`/modifier combinations. /// /// Inputs: /// - Identifiers such as `F5`, `?`, and `Backspace`, plus chord strings `Ctrl+R` and `Shift+Tab`. /// /// Output: /// - Returns matching `KeyCode` values with expected modifier flags. /// /// Details: /// - Guards against regressions when adding new key parsing rules. fn parsing_key_identifier_and_chord() { assert_eq!(parse_key_identifier("F5"), Some(KeyCode::F(5))); assert_eq!(parse_key_identifier("?"), Some(KeyCode::Char('?'))); assert_eq!(parse_key_identifier("Backspace"), Some(KeyCode::Backspace)); let kc = parse_key_chord("Ctrl+R").expect("Ctrl+R should be a valid key chord"); assert_eq!(kc.code, KeyCode::Char('r')); assert!(kc.mods.contains(KeyModifiers::CONTROL)); let bt = parse_key_chord("Shift+Tab").expect("Shift+Tab should be a valid key chord"); assert_eq!(bt.code, KeyCode::BackTab); assert!(bt.mods.is_empty()); let sr = parse_key_chord("Shift+R").expect("Shift+R should be a valid key chord"); assert_eq!(sr.code, KeyCode::Char('r')); assert!(sr.mods.contains(KeyModifiers::SHIFT)); assert!(!sr.mods.contains(KeyModifiers::CONTROL)); } #[test] /// What: Validate colour parsing and mapping helpers used by theme configuration. /// /// Inputs: /// - Hex and RGB strings plus canonical key identifiers. /// /// Output: /// - Produces `Color::Rgb` values when parsable and resolves preferred canonical keys. /// /// Details: /// - Exercises both parsing paths and fuzzy key lookup to preserve user overrides. fn parsing_color_and_canon() { assert_eq!(parse_color_value("#ff0000"), Some(Color::Rgb(255, 0, 0))); assert_eq!(parse_color_value("255,0,10"), Some(Color::Rgb(255, 0, 10))); assert!(parse_color_value("").is_none()); assert_eq!(canonical_for_key("background_base"), Some("base")); assert_eq!(canonical_to_preferred("overlay1"), "overlay_primary"); assert!(nearest_key("bas").is_some()); } #[test] /// What: Check inline comment stripping keeps colour literals while removing trailing annotations. /// /// Inputs: /// - Strings containing hex colours, `//` comments, and secondary `#` markers. /// /// Output: /// - Returns trimmed strings with comments removed but leading hex markers preserved. /// /// Details: /// - Confirms heuristics avoid truncating six-digit colour codes while cleaning inline comments. fn parsing_strip_inline_comment_variants() { // Leading '#' preserved for hex; we only strip after first character to allow '#RRGGBB' assert_eq!(strip_inline_comment("#foo"), "#foo"); assert_eq!(strip_inline_comment("abc // hi"), "abc"); assert_eq!(strip_inline_comment("#ff00ff # tail"), "#ff00ff"); // URLs with // should be preserved assert_eq!( strip_inline_comment("https://example.com/path"), "https://example.com/path" ); assert_eq!( strip_inline_comment("https://gist.github.com/user/id/raw/file.json"), "https://gist.github.com/user/id/raw/file.json" ); // URL followed by comment should preserve URL assert_eq!( strip_inline_comment("https://example.com // comment"), "https://example.com" ); } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/theme/settings/parse_settings.rs
src/theme/settings/parse_settings.rs
use std::path::Path; use crate::theme::parsing::strip_inline_comment; use crate::theme::types::{PackageMarker, Settings}; /// What: Parse a boolean value from config string. /// /// Inputs: /// - `val`: Value string from config /// /// Output: /// - `true` if value represents true, `false` otherwise /// /// Details: /// - Accepts "true", "1", "yes", "on" (case-insensitive) fn parse_bool(val: &str) -> bool { let lv = val.to_ascii_lowercase(); lv == "true" || lv == "1" || lv == "yes" || lv == "on" } /// What: Parse layout settings. /// /// Inputs: /// - `key`: Normalized config key /// - `val`: Config value /// - `settings`: Mutable settings to update /// /// Output: /// - `true` if key was handled, `false` otherwise fn parse_layout_settings(key: &str, val: &str, settings: &mut Settings) -> bool { match key { "layout_left_pct" => { if let Ok(v) = val.parse::<u16>() { settings.layout_left_pct = v; } true } "layout_center_pct" => { if let Ok(v) = val.parse::<u16>() { settings.layout_center_pct = v; } true } "layout_right_pct" => { if let Ok(v) = val.parse::<u16>() { settings.layout_right_pct = v; } true } _ => false, } } /// What: Parse app/UI settings. /// /// Inputs: /// - `key`: Normalized config key /// - `val`: Config value /// - `settings`: Mutable settings to update /// /// Output: /// - `true` if key was handled, `false` otherwise fn parse_app_settings(key: &str, val: &str, settings: &mut Settings) -> bool { match key { "app_dry_run_default" => { settings.app_dry_run_default = parse_bool(val); true } "sort_mode" | "results_sort" => { if let Some(sm) = crate::state::SortMode::from_config_key(val) { settings.sort_mode = sm; } true } "clipboard_suffix" | "copy_suffix" => { settings.clipboard_suffix = val.to_string(); true } "show_search_history_pane" | "show_recent_pane" | "recent_visible" => { settings.show_recent_pane = parse_bool(val); true } "show_install_pane" | "install_visible" | "show_install_list" => { settings.show_install_pane = parse_bool(val); true } "show_keybinds_footer" | "keybinds_visible" => { settings.show_keybinds_footer = parse_bool(val); true } "package_marker" => { let lv = val.to_ascii_lowercase(); settings.package_marker = match lv.as_str() { "full" | "full_line" | "line" | "color_line" | "color" => PackageMarker::FullLine, "end" | "suffix" => PackageMarker::End, _ => PackageMarker::Front, }; true } "skip_preflight" | "preflight_skip" | "bypass_preflight" => { settings.skip_preflight = parse_bool(val); true } _ => false, } } /// What: Parse scan-related settings. /// /// Inputs: /// - `key`: Normalized config key /// - `val`: Config value /// - `settings`: Mutable settings to update /// /// Output: /// - `true` if key was handled, `false` otherwise fn parse_scan_settings(key: &str, val: &str, settings: &mut Settings) -> bool { match key { "scan_do_clamav" => { settings.scan_do_clamav = parse_bool(val); true } "scan_do_trivy" => { settings.scan_do_trivy = parse_bool(val); true } "scan_do_semgrep" => { settings.scan_do_semgrep = parse_bool(val); true } "scan_do_shellcheck" => { settings.scan_do_shellcheck = parse_bool(val); true } "scan_do_virustotal" => { settings.scan_do_virustotal = parse_bool(val); true } "scan_do_custom" => { settings.scan_do_custom = parse_bool(val); true } "scan_do_sleuth" => { settings.scan_do_sleuth = parse_bool(val); true } "virustotal_api_key" | "vt_api_key" | "virustotal" => { // VirusTotal API key; stored as-is and trimmed later settings.virustotal_api_key = val.to_string(); true } _ => false, } } /// What: Parse mirror and country settings. /// /// Inputs: /// - `key`: Normalized config key /// - `val`: Config value /// - `settings`: Mutable settings to update /// /// Output: /// - `true` if key was handled, `false` otherwise fn parse_mirror_settings(key: &str, val: &str, settings: &mut Settings) -> bool { match key { "selected_countries" | "countries" | "country" => { // Accept comma-separated list; trimming occurs in normalization settings.selected_countries = val.to_string(); true } "mirror_count" | "mirrors" => { if let Ok(v) = val.parse::<u16>() { settings.mirror_count = v; } true } _ => false, } } /// What: Parse news-related settings. /// /// Inputs: /// - `key`: Normalized config key /// - `val`: Config value /// - `settings`: Mutable settings to update /// /// Output: /// - `true` if key was handled, `false` otherwise fn parse_news_settings(key: &str, val: &str, settings: &mut Settings) -> bool { match key { "news_read_symbol" | "news_read_mark" => { settings.news_read_symbol = val.to_string(); true } "news_unread_symbol" | "news_unread_mark" => { settings.news_unread_symbol = val.to_string(); true } "news_filter_show_arch_news" | "news_filter_arch" => { settings.news_filter_show_arch_news = parse_bool(val); true } "news_filter_show_advisories" | "news_filter_advisories" => { settings.news_filter_show_advisories = parse_bool(val); true } "news_filter_show_pkg_updates" | "news_filter_pkg_updates" | "news_filter_updates" => { settings.news_filter_show_pkg_updates = parse_bool(val); true } "news_filter_show_aur_updates" | "news_filter_aur_updates" | "news_filter_aur_upd" | "news_filter_aur_upd_updates" => { settings.news_filter_show_aur_updates = parse_bool(val); true } "news_filter_show_aur_comments" | "news_filter_aur_comments" | "news_filter_comments" => { settings.news_filter_show_aur_comments = parse_bool(val); true } "news_filter_installed_only" | "news_filter_installed" | "news_installed_only" => { settings.news_filter_installed_only = parse_bool(val); true } "news_max_age_days" | "news_age_days" | "news_age" => { let lv = val.trim().to_ascii_lowercase(); settings.news_max_age_days = match lv.as_str() { "" | "all" | "none" | "unlimited" => None, _ => val.parse::<u32>().ok(), }; true } "startup_news_configured" => { settings.startup_news_configured = parse_bool(val); true } "startup_news_show_arch_news" => { settings.startup_news_show_arch_news = parse_bool(val); true } "startup_news_show_advisories" => { settings.startup_news_show_advisories = parse_bool(val); true } "startup_news_show_aur_updates" => { settings.startup_news_show_aur_updates = parse_bool(val); true } "startup_news_show_aur_comments" => { settings.startup_news_show_aur_comments = parse_bool(val); true } "startup_news_show_pkg_updates" => { settings.startup_news_show_pkg_updates = parse_bool(val); true } "startup_news_max_age_days" => { let lv = val.trim().to_ascii_lowercase(); settings.startup_news_max_age_days = match lv.as_str() { "" | "all" | "none" | "unlimited" => None, _ => val.parse::<u32>().ok(), }; true } "news_cache_ttl_days" => { if let Ok(days) = val.parse::<u32>() { settings.news_cache_ttl_days = days.max(1); // Minimum 1 day } true } _ => false, } } /// What: Parse search-related settings. /// /// Inputs: /// - `key`: Normalized config key /// - `val`: Config value /// - `settings`: Mutable settings to update /// /// Output: /// - `true` if key was handled, `false` otherwise fn parse_search_settings(key: &str, val: &str, settings: &mut Settings) -> bool { match key { "search_startup_mode" | "startup_mode" | "search_mode" => { let lv = val.to_ascii_lowercase(); // Accept both boolean and mode name formats settings.search_startup_mode = lv == "true" || lv == "1" || lv == "yes" || lv == "on" || lv == "normal_mode" || lv == "normal"; true } "fuzzy_search" | "fuzzy_search_enabled" | "fuzzy_mode" => { settings.fuzzy_search = parse_bool(val); true } _ => false, } } /// What: Parse miscellaneous settings. /// /// Inputs: /// - `key`: Normalized config key /// - `val`: Config value /// - `settings`: Mutable settings to update /// /// Output: /// - `true` if key was handled, `false` otherwise fn parse_misc_settings(key: &str, val: &str, settings: &mut Settings) -> bool { match key { "preferred_terminal" | "terminal_preferred" | "terminal" => { settings.preferred_terminal = val.to_string(); true } "app_start_mode" | "start_mode" | "start_in_news" => { let lv = val.trim().to_ascii_lowercase(); settings.start_in_news = matches!(lv.as_str(), "news" | "true" | "1" | "on" | "yes"); true } "locale" | "language" => { settings.locale = val.trim().to_string(); true } "updates_refresh_interval" | "updates_interval" | "refresh_interval" => { if let Ok(v) = val.parse::<u64>() { // Ensure minimum value of 1 second to prevent invalid intervals settings.updates_refresh_interval = v.max(1); } true } "get_announcement" | "get_announcements" => { settings.get_announcement = parse_bool(val.trim()); true } "installed_packages_mode" | "installed_mode" | "installed_filter" => { if let Some(mode) = crate::state::InstalledPackagesMode::from_config_key(val) { settings.installed_packages_mode = mode; } true } _ => false, } } /// What: Parse non-keybind settings from settings.conf content. /// /// Inputs: /// - `content`: Content of the settings.conf file as a string. /// - `_settings_path`: Path to the settings.conf file (for appending defaults). /// - `settings`: Mutable reference to `Settings` to populate. /// /// Output: /// - None (modifies `settings` in-place). /// /// Details: /// - Parses layout percentages, app settings, scan settings, and other configuration. /// - Missing settings are handled by `ensure_settings_keys_present` with proper comments. /// - Intentionally ignores keybind_* entries (handled separately). pub fn parse_settings(content: &str, _settings_path: &Path, settings: &mut Settings) { for line in content.lines() { let trimmed = line.trim(); if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("//") { continue; } if !trimmed.contains('=') { continue; } let mut parts = trimmed.splitn(2, '='); let raw_key = parts.next().unwrap_or(""); let key = raw_key.trim().to_lowercase().replace(['.', '-', ' '], "_"); let val_raw = parts.next().unwrap_or("").trim(); let val = strip_inline_comment(val_raw); // Try each category parser in order // Note: we intentionally ignore keybind_* in settings.conf now; keybinds load below let _ = parse_layout_settings(&key, val, settings) || parse_app_settings(&key, val, settings) || parse_scan_settings(&key, val, settings) || parse_mirror_settings(&key, val, settings) || parse_news_settings(&key, val, settings) || parse_search_settings(&key, val, settings) || parse_misc_settings(&key, val, settings); } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/theme/settings/parse_keybinds.rs
src/theme/settings/parse_keybinds.rs
use crate::theme::parsing::{parse_key_chord, strip_inline_comment}; use crate::theme::types::{KeyChord, Settings}; /// What: Assign a parsed key chord to a keymap field, replacing any existing bindings. /// /// Inputs: /// - `chord`: Optional parsed key chord. /// - `target`: Mutable reference to the target vector in the keymap. /// /// Output: /// - None (modifies `target` in-place). /// /// Details: /// - If parsing succeeds, replaces the entire vector with a single-element vector containing the chord. /// - If parsing fails, the target vector remains unchanged. fn assign_keybind(chord: Option<KeyChord>, target: &mut Vec<KeyChord>) { if let Some(ch) = chord { *target = vec![ch]; } } /// What: Add a parsed key chord to a keymap field, avoiding duplicates. /// /// Inputs: /// - `chord`: Optional parsed key chord. /// - `target`: Mutable reference to the target vector in the keymap. /// /// Output: /// - None (modifies `target` in-place). /// /// Details: /// - If parsing succeeds and the chord is not already present (same code and modifiers), appends it to the vector. /// - If parsing fails or the chord already exists, the target vector remains unchanged. fn assign_keybind_with_duplicate_check(chord: Option<KeyChord>, target: &mut Vec<KeyChord>) { if let Some(ch) = chord && target .iter() .all(|c| c.code != ch.code || c.mods != ch.mods) { target.push(ch); } } /// What: Apply a parsed key chord to global keymap fields. /// /// Inputs: /// - `key`: Normalized keybind name (lowercase, underscores). /// - `chord`: Optional parsed key chord. /// - `settings`: Mutable reference to `Settings` to populate keybinds. /// /// Output: /// - `true` if the key was handled, `false` otherwise. /// /// Details: /// - Handles global keybinds (help, menus, panes, etc.). /// - Returns `true` if the key matched a global keybind pattern. fn apply_global_keybind(key: &str, chord: Option<KeyChord>, settings: &mut Settings) -> bool { match key { "keybind_help" | "keybind_help_overlay" => { assign_keybind(chord, &mut settings.keymap.help_overlay); true } "keybind_toggle_config" | "keybind_config_menu" | "keybind_config_lists" => { assign_keybind(chord, &mut settings.keymap.config_menu_toggle); true } "keybind_toggle_options" | "keybind_options_menu" => { assign_keybind(chord, &mut settings.keymap.options_menu_toggle); true } "keybind_toggle_panels" | "keybind_panels_menu" => { assign_keybind(chord, &mut settings.keymap.panels_menu_toggle); true } "keybind_reload_config" | "keybind_reload_theme" | "keybind_reload" => { assign_keybind(chord, &mut settings.keymap.reload_config); true } "keybind_exit" | "keybind_quit" => { assign_keybind(chord, &mut settings.keymap.exit); true } "keybind_show_pkgbuild" | "keybind_pkgbuild" | "keybind_toggle_pkgbuild" => { assign_keybind(chord, &mut settings.keymap.show_pkgbuild); true } "keybind_comments_toggle" | "keybind_show_comments" | "keybind_toggle_comments" => { assign_keybind(chord, &mut settings.keymap.comments_toggle); true } "keybind_change_sort" | "keybind_sort" => { assign_keybind(chord, &mut settings.keymap.change_sort); true } "keybind_pane_next" | "keybind_next_pane" | "keybind_switch_pane" => { assign_keybind(chord, &mut settings.keymap.pane_next); true } "keybind_pane_left" => { assign_keybind(chord, &mut settings.keymap.pane_left); true } "keybind_pane_right" => { assign_keybind(chord, &mut settings.keymap.pane_right); true } _ => false, } } /// What: Apply a parsed key chord to search pane keymap fields. /// /// Inputs: /// - `key`: Normalized keybind name (lowercase, underscores). /// - `chord`: Optional parsed key chord. /// - `settings`: Mutable reference to `Settings` to populate keybinds. /// /// Output: /// - `true` if the key was handled, `false` otherwise. /// /// Details: /// - Handles search pane keybinds (navigation, actions, normal mode, etc.). /// - Returns `true` if the key matched a search pane keybind pattern. fn apply_search_keybind(key: &str, chord: Option<KeyChord>, settings: &mut Settings) -> bool { match key { "keybind_search_move_up" => { assign_keybind(chord, &mut settings.keymap.search_move_up); true } "keybind_search_move_down" => { assign_keybind(chord, &mut settings.keymap.search_move_down); true } "keybind_search_page_up" => { assign_keybind(chord, &mut settings.keymap.search_page_up); true } "keybind_search_page_down" => { assign_keybind(chord, &mut settings.keymap.search_page_down); true } "keybind_search_add" => { assign_keybind(chord, &mut settings.keymap.search_add); true } "keybind_search_install" => { assign_keybind(chord, &mut settings.keymap.search_install); true } "keybind_search_focus_left" => { assign_keybind(chord, &mut settings.keymap.search_focus_left); true } "keybind_search_focus_right" => { assign_keybind(chord, &mut settings.keymap.search_focus_right); true } "keybind_search_backspace" => { assign_keybind(chord, &mut settings.keymap.search_backspace); true } "keybind_search_insert_clear" => { assign_keybind(chord, &mut settings.keymap.search_insert_clear); true } "keybind_search_normal_toggle" => { assign_keybind(chord, &mut settings.keymap.search_normal_toggle); true } "keybind_search_normal_insert" => { assign_keybind(chord, &mut settings.keymap.search_normal_insert); true } "keybind_search_normal_select_left" => { assign_keybind(chord, &mut settings.keymap.search_normal_select_left); true } "keybind_search_normal_select_right" => { assign_keybind(chord, &mut settings.keymap.search_normal_select_right); true } "keybind_search_normal_delete" => { assign_keybind(chord, &mut settings.keymap.search_normal_delete); true } "keybind_search_normal_clear" => { assign_keybind(chord, &mut settings.keymap.search_normal_clear); true } "keybind_search_normal_open_status" | "keybind_normal_open_status" | "keybind_open_status" => { assign_keybind(chord, &mut settings.keymap.search_normal_open_status); true } "keybind_search_normal_import" => { assign_keybind(chord, &mut settings.keymap.search_normal_import); true } "keybind_search_normal_export" => { assign_keybind(chord, &mut settings.keymap.search_normal_export); true } "keybind_search_normal_updates" => { assign_keybind(chord, &mut settings.keymap.search_normal_updates); true } "keybind_toggle_fuzzy" | "keybind_fuzzy_toggle" => { assign_keybind(chord, &mut settings.keymap.toggle_fuzzy); true } _ => false, } } /// What: Apply a parsed key chord to recent pane keymap fields. /// /// Inputs: /// - `key`: Normalized keybind name (lowercase, underscores). /// - `chord`: Optional parsed key chord. /// - `settings`: Mutable reference to `Settings` to populate keybinds. /// /// Output: /// - `true` if the key was handled, `false` otherwise. /// /// Details: /// - Handles recent pane keybinds (navigation, actions, etc.). /// - Returns `true` if the key matched a recent pane keybind pattern. /// - Uses duplicate checking for `recent_remove` to allow multiple bindings. fn apply_recent_keybind(key: &str, chord: Option<KeyChord>, settings: &mut Settings) -> bool { match key { "keybind_recent_move_up" => { assign_keybind(chord, &mut settings.keymap.recent_move_up); true } "keybind_recent_move_down" => { assign_keybind(chord, &mut settings.keymap.recent_move_down); true } "keybind_recent_find" => { assign_keybind(chord, &mut settings.keymap.recent_find); true } "keybind_recent_use" => { assign_keybind(chord, &mut settings.keymap.recent_use); true } "keybind_recent_add" => { assign_keybind(chord, &mut settings.keymap.recent_add); true } "keybind_recent_to_search" => { assign_keybind(chord, &mut settings.keymap.recent_to_search); true } "keybind_recent_focus_right" => { assign_keybind(chord, &mut settings.keymap.recent_focus_right); true } "keybind_recent_remove" => { assign_keybind_with_duplicate_check(chord, &mut settings.keymap.recent_remove); true } "keybind_recent_clear" => { assign_keybind(chord, &mut settings.keymap.recent_clear); true } _ => false, } } /// What: Apply a parsed key chord to install pane keymap fields. /// /// Inputs: /// - `key`: Normalized keybind name (lowercase, underscores). /// - `chord`: Optional parsed key chord. /// - `settings`: Mutable reference to `Settings` to populate keybinds. /// /// Output: /// - `true` if the key was handled, `false` otherwise. /// /// Details: /// - Handles install pane keybinds (navigation, actions, etc.). /// - Returns `true` if the key matched an install pane keybind pattern. /// - Uses duplicate checking for `install_remove` to allow multiple bindings. fn apply_install_keybind(key: &str, chord: Option<KeyChord>, settings: &mut Settings) -> bool { match key { "keybind_install_move_up" => { assign_keybind(chord, &mut settings.keymap.install_move_up); true } "keybind_install_move_down" => { assign_keybind(chord, &mut settings.keymap.install_move_down); true } "keybind_install_confirm" => { assign_keybind(chord, &mut settings.keymap.install_confirm); true } "keybind_install_remove" => { assign_keybind_with_duplicate_check(chord, &mut settings.keymap.install_remove); true } "keybind_install_clear" => { assign_keybind(chord, &mut settings.keymap.install_clear); true } "keybind_install_find" => { assign_keybind(chord, &mut settings.keymap.install_find); true } "keybind_install_to_search" => { assign_keybind(chord, &mut settings.keymap.install_to_search); true } "keybind_install_focus_left" => { assign_keybind(chord, &mut settings.keymap.install_focus_left); true } _ => false, } } /// What: Apply a parsed key chord to news modal keymap fields. /// /// Inputs: /// - `key`: Normalized keybind name (lowercase, underscores). /// - `chord`: Optional parsed key chord. /// - `settings`: Mutable reference to `Settings` to populate keybinds. /// /// Output: /// - `true` if the key was handled, `false` otherwise. /// /// Details: /// - Handles news modal keybinds. /// - Returns `true` if the key matched a news modal keybind pattern. fn apply_news_keybind(key: &str, chord: Option<KeyChord>, settings: &mut Settings) -> bool { match key { "keybind_news_mark_read" => { if chord.is_none() { tracing::warn!("Failed to parse keybind_news_mark_read"); } assign_keybind(chord, &mut settings.keymap.news_mark_read); true } "keybind_news_mark_all_read" => { if chord.is_none() { tracing::warn!("Failed to parse keybind_news_mark_all_read"); } assign_keybind(chord, &mut settings.keymap.news_mark_all_read); true } "keybind_news_feed_mark_read" => { if chord.is_none() { tracing::warn!("Failed to parse keybind_news_feed_mark_read"); } assign_keybind(chord, &mut settings.keymap.news_mark_read_feed); true } "keybind_news_feed_mark_unread" => { if chord.is_none() { tracing::warn!("Failed to parse keybind_news_feed_mark_unread"); } assign_keybind(chord, &mut settings.keymap.news_mark_unread_feed); true } "keybind_news_feed_toggle_read" => { if chord.is_none() { tracing::warn!("Failed to parse keybind_news_feed_toggle_read"); } assign_keybind(chord, &mut settings.keymap.news_toggle_read_feed); true } _ => false, } } /// What: Apply a parsed key chord to the appropriate keymap field based on the key name. /// /// Inputs: /// - `key`: Normalized keybind name (lowercase, underscores). /// - `chord`: Optional parsed key chord. /// - `settings`: Mutable reference to `Settings` to populate keybinds. /// /// Output: /// - None (modifies `settings.keymap` in-place). /// /// Details: /// - Routes the chord to the correct category-specific handler function. /// - Handles both single-assignment and duplicate-checking assignment patterns. fn apply_keybind(key: &str, chord: Option<KeyChord>, settings: &mut Settings) { if apply_global_keybind(key, chord, settings) { return; } if apply_search_keybind(key, chord, settings) { return; } if apply_recent_keybind(key, chord, settings) { return; } if apply_install_keybind(key, chord, settings) { return; } apply_news_keybind(key, chord, settings); } /// What: Parse keybind entries from configuration file content. /// /// Inputs: /// - `content`: Content of the configuration file (keybinds.conf or settings.conf) as a string. /// - `settings`: Mutable reference to `Settings` to populate keybinds. /// /// Output: /// - None (modifies `settings.keymap` in-place). /// /// Details: /// - Parses all keybind_* entries from the content. /// - Handles both dedicated keybinds.conf format and legacy settings.conf format. /// - For some keybinds (`recent_remove`, `install_remove`), allows multiple bindings by checking for duplicates. pub fn parse_keybinds(content: &str, settings: &mut Settings) { for line in content.lines() { let trimmed = line.trim(); if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("//") { continue; } if !trimmed.contains('=') { continue; } let mut parts = trimmed.splitn(2, '='); let raw_key = parts.next().unwrap_or(""); let key = raw_key.trim().to_lowercase().replace(['.', '-', ' '], "_"); let val_raw = parts.next().unwrap_or("").trim(); let val = strip_inline_comment(val_raw); let chord = parse_key_chord(val); apply_keybind(&key, chord, settings); } } #[cfg(test)] mod tests { use super::*; use crossterm::event::{KeyCode, KeyModifiers}; fn create_test_chord() -> KeyChord { KeyChord { code: KeyCode::Char('r'), mods: KeyModifiers::CONTROL, } } #[test] /// What: Ensure `apply_global_keybind` correctly assigns global keybinds and handles aliases. /// /// Inputs: /// - Various global keybind names including aliases. /// - Valid and invalid key chords. /// /// Output: /// - Returns `true` for recognized global keybinds, `false` otherwise. /// - Correctly assigns chords to the appropriate keymap fields. /// /// Details: /// - Tests primary keybind names and their aliases. /// - Verifies that invalid chords don't modify the keymap. fn test_apply_global_keybind() { let mut settings = Settings::default(); let chord = create_test_chord(); // Test primary keybind name assert!(apply_global_keybind( "keybind_help", Some(chord), &mut settings )); assert_eq!(settings.keymap.help_overlay.len(), 1); assert_eq!(settings.keymap.help_overlay[0], chord); // Test alias let mut settings2 = Settings::default(); assert!(apply_global_keybind( "keybind_help_overlay", Some(chord), &mut settings2 )); assert_eq!(settings2.keymap.help_overlay.len(), 1); // Test another keybind with multiple aliases let mut settings3 = Settings::default(); assert!(apply_global_keybind( "keybind_toggle_config", Some(chord), &mut settings3 )); assert_eq!(settings3.keymap.config_menu_toggle.len(), 1); let mut settings4 = Settings::default(); assert!(apply_global_keybind( "keybind_config_menu", Some(chord), &mut settings4 )); assert_eq!(settings4.keymap.config_menu_toggle.len(), 1); // Test invalid keybind name let mut settings5 = Settings::default(); assert!(!apply_global_keybind( "keybind_invalid", Some(chord), &mut settings5 )); // Test with None chord (should not modify) let mut settings6 = Settings::default(); let initial_len = settings6.keymap.help_overlay.len(); apply_global_keybind("keybind_help", None, &mut settings6); assert_eq!(settings6.keymap.help_overlay.len(), initial_len); } #[test] /// What: Ensure `apply_search_keybind` correctly assigns search pane keybinds. /// /// Inputs: /// - Various search pane keybind names including aliases. /// - Valid key chords. /// /// Output: /// - Returns `true` for recognized search keybinds, `false` otherwise. /// - Correctly assigns chords to the appropriate keymap fields. /// /// Details: /// - Tests search navigation, actions, and normal mode keybinds. /// - Verifies alias handling for `keybind_open_status`. fn test_apply_search_keybind() { let mut settings = Settings::default(); let chord = create_test_chord(); // Test search navigation assert!(apply_search_keybind( "keybind_search_move_up", Some(chord), &mut settings )); assert_eq!(settings.keymap.search_move_up.len(), 1); // Test search action assert!(apply_search_keybind( "keybind_search_add", Some(chord), &mut settings )); assert_eq!(settings.keymap.search_add.len(), 1); // Test alias for open_status let mut settings2 = Settings::default(); assert!(apply_search_keybind( "keybind_search_normal_open_status", Some(chord), &mut settings2 )); assert_eq!(settings2.keymap.search_normal_open_status.len(), 1); let mut settings3 = Settings::default(); assert!(apply_search_keybind( "keybind_normal_open_status", Some(chord), &mut settings3 )); assert_eq!(settings3.keymap.search_normal_open_status.len(), 1); let mut settings4 = Settings::default(); assert!(apply_search_keybind( "keybind_open_status", Some(chord), &mut settings4 )); assert_eq!(settings4.keymap.search_normal_open_status.len(), 1); // Test invalid keybind assert!(!apply_search_keybind( "keybind_invalid", Some(chord), &mut settings )); } #[test] /// What: Ensure `apply_recent_keybind` correctly assigns recent pane keybinds and handles duplicate checking. /// /// Inputs: /// - Various recent pane keybind names. /// - Valid key chords, including duplicates for `recent_remove`. /// /// Output: /// - Returns `true` for recognized recent keybinds, `false` otherwise. /// - Correctly assigns chords, allowing duplicates for `recent_remove`. /// /// Details: /// - Tests that `recent_remove` allows multiple bindings via duplicate checking. /// - Verifies other keybinds replace existing bindings. fn test_apply_recent_keybind() { let mut settings = Settings::default(); let chord1 = KeyChord { code: KeyCode::Char('d'), mods: KeyModifiers::CONTROL, }; let chord2 = KeyChord { code: KeyCode::Char('x'), mods: KeyModifiers::CONTROL, }; // Test regular keybind (replaces existing) assert!(apply_recent_keybind( "keybind_recent_move_up", Some(chord1), &mut settings )); assert_eq!(settings.keymap.recent_move_up.len(), 1); assert!(apply_recent_keybind( "keybind_recent_move_up", Some(chord2), &mut settings )); assert_eq!(settings.keymap.recent_move_up.len(), 1); // Replaced, not appended // Test recent_remove with duplicate checking (default has 2 entries) let mut settings2 = Settings::default(); let initial_len = settings2.keymap.recent_remove.len(); // Should be 2 from defaults assert!(apply_recent_keybind( "keybind_recent_remove", Some(chord1), &mut settings2 )); assert_eq!(settings2.keymap.recent_remove.len(), initial_len + 1); // Appended assert!(apply_recent_keybind( "keybind_recent_remove", Some(chord2), &mut settings2 )); assert_eq!(settings2.keymap.recent_remove.len(), initial_len + 2); // Appended again // Test duplicate prevention (same chord not added twice) assert!(apply_recent_keybind( "keybind_recent_remove", Some(chord1), &mut settings2 )); assert_eq!(settings2.keymap.recent_remove.len(), initial_len + 2); // Not added again // Test invalid keybind assert!(!apply_recent_keybind( "keybind_invalid", Some(chord1), &mut settings )); } #[test] /// What: Ensure `apply_install_keybind` correctly assigns install pane keybinds and handles duplicate checking. /// /// Inputs: /// - Various install pane keybind names. /// - Valid key chords, including duplicates for `install_remove`. /// /// Output: /// - Returns `true` for recognized install keybinds, `false` otherwise. /// - Correctly assigns chords, allowing duplicates for `install_remove`. /// /// Details: /// - Tests that `install_remove` allows multiple bindings via duplicate checking. /// - Verifies other keybinds replace existing bindings. fn test_apply_install_keybind() { let mut settings = Settings::default(); let chord1 = KeyChord { code: KeyCode::Char('d'), mods: KeyModifiers::CONTROL, }; let chord2 = KeyChord { code: KeyCode::Char('x'), mods: KeyModifiers::CONTROL, }; // Test regular keybind (replaces existing) assert!(apply_install_keybind( "keybind_install_move_up", Some(chord1), &mut settings )); assert_eq!(settings.keymap.install_move_up.len(), 1); assert!(apply_install_keybind( "keybind_install_move_up", Some(chord2), &mut settings )); assert_eq!(settings.keymap.install_move_up.len(), 1); // Replaced // Test install_remove with duplicate checking (default has 2 entries) let mut settings2 = Settings::default(); let initial_len = settings2.keymap.install_remove.len(); // Should be 2 from defaults assert!(apply_install_keybind( "keybind_install_remove", Some(chord1), &mut settings2 )); assert_eq!(settings2.keymap.install_remove.len(), initial_len + 1); // Appended assert!(apply_install_keybind( "keybind_install_remove", Some(chord2), &mut settings2 )); assert_eq!(settings2.keymap.install_remove.len(), initial_len + 2); // Appended again // Test invalid keybind assert!(!apply_install_keybind( "keybind_invalid", Some(chord1), &mut settings )); } #[test] /// What: Ensure `apply_news_keybind` correctly assigns news modal keybinds. /// /// Inputs: /// - News modal keybind name. /// - Valid key chord. /// /// Output: /// - Returns `true` for recognized news keybind, `false` otherwise. /// - Correctly assigns chord to the appropriate keymap field. /// /// Details: /// - Tests the single news modal keybind. fn test_apply_news_keybind() { let mut settings = Settings::default(); let chord = create_test_chord(); // Test news_mark_read assert!(apply_news_keybind( "keybind_news_mark_read", Some(chord), &mut settings )); assert_eq!(settings.keymap.news_mark_read.len(), 1); assert_eq!(settings.keymap.news_mark_read[0], chord); // Test news_mark_all_read let mut settings2 = Settings::default(); assert!(apply_news_keybind( "keybind_news_mark_all_read", Some(chord), &mut settings2 )); assert_eq!(settings2.keymap.news_mark_all_read.len(), 1); assert_eq!(settings2.keymap.news_mark_all_read[0], chord); // Test news feed mark read let mut settings3 = Settings::default(); assert!(apply_news_keybind( "keybind_news_feed_mark_read", Some(chord), &mut settings3 )); assert_eq!(settings3.keymap.news_mark_read_feed.len(), 1); assert_eq!(settings3.keymap.news_mark_read_feed[0], chord); // Test news feed mark unread let mut settings4 = Settings::default(); assert!(apply_news_keybind( "keybind_news_feed_mark_unread", Some(chord), &mut settings4 )); assert_eq!(settings4.keymap.news_mark_unread_feed.len(), 1); assert_eq!(settings4.keymap.news_mark_unread_feed[0], chord); // Test news feed toggle read let mut settings5 = Settings::default(); assert!(apply_news_keybind( "keybind_news_feed_toggle_read", Some(chord), &mut settings5 )); assert_eq!(settings5.keymap.news_toggle_read_feed.len(), 1); assert_eq!(settings5.keymap.news_toggle_read_feed[0], chord); // Test invalid keybind assert!(!apply_news_keybind( "keybind_invalid", Some(chord), &mut settings )); } #[test] /// What: Ensure `apply_keybind` correctly routes to category-specific handlers. /// /// Inputs: /// - Keybind names from different categories. /// - Valid key chords. /// /// Output: /// - Correctly routes and assigns chords to appropriate keymap fields. /// /// Details: /// - Tests routing through the main dispatcher function. /// - Verifies that each category is handled correctly. fn test_apply_keybind_routing() { let mut settings = Settings::default(); let chord = create_test_chord(); // Test global routing apply_keybind("keybind_help", Some(chord), &mut settings); assert_eq!(settings.keymap.help_overlay.len(), 1); // Test search routing let mut settings2 = Settings::default(); apply_keybind("keybind_search_move_up", Some(chord), &mut settings2); assert_eq!(settings2.keymap.search_move_up.len(), 1); // Test recent routing let mut settings3 = Settings::default(); apply_keybind("keybind_recent_move_up", Some(chord), &mut settings3); assert_eq!(settings3.keymap.recent_move_up.len(), 1); // Test install routing let mut settings4 = Settings::default(); apply_keybind("keybind_install_move_up", Some(chord), &mut settings4); assert_eq!(settings4.keymap.install_move_up.len(), 1); // Test news routing let mut settings5 = Settings::default(); apply_keybind("keybind_news_mark_all_read", Some(chord), &mut settings5); assert_eq!(settings5.keymap.news_mark_all_read.len(), 1); // Test unknown keybind (should not panic) let mut settings6 = Settings::default(); apply_keybind("keybind_unknown", Some(chord), &mut settings6); } #[test] /// What: Ensure `parse_keybinds` correctly parses configuration content and handles various formats. /// /// Inputs: /// - Configuration content with keybind entries, comments, and empty lines. /// - Various keybind name formats (with dots, dashes, spaces). /// /// Output: /// - Correctly parses and assigns keybinds to settings. /// - Ignores comments and empty lines. /// /// Details: /// - Tests parsing of keybind entries with different formats. /// - Verifies comment stripping and normalization. fn test_parse_keybinds() { let mut settings = Settings::default(); let content = r" # This is a comment keybind_help = Ctrl+R keybind.search.move.up = Ctrl+Up keybind-search-add = Ctrl+A keybind search install = Ctrl+I // Another comment keybind_recent_remove = Ctrl+D keybind_recent_remove = Ctrl+X invalid_line_without_equals "; parse_keybinds(content, &mut settings); // Verify parsed keybinds assert_eq!(settings.keymap.help_overlay.len(), 1); assert_eq!(settings.keymap.search_move_up.len(), 1); assert_eq!(settings.keymap.search_add.len(), 1); assert_eq!(settings.keymap.search_install.len(), 1); // recent_remove should have 4 entries: 2 defaults + 2 from parsing (due to duplicate checking) assert_eq!(settings.keymap.recent_remove.len(), 4); } #[test] /// What: Ensure news keybinds are parsed correctly from config file. /// /// Inputs: /// - Configuration content with news keybind entries. /// /// Output: /// - Correctly parses and assigns news keybinds to settings. /// /// Details: /// - Tests parsing of `news_mark_read` and `news_mark_all_read` keybinds. /// - Verifies that both keybinds are loaded correctly. fn test_parse_news_keybinds() { let mut settings = Settings::default(); let content = r" keybind_news_mark_read = r keybind_news_mark_all_read = CTRL+R "; parse_keybinds(content, &mut settings); // Verify parsed news keybinds assert_eq!(settings.keymap.news_mark_read.len(), 1); assert_eq!(settings.keymap.news_mark_read[0].code, KeyCode::Char('r')); assert!(settings.keymap.news_mark_read[0].mods.is_empty()); assert_eq!(settings.keymap.news_mark_read[0].label(), "R"); assert_eq!(settings.keymap.news_mark_all_read.len(), 1); assert_eq!( settings.keymap.news_mark_all_read[0].code, KeyCode::Char('r') ); assert!( settings.keymap.news_mark_all_read[0] .mods .contains(KeyModifiers::CONTROL) ); assert_eq!(settings.keymap.news_mark_all_read[0].label(), "Ctrl+R"); } #[test] /// What: Ensure `assign_keybind_with_duplicate_check` prevents duplicate chords. /// /// Inputs: /// - Same chord added multiple times. /// - Different chords with same code but different modifiers. /// - Different chords with different codes. /// /// Output: /// - Prevents adding exact duplicates (same code and modifiers).
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
true
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/theme/settings/mod.rs
src/theme/settings/mod.rs
use std::env; use std::fs; use std::path::{Path, PathBuf}; use std::sync::{Mutex, OnceLock}; use std::time::SystemTime; use crate::theme::paths::{resolve_keybinds_config_path, resolve_settings_config_path}; use crate::theme::types::Settings; use tracing::{debug, warn}; /// Settings normalization module. mod normalize; /// Keybind parsing module. mod parse_keybinds; /// Settings parsing module. mod parse_settings; use normalize::normalize; use parse_keybinds::parse_keybinds; use parse_settings::parse_settings; /// What: Cache for settings and keybinds with file metadata. /// /// Inputs: Loaded from disk files. /// /// Output: Cached settings with modification times. /// /// Details: Tracks settings and keybinds along with file metadata for cache invalidation. struct SettingsCache { /// Cached settings. settings: Settings, /// Settings file modification time. settings_mtime: Option<SystemTime>, /// Keybinds file modification time. keybinds_mtime: Option<SystemTime>, /// Settings file size. settings_size: Option<u64>, /// Keybinds file size. keybinds_size: Option<u64>, /// Whether the cache has been initialized. initialized: bool, } impl SettingsCache { /// What: Create a new settings cache with default values. /// /// Inputs: None. /// /// Output: New cache instance with uninitialized state. /// /// Details: Initializes all fields to default/empty values. fn new() -> Self { Self { settings: Settings::default(), settings_mtime: None, keybinds_mtime: None, settings_size: None, keybinds_size: None, initialized: false, } } } /// Global settings cache singleton. /// /// Details: Initialized on first access, providing thread-safe access to cached settings. static SETTINGS_CACHE: OnceLock<Mutex<SettingsCache>> = OnceLock::new(); /// What: Load user settings and keybinds from config files under HOME/XDG. /// /// Inputs: /// - None (reads `settings.conf` and `keybinds.conf` if present) /// /// Output: /// - A `Settings` value; falls back to `Settings::default()` when missing or invalid. /// /// # Panics /// - If the internal settings cache mutex is poisoned (unexpected). #[must_use] pub fn settings() -> Settings { let mut cache = SETTINGS_CACHE .get_or_init(|| Mutex::new(SettingsCache::new())) .lock() .expect("Settings cache mutex poisoned"); let mut out = Settings::default(); // Load settings from settings.conf (or legacy pacsea.conf) let settings_path = resolve_settings_config_path().or_else(|| { env::var("XDG_CONFIG_HOME") .ok() .map(PathBuf::from) .or_else(|| env::var("HOME").ok().map(|h| Path::new(&h).join(".config"))) .map(|base| base.join("pacsea").join("settings.conf")) }); let settings_metadata = settings_path.as_ref().and_then(|p| fs::metadata(p).ok()); let settings_mtime = settings_metadata.as_ref().and_then(|m| m.modified().ok()); let settings_size = settings_metadata.as_ref().map(std::fs::Metadata::len); let keybinds_path = resolve_keybinds_config_path(); let keybinds_metadata = keybinds_path.as_ref().and_then(|p| fs::metadata(p).ok()); let keybinds_mtime = keybinds_metadata.as_ref().and_then(|m| m.modified().ok()); let keybinds_size = keybinds_metadata.as_ref().map(std::fs::Metadata::len); let cache_initialized = cache.initialized; let mtimes_match = cache_initialized && cache.settings_mtime == settings_mtime && cache.settings_size == settings_size && cache.keybinds_mtime == keybinds_mtime && cache.keybinds_size == keybinds_size; if mtimes_match { if tracing::enabled!(tracing::Level::TRACE) { debug!("[Config] Using cached settings (unchanged files)"); } return cache.settings.clone(); } if let Some(p) = settings_path.as_ref() && let Ok(content) = fs::read_to_string(p) { debug!(path = %p.display(), bytes = content.len(), "[Config] Loaded settings.conf"); parse_settings(&content, p, &mut out); } else if let Some(p) = settings_path.as_ref() { warn!( path = %p.display(), "[Config] settings.conf missing or unreadable, using defaults" ); } // Normalize settings normalize(&mut out); // Load keybinds from keybinds.conf if available; otherwise fall back to legacy keys in settings file if let Some(kp) = keybinds_path.as_ref() { if let Ok(content) = fs::read_to_string(kp) { debug!(path = %kp.display(), bytes = content.len(), "[Config] Loaded keybinds.conf"); parse_keybinds(&content, &mut out); // Done; keybinds loaded from dedicated file, so we can return now after validation } } else if let Some(p) = settings_path.as_ref() { // Fallback: parse legacy keybind_* from settings file if keybinds.conf not present if let Ok(content) = fs::read_to_string(p) { debug!( path = %p.display(), bytes = content.len(), "[Config] Loaded legacy keybinds from settings.conf" ); parse_keybinds(&content, &mut out); } } // Validate sum; if invalid, revert layout to defaults but preserve keybinds let sum = out .layout_left_pct .saturating_add(out.layout_center_pct) .saturating_add(out.layout_right_pct); if sum != 100 || out.layout_left_pct == 0 || out.layout_center_pct == 0 || out.layout_right_pct == 0 { // Preserve keybinds when resetting layout defaults let keymap = out.keymap.clone(); out = Settings::default(); out.keymap = keymap; debug!( layout_left = out.layout_left_pct, layout_center = out.layout_center_pct, layout_right = out.layout_right_pct, "[Config] Layout percentages invalid, reset to defaults while preserving keybinds" ); } cache.settings_mtime = settings_mtime; cache.settings_size = settings_size; cache.keybinds_mtime = keybinds_mtime; cache.keybinds_size = keybinds_size; cache.settings = out.clone(); cache.initialized = true; out } #[cfg(test)] mod tests { #[test] /// What: Ensure settings parsing applies defaults when layout percentages sum incorrectly while still loading keybinds. /// /// Inputs: /// - Temporary configuration directory containing `settings.conf` with an invalid layout sum and `keybinds.conf` with overrides. /// /// Output: /// - Resulting `Settings` fall back to default layout percentages yet pick up configured keybinds. /// /// Details: /// - Overrides `HOME` to a temp dir and restores it afterwards to avoid polluting the user environment. fn settings_parse_values_and_keybinds_with_defaults_on_invalid_sum() { let _guard = crate::theme::test_mutex() .lock() .expect("Test mutex poisoned"); let orig_home = std::env::var_os("HOME"); let base = std::env::temp_dir().join(format!( "pacsea_test_settings_{}_{}", std::process::id(), std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .expect("System time is before UNIX epoch") .as_nanos() )); let cfg = base.join(".config").join("pacsea"); let _ = std::fs::create_dir_all(&cfg); unsafe { std::env::set_var("HOME", base.display().to_string()) }; // Write settings.conf with values and bad sum (should reset to defaults) let settings_path = cfg.join("settings.conf"); std::fs::write( &settings_path, "layout_left_pct=10\nlayout_center_pct=10\nlayout_right_pct=10\nsort_mode=aur_popularity\nclipboard_suffix=OK\nshow_search_history_pane=true\nshow_install_pane=false\nshow_keybinds_footer=true\n", ) .expect("failed to write test settings file"); // Write keybinds.conf let keybinds_path = cfg.join("keybinds.conf"); std::fs::write(&keybinds_path, "keybind_exit = Ctrl+Q\nkeybind_help = F1\n") .expect("Failed to write test keybinds file"); let s = super::settings(); // Invalid layout sum -> defaults assert_eq!( s.layout_left_pct + s.layout_center_pct + s.layout_right_pct, 100 ); // Keybinds parsed assert!(!s.keymap.exit.is_empty()); assert!(!s.keymap.help_overlay.is_empty()); unsafe { if let Some(v) = orig_home { std::env::set_var("HOME", v); } else { std::env::remove_var("HOME"); } } let _ = std::fs::remove_dir_all(&base); } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/theme/settings/normalize.rs
src/theme/settings/normalize.rs
use crate::theme::types::Settings; /// What: Normalize settings values parsed from configuration files. /// /// Inputs: /// - `settings`: Mutable reference to `Settings` to normalize in-place. /// /// Output: /// - None (modifies `settings` in-place). /// /// Details: /// - Ensures `mirror_count` is between 1 and 200 (defaults to 20 if 0). /// - Normalizes `selected_countries` by trimming and formatting comma-separated values. /// - Trims whitespace from `VirusTotal` API key. pub fn normalize(settings: &mut Settings) { // Normalize mirror settings parsed from settings.conf if settings.mirror_count == 0 { settings.mirror_count = 20; } if settings.mirror_count > 200 { settings.mirror_count = 200; } if !settings.selected_countries.is_empty() { settings.selected_countries = settings .selected_countries .split(',') .map(str::trim) .filter(|s| !s.is_empty()) .collect::<Vec<_>>() .join(", "); } // Normalize VirusTotal API key (trim whitespace) settings.virustotal_api_key = settings.virustotal_api_key.trim().to_string(); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/theme/config/tests.rs
src/theme/config/tests.rs
#[cfg(test)] #[allow(clippy::items_after_test_module, clippy::module_inception)] mod tests { use crate::theme::config::settings_ensure::ensure_settings_keys_present; use crate::theme::config::settings_save::{ save_selected_countries, save_show_recent_pane, save_sort_mode, }; use crate::theme::config::skeletons::{SETTINGS_SKELETON_CONTENT, THEME_SKELETON_CONTENT}; use crate::theme::config::theme_loader::try_load_theme_with_diagnostics; use crate::theme::parsing::canonical_for_key; #[test] /// What: Exercise the theme loader on both valid and invalid theme files. /// /// Inputs: /// - Minimal theme file containing required canonical keys. /// - Second file with an unknown key and missing requirements. /// /// Output: /// - Successful load for the valid file and descriptive error messages for the invalid one. /// /// Details: /// - Uses temporary directories to avoid touching user configuration and cleans them up afterwards. fn config_try_load_theme_success_and_errors() { use std::fs; use std::io::Write; use std::path::PathBuf; // Minimal valid theme with required canonical keys let mut dir: PathBuf = std::env::temp_dir(); dir.push(format!( "pacsea_test_theme_cfg_{}_{}", std::process::id(), std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .expect("System time is before UNIX epoch") .as_nanos() )); let _ = fs::create_dir_all(&dir); let mut p = dir.clone(); p.push("theme.conf"); let content = "base=#000000\nmantle=#000000\ncrust=#000000\nsurface1=#000000\nsurface2=#000000\noverlay1=#000000\noverlay2=#000000\ntext=#000000\nsubtext0=#000000\nsubtext1=#000000\nsapphire=#000000\nmauve=#000000\ngreen=#000000\nyellow=#000000\nred=#000000\nlavender=#000000\n"; fs::write(&p, content).expect("Failed to write test theme file"); let t = try_load_theme_with_diagnostics(&p).expect("valid theme"); let _ = t.base; // use // Error case: unknown key + missing required let mut pe = dir.clone(); pe.push("bad.conf"); let mut f = fs::File::create(&pe).expect("Failed to create test theme file"); writeln!(f, "unknown_key = #fff").expect("Failed to write to test theme file"); let err = try_load_theme_with_diagnostics(&pe) .expect_err("Expected error for invalid theme file"); assert!(err.contains("Unknown key")); assert!(err.contains("Missing required keys")); let _ = std::fs::remove_dir_all(&dir); } #[test] /// What: Validate theme skeleton configuration completeness and parsing. /// /// Inputs: /// - Theme skeleton content and theme loader function. /// /// Output: /// - Confirms skeleton contains all 16 required theme keys and can be parsed successfully. /// /// Details: /// - Verifies that the skeleton includes all canonical theme keys mapped from preferred names. /// - Ensures the skeleton can be loaded without errors. /// - Tests that a generated skeleton file contains all required keys. fn config_theme_skeleton_completeness() { use std::collections::HashSet; use std::fs; // Test 1: Verify all required theme keys are present in skeleton config let skeleton_content = THEME_SKELETON_CONTENT; let skeleton_keys: HashSet<String> = skeleton_content .lines() .filter_map(|line| { let trimmed = line.trim(); if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("//") { return None; } trimmed.find('=').map(|eq_pos| { let key = trimmed[..eq_pos] .trim() .to_lowercase() .replace(['.', '-', ' '], "_"); // Map to canonical key if possible let canon = canonical_for_key(&key).unwrap_or(&key); canon.to_string() }) }) .collect(); // All 16 required canonical theme keys let required_keys: HashSet<&str> = [ "base", "mantle", "crust", "surface1", "surface2", "overlay1", "overlay2", "text", "subtext0", "subtext1", "sapphire", "mauve", "green", "yellow", "red", "lavender", ] .into_iter() .collect(); for key in &required_keys { assert!( skeleton_keys.contains(*key), "Missing required key '{key}' in theme skeleton config" ); } // Test 2: Verify skeleton can be parsed successfully let mut dir = std::env::temp_dir(); dir.push(format!( "pacsea_test_theme_skeleton_{}_{}", std::process::id(), std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .expect("System time is before UNIX epoch") .as_nanos() )); let _ = fs::create_dir_all(&dir); let theme_path = dir.join("theme.conf"); fs::write(&theme_path, skeleton_content).expect("Failed to write test theme skeleton file"); let theme_result = try_load_theme_with_diagnostics(&theme_path); assert!( theme_result.is_ok(), "Theme skeleton should parse successfully: {:?}", theme_result.err() ); let theme = theme_result.expect("Failed to parse theme skeleton in test"); // Verify all fields are set (they should be non-zero colors) let _ = ( theme.base, theme.mantle, theme.crust, theme.surface1, theme.surface2, theme.overlay1, theme.overlay2, theme.text, theme.subtext0, theme.subtext1, theme.sapphire, theme.mauve, theme.green, theme.yellow, theme.red, theme.lavender, ); // Test 3: Verify generated skeleton file contains all required keys let generated_content = fs::read_to_string(&theme_path).expect("Failed to read generated theme file"); let generated_keys: HashSet<String> = generated_content .lines() .filter_map(|line| { let trimmed = line.trim(); if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("//") { return None; } trimmed.find('=').map(|eq_pos| { let key = trimmed[..eq_pos] .trim() .to_lowercase() .replace(['.', '-', ' '], "_"); // Map to canonical key if possible let canon = canonical_for_key(&key).unwrap_or(&key); canon.to_string() }) }) .collect(); for key in &required_keys { assert!( generated_keys.contains(*key), "Missing required key '{key}' in generated theme skeleton file" ); } // Cleanup let _ = fs::remove_dir_all(&dir); } /// What: Extract keys from config file content. /// /// Inputs: /// - Config file content as string. /// /// Output: /// - `HashSet` of normalized key names extracted from the config. /// /// Details: /// - Skips empty lines, comments, and lines without '='. /// - Normalizes keys by lowercasing and replacing special characters with underscores. fn extract_config_keys(content: &str) -> std::collections::HashSet<String> { content .lines() .filter_map(|line| { let trimmed = line.trim(); if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("//") { return None; } trimmed.find('=').map(|eq_pos| { trimmed[..eq_pos] .trim() .to_lowercase() .replace(['.', '-', ' '], "_") }) }) .map(|key| { if key == "show_recent_pane" { "show_search_history_pane".to_string() } else { key } }) .collect() } /// What: Get all expected Settings keys. /// /// Inputs: None /// /// Output: /// - `HashSet` of expected Settings key names. /// /// Details: /// - Returns the list of all expected Settings keys (excluding keymap which is in keybinds.conf). fn get_expected_settings_keys() -> std::collections::HashSet<&'static str> { [ "layout_left_pct", "layout_center_pct", "layout_right_pct", "app_dry_run_default", "sort_mode", "clipboard_suffix", "show_search_history_pane", "show_install_pane", "show_keybinds_footer", "selected_countries", "mirror_count", "virustotal_api_key", "scan_do_clamav", "scan_do_trivy", "scan_do_semgrep", "scan_do_shellcheck", "scan_do_virustotal", "scan_do_custom", "scan_do_sleuth", "news_read_symbol", "news_unread_symbol", "preferred_terminal", ] .into_iter() .collect() } /// What: Verify that all expected keys are present in the extracted keys. /// /// Inputs: /// - Extracted keys from config and expected keys set. /// /// Output: None (panics on failure) /// /// Details: /// - Asserts that all expected keys are present in the extracted keys. fn assert_all_keys_present( extracted_keys: &std::collections::HashSet<String>, expected_keys: &std::collections::HashSet<&str>, context: &str, ) { for key in expected_keys { assert!( extracted_keys.contains(*key), "Missing key '{key}' in {context}" ); } } /// What: Verify that loaded settings match default settings. /// /// Inputs: /// - Loaded settings and default settings. /// /// Output: None (panics on failure) /// /// Details: /// - Compares all fields of loaded settings against defaults. fn assert_settings_match_defaults( loaded: &crate::theme::types::Settings, defaults: &crate::theme::types::Settings, ) { assert_eq!( loaded.layout_left_pct, defaults.layout_left_pct, "layout_left_pct should match default" ); assert_eq!( loaded.layout_center_pct, defaults.layout_center_pct, "layout_center_pct should match default" ); assert_eq!( loaded.layout_right_pct, defaults.layout_right_pct, "layout_right_pct should match default" ); assert_eq!( loaded.app_dry_run_default, defaults.app_dry_run_default, "app_dry_run_default should match default" ); assert_eq!( loaded.sort_mode.as_config_key(), defaults.sort_mode.as_config_key(), "sort_mode should match default" ); assert_eq!( loaded.clipboard_suffix, defaults.clipboard_suffix, "clipboard_suffix should match default" ); assert_eq!( loaded.show_recent_pane, defaults.show_recent_pane, "show_recent_pane should match default" ); assert_eq!( loaded.show_install_pane, defaults.show_install_pane, "show_install_pane should match default" ); assert_eq!( loaded.show_keybinds_footer, defaults.show_keybinds_footer, "show_keybinds_footer should match default" ); assert_eq!( loaded.selected_countries, defaults.selected_countries, "selected_countries should match default" ); assert_eq!( loaded.mirror_count, defaults.mirror_count, "mirror_count should match default" ); assert_eq!( loaded.virustotal_api_key, defaults.virustotal_api_key, "virustotal_api_key should match default" ); assert_eq!( loaded.scan_do_clamav, defaults.scan_do_clamav, "scan_do_clamav should match default" ); assert_eq!( loaded.scan_do_trivy, defaults.scan_do_trivy, "scan_do_trivy should match default" ); assert_eq!( loaded.scan_do_semgrep, defaults.scan_do_semgrep, "scan_do_semgrep should match default" ); assert_eq!( loaded.scan_do_shellcheck, defaults.scan_do_shellcheck, "scan_do_shellcheck should match default" ); assert_eq!( loaded.scan_do_virustotal, defaults.scan_do_virustotal, "scan_do_virustotal should match default" ); assert_eq!( loaded.scan_do_custom, defaults.scan_do_custom, "scan_do_custom should match default" ); assert_eq!( loaded.scan_do_sleuth, defaults.scan_do_sleuth, "scan_do_sleuth should match default" ); assert_eq!( loaded.news_read_symbol, defaults.news_read_symbol, "news_read_symbol should match default" ); assert_eq!( loaded.news_unread_symbol, defaults.news_unread_symbol, "news_unread_symbol should match default" ); assert_eq!( loaded.preferred_terminal, defaults.preferred_terminal, "preferred_terminal should match default" ); } /// What: Verify that config content contains a key-value pair (with flexible spacing). /// /// Inputs: /// - Config content and key-value pair to check. /// /// Output: None (panics on failure) /// /// Details: /// - Checks for both "key = value" and "key=value" formats. fn assert_config_contains(content: &str, key: &str, value: &str, test_context: &str) { assert!( content.contains(&format!("{key} = {value}")) || content.contains(&format!("{key}={value}")), "{test_context} should persist {key}" ); } /// What: Restore original environment variables. /// /// Inputs: /// - Original HOME and `XDG_CONFIG_HOME` values. /// /// Output: None /// /// Details: /// - Restores environment variables to their original values or removes them if they were unset. fn restore_env_vars( orig_home: Option<std::ffi::OsString>, orig_xdg: Option<std::ffi::OsString>, ) { unsafe { if let Some(v) = orig_home { std::env::set_var("HOME", v); } else { std::env::remove_var("HOME"); } if let Some(v) = orig_xdg { std::env::set_var("XDG_CONFIG_HOME", v); } else { std::env::remove_var("XDG_CONFIG_HOME"); } } } /// What: Setup temporary test environment for settings tests. /// /// Inputs: None /// /// Output: /// - Tuple of (base directory, config directory, original HOME, original `XDG_CONFIG_HOME`) /// /// Details: /// - Creates temporary directory structure and sets environment variables for isolated testing. fn setup_test_environment() -> ( std::path::PathBuf, std::path::PathBuf, Option<std::ffi::OsString>, Option<std::ffi::OsString>, ) { use std::fs; let orig_home = std::env::var_os("HOME"); let orig_xdg = std::env::var_os("XDG_CONFIG_HOME"); let base = std::env::temp_dir().join(format!( "pacsea_test_config_params_{}_{}", std::process::id(), std::time::SystemTime::now() .duration_since(std::time::UNIX_EPOCH) .expect("System time is before UNIX epoch") .as_nanos() )); let cfg_dir = base.join(".config").join("pacsea"); let _ = fs::create_dir_all(&cfg_dir); unsafe { std::env::set_var("HOME", base.display().to_string()); std::env::remove_var("XDG_CONFIG_HOME"); } (base, cfg_dir, orig_home, orig_xdg) } /// What: Test that skeleton config contains all expected keys. /// /// Inputs: /// - Expected keys set. /// /// Output: None (panics on failure) /// /// Details: /// - Verifies that the skeleton configuration contains all required settings keys. fn test_skeleton_contains_all_keys(expected_keys: &std::collections::HashSet<&str>) { let skeleton_keys = extract_config_keys(SETTINGS_SKELETON_CONTENT); assert_all_keys_present(&skeleton_keys, expected_keys, "skeleton config"); } /// What: Test that missing config file is generated with skeleton. /// /// Inputs: /// - Settings path and expected keys. /// /// Output: None (panics on failure) /// /// Details: /// - Verifies that calling `ensure_settings_keys_present` creates a config file with all required keys. fn test_missing_config_generation( settings_path: &std::path::Path, expected_keys: &std::collections::HashSet<&str>, ) { use std::fs; assert!( !settings_path.exists(), "Settings file should not exist initially" ); let default_prefs = crate::theme::types::Settings::default(); ensure_settings_keys_present(&default_prefs); assert!(settings_path.exists(), "Settings file should be created"); let generated_content = fs::read_to_string(settings_path).expect("Failed to read generated settings file"); assert!( !generated_content.is_empty(), "Generated config file should not be empty" ); let generated_keys = extract_config_keys(&generated_content); assert_all_keys_present(&generated_keys, expected_keys, "generated config file"); } /// What: Test that missing keys are added to config with defaults. /// /// Inputs: /// - Settings path and expected keys. /// /// Output: None (panics on failure) /// /// Details: /// - Creates a minimal config and verifies that `ensure_settings_keys_present` adds missing keys while preserving existing ones. fn test_missing_keys_added( settings_path: &std::path::Path, expected_keys: &std::collections::HashSet<&str>, ) { use std::fs; fs::write( settings_path, "# Minimal config\nsort_mode = aur_popularity\n", ) .expect("Failed to write test settings file"); let modified_prefs = crate::theme::types::Settings { sort_mode: crate::state::SortMode::AurPopularityThenOfficial, ..crate::theme::types::Settings::default() }; ensure_settings_keys_present(&modified_prefs); let updated_content = fs::read_to_string(settings_path).expect("Failed to read updated settings file"); let updated_keys = extract_config_keys(&updated_content); assert_all_keys_present( &updated_keys, expected_keys, "after ensure_settings_keys_present", ); assert!( updated_content.contains("sort_mode = aur_popularity") || updated_content.contains("sort_mode=aur_popularity"), "sort_mode should be preserved in config" ); } /// What: Test that custom parameters can be loaded from config file. /// /// Inputs: /// - Settings path. /// /// Output: None (panics on failure) /// /// Details: /// - Writes a config file with custom values and verifies all values are loaded correctly. fn test_load_custom_parameters(settings_path: &std::path::Path) { use std::fs; fs::write( settings_path, "layout_left_pct = 25\n\ layout_center_pct = 50\n\ layout_right_pct = 25\n\ app_dry_run_default = true\n\ sort_mode = alphabetical\n\ clipboard_suffix = Custom suffix\n\ show_search_history_pane = false\n\ show_install_pane = false\n\ show_keybinds_footer = false\n\ selected_countries = Germany, France\n\ mirror_count = 30\n\ virustotal_api_key = test_api_key\n\ scan_do_clamav = false\n\ scan_do_trivy = false\n\ scan_do_semgrep = false\n\ scan_do_shellcheck = false\n\ scan_do_virustotal = false\n\ scan_do_custom = false\n\ scan_do_sleuth = false\n\ news_read_symbol = READ\n\ news_unread_symbol = UNREAD\n\ preferred_terminal = alacritty\n", ) .expect("Failed to write test settings file with custom values"); let loaded_custom = crate::theme::settings::settings(); assert_eq!(loaded_custom.layout_left_pct, 25); assert_eq!(loaded_custom.layout_center_pct, 50); assert_eq!(loaded_custom.layout_right_pct, 25); assert!(loaded_custom.app_dry_run_default); assert_eq!(loaded_custom.sort_mode.as_config_key(), "alphabetical"); assert_eq!(loaded_custom.clipboard_suffix, "Custom suffix"); assert!(!loaded_custom.show_recent_pane); assert!(!loaded_custom.show_install_pane); assert!(!loaded_custom.show_keybinds_footer); assert_eq!(loaded_custom.selected_countries, "Germany, France"); assert_eq!(loaded_custom.mirror_count, 30); assert_eq!(loaded_custom.virustotal_api_key, "test_api_key"); assert!(!loaded_custom.scan_do_clamav); assert!(!loaded_custom.scan_do_trivy); assert!(!loaded_custom.scan_do_semgrep); assert!(!loaded_custom.scan_do_shellcheck); assert!(!loaded_custom.scan_do_virustotal); assert!(!loaded_custom.scan_do_custom); assert!(!loaded_custom.scan_do_sleuth); assert_eq!(loaded_custom.news_read_symbol, "READ"); assert_eq!(loaded_custom.news_unread_symbol, "UNREAD"); assert_eq!(loaded_custom.preferred_terminal, "alacritty"); } /// What: Test that save functions persist values correctly. /// /// Inputs: /// - Settings path. /// /// Output: None (panics on failure) /// /// Details: /// - Tests that save functions correctly persist values to the config file and can be reloaded. fn test_save_functions_persist(settings_path: &std::path::Path) { use std::fs; save_sort_mode(crate::state::SortMode::BestMatches); let saved_content = fs::read_to_string(settings_path).expect("Failed to read saved settings file"); assert_config_contains( &saved_content, "sort_mode", "best_matches", "save_sort_mode", ); save_show_recent_pane(true); let saved_content2 = fs::read_to_string(settings_path) .expect("Failed to read saved settings file (second read)"); assert_config_contains( &saved_content2, "show_search_history_pane", "true", "save_show_recent_pane", ); save_selected_countries("Switzerland, Austria"); let saved_content3 = fs::read_to_string(settings_path) .expect("Failed to read saved settings file (third read)"); assert_config_contains( &saved_content3, "selected_countries", "Switzerland, Austria", "save_selected_countries", ); let reloaded = crate::theme::settings::settings(); assert_eq!(reloaded.sort_mode.as_config_key(), "best_matches"); assert!(reloaded.show_recent_pane); assert_eq!(reloaded.selected_countries, "Switzerland, Austria"); } /// What: Ensure legacy `show_recent_pane` config key remains supported. /// /// Inputs: /// - `settings_path`: Path to the settings configuration file. /// /// Output: /// - None (panics on failure). /// /// Details: /// - Writes a config using the legacy key and verifies it loads into `show_recent_pane`. fn test_load_legacy_recent_key(settings_path: &std::path::Path) { use std::fs; fs::write( settings_path, "show_recent_pane = false\nshow_install_pane = true\nshow_keybinds_footer = true\n", ) .expect("Failed to write test settings file with legacy recent key"); let loaded = crate::theme::settings::settings(); assert!(!loaded.show_recent_pane); assert!(loaded.show_install_pane); assert!(loaded.show_keybinds_footer); } #[test] /// What: Validate settings configuration scaffolding, persistence, and regeneration paths. /// /// Inputs: /// - Skeleton config content, temporary config directory, and helper functions for ensuring/saving settings. /// /// Output: /// - Confirms skeleton covers all expected keys, missing files regenerate, settings persist, and defaults apply when keys are absent. /// /// Details: /// - Manipulates `HOME`/`XDG_CONFIG_HOME` to isolate test data and cleans up generated files on completion. fn config_settings_comprehensive_parameter_check() { use std::fs; let _guard = crate::theme::test_mutex() .lock() .expect("Test mutex poisoned"); let (base, cfg_dir, orig_home, orig_xdg) = setup_test_environment(); let expected_keys = get_expected_settings_keys(); let settings_path = cfg_dir.join("settings.conf"); // Test 1: Verify all Settings fields are present in skeleton config test_skeleton_contains_all_keys(&expected_keys); // Test 2: Missing config file is correctly generated with skeleton test_missing_config_generation(&settings_path, &expected_keys); // Test 3: All parameters are loaded with defaults when missing fs::remove_file(&settings_path).expect("Failed to remove test settings file"); let loaded_settings = crate::theme::settings::settings(); let default_settings = crate::theme::types::Settings::default(); assert_settings_match_defaults(&loaded_settings, &default_settings); // Test 4: Missing keys are added to config with defaults test_missing_keys_added(&settings_path, &expected_keys); // Test 5: Parameters can be loaded from config file test_load_custom_parameters(&settings_path); // Test 6: Legacy key for search history pane is still parsed test_load_legacy_recent_key(&settings_path); // Test 7: Save functions persist values correctly test_save_functions_persist(&settings_path); // Cleanup restore_env_vars(orig_home, orig_xdg); let _ = fs::remove_dir_all(&base); } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/theme/config/skeletons.rs
src/theme/config/skeletons.rs
/// Skeleton configuration file content with default color values. pub const THEME_SKELETON_CONTENT: &str = "# Pacsea theme configuration\n\ #\n\ # Format: key = value\n\ # Value formats supported:\n\ # - #RRGGBB (hex)\n\ # - R,G,B (decimal, 0-255 each)\n\ # Example (decimal): text_primary = 205,214,244\n\ # Lines starting with # are comments.\n\ #\n\ # Key naming:\n\ # Comprehensive names are preferred (shown first). Legacy keys remain supported\n\ # for compatibility (e.g., \"base\", \"surface1\").\n\ #\n\ #-----------------------------------------------------------------------------------------------------------------------\n\ #\n\ # ---------- Catppuccin Mocha (dark) ----------\n\ #\n\ # Background layers (from darkest to lightest)\n\ background_base = #1e1e2e\n\ background_mantle = #181825\n\ background_crust = #11111b\n\ #\n\ # Component surfaces\n\ surface_level1 = #45475a\n\ surface_level2 = #585b70\n\ #\n\ # Low-contrast lines/borders\n\ overlay_primary = #7f849c\n\ overlay_secondary = #9399b2\n\ #\n\ # Text hierarchy\n\ text_primary = #cdd6f4\n\ text_secondary = #a6adc8\n\ text_tertiary = #bac2de\n\ #\n\ # Accents and semantic colors\n\ accent_interactive = #74c7ec\n\ accent_heading = #cba6f7\n\ accent_emphasis = #b4befe\n\ semantic_success = #a6e3a1\n\ semantic_warning = #f9e2af\n\ semantic_error = #f38ba8\n\ #\n\ # ---------- Alternative Theme (Light) ----------\n\ #\n\ # # Background layers (from lightest to darkest)\n\ # background_base = #f5f5f7\n\ # background_mantle = #eaeaee\n\ # background_crust = #dcdce1\n\ #\n\ # # Component surfaces\n\ # surface_level1 = #cfd1d7\n\ # surface_level2 = #b7bac3\n\ #\n\ # # Low-contrast lines/borders and secondary text accents\n\ # overlay_primary = #7a7d86\n\ # overlay_secondary = #63666f\n\ #\n\ # # Text hierarchy\n\ # text_primary = #1c1c22\n\ # text_secondary = #3c3f47\n\ # text_tertiary = #565a64\n\ #\n\ # # Accents and semantic colors\n\ # accent_interactive = #1e66f5\n\ # accent_heading = #8839ef\n\ # accent_emphasis = #7287fd\n\ # semantic_success = #40a02b\n\ # semantic_warning = #df8e1d\n\ # semantic_error = #d20f39\n\ \n\ # ---------- Alternative Theme (Tokyo Night — Night) ----------\n\ #\n\ # # Background layers (from darkest to lightest)\n\ # background_base = #1a1b26\n\ # background_mantle = #16161e\n\ # background_crust = #0f0f14\n\ #\n\ # # Component surfaces\n\ # surface_level1 = #24283b\n\ # surface_level2 = #1f2335\n\ #\n\ # # Low-contrast lines/borders\n\ # overlay_primary = #414868\n\ # overlay_secondary = #565f89\n\ #\n\ # # Text hierarchy\n\ # text_primary = #c0caf5\n\ # text_secondary = #a9b1d6\n\ # text_tertiary = #9aa5ce\n\ #\n\ # # Accents and semantic colors\n\ # accent_interactive = #7aa2f7\n\ # accent_heading = #bb9af7\n\ # accent_emphasis = #7dcfff\n\ # semantic_success = #9ece6a\n\ # semantic_warning = #e0af68\n\ # semantic_error = #f7768e\n\ \n\ # ---------- Alternative Theme (Nord) ----------\n\ #\n\ # # Background layers (from darkest to lightest)\n\ # background_base = #2e3440\n\ # background_mantle = #3b4252\n\ # background_crust = #434c5e\n\ #\n\ # # Component surfaces\n\ # surface_level1 = #3b4252\n\ # surface_level2 = #4c566a\n\ #\n\ # # Low-contrast lines/borders\n\ # overlay_primary = #4c566a\n\ # overlay_secondary = #616e88\n\ #\n\ # # Text hierarchy\n\ # text_primary = #e5e9f0\n\ # text_secondary = #d8dee9\n\ # text_tertiary = #eceff4\n\ #\n\ # # Accents and semantic colors\n\ # accent_interactive = #81a1c1\n\ # accent_heading = #b48ead\n\ # accent_emphasis = #88c0d0\n\ # semantic_success = #a3be8c\n\ # semantic_warning = #ebcb8b\n\ # semantic_error = #bf616a\n\ \n\ # ---------- Alternative Theme (Dracula) ----------\n\ #\n\ # # Background layers (from darkest to lightest)\n\ # background_base = #282a36\n\ # background_mantle = #21222c\n\ # background_crust = #44475a\n\ #\n\ # # Component surfaces\n\ # surface_level1 = #44475a\n\ # surface_level2 = #343746\n\ #\n\ # # Low-contrast lines/borders\n\ # overlay_primary = #44475a\n\ # overlay_secondary = #6272a4\n\ #\n\ # # Text hierarchy\n\ # text_primary = #f8f8f2\n\ # text_secondary = #e2e2e6\n\ # text_tertiary = #d6d6de\n\ #\n\ # # Accents and semantic colors\n\ # accent_interactive = #8be9fd\n\ # accent_heading = #bd93f9\n\ # accent_emphasis = #ff79c6\n\ # semantic_success = #50fa7b\n\ # semantic_warning = #f1fa8c\n\ # semantic_error = #ff5555\n\ #\n\ # ---------- Alternative Theme (Gruvbox Dark) ----------\n\ #\n\ # # Background layers (from darkest to lightest)\n\ # background_base = #171717\n\ # background_mantle = #1d2021\n\ # background_crust = #0d1011\n\ #\n\ # # Component surfaces\n\ # surface_level1 = #3c3836\n\ # surface_level2 = #504945\n\ #\n\ # # Low-contrast lines/borders\n\ # overlay_primary = #665c54\n\ # overlay_secondary = #7c6f64\n\ #\n\ # # Text hierarchy\n\ # text_primary = #ebdbb2\n\ # text_secondary = #d5c4a1\n\ # text_tertiary = #bdae93\n\ #\n\ # # Accents and semantic colors\n\ # accent_interactive = #83a598\n\ # accent_heading = #b16286\n\ # accent_emphasis = #d3869b\n\ # semantic_success = #b8bb26\n\ # semantic_warning = #fabd2f\n\ # semantic_error = #fb4934\n\ #\n\ #-----------------------------------------------------------------------------------------------------------------------\n"; /// Standalone settings skeleton used when initializing a separate settings.conf pub const SETTINGS_SKELETON_CONTENT: &str = "# Pacsea settings configuration\n\ # Layout percentages for the middle row panes (must sum to 100)\n\ layout_left_pct = 20\n\ layout_center_pct = 60\n\ layout_right_pct = 20\n\ # Default dry-run behavior when starting the app (overridden by --dry-run)\n\ app_dry_run_default = false\n\ # Middle row visibility (default true)\n\ show_search_history_pane = true\n\ show_install_pane = true\n\ show_keybinds_footer = true\n\ # Search input mode on startup\n\ # Allowed values: insert_mode | normal_mode\n\ # Default is insert_mode\n\ search_startup_mode = insert_mode\n\ # Fuzzy search mode\n\ # When true, uses fuzzy matching (fzf-style) instead of substring search\n\ # Default is false (normal substring search)\n\ fuzzy_search = false\n\ \n\ # Installed packages filter mode\n\ # Controls which packages are shown when viewing installed packages\n\ # Allowed values: leaf | all\n\ # - leaf: Show only leaf packages (explicitly installed, nothing depends on them) - default\n\ # - all: Show all explicitly installed packages (including those other packages depend on)\n\ installed_packages_mode = leaf\n\ \n\ # Results sorting\n\ # Allowed values: alphabetical | aur_popularity | best_matches\n\ sort_mode = best_matches\n\ \n\ # Clipboard\n\ # Text appended when copying PKGBUILD to the clipboard\n\ clipboard_suffix = Check PKGBUILD and source for suspicious and malicious activities\n\ \n\ # Preflight modal / safety confirmation\n\ # When true, Pacsea will bypass the Preflight confirmation modal and execute install/remove/downgrade actions immediately.\n\ # Recommended to keep this false for safety unless you understand the risks of executing package operations directly.\n\ skip_preflight = false\n\ \n\ # Mirrors\n\ # Select one or more countries (comma-separated). Example: \"Switzerland, Germany, Austria\"\n\ selected_countries = Worldwide\n\ # Number of HTTPS mirrors to consider when updating\n\ mirror_count = 20\n\ # Available countries (commented list; edit selected_countries above as needed):\n\ # Worldwide\n\ # Albania\n\ # Algeria\n\ # Argentina\n\ # Armenia\n\ # Australia\n\ # Austria\n\ # Azerbaijan\n\ # Belarus\n\ # Belgium\n\ # Bosnia and Herzegovina\n\ # Brazil\n\ # Bulgaria\n\ # Cambodia\n\ # Canada\n\ # Chile\n\ # China\n\ # Colombia\n\ # Costa Rica\n\ # Croatia\n\ # Cyprus\n\ # Czechia\n\ # Denmark\n\ # Ecuador\n\ # Estonia\n\ # Finland\n\ # France\n\ # Georgia\n\ # Germany\n\ # Greece\n\ # Hong Kong\n\ # Hungary\n\ # Iceland\n\ # India\n\ # Indonesia\n\ # Iran\n\ # Ireland\n\ # Israel\n\ # Italy\n\ # Japan\n\ # Kazakhstan\n\ # Latvia\n\ # Lithuania\n\ # Luxembourg\n\ # Malaysia\n\ # Mexico\n\ # Moldova\n\ # Netherlands\n\ # New Caledonia\n\ # New Zealand\n\ # Norway\n\ # Peru\n\ # Philippines\n\ # Poland\n\ # Portugal\n\ # Romania\n\ # Russia\n\ # Serbia\n\ # Singapore\n\ # Slovakia\n\ # Slovenia\n\ # South Africa\n\ # South Korea\n\ # Spain\n\ # Sweden\n\ # Switzerland\n\ # Taiwan\n\ # Thailand\n\ # Turkey\n\ # Ukraine\n\ # United Kingdom\n\ # United States\n\ # Uruguay\n\ # Vietnam\n\ \n\ # Scans\n\ # Default scan configuration used when opening Scan Configuration\n\ scan_do_clamav = true\n\ scan_do_trivy = true\n\ scan_do_semgrep = true\n\ scan_do_shellcheck = true\n\ scan_do_virustotal = true\n\ scan_do_custom = true\n\ scan_do_sleuth = true\n\ \n\ # News\n\ # Symbols for read/unread indicators in the News popup\n\ app_start_mode = package\n\ news_read_symbol = ✓\n\ news_unread_symbol = ∘\n\ news_filter_show_arch_news = true\n\ news_filter_show_advisories = true\n\ news_filter_show_pkg_updates = true\n\ news_filter_show_aur_updates = true\n\ news_filter_show_aur_comments = true\n\ # When news_filter_show_advisories is true, this restricts advisories to only those affecting installed packages\n\ news_filter_installed_only = false\n\ # Allowed values: number of days | all\n\ news_max_age_days = 30\n\ \n\ # Startup News Popup Configuration\n\ # Whether startup news popup setup has been completed\n\ startup_news_configured = false\n\ # News sources to show in startup popup\n\ startup_news_show_arch_news = true\n\ startup_news_show_advisories = true\n\ startup_news_show_aur_updates = true\n\ startup_news_show_aur_comments = true\n\ startup_news_show_pkg_updates = true\n\ # Maximum age of news items in days for startup popup (7, 30, or 90)\n\ startup_news_max_age_days = 7\n\ \n\ # News Cache\n\ # How many days to keep Arch news and advisories cached on disk.\n\ # Reduces network requests on startup. Default is 14 days.\n\ news_cache_ttl_days = 14\n\ \n\ # VirusTotal\n\ # API key used for VirusTotal scans (optional)\n\ virustotal_api_key = \n\ \n\ # Terminal\n\ # Preferred terminal emulator binary (optional): e.g., alacritty, kitty, gnome-terminal\n\ preferred_terminal = \n\ \n\ # Package selection marker\n\ # Visual marker for packages added to Install/Remove/Downgrade lists.\n\ # Allowed values: full_line | front | end\n\ # - full_line: color the entire line\n\ # - front: add marker at the front of the line (default)\n\ # - end: add marker at the end of the line\n\ package_marker = front # Language / Locale # Locale code for translations (e.g., \"en-US\", \"de-DE\"). # Leave empty to auto-detect from system locale (LANG/LC_ALL environment variables). # Available locales: en-US, de-DE, hu-HU (more coming soon) locale = \n\ \n\ # Updates refresh interval\n\ # Time in seconds between pacman -Qu and AUR helper checks.\n\ # Default is 30 seconds. Increase this value on systems with slow I/O or many packages to reduce resource usage.\n\ # Minimum value is 1 second.\n\ updates_refresh_interval = 30\n\ \n\ # Remote announcements\n\ # URL for fetching remote announcements (GitHub Gist raw URL)\n\ # Default: true\n\ # If true, fetches remote announcements from GitHub Gist\n\ # If false, remote announcements are disabled (version announcements still show)\n\ get_announcement = true\n"; /// Standalone keybinds skeleton used when initializing a separate keybinds.conf pub const KEYBINDS_SKELETON_CONTENT: &str = "# Pacsea keybindings configuration\n\ # Modifiers can be one of: SUPER, CTRL, SHIFT, ALT.\n\ \n\ # GLOBAL — App\n\ keybind_help = F1\n\ # Alternative help shortcut\n\ keybind_help = ?\n\ keybind_reload_config = CTRL+R\n\ keybind_exit = CTRL+Q\n\ keybind_show_pkgbuild = CTRL+X\n\ keybind_comments_toggle = CTRL+T\n\ \n\ # GLOBAL — Pane switching\n\ keybind_pane_left = Left\n\ keybind_pane_right = Right\n\ keybind_pane_next = Tab\n\ # GLOBAL — Sorting\n\ keybind_change_sort = BackTab\n\ \n\ # SEARCH — Navigation\n\ keybind_search_move_up = Up\n\ keybind_search_move_down = Down\n\ keybind_search_page_up = PgUp\n\ keybind_search_page_down = PgDn\n\ \n\ # SEARCH — Actions\n\ keybind_search_add = Space\n\ keybind_search_install = Enter\n\ \n\ # SEARCH — Focus/Edit\n\ keybind_search_focus_left = Left\n\ keybind_search_focus_right = Right\n\ keybind_search_backspace = Backspace\n\ keybind_search_insert_clear = Shift+Del\n\ \n\ # SEARCH — Normal Mode (Focused Search Window)\n\ keybind_search_normal_toggle = Esc\n\ keybind_search_normal_insert = i\n\ keybind_search_normal_select_left = h\n\ keybind_search_normal_select_right = l\n\ keybind_search_normal_delete = d\n\ keybind_search_normal_clear = Shift+Del\n\ \n\ # SEARCH — Normal Mode (Menus)\n\ # Toggle dropdown menus while in Normal Mode\n\ keybind_toggle_config = Shift+C\n\ keybind_toggle_options = Shift+O\n\ keybind_toggle_panels = Shift+P\n\ \n\ # SEARCH — Normal Mode (Other)\n\ # Open Arch status page in default browser\n\ keybind_search_normal_open_status = Shift+S\n\ # Import packages list into Install list\n\ keybind_search_normal_import = Shift+I\n\ # Export current Install list to a file\n\ keybind_search_normal_export = Shift+E\n\ # Open Available Updates window\n\ keybind_search_normal_updates = Shift+U\n\ \n\ # SEARCH — Fuzzy Search Toggle\n\ # Toggle between normal substring search and fuzzy search (fzf-style)\n\ keybind_toggle_fuzzy = CTRL+F\n\ \n\ # RECENT — Navigation\n\ keybind_recent_move_up = k\n\ keybind_recent_move_down = j\n\ \n\ # RECENT — Actions\n\ keybind_recent_use = Enter\n\ keybind_recent_add = Space\n\ keybind_recent_remove = d\n\ keybind_recent_remove = Del\n\ \n\ # RECENT — Find/Focus\n\ keybind_recent_find = /\n\ keybind_recent_to_search = Esc\n\ keybind_recent_focus_right = Right\n\ \n\ # INSTALL — Navigation\n\ keybind_install_move_up = k\n\ keybind_install_move_down = j\n\ \n\ # INSTALL — Actions\n\ keybind_install_confirm = Enter\n\ keybind_install_remove = Del\n\ keybind_install_remove = d\n\ keybind_install_clear = Shift+Del\n\ \n\ # INSTALL — Find/Focus\n\ keybind_install_find = /\n\ keybind_install_to_search = Esc\n\ keybind_install_focus_left = Left\n\ \n\ # NEWS — Actions\n\ keybind_news_mark_read = r\n\ keybind_news_mark_all_read = CTRL+R\n\ keybind_news_feed_mark_read = r\n\ keybind_news_feed_mark_unread = u\n\ keybind_news_feed_toggle_read = t\n";
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/theme/config/settings_save.rs
src/theme/config/settings_save.rs
use std::fs; use std::path::Path; use crate::theme::config::skeletons::SETTINGS_SKELETON_CONTENT; use crate::theme::paths::resolve_settings_config_path; /// What: Persist the user-selected sort mode into `settings.conf` (or legacy `pacsea.conf`). /// /// Inputs: /// - `sm`: Sort mode chosen in the UI, expressed as `crate::state::SortMode`. /// /// Output: /// - None. /// /// Details: /// - Ensures the target file exists by seeding from the skeleton when missing. /// - Replaces existing `sort_mode`/`results_sort` entries while preserving comments. pub fn save_sort_mode(sm: crate::state::SortMode) { let path = resolve_settings_config_path().or_else(|| { std::env::var("XDG_CONFIG_HOME") .ok() .map(std::path::PathBuf::from) .or_else(|| { std::env::var("HOME") .ok() .map(|h| Path::new(&h).join(".config")) }) .map(|base| base.join("pacsea").join("settings.conf")) }); let Some(p) = path else { return; }; // Ensure directory exists if let Some(dir) = p.parent() { let _ = fs::create_dir_all(dir); } // If file doesn't exist or is empty, initialize with skeleton let meta = std::fs::metadata(&p).ok(); let file_exists = meta.is_some(); let file_empty = meta.is_none_or(|m| m.len() == 0); let mut lines: Vec<String> = if file_exists && !file_empty { // File exists and has content - read it fs::read_to_string(&p) .map(|content| content.lines().map(ToString::to_string).collect()) .unwrap_or_default() } else { // File doesn't exist or is empty - start with skeleton SETTINGS_SKELETON_CONTENT .lines() .map(ToString::to_string) .collect() }; let mut replaced = false; for line in &mut lines { let trimmed = line.trim(); if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("//") { continue; } if let Some(eq) = trimmed.find('=') { let (kraw, _) = trimmed.split_at(eq); let key = kraw.trim().to_lowercase().replace(['.', '-', ' '], "_"); if key == "sort_mode" || key == "results_sort" { *line = format!("sort_mode = {}", sm.as_config_key()); replaced = true; } } } if !replaced { if let Some(dir) = p.parent() { let _ = fs::create_dir_all(dir); } lines.push(format!("sort_mode = {}", sm.as_config_key())); } let new_content = if lines.is_empty() { format!("sort_mode = {}\n", sm.as_config_key()) } else { lines.join("\n") }; let _ = fs::write(p, new_content); } /// What: Persist a single boolean toggle within `settings.conf` while preserving unrelated content. /// /// Inputs: /// - `primary_key`: Primary key name to update (lowercase, underscore-separated recommended). /// - `aliases`: Optional aliases that should map to the same setting (legacy compatibility). /// - `value`: Boolean flag to serialize as `true` or `false`. /// /// Output: /// - None. /// /// Details: /// - Creates the configuration file from the skeleton when it is missing or empty. /// - Rewrites existing entries (including aliases) in place; otherwise appends the primary key. /// - When an alias is encountered, it is replaced with the primary key to migrate configs forward. fn save_boolean_key_with_aliases(primary_key: &str, aliases: &[&str], value: bool) { let path = resolve_settings_config_path().or_else(|| { std::env::var("XDG_CONFIG_HOME") .ok() .map(std::path::PathBuf::from) .or_else(|| { std::env::var("HOME") .ok() .map(|h| Path::new(&h).join(".config")) }) .map(|base| base.join("pacsea").join("settings.conf")) }); let Some(p) = path else { return; }; // Ensure directory exists if let Some(dir) = p.parent() { let _ = fs::create_dir_all(dir); } // If file doesn't exist or is empty, initialize with skeleton let meta = std::fs::metadata(&p).ok(); let file_exists = meta.is_some(); let file_empty = meta.is_none_or(|m| m.len() == 0); let mut lines: Vec<String> = if file_exists && !file_empty { // File exists and has content - read it fs::read_to_string(&p) .map(|content| content.lines().map(ToString::to_string).collect()) .unwrap_or_default() } else { // File doesn't exist or is empty - start with skeleton SETTINGS_SKELETON_CONTENT .lines() .map(ToString::to_string) .collect() }; let bool_text = if value { "true" } else { "false" }; let primary_norm = primary_key .trim() .to_lowercase() .replace(['.', '-', ' '], "_"); let alias_norms: Vec<String> = aliases .iter() .map(|k| k.trim().to_lowercase().replace(['.', '-', ' '], "_")) .collect(); let mut replaced = false; for line in &mut lines { let trimmed = line.trim(); if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("//") { continue; } if let Some(eq) = trimmed.find('=') { let (kraw, _) = trimmed.split_at(eq); let key = kraw.trim().to_lowercase().replace(['.', '-', ' '], "_"); if key == primary_norm || alias_norms.iter().any(|alias| alias == &key) { *line = format!("{primary_key} = {bool_text}"); replaced = true; } } } if !replaced { if let Some(dir) = p.parent() { let _ = fs::create_dir_all(dir); } lines.push(format!("{primary_key} = {bool_text}")); } let new_content = if lines.is_empty() { format!("{primary_key} = {bool_text}\n") } else { lines.join("\n") }; let _ = fs::write(p, new_content); } /// What: Persist a single boolean toggle within `settings.conf` while preserving unrelated content. /// /// Inputs: /// - `key_norm`: Normalized (lowercase, underscore-separated) key name to update. /// - `value`: Boolean flag to serialize as `true` or `false`. /// /// Output: /// - None. /// /// Details: /// - Convenience wrapper that delegates to `save_boolean_key_with_aliases` without aliases. fn save_boolean_key(key_norm: &str, value: bool) { save_boolean_key_with_aliases(key_norm, &[], value); } /// What: Persist a string-valued setting inside `settings.conf` without disturbing other keys. /// /// Inputs: /// - `key_norm`: Normalized key to update. /// - `value`: String payload that should be written verbatim after trimming handled by the caller. /// /// Output: /// - None. /// /// Details: /// - Bootstraps the configuration file from the skeleton if necessary. /// - Updates the existing key in place or appends a new line when absent. fn save_string_key(key_norm: &str, value: &str) { let path = resolve_settings_config_path().or_else(|| { std::env::var("XDG_CONFIG_HOME") .ok() .map(std::path::PathBuf::from) .or_else(|| { std::env::var("HOME") .ok() .map(|h| Path::new(&h).join(".config")) }) .map(|base| base.join("pacsea").join("settings.conf")) }); let Some(p) = path else { return; }; // Ensure directory exists if let Some(dir) = p.parent() { let _ = fs::create_dir_all(dir); } // If file doesn't exist or is empty, initialize with skeleton let meta = std::fs::metadata(&p).ok(); let file_exists = meta.is_some(); let file_empty = meta.is_none_or(|m| m.len() == 0); let mut lines: Vec<String> = if file_exists && !file_empty { // File exists and has content - read it fs::read_to_string(&p) .map(|content| content.lines().map(ToString::to_string).collect()) .unwrap_or_default() } else { // File doesn't exist or is empty - start with skeleton SETTINGS_SKELETON_CONTENT .lines() .map(ToString::to_string) .collect() }; let mut replaced = false; for line in &mut lines { let trimmed = line.trim(); if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("//") { continue; } if let Some(eq) = trimmed.find('=') { let (kraw, _) = trimmed.split_at(eq); let key = kraw.trim().to_lowercase().replace(['.', '-', ' '], "_"); if key == key_norm { *line = format!("{key_norm} = {value}"); replaced = true; } } } if !replaced { if let Some(dir) = p.parent() { let _ = fs::create_dir_all(dir); } lines.push(format!("{key_norm} = {value}")); } let new_content = if lines.is_empty() { format!("{key_norm} = {value}\n") } else { lines.join("\n") }; let _ = fs::write(p, new_content); } /// What: Persist the visibility flag for the Search history pane. /// /// Inputs: /// - `value`: Whether the Search history pane should be shown on startup. /// /// Output: /// - None. /// /// Details: /// - Writes to the canonical `show_search_history_pane` key while migrating legacy /// `show_recent_pane` entries. pub fn save_show_recent_pane(value: bool) { save_boolean_key_with_aliases("show_search_history_pane", &["show_recent_pane"], value); } /// What: Persist the visibility flag for the Install pane. /// /// Inputs: /// - `value`: Whether the Install pane should be shown on startup. /// /// Output: /// - None. /// /// Details: /// - Delegates to `save_boolean_key("show_install_pane", value)`. pub fn save_show_install_pane(value: bool) { save_boolean_key("show_install_pane", value); } /// What: Persist the visibility flag for the keybinds footer. /// /// Inputs: /// - `value`: Whether the footer should be rendered. /// /// Output: /// - None. /// /// Details: /// - Delegates to `save_boolean_key("show_keybinds_footer", value)`. pub fn save_show_keybinds_footer(value: bool) { save_boolean_key("show_keybinds_footer", value); } /// What: Persist the comma-separated list of preferred mirror countries. /// /// Inputs: /// - `value`: Country list string (already normalized by caller). /// /// Output: /// - None. /// /// Details: /// - Delegates to `save_string_key("selected_countries", ...)`. pub fn save_selected_countries(value: &str) { save_string_key("selected_countries", value); } /// What: Persist the numeric limit on ranked mirrors. /// /// Inputs: /// - `value`: Mirror count to record. /// /// Output: /// - None. /// /// Details: /// - Delegates to `save_string_key("mirror_count", value)` after converting to text. pub fn save_mirror_count(value: u16) { save_string_key("mirror_count", &value.to_string()); } /// Persist start mode (package/news). pub fn save_app_start_mode(start_in_news: bool) { let v = if start_in_news { "news" } else { "package" }; save_string_key("app_start_mode", v); } /// Persist whether to show Arch news items. pub fn save_news_filter_show_arch_news(value: bool) { save_boolean_key("news_filter_show_arch_news", value); } /// Persist whether to show security advisories. pub fn save_news_filter_show_advisories(value: bool) { save_boolean_key("news_filter_show_advisories", value); } /// Persist whether to show installed package updates in the News view. pub fn save_news_filter_show_pkg_updates(value: bool) { save_boolean_key("news_filter_show_pkg_updates", value); } /// Persist whether to show AUR package updates in the News view. pub fn save_news_filter_show_aur_updates(value: bool) { save_boolean_key("news_filter_show_aur_updates", value); } /// Persist whether to show AUR comments in the News view. pub fn save_news_filter_show_aur_comments(value: bool) { save_boolean_key("news_filter_show_aur_comments", value); } /// Persist whether to restrict advisories to installed packages. pub fn save_news_filter_installed_only(value: bool) { save_boolean_key("news_filter_installed_only", value); } /// Persist whether news filters are collapsed behind the Filters button. pub fn save_news_filters_collapsed(value: bool) { save_boolean_key("news_filters_collapsed", value); } /// Persist the maximum age of news items (None = all). pub fn save_news_max_age_days(value: Option<u32>) { let v = value.map_or_else(|| "all".to_string(), |d| d.to_string()); save_string_key("news_max_age_days", &v); } /// Persist whether startup news popup setup has been completed. pub fn save_startup_news_configured(value: bool) { save_boolean_key("startup_news_configured", value); } /// Persist whether to show Arch news in startup news popup. pub fn save_startup_news_show_arch_news(value: bool) { save_boolean_key("startup_news_show_arch_news", value); } /// Persist whether to show security advisories in startup news popup. pub fn save_startup_news_show_advisories(value: bool) { save_boolean_key("startup_news_show_advisories", value); } /// Persist whether to show AUR updates in startup news popup. pub fn save_startup_news_show_aur_updates(value: bool) { save_boolean_key("startup_news_show_aur_updates", value); } /// Persist whether to show AUR comments in startup news popup. pub fn save_startup_news_show_aur_comments(value: bool) { save_boolean_key("startup_news_show_aur_comments", value); } /// Persist whether to show official package updates in startup news popup. pub fn save_startup_news_show_pkg_updates(value: bool) { save_boolean_key("startup_news_show_pkg_updates", value); } /// Persist the maximum age of news items for startup news popup (None = all). pub fn save_startup_news_max_age_days(value: Option<u32>) { let v = value.map_or_else(|| "all".to_string(), |d| d.to_string()); save_string_key("startup_news_max_age_days", &v); } /// What: Persist the `VirusTotal` API key used for scanning packages. /// /// Inputs: /// - `value`: API key string supplied by the user. /// /// Output: /// - None. /// /// Details: /// - Delegates to `save_string_key("virustotal_api_key", ...)`. pub fn save_virustotal_api_key(value: &str) { save_string_key("virustotal_api_key", value); } /// What: Persist the `ClamAV` scan toggle. /// /// Inputs: /// - `value`: Whether `ClamAV` scans should run by default. /// /// Output: /// - None. /// /// Details: /// - Delegates to `save_boolean_key("scan_do_clamav", value)`. pub fn save_scan_do_clamav(value: bool) { save_boolean_key("scan_do_clamav", value); } /// What: Persist the Trivy scan toggle. /// /// Inputs: /// - `value`: Whether Trivy scans should run by default. /// /// Output: /// - None. /// /// Details: /// - Delegates to `save_boolean_key("scan_do_trivy", value)`. pub fn save_scan_do_trivy(value: bool) { save_boolean_key("scan_do_trivy", value); } /// What: Persist the Semgrep scan toggle. /// /// Inputs: /// - `value`: Whether Semgrep scans should run by default. /// /// Output: /// - None. /// /// Details: /// - Delegates to `save_boolean_key("scan_do_semgrep", value)`. pub fn save_scan_do_semgrep(value: bool) { save_boolean_key("scan_do_semgrep", value); } /// What: Persist the `ShellCheck` scan toggle. /// /// Inputs: /// - `value`: Whether `ShellCheck` scans should run by default. /// /// Output: /// - None. /// /// Details: /// - Delegates to `save_boolean_key("scan_do_shellcheck", value)`. pub fn save_scan_do_shellcheck(value: bool) { save_boolean_key("scan_do_shellcheck", value); } /// What: Persist the `VirusTotal` scan toggle. /// /// Inputs: /// - `value`: Whether `VirusTotal` scans should run by default. /// /// Output: /// - None. /// /// Details: /// - Delegates to `save_boolean_key("scan_do_virustotal", value)`. pub fn save_scan_do_virustotal(value: bool) { save_boolean_key("scan_do_virustotal", value); } /// What: Persist the custom scan toggle. /// /// Inputs: /// - `value`: Whether user-defined custom scans should run by default. /// /// Output: /// - None. /// /// Details: /// - Delegates to `save_boolean_key("scan_do_custom", value)`. pub fn save_scan_do_custom(value: bool) { save_boolean_key("scan_do_custom", value); } /// What: Persist the Sleuth scan toggle. /// /// Inputs: /// - `value`: Whether Sleuth scans should run by default. /// /// Output: /// - None. /// /// Details: /// - Delegates to `save_boolean_key("scan_do_sleuth", value)`. pub fn save_scan_do_sleuth(value: bool) { save_boolean_key("scan_do_sleuth", value); } /// What: Persist the fuzzy search toggle. /// /// Inputs: /// - `value`: Whether fuzzy search should be enabled. /// /// Output: /// - None. /// /// Details: /// - Delegates to `save_boolean_key("fuzzy_search", value)`. pub fn save_fuzzy_search(value: bool) { save_boolean_key("fuzzy_search", value); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/theme/config/theme_loader.rs
src/theme/config/theme_loader.rs
use ratatui::style::Color; use std::collections::{HashMap, HashSet}; use std::fs; use std::path::Path; use crate::theme::parsing::{apply_override_to_map, canonical_to_preferred}; use crate::theme::types::Theme; /// What: Parse a theme configuration file containing `key = value` color pairs into a `Theme`. /// /// Inputs: /// - `path`: Filesystem location of the theme configuration. /// /// Output: /// - `Ok(Theme)` when all required colors are present and valid. /// - `Err(String)` containing newline-separated diagnostics when parsing fails. /// /// Details: /// - Ignores preference keys that belong to other config files for backwards compatibility. /// - Detects duplicates, missing required keys, and invalid color formats with precise line info. pub fn try_load_theme_with_diagnostics(path: &Path) -> Result<Theme, String> { const REQUIRED: [&str; 16] = [ "base", "mantle", "crust", "surface1", "surface2", "overlay1", "overlay2", "text", "subtext0", "subtext1", "sapphire", "mauve", "green", "yellow", "red", "lavender", ]; let content = fs::read_to_string(path).map_err(|e| format!("{e}"))?; let mut map: HashMap<String, Color> = HashMap::new(); let mut errors: Vec<String> = Vec::new(); let mut seen_keys: HashSet<String> = HashSet::new(); for (idx, line) in content.lines().enumerate() { let line_no = idx + 1; let trimmed = line.trim(); if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("//") { continue; } if !trimmed.contains('=') { errors.push(format!("- Missing '=' on line {line_no}")); continue; } let mut parts = trimmed.splitn(2, '='); let raw_key = parts.next().unwrap_or(""); let key = raw_key.trim(); let val = parts.next().unwrap_or("").trim(); if key.is_empty() { errors.push(format!("- Missing key before '=' on line {line_no}")); continue; } let norm = key.to_lowercase().replace(['.', '-', ' '], "_"); // Allow non-theme preference keys to live in pacsea.conf without erroring let is_pref_key = norm.starts_with("pref_") || norm.starts_with("settings_") || norm.starts_with("layout_") || norm.starts_with("keybind_") || norm.starts_with("app_") || norm.starts_with("sort_") || norm.starts_with("clipboard_") || norm.starts_with("show_") || norm == "results_sort"; if is_pref_key { // Skip theme handling; parsed elsewhere continue; } // Track duplicates (by canonical form if known, otherwise normalized input) let canon_or_norm = crate::theme::parsing::canonical_for_key(&norm).unwrap_or(norm.as_str()); if !seen_keys.insert(canon_or_norm.to_string()) { errors.push(format!("- Duplicate key '{key}' on line {line_no}")); } apply_override_to_map(&mut map, key, val, &mut errors, line_no); } // Check missing required keys // Syntax command color defaults to sapphire if not specified let mut missing: Vec<&str> = Vec::new(); for k in REQUIRED { if !map.contains_key(k) { missing.push(k); } } if !missing.is_empty() { let preferred: Vec<String> = missing.iter().map(|k| canonical_to_preferred(k)).collect(); errors.push(format!("- Missing required keys: {}", preferred.join(", "))); } if errors.is_empty() { let get = |name: &str| { map.get(name) .copied() .expect("all required keys should be present after validation") }; Ok(Theme { base: get("base"), mantle: get("mantle"), crust: get("crust"), surface1: get("surface1"), surface2: get("surface2"), overlay1: get("overlay1"), overlay2: get("overlay2"), text: get("text"), subtext0: get("subtext0"), subtext1: get("subtext1"), sapphire: get("sapphire"), mauve: get("mauve"), green: get("green"), yellow: get("yellow"), red: get("red"), lavender: get("lavender"), }) } else { Err(errors.join("\n")) } } /// What: Load a theme from disk while discarding any diagnostics on failure. /// /// Inputs: /// - `path`: Filesystem path to the theme configuration. /// /// Output: /// - `Some(Theme)` when parsing succeeds. /// - `None` when the file is missing or contains validation errors. /// /// Details: /// - Wraps [`try_load_theme_with_diagnostics`] and converts its error into `None`. pub fn load_theme_from_file(path: &Path) -> Option<Theme> { try_load_theme_with_diagnostics(path).ok() }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/theme/config/settings_ensure.rs
src/theme/config/settings_ensure.rs
use std::collections::HashSet; use std::fs; use std::path::Path; use crate::theme::config::skeletons::{ KEYBINDS_SKELETON_CONTENT, SETTINGS_SKELETON_CONTENT, THEME_SKELETON_CONTENT, }; use crate::theme::paths::{config_dir, resolve_keybinds_config_path, resolve_settings_config_path}; use crate::theme::types::Settings; /// What: Convert a boolean value to a config string. /// /// Inputs: /// - `value`: Boolean value to convert /// /// Output: /// - "true" or "false" string fn bool_to_string(value: bool) -> String { if value { "true".to_string() } else { "false".to_string() } } /// What: Convert an optional integer to a config string. /// /// Inputs: /// - `value`: Optional integer value /// /// Output: /// - String representation of the value, or "all" if None fn optional_int_to_string(value: Option<u32>) -> String { value.map_or_else(|| "all".to_string(), |v| v.to_string()) } /// What: Get layout-related setting values. /// /// Inputs: /// - `key`: Normalized key name /// - `prefs`: Current in-memory settings /// /// Output: /// - Some(String) if key was handled, None otherwise fn get_layout_value(key: &str, prefs: &Settings) -> Option<String> { match key { "layout_left_pct" => Some(prefs.layout_left_pct.to_string()), "layout_center_pct" => Some(prefs.layout_center_pct.to_string()), "layout_right_pct" => Some(prefs.layout_right_pct.to_string()), _ => None, } } /// What: Get app/UI-related setting values. /// /// Inputs: /// - `key`: Normalized key name /// - `prefs`: Current in-memory settings /// /// Output: /// - Some(String) if key was handled, None otherwise fn get_app_value(key: &str, prefs: &Settings) -> Option<String> { match key { "app_dry_run_default" => Some(bool_to_string(prefs.app_dry_run_default)), "sort_mode" => Some(prefs.sort_mode.as_config_key().to_string()), "clipboard_suffix" => Some(prefs.clipboard_suffix.clone()), "show_recent_pane" | "show_search_history_pane" => { Some(bool_to_string(prefs.show_recent_pane)) } "show_install_pane" => Some(bool_to_string(prefs.show_install_pane)), "show_keybinds_footer" => Some(bool_to_string(prefs.show_keybinds_footer)), "package_marker" => { let marker_str = match prefs.package_marker { crate::theme::types::PackageMarker::FullLine => "full_line", crate::theme::types::PackageMarker::Front => "front", crate::theme::types::PackageMarker::End => "end", }; Some(marker_str.to_string()) } "app_start_mode" => { let mode = if prefs.start_in_news { "news" } else { "package" }; Some(mode.to_string()) } "skip_preflight" => Some(bool_to_string(prefs.skip_preflight)), "search_startup_mode" => { let mode = if prefs.search_startup_mode { "normal_mode" } else { "insert_mode" }; Some(mode.to_string()) } "locale" => Some(prefs.locale.clone()), "preferred_terminal" => Some(prefs.preferred_terminal.clone()), _ => None, } } /// What: Get mirror-related setting values. /// /// Inputs: /// - `key`: Normalized key name /// - `prefs`: Current in-memory settings /// /// Output: /// - Some(String) if key was handled, None otherwise fn get_mirror_value(key: &str, prefs: &Settings) -> Option<String> { match key { "selected_countries" => Some(prefs.selected_countries.clone()), "mirror_count" => Some(prefs.mirror_count.to_string()), "virustotal_api_key" => Some(prefs.virustotal_api_key.clone()), _ => None, } } /// What: Get news-related setting values. /// /// Inputs: /// - `key`: Normalized key name /// - `prefs`: Current in-memory settings /// /// Output: /// - Some(String) if key was handled, None otherwise fn get_news_value(key: &str, prefs: &Settings) -> Option<String> { match key { "news_read_symbol" => Some(prefs.news_read_symbol.clone()), "news_unread_symbol" => Some(prefs.news_unread_symbol.clone()), "news_filter_show_arch_news" => Some(bool_to_string(prefs.news_filter_show_arch_news)), "news_filter_show_advisories" => Some(bool_to_string(prefs.news_filter_show_advisories)), "news_filter_show_pkg_updates" => Some(bool_to_string(prefs.news_filter_show_pkg_updates)), "news_filter_show_aur_updates" => Some(bool_to_string(prefs.news_filter_show_aur_updates)), "news_filter_show_aur_comments" => { Some(bool_to_string(prefs.news_filter_show_aur_comments)) } "news_filter_installed_only" => Some(bool_to_string(prefs.news_filter_installed_only)), "news_max_age_days" => Some(optional_int_to_string(prefs.news_max_age_days)), "startup_news_configured" => Some(bool_to_string(prefs.startup_news_configured)), "startup_news_show_arch_news" => Some(bool_to_string(prefs.startup_news_show_arch_news)), "startup_news_show_advisories" => Some(bool_to_string(prefs.startup_news_show_advisories)), "startup_news_show_aur_updates" => { Some(bool_to_string(prefs.startup_news_show_aur_updates)) } "startup_news_show_aur_comments" => { Some(bool_to_string(prefs.startup_news_show_aur_comments)) } "startup_news_show_pkg_updates" => { Some(bool_to_string(prefs.startup_news_show_pkg_updates)) } "startup_news_max_age_days" => { Some(optional_int_to_string(prefs.startup_news_max_age_days)) } "news_cache_ttl_days" => Some(prefs.news_cache_ttl_days.to_string()), _ => None, } } /// What: Get updates/refresh-related setting values. /// /// Inputs: /// - `key`: Normalized key name /// - `prefs`: Current in-memory settings /// /// Output: /// - Some(String) if key was handled, None otherwise fn get_updates_value(key: &str, prefs: &Settings) -> Option<String> { match key { "updates_refresh_interval" | "updates_interval" | "refresh_interval" => { Some(prefs.updates_refresh_interval.to_string()) } _ => None, } } /// What: Get scan-related setting values. /// /// Inputs: /// - `key`: Normalized key name /// - `prefs`: Current in-memory settings /// /// Output: /// - Some(String) if key was handled, None otherwise fn get_scan_value(key: &str, _prefs: &Settings) -> Option<String> { match key { "scan_do_clamav" | "scan_do_trivy" | "scan_do_semgrep" | "scan_do_shellcheck" | "scan_do_virustotal" | "scan_do_custom" | "scan_do_sleuth" => { // Scan keys default to true Some("true".to_string()) } _ => None, } } /// What: Get the value for a setting key, preferring prefs over skeleton default. /// /// Inputs: /// - `key`: Normalized key name /// - `skeleton_value`: Default value from skeleton /// - `prefs`: Current in-memory settings /// /// Output: /// - String value to use for the setting /// /// Details: /// - Delegates to category-specific functions to reduce complexity. /// - Mirrors the parsing architecture for consistency. fn get_setting_value(key: &str, skeleton_value: String, prefs: &Settings) -> String { get_layout_value(key, prefs) .or_else(|| get_app_value(key, prefs)) .or_else(|| get_mirror_value(key, prefs)) .or_else(|| get_news_value(key, prefs)) .or_else(|| get_updates_value(key, prefs)) .or_else(|| get_scan_value(key, prefs)) .unwrap_or(skeleton_value) } /// What: Parse skeleton and extract missing settings with comments. /// /// Inputs: /// - `skeleton_lines`: Lines from the settings skeleton /// - `have`: Set of existing keys /// - `prefs`: Current settings to get values from /// /// Output: /// - Vector of (`setting_line`, `optional_comment`) tuples fn parse_missing_settings( skeleton_lines: &[&str], have: &HashSet<String>, prefs: &Settings, ) -> Vec<(String, Option<String>)> { let mut missing_settings: Vec<(String, Option<String>)> = Vec::new(); let mut current_comment: Option<String> = None; for line in skeleton_lines { let trimmed = line.trim(); if trimmed.is_empty() { current_comment = None; continue; } if trimmed.starts_with('#') { // Check if this is a comment for a setting (not a section header or empty comment) if !trimmed.contains("—") && !trimmed.starts_with("# Pacsea") && trimmed.len() > 1 && !trimmed.starts_with("# Available countries") { current_comment = Some(trimmed.to_string()); } else { current_comment = None; } continue; } if trimmed.starts_with("//") { current_comment = None; continue; } if trimmed.contains('=') { let mut parts = trimmed.splitn(2, '='); let raw_key = parts.next().unwrap_or(""); let skeleton_value = parts.next().unwrap_or("").trim().to_string(); let key = raw_key.trim().to_lowercase().replace(['.', '-', ' '], "_"); if have.contains(&key) { current_comment = None; } else { // Use value from prefs if available, otherwise use skeleton value let value = get_setting_value(&key, skeleton_value, prefs); let setting_line = format!("{} = {}", raw_key.trim(), value); missing_settings.push((setting_line, current_comment.take())); } } } missing_settings } /// What: Ensure all expected settings keys exist in `settings.conf`, appending defaults as needed. /// /// Inputs: /// - `prefs`: Current in-memory settings whose values seed the file when keys are missing. /// /// Output: /// - None. /// /// # Panics /// - Panics if `lines.last()` is called on an empty vector after checking `!lines.is_empty()` (should not happen due to the check) /// /// Details: /// - Preserves existing lines and comments while adding only absent keys. /// - Creates the settings file from the skeleton when it is missing or empty. pub fn ensure_settings_keys_present(prefs: &Settings) { // Always resolve to HOME/XDG path similar to save_sort_mode // This ensures we always have a path, even if the file doesn't exist yet let p = resolve_settings_config_path().or_else(|| { std::env::var("XDG_CONFIG_HOME") .ok() .map(std::path::PathBuf::from) .or_else(|| { std::env::var("HOME") .ok() .map(|h| Path::new(&h).join(".config")) }) .map(|base| base.join("pacsea").join("settings.conf")) }); let Some(p) = p else { // This should never happen (HOME should always be set), but if it does, we can't proceed return; }; // Ensure directory exists if let Some(dir) = p.parent() { let _ = fs::create_dir_all(dir); } let meta = std::fs::metadata(&p).ok(); let file_exists = meta.is_some(); let file_empty = meta.is_none_or(|m| m.len() == 0); let created_new = !file_exists || file_empty; let mut lines: Vec<String> = if file_exists && !file_empty { // File exists and has content - read it fs::read_to_string(&p) .map(|content| content.lines().map(ToString::to_string).collect()) .unwrap_or_default() } else { // File doesn't exist or is empty - start with skeleton Vec::new() }; // If file is missing or empty, seed with the built-in skeleton content first if created_new || lines.is_empty() { lines = SETTINGS_SKELETON_CONTENT .lines() .map(ToString::to_string) .collect(); } // Parse existing settings keys (normalize keys like the parser does) let mut have: HashSet<String> = HashSet::new(); for line in &lines { let trimmed = line.trim(); if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("//") { continue; } if let Some(eq) = trimmed.find('=') { let (kraw, _) = trimmed.split_at(eq); let key = kraw.trim().to_lowercase().replace(['.', '-', ' '], "_"); if key == "show_recent_pane" { have.insert("show_search_history_pane".to_string()); } have.insert(key); } } // Parse skeleton to extract settings entries with their comments let skeleton_lines: Vec<&str> = SETTINGS_SKELETON_CONTENT.lines().collect(); let missing_settings = parse_missing_settings(&skeleton_lines, &have, prefs); // Update settings file if needed if created_new || !missing_settings.is_empty() { // Append missing settings to the file // Add separator and header comment for auto-added settings if !created_new && !lines.is_empty() && !lines .last() .expect("lines should not be empty after is_empty() check") .trim() .is_empty() { lines.push(String::new()); } if !missing_settings.is_empty() { lines.push("# Missing settings added automatically".to_string()); lines.push(String::new()); } for (setting_line, comment) in &missing_settings { if let Some(comment) = comment { lines.push(comment.clone()); } lines.push(setting_line.clone()); } let new_content = lines.join("\n"); let _ = fs::write(p, new_content); } // Ensure keybinds file exists with skeleton if missing (best-effort) // Try to use the same path resolution as reading, but fall back to config_dir if file doesn't exist yet let kb = resolve_keybinds_config_path().unwrap_or_else(|| config_dir().join("keybinds.conf")); if kb.exists() { // Append missing keybinds to existing file ensure_keybinds_present(&kb); } else { if let Some(dir) = kb.parent() { let _ = fs::create_dir_all(dir); } let _ = fs::write(&kb, KEYBINDS_SKELETON_CONTENT); } } /// What: Ensure all expected keybind entries exist in `keybinds.conf`, appending defaults as needed. /// /// Inputs: /// - `keybinds_path`: Path to the keybinds.conf file. /// /// Output: /// - None. /// /// Details: /// - Preserves existing lines and comments while adding only absent keybinds. /// - Parses the skeleton to extract all keybind entries with their associated comments. /// - Appends missing keybinds with their comments in the correct sections. fn ensure_keybinds_present(keybinds_path: &Path) { // Read existing file let Ok(existing_content) = fs::read_to_string(keybinds_path) else { return; // Can't read, skip }; // Parse existing keybinds (normalize keys like the parser does) let mut have: HashSet<String> = HashSet::new(); for line in existing_content.lines() { let trimmed = line.trim(); if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("//") { continue; } if !trimmed.contains('=') { continue; } let mut parts = trimmed.splitn(2, '='); let raw_key = parts.next().unwrap_or(""); let key = raw_key.trim().to_lowercase().replace(['.', '-', ' '], "_"); have.insert(key); } // Parse skeleton to extract keybind entries with their comments let skeleton_lines: Vec<&str> = KEYBINDS_SKELETON_CONTENT.lines().collect(); let mut missing_keybinds: Vec<(String, Option<String>)> = Vec::new(); let mut current_comment: Option<String> = None; let mut current_section_header: Option<String> = None; for line in skeleton_lines { let trimmed = line.trim(); if trimmed.is_empty() { // Clear descriptive comment on empty lines (section header persists until next keybind) current_comment = None; continue; } if trimmed.starts_with('#') { // Check if this is a section header (contains "—" or is a special header) if trimmed.contains("—") || trimmed.starts_with("# Pacsea") || trimmed.starts_with("# Modifiers") { current_section_header = Some(trimmed.to_string()); current_comment = None; } else { // Descriptive comment for a keybind current_comment = Some(trimmed.to_string()); } continue; } if trimmed.starts_with("//") { current_comment = None; continue; } if trimmed.contains('=') { let mut parts = trimmed.splitn(2, '='); let raw_key = parts.next().unwrap_or(""); let key = raw_key.trim().to_lowercase().replace(['.', '-', ' '], "_"); if !have.contains(&key) { // Key is missing, build comment string with section header and descriptive comment let mut comment_parts = Vec::new(); if let Some(ref section) = current_section_header { comment_parts.push(section.clone()); } if let Some(ref desc) = current_comment { comment_parts.push(desc.clone()); } let combined_comment = if comment_parts.is_empty() { None } else { Some(comment_parts.join("\n")) }; missing_keybinds.push((trimmed.to_string(), combined_comment)); } // Clear both descriptive comment and section header after processing keybind // (whether the keybind exists or not). Only the first missing keybind in a section // will include the section header in its comment. current_comment = None; current_section_header = None; } } // If no missing keybinds, nothing to do if missing_keybinds.is_empty() { return; } // Append missing keybinds to the file let mut new_lines: Vec<String> = existing_content.lines().map(ToString::to_string).collect(); // Add separator and header comment for auto-added keybinds if !new_lines.is_empty() && !new_lines .last() .expect("new_lines should not be empty after is_empty() check") .trim() .is_empty() { new_lines.push(String::new()); } if !missing_keybinds.is_empty() { new_lines.push("# Missing keybinds added automatically".to_string()); new_lines.push(String::new()); } for (keybind_line, comment) in &missing_keybinds { if let Some(comment) = comment { new_lines.push(comment.clone()); } new_lines.push(keybind_line.clone()); } let new_content = new_lines.join("\n"); let _ = fs::write(keybinds_path, new_content); } /// What: Migrate legacy `pacsea.conf` into the split `theme.conf` and `settings.conf` files. /// /// Inputs: /// - None. /// /// Output: /// - None. /// /// Details: /// - Copies non-preference keys to `theme.conf` and preference keys (excluding keybinds) to `settings.conf`. /// - Seeds missing files with skeleton content when the legacy file is absent or empty. /// - Leaves existing, non-empty split configs untouched to avoid overwriting user changes. pub fn maybe_migrate_legacy_confs() { let base = config_dir(); let legacy = base.join("pacsea.conf"); if !legacy.is_file() { // No legacy file: ensure split configs exist with skeletons let theme_path = base.join("theme.conf"); let settings_path = base.join("settings.conf"); let keybinds_path = base.join("keybinds.conf"); // theme.conf let theme_missing_or_empty = std::fs::metadata(&theme_path) .ok() .is_none_or(|m| m.len() == 0); if theme_missing_or_empty { if let Some(dir) = theme_path.parent() { let _ = fs::create_dir_all(dir); } let _ = fs::write(&theme_path, THEME_SKELETON_CONTENT); } // settings.conf let settings_missing_or_empty = std::fs::metadata(&settings_path) .ok() .is_none_or(|m| m.len() == 0); if settings_missing_or_empty { if let Some(dir) = settings_path.parent() { let _ = fs::create_dir_all(dir); } let _ = fs::write(&settings_path, SETTINGS_SKELETON_CONTENT); } // keybinds.conf let keybinds_missing_or_empty = std::fs::metadata(&keybinds_path) .ok() .is_none_or(|m| m.len() == 0); if keybinds_missing_or_empty { if let Some(dir) = keybinds_path.parent() { let _ = fs::create_dir_all(dir); } let _ = fs::write(&keybinds_path, KEYBINDS_SKELETON_CONTENT); } return; } let theme_path = base.join("theme.conf"); let settings_path = base.join("settings.conf"); let theme_missing_or_empty = std::fs::metadata(&theme_path) .ok() .is_none_or(|m| m.len() == 0); let settings_missing_or_empty = std::fs::metadata(&settings_path) .ok() .is_none_or(|m| m.len() == 0); if !theme_missing_or_empty && !settings_missing_or_empty { // Nothing to do return; } let Ok(content) = fs::read_to_string(&legacy) else { return; }; let mut theme_lines: Vec<String> = Vec::new(); let mut settings_lines: Vec<String> = Vec::new(); for line in content.lines() { let trimmed = line.trim(); if trimmed.is_empty() || trimmed.starts_with('#') || trimmed.starts_with("//") { continue; } if !trimmed.contains('=') { continue; } let mut parts = trimmed.splitn(2, '='); let raw_key = parts.next().unwrap_or(""); let key = raw_key.trim(); let norm = key.to_lowercase().replace(['.', '-', ' '], "_"); // Same classification as theme parsing: treat these as non-theme preference keys let is_pref_key = norm.starts_with("pref_") || norm.starts_with("settings_") || norm.starts_with("layout_") || norm.starts_with("keybind_") || norm.starts_with("app_") || norm.starts_with("sort_") || norm.starts_with("clipboard_") || norm.starts_with("show_") || norm == "results_sort"; if is_pref_key { // Exclude keybinds from settings.conf; those live in keybinds.conf if !norm.starts_with("keybind_") { settings_lines.push(trimmed.to_string()); } } else { theme_lines.push(trimmed.to_string()); } } if theme_missing_or_empty { if let Some(dir) = theme_path.parent() { let _ = fs::create_dir_all(dir); } if theme_lines.is_empty() { let _ = fs::write(&theme_path, THEME_SKELETON_CONTENT); } else { let mut out = String::new(); out.push_str("# Pacsea theme configuration (migrated from pacsea.conf)\n"); out.push_str(&theme_lines.join("\n")); out.push('\n'); let _ = fs::write(&theme_path, out); } } if settings_missing_or_empty { if let Some(dir) = settings_path.parent() { let _ = fs::create_dir_all(dir); } if settings_lines.is_empty() { let _ = fs::write(&settings_path, SETTINGS_SKELETON_CONTENT); } else { let mut out = String::new(); out.push_str("# Pacsea settings configuration (migrated from pacsea.conf)\n"); out.push_str(&settings_lines.join("\n")); out.push('\n'); let _ = fs::write(&settings_path, out); } } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/updates.rs
src/ui/updates.rs
use ratatui::{ Frame, prelude::{Alignment, Rect}, style::{Modifier, Style}, text::{Line, Span}, widgets::{Block, Paragraph}, }; use unicode_width::UnicodeWidthStr; use crate::i18n; use crate::state::{AppState, types::AppMode}; use crate::theme::theme; /// What: Render the updates available button at the top of the window and lockout status on the right. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Application state containing updates count, loading state, and faillock status /// - `area`: Target rectangle for the updates button (should be 1 line high) /// /// Output: /// - Draws the updates button and lockout status, records clickable rectangle in `app.updates_button_rect` /// /// Details: /// - In Package mode: Shows "Updates available (X)" if count > 0, "No updates available" if count is 0, /// or "Checking updates..." if still loading /// - In News mode: Shows "News Ready" if news are available, "No News available" if no news, /// or "Loading news..." if still loading /// - Shows lockout status on the right if user is locked out /// - Button is styled similar to other buttons in the UI /// - Records clickable rectangle for mouse interaction pub fn render_updates_button(f: &mut Frame, app: &mut AppState, area: Rect) { let th = theme(); // Determine button text based on app mode let button_text = if matches!(app.app_mode, AppMode::News) { // News mode: show news button if app.news_loading { i18n::t(app, "app.news_button.loading") } else if app.news_ready { i18n::t(app, "app.news_button.ready") } else { i18n::t(app, "app.news_button.none") } } else { // Package mode: show updates button if app.updates_loading { i18n::t(app, "app.updates_button.loading") } else if let Some(count) = app.updates_count { if count > 0 { i18n::t_fmt1(app, "app.updates_button.available", count) } else { i18n::t(app, "app.updates_button.none") } } else { i18n::t(app, "app.updates_button.none") } }; // Check if lockout status should be displayed let lockout_text = if app.faillock_locked { app.faillock_remaining_minutes.map_or_else( || Some(crate::i18n::t(app, "app.updates_button.locked")), |remaining| { if remaining > 0 { Some(crate::i18n::t_fmt1( app, "app.updates_button.locked_with_time", remaining, )) } else { Some(crate::i18n::t(app, "app.updates_button.locked")) } }, ) } else { None }; // Split area if lockout status is shown if let Some(lockout) = &lockout_text { let chunks = ratatui::layout::Layout::default() .direction(ratatui::layout::Direction::Horizontal) .constraints([ ratatui::layout::Constraint::Min(0), ratatui::layout::Constraint::Length( u16::try_from(lockout.width()) .unwrap_or(20) .min(area.width.saturating_sub(10)), ), ]) .split(area); // Render button in left area (updates or news depending on mode) if matches!(app.app_mode, AppMode::News) { render_news_button_inner(f, app, chunks[0], &button_text, &th); } else { render_updates_button_inner(f, app, chunks[0], &button_text, &th); } // Render lockout status in right area let lockout_style = Style::default() .fg(th.red) .bg(th.base) .add_modifier(Modifier::BOLD); let lockout_line = Line::from(Span::styled(lockout.clone(), lockout_style)); let lockout_paragraph = Paragraph::new(lockout_line) .alignment(Alignment::Right) .block( Block::default() .borders(ratatui::widgets::Borders::NONE) .style(Style::default().bg(th.base)), ); f.render_widget(lockout_paragraph, chunks[1]); } else { // Render button only (centered) - updates or news depending on mode if matches!(app.app_mode, AppMode::News) { render_news_button_inner(f, app, area, &button_text, &th); } else { render_updates_button_inner(f, app, area, &button_text, &th); } } } /// What: Render the updates button inner content. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Application state /// - `area`: Target rectangle /// - `button_text`: Button text to display /// - `th`: Theme /// /// Output: /// - Draws the updates button and records clickable rectangle fn render_updates_button_inner( f: &mut Frame, app: &mut AppState, area: Rect, button_text: &str, th: &crate::theme::Theme, ) { // Style the button (similar to other buttons) let button_style = Style::default() .fg(th.mauve) .bg(th.surface2) .add_modifier(Modifier::BOLD); // Create button with underlined first character let mut spans = Vec::new(); if let Some(first) = button_text.chars().next() { let rest = &button_text[first.len_utf8()..]; spans.push(Span::styled( first.to_string(), button_style.add_modifier(Modifier::UNDERLINED), )); spans.push(Span::styled(rest.to_string(), button_style)); } else { spans.push(Span::styled(button_text.to_string(), button_style)); } let line = Line::from(spans); let paragraph = Paragraph::new(line).alignment(Alignment::Center).block( Block::default() .borders(ratatui::widgets::Borders::NONE) .style(Style::default().bg(th.base)), ); // Render the button f.render_widget(paragraph, area); // Calculate clickable rectangle: only the button text width, centered // Use Unicode display width, not byte length, to handle wide characters let button_width = u16::try_from(button_text.width()).unwrap_or(u16::MAX); let button_x = area .x .saturating_add(area.width.saturating_sub(button_width) / 2); app.updates_button_rect = Some((button_x, area.y, button_width, area.height)); } /// What: Render the news button inner content. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Application state /// - `area`: Target rectangle /// - `button_text`: Button text to display /// - `th`: Theme /// /// Output: /// - Draws the news button and records clickable rectangle fn render_news_button_inner( f: &mut Frame, app: &mut AppState, area: Rect, button_text: &str, th: &crate::theme::Theme, ) { // Style the button (similar to other buttons) let button_style = Style::default() .fg(th.mauve) .bg(th.surface2) .add_modifier(Modifier::BOLD); // Create button with underlined first character let mut spans = Vec::new(); if let Some(first) = button_text.chars().next() { let rest = &button_text[first.len_utf8()..]; spans.push(Span::styled( first.to_string(), button_style.add_modifier(Modifier::UNDERLINED), )); spans.push(Span::styled(rest.to_string(), button_style)); } else { spans.push(Span::styled(button_text.to_string(), button_style)); } let line = Line::from(spans); let paragraph = Paragraph::new(line).alignment(Alignment::Center).block( Block::default() .borders(ratatui::widgets::Borders::NONE) .style(Style::default().bg(th.base)), ); // Render the button f.render_widget(paragraph, area); // Calculate clickable rectangle: only the button text width, centered // Use Unicode display width, not byte length, to handle wide characters let button_width = u16::try_from(button_text.width()).unwrap_or(u16::MAX); let button_x = area .x .saturating_add(area.width.saturating_sub(button_width) / 2); app.news_button_rect = Some((button_x, area.y, button_width, area.height)); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/misc.rs
src/ui/modals/misc.rs
use ratatui::{ Frame, prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap}, }; use super::common::render_simple_list_modal; use crate::state::{AppState, types::OptionalDepRow}; use crate::theme::theme; /// What: Render the optional dependencies modal with install status indicators. /// /// Inputs: /// - `f`: Frame to render into /// - `area`: Full screen area used to center the modal /// - `rows`: Optional dependency entries (label, package, status) /// - `selected`: Index of the currently highlighted row /// /// Output: /// - Draws the modal content and highlights the selected row; no state mutations besides rendering. /// /// Details: /// - Marks installed rows, shows optional notes, and reuses the common simple modal renderer for /// consistent styling. pub fn render_optional_deps( f: &mut Frame, area: Rect, rows: &[OptionalDepRow], selected: usize, app: &crate::state::AppState, ) { let th = theme(); // Build content lines with selection and install status markers let mut lines: Vec<Line<'static>> = Vec::new(); lines.push(Line::from(Span::styled( crate::i18n::t(app, "app.modals.optional_deps.heading"), Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), ))); lines.push(Line::from("")); for (i, row) in rows.iter().enumerate() { let is_sel = selected == i; let (mark, color) = if row.installed { ( crate::i18n::t(app, "app.modals.optional_deps.markers.installed"), th.green, ) } else { ( crate::i18n::t(app, "app.modals.optional_deps.markers.not_installed"), th.overlay1, ) }; let style = if is_sel { Style::default() .fg(th.crust) .bg(th.lavender) .add_modifier(Modifier::BOLD) } else { Style::default().fg(th.text) }; let mut segs: Vec<Span> = Vec::new(); segs.push(Span::styled(format!("{} ", row.label), style)); segs.push(Span::styled( format!("[{}]", row.package), Style::default().fg(th.overlay1), )); segs.push(Span::raw(" ")); segs.push(Span::styled(mark.clone(), Style::default().fg(color))); if let Some(note) = &row.note { segs.push(Span::raw(" ")); segs.push(Span::styled( format!("({note})"), Style::default().fg(th.overlay2), )); } lines.push(Line::from(segs)); } lines.push(Line::from("")); lines.push(Line::from(Span::styled( crate::i18n::t(app, "app.modals.optional_deps.footer_hint"), Style::default().fg(th.subtext1), ))); render_simple_list_modal( f, area, &crate::i18n::t(app, "app.modals.optional_deps.title"), lines, ); } #[allow(clippy::too_many_arguments)] /// What: Render the scan configuration modal listing security tools to toggle. /// /// Inputs: /// - `f`: Frame to render into /// - `area`: Full screen area used to center the modal /// - `do_clamav`…`do_sleuth`: Flags indicating which scanners are enabled /// - `cursor`: Index of the row currently focused /// /// Output: /// - Draws the configuration list, highlighting the focused entry and indicating current toggles. /// /// Details: /// - Presents each scanner with checkboxes, respecting theme emphasis for the cursor and summarizing /// available shortcuts at the bottom. #[allow(clippy::fn_params_excessive_bools)] pub fn render_scan_config( f: &mut Frame, area: Rect, do_clamav: bool, do_trivy: bool, do_semgrep: bool, do_shellcheck: bool, do_virustotal: bool, do_custom: bool, do_sleuth: bool, cursor: usize, ) { let th = theme(); let mut lines: Vec<Line<'static>> = Vec::new(); let items: [(&str, bool); 7] = [ ("ClamAV (antivirus)", do_clamav), ("Trivy (filesystem)", do_trivy), ("Semgrep (static analysis)", do_semgrep), ("ShellCheck (PKGBUILD/.install)", do_shellcheck), ("VirusTotal (hash lookups)", do_virustotal), ("Custom scan for Suspicious patterns", do_custom), ("aur-sleuth (LLM audit)", do_sleuth), ]; for (i, (label, checked)) in items.iter().enumerate() { let mark = if *checked { "[x]" } else { "[ ]" }; let mut spans: Vec<Span> = Vec::new(); spans.push(Span::styled( format!("{mark} "), Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), )); let style = if i == cursor { Style::default() .fg(th.text) .add_modifier(Modifier::BOLD | Modifier::UNDERLINED) } else { Style::default().fg(th.subtext1) }; spans.push(Span::styled((*label).to_string(), style)); lines.push(Line::from(spans)); } lines.push(Line::from(Span::raw(""))); lines.push(Line::from(Span::styled( "Up/Down: select • Space: toggle • Enter: run • Esc: cancel", Style::default().fg(th.overlay1), ))); render_simple_list_modal(f, area, "Scan Configuration", lines); } /// What: Render the news setup modal for configuring startup news popup. /// /// Inputs: /// - `f`: Frame to render into /// - `area`: Full screen area used to center the modal /// - `app`: Application state for i18n /// - `show_arch_news`…`show_pkg_updates`: Flags indicating which news sources are enabled /// - `max_age_days`: Selected maximum age (7, 30, or 90) /// - `cursor`: Index of the row currently focused (0-4 for toggles, 5-7 for date buttons) /// /// Output: /// - Draws the configuration list, highlighting the focused entry and indicating current toggles. /// /// Details: /// - Presents 5 news source toggles with checkboxes, then date selection buttons (7/30/90 days). /// - Respects theme emphasis for the cursor and summarizes available shortcuts at the bottom. #[allow(clippy::too_many_arguments, clippy::fn_params_excessive_bools)] pub fn render_news_setup( f: &mut Frame, area: Rect, app: &AppState, show_arch_news: bool, show_advisories: bool, show_aur_updates: bool, show_aur_comments: bool, show_pkg_updates: bool, max_age_days: Option<u32>, cursor: usize, ) { let th = theme(); let mut lines: Vec<Line<'static>> = Vec::new(); // News source toggles (cursor 0-4) let items: [(&str, bool); 5] = [ ( &crate::i18n::t(app, "app.modals.news_setup.arch_news"), show_arch_news, ), ( &crate::i18n::t(app, "app.modals.news_setup.advisories"), show_advisories, ), ( &crate::i18n::t(app, "app.modals.news_setup.aur_updates"), show_aur_updates, ), ( &crate::i18n::t(app, "app.modals.news_setup.aur_comments"), show_aur_comments, ), ( &crate::i18n::t(app, "app.modals.news_setup.pkg_updates"), show_pkg_updates, ), ]; for (i, (label, checked)) in items.iter().enumerate() { let mark = if *checked { "[x]" } else { "[ ]" }; let mut spans: Vec<Span> = Vec::new(); spans.push(Span::styled( format!("{mark} "), Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), )); let style = if i == cursor { Style::default() .fg(th.text) .add_modifier(Modifier::BOLD | Modifier::UNDERLINED) } else { Style::default().fg(th.subtext1) }; spans.push(Span::styled((*label).to_string(), style)); lines.push(Line::from(spans)); } // Date selection row (cursor 5-7) lines.push(Line::from("")); let date_label = crate::i18n::t(app, "app.modals.news_setup.date_selection"); lines.push(Line::from(Span::styled( format!("{date_label}:"), Style::default().fg(th.subtext1), ))); let date_options = [7, 30, 90]; let mut date_spans: Vec<Span> = Vec::new(); for (i, &days) in date_options.iter().enumerate() { let date_cursor = 5 + i; // cursor 5, 6, 7 let is_selected = max_age_days == Some(days); let is_cursor = cursor == date_cursor; let button_text = if is_selected { format!("[{days} days]") } else { format!(" {days} days ") }; let style = if is_cursor { Style::default() .fg(th.text) .add_modifier(Modifier::BOLD | Modifier::UNDERLINED) } else if is_selected { Style::default().fg(th.mauve).add_modifier(Modifier::BOLD) } else { Style::default().fg(th.subtext1) }; date_spans.push(Span::styled(button_text.clone(), style)); if i < date_options.len() - 1 { date_spans.push(Span::raw(" ")); } } lines.push(Line::from(date_spans)); lines.push(Line::from(Span::raw(""))); let footer_hint = crate::i18n::t(app, "app.modals.news_setup.footer_hint"); lines.push(Line::from(Span::styled( footer_hint, Style::default().fg(th.overlay1), ))); render_simple_list_modal( f, area, &crate::i18n::t(app, "app.modals.news_setup.title"), lines, ); } /// What: Render the prompt encouraging installation of GNOME Terminal in GNOME environments. /// /// Inputs: /// - `f`: Frame to render into /// - `area`: Full screen area used to center the modal /// /// Output: /// - Draws a concise confirmation dialog describing recommended action and key hints. /// /// Details: /// - Highlights the heading, explains why the terminal is recommended, and warns about cancelling. #[allow(clippy::many_single_char_names)] pub fn render_gnome_terminal_prompt(f: &mut Frame, area: Rect) { let th = theme(); // Centered confirmation dialog for installing GNOME Terminal let w = area.width.saturating_sub(10).min(90); let h = 9; let x = area.x + (area.width.saturating_sub(w)) / 2; let y = area.y + (area.height.saturating_sub(h)) / 2; let rect = ratatui::prelude::Rect { x, y, width: w, height: h, }; f.render_widget(Clear, rect); let lines: Vec<Line<'static>> = vec![ Line::from(Span::styled( "GNOME Terminal or Console recommended", Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), )), Line::from(""), Line::from(Span::styled( "GNOME was detected, but no GNOME terminal (gnome-terminal or gnome-console/kgx) is installed.", Style::default().fg(th.text), )), Line::from(""), Line::from(Span::styled( "Press Enter to install gnome-terminal • Esc to cancel", Style::default().fg(th.subtext1), )), Line::from(Span::styled( "Cancel may lead to unexpected behavior.", Style::default().fg(th.yellow), )), ]; let boxw = Paragraph::new(lines) .style(Style::default().fg(th.text).bg(th.mantle)) .wrap(Wrap { trim: true }) .block( Block::default() .title(Span::styled( " Install a GNOME Terminal ", Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), )) .borders(Borders::ALL) .border_type(BorderType::Double) .border_style(Style::default().fg(th.mauve)) .style(Style::default().bg(th.mantle)), ); f.render_widget(boxw, rect); } /// What: Render the `VirusTotal` API setup modal with clickable URL and current input preview. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state (records URL rect for mouse clicks) /// - `area`: Full screen area used to center the modal /// - `input`: Current API key buffer contents /// /// Output: /// - Draws the setup dialog, updates `app.vt_url_rect`, and shows current text entry. /// /// Details: /// - Provides direct link to the API portal, surfaces instructions, and mirrors the buffer so users /// can verify pasted values. #[allow(clippy::many_single_char_names)] pub fn render_virustotal_setup(f: &mut Frame, app: &mut AppState, area: Rect, input: &str) { let th = theme(); // Centered dialog for VirusTotal API key setup with clickable URL and input field let w = area.width.saturating_sub(10).min(90); let h = 11; let x = area.x + (area.width.saturating_sub(w)) / 2; let y = area.y + (area.height.saturating_sub(h)) / 2; let rect = ratatui::prelude::Rect { x, y, width: w, height: h, }; f.render_widget(Clear, rect); // Build content let vt_url = "https://www.virustotal.com/gui/my-apikey"; // Show input buffer (not masked) let shown = if input.is_empty() { "<empty>".to_string() } else { input.to_string() }; let lines: Vec<Line<'static>> = vec![ Line::from(Span::styled( "VirusTotal API Setup", Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), )), Line::from(""), Line::from(Span::styled( "Open the link to view your API key:", Style::default().fg(th.text), )), Line::from(vec![ // Surround with spaces to avoid visual concatenation with underlying content Span::styled(" ", Style::default().fg(th.text)), Span::styled( vt_url.to_string(), Style::default() .fg(th.lavender) .add_modifier(Modifier::UNDERLINED | Modifier::BOLD), ), ]), Line::from(""), Line::from(Span::styled( "Enter/paste your API key below and press Enter to save (Esc to cancel):", Style::default().fg(th.subtext1), )), Line::from(Span::styled( format!("API key: {shown}"), Style::default().fg(th.text), )), Line::from(""), Line::from(Span::styled( "Tip: After saving, scans will auto-query VirusTotal by file hash.", Style::default().fg(th.overlay1), )), ]; let inner_x = rect.x + 1; let inner_y = rect.y + 1; let url_line_y = inner_y + 3; let url_x = inner_x + 1; let url_w = u16::try_from(vt_url.len()).unwrap_or(u16::MAX); app.vt_url_rect = Some((url_x, url_line_y, url_w, 1)); let boxw = Paragraph::new(lines) .style(Style::default().fg(th.text).bg(th.mantle)) .wrap(Wrap { trim: true }) .block( Block::default() .title(Span::styled( " VirusTotal ", Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), )) .borders(Borders::ALL) .border_type(BorderType::Double) .border_style(Style::default().fg(th.mauve)) .style(Style::default().bg(th.mantle)), ); f.render_widget(boxw, rect); } /// What: Render the import help modal describing expected file format and keybindings. /// /// Inputs: /// - `f`: Frame to render into /// - `area`: Full screen area used to center the modal /// - `app`: Application state for i18n translation /// /// Output: /// - Draws instructions for import file syntax and highlights confirm/cancel keys. /// /// Details: /// - Enumerates formatting rules, provides an example snippet, and keeps styling aligned with other /// informational modals. #[allow(clippy::many_single_char_names)] pub fn render_import_help(f: &mut Frame, area: Rect, app: &crate::state::AppState) { let th = theme(); let w = area.width.saturating_sub(10).min(85); let h = 19; let x = area.x + (area.width.saturating_sub(w)) / 2; let y = area.y + (area.height.saturating_sub(h)) / 2; let rect = ratatui::prelude::Rect { x, y, width: w, height: h, }; f.render_widget(Clear, rect); let lines: Vec<Line<'static>> = vec![ Line::from(Span::styled( crate::i18n::t(app, "app.modals.import_help.heading"), Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), )), Line::from(""), Line::from(Span::styled( crate::i18n::t(app, "app.modals.import_help.description"), Style::default().fg(th.text), )), Line::from(""), Line::from(Span::styled( crate::i18n::t(app, "app.modals.import_help.format_label"), Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD), )), Line::from(Span::raw(crate::i18n::t( app, "app.modals.import_help.format_one_per_line", ))), Line::from(Span::raw(crate::i18n::t( app, "app.modals.import_help.format_blank_ignored", ))), Line::from(Span::raw(crate::i18n::t( app, "app.modals.import_help.format_comments", ))), Line::from(""), Line::from(Span::styled( crate::i18n::t(app, "app.modals.import_help.example_label"), Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD), )), Line::from(Span::raw(" firefox")), Line::from(Span::raw(crate::i18n::t( app, "app.modals.import_help.example_comment", ))), Line::from(Span::raw(" vim")), Line::from(Span::raw(" paru")), Line::from(""), Line::from(vec![ Span::styled( "[Enter]", Style::default().fg(th.text).add_modifier(Modifier::BOLD), ), Span::styled( crate::i18n::t(app, "app.modals.import_help.hint_confirm"), Style::default().fg(th.overlay1), ), Span::raw(" • "), Span::styled( "[Esc]", Style::default().fg(th.text).add_modifier(Modifier::BOLD), ), Span::styled( crate::i18n::t(app, "app.modals.import_help.hint_cancel"), Style::default().fg(th.overlay1), ), ]), ]; let boxw = Paragraph::new(lines) .style(Style::default().fg(th.text).bg(th.mantle)) .wrap(Wrap { trim: true }) .block( Block::default() .title(Span::styled( crate::i18n::t(app, "app.modals.import_help.title"), Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), )) .borders(Borders::ALL) .border_type(BorderType::Double) .border_style(Style::default().fg(th.mauve)) .style(Style::default().bg(th.mantle)), ); f.render_widget(boxw, rect); } /// What: Render a simple loading indicator modal. /// /// Inputs: /// - `f`: Frame to render into /// - `area`: Full screen area used to center the modal /// - `message`: Loading message to display /// /// Output: /// - Draws a centered loading modal with the given message. /// /// Details: /// - Shows a simple centered box with a loading message and spinner indicator. pub fn render_loading(f: &mut Frame, area: Rect, message: &str) { let th = theme(); // Small centered modal let width = 40_u16.min(area.width.saturating_sub(4)); let height = 5_u16.min(area.height.saturating_sub(4)); let x = area.x + (area.width.saturating_sub(width)) / 2; let y = area.y + (area.height.saturating_sub(height)) / 2; let rect = Rect::new(x, y, width, height); f.render_widget(Clear, rect); let lines = vec![ Line::from(""), Line::from(Span::styled( format!("⏳ {message}"), Style::default().fg(th.text), )), ]; let boxw = Paragraph::new(lines) .style(Style::default().fg(th.text).bg(th.mantle)) .alignment(ratatui::layout::Alignment::Center) .block( Block::default() .title(Span::styled( " Loading ", Style::default().fg(th.yellow).add_modifier(Modifier::BOLD), )) .borders(Borders::ALL) .border_type(BorderType::Rounded) .border_style(Style::default().fg(th.yellow)) .style(Style::default().bg(th.mantle)), ); f.render_widget(boxw, rect); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/password.rs
src/ui/modals/password.rs
use ratatui::{ Frame, prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap}, }; use crate::state::{AppState, PackageItem, modal::PasswordPurpose}; use crate::theme::theme; /// What: Render the password prompt modal for sudo authentication. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Application state for translations /// - `area`: Full screen area used to center the modal /// - `purpose`: Purpose of the password prompt /// - `items`: Packages involved in the operation /// - `input`: Current password input (masked) /// - `error`: Optional error message /// /// Output: /// - Draws the password prompt dialog with masked input field. /// /// Details: /// - Shows purpose-specific message, package list, and masked password input. /// - Displays error message if password was incorrect. #[allow(clippy::many_single_char_names)] pub fn render_password_prompt( f: &mut Frame, app: &AppState, area: Rect, purpose: PasswordPurpose, items: &[PackageItem], input: &str, error: Option<&str>, ) { let th = theme(); // Calculate required height based on content let base_height = 8u16; // heading + empty + password label + input + empty + error space + empty + instructions let package_lines = if items.is_empty() { 0u16 } else { // package label + packages (max 4 shown) + empty u16::try_from(items.len().min(4) + 2).unwrap_or(6) }; let error_lines = if error.is_some() { 2u16 } else { 0u16 }; let required_height = base_height + package_lines + error_lines; let h = area .height .saturating_sub(6) .min(required_height.clamp(8, 14)); let w = area.width.saturating_sub(6).min(65); let x = area.x + (area.width.saturating_sub(w)) / 2; let y = area.y + (area.height.saturating_sub(h)) / 2; let rect = Rect { x, y, width: w, height: h, }; f.render_widget(Clear, rect); let mut lines: Vec<Line<'static>> = Vec::new(); // Purpose-specific heading let heading = match purpose { PasswordPurpose::Install => { crate::i18n::t(app, "app.modals.password_prompt.heading_install") } PasswordPurpose::Remove => crate::i18n::t(app, "app.modals.password_prompt.heading_remove"), PasswordPurpose::Update => crate::i18n::t(app, "app.modals.password_prompt.heading_update"), PasswordPurpose::Downgrade => { crate::i18n::t(app, "app.modals.password_prompt.heading_downgrade") } PasswordPurpose::FileSync => { crate::i18n::t(app, "app.modals.password_prompt.heading_file_sync") } }; lines.push(Line::from(Span::styled( heading, Style::default().fg(th.subtext1), ))); lines.push(Line::from("")); // Show package list if available if !items.is_empty() { let package_label = if items.len() == 1 { crate::i18n::t(app, "app.modals.password_prompt.package_label_singular") } else { crate::i18n::t(app, "app.modals.password_prompt.package_label_plural") }; lines.push(Line::from(Span::styled( package_label, Style::default().fg(th.subtext1), ))); // Show max 4 packages to keep dialog compact for p in items.iter().take(4) { let p_name = &p.name; lines.push(Line::from(Span::styled( format!(" • {p_name}"), Style::default().fg(th.text), ))); } if items.len() > 4 { let remaining = items.len() - 4; lines.push(Line::from(Span::styled( crate::i18n::t_fmt1(app, "app.modals.password_prompt.and_more", remaining), Style::default().fg(th.subtext1), ))); } lines.push(Line::from("")); } // Password input field (masked) let masked_input = "*".repeat(input.len()); lines.push(Line::from(Span::styled( crate::i18n::t(app, "app.modals.password_prompt.password_label"), Style::default().fg(th.subtext1), ))); lines.push(Line::from(Span::styled( format!(" {masked_input}_"), Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), ))); lines.push(Line::from("")); // Error message if present if let Some(err) = error { lines.push(Line::from(Span::styled( format!("⚠ {err}"), Style::default().fg(th.red).add_modifier(Modifier::BOLD), ))); lines.push(Line::from("")); } // Instructions lines.push(Line::from(Span::styled( crate::i18n::t(app, "app.modals.common.close_hint"), Style::default().fg(th.overlay1), ))); let boxw = Paragraph::new(lines) .style(Style::default().fg(th.text).bg(th.mantle)) .wrap(Wrap { trim: true }) .block( Block::default() .title(Span::styled( "Password Required", Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), )) .borders(Borders::ALL) .border_type(BorderType::Double) .border_style(Style::default().fg(th.mauve)) .style(Style::default().bg(th.mantle)), ); f.render_widget(boxw, rect); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/system_update.rs
src/ui/modals/system_update.rs
use ratatui::{ Frame, prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap}, }; use crate::i18n; use crate::state::AppState; use crate::theme::{Theme, theme}; /// What: Get style for a row based on cursor position. fn row_style(th: &Theme, cursor: usize, row: usize) -> Style { if cursor == row { Style::default() .fg(th.crust) .bg(th.lavender) .add_modifier(Modifier::BOLD) } else { Style::default().fg(th.text) } } /// What: Create a checkbox line with label. fn checkbox_line(th: &Theme, checked: bool, label: String, style: Style) -> Line<'static> { let mark = if checked { "[x]" } else { "[ ]" }; Line::from(vec![ Span::styled(format!("{mark} "), Style::default().fg(th.overlay1)), Span::styled(label, style), ]) } #[allow(clippy::too_many_arguments)] /// What: Render the system update modal with toggles for mirror/pacman/AUR/cache actions. /// /// Inputs: /// - `f`: Frame to render into /// - `area`: Full screen area used to center the modal /// - `do_mirrors`, `do_pacman`, `force_sync`, `do_aur`, `do_cache`: Selected operations /// - `country_idx`: Selected country index for mirrors /// - `countries`: Available country list /// - `mirror_count`: Desired number of mirrors /// - `cursor`: Currently highlighted row index /// /// Output: /// - Draws the update configuration dialog, highlighting the focused row and showing shortcuts. /// /// Details: /// - Formats checkbox rows, displays the effective country list from settings. /// - Pacman update shows sync mode on same line, toggled with Left/Right arrows. #[allow(clippy::many_single_char_names, clippy::fn_params_excessive_bools)] pub fn render_system_update( f: &mut Frame, app: &AppState, area: Rect, do_mirrors: bool, do_pacman: bool, force_sync: bool, do_aur: bool, do_cache: bool, country_idx: usize, countries: &[String], mirror_count: u16, cursor: usize, ) { let th = theme(); let w = area.width.saturating_sub(8).min(80); let h = 14; let x = area.x + (area.width.saturating_sub(w)) / 2; let y = area.y + (area.height.saturating_sub(h)) / 2; let rect = Rect { x, y, width: w, height: h, }; f.render_widget(Clear, rect); let mut lines: Vec<Line<'static>> = Vec::new(); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.system_update.heading"), Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), ))); lines.push(Line::from("")); // Row 0: Update Arch Mirrors lines.push(checkbox_line( &th, do_mirrors, i18n::t(app, "app.modals.system_update.entries.update_arch_mirrors"), row_style(&th, cursor, 0), )); // Row 1: Update Pacman with sync mode selector let mode_style = if cursor == 1 { Style::default().fg(th.yellow).add_modifier(Modifier::BOLD) } else { Style::default().fg(th.overlay1) }; let sync_mode = if force_sync { i18n::t(app, "app.modals.system_update.sync_mode.force") } else { i18n::t(app, "app.modals.system_update.sync_mode.normal") }; let mark = if do_pacman { "[x]" } else { "[ ]" }; lines.push(Line::from(vec![ Span::styled(format!("{mark} "), Style::default().fg(th.overlay1)), Span::styled( i18n::t(app, "app.modals.system_update.entries.update_pacman"), row_style(&th, cursor, 1), ), Span::styled(" ◄ ", mode_style), Span::styled(sync_mode, mode_style), Span::styled(" ►", mode_style), ])); // Row 2: Update AUR lines.push(checkbox_line( &th, do_aur, i18n::t(app, "app.modals.system_update.entries.update_aur"), row_style(&th, cursor, 2), )); // Row 3: Remove Cache lines.push(checkbox_line( &th, do_cache, i18n::t(app, "app.modals.system_update.entries.remove_cache"), row_style(&th, cursor, 3), )); // Row 4: Country selector (mirrors) lines.push(Line::from("")); let worldwide_text = i18n::t(app, "app.modals.system_update.worldwide"); let country_label = countries.get(country_idx).unwrap_or(&worldwide_text); let prefs = crate::theme::settings(); let conf_countries = if prefs.selected_countries.trim().is_empty() { worldwide_text.clone() } else { prefs.selected_countries }; let shown_countries = if country_label == &worldwide_text { conf_countries.as_str() } else { country_label }; lines.push(Line::from(vec![ Span::styled( i18n::t(app, "app.modals.system_update.country_label"), Style::default().fg(th.overlay1), ), Span::styled(shown_countries.to_string(), row_style(&th, cursor, 4)), Span::raw(" • "), Span::styled( i18n::t_fmt1(app, "app.modals.system_update.count_label", mirror_count), Style::default().fg(th.overlay1), ), ])); lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.system_update.footer_hint"), Style::default().fg(th.subtext1), ))); let boxw = Paragraph::new(lines) .style(Style::default().fg(th.text).bg(th.mantle)) .wrap(Wrap { trim: true }) .block( Block::default() .title(Span::styled( format!(" {} ", i18n::t(app, "app.modals.system_update.title")), Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), )) .borders(Borders::ALL) .border_type(BorderType::Double) .border_style(Style::default().fg(th.mauve)) .style(Style::default().bg(th.mantle)), ); f.render_widget(boxw, rect); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/renderer.rs
src/ui/modals/renderer.rs
use ratatui::Frame; use ratatui::prelude::Rect; use crate::state::{AppState, Modal, modal::PreflightHeaderChips, types::OptionalDepRow}; use crate::ui::modals::{ alert, announcement, confirm, help, misc, news, password, post_summary, preflight, preflight_exec, system_update, updates, }; /// What: Render `ConfirmBatchUpdate` modal and return reconstructed state. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Application state /// - `area`: Full screen area /// - `ctx`: Context struct containing all `ConfirmBatchUpdate` fields (taken by value) /// /// Output: /// - Returns reconstructed `Modal::ConfirmBatchUpdate` variant /// /// Details: /// - Delegates to `confirm::render_confirm_batch_update` and reconstructs the modal variant fn render_confirm_reinstall_modal( f: &mut Frame, app: &AppState, area: Rect, ctx: ConfirmReinstallContext, ) -> Modal { confirm::render_confirm_reinstall(f, app, area, &ctx.items); Modal::ConfirmReinstall { items: ctx.items, all_items: ctx.all_items, header_chips: ctx.header_chips, } } /// What: Render the confirm batch update modal. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Application state /// - `area`: Rendering area /// - `ctx`: Context with items and dry-run flag /// /// Output: /// - Returns the modal state after rendering /// /// Details: /// - Displays confirmation dialog for batch package updates fn render_confirm_batch_update_modal( f: &mut Frame, app: &AppState, area: Rect, ctx: ConfirmBatchUpdateContext, ) -> Modal { confirm::render_confirm_batch_update(f, app, area, &ctx.items); Modal::ConfirmBatchUpdate { items: ctx.items, dry_run: ctx.dry_run, } } /// What: Render `ConfirmAurUpdate` modal and return reconstructed state. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Application state /// - `area`: Full screen area /// - `ctx`: Context struct containing all `ConfirmAurUpdate` fields (taken by value) /// /// Output: /// - Returns reconstructed `Modal::ConfirmAurUpdate` variant /// /// Details: /// - Delegates to `confirm::render_confirm_aur_update` and reconstructs the modal variant fn render_confirm_aur_update_modal( f: &mut Frame, app: &AppState, area: Rect, ctx: ConfirmAurUpdateContext, ) -> Modal { confirm::render_confirm_aur_update(f, app, area, &ctx.message); Modal::ConfirmAurUpdate { message: ctx.message, } } /// What: Context struct grouping `PreflightExec` modal fields to reduce data flow complexity. /// /// Inputs: None (constructed from Modal variant). /// /// Output: Groups related fields together for passing to render functions. /// /// Details: Reduces individual field extractions and uses, lowering data flow complexity. struct PreflightExecContext { /// Package items being processed. items: Vec<crate::state::PackageItem>, /// Preflight action (install/remove/downgrade). action: crate::state::PreflightAction, /// Currently active preflight tab. tab: crate::state::PreflightTab, /// Whether verbose logging is enabled. verbose: bool, /// Log lines to display. log_lines: Vec<String>, /// Whether the operation can be aborted. abortable: bool, /// Header chip metrics. header_chips: PreflightHeaderChips, /// Operation success status (None if still running). success: Option<bool>, } /// What: Context struct grouping `SystemUpdate` modal fields to reduce data flow complexity. /// /// Inputs: None (constructed from Modal variant). /// /// Output: Groups related fields together for passing to render functions. /// /// Details: Reduces individual field extractions and uses, lowering data flow complexity. #[allow(clippy::struct_excessive_bools)] struct SystemUpdateContext { /// Whether to update mirrors. do_mirrors: bool, /// Whether to update official packages. do_pacman: bool, /// Whether to force database sync. force_sync: bool, /// Whether to update AUR packages. do_aur: bool, /// Whether to clean package cache. do_cache: bool, /// Currently selected country index. country_idx: usize, /// List of available countries for mirror selection. countries: Vec<String>, /// Number of mirrors to use. mirror_count: u16, /// Cursor position in the UI. cursor: usize, } /// What: Context struct grouping `PostSummary` modal fields to reduce data flow complexity. /// /// Inputs: None (constructed from Modal variant). /// /// Output: Groups related fields together for passing to render functions. /// /// Details: Reduces individual field extractions and uses, lowering data flow complexity. struct PostSummaryContext { /// Whether the operation succeeded. success: bool, /// Number of files changed. changed_files: usize, /// Number of .pacnew files created. pacnew_count: usize, /// Number of .pacsave files created. pacsave_count: usize, /// List of services pending restart. services_pending: Vec<String>, /// Snapshot label if a snapshot was created. snapshot_label: Option<String>, } /// What: Context struct grouping `ScanConfig` modal fields to reduce data flow complexity. /// /// Inputs: None (constructed from Modal variant). /// /// Output: Groups related fields together for passing to render functions. /// /// Details: Reduces individual field extractions and uses, lowering data flow complexity. #[allow(clippy::struct_excessive_bools)] struct ScanConfigContext { /// Whether to run `ClamAV` scan. do_clamav: bool, /// Whether to run `Trivy` scan. do_trivy: bool, /// Whether to run `Semgrep` scan. do_semgrep: bool, /// Whether to run `ShellCheck` scan. do_shellcheck: bool, /// Whether to run `VirusTotal` scan. do_virustotal: bool, /// Whether to run custom scan. do_custom: bool, /// Whether to run Sleuth scan. do_sleuth: bool, /// Cursor position in the UI. cursor: usize, } /// What: Context struct grouping Alert modal fields to reduce data flow complexity. /// /// Inputs: None (constructed from Modal variant). /// /// Output: Groups related fields together for passing to render functions. /// /// Details: Reduces individual field extractions and uses, lowering data flow complexity. struct AlertContext { /// Alert message to display. message: String, } /// What: Context struct grouping `ConfirmInstall` modal fields to reduce data flow complexity. /// /// Inputs: None (constructed from Modal variant). /// /// Output: Groups related fields together for passing to render functions. /// /// Details: Reduces individual field extractions and uses, lowering data flow complexity. struct ConfirmInstallContext { /// Package items to install. items: Vec<crate::state::PackageItem>, } /// What: Context struct grouping `ConfirmRemove` modal fields to reduce data flow complexity. /// /// Inputs: None (constructed from Modal variant). /// /// Output: Groups related fields together for passing to render functions. /// /// Details: Reduces individual field extractions and uses, lowering data flow complexity. struct ConfirmRemoveContext { /// Package items to remove. items: Vec<crate::state::PackageItem>, } /// What: Context struct grouping `ConfirmBatchUpdate` modal fields to reduce data flow complexity. /// /// Inputs: None (constructed from Modal variant). /// /// Output: Groups related fields together for passing to render functions. /// /// Details: Reduces individual field extractions and uses, lowering data flow complexity. struct ConfirmReinstallContext { /// Packages that are already installed (shown in confirmation). items: Vec<crate::state::PackageItem>, /// All packages to install (including both installed and not installed). all_items: Vec<crate::state::PackageItem>, /// Header chip metrics. header_chips: PreflightHeaderChips, } /// What: Context struct grouping `ConfirmBatchUpdate` modal fields to reduce data flow complexity. /// /// Inputs: None (constructed from Modal variant). /// /// Output: Groups related fields together for passing to render functions. /// /// Details: Reduces individual field extractions and uses, lowering data flow complexity. struct ConfirmBatchUpdateContext { /// Package items to update. items: Vec<crate::state::PackageItem>, /// Whether this is a dry-run operation. dry_run: bool, } /// What: Context struct grouping `ConfirmAurUpdate` modal fields to reduce data flow complexity. /// /// Inputs: None (constructed from Modal variant). /// /// Output: Groups related fields together for passing to render functions. /// /// Details: Reduces individual field extractions and uses, lowering data flow complexity. struct ConfirmAurUpdateContext { /// Confirmation message text to display to the user. message: String, } /// What: Context struct grouping News modal fields to reduce data flow complexity. /// /// Inputs: None (constructed from Modal variant). /// /// Output: Groups related fields together for passing to render functions. /// /// Details: Reduces individual field extractions and uses, lowering data flow complexity. struct NewsContext { /// News feed items to display. items: Vec<crate::state::types::NewsFeedItem>, /// Currently selected news item index. selected: usize, /// Scroll offset (lines) for the news list. scroll: u16, } /// What: Context struct grouping Announcement modal fields to reduce data flow complexity. /// /// Inputs: None (constructed from Modal variant). /// /// Output: Groups related fields together for passing to render functions. /// /// Details: Reduces individual field extractions and uses, lowering data flow complexity. struct AnnouncementContext { /// Announcement title. title: String, /// Announcement content text. content: String, /// Announcement identifier. id: String, /// Scroll offset in lines. scroll: u16, } /// What: Context struct grouping Updates modal fields to reduce data flow complexity. /// /// Inputs: None (constructed from Modal variant). /// /// Output: Groups related fields together for passing to render functions. /// /// Details: Reduces individual field extractions and uses, lowering data flow complexity. struct UpdatesContext { /// Update entries (package name, current version, new version). entries: Vec<(String, String, String)>, /// Scroll offset in lines. scroll: u16, /// Currently selected entry index. selected: usize, } /// What: Context struct grouping `OptionalDeps` modal fields to reduce data flow complexity. /// /// Inputs: None (constructed from Modal variant). /// /// Output: Groups related fields together for passing to render functions. /// /// Details: Reduces individual field extractions and uses, lowering data flow complexity. struct OptionalDepsContext { /// Optional dependency rows to display. rows: Vec<OptionalDepRow>, /// Currently selected row index. selected: usize, } /// What: Context struct grouping `VirusTotalSetup` modal fields to reduce data flow complexity. /// /// Inputs: None (constructed from Modal variant). /// /// Output: Groups related fields together for passing to render functions. /// /// Details: Reduces individual field extractions and uses, lowering data flow complexity. struct VirusTotalSetupContext { /// API key input buffer. input: String, /// Cursor position within the input buffer. cursor: usize, } /// What: Context struct grouping `NewsSetup` modal fields to reduce data flow complexity. /// /// Inputs: None (constructed from Modal variant). /// /// Output: Groups related fields together for passing to render functions. /// /// Details: Reduces individual field extractions and uses, lowering data flow complexity. #[allow(clippy::struct_excessive_bools)] struct NewsSetupContext { /// Whether to show Arch news. show_arch_news: bool, /// Whether to show security advisories. show_advisories: bool, /// Whether to show AUR updates. show_aur_updates: bool, /// Whether to show AUR comments. show_aur_comments: bool, /// Whether to show official package updates. show_pkg_updates: bool, /// Maximum age of news items in days (7, 30, or 90). max_age_days: Option<u32>, /// Current cursor position (0-4 for toggles, 5-7 for date buttons). cursor: usize, } /// What: Context struct grouping `PasswordPrompt` modal fields to reduce data flow complexity. /// /// Inputs: None (constructed from Modal variant). /// /// Output: Groups related fields together for passing to render functions. /// /// Details: Reduces individual field extractions and uses, lowering data flow complexity. struct PasswordPromptContext { /// Purpose for requesting the password (install/remove/update/etc.). purpose: crate::state::modal::PasswordPurpose, /// Items involved in the operation requiring authentication. items: Vec<crate::state::PackageItem>, /// Current password input buffer. input: String, /// Cursor position within the input buffer. cursor: usize, /// Optional error message to display. error: Option<String>, } /// What: Trait for rendering modal variants and managing their state. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state /// - `area`: Full available area /// - `modal`: The modal variant to render (taken by value) /// /// Output: /// - Returns the modal back (for state reconstruction) /// /// Details: /// - Each implementation handles field extraction, rendering, and state reconstruction. /// - This trait pattern eliminates repetitive match arms in the main render function. trait ModalRenderer { /// What: Render a modal variant to the frame. /// /// Inputs: /// - `f`: Frame to render into. /// - `app`: Application state. /// - `area`: Area to render within. /// /// Output: Returns the next modal state (may be the same or different). /// /// Details: Each modal variant implements this trait to render itself. fn render(self, f: &mut Frame, app: &mut AppState, area: Rect) -> Modal; } impl ModalRenderer for Modal { #[allow(clippy::too_many_lines)] // Modal match with many variants (function has 215 lines) fn render(self, f: &mut Frame, app: &mut AppState, area: Rect) -> Modal { match self { Self::Alert { message } => { let ctx = AlertContext { message }; render_alert_modal(f, app, area, ctx) } Self::Loading { message } => { render_loading_modal(f, area, &message); Self::Loading { message } } Self::ConfirmInstall { items } => { let ctx = ConfirmInstallContext { items }; render_confirm_install_modal(f, app, area, ctx) } Self::Preflight { .. } => { unreachable!("Preflight should be handled separately before trait dispatch") } Self::PreflightExec { items, action, tab, verbose, log_lines, abortable, header_chips, success, } => { let ctx = PreflightExecContext { items, action, tab, verbose, log_lines, abortable, header_chips, success, }; render_preflight_exec_modal(f, app, area, ctx) } Self::PostSummary { success, changed_files, pacnew_count, pacsave_count, services_pending, snapshot_label, } => { let ctx = PostSummaryContext { success, changed_files, pacnew_count, pacsave_count, services_pending, snapshot_label, }; render_post_summary_modal(f, app, area, ctx) } Self::ConfirmRemove { items } => { let ctx = ConfirmRemoveContext { items }; render_confirm_remove_modal(f, app, area, ctx) } Self::ConfirmReinstall { items, all_items, header_chips, } => { let ctx = ConfirmReinstallContext { items, all_items, header_chips, }; render_confirm_reinstall_modal(f, app, area, ctx) } Self::ConfirmBatchUpdate { items, dry_run } => { let ctx = ConfirmBatchUpdateContext { items, dry_run }; render_confirm_batch_update_modal(f, app, area, ctx) } Self::ConfirmAurUpdate { message } => { let ctx = ConfirmAurUpdateContext { message }; render_confirm_aur_update_modal(f, app, area, ctx) } Self::SystemUpdate { do_mirrors, do_pacman, force_sync, do_aur, do_cache, country_idx, countries, mirror_count, cursor, } => { let ctx = SystemUpdateContext { do_mirrors, do_pacman, force_sync, do_aur, do_cache, country_idx, countries, mirror_count, cursor, }; render_system_update_modal(f, app, area, ctx) } Self::Help => render_help_modal(f, app, area), Self::News { items, selected, scroll, } => { let ctx = NewsContext { items, selected, scroll, }; render_news_modal(f, app, area, ctx) } Self::Announcement { title, content, id, scroll, } => { let ctx = AnnouncementContext { title, content, id, scroll, }; render_announcement_modal(f, app, area, ctx) } Self::Updates { entries, scroll, selected, } => { let ctx = UpdatesContext { entries, scroll, selected, }; render_updates_modal(f, app, area, ctx) } Self::OptionalDeps { rows, selected } => { let ctx = OptionalDepsContext { rows, selected }; render_optional_deps_modal(f, area, ctx, app) } Self::ScanConfig { do_clamav, do_trivy, do_semgrep, do_shellcheck, do_virustotal, do_custom, do_sleuth, cursor, } => { let ctx = ScanConfigContext { do_clamav, do_trivy, do_semgrep, do_shellcheck, do_virustotal, do_custom, do_sleuth, cursor, }; render_scan_config_modal(f, area, &ctx) } Self::GnomeTerminalPrompt => render_gnome_terminal_prompt_modal(f, area), Self::VirusTotalSetup { input, cursor } => { let ctx = VirusTotalSetupContext { input, cursor }; render_virustotal_setup_modal(f, app, area, ctx) } Self::ImportHelp => render_import_help_modal(f, app, area), Self::NewsSetup { show_arch_news, show_advisories, show_aur_updates, show_aur_comments, show_pkg_updates, max_age_days, cursor, } => { let ctx = NewsSetupContext { show_arch_news, show_advisories, show_aur_updates, show_aur_comments, show_pkg_updates, max_age_days, cursor, }; render_news_setup_modal(f, app, area, ctx) } Self::PasswordPrompt { purpose, items, input, cursor, error, } => { let ctx = PasswordPromptContext { purpose, items, input, cursor, error, }; render_password_prompt_modal(f, app, area, ctx) } Self::None => Self::None, } } } /// What: Render Alert modal and return reconstructed state. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state /// - `area`: Full available area /// - `ctx`: Context struct containing all Alert fields (taken by value) /// /// Output: /// - Returns the reconstructed Modal /// /// Details: /// - Uses context struct to reduce data flow complexity by grouping related fields. /// - Takes context by value to avoid cloning when reconstructing the Modal. fn render_alert_modal(f: &mut Frame, app: &AppState, area: Rect, ctx: AlertContext) -> Modal { alert::render_alert(f, app, area, &ctx.message); Modal::Alert { message: ctx.message, } } /// What: Render Loading modal. /// /// Inputs: /// - `f`: Frame to render into /// - `area`: Full available area /// - `message`: Loading message to display /// /// Output: None (rendering only) /// /// Details: /// - Shows a simple centered loading indicator. fn render_loading_modal(f: &mut Frame, area: Rect, message: &str) { misc::render_loading(f, area, message); } /// What: Render `ConfirmInstall` modal and return reconstructed state. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state /// - `area`: Full available area /// - `ctx`: Context struct containing all `ConfirmInstall` fields (taken by value) /// /// Output: /// - Returns the reconstructed Modal /// /// Details: /// - Uses context struct to reduce data flow complexity by grouping related fields. /// - Takes context by value to avoid cloning when reconstructing the Modal. fn render_confirm_install_modal( f: &mut Frame, app: &AppState, area: Rect, ctx: ConfirmInstallContext, ) -> Modal { confirm::render_confirm_install(f, app, area, &ctx.items); Modal::ConfirmInstall { items: ctx.items } } /// What: Render `PreflightExec` modal and return reconstructed state. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state /// - `area`: Full available area /// - `ctx`: Context struct containing all `PreflightExec` fields (taken by value) /// /// Output: /// - Returns the reconstructed Modal /// /// Details: /// - Uses context struct to reduce data flow complexity by grouping related fields. /// - Takes context by value to avoid cloning when reconstructing the Modal. fn render_preflight_exec_modal( f: &mut Frame, app: &AppState, area: Rect, ctx: PreflightExecContext, ) -> Modal { preflight_exec::render_preflight_exec( f, app, area, &ctx.items, ctx.action, ctx.tab, ctx.verbose, &ctx.log_lines, ctx.abortable, &ctx.header_chips, ); Modal::PreflightExec { items: ctx.items, action: ctx.action, tab: ctx.tab, verbose: ctx.verbose, log_lines: ctx.log_lines, abortable: ctx.abortable, header_chips: ctx.header_chips, success: ctx.success, } } /// What: Render `PostSummary` modal and return reconstructed state. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state /// - `area`: Full available area /// - `ctx`: Context struct containing all `PostSummary` fields (taken by value) /// /// Output: /// - Returns the reconstructed Modal /// /// Details: /// - Uses context struct to reduce data flow complexity by grouping related fields. /// - Takes context by value to avoid cloning when reconstructing the Modal. fn render_post_summary_modal( f: &mut Frame, app: &AppState, area: Rect, ctx: PostSummaryContext, ) -> Modal { post_summary::render_post_summary( f, app, area, ctx.success, ctx.changed_files, ctx.pacnew_count, ctx.pacsave_count, &ctx.services_pending, ctx.snapshot_label.as_ref(), ); Modal::PostSummary { success: ctx.success, changed_files: ctx.changed_files, pacnew_count: ctx.pacnew_count, pacsave_count: ctx.pacsave_count, services_pending: ctx.services_pending, snapshot_label: ctx.snapshot_label, } } /// What: Render `ConfirmRemove` modal and return reconstructed state. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state /// - `area`: Full available area /// - `ctx`: Context struct containing all `ConfirmRemove` fields (taken by value) /// /// Output: /// - Returns the reconstructed Modal /// /// Details: /// - Uses context struct to reduce data flow complexity by grouping related fields. /// - Takes context by value to avoid cloning when reconstructing the Modal. fn render_confirm_remove_modal( f: &mut Frame, app: &AppState, area: Rect, ctx: ConfirmRemoveContext, ) -> Modal { confirm::render_confirm_remove(f, app, area, &ctx.items); Modal::ConfirmRemove { items: ctx.items } } /// What: Render `SystemUpdate` modal and return reconstructed state. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state /// - `area`: Full available area /// - `ctx`: Context struct containing all `SystemUpdate` fields (taken by value) /// /// Output: /// - Returns the reconstructed Modal /// /// Details: /// - Uses context struct to reduce data flow complexity by grouping related fields. /// - Takes context by value to avoid cloning when reconstructing the Modal. fn render_system_update_modal( f: &mut Frame, app: &AppState, area: Rect, ctx: SystemUpdateContext, ) -> Modal { system_update::render_system_update( f, app, area, ctx.do_mirrors, ctx.do_pacman, ctx.force_sync, ctx.do_aur, ctx.do_cache, ctx.country_idx, &ctx.countries, ctx.mirror_count, ctx.cursor, ); Modal::SystemUpdate { do_mirrors: ctx.do_mirrors, do_pacman: ctx.do_pacman, force_sync: ctx.force_sync, do_aur: ctx.do_aur, do_cache: ctx.do_cache, country_idx: ctx.country_idx, countries: ctx.countries, mirror_count: ctx.mirror_count, cursor: ctx.cursor, } } /// What: Render Help modal and return reconstructed state. fn render_help_modal(f: &mut Frame, app: &mut AppState, area: Rect) -> Modal { help::render_help(f, app, area); Modal::Help } /// What: Render News modal and return reconstructed state. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state /// - `area`: Full available area /// - `ctx`: Context struct containing all News fields (taken by value) /// /// Output: /// - Returns the reconstructed Modal /// /// Details: /// - Uses context struct to reduce data flow complexity by grouping related fields. /// - Takes context by value to avoid cloning when reconstructing the Modal. fn render_news_modal(f: &mut Frame, app: &mut AppState, area: Rect, ctx: NewsContext) -> Modal { news::render_news(f, app, area, &ctx.items, ctx.selected, ctx.scroll); Modal::News { items: ctx.items, selected: ctx.selected, scroll: ctx.scroll, } } /// What: Render Announcement modal and return reconstructed state. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state /// - `area`: Full available area /// - `ctx`: Context struct containing all Announcement fields (taken by value) /// /// Output: /// - Returns the reconstructed Modal /// /// Details: /// - Uses context struct to reduce data flow complexity by grouping related fields. /// - Takes context by value to avoid cloning when reconstructing the Modal. fn render_announcement_modal( f: &mut Frame, app: &mut AppState, area: Rect, ctx: AnnouncementContext, ) -> Modal { announcement::render_announcement(f, app, area, &ctx.title, &ctx.content, ctx.scroll); Modal::Announcement { title: ctx.title, content: ctx.content, id: ctx.id, scroll: ctx.scroll, } } /// What: Render Updates modal and return reconstructed state. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state /// - `area`: Full available area /// - `ctx`: Context struct containing all Updates fields (taken by value) /// /// Output: /// - Returns the reconstructed Modal /// /// Details: /// - Uses context struct to reduce data flow complexity by grouping related fields. /// - Takes context by value to avoid cloning when reconstructing the Modal. fn render_updates_modal( f: &mut Frame, app: &mut AppState, area: Rect, ctx: UpdatesContext, ) -> Modal { updates::render_updates(f, app, area, &ctx.entries, ctx.scroll, ctx.selected); Modal::Updates { entries: ctx.entries, scroll: ctx.scroll, selected: ctx.selected, } } /// What: Render `OptionalDeps` modal and return reconstructed state. /// /// Inputs: /// - `f`: Frame to render into /// - `area`: Full available area /// - `ctx`: Context struct containing all `OptionalDeps` fields (taken by value) /// - `app`: Mutable application state /// /// Output: /// - Returns the reconstructed Modal /// /// Details: /// - Uses context struct to reduce data flow complexity by grouping related fields. /// - Takes context by value to avoid cloning when reconstructing the Modal. fn render_optional_deps_modal( f: &mut Frame, area: Rect, ctx: OptionalDepsContext, app: &AppState, ) -> Modal { misc::render_optional_deps(f, area, &ctx.rows, ctx.selected, app); Modal::OptionalDeps { rows: ctx.rows, selected: ctx.selected, } } /// What: Render `ScanConfig` modal and return reconstructed state. /// /// Inputs: /// - `f`: Frame to render into /// - `area`: Full available area /// - `ctx`: Context struct containing all `ScanConfig` fields (taken by value) /// /// Output: /// - Returns the reconstructed Modal /// /// Details: /// - Uses context struct to reduce data flow complexity by grouping related fields. /// - Takes context by value to avoid cloning when reconstructing the Modal. fn render_scan_config_modal(f: &mut Frame, area: Rect, ctx: &ScanConfigContext) -> Modal { misc::render_scan_config( f, area, ctx.do_clamav, ctx.do_trivy, ctx.do_semgrep, ctx.do_shellcheck, ctx.do_virustotal, ctx.do_custom, ctx.do_sleuth, ctx.cursor, ); Modal::ScanConfig { do_clamav: ctx.do_clamav, do_trivy: ctx.do_trivy, do_semgrep: ctx.do_semgrep, do_shellcheck: ctx.do_shellcheck, do_virustotal: ctx.do_virustotal, do_custom: ctx.do_custom, do_sleuth: ctx.do_sleuth, cursor: ctx.cursor, } } /// What: Render `GnomeTerminalPrompt` modal and return reconstructed state. fn render_gnome_terminal_prompt_modal(f: &mut Frame, area: Rect) -> Modal { misc::render_gnome_terminal_prompt(f, area); Modal::GnomeTerminalPrompt } /// What: Render `VirusTotalSetup` modal and return reconstructed state. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state /// - `area`: Full available area
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
true
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/help.rs
src/ui/modals/help.rs
use ratatui::{ Frame, prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap}, }; use crate::i18n; use crate::state::AppState; use crate::theme::{KeyChord, theme}; /// What: Parse YAML array lines from i18n strings into help lines. /// /// Inputs: /// - `yaml_text`: YAML array string from i18n /// /// Output: /// - Vector of Lines extracted from YAML format /// /// Details: /// - Handles quoted and unquoted YAML list items, stripping prefixes and quotes. fn parse_yaml_lines(yaml_text: &str) -> Vec<Line<'static>> { let mut result = Vec::new(); for line in yaml_text.lines() { let trimmed = line.trim(); if trimmed.starts_with("- \"") || trimmed.starts_with("- '") { let content = trimmed .strip_prefix("- \"") .or_else(|| trimmed.strip_prefix("- '")) .and_then(|s| s.strip_suffix('"').or_else(|| s.strip_suffix('\''))) .unwrap_or(trimmed); result.push(Line::from(Span::raw(content.to_string()))); } else if trimmed.starts_with("- ") { result.push(Line::from(Span::raw( trimmed.strip_prefix("- ").unwrap_or(trimmed).to_string(), ))); } } result } /// What: Add a section header to the lines vector. /// /// Inputs: /// - `lines`: Mutable reference to lines vector /// - `app`: Application state for i18n /// - `th`: Theme reference /// - `key`: i18n key for section title /// /// Output: /// - Adds empty line and styled section header to lines /// /// Details: /// - Formats section headers with consistent styling. fn add_section_header( lines: &mut Vec<Line<'static>>, app: &AppState, th: &crate::theme::Theme, key: &str, ) { lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t(app, key), Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD), ))); } /// What: Conditionally add a binding line if the key exists. /// /// Inputs: /// - `lines`: Mutable reference to lines vector /// - `app`: Application state for i18n /// - `th`: Theme reference /// - `key_opt`: Optional keybinding /// - `label_key`: i18n key for label /// /// Output: /// - Adds formatted binding line if key exists /// /// Details: /// - Uses fmt closure to format binding consistently. fn add_binding_if_some( lines: &mut Vec<Line<'static>>, app: &AppState, th: &crate::theme::Theme, key_opt: Option<KeyChord>, label_key: &str, ) { if let Some(k) = key_opt { let fmt = |label: &str, chord: KeyChord| -> Line<'static> { Line::from(vec![ Span::styled( format!("{label:18}"), Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD), ), Span::raw(" "), Span::styled( format!("[{}]", chord.label()), Style::default().fg(th.text).add_modifier(Modifier::BOLD), ), ]) }; lines.push(fmt(&i18n::t(app, label_key), k)); } } /// What: Build global keybindings section. /// /// Inputs: /// - `lines`: Mutable reference to lines vector /// - `app`: Application state /// - `th`: Theme reference /// - `km`: Keymap reference /// /// Output: /// - Adds global bindings to lines /// /// Details: /// - Formats all global application keybindings. fn build_global_bindings( lines: &mut Vec<Line<'static>>, app: &AppState, th: &crate::theme::Theme, km: &crate::theme::KeyMap, ) { add_binding_if_some( lines, app, th, km.help_overlay.first().copied(), "app.modals.help.key_labels.help_overlay", ); add_binding_if_some( lines, app, th, km.exit.first().copied(), "app.modals.help.key_labels.exit", ); add_binding_if_some( lines, app, th, km.reload_config.first().copied(), "app.modals.help.key_labels.reload_config", ); add_binding_if_some( lines, app, th, km.pane_next.first().copied(), "app.modals.help.key_labels.next_pane", ); add_binding_if_some( lines, app, th, km.pane_left.first().copied(), "app.modals.help.key_labels.focus_left", ); add_binding_if_some( lines, app, th, km.pane_right.first().copied(), "app.modals.help.key_labels.focus_right", ); add_binding_if_some( lines, app, th, km.show_pkgbuild.first().copied(), "app.modals.help.key_labels.show_pkgbuild", ); add_binding_if_some( lines, app, th, km.comments_toggle.first().copied(), "app.modals.help.key_labels.show_comments", ); add_binding_if_some( lines, app, th, km.change_sort.first().copied(), "app.modals.help.key_labels.change_sorting", ); } /// What: Build search pane keybindings section. /// /// Inputs: /// - `lines`: Mutable reference to lines vector /// - `app`: Application state /// - `th`: Theme reference /// - `km`: Keymap reference /// /// Output: /// - Adds search bindings to lines /// /// Details: /// - Formats search pane navigation and action keybindings. fn build_search_bindings( lines: &mut Vec<Line<'static>>, app: &AppState, th: &crate::theme::Theme, km: &crate::theme::KeyMap, ) { let fmt = |label: &str, chord: KeyChord| -> Line<'static> { Line::from(vec![ Span::styled( format!("{label:18}"), Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD), ), Span::raw(" "), Span::styled( format!("[{}]", chord.label()), Style::default().fg(th.text).add_modifier(Modifier::BOLD), ), ]) }; if let (Some(up), Some(dn)) = (km.search_move_up.first(), km.search_move_down.first()) { lines.push(fmt( &i18n::t(app, "app.modals.help.key_labels.move"), KeyChord { code: up.code, mods: up.mods, }, )); lines.push(fmt( &i18n::t(app, "app.modals.help.key_labels.move"), KeyChord { code: dn.code, mods: dn.mods, }, )); } if let (Some(pu), Some(pd)) = (km.search_page_up.first(), km.search_page_down.first()) { lines.push(fmt( &i18n::t(app, "app.modals.help.key_labels.page"), KeyChord { code: pu.code, mods: pu.mods, }, )); lines.push(fmt( &i18n::t(app, "app.modals.help.key_labels.page"), KeyChord { code: pd.code, mods: pd.mods, }, )); } add_binding_if_some( lines, app, th, km.search_add.first().copied(), "app.modals.help.key_labels.add", ); add_binding_if_some( lines, app, th, km.search_install.first().copied(), "app.modals.help.key_labels.install", ); add_binding_if_some( lines, app, th, km.search_backspace.first().copied(), "app.modals.help.key_labels.delete", ); add_binding_if_some( lines, app, th, km.search_insert_clear.first().copied(), "app.modals.help.key_labels.clear_input", ); add_binding_if_some( lines, app, th, km.toggle_fuzzy.first().copied(), "app.modals.help.key_labels.toggle_fuzzy", ); } /// What: Build search normal mode keybindings section. /// /// Inputs: /// - `lines`: Mutable reference to lines vector /// - `app`: Application state /// - `th`: Theme reference /// - `km`: Keymap reference /// /// Output: /// - Adds search normal mode bindings to lines if any exist /// /// Details: /// - Only renders section if at least one normal mode binding is configured. fn build_search_normal_bindings( lines: &mut Vec<Line<'static>>, app: &AppState, th: &crate::theme::Theme, km: &crate::theme::KeyMap, ) { let has_normal_bindings = !km.search_normal_toggle.is_empty() || !km.search_normal_insert.is_empty() || !km.search_normal_select_left.is_empty() || !km.search_normal_select_right.is_empty() || !km.search_normal_delete.is_empty() || !km.search_normal_clear.is_empty() || !km.search_normal_open_status.is_empty() || !km.config_menu_toggle.is_empty() || !km.options_menu_toggle.is_empty() || !km.panels_menu_toggle.is_empty(); if !has_normal_bindings { return; } add_section_header(lines, app, th, "app.modals.help.sections.search_normal"); add_binding_if_some( lines, app, th, km.search_normal_toggle.first().copied(), "app.modals.help.key_labels.toggle_normal", ); add_binding_if_some( lines, app, th, km.search_normal_insert.first().copied(), "app.modals.help.key_labels.insert_mode", ); add_binding_if_some( lines, app, th, km.search_normal_select_left.first().copied(), "app.modals.help.key_labels.select_left", ); add_binding_if_some( lines, app, th, km.search_normal_select_right.first().copied(), "app.modals.help.key_labels.select_right", ); add_binding_if_some( lines, app, th, km.search_normal_delete.first().copied(), "app.modals.help.key_labels.delete", ); add_binding_if_some( lines, app, th, km.search_normal_clear.first().copied(), "app.modals.help.key_labels.clear_input", ); add_binding_if_some( lines, app, th, km.search_normal_open_status.first().copied(), "app.modals.help.key_labels.open_arch_status", ); add_binding_if_some( lines, app, th, km.config_menu_toggle.first().copied(), "app.modals.help.key_labels.config_lists_menu", ); add_binding_if_some( lines, app, th, km.options_menu_toggle.first().copied(), "app.modals.help.key_labels.options_menu", ); add_binding_if_some( lines, app, th, km.panels_menu_toggle.first().copied(), "app.modals.help.key_labels.panels_menu", ); } /// What: Build install pane keybindings section. /// /// Inputs: /// - `lines`: Mutable reference to lines vector /// - `app`: Application state /// - `th`: Theme reference /// - `km`: Keymap reference /// /// Output: /// - Adds install bindings to lines /// /// Details: /// - Formats install pane navigation and action keybindings. fn build_install_bindings( lines: &mut Vec<Line<'static>>, app: &AppState, th: &crate::theme::Theme, km: &crate::theme::KeyMap, ) { let fmt = |label: &str, chord: KeyChord| -> Line<'static> { Line::from(vec![ Span::styled( format!("{label:18}"), Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD), ), Span::raw(" "), Span::styled( format!("[{}]", chord.label()), Style::default().fg(th.text).add_modifier(Modifier::BOLD), ), ]) }; if let (Some(up), Some(dn)) = (km.install_move_up.first(), km.install_move_down.first()) { lines.push(fmt( &i18n::t(app, "app.modals.help.key_labels.move"), KeyChord { code: up.code, mods: up.mods, }, )); lines.push(fmt( &i18n::t(app, "app.modals.help.key_labels.move"), KeyChord { code: dn.code, mods: dn.mods, }, )); } add_binding_if_some( lines, app, th, km.install_confirm.first().copied(), "app.modals.help.key_labels.confirm", ); add_binding_if_some( lines, app, th, km.install_remove.first().copied(), "app.modals.help.key_labels.remove", ); add_binding_if_some( lines, app, th, km.install_clear.first().copied(), "app.modals.help.key_labels.clear", ); add_binding_if_some( lines, app, th, km.install_find.first().copied(), "app.modals.help.key_labels.find", ); add_binding_if_some( lines, app, th, km.install_to_search.first().copied(), "app.modals.help.key_labels.to_search", ); } /// What: Build recent pane keybindings section. /// /// Inputs: /// - `lines`: Mutable reference to lines vector /// - `app`: Application state /// - `th`: Theme reference /// - `km`: Keymap reference /// /// Output: /// - Adds recent bindings to lines /// /// Details: /// - Formats recent pane navigation and action keybindings, including explicit Shift+Del. fn build_recent_bindings( lines: &mut Vec<Line<'static>>, app: &AppState, th: &crate::theme::Theme, km: &crate::theme::KeyMap, ) { let fmt = |label: &str, chord: KeyChord| -> Line<'static> { Line::from(vec![ Span::styled( format!("{label:18}"), Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD), ), Span::raw(" "), Span::styled( format!("[{}]", chord.label()), Style::default().fg(th.text).add_modifier(Modifier::BOLD), ), ]) }; if let (Some(up), Some(dn)) = (km.recent_move_up.first(), km.recent_move_down.first()) { lines.push(fmt( &i18n::t(app, "app.modals.help.key_labels.move"), KeyChord { code: up.code, mods: up.mods, }, )); lines.push(fmt( &i18n::t(app, "app.modals.help.key_labels.move"), KeyChord { code: dn.code, mods: dn.mods, }, )); } add_binding_if_some( lines, app, th, km.recent_use.first().copied(), "app.modals.help.key_labels.use", ); add_binding_if_some( lines, app, th, km.recent_add.first().copied(), "app.modals.help.key_labels.add", ); add_binding_if_some( lines, app, th, km.recent_find.first().copied(), "app.modals.help.key_labels.find", ); add_binding_if_some( lines, app, th, km.recent_to_search.first().copied(), "app.modals.help.key_labels.to_search", ); add_binding_if_some( lines, app, th, km.recent_remove.first().copied(), "app.modals.help.key_labels.remove", ); // Explicit: Shift+Del clears Recent (display only) lines.push(fmt( &i18n::t(app, "app.modals.help.key_labels.clear"), KeyChord { code: crossterm::event::KeyCode::Delete, mods: crossterm::event::KeyModifiers::SHIFT, }, )); } /// What: Render the interactive help overlay summarizing keybindings and mouse tips. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state (keymap, help scroll, rect tracking) /// - `area`: Full screen area used to center the help modal /// /// Output: /// - Draws the help dialog, updates `app.help_rect`, and respects stored scroll offset. /// /// Details: /// - Formats bindings per pane, includes normal-mode guidance, and records clickable bounds to /// enable mouse scrolling while using the current theme colors. #[allow(clippy::many_single_char_names)] pub fn render_help(f: &mut Frame, app: &mut AppState, area: Rect) { let th = theme(); // Full-screen translucent help overlay let w = area.width.saturating_sub(6).min(96); let h = area.height.saturating_sub(4).min(28); let x = area.x + (area.width.saturating_sub(w)) / 2; let y = area.y + (area.height.saturating_sub(h)) / 2; let rect = ratatui::prelude::Rect { x, y, width: w, height: h, }; f.render_widget(Clear, rect); // Record inner content rect (exclude borders) for mouse hit-testing app.help_rect = Some(( rect.x + 1, rect.y + 1, rect.width.saturating_sub(2), rect.height.saturating_sub(2), )); let km = &app.keymap; let mut lines: Vec<Line<'static>> = Vec::new(); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.help.heading"), Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), ))); lines.push(Line::from("")); // Build all sections using helper functions build_global_bindings(&mut lines, app, &th, km); lines.push(Line::from("")); add_section_header(&mut lines, app, &th, "app.modals.help.sections.search"); build_search_bindings(&mut lines, app, &th, km); build_search_normal_bindings(&mut lines, app, &th, km); add_section_header(&mut lines, app, &th, "app.modals.help.sections.install"); build_install_bindings(&mut lines, app, &th, km); add_section_header(&mut lines, app, &th, "app.modals.help.sections.recent"); build_recent_bindings(&mut lines, app, &th, km); // Mouse and UI controls add_section_header(&mut lines, app, &th, "app.modals.help.sections.mouse"); lines.extend(parse_yaml_lines(&i18n::t( app, "app.modals.help.mouse_lines", ))); // Dialogs add_section_header( &mut lines, app, &th, "app.modals.help.sections.system_update_dialog", ); lines.extend(parse_yaml_lines(&i18n::t( app, "app.modals.help.system_update_lines", ))); add_section_header(&mut lines, app, &th, "app.modals.help.sections.news_dialog"); lines.extend(parse_yaml_lines(&i18n::t( app, "app.modals.help.news_lines", ))); lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.help.close_hint"), Style::default().fg(th.subtext1), ))); let help_title = format!(" {} ", i18n::t(app, "app.titles.help")); let boxw = Paragraph::new(lines) .style(Style::default().fg(th.text).bg(th.mantle)) .wrap(Wrap { trim: true }) .scroll((app.help_scroll, 0)) .block( Block::default() .title(Span::styled( &help_title, Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), )) .borders(Borders::ALL) .border_type(BorderType::Double) .border_style(Style::default().fg(th.mauve)) .style(Style::default().bg(th.mantle)), ); f.render_widget(boxw, rect); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight_exec.rs
src/ui/modals/preflight_exec.rs
use ratatui::{ Frame, prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap}, }; use crate::state::modal::PreflightHeaderChips; use crate::state::{PackageItem, PreflightAction, PreflightTab}; use crate::theme::theme; use crate::ui::helpers::{format_bytes, format_signed_bytes}; /// What: Calculate modal layout dimensions and split into sidebar and log columns. /// /// Inputs: /// - `area`: Full screen area used to center the modal /// - `f`: Frame to render into (for clearing the modal area) /// /// Output: /// - Returns tuple of (`modal_rect`, `inner_rect`, `column_rects`) where `column_rects[0]` is sidebar and `column_rects[1]` is log panel. /// /// Details: /// - Centers modal with max width of 110, calculates inner area with 1px border, and splits into 30%/70% columns. #[allow(clippy::many_single_char_names)] fn calculate_modal_layout(area: Rect, f: &mut Frame) -> (Rect, Rect, Vec<Rect>) { let w = area.width.saturating_sub(4).min(110); let h = area.height.saturating_sub(4).min(area.height); let x = area.x + (area.width.saturating_sub(w)) / 2; let y = area.y + (area.height.saturating_sub(h)) / 2; let rect = Rect { x, y, width: w, height: h, }; f.render_widget(Clear, rect); let inner = Rect { x: rect.x + 1, y: rect.y + 1, width: rect.width.saturating_sub(2), height: rect.height.saturating_sub(2), }; let cols = ratatui::layout::Layout::default() .direction(ratatui::layout::Direction::Horizontal) .constraints([ ratatui::layout::Constraint::Percentage(30), ratatui::layout::Constraint::Percentage(70), ]) .split(inner); (rect, inner, cols.to_vec()) } /// What: Render tab header line showing available tabs with current tab highlighted. /// /// Inputs: /// - `tab`: Currently focused sidebar tab /// /// Output: /// - Returns a styled `Line` containing tab labels with the active tab in brackets. /// /// Details: /// - Displays all tabs (Summary, Deps, Files, Services, Sandbox) with the active tab wrapped in brackets. fn render_tab_header(tab: PreflightTab) -> Line<'static> { let th = theme(); let tab_labels = ["Summary", "Deps", "Files", "Services", "Sandbox"]; let mut header = String::new(); for (i, lbl) in tab_labels.iter().enumerate() { let is_active = matches!( (i, tab), (0, PreflightTab::Summary) | (1, PreflightTab::Deps) | (2, PreflightTab::Files) | (3, PreflightTab::Services) | (4, PreflightTab::Sandbox) ); if i > 0 { header.push_str(" "); } if is_active { header.push('['); header.push_str(lbl); header.push(']'); } else { header.push_str(lbl); } } Line::from(Span::styled( header, Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD), )) } /// What: Format log panel footer with current state indicators. /// /// Inputs: /// - `verbose`: Whether verbose logging is enabled /// - `abortable`: Whether abort is currently available /// /// Output: /// - Returns a formatted string describing current controls and their states. /// /// Details: /// - Shows verbose toggle state and abort availability status. #[allow(dead_code)] // Temporarily unused while debugging scroll fn format_log_footer(verbose: bool, abortable: bool) -> String { format!( "l: verbose={} • x: abort{} • q/Esc/Enter: close", if verbose { "ON" } else { "OFF" }, if abortable { " (available)" } else { "" } ) } /// What: Render sidebar widget showing plan summary with header chips, tab header, and package list. /// /// Inputs: /// - `items`: Packages involved in the action /// - `tab`: Currently focused sidebar tab /// - `header_chips`: Header chip metrics to display /// - `border_color`: Color for sidebar border /// - `bg_color`: Background color for sidebar /// /// Output: /// - Returns a `Paragraph` widget ready to render. /// /// Details: /// - Displays header chips, tab navigation, and up to 10 package names in a bordered block. fn render_sidebar( items: &[PackageItem], tab: PreflightTab, header_chips: &PreflightHeaderChips, border_color: ratatui::style::Color, bg_color: ratatui::style::Color, ) -> Paragraph<'static> { let th = theme(); let mut s_lines = vec![ render_header_chips(header_chips), Line::from(""), Line::from(Span::styled( "─────────────────────────", Style::default().fg(th.overlay1), )), Line::from(""), render_tab_header(tab), Line::from(""), ]; // Package list with better formatting if items.is_empty() { s_lines.push(Line::from(Span::styled( "No packages", Style::default().fg(th.subtext1), ))); } else { s_lines.push(Line::from(Span::styled( "Packages:", Style::default() .fg(th.subtext1) .add_modifier(Modifier::BOLD), ))); for p in items.iter().take(10) { let p_name = &p.name; s_lines.push(Line::from(Span::styled( format!(" • {p_name}"), Style::default().fg(th.text), ))); } if items.len() > 10 { let remaining = items.len() - 10; s_lines.push(Line::from(Span::styled( format!(" ... and {remaining} more"), Style::default().fg(th.subtext1), ))); } } Paragraph::new(s_lines) .style(Style::default().fg(th.text).bg(bg_color)) .wrap(Wrap { trim: true }) .block( Block::default() .title(Span::styled( " Plan ", Style::default() .fg(border_color) .add_modifier(Modifier::BOLD), )) .borders(Borders::ALL) .border_style(Style::default().fg(border_color)) .style(Style::default().bg(bg_color)), ) } /// What: Render log panel widget showing execution logs with footer. /// /// Inputs: /// - `log_lines`: Buffered log output /// - `verbose`: Whether verbose logging is enabled /// - `abortable`: Whether abort is currently available /// - `title`: Title for the log panel block /// - `border_color`: Color for log panel border /// - `log_area_height`: Height of the log area in characters (full area including borders) /// /// Output: /// - Returns a `Paragraph` widget ready to render. /// /// Details: /// - Shows placeholder message if no logs, otherwise displays all log lines with auto-scroll to bottom. /// - Calculates scroll offset to always show the most recent output at the bottom. /// - Follows the same pattern as archinstall-rs: calculate visible lines by taking the last N lines. fn render_log_panel( log_lines: &[String], verbose: bool, abortable: bool, title: String, border_color: ratatui::style::Color, log_area_height: u16, ) -> Paragraph<'static> { let th = theme(); // Create block to get inner area (like archinstall-rs does) let block = Block::default() .title(Span::styled( title, Style::default() .fg(border_color) .add_modifier(Modifier::BOLD), )) .borders(Borders::ALL) .border_type(BorderType::Double) .border_style(Style::default().fg(border_color)) .style(Style::default().bg(th.base)); // Get inner height (after borders) // Block with borders uses 2 lines (top + bottom), so inner = outer - 2 let inner_height = log_area_height.saturating_sub(2) as usize; // Reserve space for footer when process is done (abortable=false means finished) let footer_reserve = usize::from(!abortable); let max_log_lines = inner_height.saturating_sub(footer_reserve); // Simple: take last N lines let start = log_lines.len().saturating_sub(max_log_lines); let mut visible_lines: Vec<Line> = if log_lines.is_empty() { vec![Line::from(Span::styled( format!("Waiting for output... [v={verbose}]"), Style::default().fg(th.subtext1), ))] } else { log_lines[start..] .iter() .map(|l| Line::from(Span::styled(l.clone(), Style::default().fg(th.text)))) .collect() }; // Add footer when process is done if !abortable && !log_lines.is_empty() { visible_lines.push(Line::from(Span::styled( "[Press q/Esc/Enter to close]", Style::default().fg(th.subtext0), ))); } Paragraph::new(visible_lines) .style(Style::default().fg(th.text).bg(th.base)) .block(block) } /// What: Render header chips as a compact horizontal line of metrics. /// /// Inputs: /// - `chips`: Header chip data containing counts and sizes. /// /// Output: /// - Returns a `Line` containing styled chip spans separated by spaces. fn render_header_chips(chips: &PreflightHeaderChips) -> Line<'static> { let th = theme(); let mut spans = Vec::new(); // Package count chip let package_count = chips.package_count; let aur_count = chips.aur_count; let pkg_text = if aur_count > 0 { format!("{package_count} ({aur_count} AUR)") } else { format!("{package_count}") }; spans.push(Span::styled( format!("Packages: {pkg_text}"), Style::default() .fg(th.sapphire) .add_modifier(Modifier::BOLD), )); // Download size chip (always shown) spans.push(Span::styled(" • ", Style::default().fg(th.overlay1))); spans.push(Span::styled( format!("DL: {}", format_bytes(chips.download_bytes)), Style::default().fg(th.sapphire), )); // Install delta chip (always shown) spans.push(Span::styled(" • ", Style::default().fg(th.overlay1))); let delta_color = match chips.install_delta_bytes.cmp(&0) { std::cmp::Ordering::Greater => th.green, std::cmp::Ordering::Less => th.red, std::cmp::Ordering::Equal => th.overlay1, // Neutral color for zero }; spans.push(Span::styled( format!("Size: {}", format_signed_bytes(chips.install_delta_bytes)), Style::default().fg(delta_color), )); // Risk score chip (always shown) spans.push(Span::styled(" • ", Style::default().fg(th.overlay1))); let risk_label = match chips.risk_level { crate::state::modal::RiskLevel::Low => "Low", crate::state::modal::RiskLevel::Medium => "Medium", crate::state::modal::RiskLevel::High => "High", }; let risk_color = match chips.risk_level { crate::state::modal::RiskLevel::Low => th.green, crate::state::modal::RiskLevel::Medium => th.yellow, crate::state::modal::RiskLevel::High => th.red, }; spans.push(Span::styled( format!("Risk: {} ({})", risk_label, chips.risk_score), Style::default().fg(risk_color).add_modifier(Modifier::BOLD), )); Line::from(spans) } #[allow(clippy::too_many_arguments)] /// What: Render the preflight execution modal showing plan summary and live logs. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state /// - `area`: Full screen area used to center the modal /// - `items`: Packages involved in the action /// - `action`: Install or remove action being executed /// - `tab`: Currently focused sidebar tab /// - `verbose`: Whether verbose logging is enabled /// - `log_lines`: Buffered log output /// - `abortable`: Whether abort is currently available /// - `header_chips`: Header chip metrics to display in sidebar /// /// Output: /// - Draws sidebar summary plus log panel, reflecting controls for verbosity and aborting. /// /// Details: /// - Splits the modal into sidebar/log columns, caps displayed log lines to viewport, and appends /// footer instructions with dynamic state indicators. pub fn render_preflight_exec( f: &mut Frame, app: &crate::state::AppState, area: Rect, items: &[PackageItem], action: PreflightAction, tab: PreflightTab, verbose: bool, log_lines: &[String], abortable: bool, header_chips: &PreflightHeaderChips, ) { let th = theme(); let (_rect, _inner, cols) = calculate_modal_layout(area, f); let border_color = th.lavender; let bg_color = th.crust; let title = match action { PreflightAction::Install => crate::i18n::t(app, "app.modals.preflight_exec.title_install"), PreflightAction::Remove => crate::i18n::t(app, "app.modals.preflight_exec.title_remove"), PreflightAction::Downgrade => { crate::i18n::t(app, "app.modals.preflight_exec.title_downgrade") } }; let sidebar = render_sidebar(items, tab, header_chips, border_color, bg_color); f.render_widget(sidebar, cols[0]); let log_panel = render_log_panel( log_lines, verbose, abortable, title, border_color, cols[1].height, ); f.render_widget(log_panel, cols[1]); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/mod.rs
src/ui/modals/mod.rs
use ratatui::{Frame, prelude::Rect, style::Style, widgets::Block}; use crate::state::AppState; use crate::theme::theme; /// Alert modal rendering. mod alert; /// Announcement modal rendering. mod announcement; /// Common utilities for modal rendering. mod common; /// Confirmation modal rendering. mod confirm; /// Help overlay modal rendering. mod help; /// Miscellaneous modal rendering utilities. mod misc; /// News modal rendering. mod news; /// Password prompt modal rendering. mod password; /// Post-summary modal rendering. mod post_summary; /// Preflight modal rendering. mod preflight; /// Preflight execution modal rendering. mod preflight_exec; /// Modal renderer utilities. mod renderer; /// System update modal rendering. mod system_update; /// Updates modal rendering. mod updates; /// What: Render modal overlays (`Alert`, `ConfirmInstall`, `ConfirmRemove`, `SystemUpdate`, `Help`, `News`). /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state (modal state, rects) /// - `area`: Full available area; modals are centered within it /// /// Output: /// - Draws the active modal overlay and updates any modal-specific rects for hit-testing. /// /// Details: /// - Clears the area behind the modal; draws a styled centered box; content varies by modal. /// - Help dynamically reflects keymap; News draws a selectable list and records list rect. /// - Uses trait-based rendering to reduce cognitive complexity. pub fn render_modals(f: &mut Frame, app: &mut AppState, area: Rect) { let th = theme(); // Draw a full-screen scrim behind any active modal to avoid underlying text bleed/concatenation if !matches!(app.modal, crate::state::Modal::None) { let scrim = Block::default().style(Style::default().bg(th.mantle)); f.render_widget(scrim, area); } // Extract modal to avoid borrow conflicts let modal = std::mem::replace(&mut app.modal, crate::state::Modal::None); // Use trait-based renderer to handle all modal variants app.modal = renderer::render_modal(modal, f, app, area); } #[cfg(test)] mod tests { /// What: Render each modal variant to ensure layout rects and state assignments succeed without panic. /// /// Inputs: /// - Iterates through Alert, `ConfirmInstall`, `ConfirmRemove` (core item), Help, and News variants. /// /// Output: /// - Rendering completes without error, with Help and News variants setting their associated rectangles. /// /// Details: /// - Uses a `TestBackend` terminal to capture layout side effects while mutating `app.modal` as each branch runs. #[test] fn modals_set_rects_and_render_variants() { use ratatui::{Terminal, backend::TestBackend}; let backend = TestBackend::new(100, 28); let mut term = Terminal::new(backend).expect("Failed to create terminal for test"); // Alert let mut app = crate::state::AppState { modal: crate::state::Modal::Alert { message: "Test".into(), }, ..Default::default() }; term.draw(|f| { let area = f.area(); super::render_modals(f, &mut app, area); }) .expect("Failed to render Alert modal"); // ConfirmInstall app.modal = crate::state::Modal::ConfirmInstall { items: vec![] }; term.draw(|f| { let area = f.area(); super::render_modals(f, &mut app, area); }) .expect("Failed to render ConfirmInstall modal"); // ConfirmRemove with core warn app.modal = crate::state::Modal::ConfirmRemove { items: vec![crate::state::PackageItem { name: "glibc".into(), version: "1".into(), description: String::new(), source: crate::state::Source::Official { repo: "core".into(), arch: "x86_64".into(), }, popularity: None, out_of_date: None, orphaned: false, }], }; term.draw(|f| { let area = f.area(); super::render_modals(f, &mut app, area); }) .expect("Failed to render ConfirmRemove modal"); // Help app.modal = crate::state::Modal::Help; term.draw(|f| { let area = f.area(); super::render_modals(f, &mut app, area); }) .expect("Failed to render Help modal"); assert!(app.help_rect.is_some()); // News app.modal = crate::state::Modal::News { items: vec![crate::state::types::NewsFeedItem { id: "test".to_string(), date: "2025-10-11".into(), title: "Test".into(), summary: None, url: Some(String::new()), source: crate::state::types::NewsFeedSource::ArchNews, severity: None, packages: Vec::new(), }], selected: 0, scroll: 0, }; term.draw(|f| { let area = f.area(); super::render_modals(f, &mut app, area); }) .expect("Failed to render News modal"); assert!(app.news_rect.is_some()); assert!(app.news_list_rect.is_some()); } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/announcement.rs
src/ui/modals/announcement.rs
use ratatui::{ Frame, prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap}, }; use unicode_width::UnicodeWidthStr; use crate::i18n; use crate::state::AppState; use crate::theme::theme; /// Minimum width for announcement modal. const MODAL_MIN_WIDTH: u16 = 40; /// Maximum width ratio for announcement modal. const MODAL_MAX_WIDTH_RATIO: u16 = 3; /// Maximum width divisor for announcement modal. const MODAL_MAX_WIDTH_DIVISOR: u16 = 4; /// Minimum height for announcement modal. const MODAL_MIN_HEIGHT: u16 = 6; /// Maximum height for announcement modal. const MODAL_MAX_HEIGHT: u16 = 25; /// Height padding for announcement modal. const MODAL_HEIGHT_PADDING: u16 = 4; /// Border width for announcement modal. const BORDER_WIDTH: u16 = 2; /// Number of header lines. const HEADER_LINES: u16 = 2; /// Number of footer lines. const FOOTER_LINES: u16 = 1; /// Total header and footer lines. const TOTAL_HEADER_FOOTER_LINES: u16 = HEADER_LINES + FOOTER_LINES; /// Left/right padding for content. const CONTENT_PADDING: u16 = 2; /// Buffer lines between content and footer. const CONTENT_FOOTER_BUFFER: u16 = 2; /// What: Calculate the number of display lines needed for content with wrapping. /// /// Inputs: /// - `content`: Markdown content string /// - `available_width`: Width available for content (inside borders and padding) /// /// Output: /// - Number of display lines the content will take after wrapping /// /// Details: /// - Calculates how many lines each source line will wrap to /// - Accounts for word wrapping at the available width fn calculate_wrapped_lines(content: &str, available_width: u16) -> u16 { if content.trim().is_empty() { return 1; } let width = available_width.max(1) as usize; let mut total_lines: u16 = 0; for line in content.lines() { if line.is_empty() { total_lines = total_lines.saturating_add(1); } else { // Calculate wrapped line count for this source line using display width let line_width = line.width(); #[allow(clippy::cast_possible_truncation)] let wrapped = line_width.div_ceil(width).max(1).min(u16::MAX as usize) as u16; total_lines = total_lines.saturating_add(wrapped); } } total_lines.max(1) } /// What: Calculate the maximum width needed for content lines. /// /// Inputs: /// - `content`: Markdown content string /// - `max_width`: Maximum width to consider /// /// Output: /// - Maximum line width needed (capped at `max_width`) /// /// Details: /// - Finds the longest line in the content /// - Accounts for markdown formatting that might add characters fn calculate_content_width(content: &str, max_width: u16) -> u16 { let mut max_line_len = 0; for line in content.lines() { // Remove markdown formatting for width calculation let cleaned = line .replace("**", "") .replace("## ", "") .replace("### ", "") .replace("# ", ""); // Use display width instead of byte length for multi-byte UTF-8 characters let line_width = cleaned.trim().width(); #[allow(clippy::cast_possible_truncation)] let line_len = line_width.min(u16::MAX as usize) as u16; max_line_len = max_line_len.max(line_len); } max_line_len.min(max_width).max(MODAL_MIN_WIDTH) } /// What: Calculate the modal rectangle dimensions and position centered in the given area. /// /// Inputs: /// - `area`: Full screen area to center the modal within /// - `content`: Content string to size the modal for /// - `app`: Application state for i18n (to get footer text) /// /// Output: /// - `Rect` representing the modal's position and size /// /// Details: /// - Width: Based on max of content width and footer width, with min/max constraints /// - Height: Based on content lines + header + footer, with min/max constraints /// - Modal is centered both horizontally and vertically fn calculate_modal_rect(area: Rect, content: &str, app: &crate::state::AppState) -> Rect { // Calculate max available width first let max_available_width = (area.width * MODAL_MAX_WIDTH_RATIO) / MODAL_MAX_WIDTH_DIVISOR; let content_width = calculate_content_width(content, max_available_width); // Calculate footer text width dynamically using display width let footer_text = crate::i18n::t(app, "app.modals.announcement.footer_hint"); let footer_text_display_width = footer_text.width(); #[allow(clippy::cast_possible_truncation)] let footer_text_width = footer_text_display_width.min(u16::MAX as usize) as u16; let footer_width = footer_text_width + CONTENT_PADDING * 2; // Calculate modal width (max of content width and footer width, with padding + borders) let required_width = content_width.max(footer_width) + CONTENT_PADDING * 2 + BORDER_WIDTH; let modal_width = required_width.min(max_available_width).max(MODAL_MIN_WIDTH); // Calculate content area width (inside borders and padding) let content_area_width = modal_width.saturating_sub(BORDER_WIDTH + CONTENT_PADDING * 2); // Calculate wrapped content lines based on available width let content_lines = calculate_wrapped_lines(content, content_area_width); // Calculate modal height (content + header + footer + buffer + borders) let modal_height = (content_lines + TOTAL_HEADER_FOOTER_LINES + CONTENT_FOOTER_BUFFER + BORDER_WIDTH) .min(area.height.saturating_sub(MODAL_HEIGHT_PADDING)) .min(MODAL_MAX_HEIGHT) .clamp(MODAL_MIN_HEIGHT, MODAL_MAX_HEIGHT); // Center the modal let x = area.x + (area.width.saturating_sub(modal_width)) / 2; let y = area.y + (area.height.saturating_sub(modal_height)) / 2; Rect { x, y, width: modal_width, height: modal_height, } } /// What: Detect URLs in text and return vector of (`start_pos`, `end_pos`, `url_string`). /// /// Inputs: /// - `text`: Text to search for URLs. /// /// Output: /// - Vector of tuples: (`start_byte_pos`, `end_byte_pos`, `url_string`). /// /// Details: /// - Detects http://, https://, and www. URLs. /// - Returns positions in byte offsets for string slicing. fn detect_urls(text: &str) -> Vec<(usize, usize, String)> { let mut urls = Vec::new(); let text_bytes = text.as_bytes(); let mut i = 0; while i < text_bytes.len() { // Look for http:// or https:// let is_http = i + 7 < text_bytes.len() && &text_bytes[i..i + 7] == b"http://"; let is_https = i + 8 < text_bytes.len() && &text_bytes[i..i + 8] == b"https://"; if is_http || is_https { let offset = if is_https { 8 } else { 7 }; if let Some(end) = find_url_end(text, i + offset) { let url = text[i..end].to_string(); urls.push((i, end, url)); i = end; continue; } } // Look for www. (must be at word boundary) if i + 4 < text_bytes.len() && (i == 0 || text_bytes[i - 1].is_ascii_whitespace()) && &text_bytes[i..i + 4] == b"www." && let Some(end) = find_url_end(text, i + 4) { let url = format!("https://{}", &text[i..end]); urls.push((i, end, url)); i = end; continue; } i += 1; } urls } /// What: Find the end position of a URL in text. /// /// Inputs: /// - `text`: Text containing the URL. /// - `start`: Starting byte position of the URL. /// /// Output: /// - `Some(usize)` with end byte position, or `None` if URL is invalid. /// /// Details: /// - URL ends at whitespace, closing parenthesis, or end of string. /// - Removes trailing punctuation that's not part of the URL. fn find_url_end(text: &str, start: usize) -> Option<usize> { let mut end = start; let text_bytes = text.as_bytes(); // Find the end of the URL (stop at whitespace or closing paren) while end < text_bytes.len() { let byte = text_bytes[end]; if byte.is_ascii_whitespace() || byte == b')' || byte == b']' || byte == b'>' { break; } end += 1; } // Remove trailing punctuation that's likely not part of the URL while end > start { let last_char = text_bytes[end - 1]; if matches!(last_char, b'.' | b',' | b';' | b':' | b'!' | b'?') { end -= 1; } else { break; } } if end > start { Some(end) } else { None } } /// What: Parse markdown content into styled lines for display. /// /// Inputs: /// - `content`: Markdown content string /// - `scroll`: Scroll offset in lines /// - `max_lines`: Maximum number of lines to display /// - `url_positions`: Mutable vector to track URL positions for click detection /// - `content_rect`: Rectangle where content is rendered (for position tracking) /// - `start_y`: Starting Y coordinate for content (after header) /// /// Output: /// - Vector of styled lines for rendering /// /// Details: /// What: Parse a header line and return styled line. /// /// Inputs: /// - `trimmed`: Trimmed line text /// /// Output: /// - `Some(Line)` if line is a header, `None` otherwise /// /// Details: /// - Handles #, ##, and ### headers with appropriate styling fn parse_header_line(trimmed: &str) -> Option<Line<'static>> { let th = theme(); if trimmed.starts_with("# ") { let text = trimmed.strip_prefix("# ").unwrap_or(trimmed).to_string(); Some(Line::from(Span::styled( text, Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), ))) } else if trimmed.starts_with("## ") { let text = trimmed.strip_prefix("## ").unwrap_or(trimmed).to_string(); Some(Line::from(Span::styled( text, Style::default().fg(th.mauve), ))) } else if trimmed.starts_with("### ") { let text = trimmed.strip_prefix("### ").unwrap_or(trimmed).to_string(); Some(Line::from(Span::styled( text, Style::default() .fg(th.subtext1) .add_modifier(Modifier::BOLD), ))) } else { None } } /// What: Parse a code block line. /// /// Inputs: /// - `trimmed`: Trimmed line text /// /// Output: /// - `Some(Line)` if line is a code block marker, `None` otherwise /// /// Details: /// - Styles code block markers with subtext0 color fn parse_code_block_line(trimmed: &str) -> Option<Line<'static>> { if trimmed.starts_with("```") { let th = theme(); Some(Line::from(Span::styled( trimmed.to_string(), Style::default().fg(th.subtext0), ))) } else { None } } /// What: Parse text into segments (URLs, bold, plain text). /// /// Inputs: /// - `trimmed`: Trimmed line text /// /// Output: /// - Vector of segments: (`text`, `style`, `is_url`, `url_string`) /// /// Details: /// - Detects URLs and bold markers (**text**) /// - Returns styled segments for rendering fn parse_text_segments(trimmed: &str) -> Vec<(String, Style, bool, Option<String>)> { let th = theme(); let urls = detect_urls(trimmed); let mut segments: Vec<(String, Style, bool, Option<String>)> = Vec::new(); let mut i = 0usize; let trimmed_bytes = trimmed.as_bytes(); while i < trimmed_bytes.len() { // Check if we're at a URL position if let Some((url_start, url_end, url)) = urls.iter().find(|(s, _e, _)| *s == i) { // Add text before URL if *url_start > i { segments.push(( trimmed[i..*url_start].to_string(), Style::default().fg(th.text), false, None, )); } // Add URL segment segments.push(( trimmed[*url_start..*url_end].to_string(), Style::default() .fg(th.mauve) .add_modifier(Modifier::UNDERLINED | Modifier::BOLD), true, Some(url.clone()), )); i = *url_end; continue; } // Check for bold markers if let Some(pos) = trimmed[i..].find("**") { let pos = i + pos; if pos > i { segments.push(( trimmed[i..pos].to_string(), Style::default().fg(th.text), false, None, )); } // Find closing ** if let Some(end_pos) = trimmed[pos + 2..].find("**") { let end_pos = pos + 2 + end_pos; segments.push(( trimmed[pos + 2..end_pos].to_string(), Style::default() .fg(th.lavender) .add_modifier(Modifier::BOLD), false, None, )); i = end_pos + 2; } else { // Unclosed bold, treat rest as bold segments.push(( trimmed[pos + 2..].to_string(), Style::default() .fg(th.lavender) .add_modifier(Modifier::BOLD), false, None, )); break; } continue; } // No more special markers, add remaining text if i < trimmed.len() { segments.push(( trimmed[i..].to_string(), Style::default().fg(th.text), false, None, )); } break; } if segments.is_empty() { segments.push(( trimmed.to_string(), Style::default().fg(th.text), false, None, )); } segments } /// What: Build wrapped lines from text segments with URL position tracking. /// /// Inputs: /// - `segments`: Text segments with styles /// - `content_width`: Available width for wrapping /// - `content_rect`: Content rectangle for URL position calculation /// - `start_y`: Starting Y position /// - `url_positions`: Mutable vector to track URL positions /// /// Output: /// - Tuple of (wrapped lines, final Y position) /// /// Details: /// - Wraps text at word boundaries /// - Tracks URL positions for click detection fn build_wrapped_lines_from_segments( segments: Vec<(String, Style, bool, Option<String>)>, content_width: usize, content_rect: Rect, start_y: u16, url_positions: &mut Vec<(u16, u16, u16, String)>, ) -> (Vec<Line<'static>>, u16) { let mut lines = Vec::new(); let mut current_line_spans: Vec<Span<'static>> = Vec::new(); let mut current_line_width = 0usize; let mut line_y = start_y; for (text, style, is_url, url_string) in segments { let words: Vec<&str> = text.split_whitespace().collect(); for word in words { let word_width = word.width(); let separator_width = usize::from(current_line_width > 0); let test_width = current_line_width + separator_width + word_width; if test_width > content_width && !current_line_spans.is_empty() { // Wrap to new line lines.push(Line::from(current_line_spans.clone())); current_line_spans.clear(); current_line_width = 0; line_y += 1; } // Track URL position if this is a URL if is_url && let Some(ref url) = url_string { let url_x = content_rect.x + u16::try_from(current_line_width + separator_width).unwrap_or(u16::MAX); let url_width = u16::try_from(word_width).unwrap_or(u16::MAX); url_positions.push((url_x, line_y, url_width, url.clone())); } if current_line_width > 0 { current_line_spans.push(Span::raw(" ")); current_line_width += 1; } current_line_spans.push(Span::styled(word.to_string(), style)); current_line_width += word_width; } } if !current_line_spans.is_empty() { lines.push(Line::from(current_line_spans)); } (lines, line_y + 1) } /// What: Parse markdown content into styled lines with wrapping and URL detection. /// /// Inputs: /// - `content`: Markdown content string /// - `scroll`: Scroll offset (lines) /// - `max_lines`: Maximum number of lines to render /// - `url_positions`: Mutable vector to track URL positions for click detection /// - `content_rect`: Content rectangle for width calculation and URL positioning /// - `start_y`: Starting Y position for rendering /// /// Output: /// - Vector of styled lines for rendering /// /// Details: /// - Basic markdown parsing: headers (#), bold (**text**), code blocks (triple backticks) /// - Detects and styles URLs with mauve color, underlined and bold /// - Tracks URL positions for click detection fn parse_markdown( content: &str, scroll: u16, max_lines: usize, url_positions: &mut Vec<(u16, u16, u16, String)>, content_rect: Rect, start_y: u16, ) -> Vec<Line<'static>> { let mut lines = Vec::new(); let content_lines: Vec<&str> = content.lines().collect(); let scroll_usize = scroll as usize; let start_idx = scroll_usize.min(content_lines.len()); // Take up to max_lines starting from start_idx let lines_to_take = max_lines.min(content_lines.len().saturating_sub(start_idx)); let mut current_y = start_y; let content_width = content_rect.width as usize; for line in content_lines.iter().skip(start_idx).take(lines_to_take) { let trimmed = line.trim(); if trimmed.is_empty() { lines.push(Line::from("")); current_y += 1; continue; } // Check for headers if let Some(header_line) = parse_header_line(trimmed) { lines.push(header_line); current_y += 1; continue; } // Check for code blocks if let Some(code_line) = parse_code_block_line(trimmed) { lines.push(code_line); current_y += 1; continue; } // Regular text - handle URLs and bold markers let segments = parse_text_segments(trimmed); let (wrapped_lines, final_y) = build_wrapped_lines_from_segments( segments, content_width, content_rect, current_y, url_positions, ); lines.extend(wrapped_lines); current_y = final_y; } lines } /// What: Build footer line with keybindings hint. /// /// Inputs: /// - `app`: Application state for i18n /// /// Output: /// - `Line<'static>` containing the formatted footer hint /// /// Details: /// - Shows keybindings for marking as read and dismissing fn build_footer(app: &AppState) -> Line<'static> { let th = theme(); let footer_text = i18n::t(app, "app.modals.announcement.footer_hint"); Line::from(Span::styled(footer_text, Style::default().fg(th.overlay1))) } /// What: Render the announcement modal with markdown content. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state (records rect) /// - `area`: Full screen area used to center the modal /// - `title`: Title to display in the modal header /// - `content`: Markdown content to display /// - `scroll`: Scroll offset in lines /// /// Output: /// - Draws the announcement modal and updates rect for hit-testing /// /// Details: /// - Centers modal, renders markdown content with basic formatting pub fn render_announcement( f: &mut Frame, app: &mut AppState, area: Rect, title: &str, content: &str, scroll: u16, ) { let rect = calculate_modal_rect(area, content, app); app.announcement_rect = Some((rect.x, rect.y, rect.width, rect.height)); let th = theme(); // Calculate areas: footer needs 1 line for text, buffer is positional gap above let footer_height = FOOTER_LINES; // Footer text only let footer_total_height = footer_height + CONTENT_FOOTER_BUFFER; // Footer + buffer space let inner_height = rect.height.saturating_sub(BORDER_WIDTH); // Height inside borders (top + bottom) // Content area should fit: header (2 lines) + content + buffer + footer (2 lines) // So content area = inner_height - footer_total_height (header + content share the remaining space) let content_area_height = inner_height.saturating_sub(footer_total_height); // Area for header + content // Content rect (inside borders, for header + content, excluding footer area) // Ensure minimum height for header + at least 1 line of content let min_content_height = HEADER_LINES + 1; let content_rect = Rect { x: rect.x + 1, // Inside left border y: rect.y + 1, // Inside top border width: rect.width.saturating_sub(2), // Account for left + right borders height: content_area_height.max(min_content_height), // At least header + 1 line for content }; // Footer rect at the bottom (inside borders, footer text only) // Position footer after content area + buffer gap, ensuring it's inside the modal let footer_y = rect.y + 1 + content_area_height + CONTENT_FOOTER_BUFFER; // Ensure footer fits within the modal bounds let footer_available_height = inner_height.saturating_sub(content_area_height + CONTENT_FOOTER_BUFFER); let footer_rect = Rect { x: rect.x + 1, // Inside left border y: footer_y.min(rect.y + rect.height.saturating_sub(footer_height + 1)), // Ensure it fits width: rect.width.saturating_sub(2), // Account for left + right borders height: footer_height.min(footer_available_height), }; // Clear URL positions at start of rendering app.announcement_urls.clear(); // Build content lines (header + content, no footer) let mut content_lines = Vec::new(); content_lines.push(Line::from(Span::styled( title.to_string(), Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), ))); content_lines.push(Line::from("")); // Available height for actual content (after header) let available_height = content_area_height.saturating_sub(HEADER_LINES); let max_content_lines = available_height.max(1) as usize; let start_y = content_rect.y + HEADER_LINES; let parsed_content = parse_markdown( content, scroll, max_content_lines, &mut app.announcement_urls, content_rect, start_y, ); content_lines.extend(parsed_content); // Render modal border first f.render_widget(Clear, rect); let block = Block::default() .borders(Borders::ALL) .border_type(BorderType::Rounded) .border_style(Style::default().fg(th.subtext0)); // Render border block (empty content, just borders) let empty_paragraph = Paragraph::new(vec![]).block(block); f.render_widget(empty_paragraph, rect); // Render content area (no borders, borders already drawn) let content_paragraph = Paragraph::new(content_lines).wrap(Wrap { trim: true }); f.render_widget(content_paragraph, content_rect); // Render footer separately at fixed bottom position (always visible) // Buffer space is provided by the positional gap between content_rect and footer_rect let footer_lines = vec![build_footer(app)]; let footer_paragraph = Paragraph::new(footer_lines); f.render_widget(footer_paragraph, footer_rect); } #[cfg(test)] mod tests { use super::*; #[test] /// What: Verify URL detection for https:// URLs. /// /// Inputs: /// - Text containing https:// URLs. /// /// Output: /// - Returns correct URL positions and strings. /// /// Details: /// - Should detect https:// URLs and return byte positions. fn test_detect_urls_https() { let text = "Visit https://example.com for more info"; let urls = detect_urls(text); assert_eq!(urls.len(), 1); assert_eq!(urls[0].0, 6); // start position (after "Visit ") assert_eq!(urls[0].1, 25); // end position (exclusive, after "https://example.com") assert_eq!(urls[0].2, "https://example.com"); } #[test] /// What: Verify URL detection for http:// URLs. /// /// Inputs: /// - Text containing http:// URLs. /// /// Output: /// - Returns correct URL positions and strings. /// /// Details: /// - Should detect http:// URLs and return byte positions. fn test_detect_urls_http() { let text = "Visit http://example.com for more info"; let urls = detect_urls(text); assert_eq!(urls.len(), 1); assert_eq!(urls[0].2, "http://example.com"); } #[test] /// What: Verify URL detection for www. URLs. /// /// Inputs: /// - Text containing www. URLs. /// /// Output: /// - Returns URLs with https:// prefix added. /// /// Details: /// - www. URLs should be converted to https:// URLs. fn test_detect_urls_www() { let text = "Visit www.example.com for more info"; let urls = detect_urls(text); assert_eq!(urls.len(), 1); assert_eq!(urls[0].2, "https://www.example.com"); } #[test] /// What: Verify URL detection with multiple URLs in one line. /// /// Inputs: /// - Text containing multiple URLs. /// /// Output: /// - Returns all detected URLs with correct positions. /// /// Details: /// - Should detect all URLs in the text. fn test_detect_urls_multiple() { let text = "Visit https://example.com and http://test.org for more"; let urls = detect_urls(text); assert_eq!(urls.len(), 2); assert_eq!(urls[0].2, "https://example.com"); assert_eq!(urls[1].2, "http://test.org"); } #[test] /// What: Verify URL detection with trailing punctuation. /// /// Inputs: /// - Text with URLs followed by punctuation. /// /// Output: /// - URLs should exclude trailing punctuation. /// /// Details: /// - Trailing punctuation (., ,, ;, :, !, ?) should be trimmed. fn test_detect_urls_trailing_punctuation() { let text = "Visit https://example.com. Also http://test.org!"; let urls = detect_urls(text); assert_eq!(urls.len(), 2); assert_eq!(urls[0].2, "https://example.com"); assert_eq!(urls[1].2, "http://test.org"); } #[test] /// What: Verify URL detection at end of text. /// /// Inputs: /// - Text ending with a URL (no trailing whitespace). /// /// Output: /// - Should detect URL correctly. /// /// Details: /// - URLs at end of text should be detected without trailing whitespace. fn test_detect_urls_end_of_text() { let text = "Visit https://example.com"; let urls = detect_urls(text); assert_eq!(urls.len(), 1); assert_eq!(urls[0].2, "https://example.com"); } #[test] /// What: Verify URL detection with parentheses termination. /// /// Inputs: /// - Text with URLs inside parentheses. /// /// Output: /// - URLs should stop at closing parenthesis. /// /// Details: /// - Closing parenthesis should terminate URL detection. fn test_detect_urls_parentheses() { let text = "Visit (https://example.com) for more"; let urls = detect_urls(text); assert_eq!(urls.len(), 1); assert_eq!(urls[0].2, "https://example.com"); } #[test] /// What: Verify URL detection with empty text. /// /// Inputs: /// - Empty string. /// /// Output: /// - Returns empty vector. /// /// Details: /// - Empty text should return no URLs. fn test_detect_urls_empty() { let text = ""; let urls = detect_urls(text); assert!(urls.is_empty()); } #[test] /// What: Verify URL detection with no URLs. /// /// Inputs: /// - Text without any URLs. /// /// Output: /// - Returns empty vector. /// /// Details: /// - Text without URLs should return empty vector. fn test_detect_urls_none() { let text = "This is just regular text without any URLs"; let urls = detect_urls(text); assert!(urls.is_empty()); } #[test] /// What: Verify `find_url_end` function behavior. /// /// Inputs: /// - Text with URL and various termination conditions. /// /// Output: /// - Returns correct end position. /// /// Details: /// - Should find end position correctly for different scenarios. fn test_find_url_end() { // URL with space termination - start is after "https://" (position 8) let text = "https://example.com more text"; assert_eq!(find_url_end(text, 8), Some(19)); // "example.com" ends at position 19 // URL with parenthesis termination let text2 = "https://example.com)"; assert_eq!(find_url_end(text2, 8), Some(19)); // "example.com" ends before ')' // URL with trailing punctuation - should trim the trailing period let text3 = "https://example.com."; assert_eq!(find_url_end(text3, 8), Some(19)); // "example.com" (period trimmed) // URL at end of string let text4 = "https://example.com"; assert_eq!(find_url_end(text4, 8), Some(19)); // "example.com" ends at position 19 } #[test] /// What: Verify header parsing for H1 headers. /// /// Inputs: /// - Text starting with "# ". /// /// Output: /// - Returns Some(Line) with styled header. /// /// Details: /// - H1 headers should be parsed and styled correctly. fn test_parse_header_line_h1() { let line = "# Main Title"; let result = parse_header_line(line); assert!(result.is_some()); let line_result = result.expect("should parse H1 header"); assert_eq!(line_result.spans.len(), 1); assert_eq!(line_result.spans[0].content.as_ref(), "Main Title"); } #[test] /// What: Verify header parsing for H2 headers. /// /// Inputs: /// - Text starting with "## ". /// /// Output: /// - Returns Some(Line) with styled header. /// /// Details: /// - H2 headers should be parsed and styled correctly. fn test_parse_header_line_h2() { let line = "## Section Title"; let result = parse_header_line(line); assert!(result.is_some()); let line_result = result.expect("should parse H2 header"); assert_eq!(line_result.spans.len(), 1); assert_eq!(line_result.spans[0].content.as_ref(), "Section Title"); } #[test] /// What: Verify header parsing for H3 headers. /// /// Inputs: /// - Text starting with "### ". /// /// Output: /// - Returns Some(Line) with styled header. /// /// Details: /// - H3 headers should be parsed and styled correctly. fn test_parse_header_line_h3() { let line = "### Subsection Title"; let result = parse_header_line(line); assert!(result.is_some()); let line_result = result.expect("should parse H3 header"); assert_eq!(line_result.spans.len(), 1); assert_eq!(line_result.spans[0].content.as_ref(), "Subsection Title"); } #[test] /// What: Verify header parsing for non-header lines. /// /// Inputs: /// - Text that is not a header. /// /// Output: /// - Returns None. /// /// Details: /// - Non-header lines should return None. fn test_parse_header_line_non_header() { let line = "This is not a header"; let result = parse_header_line(line); assert!(result.is_none()); let line2 = "#Not a header (no space)"; let result2 = parse_header_line(line2); assert!(result2.is_none()); } #[test] /// What: Verify code block parsing. /// /// Inputs: /// - Text starting with triple backticks. /// /// Output: /// - Returns Some(Line) with styled code block marker. /// /// Details: /// - Code block markers should be parsed and styled correctly. fn test_parse_code_block_line() { let line = "```rust";
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
true
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/post_summary.rs
src/ui/modals/post_summary.rs
use ratatui::{ Frame, prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap}, }; use crate::i18n; use crate::state::AppState; use crate::theme::theme; #[allow(clippy::too_many_arguments)] /// What: Render the post-transaction summary modal summarizing results and follow-up actions. /// /// Inputs: /// - `f`: Frame to render into /// - `area`: Full screen area used to center the modal /// - `success`: Whether the transaction succeeded /// - `changed_files`, `pacnew_count`, `pacsave_count`: File change metrics /// - `services_pending`: Services requiring restart /// - `snapshot_label`: Optional snapshot identifier /// /// Output: /// - Draws the summary dialog highlighting status, file counts, and optional services list. /// /// Details: /// - Colors border based on success, truncates service lines to fit, and advertises rollback/service /// restart shortcuts. #[allow(clippy::many_single_char_names)] pub fn render_post_summary( f: &mut Frame, app: &AppState, area: Rect, success: bool, changed_files: usize, pacnew_count: usize, pacsave_count: usize, services_pending: &[String], snapshot_label: Option<&String>, ) { let th = theme(); // Calculate required height based on content // Structure: success/failed + empty + changed_files + snapshot(optional) + empty + services(optional) + empty + footer_hint // Base: success(1) + empty(1) + changed_files(1) + empty(1) + footer_hint(1) = 5 let base_lines = 5u16; let snapshot_lines = u16::from(snapshot_label.is_some()); let services_lines = if services_pending.is_empty() { 0u16 } else { // empty + services label + services (max 4 shown) + potentially "and more" line let service_count = services_pending.len().min(4); u16::try_from(service_count + 2 + usize::from(services_pending.len() > 4)).unwrap_or(7) }; // Total content lines needed (borders take 2 lines, so add 2) let required_height = base_lines + snapshot_lines + services_lines + 2; let h = area .height .saturating_sub(4) .min(required_height.clamp(9, 18)); let w = area.width.saturating_sub(8).min(70); let x = area.x + (area.width.saturating_sub(w)) / 2; let y = area.y + (area.height.saturating_sub(h)) / 2; let rect = ratatui::prelude::Rect { x, y, width: w, height: h, }; f.render_widget(Clear, rect); let border_color = if success { th.green } else { th.red }; let mut lines: Vec<Line<'static>> = Vec::new(); lines.push(Line::from(Span::styled( if success { i18n::t(app, "app.modals.post_summary.success") } else { i18n::t(app, "app.modals.post_summary.failed") }, Style::default() .fg(border_color) .add_modifier(Modifier::BOLD), ))); lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t_fmt( app, "app.modals.post_summary.changed_files", &[ &changed_files.to_string(), &pacnew_count.to_string(), &pacsave_count.to_string(), ], ), Style::default().fg(th.text), ))); if let Some(label) = snapshot_label { lines.push(Line::from(Span::styled( i18n::t_fmt1(app, "app.modals.post_summary.snapshot", label), Style::default().fg(th.text), ))); } if !services_pending.is_empty() { lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.post_summary.services_pending"), Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD), ))); // Show max 4 services to keep dialog compact for s in services_pending.iter().take(4) { lines.push(Line::from(Span::styled( format!(" • {s}"), Style::default().fg(th.text), ))); } if services_pending.len() > 4 { let remaining = services_pending.len() - 4; lines.push(Line::from(Span::styled( format!(" ... and {remaining} more"), Style::default().fg(th.subtext1), ))); } } lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.post_summary.footer_hint"), Style::default() .fg(th.subtext1) .add_modifier(Modifier::BOLD), ))); let boxw = Paragraph::new(lines) .style(Style::default().fg(th.text).bg(th.mantle)) .wrap(Wrap { trim: true }) .block( Block::default() .title(Span::styled( format!(" {} ", i18n::t(app, "app.modals.post_summary.title")), Style::default() .fg(border_color) .add_modifier(Modifier::BOLD), )) .borders(Borders::ALL) .border_type(BorderType::Double) .border_style(Style::default().fg(border_color)) .style(Style::default().bg(th.mantle)), ); f.render_widget(boxw, rect); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/alert.rs
src/ui/modals/alert.rs
use ratatui::{ Frame, prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap}, }; use crate::i18n; use crate::state::AppState; use crate::theme::theme; /// What: Detect the type of alert message based on content. /// /// Inputs: /// - `message`: The alert message text. /// /// Output: /// - Tuple of (`is_help`, `is_config`, `is_clipboard`, `is_account_locked`, `is_config_dirs`). /// /// Details: /// - Checks message content for various patterns to determine alert type. #[must_use] fn detect_message_type(message: &str) -> (bool, bool, bool, bool, bool) { let is_help = message.contains("Help") || message.contains("Tab Help"); let is_config = message.contains("Unknown key") || message.contains("Missing required keys") || message.contains("Missing '='") || message.contains("Missing key before '='") || message.contains("Duplicate key") || message.contains("Invalid color") || message.to_lowercase().contains("theme configuration"); let is_clipboard = { let ml = message.to_lowercase(); ml.contains("clipboard") || ml.contains("wl-copy") || ml.contains("xclip") || ml.contains("wl-clipboard") }; let is_account_locked = message.to_lowercase().contains("account") && (message.to_lowercase().contains("locked") || message.to_lowercase().contains("lockout")); // Detect config directory messages by checking for path patterns // Format: "package: /path/to/dir" - language agnostic detection // The message contains lines with "package: /path" pattern followed by paths let is_config_dirs = { let lines: Vec<&str> = message.lines().collect(); // Check if message has multiple lines with "package: /path" pattern // This pattern is language-agnostic as paths are always in the same format lines.iter().any(|line| { let trimmed = line.trim(); // Pattern: "package_name: /absolute/path" or "package_name: ~/.config/package" // Must have colon followed by whitespace and a path trimmed.find(':').is_some_and(|colon_pos| { let after_colon = &trimmed[colon_pos + 1..].trim(); // Check if after colon there's a path (starts with /, ~, or contains .config/) after_colon.starts_with('/') || after_colon.starts_with("~/") || after_colon.contains("/.config/") || after_colon.contains("\\.config\\") // Windows paths }) }) }; ( is_help, is_config, is_clipboard, is_account_locked, is_config_dirs, ) } /// What: Get header text and box title for alert based on message type. /// /// Inputs: /// - `app`: Application state for i18n. /// - `is_help`, `is_config`, `is_clipboard`, `is_account_locked`, `is_config_dirs`: Message type flags. /// /// Output: /// - Tuple of (`header_text`, `box_title`). /// /// Details: /// - Returns appropriate i18n strings based on message type. #[must_use] // Multiple bools are used here because message types are mutually exclusive flags // that are easier to work with as separate parameters than as an enum with many variants. #[allow(clippy::fn_params_excessive_bools)] fn get_alert_labels( app: &AppState, is_help: bool, is_config: bool, is_clipboard: bool, is_account_locked: bool, is_config_dirs: bool, ) -> (String, String) { let header_text = if is_help { i18n::t(app, "app.modals.help.heading") } else if is_config { i18n::t(app, "app.modals.alert.header_configuration_error") } else if is_clipboard { i18n::t(app, "app.modals.alert.header_clipboard_copy") } else if is_account_locked { i18n::t(app, "app.modals.alert.header_account_locked") } else if is_config_dirs { i18n::t(app, "app.modals.alert.header_config_directories") } else { i18n::t(app, "app.modals.alert.header_connection_issue") }; let box_title = if is_help { format!(" {} ", i18n::t(app, "app.modals.help.title")) } else if is_config { i18n::t(app, "app.modals.alert.title_configuration_error") } else if is_clipboard { i18n::t(app, "app.modals.alert.title_clipboard_copy") } else if is_account_locked { i18n::t(app, "app.modals.alert.title_account_locked") } else if is_config_dirs { i18n::t(app, "app.modals.alert.title_config_directories") } else { i18n::t(app, "app.modals.alert.title_connection_issue") }; (header_text, box_title) } /// What: Format account locked message with command highlighting. /// /// Inputs: /// - `message`: The message text. /// - `th`: Theme for styling. /// /// Output: /// - Vector of formatted lines. /// /// Details: /// - Highlights commands in backticks with mauve color and bold. fn format_account_locked_message(message: &str, th: &crate::theme::Theme) -> Vec<Line<'static>> { let mut lines = Vec::new(); let message_lines: Vec<&str> = message.lines().collect(); for (i, line) in message_lines.iter().enumerate() { if i > 0 { lines.push(Line::from("")); } // Highlight commands in backticks let parts: Vec<&str> = line.split('`').collect(); let mut spans = Vec::new(); for (idx, part) in parts.iter().enumerate() { if idx % 2 == 0 { // Regular text spans.push(Span::styled( (*part).to_string(), Style::default().fg(th.text), )); } else { // Command in backticks - highlight it spans.push(Span::styled( format!("`{part}`"), Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), )); } } lines.push(Line::from(spans)); } lines } /// What: Render the alert modal with contextual styling for help/config/network messages. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state (help scroll used for large help dialogs) /// - `area`: Full screen area used to center the modal /// - `message`: Alert message text to display /// /// Output: /// - Draws a centered alert box and adjusts styling/size based on the message content. /// /// Details: /// - Detects help/configuration/clipboard keywords to pick header titles, resizes large help /// dialogs, and instructs users on dismissal while respecting the current theme. #[allow(clippy::many_single_char_names)] #[allow(clippy::missing_const_for_fn)] pub fn render_alert(f: &mut Frame, app: &AppState, area: Rect, message: &str) { let th = theme(); let (is_help, is_config, is_clipboard, is_account_locked, is_config_dirs) = detect_message_type(message); let w = area .width .saturating_sub(10) .min(if is_help { 90 } else { 80 }); let h = if is_help { area.height.saturating_sub(6).min(28) } else { 7 }; let x = area.x + (area.width.saturating_sub(w)) / 2; let y = area.y + (area.height.saturating_sub(h)) / 2; let rect = ratatui::prelude::Rect { x, y, width: w, height: h, }; f.render_widget(Clear, rect); let (header_text, box_title) = get_alert_labels( app, is_help, is_config, is_clipboard, is_account_locked, is_config_dirs, ); let header_color = if is_help || is_config || is_config_dirs { th.mauve } else { th.red }; // Parse message into lines for help messages let mut lines: Vec<Line<'static>> = Vec::new(); if is_help { for line in message.lines() { lines.push(Line::from(Span::styled( line.to_string(), Style::default().fg(th.text), ))); } } else { // Don't show header text again if it's the same as the title if !is_account_locked { lines.push(Line::from(Span::styled( header_text, Style::default() .fg(header_color) .add_modifier(Modifier::BOLD), ))); lines.push(Line::from("")); } // Format account locked messages more nicely if is_account_locked { lines.extend(format_account_locked_message(message, &th)); } else if is_config_dirs { // Format config directory messages line by line for better readability for line in message.lines() { if line.trim().is_empty() { lines.push(Line::from("")); } else { lines.push(Line::from(Span::styled( line.to_string(), Style::default().fg(th.text), ))); } } } else { lines.push(Line::from(Span::styled( message.to_string(), Style::default().fg(th.text), ))); } } lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.common.close_hint"), Style::default().fg(th.subtext1), ))); let boxw = Paragraph::new(lines) .style(Style::default().fg(th.text).bg(th.mantle)) .wrap(Wrap { trim: true }) .scroll((if is_help { app.help_scroll } else { 0 }, 0)) .block( Block::default() .title(Span::styled( box_title, Style::default() .fg(header_color) .add_modifier(Modifier::BOLD), )) .borders(Borders::ALL) .border_type(BorderType::Double) .border_style(Style::default().fg(header_color)) .style(Style::default().bg(th.mantle)), ); f.render_widget(boxw, rect); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/common.rs
src/ui/modals/common.rs
use ratatui::{ Frame, prelude::Rect, style::{Modifier, Style}, text::Line, widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap}, }; use crate::theme::theme; /// What: Render a centered list modal with a styled title and supplied lines. /// /// Inputs: /// - `f`: Frame to render into /// - `area`: Full screen area used to center the modal /// - `box_title`: Border title to display /// - `lines`: Fully prepared line content /// /// Output: /// - Draws the modal box with the provided lines; does not mutate shared state. /// /// Details: /// - Applies consistent theming (double border, mantle background) and ensures the modal fits by /// clamping width/height within the supplied area. #[allow(clippy::many_single_char_names)] pub fn render_simple_list_modal( f: &mut Frame, area: Rect, box_title: &str, lines: Vec<Line<'static>>, ) { let th = theme(); let w = area.width.saturating_sub(8).min(80); let h = area.height.saturating_sub(8).min(20); let x = area.x + (area.width.saturating_sub(w)) / 2; let y = area.y + (area.height.saturating_sub(h)) / 2; let rect = ratatui::prelude::Rect { x, y, width: w, height: h, }; f.render_widget(Clear, rect); let boxw = Paragraph::new(lines) .style(Style::default().fg(th.text).bg(th.mantle)) .wrap(Wrap { trim: true }) .block( Block::default() .title(ratatui::text::Span::styled( format!(" {box_title} "), Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), )) .borders(Borders::ALL) .border_type(BorderType::Double) .border_style(Style::default().fg(th.mauve)) .style(Style::default().bg(th.mantle)), ); f.render_widget(boxw, rect); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/news.rs
src/ui/modals/news.rs
use ratatui::{ Frame, layout::{Constraint, Direction, Layout}, prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap}, }; use crate::i18n; use crate::state::{AppState, types::NewsFeedItem, types::NewsFeedSource}; use crate::theme::{KeyChord, theme}; /// Width ratio for news modal. const MODAL_WIDTH_RATIO: u16 = 2; /// Width divisor for news modal. const MODAL_WIDTH_DIVISOR: u16 = 3; /// Height padding for news modal. const MODAL_HEIGHT_PADDING: u16 = 8; /// Maximum height for news modal. const MODAL_MAX_HEIGHT: u16 = 20; /// Border width for news modal. const BORDER_WIDTH: u16 = 1; /// Number of header lines. const HEADER_LINES: u16 = 2; /// Height of the keybinds pane at the bottom. const KEYBINDS_PANE_HEIGHT: u16 = 3; /// What: Determine if a news item title indicates a critical announcement. /// /// Inputs: /// - `title`: The news item title to check /// /// Output: /// - `true` if the title contains critical keywords, `false` otherwise /// /// Details: /// - Checks for "critical", "require manual intervention", "requires manual intervention", or "corrupting" /// in the lowercase title text. fn is_critical_news(title: &str) -> bool { let title_lower = title.to_lowercase(); title_lower.contains("critical") || title_lower.contains("require manual intervention") || title_lower.contains("requires manual intervention") || title_lower.contains("corrupting") } /// What: Compute foreground and background colors for a news item based on selection and criticality. /// /// Inputs: /// - `is_selected`: Whether this item is currently selected /// - `is_critical`: Whether this item is marked as critical /// /// Output: /// - Tuple of `(foreground_color, background_color)` from the theme /// /// Details: /// - Critical items use red foreground regardless of selection state. /// - Selected items have a background color applied. fn compute_item_colors( is_selected: bool, is_critical: bool, ) -> (ratatui::style::Color, Option<ratatui::style::Color>) { let th = theme(); let fg = if is_critical { th.red } else { th.text }; let bg = if is_selected { Some(th.surface1) } else { None }; (fg, bg) } /// What: Calculate the modal rectangle dimensions and position centered in the given area. /// /// Inputs: /// - `area`: Full screen area to center the modal within /// /// Output: /// - `Rect` representing the modal's position and size /// /// Details: /// - Modal width is 2/3 of the area width. /// - Modal height is area height minus padding, capped at maximum height. /// - Modal is centered both horizontally and vertically. fn calculate_modal_rect(area: Rect) -> Rect { let w = (area.width * MODAL_WIDTH_RATIO) / MODAL_WIDTH_DIVISOR; let h = area .height .saturating_sub(MODAL_HEIGHT_PADDING) .min(MODAL_MAX_HEIGHT); let x = area.x + (area.width.saturating_sub(w)) / 2; let y = area.y + (area.height.saturating_sub(h)) / 2; Rect { x, y, width: w, height: h, } } /// What: Highlight text with red/green/yellow keywords for AUR comments and Arch News. /// /// Inputs: /// - `text`: The text to highlight /// - `th`: Theme for colors /// /// Output: /// - Vector of styled spans with keyword highlighting /// /// Details: /// - Red for negative keywords (crash, bug, fail, etc.) /// - Green for positive keywords (fix, patch, solve, etc.) /// - Yellow (bold) for default text fn highlight_keywords(text: &str, th: &crate::theme::Theme) -> Vec<Span<'static>> { let normal = Style::default().fg(th.yellow).add_modifier(Modifier::BOLD); let neg = Style::default().fg(th.red).add_modifier(Modifier::BOLD); let pos = Style::default().fg(th.green).add_modifier(Modifier::BOLD); let negative_words = [ "crash", "crashed", "crashes", "critical", "bug", "bugs", "fail", "fails", "failed", "failure", "failures", "issue", "issues", "trouble", "troubles", "panic", "segfault", "broken", "regression", "hang", "freeze", "unstable", "error", "errors", "require manual intervention", "requires manual intervention", "corrupting", ]; let positive_words = [ "fix", "fixed", "fixes", "patch", "patched", "solve", "solved", "solves", "solution", "resolve", "resolved", "resolves", "workaround", ]; let neg_set: std::collections::HashSet<&str> = negative_words.into_iter().collect(); let pos_set: std::collections::HashSet<&str> = positive_words.into_iter().collect(); let mut spans = Vec::new(); for token in text.split_inclusive(' ') { let cleaned = token .trim_matches(|c: char| !c.is_alphanumeric() && c != '-' && c != '_') .to_ascii_lowercase(); let style = if pos_set.contains(cleaned.as_str()) { pos } else if neg_set.contains(cleaned.as_str()) { neg } else { normal }; spans.push(Span::styled(token.to_string(), style)); } spans } /// What: Format a single news feed item into a styled line for display. /// /// Inputs: /// - `item`: The news feed item to format /// - `is_selected`: Whether this item is currently selected /// - `is_read`: Whether this item has been marked as read /// - `is_critical`: Whether this item is critical /// /// Output: /// - `Line<'static>` containing the formatted news item with appropriate styling /// /// Details: /// - Uses read/unread symbols from theme settings. /// - Applies color styling based on selection and criticality. /// - Shows source type indicator with color coding. /// - For AUR comments, shows actual comment text (summary) instead of title. /// - Applies keyword highlighting for AUR comments and Arch News. fn format_news_item( item: &NewsFeedItem, is_selected: bool, is_read: bool, is_critical: bool, ) -> Line<'static> { let th = theme(); let prefs = crate::theme::settings(); let symbol = if is_read { &prefs.news_read_symbol } else { &prefs.news_unread_symbol }; // Get source label and color let (source_label, source_color) = match item.source { NewsFeedSource::ArchNews => ("Arch", th.sapphire), NewsFeedSource::SecurityAdvisory => ("Advisory", th.yellow), NewsFeedSource::InstalledPackageUpdate => ("Update", th.green), NewsFeedSource::AurPackageUpdate => ("AUR Upd", th.mauve), NewsFeedSource::AurComment => ("AUR Cmt", th.yellow), }; // Build the line with source indicator let source_span = Span::styled( format!("[{source_label}] "), Style::default().fg(source_color), ); let symbol_span = Span::raw(format!("{symbol} ")); let date_span = Span::raw(format!("{} ", item.date)); // Determine what text to display and how to style it let (display_text, should_highlight) = match item.source { NewsFeedSource::AurComment => { // For AUR comments, show the actual comment text (summary) instead of title let text = item .summary .as_ref() .map_or_else(|| item.title.as_str(), String::as_str); (text.to_string(), true) } NewsFeedSource::ArchNews => { // For Arch News, show title with keyword highlighting (item.title.clone(), true) } _ => { // For other sources, show title without keyword highlighting (item.title.clone(), false) } }; let (fg, bg) = compute_item_colors(is_selected, is_critical); let base_style = bg.map_or_else( || Style::default().fg(fg), |bg_color| Style::default().fg(fg).bg(bg_color), ); // Build content spans with or without keyword highlighting let mut content_spans = if should_highlight { // Apply keyword highlighting let highlighted = highlight_keywords(&display_text, &th); // Apply base style (selection background) to each span highlighted .into_iter() .map(|mut span| { // Merge styles: preserve keyword color, add selection background if needed if let Some(bg_color) = bg { span.style = span.style.bg(bg_color); } span }) .collect() } else { // No keyword highlighting, just apply base style vec![Span::styled(display_text, base_style)] }; // Combine all spans let mut all_spans = vec![source_span, symbol_span, date_span]; all_spans.append(&mut content_spans); Line::from(all_spans) } /// What: Build the keybinds pane lines for the news modal footer. /// /// Inputs: /// - `app`: Application state containing keymap and i18n context /// /// Output: /// - `Vec<Line<'static>>` containing the formatted keybinds hint /// /// Details: /// - Extracts key labels from keymap, falling back to defaults if unavailable. /// - Replaces placeholders in the i18n template with actual key labels. /// - Returns multiple lines for the keybinds pane. fn build_keybinds_lines(app: &AppState) -> Vec<Line<'static>> { let th = theme(); let mark_read_key = app .keymap .news_mark_read .first() .map_or_else(|| "R".to_string(), KeyChord::label); let mark_all_read_key = app .keymap .news_mark_all_read .first() .map_or_else(|| "Ctrl+R".to_string(), KeyChord::label); let footer_template = i18n::t(app, "app.modals.news.keybinds_hint"); // Replace placeholders one at a time to avoid replacing all {} with the first value let footer_text = footer_template .replacen("{}", &mark_read_key, 1) .replacen("{}", &mark_all_read_key, 1); vec![ Line::from(""), // Empty line for spacing Line::from(Span::styled(footer_text, Style::default().fg(th.subtext1))), ] } /// What: Build all content lines for the news modal including header and items. /// /// Inputs: /// - `app`: Application state for i18n and read status tracking /// - `items`: News entries to display /// - `selected`: Index of the currently highlighted news item /// /// Output: /// - `Vec<Line<'static>>` containing all formatted lines for the modal content /// /// Details: /// - Includes heading, empty line, and news items (or "none" message). /// - Applies critical styling and read markers to items. /// - Footer/keybinds are rendered separately in a bottom pane. fn build_news_lines(app: &AppState, items: &[NewsFeedItem], selected: usize) -> Vec<Line<'static>> { let th = theme(); let mut lines = Vec::new(); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.news.heading"), Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), ))); lines.push(Line::from("")); if items.is_empty() { lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.news.none"), Style::default().fg(th.subtext1), ))); } else { for (i, item) in items.iter().enumerate() { let is_critical = is_critical_news(&item.title); let is_selected = selected == i; // Check read status using id (for NewsFeedItem) or url if available let is_read = app.news_read_ids.contains(&item.id) || item .url .as_ref() .is_some_and(|url| app.news_read_urls.contains(url)); lines.push(format_news_item(item, is_selected, is_read, is_critical)); } } lines } /// What: Calculate the inner list rectangle for mouse hit-testing. /// /// Inputs: /// - `rect`: The outer modal rectangle /// /// Output: /// - Tuple of `(x, y, width, height)` representing the inner list area /// /// Details: /// - Accounts for borders, header lines, and keybinds pane. /// - Used for mouse click detection on news items. #[allow(clippy::missing_const_for_fn)] // Cannot be const due to saturating_sub fn calculate_list_rect(rect: Rect) -> (u16, u16, u16, u16) { let list_inner_x = rect.x + BORDER_WIDTH; let list_inner_y = rect.y + BORDER_WIDTH + HEADER_LINES; let list_inner_w = rect.width.saturating_sub(BORDER_WIDTH * 2); let inner_h = rect.height.saturating_sub(BORDER_WIDTH * 2); // Subtract keybinds pane height from available height let list_rows = inner_h.saturating_sub(HEADER_LINES + KEYBINDS_PANE_HEIGHT); (list_inner_x, list_inner_y, list_inner_w, list_rows) } /// What: Build a styled Paragraph widget for the news modal. /// /// Inputs: /// - `app`: Application state for i18n /// - `lines`: Content lines to display in the paragraph /// /// Output: /// - Configured `Paragraph` widget ready for rendering /// /// Details: /// - Applies theme colors, wrapping, borders, and title styling. fn build_news_paragraph(app: &AppState, lines: Vec<Line<'static>>) -> Paragraph<'static> { let th = theme(); Paragraph::new(lines) .style(Style::default().fg(th.text).bg(th.mantle)) .wrap(Wrap { trim: true }) .block( Block::default() .title(Span::styled( i18n::t(app, "app.modals.news.title"), Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), )) .borders(Borders::TOP | Borders::LEFT | Borders::RIGHT) .border_type(BorderType::Double) .border_style(Style::default().fg(th.mauve)) .style(Style::default().bg(th.mantle)), ) } /// What: Prepare all data needed for rendering the news modal. /// /// Inputs: /// - `app`: Mutable application state (will be updated with rect information) /// - `area`: Full screen area used to center the modal /// - `items`: News feed entries to display /// - `selected`: Index of the currently highlighted news item /// /// Output: /// - Tuple of `(Rect, Vec<Line<'static>>, Rect)` containing the modal rect, content lines, and keybinds rect /// /// Details: /// - Calculates modal dimensions and position. /// - Builds content lines including header and items. /// - Calculates keybinds pane rectangle. /// - Updates app state with rect information for mouse hit-testing. fn prepare_news_modal( app: &mut AppState, area: Rect, items: &[NewsFeedItem], selected: usize, ) -> (Rect, Vec<Line<'static>>, Rect) { let rect = calculate_modal_rect(area); app.news_rect = Some((rect.x, rect.y, rect.width, rect.height)); let (list_x, list_y, list_w, list_h) = calculate_list_rect(rect); app.news_list_rect = Some((list_x, list_y, list_w, list_h)); let lines = build_news_lines(app, items, selected); // Calculate keybinds pane rect (will be adjusted in render function) let keybinds_rect = Rect { x: rect.x + BORDER_WIDTH, y: rect.y + rect.height - KEYBINDS_PANE_HEIGHT - BORDER_WIDTH, width: rect.width.saturating_sub(BORDER_WIDTH * 2), height: KEYBINDS_PANE_HEIGHT, }; (rect, lines, keybinds_rect) } /// What: Render the prepared news modal content and keybinds pane to the frame. /// /// Inputs: /// - `f`: Frame to render into /// - `rect`: Modal rectangle position and dimensions /// - `content_lines`: Content lines to display /// - `keybinds_rect`: Rectangle for the keybinds pane /// - `app`: Application state for i18n (used in paragraph building) /// - `scroll`: Scroll offset (lines) for the news list /// /// Output: /// - Draws the modal widget and keybinds pane to the frame /// /// Details: /// - Clears the area first, then renders the styled paragraph with scroll offset. /// - Renders keybinds pane at the bottom with borders. fn render_news_modal( f: &mut Frame, rect: Rect, content_lines: Vec<Line<'static>>, _keybinds_rect: Rect, app: &AppState, scroll: u16, ) { let th = theme(); f.render_widget(Clear, rect); // Split rect into content and keybinds areas let chunks = Layout::default() .direction(Direction::Vertical) .constraints([ Constraint::Min(1), // Content area Constraint::Length(KEYBINDS_PANE_HEIGHT), // Keybinds pane ]) .split(rect); // Render content area let mut paragraph = build_news_paragraph(app, content_lines); paragraph = paragraph.scroll((scroll, 0)); f.render_widget(paragraph, chunks[0]); // Render keybinds pane let keybinds_lines = build_keybinds_lines(app); let keybinds_widget = Paragraph::new(keybinds_lines) .style(Style::default().fg(th.text).bg(th.mantle)) .wrap(Wrap { trim: true }) .block( Block::default() .borders(Borders::LEFT | Borders::BOTTOM | Borders::RIGHT) .border_type(BorderType::Double) .border_style(Style::default().fg(th.mauve)) .style(Style::default().bg(th.mantle)), ); f.render_widget(keybinds_widget, chunks[1]); } /// What: Render the Arch news modal with selectable entries and read markers. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state (records list rects, read state) /// - `area`: Full screen area used to center the modal /// - `items`: News entries to display /// - `selected`: Index of the currently highlighted news item /// /// Output: /// - Draws the news list, updates overall/list rects, and marks unread items with theme symbols. /// /// Details: /// - Styles critical headlines, honors user-configured read symbols, and surfaces keybindings from /// the keymap in the footer line. /// - Separates data preparation from rendering for reduced complexity. pub fn render_news( f: &mut Frame, app: &mut AppState, area: Rect, items: &[NewsFeedItem], selected: usize, scroll: u16, ) { let (rect, content_lines, keybinds_rect) = prepare_news_modal(app, area, items, selected); render_news_modal(f, rect, content_lines, keybinds_rect, app, scroll); } #[cfg(test)] mod tests { use super::*; use crate::state::types::NewsFeedItem; #[test] fn test_is_critical_news() { assert!(is_critical_news("Critical security update")); assert!(is_critical_news("CRITICAL: Important")); assert!(is_critical_news("Require manual intervention")); assert!(is_critical_news("Requires manual intervention")); assert!(is_critical_news("Corrupting filesystem")); assert!(!is_critical_news("Regular update")); assert!(!is_critical_news("Minor bug fix")); } #[test] fn test_compute_item_colors() { let (fg_normal, bg_normal) = compute_item_colors(false, false); let (fg_critical, _bg_critical) = compute_item_colors(false, true); let (_fg_selected, bg_selected) = compute_item_colors(true, false); let (_fg_selected_critical, bg_selected_critical) = compute_item_colors(true, true); assert_eq!(bg_normal, None); assert!(bg_selected.is_some()); assert!(bg_selected_critical.is_some()); // Critical items should have red foreground assert_ne!(fg_normal, fg_critical); } #[test] fn test_calculate_modal_rect() { let area = Rect { x: 0, y: 0, width: 100, height: 30, }; let rect = calculate_modal_rect(area); // Width should be 2/3 of area width assert_eq!(rect.width, 66); // Should be centered horizontally assert_eq!(rect.x, 17); // Should be centered vertically: (30 - 20) / 2 = 5 assert_eq!(rect.y, 5); // Height should be capped at MODAL_MAX_HEIGHT assert_eq!(rect.height, MODAL_MAX_HEIGHT); } #[test] fn test_format_news_item() { let item = NewsFeedItem { id: "https://example.com".to_string(), date: "2025-01-01".to_string(), title: "Test News".to_string(), summary: None, url: Some("https://example.com".to_string()), source: crate::state::types::NewsFeedSource::ArchNews, severity: None, packages: Vec::new(), }; let line = format_news_item(&item, false, false, false); assert!(!line.spans.is_empty()); let line_critical = format_news_item(&item, false, false, true); assert!(!line_critical.spans.is_empty()); } #[test] fn test_calculate_list_rect() { let rect = Rect { x: 10, y: 5, width: 50, height: 20, }; let (x, y, w, h) = calculate_list_rect(rect); assert_eq!(x, rect.x + BORDER_WIDTH); assert_eq!(y, rect.y + BORDER_WIDTH + HEADER_LINES); assert_eq!(w, rect.width.saturating_sub(BORDER_WIDTH * 2)); assert!(h <= rect.height); } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/updates.rs
src/ui/modals/updates.rs
use ratatui::{ Frame, layout::{Alignment, Constraint, Direction, Layout}, prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, widgets::{Block, BorderType, Borders, Clear, Paragraph}, }; use unicode_width::UnicodeWidthStr; use crate::i18n; use crate::state::AppState; use crate::theme::{Theme, theme}; /// What: Collection of line vectors for the three panes in the updates modal. /// /// Inputs: /// - None (constructed by `build_update_lines`) /// /// Output: /// - Holds left, center, and right pane lines /// /// Details: /// - Used to group related line collections and reduce data flow complexity. struct UpdateLines { /// Left pane lines showing old versions (right-aligned). left: Vec<Line<'static>>, /// Center pane lines showing arrows (centered). center: Vec<Line<'static>>, /// Right pane lines showing new versions (left-aligned). right: Vec<Line<'static>>, } /// What: Calculate the modal rectangle centered within the available area. /// /// Inputs: /// - `area`: Full screen area used to center the modal /// /// Output: /// - Returns a `Rect` representing the modal's position and size /// /// Details: /// - Calculates desired dimensions (half width, constrained height) /// - Clamps dimensions to fit within available area with margins /// - Centers the modal and ensures it fits within bounds fn calculate_modal_rect(area: Rect) -> Rect { // Calculate desired dimensions let desired_w = area.width / 2; let desired_h = (area.height.saturating_sub(8).min(20)) * 2; // Clamp dimensions to fit within available area (with 2px margins on each side) let w = desired_w.min(area.width.saturating_sub(4)).max(20); let h = desired_h.min(area.height.saturating_sub(4)).max(10); // Center the modal within the area let x = area.x + (area.width.saturating_sub(w)) / 2; let y = area.y + (area.height.saturating_sub(h)) / 2; // Final clamp: ensure the entire rect fits within the area let x = x.max(area.x); let y = y.max(area.y); let max_w = (area.x + area.width).saturating_sub(x); let max_h = (area.y + area.height).saturating_sub(y); let w = w.min(max_w); let h = h.min(max_h); Rect { x, y, width: w, height: h, } } /// What: Determine which tool will be used to install/update a package. /// /// Inputs: /// - `pkg_name`: Name of the package /// /// Output: /// - Returns "pacman" for official packages, "AUR" for AUR packages /// /// Details: /// - Checks if package exists in official index first /// - For AUR packages, returns "AUR" regardless of which helper is installed fn get_install_tool(pkg_name: &str) -> &'static str { // Check if it's in official repos if crate::index::find_package_by_name(pkg_name).is_some() { return "pacman"; } // It's an AUR package "AUR" } /// What: Wrap text into lines that fit within the given width. /// /// Inputs: /// - `content`: Text content to wrap /// - `available_width`: Width available for wrapping /// /// Output: /// - Vector of strings, each representing a wrapped line /// /// Details: /// - Uses Unicode display width for accurate measurement /// - Wraps at word boundaries /// - Returns at least one empty line if content is empty fn wrap_text_to_lines(content: &str, available_width: u16) -> Vec<String> { if content.trim().is_empty() { return vec![String::new()]; } let width = available_width.max(1) as usize; let words: Vec<&str> = content.split_whitespace().collect(); if words.is_empty() { return vec![String::new()]; } let mut lines = Vec::new(); let mut current_line = String::new(); let mut current_width = 0usize; for word in words { let word_width = word.width(); let separator_width = usize::from(current_width > 0); let test_width = current_width + separator_width + word_width; if test_width > width && current_width > 0 { // Wrap to new line lines.push(current_line); current_line = word.to_string(); current_width = word_width; } else { if current_width > 0 { current_line.push(' '); } current_line.push_str(word); current_width = test_width; } } if !current_line.is_empty() { lines.push(current_line); } if lines.is_empty() { lines.push(String::new()); } lines } /// What: Build all three line vectors for update entries with proper alignment. /// /// Inputs: /// - `entries`: Update entries to display (`name`, `old_version`, `new_version`) /// - `th`: Theme for styling /// - `selected`: Index of the currently selected entry /// - `left_width`: Width of the left pane in characters /// - `right_width`: Width of the right pane in characters /// /// Output: /// - Returns `UpdateLines` containing left, center, and right pane lines /// /// Details: /// - Pre-calculates wrapping for each entry to ensure all panes have matching line counts /// - Left pane: old versions with right padding (right-aligned) /// - Center pane: arrows with spacing (centered) /// - Right pane: new versions with tool label (left-aligned) /// - Highlights the selected entry with cursor indicator /// - All three panes have the same number of lines per entry for proper alignment fn build_update_lines( entries: &[(String, String, String)], th: &Theme, selected: usize, left_width: u16, right_width: u16, ) -> UpdateLines { let mut left_lines = Vec::new(); let mut center_lines = Vec::new(); let mut right_lines = Vec::new(); let text_style = Style::default().fg(th.text); let cursor_style = Style::default().fg(th.mauve).add_modifier(Modifier::BOLD); let center_style = Style::default().fg(th.mauve).add_modifier(Modifier::BOLD); for (idx, (name, old_version, new_version)) in entries.iter().enumerate() { let is_selected = idx == selected; // Determine which tool will be used for this package let tool = get_install_tool(name); let tool_color = match tool { "pacman" => th.green, "AUR" => th.yellow, _ => th.overlay1, }; // Build left text without cursor/indicator initially let left_text = format!("{name} - {old_version} "); // Build right text without padding initially (we'll add tool label later) let right_text = format!(" {name} - {new_version}"); // Calculate wrapped lines for left and right text let left_wrapped = wrap_text_to_lines(&left_text, left_width); let right_wrapped = wrap_text_to_lines(&right_text, right_width); // Determine maximum lines needed across all panes (center always 1 line) let left_lines_count = left_wrapped.len(); let right_lines_count = right_wrapped.len(); let max_lines = left_lines_count.max(right_lines_count).max(1); // Build left pane lines for (line_idx, line) in left_wrapped.iter().enumerate() { if line_idx == 0 && is_selected { // First line gets cursor indicator let spans = vec![ Span::styled("▶ ", cursor_style), Span::styled(line.clone(), text_style), ]; left_lines.push(Line::from(spans)); } else if line_idx == 0 && !is_selected { // First line gets spacing for alignment left_lines.push(Line::from(Span::styled(format!(" {line}"), text_style))); } else { // Subsequent lines left_lines.push(Line::from(Span::styled(line.clone(), text_style))); } } // Pad left pane with empty lines if needed while left_lines.len() < max_lines { left_lines.push(Line::from(Span::styled("", text_style))); } // Build center pane lines (always 1 line, pad if needed) center_lines.push(Line::from(Span::styled(" → ", center_style))); while center_lines.len() < max_lines { center_lines.push(Line::from(Span::styled("", center_style))); } // Build right pane lines for (line_idx, line) in right_wrapped.iter().enumerate() { let is_last_line = line_idx == right_wrapped.len() - 1; if is_last_line { // Last line gets tool label let spans = vec![ Span::styled(line.clone(), text_style), Span::styled(" ", text_style), Span::styled( format!("[{tool}]"), Style::default().fg(tool_color).add_modifier(Modifier::BOLD), ), ]; right_lines.push(Line::from(spans)); } else { // Other lines right_lines.push(Line::from(Span::styled(line.clone(), text_style))); } } // Pad right pane with empty lines if needed while right_lines.len() < max_lines { right_lines.push(Line::from(Span::styled("", text_style))); } } UpdateLines { left: left_lines, center: center_lines, right: right_lines, } } /// What: Render a scrollable pane with common styling. /// /// Inputs: /// - `f`: Frame to render into /// - `lines`: Lines to render in the pane /// - `chunk`: Rect area for the pane /// - `alignment`: Text alignment (Left, Right, or Center) /// - `scroll`: Scroll offset (lines) for the pane /// - `th`: Theme for styling /// /// Output: /// - Renders the paragraph widget to the frame /// /// Details: /// - Creates a paragraph with common styling (text color, background, scroll) /// - Applies the specified alignment /// - Wrapping is pre-calculated in `build_update_lines()`, so no wrap needed here fn render_pane( f: &mut Frame, lines: Vec<Line<'static>>, chunk: Rect, alignment: Alignment, scroll: u16, th: &Theme, ) { // Render the paragraph with base background let para = Paragraph::new(lines) .style(Style::default().fg(th.text).bg(th.mantle)) .alignment(alignment) .scroll((scroll, 0)); f.render_widget(para, chunk); } /// What: Render the available updates modal with scrollable list. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state (records rects) /// - `area`: Full screen area used to center the modal /// - `entries`: Update entries to display (`name`, `old_version`, `new_version`) /// - `scroll`: Scroll offset (lines) for the updates list /// - `selected`: Index of the currently selected entry /// /// Output: /// - Draws the updates list with scroll support and selection highlighting /// /// Details: /// - Shows update entries with old version on left, arrow in center, new version on right /// - Highlights the selected entry with background color /// - Records rects for mouse interaction and scrolling pub fn render_updates( f: &mut Frame, app: &mut AppState, area: Rect, entries: &[(String, String, String)], scroll: u16, selected: usize, ) { let th = theme(); let rect = calculate_modal_rect(area); f.render_widget(Clear, rect); // Record outer rect for mouse hit-testing app.updates_modal_rect = Some((rect.x, rect.y, rect.width, rect.height)); // Split into header and content areas let inner_rect = Rect { x: rect.x + 1, y: rect.y + 1, width: rect.width.saturating_sub(2), height: rect.height.saturating_sub(2), }; let chunks = Layout::default() .direction(Direction::Vertical) .constraints([ Constraint::Length(2), // Heading + blank line Constraint::Min(1), // Content area ]) .split(inner_rect); // Render heading let heading_line = Line::from(Span::styled( i18n::t(app, "app.modals.updates_window.heading"), Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), )); let heading_para = Paragraph::new(heading_line).style(Style::default().fg(th.text).bg(th.mantle)); f.render_widget(heading_para, chunks[0]); if entries.is_empty() { let none_line = Line::from(Span::styled( i18n::t(app, "app.modals.updates_window.none"), Style::default().fg(th.subtext1), )); let none_para = Paragraph::new(none_line).style(Style::default().fg(th.text).bg(th.mantle)); f.render_widget(none_para, chunks[1]); } else { // Split content area into three sections: left pane, center arrow, right pane let pane_chunks = Layout::default() .direction(Direction::Horizontal) .constraints([ Constraint::Percentage(48), // Left pane (old versions) Constraint::Length(11), // Center arrow with spacing (5 spaces + arrow + 5 spaces = 11 chars) Constraint::Percentage(48), // Right pane (new versions) ]) .split(chunks[1]); // Calculate pane widths for wrapping calculations let left_width = pane_chunks[0].width; let right_width = pane_chunks[2].width; let update_lines = build_update_lines(entries, &th, selected, left_width, right_width); // Render panes using helper function render_pane( f, update_lines.left, pane_chunks[0], Alignment::Right, scroll, &th, ); render_pane( f, update_lines.center, pane_chunks[1], Alignment::Center, scroll, &th, ); render_pane( f, update_lines.right, pane_chunks[2], Alignment::Left, scroll, &th, ); } // Render modal border let border_block = Block::default() .title(Span::styled( i18n::t(app, "app.modals.updates_window.title"), Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), )) .borders(Borders::ALL) .border_type(BorderType::Double) .border_style(Style::default().fg(th.mauve)) .style(Style::default().bg(th.mantle)); f.render_widget(border_block, rect); // Record inner content rect for scroll handling (reuse inner_rect) app.updates_modal_content_rect = Some(( inner_rect.x, inner_rect.y, inner_rect.width, inner_rect.height, )); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/confirm.rs
src/ui/modals/confirm.rs
use ratatui::{ Frame, prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap}, }; use crate::i18n; use crate::state::{AppState, PackageItem}; use crate::theme::theme; /// What: Render the confirmation modal listing packages slated for installation. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: `AppState` for translations /// - `area`: Full screen area used to center the modal /// - `items`: Packages selected for installation /// /// Output: /// - Draws the install confirmation dialog and informs users about scan shortcuts. /// /// Details: /// - Highlights the heading, truncates the list to fit the modal, and shows instructions for /// confirming, cancelling, or initiating security scans. #[allow(clippy::many_single_char_names)] pub fn render_confirm_install(f: &mut Frame, app: &AppState, area: Rect, items: &[PackageItem]) { let th = theme(); let w = area.width.saturating_sub(6).min(90); let h = area.height.saturating_sub(6).min(20); let x = area.x + (area.width.saturating_sub(w)) / 2; let y = area.y + (area.height.saturating_sub(h)) / 2; let rect = ratatui::prelude::Rect { x, y, width: w, height: h, }; f.render_widget(Clear, rect); let mut lines: Vec<Line<'static>> = Vec::new(); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.confirm_install.heading"), Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), ))); lines.push(Line::from("")); if items.is_empty() { lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.confirm_install.none"), Style::default().fg(th.subtext1), ))); } else { for p in items.iter().take((h as usize).saturating_sub(6)) { let p_name = &p.name; lines.push(Line::from(Span::styled( format!("- {p_name}"), Style::default().fg(th.text), ))); } if items.len() + 6 > h as usize { lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.confirm_install.list_ellipsis"), Style::default().fg(th.subtext1), ))); } } lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.confirm_install.confirm_hint"), Style::default().fg(th.subtext1), ))); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.confirm_install.scan_hint"), Style::default().fg(th.overlay1), ))); let boxw = Paragraph::new(lines) .style(Style::default().fg(th.text).bg(th.mantle)) .wrap(Wrap { trim: true }) .block( Block::default() .title(Span::styled( i18n::t(app, "app.modals.confirm_install.title"), Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), )) .borders(Borders::ALL) .border_type(BorderType::Double) .border_style(Style::default().fg(th.mauve)) .style(Style::default().bg(th.mantle)), ); f.render_widget(boxw, rect); } /// What: Render the confirmation modal enumerating packages selected for removal. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: `AppState` for translations /// - `area`: Full screen area used to center the modal /// - `items`: Packages scheduled for removal /// /// Output: /// - Draws the removal confirmation dialog, including warnings for core packages. /// /// Details: /// - Emphasizes critical warnings when core packages are present, truncates long lists, and /// instructs on confirm/cancel actions while matching the theme. #[allow(clippy::many_single_char_names)] pub fn render_confirm_remove(f: &mut Frame, app: &AppState, area: Rect, items: &[PackageItem]) { let th = theme(); let w = area.width.saturating_sub(6).min(90); let h = area.height.saturating_sub(6).min(20); let x = area.x + (area.width.saturating_sub(w)) / 2; let y = area.y + (area.height.saturating_sub(h)) / 2; let rect = ratatui::prelude::Rect { x, y, width: w, height: h, }; f.render_widget(Clear, rect); let mut lines: Vec<Line<'static>> = Vec::new(); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.confirm_remove.heading"), Style::default().fg(th.red).add_modifier(Modifier::BOLD), ))); lines.push(Line::from("")); // Warn explicitly if any core packages are present let has_core = items.iter().any(|p| match &p.source { crate::state::Source::Official { repo, .. } => repo.eq_ignore_ascii_case("core"), crate::state::Source::Aur => false, }); if has_core { lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.confirm_remove.warning_core"), Style::default().fg(th.red).add_modifier(Modifier::BOLD), ))); lines.push(Line::from("")); } if items.is_empty() { lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.confirm_remove.none"), Style::default().fg(th.subtext1), ))); } else { for p in items.iter().take((h as usize).saturating_sub(6)) { let p_name = &p.name; lines.push(Line::from(Span::styled( format!("- {p_name}"), Style::default().fg(th.text), ))); } if items.len() + 6 > h as usize { lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.confirm_install.list_ellipsis"), Style::default().fg(th.subtext1), ))); } } lines.push(Line::from("")); // Add warning about removal and no backup lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.confirm_remove.warning_removal"), Style::default().fg(th.red).add_modifier(Modifier::BOLD), ))); lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.confirm_remove.confirm_hint"), Style::default().fg(th.subtext1), ))); let boxw = Paragraph::new(lines) .style(Style::default().fg(th.text).bg(th.mantle)) .wrap(Wrap { trim: true }) .block( Block::default() .title(Span::styled( i18n::t(app, "app.modals.confirm_remove.title"), Style::default().fg(th.red).add_modifier(Modifier::BOLD), )) .borders(Borders::ALL) .border_type(BorderType::Double) .border_style(Style::default().fg(th.red)) .style(Style::default().bg(th.mantle)), ); f.render_widget(boxw, rect); } /// What: Render the confirmation modal for batch updates that may cause dependency conflicts. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: `AppState` for translations /// - `area`: Full screen area used to center the modal /// - `items`: Packages to update /// /// Output: /// - Draws the batch update warning dialog. /// /// Details: /// - Shows warning message about potential dependency conflicts and instructions for confirm/cancel. #[allow(clippy::many_single_char_names)] pub fn render_confirm_batch_update( f: &mut Frame, _app: &AppState, area: Rect, items: &[PackageItem], ) { let th = theme(); let w = area.width.saturating_sub(6).min(90); let h = area.height.saturating_sub(6).min(20); let x = area.x + (area.width.saturating_sub(w)) / 2; let y = area.y + (area.height.saturating_sub(h)) / 2; let rect = ratatui::prelude::Rect { x, y, width: w, height: h, }; f.render_widget(Clear, rect); let mut lines = vec![ Line::from(Span::styled( "Warning: Single package updates may break package, due to dependency conflicts.", Style::default().fg(th.red).add_modifier(Modifier::BOLD), )), Line::from(""), Line::from(Span::styled( "Do you want to continue?", Style::default().fg(th.text), )), Line::from(""), ]; if !items.is_empty() { lines.push(Line::from(Span::styled( "Packages to update:", Style::default().fg(th.subtext1), ))); for p in items.iter().take((h as usize).saturating_sub(8)) { let p_name = &p.name; lines.push(Line::from(Span::styled( format!(" - {p_name}"), Style::default().fg(th.text), ))); } if items.len() + 8 > h as usize { lines.push(Line::from(Span::styled( "...", Style::default().fg(th.subtext1), ))); } lines.push(Line::from("")); } lines.push(Line::from(Span::styled( "Press Enter to continue, Esc/q to cancel", Style::default().fg(th.subtext1), ))); let boxw = Paragraph::new(lines) .style(Style::default().fg(th.text).bg(th.mantle)) .wrap(Wrap { trim: true }) .block( Block::default() .title(Span::styled( "Confirm Batch Update", Style::default().fg(th.red).add_modifier(Modifier::BOLD), )) .borders(Borders::ALL) .border_type(BorderType::Double) .border_style(Style::default().fg(th.red)) .style(Style::default().bg(th.mantle)), ); f.render_widget(boxw, rect); } /// What: Render the confirmation modal for continuing AUR update after pacman failed. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Application state /// - `area`: Full screen area used to center the modal /// - `message`: Message explaining the situation /// /// Output: /// - Draws the confirmation dialog asking if user wants to continue with AUR update /// /// Details: /// - Shows a warning message about pacman failure /// - Prompts user to continue with AUR update or cancel /// - Uses similar styling to other confirmation modals #[allow(clippy::many_single_char_names)] pub fn render_confirm_aur_update(f: &mut Frame, app: &AppState, area: Rect, message: &str) { let th = theme(); let w = area.width.saturating_sub(6).min(90); let h = area.height.saturating_sub(6).min(20); let x = area.x + (area.width.saturating_sub(w)) / 2; let y = area.y + (area.height.saturating_sub(h)) / 2; let rect = Rect { x, y, width: w, height: h, }; f.render_widget(Clear, rect); let lines: Vec<Line> = message .lines() .map(|l| Line::from(Span::styled(l, Style::default().fg(th.text)))) .collect(); let paragraph = Paragraph::new(lines).wrap(Wrap { trim: true }).block( Block::default() .title(Span::styled( i18n::t(app, "app.modals.confirm_aur_update.title"), Style::default().fg(th.yellow).add_modifier(Modifier::BOLD), )) .borders(Borders::ALL) .border_type(BorderType::Double) .border_style(Style::default().fg(th.yellow)) .style(Style::default().bg(th.mantle)), ); f.render_widget(paragraph, rect); } /// What: Render the confirmation modal for reinstalling already installed packages. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: `AppState` for translations /// - `area`: Full screen area used to center the modal /// - `items`: Packages to reinstall /// /// Output: /// - Draws the reinstall confirmation dialog. /// /// Details: /// - Shows warning message about reinstalling packages and instructions for confirm/cancel. #[allow(clippy::many_single_char_names)] pub fn render_confirm_reinstall(f: &mut Frame, app: &AppState, area: Rect, items: &[PackageItem]) { let th = theme(); // Calculate required height based on content // Structure: heading + empty + message + empty + packages/none + empty + hint // Base: heading(1) + empty(1) + message(1) + empty(1) + empty(1) + hint(1) = 6 let base_lines = 6u16; let content_lines = if items.is_empty() { 1u16 // "No packages" message } else { // packages (max 5 shown) + potentially "and more" line let package_count = items.len().min(5); u16::try_from(package_count + usize::from(items.len() > 5)).unwrap_or(6) }; // Total content lines needed (borders take 2 lines, so add 2) let required_height = base_lines + content_lines + 2; let h = area .height .saturating_sub(4) .min(required_height.clamp(10, 18)); let w = area.width.saturating_sub(6).min(65); let x = area.x + (area.width.saturating_sub(w)) / 2; let y = area.y + (area.height.saturating_sub(h)) / 2; let rect = ratatui::prelude::Rect { x, y, width: w, height: h, }; f.render_widget(Clear, rect); let mut lines = vec![ Line::from(Span::styled( i18n::t(app, "app.modals.confirm_reinstall.heading"), Style::default().fg(th.yellow).add_modifier(Modifier::BOLD), )), Line::from(""), Line::from(Span::styled( i18n::t(app, "app.modals.confirm_reinstall.message"), Style::default().fg(th.subtext1), )), Line::from(""), ]; if items.is_empty() { lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.confirm_reinstall.none"), Style::default().fg(th.subtext1), ))); } else { // Show max 5 packages to keep dialog compact for p in items.iter().take(5) { let p_name = &p.name; lines.push(Line::from(Span::styled( format!(" • {p_name}"), Style::default().fg(th.text), ))); } if items.len() > 5 { let remaining = items.len() - 5; lines.push(Line::from(Span::styled( i18n::t_fmt1(app, "app.modals.confirm_reinstall.and_more", remaining), Style::default().fg(th.subtext1), ))); } } lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.confirm_reinstall.confirm_hint"), Style::default() .fg(th.subtext1) .add_modifier(Modifier::BOLD), ))); let boxw = Paragraph::new(lines) .style(Style::default().fg(th.text).bg(th.mantle)) .wrap(Wrap { trim: true }) .block( Block::default() .title(Span::styled( i18n::t(app, "app.modals.confirm_reinstall.title"), Style::default().fg(th.yellow).add_modifier(Modifier::BOLD), )) .borders(Borders::ALL) .border_type(BorderType::Double) .border_style(Style::default().fg(th.yellow)) .style(Style::default().bg(th.mantle)), ); f.render_widget(boxw, rect); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/footer.rs
src/ui/modals/preflight/footer.rs
use ratatui::{ Frame, prelude::Rect, style::Style, text::{Line, Span}, widgets::{Block, BorderType, Borders, Paragraph, Wrap}, }; use crate::i18n; use crate::state::{AppState, PackageItem, PreflightAction, PreflightTab}; use crate::theme::theme; /// What: Render footer/keybinds pane at the bottom of the modal. /// /// Inputs: /// - `f`: Frame to render into. /// - `app`: Application state for i18n. /// - `items`: Packages being reviewed. /// - `action`: Whether install or remove. /// - `tab`: Current active tab. /// - `content_rect`: Content area rectangle. /// - `keybinds_rect`: Keybinds area rectangle. /// - `bg_color`: Background color. /// - `border_color`: Border color. /// /// Output: /// - Renders the footer widget with keybinds hints. /// /// Details: /// - Builds footer hint based on current tab and whether AUR packages are present. /// - Adds cascade mode hint for remove actions. #[allow(clippy::too_many_arguments)] pub fn render_footer( f: &mut Frame, app: &AppState, items: &[PackageItem], action: PreflightAction, tab: PreflightTab, content_rect: Rect, keybinds_rect: Rect, bg_color: ratatui::style::Color, border_color: ratatui::style::Color, ) { let th = theme(); // Render keybinds pane at the bottom // Check if any AUR packages are present for scanning let has_aur = items .iter() .any(|p| matches!(p.source, crate::state::Source::Aur)); // Build footer hint based on current tab let mut scan_hint = match tab { PreflightTab::Deps => { if has_aur { i18n::t(app, "app.modals.preflight.footer_hints.deps_with_aur") } else { i18n::t(app, "app.modals.preflight.footer_hints.deps_without_aur") } } PreflightTab::Files => { if has_aur { i18n::t(app, "app.modals.preflight.footer_hints.files_with_aur") } else { i18n::t(app, "app.modals.preflight.footer_hints.files_without_aur") } } PreflightTab::Services => { if has_aur { i18n::t(app, "app.modals.preflight.footer_hints.services_with_aur") } else { i18n::t( app, "app.modals.preflight.footer_hints.services_without_aur", ) } } _ => { if has_aur { i18n::t(app, "app.modals.preflight.footer_hints.default_with_aur") } else { i18n::t(app, "app.modals.preflight.footer_hints.default_without_aur") } } }; if matches!(action, PreflightAction::Remove) { scan_hint.push_str(&i18n::t( app, "app.modals.preflight.footer_hints.cascade_mode", )); } let keybinds_lines = vec![ Line::from(""), // Empty line for spacing Line::from(Span::styled(scan_hint, Style::default().fg(th.subtext1))), ]; // Adjust keybinds rect to start exactly where content rect ends (no gap) let keybinds_rect_adjusted = Rect { x: keybinds_rect.x, y: content_rect.y + content_rect.height, width: keybinds_rect.width, height: keybinds_rect.height, }; let keybinds_widget = Paragraph::new(keybinds_lines) .style(Style::default().fg(th.text).bg(bg_color)) .wrap(Wrap { trim: true }) .block( Block::default() .borders(Borders::LEFT | Borders::BOTTOM | Borders::RIGHT) .border_type(BorderType::Double) .border_style(Style::default().fg(border_color)) .style(Style::default().bg(bg_color)), ); f.render_widget(keybinds_widget, keybinds_rect_adjusted); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/header.rs
src/ui/modals/preflight/header.rs
use ratatui::{ prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, }; use crate::i18n; use crate::state::modal::PreflightHeaderChips; use crate::state::{AppState, PreflightTab}; use crate::theme::theme; use super::helpers::render_header_chips; /// What: Represents the completion and loading status of a tab. /// /// Inputs: None (struct definition). /// /// Output: None (struct definition). /// /// Details: Used to track whether a tab is complete and/or loading. struct TabStatus { /// Whether the tab data is complete. complete: bool, /// Whether the tab is currently loading. loading: bool, } /// What: Calculate completion status for the summary tab. /// /// Inputs: /// - `summary`: Summary data option. /// - `summary_loading`: Whether summary is currently loading. /// /// Output: Returns `TabStatus` with completion and loading flags. /// /// Details: Summary is complete if data exists. const fn calculate_summary_status( summary: Option<&crate::state::modal::PreflightSummaryData>, summary_loading: bool, ) -> TabStatus { TabStatus { complete: summary.is_some(), loading: summary_loading, } } /// What: Calculate completion status for the dependencies tab. /// /// Inputs: /// - `app`: Application state (for loading flags). /// - `item_names`: Set of all package names. /// - `dependency_info`: Dependency information array. /// /// Output: Returns `TabStatus` with completion and loading flags. /// /// Details: Dependencies are complete when not loading and all packages are represented /// (either all have deps or all have 0 deps). fn calculate_deps_status( app: &AppState, item_names: &std::collections::HashSet<String>, dependency_info: &[crate::state::modal::DependencyInfo], ) -> TabStatus { let loading = app.preflight_deps_resolving || app.deps_resolving || app.preflight_deps_items.is_some(); if loading { return TabStatus { complete: false, loading: true, }; } let packages_with_deps: std::collections::HashSet<String> = dependency_info .iter() .flat_map(|d| d.required_by.iter()) .cloned() .collect(); let all_packages_have_deps = packages_with_deps.len() == item_names.len(); let complete = item_names.is_empty() || dependency_info.is_empty() // All have 0 deps || all_packages_have_deps; // All have deps and all are represented TabStatus { complete, loading: false, } } /// What: Calculate completion status for the files tab. /// /// Inputs: /// - `app`: Application state (for loading flags). /// - `item_names`: Set of all package names. /// - `file_info`: File information array. /// /// Output: Returns `TabStatus` with completion and loading flags. /// /// Details: Files are complete when not loading and all packages have file info. fn calculate_files_status( app: &AppState, item_names: &std::collections::HashSet<String>, file_info: &[crate::state::modal::PackageFileInfo], ) -> TabStatus { let loading = app.preflight_files_resolving || app.files_resolving || app.preflight_files_items.is_some(); if loading { return TabStatus { complete: false, loading: true, }; } let file_info_names: std::collections::HashSet<String> = file_info.iter().map(|f| f.name.clone()).collect(); let complete = (!item_names.is_empty() && file_info_names.len() == item_names.len()) || (item_names.is_empty() && !app.install_list_files.is_empty()); TabStatus { complete, loading: false, } } /// What: Calculate completion status for the services tab. /// /// Inputs: /// - `app`: Application state (for loading flags). /// - `services_loaded`: Whether services are loaded. /// /// Output: Returns `TabStatus` with completion and loading flags. /// /// Details: Services are complete if marked as loaded or if install list has services. const fn calculate_services_status(app: &AppState, services_loaded: bool) -> TabStatus { let loading = app.preflight_services_resolving || app.services_resolving; let complete = services_loaded || (!loading && !app.install_list_services.is_empty()); TabStatus { complete, loading } } /// What: Calculate completion status for the sandbox tab. /// /// Inputs: /// - `app`: Application state (for loading flags). /// - `aur_items`: Set of AUR package names. /// - `sandbox_info`: Sandbox information array. /// - `sandbox_loaded`: Whether sandbox is loaded. /// /// Output: Returns `TabStatus` with completion and loading flags. /// /// Details: Sandbox is complete when not loading and all AUR packages have sandbox info. fn calculate_sandbox_status( app: &AppState, aur_items: &std::collections::HashSet<String>, sandbox_info: &[crate::logic::sandbox::SandboxInfo], sandbox_loaded: bool, ) -> TabStatus { let loading = app.preflight_sandbox_resolving || app.sandbox_resolving; if loading { return TabStatus { complete: false, loading: true, }; } let sandbox_info_names: std::collections::HashSet<String> = sandbox_info .iter() .map(|s| s.package_name.clone()) .collect(); let complete = sandbox_loaded || (aur_items.is_empty() || sandbox_info_names.len() == aur_items.len()) || (aur_items.is_empty() && !app.install_list_sandbox.is_empty()); TabStatus { complete, loading: false, } } /// What: Get status icon and color for a tab based on its status. /// /// Inputs: /// - `status`: Tab status (complete/loading). /// - `th`: Theme reference. /// /// Output: Returns tuple of (icon string, color). /// /// Details: Returns loading icon if loading, checkmark if complete, empty otherwise. const fn get_status_icon( status: &TabStatus, th: &crate::theme::Theme, ) -> (&'static str, ratatui::style::Color) { if status.loading { ("⟳ ", th.sapphire) } else if status.complete { ("✓ ", th.green) } else { ("", th.overlay1) } } /// What: Build completion order vector from tab statuses. /// /// Inputs: /// - `statuses`: Array of tab statuses. /// /// Output: Returns vector of tab indices in completion order. /// /// Details: Only includes tabs that are complete and not loading. fn build_completion_order(statuses: &[TabStatus]) -> Vec<usize> { statuses .iter() .enumerate() .filter_map(|(i, status)| { if status.complete && !status.loading { Some(i) } else { None } }) .collect() } /// What: Get completion highlight color based on position in completion order. /// /// Inputs: /// - `order_idx`: Position in completion order (0 = first, 1 = second, etc.). /// - `th`: Theme reference. /// /// Output: Returns color for the highlight. /// /// Details: Uses different colors for different completion positions. const fn get_completion_highlight_color( order_idx: usize, th: &crate::theme::Theme, ) -> ratatui::style::Color { match order_idx { 0 => th.green, // First completed 1 => th.sapphire, // Second completed 2 => th.mauve, // Third completed _ => th.overlay1, // Others } } /// What: Check if a tab index matches the current active tab. /// /// Inputs: /// - `tab_idx`: Index of the tab (0-4). /// - `current_tab`: Currently active tab enum. /// /// Output: Returns true if the tab is active. /// /// Details: Maps tab indices to `PreflightTab` enum variants. const fn is_tab_active(tab_idx: usize, current_tab: PreflightTab) -> bool { matches!( (tab_idx, current_tab), (0, PreflightTab::Summary) | (1, PreflightTab::Deps) | (2, PreflightTab::Files) | (3, PreflightTab::Services) | (4, PreflightTab::Sandbox) ) } /// What: Calculate the color for a tab based on its state. /// /// Inputs: /// - `is_active`: Whether the tab is currently active. /// - `tab_idx`: Index of the tab. /// - `completion_order`: Vector of completed tab indices in order. /// - `th`: Theme reference. /// /// Output: Returns the color for the tab. /// /// Details: Active tabs use mauve, completed tabs use highlight colors, others use overlay1. fn calculate_tab_color( is_active: bool, tab_idx: usize, completion_order: &[usize], th: &crate::theme::Theme, ) -> ratatui::style::Color { if is_active { return th.mauve; } completion_order .iter() .position(|&x| x == tab_idx) .map_or(th.overlay1, |order_idx| { get_completion_highlight_color(order_idx, th) }) } /// What: Calculate the width of a tab for rectangle storage. /// /// Inputs: /// - `label`: Tab label text. /// - `status_icon`: Status icon string. /// - `is_active`: Whether the tab is active. /// /// Output: Returns the width in characters as u16. /// /// Details: Active tabs include brackets, adding 2 characters to the width. fn calculate_tab_width(label: &str, status_icon: &str, is_active: bool) -> u16 { let base_width = label.len() + status_icon.len(); if is_active { u16::try_from(base_width + 2).unwrap_or(u16::MAX) // +2 for brackets } else { u16::try_from(base_width).unwrap_or(u16::MAX) } } /// What: Create status icon span if icon exists. /// /// Inputs: /// - `status_icon`: Status icon string (must be static). /// - `status_color`: Color for the icon. /// /// Output: Returns optional span for the status icon. /// /// Details: Returns None if icon is empty, otherwise returns styled span. fn create_status_icon_span( status_icon: &'static str, status_color: ratatui::style::Color, ) -> Option<Span<'static>> { if status_icon.is_empty() { return None; } Some(Span::styled( status_icon, Style::default() .fg(status_color) .add_modifier(Modifier::BOLD), )) } /// What: Create tab label span based on active state. /// /// Inputs: /// - `label`: Tab label text. /// - `is_active`: Whether the tab is active. /// - `is_completed`: Whether the tab is completed. /// - `tab_color`: Color for the label. /// /// Output: Returns styled span for the tab label. /// /// Details: Active tabs have brackets and bold, completed tabs have bold modifier. fn create_tab_label_span( label: &str, is_active: bool, is_completed: bool, tab_color: ratatui::style::Color, ) -> Span<'static> { let text = if is_active { format!("[{label}]") } else { label.to_string() }; let modifier = if is_active || is_completed { Modifier::BOLD } else { Modifier::empty() }; Span::styled(text, Style::default().fg(tab_color).add_modifier(modifier)) } /// What: Render spans for a single tab and store its rectangle. /// /// Inputs: /// - `tab_idx`: Index of the tab. /// - `label`: Tab label text. /// - `status`: Tab status (complete/loading). /// - `is_active`: Whether the tab is active. /// - `completion_order`: Vector of completed tab indices in order. /// - `tab_x`: Current X position for the tab. /// - `tab_y`: Y position for the tab. /// - `th`: Theme reference. /// - `tab_rects`: Mutable reference to tab rectangles array. /// /// Output: Returns tuple of (spans for this tab, new `tab_x` position). /// /// Details: Builds status icon and label spans, stores rectangle for mouse clicks. #[allow(clippy::too_many_arguments)] fn render_single_tab( tab_idx: usize, label: &str, status: &TabStatus, is_active: bool, completion_order: &[usize], tab_x: u16, tab_y: u16, th: &crate::theme::Theme, tab_rects: &mut [Option<(u16, u16, u16, u16)>; 5], ) -> (Vec<Span<'static>>, u16) { let (status_icon, status_color) = get_status_icon(status, th); let tab_color = calculate_tab_color(is_active, tab_idx, completion_order, th); let tab_width = calculate_tab_width(label, status_icon, is_active); // Store rectangle for this tab tab_rects[tab_idx] = Some((tab_x, tab_y, tab_width, 1)); let new_tab_x = tab_x + tab_width; let mut spans = Vec::new(); // Add status icon if present if let Some(icon_span) = create_status_icon_span(status_icon, status_color) { spans.push(icon_span); } // Add tab label let is_completed = completion_order.contains(&tab_idx); spans.push(create_tab_label_span( label, is_active, is_completed, tab_color, )); (spans, new_tab_x) } /// What: Extract package names and AUR items from package list. /// /// Inputs: /// - `items`: Package items to extract from. /// /// Output: Returns tuple of (all item names, AUR item names). /// /// Details: Separates all packages from AUR-only packages for different completion checks. fn extract_package_sets( items: &[crate::state::PackageItem], ) -> ( std::collections::HashSet<String>, std::collections::HashSet<String>, ) { let item_names: std::collections::HashSet<String> = items.iter().map(|i| i.name.clone()).collect(); let aur_items: std::collections::HashSet<String> = items .iter() .filter(|p| matches!(p.source, crate::state::Source::Aur)) .map(|i| i.name.clone()) .collect(); (item_names, aur_items) } /// What: Build tab labels array from i18n strings. /// /// Inputs: /// - `app`: Application state (for i18n). /// /// Output: Returns array of 5 tab label strings. /// /// Details: Creates localized tab labels for all preflight tabs. fn build_tab_labels(app: &AppState) -> [String; 5] { [ i18n::t(app, "app.modals.preflight.tabs.summary"), i18n::t(app, "app.modals.preflight.tabs.deps"), i18n::t(app, "app.modals.preflight.tabs.files"), i18n::t(app, "app.modals.preflight.tabs.services"), i18n::t(app, "app.modals.preflight.tabs.sandbox"), ] } /// What: Calculate completion status for all tabs. /// /// Inputs: /// - `app`: Application state. /// - `item_names`: All package names. /// - `aur_items`: AUR package names. /// - `summary`: Summary data. /// - `dependency_info`: Dependency info. /// - `file_info`: File info. /// - `services_loaded`: Services loaded flag. /// - `sandbox_info`: Sandbox info. /// - `sandbox_loaded`: Sandbox loaded flag. /// /// Output: Returns array of tab statuses. /// /// Details: Centralizes all status calculation logic. #[allow(clippy::too_many_arguments)] fn calculate_all_tab_statuses( app: &AppState, item_names: &std::collections::HashSet<String>, aur_items: &std::collections::HashSet<String>, summary: Option<&crate::state::modal::PreflightSummaryData>, dependency_info: &[crate::state::modal::DependencyInfo], file_info: &[crate::state::modal::PackageFileInfo], services_loaded: bool, sandbox_info: &[crate::logic::sandbox::SandboxInfo], sandbox_loaded: bool, ) -> [TabStatus; 5] { [ calculate_summary_status(summary, app.preflight_summary_resolving), calculate_deps_status(app, item_names, dependency_info), calculate_files_status(app, item_names, file_info), calculate_services_status(app, services_loaded), calculate_sandbox_status(app, aur_items, sandbox_info, sandbox_loaded), ] } /// What: Build tab header spans and calculate tab rectangles. /// /// Inputs: /// - `tab_labels`: Array of tab label strings. /// - `statuses`: Array of tab statuses. /// - `current_tab`: Currently active tab. /// - `completion_order`: Order of completed tabs. /// - `content_rect`: Content area rectangle. /// - `th`: Theme reference. /// - `tab_rects`: Mutable reference to store tab rectangles. /// /// Output: Returns vector of spans for the tab header. /// /// Details: Handles all tab rendering and rectangle calculation. fn build_tab_header_spans( tab_labels: &[String; 5], statuses: &[TabStatus; 5], current_tab: PreflightTab, completion_order: &[usize], content_rect: Rect, th: &crate::theme::Theme, tab_rects: &mut [Option<(u16, u16, u16, u16)>; 5], ) -> Vec<Span<'static>> { let tab_y = content_rect.y + 2; // +1 for top border + 1 for chips line let mut tab_x = content_rect.x + 1; // +1 for left border let mut tab_spans = Vec::new(); for (i, lbl) in tab_labels.iter().enumerate() { if i > 0 { tab_spans.push(Span::raw(" ")); tab_x += 2; // Account for spacing } let is_active = is_tab_active(i, current_tab); let status = &statuses[i]; let (spans, new_tab_x) = render_single_tab( i, lbl, status, is_active, completion_order, tab_x, tab_y, th, tab_rects, ); tab_spans.extend(spans); tab_x = new_tab_x; } tab_spans } /// What: Calculate and store content area rectangle. /// /// Inputs: /// - `app`: Application state to store rectangle in. /// - `content_rect`: Original content rectangle. /// /// Output: None (stores in app state). /// /// Details: Calculates content area after header (3 lines: chips + tabs + empty). #[allow(clippy::missing_const_for_fn)] fn store_content_rect(app: &mut AppState, content_rect: Rect) { app.preflight_content_rect = Some(( content_rect.x + 1, // +1 for left border content_rect.y + 4, // +1 for top border + 3 for header lines content_rect.width.saturating_sub(2), // -2 for borders content_rect.height.saturating_sub(4), // -1 for top border - 3 for header lines )); } /// What: Context data for rendering tab header. /// /// Inputs: None (struct definition). /// /// Output: None (struct definition). /// /// Details: Groups all data needed for tab header rendering to reduce parameter count. pub struct TabHeaderContext<'a> { /// Application state. pub app: &'a mut AppState, /// Content rectangle for rendering. pub content_rect: Rect, /// Currently active preflight tab. pub current_tab: PreflightTab, /// Header chip metrics. pub header_chips: &'a PreflightHeaderChips, /// Package items being analyzed. pub items: &'a [crate::state::PackageItem], /// Preflight summary data, if available. pub summary: Option<&'a crate::state::modal::PreflightSummaryData>, /// Dependency information. pub dependency_info: &'a [crate::state::modal::DependencyInfo], /// File information. pub file_info: &'a [crate::state::modal::PackageFileInfo], /// Whether service information has been loaded. pub services_loaded: bool, /// Sandbox analysis information. pub sandbox_info: &'a [crate::logic::sandbox::SandboxInfo], /// Whether sandbox information has been loaded. pub sandbox_loaded: bool, } /// What: Render tab header with progress indicators and calculate tab rectangles. /// /// Inputs: /// - `ctx`: Context containing all data needed for rendering. /// /// Output: /// - Returns a tuple of `(Line, Line)` containing the header chips and tab header lines. /// /// Details: /// - Calculates completion status for each tab and displays progress indicators. /// - Checks if data is complete for ALL packages, not just if any data exists. /// - Stores tab rectangles in `app.preflight_tab_rects` for mouse click detection. /// - Stores content area rectangle in `app.preflight_content_rect`. pub fn render_tab_header(ctx: &mut TabHeaderContext<'_>) -> (Line<'static>, Line<'static>) { let th = theme(); // Extract data preparation let (item_names, aur_items) = extract_package_sets(ctx.items); // Build tab labels let tab_labels = build_tab_labels(ctx.app); // Extract status calculation let statuses = calculate_all_tab_statuses( ctx.app, &item_names, &aur_items, ctx.summary, ctx.dependency_info, ctx.file_info, ctx.services_loaded, ctx.sandbox_info, ctx.sandbox_loaded, ); // Track completion order (for highlighting) let completion_order = build_completion_order(&statuses); // Initialize tab rectangles ctx.app.preflight_tab_rects = [None; 5]; // Extract tab rendering loop let tab_spans = build_tab_header_spans( &tab_labels, &statuses, ctx.current_tab, &completion_order, ctx.content_rect, &th, &mut ctx.app.preflight_tab_rects, ); // Extract rectangle storage store_content_rect(ctx.app, ctx.content_rect); let header_chips_line = render_header_chips(ctx.app, ctx.header_chips); let tab_header_line = Line::from(tab_spans); (header_chips_line, tab_header_line) }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/mod.rs
src/ui/modals/preflight/mod.rs
use ratatui::{Frame, prelude::Rect, widgets::Clear}; use std::convert::AsRef; use crate::i18n; use crate::state::{AppState, PreflightAction}; /// Footer rendering for preflight modal. mod footer; /// Header rendering for preflight modal. mod header; /// Helper utilities for preflight modal rendering. mod helpers; /// Tab rendering modules for preflight modal. mod tabs; use footer::render_footer; use header::render_tab_header; use helpers::{extract, layout, scroll, sync, tabs as tab_helpers, widget}; use ratatui::text::Line; use crate::theme::theme; /// What: Sync all preflight data from app cache to modal state. /// /// Inputs: /// - `app`: Application state /// - `fields`: Preflight fields extracted from modal /// /// Output: /// - Updates modal state with synced data. fn sync_preflight_data(app: &AppState, fields: &mut extract::PreflightFields) { sync::sync_dependencies( app, fields.items, *fields.action, *fields.tab, fields.dependency_info, fields.dep_selected, ); sync::sync_files( app, fields.items, *fields.tab, fields.file_info, fields.file_selected, ); sync::sync_services( app, fields.items, *fields.action, fields.service_info, fields.service_selected, fields.services_loaded, ); sync::sync_sandbox( app, fields.items, *fields.action, *fields.tab, fields.sandbox_info, fields.sandbox_loaded, ); } /// What: Build content lines for preflight modal. /// /// Inputs: /// - `app`: Application state /// - `fields`: Preflight fields /// - `content_rect`: Content area rectangle /// /// Output: /// - Vector of lines to render. fn build_preflight_content_lines( app: &mut AppState, fields: &mut extract::PreflightFields, content_rect: Rect, ) -> Vec<Line<'static>> { let mut ctx = header::TabHeaderContext { app, content_rect, current_tab: *fields.tab, header_chips: fields.header_chips, items: fields.items, summary: fields.summary.as_ref().map(AsRef::as_ref), dependency_info: fields.dependency_info, file_info: fields.file_info, services_loaded: *fields.services_loaded, sandbox_info: fields.sandbox_info, sandbox_loaded: *fields.sandbox_loaded, }; let (header_chips_line, tab_header_line) = render_tab_header(&mut ctx); let mut lines: Vec<Line<'static>> = Vec::new(); lines.push(header_chips_line); lines.push(tab_header_line); lines.push(Line::from("")); let tab_lines = tab_helpers::render_tab_content( app, *fields.tab, fields.items, *fields.action, fields.summary.as_ref().map(AsRef::as_ref), fields.header_chips, fields.dependency_info, fields.dep_selected, fields.dep_tree_expanded, fields.deps_error.as_ref(), fields.file_info, fields.file_selected, fields.file_tree_expanded, fields.files_error.as_ref(), fields.service_info, fields.service_selected, *fields.services_loaded, fields.services_error.as_ref(), fields.sandbox_info, fields.sandbox_selected, fields.sandbox_tree_expanded, *fields.sandbox_loaded, fields.sandbox_error.as_ref(), fields.selected_optdepends, *fields.cascade_mode, content_rect, ); lines.extend(tab_lines); lines } /// What: Render the preflight modal summarizing dependency/file checks before install/remove. /// /// Inputs: /// - `f`: Frame to render into /// - `area`: Full screen area used to center the modal /// - `app`: Mutable application state (stores tab rects/content rects) /// - `modal`: Mutable modal state containing all preflight data /// /// Output: /// - Draws the modal content for the chosen tab and updates cached data along with clickable rects. /// /// Details: /// - Lazily resolves dependencies/files when first accessed, lays out tab headers, records tab /// rectangles for mouse navigation, and tailors summaries per tab with theming cues. pub fn render_preflight( f: &mut Frame, area: Rect, app: &mut AppState, modal: &mut crate::state::Modal, ) { let render_start = std::time::Instant::now(); let Some(mut fields) = extract::extract_preflight_fields(modal) else { return; }; let th = theme(); if tracing::enabled!(tracing::Level::TRACE) { tracing::trace!( "[UI] render_preflight START: tab={:?}, items={}, deps={}, files={}, services={}, sandbox={}, cache_deps={}, cache_files={}", fields.tab, fields.items.len(), fields.dependency_info.len(), fields.file_info.len(), fields.service_info.len(), fields.sandbox_info.len(), app.install_list_deps.len(), app.install_list_files.len() ); } sync_preflight_data(app, &mut fields); if tracing::enabled!(tracing::Level::TRACE) { tracing::trace!( "[UI] render_preflight AFTER SYNC: tab={:?}, deps={}, files={}, cache_deps={}, cache_files={}, resolving_deps={}, resolving_files={}", fields.tab, fields.dependency_info.len(), fields.file_info.len(), app.install_list_deps.len(), app.install_list_files.len(), app.preflight_deps_resolving || app.deps_resolving, app.preflight_files_resolving || app.files_resolving ); } let (rect, content_rect, keybinds_rect) = layout::calculate_modal_layout(area); f.render_widget(Clear, rect); let title = match *fields.action { PreflightAction::Install => i18n::t(app, "app.modals.preflight.title_install"), PreflightAction::Remove => i18n::t(app, "app.modals.preflight.title_remove"), PreflightAction::Downgrade => i18n::t(app, "app.modals.preflight.title_downgrade"), }; let border_color = th.lavender; let bg_color = th.crust; let lines = build_preflight_content_lines(app, &mut fields, content_rect); let scroll_offset = scroll::calculate_scroll_offset(app, *fields.tab); let content_widget = widget::ParagraphBuilder::new() .with_lines(lines) .with_title(title) .with_scroll(scroll_offset) .with_text_color(th.text) .with_bg_color(bg_color) .with_border_color(border_color) .build(); f.render_widget(content_widget, content_rect); render_footer( f, app, fields.items, *fields.action, *fields.tab, content_rect, keybinds_rect, bg_color, border_color, ); let render_duration = render_start.elapsed(); if render_duration.as_millis() > 50 { tracing::warn!("[UI] render_preflight took {:?} (slow!)", render_duration); } else if tracing::enabled!(tracing::Level::TRACE) { tracing::trace!("[UI] render_preflight completed in {:?}", render_duration); } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/helpers/sync_files_tests.rs
src/ui/modals/preflight/helpers/sync_files_tests.rs
//! Unit tests for `sync_files` function. use super::sync; use crate::state::AppState; use crate::state::modal::{FileChange, FileChangeType, PackageFileInfo, PreflightTab}; use crate::state::{PackageItem, Source}; /// What: Test `sync_files` early return when not on Files tab. /// /// Inputs: /// - `tab`: `PreflightTab::Summary` /// - `file_info`: Empty vector /// /// Output: /// - `file_info` remains unchanged /// /// Details: /// - Verifies that file sync is skipped when not on Files tab. #[test] fn test_sync_files_early_return_wrong_tab() { let app = AppState::default(); let items = vec![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, }]; let tab = PreflightTab::Summary; let mut file_info = Vec::new(); let mut file_selected = 0; sync::sync_files(&app, &items, tab, &mut file_info, &mut file_selected); assert!(file_info.is_empty()); } /// What: Test `sync_files` filters files by package name. /// /// Inputs: /// - `app`: `AppState` with cached file info /// - `items`: Packages to filter by /// /// Output: /// - `file_info` contains only files for matching packages /// /// Details: /// - Verifies that file filtering works correctly. #[test] #[allow(clippy::field_reassign_with_default)] fn test_sync_files_filters_by_package_name() { let mut app = AppState::default(); app.install_list_files = vec![ PackageFileInfo { name: "test-pkg".to_string(), files: vec![FileChange { path: "/usr/bin/test".to_string(), change_type: FileChangeType::New, package: "test-pkg".to_string(), is_config: false, predicted_pacnew: false, predicted_pacsave: false, }], total_count: 1, new_count: 1, changed_count: 0, removed_count: 0, config_count: 0, pacnew_candidates: 0, pacsave_candidates: 0, }, PackageFileInfo { name: "other-pkg".to_string(), files: vec![], total_count: 0, new_count: 0, changed_count: 0, removed_count: 0, config_count: 0, pacnew_candidates: 0, pacsave_candidates: 0, }, ]; let items = vec![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, }]; let tab = PreflightTab::Files; let mut file_info = Vec::new(); let mut file_selected = 0; sync::sync_files(&app, &items, tab, &mut file_info, &mut file_selected); assert_eq!(file_info.len(), 1); assert_eq!(file_info[0].name, "test-pkg"); assert_eq!(file_selected, 0); } /// What: Test `sync_files` resets selection when files change. /// /// Inputs: /// - `file_info`: Empty /// - `file_selected`: 5 /// - Cache has files /// /// Output: /// - `file_selected` is reset to 0 /// /// Details: /// - Verifies that selection is reset when files are synced. #[test] #[allow(clippy::field_reassign_with_default)] fn test_sync_files_resets_selection_when_files_change() { let mut app = AppState::default(); app.install_list_files = vec![PackageFileInfo { name: "test-pkg".to_string(), files: vec![], total_count: 0, new_count: 0, changed_count: 0, removed_count: 0, config_count: 0, pacnew_candidates: 0, pacsave_candidates: 0, }]; let items = vec![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, }]; let tab = PreflightTab::Files; let mut file_info = Vec::new(); let mut file_selected = 5; sync::sync_files(&app, &items, tab, &mut file_info, &mut file_selected); assert_eq!(file_selected, 0); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/helpers/sync_sandbox_tests.rs
src/ui/modals/preflight/helpers/sync_sandbox_tests.rs
//! Unit tests for `sync_sandbox` function. use super::sync; use crate::state::AppState; use crate::state::modal::{PreflightAction, PreflightTab}; use crate::state::{PackageItem, Source}; /// What: Test `sync_sandbox` early return for Remove action. /// /// Inputs: /// - `action`: `PreflightAction::Remove` /// - `sandbox_info`: Empty vector /// /// Output: /// - `sandbox_info` remains unchanged (unless no AUR packages) /// /// Details: /// - Verifies that sandbox sync handles remove actions correctly. #[test] fn test_sync_sandbox_early_return_remove() { let app = AppState::default(); let items = vec![PackageItem { name: "test-pkg".to_string(), version: "1.0".to_string(), description: String::new(), source: Source::Official { repo: "core".to_string(), arch: "x86_64".to_string(), }, popularity: None, out_of_date: None, orphaned: false, }]; let action = PreflightAction::Remove; let tab = PreflightTab::Sandbox; let mut sandbox_info = Vec::new(); let mut sandbox_loaded = false; sync::sync_sandbox( &app, &items, action, tab, &mut sandbox_info, &mut sandbox_loaded, ); // For remove with no AUR packages, should mark as loaded assert!(sandbox_loaded); } /// What: Test `sync_sandbox` early return when not on Sandbox tab. /// /// Inputs: /// - `tab`: `PreflightTab::Summary` /// - `sandbox_info`: Empty vector /// /// Output: /// - `sandbox_info` remains unchanged /// /// Details: /// - Verifies that sandbox sync is skipped when not on Sandbox tab. #[test] fn test_sync_sandbox_early_return_wrong_tab() { let app = AppState::default(); let items = vec![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, }]; let action = PreflightAction::Install; let tab = PreflightTab::Summary; let mut sandbox_info = Vec::new(); let mut sandbox_loaded = false; sync::sync_sandbox( &app, &items, action, tab, &mut sandbox_info, &mut sandbox_loaded, ); assert!(sandbox_info.is_empty()); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/helpers/render_tests.rs
src/ui/modals/preflight/helpers/render_tests.rs
//! Unit tests for `render_header_chips` function. use super::render_header_chips; use crate::state::AppState; use crate::state::modal::{PreflightHeaderChips, RiskLevel}; /// What: Test `render_header_chips` with minimal data. /// /// Inputs: /// - `app`: Default `AppState` /// - `chips`: Minimal `PreflightHeaderChips` with zero values /// /// Output: /// - Returns a Line containing styled spans /// /// Details: /// - Verifies that header chips render without panicking with minimal data. #[test] fn test_render_header_chips_minimal() { let app = AppState::default(); let chips = PreflightHeaderChips { package_count: 0, aur_count: 0, download_bytes: 0, install_delta_bytes: 0, risk_level: RiskLevel::Low, risk_score: 0, }; let line = render_header_chips(&app, &chips); assert!(!line.spans.is_empty()); } /// What: Test `render_header_chips` with AUR packages. /// /// Inputs: /// - `app`: Default `AppState` /// - `chips`: `PreflightHeaderChips` with AUR count > 0 /// /// Output: /// - Returns a Line containing AUR package count in chips /// /// Details: /// - Verifies that AUR count is included in the package count chip when > 0. #[test] fn test_render_header_chips_with_aur() { let app = AppState::default(); let chips = PreflightHeaderChips { package_count: 5, aur_count: 2, download_bytes: 1_048_576, install_delta_bytes: 512_000, risk_level: RiskLevel::Medium, risk_score: 5, }; let line = render_header_chips(&app, &chips); assert!(!line.spans.is_empty()); // Verify AUR count is mentioned in the output let line_text: String = line .spans .iter() .map(|s| s.content.as_ref()) .collect::<String>(); // The AUR count should be included in the package count chip assert!(line_text.contains('5') || line_text.contains('2')); } /// What: Test `render_header_chips` with positive install delta. /// /// Inputs: /// - `app`: Default `AppState` /// - `chips`: `PreflightHeaderChips` with positive `install_delta_bytes` /// /// Output: /// - Returns a Line with green delta color /// /// Details: /// - Verifies that positive install delta uses green color. #[test] fn test_render_header_chips_positive_delta() { let app = AppState::default(); let chips = PreflightHeaderChips { package_count: 1, aur_count: 0, download_bytes: 0, install_delta_bytes: 1_048_576, // Positive risk_level: RiskLevel::Low, risk_score: 1, }; let line = render_header_chips(&app, &chips); assert!(!line.spans.is_empty()); } /// What: Test `render_header_chips` with negative install delta. /// /// Inputs: /// - `app`: Default `AppState` /// - `chips`: `PreflightHeaderChips` with negative `install_delta_bytes` /// /// Output: /// - Returns a Line with red delta color /// /// Details: /// - Verifies that negative install delta uses red color. #[test] fn test_render_header_chips_negative_delta() { let app = AppState::default(); let chips = PreflightHeaderChips { package_count: 1, aur_count: 0, download_bytes: 0, install_delta_bytes: -1_048_576, // Negative risk_level: RiskLevel::Low, risk_score: 1, }; let line = render_header_chips(&app, &chips); assert!(!line.spans.is_empty()); } /// What: Test `render_header_chips` with zero install delta. /// /// Inputs: /// - `app`: Default `AppState` /// - `chips`: `PreflightHeaderChips` with zero `install_delta_bytes` /// /// Output: /// - Returns a Line with neutral delta color /// /// Details: /// - Verifies that zero install delta uses neutral color. #[test] fn test_render_header_chips_zero_delta() { let app = AppState::default(); let chips = PreflightHeaderChips { package_count: 1, aur_count: 0, download_bytes: 0, install_delta_bytes: 0, // Zero risk_level: RiskLevel::Low, risk_score: 1, }; let line = render_header_chips(&app, &chips); assert!(!line.spans.is_empty()); } /// What: Test `render_header_chips` with different risk levels. /// /// Inputs: /// - `app`: Default `AppState` /// - `chips`: `PreflightHeaderChips` with Low, Medium, and High risk levels /// /// Output: /// - Returns Lines with appropriate risk colors /// /// Details: /// - Verifies that different risk levels render with correct color coding. #[test] fn test_render_header_chips_risk_levels() { let app = AppState::default(); // Test Low risk let chips_low = PreflightHeaderChips { package_count: 1, aur_count: 0, download_bytes: 0, install_delta_bytes: 0, risk_level: RiskLevel::Low, risk_score: 1, }; let line_low = render_header_chips(&app, &chips_low); assert!(!line_low.spans.is_empty()); // Test Medium risk let chips_medium = PreflightHeaderChips { package_count: 1, aur_count: 0, download_bytes: 0, install_delta_bytes: 0, risk_level: RiskLevel::Medium, risk_score: 5, }; let line_medium = render_header_chips(&app, &chips_medium); assert!(!line_medium.spans.is_empty()); // Test High risk let chips_high = PreflightHeaderChips { package_count: 1, aur_count: 0, download_bytes: 0, install_delta_bytes: 0, risk_level: RiskLevel::High, risk_score: 10, }; let line_high = render_header_chips(&app, &chips_high); assert!(!line_high.spans.is_empty()); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/helpers/scroll.rs
src/ui/modals/preflight/helpers/scroll.rs
use crate::state::{AppState, Modal, PreflightTab}; /// What: Calculate scroll offset for the preflight modal content. /// /// Inputs: /// - `app`: Application state containing modal scroll information. /// - `tab`: Current active tab. /// /// Output: /// - Returns tuple of (`vertical_offset`, `horizontal_offset`) for scrolling. /// /// Details: /// - Only applies scroll offset for Summary tab (mouse scrolling only). /// - Returns (0, 0) for all other tabs. pub const fn calculate_scroll_offset(app: &AppState, tab: PreflightTab) -> (u16, u16) { if !matches!(tab, PreflightTab::Summary) { return (0, 0); } if let Modal::Preflight { summary_scroll, .. } = &app.modal { (*summary_scroll, 0) } else { (0, 0) } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/helpers/sync_services_tests.rs
src/ui/modals/preflight/helpers/sync_services_tests.rs
//! Unit tests for `sync_services` function. use super::sync; use crate::state::AppState; use crate::state::modal::{PreflightAction, ServiceImpact, ServiceRestartDecision}; use crate::state::{PackageItem, Source}; /// What: Test `sync_services` behavior for Remove action when no cached services exist. /// /// Inputs: /// - `action`: `PreflightAction::Remove` /// - `service_info`: Empty vector /// - `services_loaded`: false /// - No cached services in app state /// - No cache file exists /// /// Output: /// - `service_info` remains unchanged /// - `services_loaded` remains false (services will be resolved in background) /// /// Details: /// - Verifies that for Remove actions, services are not marked as loaded immediately /// when no cached services exist, allowing background resolution to proceed. #[test] fn test_sync_services_for_remove_without_cache() { let app = AppState::default(); let items = vec![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, }]; let action = PreflightAction::Remove; let mut service_info = Vec::new(); let mut service_selected = 0; let mut services_loaded = false; sync::sync_services( &app, &items, action, &mut service_info, &mut service_selected, &mut services_loaded, ); assert!(service_info.is_empty()); // services_loaded should remain false when no cache exists, allowing background resolution assert!(!services_loaded); } /// What: Test `sync_services` filters services by providers. /// /// Inputs: /// - `app`: `AppState` with cached service info /// - `items`: Packages that provide services /// /// Output: /// - `service_info` contains only services provided by items /// /// Details: /// - Verifies that service filtering works correctly. #[test] #[allow(clippy::field_reassign_with_default)] fn test_sync_services_filters_by_providers() { let mut app = AppState::default(); app.install_list_services = vec![ ServiceImpact { unit_name: "test.service".to_string(), providers: vec!["test-pkg".to_string()], is_active: true, needs_restart: true, recommended_decision: ServiceRestartDecision::Restart, restart_decision: ServiceRestartDecision::Restart, }, ServiceImpact { unit_name: "other.service".to_string(), providers: vec!["other-pkg".to_string()], is_active: false, needs_restart: false, recommended_decision: ServiceRestartDecision::Defer, restart_decision: ServiceRestartDecision::Defer, }, ]; let items = vec![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, }]; let action = PreflightAction::Install; let mut service_info = Vec::new(); let mut service_selected = 0; let mut services_loaded = false; sync::sync_services( &app, &items, action, &mut service_info, &mut service_selected, &mut services_loaded, ); assert_eq!(service_info.len(), 1); assert_eq!(service_info[0].unit_name, "test.service"); assert!(services_loaded); } /// What: Test `sync_services` adjusts selection when out of bounds. /// /// Inputs: /// - `service_info`: 3 services /// - `service_selected`: 5 (out of bounds) /// /// Output: /// - `service_selected` is adjusted to 2 (last valid index) /// /// Details: /// - Verifies that selection is clamped to valid range. #[test] #[allow(clippy::field_reassign_with_default)] fn test_sync_services_adjusts_selection_out_of_bounds() { let mut app = AppState::default(); app.install_list_services = vec![ ServiceImpact { unit_name: "service1.service".to_string(), providers: vec!["test-pkg".to_string()], is_active: true, needs_restart: true, recommended_decision: ServiceRestartDecision::Restart, restart_decision: ServiceRestartDecision::Restart, }, ServiceImpact { unit_name: "service2.service".to_string(), providers: vec!["test-pkg".to_string()], is_active: true, needs_restart: true, recommended_decision: ServiceRestartDecision::Restart, restart_decision: ServiceRestartDecision::Restart, }, ServiceImpact { unit_name: "service3.service".to_string(), providers: vec!["test-pkg".to_string()], is_active: true, needs_restart: true, recommended_decision: ServiceRestartDecision::Restart, restart_decision: ServiceRestartDecision::Restart, }, ]; let items = vec![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, }]; let action = PreflightAction::Install; let mut service_info = Vec::new(); let mut service_selected = 5; // Out of bounds let mut services_loaded = false; sync::sync_services( &app, &items, action, &mut service_info, &mut service_selected, &mut services_loaded, ); assert_eq!(service_info.len(), 3); assert_eq!(service_selected, 2); // Clamped to last valid index }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/helpers/tabs.rs
src/ui/modals/preflight/helpers/tabs.rs
use ratatui::prelude::Rect; use ratatui::text::Line; use crate::logic::sandbox::SandboxInfo; use crate::state::modal::{ CascadeMode, DependencyInfo, PackageFileInfo, PreflightAction, PreflightHeaderChips, PreflightSummaryData, PreflightTab, ServiceImpact, }; use crate::state::{AppState, PackageItem}; use std::collections::{HashMap, HashSet}; use super::super::tabs::{ SandboxTabContext, render_deps_tab, render_files_tab, render_sandbox_tab, render_services_tab, render_summary_tab, }; /// What: Render content lines for the currently active tab. /// /// Inputs: /// - `app`: Application state for i18n and other context. /// - `tab`: Current active tab. /// - `items`: Packages being reviewed. /// - `action`: Whether install or remove. /// - `summary`: Summary data option. /// - `header_chips`: Header chip data. /// - `dependency_info`: Dependency information. /// - `dep_selected`: Mutable reference to selected dependency index. /// - `dep_tree_expanded`: Set of expanded dependency tree nodes. /// - `deps_error`: Dependency resolution error if any. /// - `file_info`: File information. /// - `file_selected`: Mutable reference to selected file index. /// - `file_tree_expanded`: Set of expanded file tree nodes. /// - `files_error`: File resolution error if any. /// - `service_info`: Service impact information. /// - `service_selected`: Mutable reference to selected service index. /// - `services_loaded`: Whether services are loaded. /// - `services_error`: Service resolution error if any. /// - `sandbox_info`: Sandbox information. /// - `sandbox_selected`: Mutable reference to selected sandbox index. /// - `sandbox_tree_expanded`: Set of expanded sandbox tree nodes. /// - `sandbox_loaded`: Whether sandbox is loaded. /// - `sandbox_error`: Sandbox resolution error if any. /// - `selected_optdepends`: Selected optional dependencies map. /// - `cascade_mode`: Cascade removal mode. /// - `content_rect`: Content area rectangle. /// /// Output: /// - Returns vector of lines to render for the active tab. /// /// Details: /// - Delegates to tab-specific render functions based on the active tab. /// - Each tab receives only the data it needs for rendering. #[allow(clippy::too_many_arguments)] pub fn render_tab_content( app: &AppState, tab: PreflightTab, items: &[PackageItem], action: PreflightAction, summary: Option<&PreflightSummaryData>, header_chips: &PreflightHeaderChips, dependency_info: &[DependencyInfo], dep_selected: &mut usize, dep_tree_expanded: &HashSet<String>, deps_error: Option<&String>, file_info: &[PackageFileInfo], file_selected: &mut usize, file_tree_expanded: &HashSet<String>, files_error: Option<&String>, service_info: &[ServiceImpact], service_selected: &mut usize, services_loaded: bool, services_error: Option<&String>, sandbox_info: &[SandboxInfo], sandbox_selected: &mut usize, sandbox_tree_expanded: &HashSet<String>, sandbox_loaded: bool, sandbox_error: Option<&String>, selected_optdepends: &HashMap<String, HashSet<String>>, cascade_mode: CascadeMode, content_rect: Rect, ) -> Vec<Line<'static>> { match tab { PreflightTab::Summary => render_summary_tab( app, items, action, summary, header_chips, dependency_info, cascade_mode, content_rect, ), PreflightTab::Deps => render_deps_tab( app, items, action, dependency_info, dep_selected, dep_tree_expanded, deps_error, content_rect, ), PreflightTab::Files => render_files_tab( app, items, file_info, file_selected, file_tree_expanded, files_error, content_rect, ), PreflightTab::Services => render_services_tab( app, service_info, service_selected, services_loaded, services_error, content_rect, ), PreflightTab::Sandbox => { let ctx = SandboxTabContext { items, sandbox_info, sandbox_tree_expanded, sandbox_loaded, sandbox_error, selected_optdepends, content_rect, }; render_sandbox_tab(app, &ctx, sandbox_selected) } } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/helpers/widget.rs
src/ui/modals/preflight/helpers/widget.rs
use ratatui::{ style::{Modifier, Style}, text::{Line, Span}, widgets::{Block, BorderType, Borders, Paragraph, Wrap}, }; use crate::theme::theme; /// What: Builder for creating styled Paragraph widgets for preflight modal. /// /// Inputs: None (struct definition). /// /// Output: None (struct definition). /// /// Details: Provides a fluent interface for building Paragraph widgets with consistent styling. pub struct ParagraphBuilder { /// Lines of text to display. lines: Vec<Line<'static>>, /// Optional title for the paragraph. title: Option<String>, /// Scroll offset (x, y). scroll_offset: (u16, u16), /// Text color. text_color: ratatui::style::Color, /// Background color. bg_color: ratatui::style::Color, /// Border color. border_color: ratatui::style::Color, } impl ParagraphBuilder { /// What: Create a new `ParagraphBuilder` with default values. /// /// Inputs: None. /// /// Output: Returns a new `ParagraphBuilder` instance. /// /// Details: Initializes with empty lines and default colors from theme. pub fn new() -> Self { let th = theme(); Self { lines: Vec::new(), title: None, scroll_offset: (0, 0), text_color: th.text, bg_color: th.crust, border_color: th.lavender, } } /// What: Set the content lines for the paragraph. /// /// Inputs: /// - `lines`: Vector of lines to display. /// /// Output: Returns self for method chaining. /// /// Details: Replaces any existing lines with the provided lines. pub fn with_lines(mut self, lines: Vec<Line<'static>>) -> Self { self.lines = lines; self } /// What: Set the title for the paragraph block. /// /// Inputs: /// - `title`: Title string to display in the block border. /// /// Output: Returns self for method chaining. /// /// Details: The title will be styled with bold modifier and border color. pub fn with_title(mut self, title: String) -> Self { self.title = Some(title); self } /// What: Set the scroll offset for the paragraph. /// /// Inputs: /// - `offset`: Tuple of (vertical, horizontal) scroll offset. /// /// Output: Returns self for method chaining. /// /// Details: Used for scrolling content within the paragraph widget. pub const fn with_scroll(mut self, offset: (u16, u16)) -> Self { self.scroll_offset = offset; self } /// What: Set the text color. /// /// Inputs: /// - `color`: Text color to use. /// /// Output: Returns self for method chaining. /// /// Details: Overrides default text color from theme. pub const fn with_text_color(mut self, color: ratatui::style::Color) -> Self { self.text_color = color; self } /// What: Set the background color. /// /// Inputs: /// - `color`: Background color to use. /// /// Output: Returns self for method chaining. /// /// Details: Overrides default background color from theme. pub const fn with_bg_color(mut self, color: ratatui::style::Color) -> Self { self.bg_color = color; self } /// What: Set the border color. /// /// Inputs: /// - `color`: Border color to use. /// /// Output: Returns self for method chaining. /// /// Details: Overrides default border color from theme. pub const fn with_border_color(mut self, color: ratatui::style::Color) -> Self { self.border_color = color; self } /// What: Build the final Paragraph widget. /// /// Inputs: None. /// /// Output: Returns a fully configured Paragraph widget. /// /// Details: /// - Applies all styling, borders, title, and scroll settings. /// - Uses double border type and left/top/right borders only. pub fn build(self) -> Paragraph<'static> { let block = if let Some(title) = self.title { Block::default() .title(Span::styled( title, Style::default() .fg(self.border_color) .add_modifier(Modifier::BOLD), )) .borders(Borders::LEFT | Borders::TOP | Borders::RIGHT) .border_type(BorderType::Double) .border_style(Style::default().fg(self.border_color)) .style(Style::default().bg(self.bg_color)) } else { Block::default() .borders(Borders::LEFT | Borders::TOP | Borders::RIGHT) .border_type(BorderType::Double) .border_style(Style::default().fg(self.border_color)) .style(Style::default().bg(self.bg_color)) }; Paragraph::new(self.lines) .style(Style::default().fg(self.text_color).bg(self.bg_color)) .wrap(Wrap { trim: true }) .scroll(self.scroll_offset) .block(block) } } impl Default for ParagraphBuilder { fn default() -> Self { Self::new() } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/helpers/sync_dependencies_tests.rs
src/ui/modals/preflight/helpers/sync_dependencies_tests.rs
//! Unit tests for `sync_dependencies` function. use super::sync; use crate::state::AppState; use crate::state::modal::{ DependencyInfo, DependencySource, DependencyStatus, PreflightAction, PreflightTab, }; use crate::state::{PackageItem, Source}; /// What: Test `sync_dependencies` early return for Remove action. /// /// Inputs: /// - `action`: `PreflightAction::Remove` /// - `dependency_info`: Empty vector /// /// Output: /// - `dependency_info` remains unchanged /// /// Details: /// - Verifies that dependency sync is skipped for remove actions. #[test] fn test_sync_dependencies_early_return_remove() { let app = AppState::default(); let items = vec![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, }]; let action = PreflightAction::Remove; let tab = PreflightTab::Deps; let mut dependency_info = Vec::new(); let mut dep_selected = 0; sync::sync_dependencies( &app, &items, action, tab, &mut dependency_info, &mut dep_selected, ); assert!(dependency_info.is_empty()); } /// What: Test `sync_dependencies` early return when not on Deps tab. /// /// Inputs: /// - `tab`: `PreflightTab::Summary` /// - `dependency_info`: Empty vector /// /// Output: /// - `dependency_info` remains unchanged /// /// Details: /// - Verifies that dependency sync is skipped when not on Deps tab. #[test] fn test_sync_dependencies_early_return_wrong_tab() { let app = AppState::default(); let items = vec![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, }]; let action = PreflightAction::Install; let tab = PreflightTab::Summary; let mut dependency_info = Vec::new(); let mut dep_selected = 0; sync::sync_dependencies( &app, &items, action, tab, &mut dependency_info, &mut dep_selected, ); assert!(dependency_info.is_empty()); } /// What: Test `sync_dependencies` filters dependencies by `required_by`. /// /// Inputs: /// - `app`: `AppState` with cached dependencies /// - `items`: Packages that require dependencies /// /// Output: /// - `dependency_info` contains only dependencies required by items /// /// Details: /// - Verifies that dependency filtering works correctly. #[test] #[allow(clippy::field_reassign_with_default)] fn test_sync_dependencies_filters_by_required_by() { let mut app = AppState::default(); app.install_list_deps = vec![ DependencyInfo { name: "dep1".to_string(), version: "1.0".to_string(), status: DependencyStatus::ToInstall, source: DependencySource::Official { repo: "core".to_string(), }, required_by: vec!["test-pkg".to_string()], depends_on: Vec::new(), is_core: false, is_system: false, }, DependencyInfo { name: "dep2".to_string(), version: "1.0".to_string(), status: DependencyStatus::ToInstall, source: DependencySource::Official { repo: "core".to_string(), }, required_by: vec!["other-pkg".to_string()], depends_on: Vec::new(), is_core: false, is_system: false, }, ]; let items = vec![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, }]; let action = PreflightAction::Install; let tab = PreflightTab::Deps; let mut dependency_info = Vec::new(); let mut dep_selected = 0; sync::sync_dependencies( &app, &items, action, tab, &mut dependency_info, &mut dep_selected, ); assert_eq!(dependency_info.len(), 1); assert_eq!(dependency_info[0].name, "dep1"); assert_eq!(dep_selected, 0); } /// What: Test `sync_dependencies` resets selection on first load. /// /// Inputs: /// - `dependency_info`: Empty (first load) /// - `dep_selected`: 5 /// /// Output: /// - `dep_selected` is reset to 0 /// /// Details: /// - Verifies that selection is reset on first load. #[test] #[allow(clippy::field_reassign_with_default)] fn test_sync_dependencies_resets_selection_on_first_load() { let mut app = AppState::default(); app.install_list_deps = vec![DependencyInfo { name: "dep1".to_string(), version: "1.0".to_string(), status: DependencyStatus::ToInstall, source: DependencySource::Official { repo: "core".to_string(), }, required_by: vec!["test-pkg".to_string()], depends_on: Vec::new(), is_core: false, is_system: false, }]; let items = vec![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, }]; let action = PreflightAction::Install; let tab = PreflightTab::Deps; let mut dependency_info = Vec::new(); let mut dep_selected = 5; sync::sync_dependencies( &app, &items, action, tab, &mut dependency_info, &mut dep_selected, ); assert_eq!(dep_selected, 0); } /// What: Test `sync_dependencies` does not reset selection on subsequent loads. /// /// Inputs: /// - `dependency_info`: Already populated /// - `dep_selected`: 2 /// /// Output: /// - `dep_selected` remains 2 /// /// Details: /// - Verifies that selection is preserved on subsequent syncs. #[test] #[allow(clippy::field_reassign_with_default)] fn test_sync_dependencies_preserves_selection_on_subsequent_load() { let mut app = AppState::default(); app.install_list_deps = vec![ DependencyInfo { name: "dep1".to_string(), version: "1.0".to_string(), status: DependencyStatus::ToInstall, source: DependencySource::Official { repo: "core".to_string(), }, required_by: vec!["test-pkg".to_string()], depends_on: Vec::new(), is_core: false, is_system: false, }, DependencyInfo { name: "dep2".to_string(), version: "1.0".to_string(), status: DependencyStatus::ToInstall, source: DependencySource::Official { repo: "core".to_string(), }, required_by: vec!["test-pkg".to_string()], depends_on: Vec::new(), is_core: false, is_system: false, }, ]; let items = vec![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, }]; let action = PreflightAction::Install; let tab = PreflightTab::Deps; let mut dependency_info = vec![DependencyInfo { name: "dep1".to_string(), version: "1.0".to_string(), status: DependencyStatus::ToInstall, source: DependencySource::Official { repo: "core".to_string(), }, required_by: vec!["test-pkg".to_string()], depends_on: Vec::new(), is_core: false, is_system: false, }]; let mut dep_selected = 2; sync::sync_dependencies( &app, &items, action, tab, &mut dependency_info, &mut dep_selected, ); assert_eq!(dep_selected, 2); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/helpers/sync.rs
src/ui/modals/preflight/helpers/sync.rs
use crate::state::modal::{ DependencyInfo, PackageFileInfo, PreflightAction, PreflightTab, ServiceImpact, }; use crate::state::{AppState, PackageItem}; /// What: Synchronize dependency information from app cache to preflight modal. /// /// Inputs: /// - `app`: Application state containing cached dependencies /// - `items`: Packages currently in preflight review /// - `action`: Whether this is an install or remove action /// - `tab`: Current active tab /// - `dependency_info`: Mutable reference to dependency info in modal /// - `dep_selected`: Mutable reference to selected dependency index /// /// Output: /// - Updates `dependency_info` and `dep_selected` if cache has new data /// /// Details: /// - Only syncs when action is Install and tab is Deps /// - Filters dependencies to only those required by current items /// - Handles background resolution state checking pub fn sync_dependencies( app: &AppState, items: &[PackageItem], action: PreflightAction, tab: PreflightTab, dependency_info: &mut Vec<DependencyInfo>, dep_selected: &mut usize, ) { if !matches!(action, PreflightAction::Install) { return; } // Sync dependencies when: // 1. On Deps tab (to show dependency list) // 2. On Summary tab (to show conflicts) // 3. Or when dependency_info is empty (first load) let should_sync = dependency_info.is_empty() || matches!(tab, PreflightTab::Deps) || matches!(tab, PreflightTab::Summary); if !should_sync { return; } if !app.install_list_deps.is_empty() { // Get set of current package names for filtering let item_names: std::collections::HashSet<String> = items.iter().map(|i| i.name.clone()).collect(); // Filter to only show dependencies required by current items let filtered: Vec<DependencyInfo> = app .install_list_deps .iter() .filter(|dep| { // Show dependency if any current item requires it dep.required_by .iter() .any(|req_by| item_names.contains(req_by)) }) .cloned() .collect(); tracing::debug!( "[UI] Deps sync: tab={:?}, cache={}, filtered={}, items={:?}, resolving={}, current={}", tab, app.install_list_deps.len(), filtered.len(), item_names, app.deps_resolving, dependency_info.len() ); // Always update when cache has data and we're on a tab that needs it // This ensures conflicts are shown in Summary tab and dependencies in Deps tab // Only reset selection if dependencies were empty (first load) - don't reset on every render let was_empty = dependency_info.is_empty(); let old_len = dependency_info.len(); *dependency_info = filtered; let new_len = dependency_info.len(); if old_len != new_len { tracing::info!( "[UI] Deps sync: Updated dependency_info from {} to {} entries (was_empty={})", old_len, new_len, was_empty ); } // Only reset selection if this is the first load (was empty), not on every render if was_empty { *dep_selected = 0; } } else if dependency_info.is_empty() { // Check if background resolution is in progress if app.preflight_deps_resolving || app.deps_resolving { // Background resolution in progress - UI will show loading state tracing::debug!( "[UI] Deps tab: background resolution in progress, items={:?}", items.iter().map(|i| &i.name).collect::<Vec<_>>() ); } else { // Cache is empty and no resolution in progress - trigger background resolution // This will be handled by the event handler when switching to Deps tab tracing::debug!( "[UI] Deps tab: cache is empty, will auto-resolve, items={:?}", items.iter().map(|i| &i.name).collect::<Vec<_>>() ); } } } /// What: Filter cached files to match current items. /// /// Inputs: /// - `app`: Application state with cached files /// - `item_names`: Set of current package names /// /// Output: /// - Vector of matching cached files. fn filter_cached_files( app: &AppState, item_names: &std::collections::HashSet<String>, ) -> Vec<PackageFileInfo> { app.install_list_files .iter() .filter(|file_info| item_names.contains(&file_info.name)) .cloned() .collect() } /// What: Log detailed cache lookup information for debugging. /// /// Inputs: /// - `item_names`: Set of current package names /// - `app`: Application state with cached files /// - `cached_files`: Filtered cached files /// /// Output: /// - None (logs to tracing). fn log_cache_lookup( item_names: &std::collections::HashSet<String>, app: &AppState, cached_files: &[PackageFileInfo], ) { if item_names.is_empty() { return; } let cache_package_names: Vec<String> = app .install_list_files .iter() .map(|f| f.name.clone()) .collect(); let missing_from_cache: Vec<String> = item_names .iter() .filter(|item_name| !cache_package_names.contains(item_name)) .cloned() .collect(); if !missing_from_cache.is_empty() { tracing::debug!( "[UI] sync_files: Cache lookup - items={:?}, cache_has={:?}, missing_from_cache={:?}, matched={:?}", item_names.iter().collect::<Vec<_>>(), cache_package_names, missing_from_cache, cached_files.iter().map(|f| &f.name).collect::<Vec<_>>() ); } } /// What: Build complete file info list including empty entries for missing packages. /// /// Inputs: /// - `items`: Current packages /// - `cached_files_map`: Map of cached files by package name /// /// Output: /// - Complete file info list with all items represented. fn build_complete_file_info( items: &[PackageItem], cached_files_map: &std::collections::HashMap<String, PackageFileInfo>, ) -> Vec<PackageFileInfo> { items .iter() .map(|item| { cached_files_map .get(&item.name) .cloned() .unwrap_or_else(|| { tracing::debug!( "[UI] sync_files: Creating empty entry for '{}' (not found in cache map)", item.name ); PackageFileInfo { name: item.name.clone(), files: Vec::new(), total_count: 0, new_count: 0, changed_count: 0, removed_count: 0, config_count: 0, pacnew_candidates: 0, pacsave_candidates: 0, } }) }) .collect() } /// What: Check if file info needs to be updated. /// /// Inputs: /// - `file_info`: Current file info in modal /// - `items`: Current packages /// - `complete_file_info`: Complete file info to compare /// /// Output: /// - `true` if update is needed, `false` otherwise. fn should_update_file_info( file_info: &[PackageFileInfo], items: &[PackageItem], complete_file_info: &[PackageFileInfo], ) -> bool { file_info.is_empty() || file_info.len() != items.len() || complete_file_info.iter().any(|new_info| { !file_info.iter().any(|old_info| { old_info.name == new_info.name && old_info.total_count == new_info.total_count }) }) } /// What: Apply file info update to modal. /// /// Inputs: /// - `file_info`: Mutable reference to file info in modal /// - `file_selected`: Mutable reference to selected index /// - `complete_file_info`: Complete file info to apply /// - `cached_files`: Cached files for logging /// /// Output: /// - Updates modal state. fn apply_file_info_update( file_info: &mut Vec<PackageFileInfo>, file_selected: &mut usize, complete_file_info: Vec<PackageFileInfo>, cached_files: &[PackageFileInfo], ) { let old_file_info_len = file_info.len(); let missing_count = complete_file_info .iter() .filter(|f| f.total_count == 0) .count(); tracing::info!( "[UI] sync_files: Found {} cached file entries, {} missing (creating empty entries), modal had {}, updating...", cached_files.len(), missing_count, old_file_info_len ); for file_info_entry in &complete_file_info { if file_info_entry.total_count > 0 { tracing::info!( "[UI] sync_files: Package '{}' - total={}, new={}, changed={}, removed={}, config={}", file_info_entry.name, file_info_entry.total_count, file_info_entry.new_count, file_info_entry.changed_count, file_info_entry.removed_count, file_info_entry.config_count ); } else { tracing::debug!( "[UI] sync_files: Package '{}' - no file info yet (empty entry)", file_info_entry.name ); } } tracing::debug!( "[UI] sync_files: Syncing {} file infos ({} with data, {} empty) to Preflight modal", complete_file_info.len(), cached_files.len(), missing_count ); *file_info = complete_file_info; if *file_selected >= file_info.len() { *file_selected = 0; } tracing::info!( "[UI] sync_files: Successfully synced, modal now has {} file entries (was {})", file_info.len(), old_file_info_len ); } /// What: Synchronize file information from app cache to preflight modal. /// /// Inputs: /// - `app`: Application state containing cached file info /// - `items`: Packages currently in preflight review /// - `tab`: Current active tab /// - `file_info`: Mutable reference to file info in modal /// - `file_selected`: Mutable reference to selected file index /// /// Output: /// - Updates `file_info` and `file_selected` if cache has new data /// /// Details: /// - Only syncs when tab is Files /// - Filters files to only those belonging to current items /// - Handles background resolution state checking pub fn sync_files( app: &AppState, items: &[PackageItem], tab: PreflightTab, file_info: &mut Vec<PackageFileInfo>, file_selected: &mut usize, ) { if !matches!(tab, PreflightTab::Files) { return; } let item_names: std::collections::HashSet<String> = items.iter().map(|i| i.name.clone()).collect(); let cached_files = filter_cached_files(app, &item_names); log_cache_lookup(&item_names, app, &cached_files); let cached_files_map: std::collections::HashMap<String, PackageFileInfo> = cached_files .iter() .map(|f| (f.name.clone(), f.clone())) .collect(); let complete_file_info = build_complete_file_info(items, &cached_files_map); tracing::debug!( "[UI] sync_files: items={}, cache_size={}, cached_matching={}, modal_size={}, complete={}, resolving={}/{}", items.len(), app.install_list_files.len(), cached_files.len(), file_info.len(), complete_file_info.len(), app.preflight_files_resolving, app.files_resolving ); if should_update_file_info(file_info, items, &complete_file_info) { apply_file_info_update(file_info, file_selected, complete_file_info, &cached_files); } else { if app.preflight_files_resolving || app.files_resolving { tracing::debug!( "[UI] sync_files: Background resolution in progress, items={:?}", items.iter().map(|i| &i.name).collect::<Vec<_>>() ); } else if cached_files.is_empty() { tracing::debug!( "[UI] sync_files: No cached files available and not resolving, items={:?}", items.iter().map(|i| &i.name).collect::<Vec<_>>() ); } else { tracing::debug!( "[UI] sync_files: File info already synced (modal has {} entries, cache has {} matching), no update needed", file_info.len(), cached_files.len() ); } tracing::debug!( "[UI] sync_files: No update needed, file_info already in sync (modal={}, items={}, complete={})", file_info.len(), items.len(), complete_file_info.len() ); } } /// What: Synchronize service impact information from app cache to preflight modal. /// /// Inputs: /// - `app`: Application state containing cached service info /// - `items`: Packages currently in preflight review /// - `action`: Whether this is an install or remove action /// - `service_info`: Mutable reference to service info in modal /// - `service_selected`: Mutable reference to selected service index /// - `services_loaded`: Mutable reference to loaded flag /// /// Output: /// - Updates `service_info`, `service_selected`, and `services_loaded` if cache has new data /// /// Details: /// - Syncs for both Install and Remove actions when no resolution is in progress /// - Filters services to only those provided by current items /// - Handles cache file checking for empty results /// - Syncs resolved service impacts from background resolution pub fn sync_services( app: &AppState, items: &[PackageItem], _action: PreflightAction, service_info: &mut Vec<ServiceImpact>, service_selected: &mut usize, services_loaded: &mut bool, ) { if app.services_resolving || app.preflight_services_resolving { return; } let item_names: std::collections::HashSet<String> = items.iter().map(|i| i.name.clone()).collect(); let cached_services: Vec<_> = app .install_list_services .iter() .filter(|s| s.providers.iter().any(|p| item_names.contains(p))) .cloned() .collect(); // Sync results from background resolution if available if !cached_services.is_empty() { let needs_update = service_info.is_empty() || cached_services.len() != service_info.len() || cached_services.iter().any(|cached| { !service_info .iter() .any(|existing| existing.unit_name == cached.unit_name) }); if needs_update { tracing::debug!( "[UI] Syncing {} services from background resolution to Preflight modal", cached_services.len() ); *service_info = cached_services; *services_loaded = true; } } else if service_info.is_empty() && !*services_loaded { // Check if cache file exists with matching signature (even if empty) let cache_check_start = std::time::Instant::now(); let cache_exists = if items.is_empty() { false } else { let signature = crate::app::services_cache::compute_signature(items); let result = crate::app::services_cache::load_cache(&app.services_cache_path, &signature) .is_some(); let cache_duration = cache_check_start.elapsed(); if cache_duration.as_millis() > 10 { tracing::warn!( "[UI] Services cache check took {:?} (slow!)", cache_duration ); } result }; if cache_exists { // Cache exists but is empty - this is valid, means no services found tracing::debug!("[UI] Using cached service impacts (empty - no services found)"); *services_loaded = true; } } if !service_info.is_empty() && *service_selected >= service_info.len() { *service_selected = service_info.len().saturating_sub(1); } } /// What: Check if sandbox resolution is in progress. /// /// Inputs: /// - `app`: Application state /// /// Output: /// - Returns true if sandbox resolution is in progress const fn is_sandbox_resolving(app: &AppState) -> bool { app.preflight_sandbox_resolving || app.sandbox_resolving } /// What: Check if cached sandbox data needs to be updated. /// /// Inputs: /// - `sandbox_info`: Current sandbox info in modal /// - `cached_sandbox`: Cached sandbox data from app state /// /// Output: /// - Returns true if update is needed fn needs_sandbox_update( sandbox_info: &[crate::logic::sandbox::SandboxInfo], cached_sandbox: &[crate::logic::sandbox::SandboxInfo], ) -> bool { sandbox_info.is_empty() || cached_sandbox.len() != sandbox_info.len() || cached_sandbox.iter().any(|cached| { !sandbox_info .iter() .any(|existing| existing.package_name == cached.package_name) }) } /// What: Log detailed dependency information for sandbox entries. /// /// Inputs: /// - `cached_sandbox`: Cached sandbox data to log fn log_sandbox_dependencies(cached_sandbox: &[crate::logic::sandbox::SandboxInfo]) { tracing::info!( "[UI] sync_sandbox: Found {} cached sandbox entries matching current items", cached_sandbox.len() ); for cached in cached_sandbox { let total_deps = cached.depends.len() + cached.makedepends.len() + cached.checkdepends.len() + cached.optdepends.len(); let installed_deps = cached.depends.iter().filter(|d| d.is_installed).count() + cached.makedepends.iter().filter(|d| d.is_installed).count() + cached .checkdepends .iter() .filter(|d| d.is_installed) .count() + cached.optdepends.iter().filter(|d| d.is_installed).count(); tracing::info!( "[UI] sync_sandbox: Package '{}' - total_deps={}, installed_deps={}, depends={}, makedepends={}, checkdepends={}, optdepends={}", cached.package_name, total_deps, installed_deps, cached.depends.len(), cached.makedepends.len(), cached.checkdepends.len(), cached.optdepends.len() ); } } /// What: Sync cached sandbox data to modal if update is needed. /// /// Inputs: /// - `sandbox_info`: Mutable reference to sandbox info in modal /// - `sandbox_loaded`: Mutable reference to loaded flag /// - `cached_sandbox`: Cached sandbox data from app state /// /// Output: /// - Updates `sandbox_info` and `sandbox_loaded` if needed fn sync_cached_sandbox( sandbox_info: &mut Vec<crate::logic::sandbox::SandboxInfo>, sandbox_loaded: &mut bool, cached_sandbox: Vec<crate::logic::sandbox::SandboxInfo>, ) { if !needs_sandbox_update(sandbox_info, &cached_sandbox) { tracing::debug!("[UI] sync_sandbox: No update needed, sandbox_info already in sync"); return; } log_sandbox_dependencies(&cached_sandbox); tracing::info!( "[UI] sync_sandbox: Syncing {} sandbox info entries from background resolution to Preflight modal (was_empty={}, len_diff={})", cached_sandbox.len(), sandbox_info.is_empty(), cached_sandbox.len() != sandbox_info.len() ); *sandbox_info = cached_sandbox; *sandbox_loaded = true; tracing::debug!( "[UI] sync_sandbox: Successfully synced sandbox info, loaded={}", *sandbox_loaded ); } /// What: Check if sandbox cache file exists. /// /// Inputs: /// - `app`: Application state /// - `items`: Packages to check cache for /// /// Output: /// - Returns true if cache file exists fn check_sandbox_cache(app: &AppState, items: &[PackageItem]) -> bool { let cache_start = std::time::Instant::now(); let signature = crate::app::sandbox_cache::compute_signature(items); let cache_exists = crate::app::sandbox_cache::load_cache(&app.sandbox_cache_path, &signature).is_some(); let cache_duration = cache_start.elapsed(); if cache_duration.as_millis() > 10 { tracing::warn!("[UI] Sandbox cache check took {:?} (slow!)", cache_duration); } cache_exists } /// What: Handle empty sandbox info case by checking cache or resolution state. /// /// Inputs: /// - `app`: Application state /// - `items`: Packages currently in preflight review /// - `aur_items`: AUR packages only /// - `sandbox_loaded`: Mutable reference to loaded flag /// /// Output: /// - Updates `sandbox_loaded` if appropriate fn handle_empty_sandbox_info( app: &AppState, items: &[PackageItem], aur_items: &[&PackageItem], sandbox_loaded: &mut bool, ) { tracing::debug!( "[UI] sync_sandbox: Empty sandbox_info, checking cache for items={:?}", items.iter().map(|i| &i.name).collect::<Vec<_>>() ); let cache_exists = check_sandbox_cache(app, items); if cache_exists { if !is_sandbox_resolving(app) { tracing::info!( "[UI] sync_sandbox: Using cached sandbox info (empty - no sandbox info found)" ); *sandbox_loaded = true; } return; } if aur_items.is_empty() { tracing::debug!("[UI] sync_sandbox: No AUR packages, marking as loaded"); *sandbox_loaded = true; return; } if is_sandbox_resolving(app) { tracing::info!( "[UI] sync_sandbox: Background resolution in progress, items={:?}, aur_items={:?}", items.iter().map(|i| &i.name).collect::<Vec<_>>(), aur_items.iter().map(|i| &i.name).collect::<Vec<_>>() ); } else { tracing::debug!( "[UI] sync_sandbox: No cache and no resolution in progress, will trigger on tab switch" ); } } /// What: Handle remove action case for sandbox sync. /// /// Inputs: /// - `items`: Packages currently in preflight review /// - `sandbox_loaded`: Mutable reference to loaded flag /// /// Output: /// - Updates `sandbox_loaded` if no AUR packages fn handle_remove_action(items: &[PackageItem], sandbox_loaded: &mut bool) { if !items .iter() .any(|p| matches!(p.source, crate::state::Source::Aur)) { tracing::debug!("[UI] sync_sandbox: Remove action, no AUR packages, marking as loaded"); *sandbox_loaded = true; } } /// What: Synchronize sandbox information from app cache to preflight modal. /// /// Inputs: /// - `app`: Application state containing cached sandbox info /// - `items`: Packages currently in preflight review /// - `action`: Whether this is an install or remove action /// - `tab`: Current active tab /// - `sandbox_info`: Mutable reference to sandbox info in modal /// - `sandbox_selected`: Mutable reference to selected sandbox index /// - `sandbox_loaded`: Mutable reference to loaded flag /// /// Output: /// - Updates `sandbox_info`, `sandbox_selected`, and `sandbox_loaded` if cache has new data /// /// Details: /// - Only syncs when action is Install and tab is Sandbox /// - Filters sandbox info to only AUR packages /// - Handles cache file checking and background resolution state /// - Includes comprehensive logging for dependency loading verification pub fn sync_sandbox( app: &AppState, items: &[PackageItem], action: PreflightAction, tab: PreflightTab, sandbox_info: &mut Vec<crate::logic::sandbox::SandboxInfo>, sandbox_loaded: &mut bool, ) { if matches!(action, PreflightAction::Remove) { handle_remove_action(items, sandbox_loaded); return; } if !matches!(action, PreflightAction::Install) || !matches!(tab, PreflightTab::Sandbox) { return; } // Show all packages, but only analyze AUR packages let aur_items: Vec<_> = items .iter() .filter(|p| matches!(p.source, crate::state::Source::Aur)) .collect(); tracing::debug!( "[UI] sync_sandbox: items={}, aur_items={}, cache_size={}, modal_size={}, loaded={}, resolving={}/{}", items.len(), aur_items.len(), app.install_list_sandbox.len(), sandbox_info.len(), *sandbox_loaded, app.preflight_sandbox_resolving, app.sandbox_resolving ); // Check if we have cached sandbox info from app state that matches current items let item_names: std::collections::HashSet<String> = items.iter().map(|i| i.name.clone()).collect(); let cached_sandbox: Vec<_> = app .install_list_sandbox .iter() .filter(|s| item_names.contains(&s.package_name)) .cloned() .collect(); // Sync results from background resolution if available if !cached_sandbox.is_empty() { sync_cached_sandbox(sandbox_info, sandbox_loaded, cached_sandbox); } // If sandbox_info is empty and we haven't loaded yet, check cache or trigger resolution if sandbox_info.is_empty() && !*sandbox_loaded && !is_sandbox_resolving(app) { handle_empty_sandbox_info(app, items, &aur_items, sandbox_loaded); } // Also check if we have sandbox_info already populated (from previous sync or initial load) // This ensures we show data even if cached_sandbox is empty but sandbox_info has data // But don't mark as loaded if resolution is still in progress if !sandbox_info.is_empty() && !*sandbox_loaded && !is_sandbox_resolving(app) { tracing::info!( "[UI] sync_sandbox: sandbox_info has {} entries, marking as loaded", sandbox_info.len() ); *sandbox_loaded = true; } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/helpers/mod.rs
src/ui/modals/preflight/helpers/mod.rs
use ratatui::{ style::{Modifier, Style}, text::{Line, Span}, }; use crate::i18n; use crate::state::AppState; use crate::state::modal::PreflightHeaderChips; use crate::theme::theme; /// Field extraction helpers for preflight modal. pub mod extract; /// Layout calculation helpers for preflight modal. pub mod layout; /// Scroll handling helpers for preflight modal. pub mod scroll; /// Sync information helpers for preflight modal. pub mod sync; /// Tab rendering helpers for preflight modal. pub mod tabs; /// Widget building helpers for preflight modal. pub mod widget; // Re-export byte formatting functions from helpers pub use crate::ui::helpers::{format_bytes, format_signed_bytes}; /// What: Format count with incomplete data indicator when data is still resolving. /// /// Inputs: /// - `count`: Current count of resolved items. /// - `total_items`: Total number of items expected. /// - `is_resolving`: Whether resolution is still in progress. /// /// Output: /// - Returns formatted string like "7", "7...", or "7/9" depending on state. /// /// Details: /// - Shows plain count if complete or not resolving. /// - Shows count with "..." if partial and still resolving. /// - Shows "count/total" if complete but count doesn't match total (shouldn't happen normally). pub fn format_count_with_indicator(count: usize, total_items: usize, is_resolving: bool) -> String { if !is_resolving { // Resolution complete, show actual count format!("{count}") } else if count < total_items { // Still resolving and we have partial data format!("{count}...") } else { // Resolving but count matches total (shouldn't happen, but be safe) format!("{count}") } } /// What: Render header chips as a compact horizontal line of metrics. /// /// Inputs: /// - `app`: Application state for i18n. /// - `chips`: Header chip data containing counts and sizes. /// /// Output: /// - Returns a `Line` containing styled chip spans separated by spaces. /// /// Details: /// - Formats package count, download size, install delta, AUR count, and risk score /// as compact chips. Risk score uses color coding (green/yellow/red) based on level. pub fn render_header_chips(app: &AppState, chips: &PreflightHeaderChips) -> Line<'static> { let th = theme(); let mut spans = Vec::new(); // Package count chip let package_count = chips.package_count; let aur_count = chips.aur_count; let pkg_text = if aur_count > 0 { format!("{package_count} ({aur_count} AUR)") } else { format!("{package_count}") }; spans.push(Span::styled( format!("[{pkg_text}]"), Style::default() .fg(th.sapphire) .add_modifier(Modifier::BOLD), )); // Download size chip (always shown) spans.push(Span::styled(" ", Style::default())); spans.push(Span::styled( i18n::t_fmt1( app, "app.modals.preflight.header_chips.download_label", format_bytes(chips.download_bytes), ), Style::default().fg(th.sapphire), )); // Install delta chip (always shown) spans.push(Span::styled(" ", Style::default())); let delta_color = match chips.install_delta_bytes.cmp(&0) { std::cmp::Ordering::Greater => th.green, std::cmp::Ordering::Less => th.red, std::cmp::Ordering::Equal => th.overlay1, // Neutral color for zero }; spans.push(Span::styled( i18n::t_fmt1( app, "app.modals.preflight.header_chips.size_label", format_signed_bytes(chips.install_delta_bytes), ), Style::default().fg(delta_color), )); // Risk score chip (always shown) spans.push(Span::styled(" ", Style::default())); let risk_label = match chips.risk_level { crate::state::modal::RiskLevel::Low => { i18n::t(app, "app.modals.preflight.header_chips.risk_low") } crate::state::modal::RiskLevel::Medium => { i18n::t(app, "app.modals.preflight.header_chips.risk_medium") } crate::state::modal::RiskLevel::High => { i18n::t(app, "app.modals.preflight.header_chips.risk_high") } }; let risk_color = match chips.risk_level { crate::state::modal::RiskLevel::Low => th.green, crate::state::modal::RiskLevel::Medium => th.yellow, crate::state::modal::RiskLevel::High => th.red, }; spans.push(Span::styled( format!("[Risk: {} ({})]", risk_label, chips.risk_score), Style::default().fg(risk_color).add_modifier(Modifier::BOLD), )); Line::from(spans) } #[cfg(test)] mod format_tests; #[cfg(test)] mod layout_tests; #[cfg(test)] mod render_tests; #[cfg(test)] mod sync_dependencies_tests; #[cfg(test)] mod sync_files_tests; #[cfg(test)] mod sync_sandbox_tests; #[cfg(test)] mod sync_services_tests;
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/helpers/layout.rs
src/ui/modals/preflight/helpers/layout.rs
use ratatui::{ layout::{Constraint, Direction, Layout}, prelude::Rect, }; /// What: Calculate modal layout dimensions and split into content and keybinds areas. /// /// Inputs: /// - `area`: Full screen area used to center the modal /// /// Output: /// - Returns a tuple of (`modal_rect`, `content_rect`, `keybinds_rect`) /// /// Details: /// - Calculates centered modal size (max 96x32, with 6/8 pixel margins) /// - Splits modal into content area and keybinds pane (4 lines for keybinds) /// - Returns the full modal rect, content rect, and keybinds rect pub fn calculate_modal_layout(area: Rect) -> (Rect, Rect, Rect) { // Calculate modal size and position let w = area.width.saturating_sub(6).min(96); let h = area.height.saturating_sub(8).min(32); let x = area.x + (area.width.saturating_sub(w)) / 2; let y = area.y + (area.height.saturating_sub(h)) / 2; let rect = Rect { x, y, width: w, height: h, }; // Split rect into content area and keybinds pane (reserve 4 lines for keybinds to account for borders) // With double borders, we need: 1 top border + 2 content lines + 1 bottom border = 4 lines minimum let keybinds_height = 4; let layout = Layout::default() .direction(Direction::Vertical) .constraints([Constraint::Min(1), Constraint::Length(keybinds_height)]) .split(rect); let content_rect = layout[0]; let keybinds_rect = layout[1]; (rect, content_rect, keybinds_rect) }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/helpers/format_tests.rs
src/ui/modals/preflight/helpers/format_tests.rs
//! Unit tests for `format_bytes` and `format_signed_bytes` functions. use super::{format_bytes, format_signed_bytes}; /// What: Test `format_bytes` with zero bytes. /// /// Inputs: /// - `value`: 0 bytes /// /// Output: /// - Returns "0 B" /// /// Details: /// - Verifies that zero bytes are formatted correctly without decimal places. #[test] fn test_format_bytes_zero() { assert_eq!(format_bytes(0), "0 B"); } /// What: Test `format_bytes` with single byte. /// /// Inputs: /// - `value`: 1 byte /// /// Output: /// - Returns "1 B" /// /// Details: /// - Verifies that single bytes are formatted without decimal places. #[test] fn test_format_bytes_one() { assert_eq!(format_bytes(1), "1 B"); } /// What: Test `format_bytes` with bytes less than 1 KiB. /// /// Inputs: /// - `value`: 1023 bytes /// /// Output: /// - Returns "1023 B" /// /// Details: /// - Verifies that bytes less than 1024 are formatted in bytes without decimal places. #[test] fn test_format_bytes_less_than_kib() { assert_eq!(format_bytes(1023), "1023 B"); } /// What: Test `format_bytes` with exactly 1 KiB. /// /// Inputs: /// - `value`: 1024 bytes /// /// Output: /// - Returns "1.0 KiB" /// /// Details: /// - Verifies that exactly 1024 bytes converts to 1.0 KiB with one decimal place. #[test] fn test_format_bytes_one_kib() { assert_eq!(format_bytes(1024), "1.0 KiB"); } /// What: Test `format_bytes` with values between KiB and MiB. /// /// Inputs: /// - `value`: 1536 bytes (1.5 KiB) /// /// Output: /// - Returns "1.5 KiB" /// /// Details: /// - Verifies that fractional KiB values are formatted with one decimal place. #[test] fn test_format_bytes_fractional_kib() { assert_eq!(format_bytes(1536), "1.5 KiB"); } /// What: Test `format_bytes` with exactly 1 MiB. /// /// Inputs: /// - `value`: 1048576 bytes (1024 * 1024) /// /// Output: /// - Returns "1.0 MiB" /// /// Details: /// - Verifies that exactly 1 MiB is formatted correctly. #[test] fn test_format_bytes_one_mib() { assert_eq!(format_bytes(1_048_576), "1.0 MiB"); } /// What: Test `format_bytes` with values between MiB and GiB. /// /// Inputs: /// - `value`: 15728640 bytes (15 MiB) /// /// Output: /// - Returns "15.0 MiB" /// /// Details: /// - Verifies that MiB values are formatted with one decimal place. #[test] fn test_format_bytes_mib() { assert_eq!(format_bytes(15_728_640), "15.0 MiB"); } /// What: Test `format_bytes` with exactly 1 GiB. /// /// Inputs: /// - `value`: 1073741824 bytes (1024 * 1024 * 1024) /// /// Output: /// - Returns "1.0 GiB" /// /// Details: /// - Verifies that exactly 1 GiB is formatted correctly. #[test] fn test_format_bytes_one_gib() { assert_eq!(format_bytes(1_073_741_824), "1.0 GiB"); } /// What: Test `format_bytes` with large values (TiB). /// /// Inputs: /// - `value`: 1099511627776 bytes (1 TiB) /// /// Output: /// - Returns "1.0 TiB" /// /// Details: /// - Verifies that TiB values are formatted correctly. #[test] fn test_format_bytes_one_tib() { assert_eq!(format_bytes(1_099_511_627_776), "1.0 TiB"); } /// What: Test `format_bytes` with very large values (PiB). /// /// Inputs: /// - `value`: 1125899906842624 bytes (1 PiB) /// /// Output: /// - Returns "1.0 PiB" /// /// Details: /// - Verifies that PiB values are formatted correctly. #[test] fn test_format_bytes_one_pib() { assert_eq!(format_bytes(1_125_899_906_842_624), "1.0 PiB"); } /// What: Test `format_bytes` with fractional values. /// /// Inputs: /// - `value`: 2621440 bytes (2.5 MiB) /// /// Output: /// - Returns "2.5 MiB" /// /// Details: /// - Verifies that fractional values are rounded to one decimal place. #[test] fn test_format_bytes_fractional_mib() { assert_eq!(format_bytes(2_621_440), "2.5 MiB"); } /// What: Test `format_signed_bytes` with zero. /// /// Inputs: /// - `value`: 0 /// /// Output: /// - Returns "0 B" /// /// Details: /// - Verifies that zero is formatted without a sign prefix. #[test] fn test_format_signed_bytes_zero() { assert_eq!(format_signed_bytes(0), "0 B"); } /// What: Test `format_signed_bytes` with positive value. /// /// Inputs: /// - `value`: 1024 /// /// Output: /// - Returns "+1.0 KiB" /// /// Details: /// - Verifies that positive values get a "+" prefix. #[test] fn test_format_signed_bytes_positive() { assert_eq!(format_signed_bytes(1024), "+1.0 KiB"); } /// What: Test `format_signed_bytes` with negative value. /// /// Inputs: /// - `value`: -1024 /// /// Output: /// - Returns "-1.0 KiB" /// /// Details: /// - Verifies that negative values get a "-" prefix. #[test] fn test_format_signed_bytes_negative() { assert_eq!(format_signed_bytes(-1024), "-1.0 KiB"); } /// What: Test `format_signed_bytes` with large positive value. /// /// Inputs: /// - `value`: 1048576 (1 MiB) /// /// Output: /// - Returns "+1.0 MiB" /// /// Details: /// - Verifies that large positive values are formatted correctly with sign. #[test] fn test_format_signed_bytes_large_positive() { assert_eq!(format_signed_bytes(1_048_576), "+1.0 MiB"); } /// What: Test `format_signed_bytes` with large negative value. /// /// Inputs: /// - `value`: -1048576 (-1 MiB) /// /// Output: /// - Returns "-1.0 MiB" /// /// Details: /// - Verifies that large negative values are formatted correctly with sign. #[test] fn test_format_signed_bytes_large_negative() { assert_eq!(format_signed_bytes(-1_048_576), "-1.0 MiB"); } /// What: Test `format_signed_bytes` with fractional positive value. /// /// Inputs: /// - `value`: 1536 (1.5 KiB) /// /// Output: /// - Returns "+1.5 KiB" /// /// Details: /// - Verifies that fractional positive values are formatted correctly. #[test] fn test_format_signed_bytes_fractional_positive() { assert_eq!(format_signed_bytes(1536), "+1.5 KiB"); } /// What: Test `format_signed_bytes` with fractional negative value. /// /// Inputs: /// - `value`: -1536 (-1.5 KiB) /// /// Output: /// - Returns "-1.5 KiB" /// /// Details: /// - Verifies that fractional negative values are formatted correctly. #[test] fn test_format_signed_bytes_fractional_negative() { assert_eq!(format_signed_bytes(-1536), "-1.5 KiB"); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/helpers/extract.rs
src/ui/modals/preflight/helpers/extract.rs
use crate::logic::sandbox::SandboxInfo; use crate::state::modal::{ CascadeMode, DependencyInfo, PackageFileInfo, PreflightAction, PreflightHeaderChips, PreflightSummaryData, PreflightTab, ServiceImpact, }; use crate::state::{Modal, PackageItem}; use std::collections::{HashMap, HashSet}; /// What: Holds all extracted fields from `Modal::Preflight` variant. /// /// Inputs: None (struct definition). /// /// Output: None (struct definition). /// /// Details: Used to simplify field extraction and reduce pattern matching complexity. pub struct PreflightFields<'a> { /// Package items for the operation. pub items: &'a [PackageItem], /// Preflight action (install, remove, downgrade). pub action: &'a PreflightAction, /// Currently active preflight tab. pub tab: &'a PreflightTab, /// Optional preflight summary data. pub summary: &'a Option<Box<PreflightSummaryData>>, /// Header chip metrics. pub header_chips: &'a PreflightHeaderChips, /// Dependency information. pub dependency_info: &'a mut Vec<DependencyInfo>, /// Currently selected dependency index. pub dep_selected: &'a mut usize, /// Set of expanded dependency names in the tree view. pub dep_tree_expanded: &'a HashSet<String>, /// Optional error message for dependencies tab. pub deps_error: &'a Option<String>, /// Package file information. pub file_info: &'a mut Vec<PackageFileInfo>, /// Currently selected file index. pub file_selected: &'a mut usize, /// Set of expanded file names in the tree view. pub file_tree_expanded: &'a HashSet<String>, /// Optional error message for files tab. pub files_error: &'a Option<String>, /// Service impact information. pub service_info: &'a mut Vec<ServiceImpact>, /// Currently selected service index. pub service_selected: &'a mut usize, /// Whether services data has been loaded. pub services_loaded: &'a mut bool, /// Optional error message for services tab. pub services_error: &'a Option<String>, /// Sandbox information. pub sandbox_info: &'a mut Vec<SandboxInfo>, /// Currently selected sandbox item index. pub sandbox_selected: &'a mut usize, /// Set of expanded sandbox names in the tree view. pub sandbox_tree_expanded: &'a HashSet<String>, /// Whether sandbox data has been loaded. pub sandbox_loaded: &'a mut bool, /// Optional error message for sandbox tab. pub sandbox_error: &'a Option<String>, /// Selected optional dependencies by package name. pub selected_optdepends: &'a HashMap<String, HashSet<String>>, /// Cascade removal mode. pub cascade_mode: &'a CascadeMode, } /// What: Extract all fields from `Modal::Preflight` variant into a struct. /// /// Inputs: /// - `modal`: Mutable reference to Modal enum. /// /// Output: /// - Returns `Some(PreflightFields)` if modal is Preflight variant, `None` otherwise. /// /// Details: /// - Extracts all 25+ fields from the Preflight variant into a more manageable struct. /// - Returns None if modal is not the Preflight variant. pub fn extract_preflight_fields(modal: &mut Modal) -> Option<PreflightFields<'_>> { let Modal::Preflight { items, action, tab, summary, summary_scroll: _, header_chips, dependency_info, dep_selected, dep_tree_expanded, deps_error, file_info, file_selected, file_tree_expanded, files_error, service_info, service_selected, services_loaded, services_error, sandbox_info, sandbox_selected, sandbox_tree_expanded, sandbox_loaded, sandbox_error, selected_optdepends, cascade_mode, cached_reverse_deps_report: _, } = modal else { return None; }; Some(PreflightFields { items, action, tab, summary, header_chips, dependency_info, dep_selected, dep_tree_expanded, deps_error, file_info, file_selected, file_tree_expanded, files_error, service_info, service_selected, services_loaded, services_error, sandbox_info, sandbox_selected, sandbox_tree_expanded, sandbox_loaded, sandbox_error, selected_optdepends, cascade_mode, }) }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/helpers/layout_tests.rs
src/ui/modals/preflight/helpers/layout_tests.rs
//! Unit tests for `calculate_modal_layout` function. use super::layout; /// What: Test `calculate_modal_layout` with standard area. /// /// Inputs: /// - `area`: Standard terminal area (120x40) /// /// Output: /// - Returns properly sized and centered modal rects /// /// Details: /// - Verifies that layout calculation works for standard sizes. #[test] fn test_calculate_modal_layout_standard() { use ratatui::prelude::Rect; let area = Rect { x: 0, y: 0, width: 120, height: 40, }; let (modal_rect, content_rect, keybinds_rect) = layout::calculate_modal_layout(area); // Modal should be centered and within max size assert!(modal_rect.width <= 96); assert!(modal_rect.height <= 32); assert!(modal_rect.x > 0); // Centered assert!(modal_rect.y > 0); // Centered // Content and keybinds should fit within modal assert!(content_rect.width <= modal_rect.width); assert!(content_rect.height + keybinds_rect.height <= modal_rect.height); assert_eq!(keybinds_rect.height, 4); } /// What: Test `calculate_modal_layout` with small area. /// /// Inputs: /// - `area`: Small terminal area (50x20) /// /// Output: /// - Returns modal that fits within area /// /// Details: /// - Verifies that layout calculation handles small areas correctly. #[test] fn test_calculate_modal_layout_small() { use ratatui::prelude::Rect; let area = Rect { x: 0, y: 0, width: 50, height: 20, }; let (modal_rect, content_rect, keybinds_rect) = layout::calculate_modal_layout(area); // Modal should fit within area (with margins) assert!(modal_rect.width <= area.width); assert!(modal_rect.height <= area.height); assert!(content_rect.width <= modal_rect.width); assert!(content_rect.height + keybinds_rect.height <= modal_rect.height); } /// What: Test `calculate_modal_layout` with maximum constraints. /// /// Inputs: /// - `area`: Very large terminal area (200x100) /// /// Output: /// - Returns modal constrained to max 96x32 /// /// Details: /// - Verifies that maximum size constraints are enforced. #[test] fn test_calculate_modal_layout_max_constraints() { use ratatui::prelude::Rect; let area = Rect { x: 0, y: 0, width: 200, height: 100, }; let (modal_rect, _, _) = layout::calculate_modal_layout(area); // Modal should be constrained to max size assert_eq!(modal_rect.width, 96); assert_eq!(modal_rect.height, 32); } /// What: Test `calculate_modal_layout` with offset area. /// /// Inputs: /// - `area`: Area with non-zero offset (x=10, y=5) /// /// Output: /// - Returns modal centered within offset area /// /// Details: /// - Verifies that layout calculation handles offset areas correctly. #[test] fn test_calculate_modal_layout_offset() { use ratatui::prelude::Rect; let area = Rect { x: 10, y: 5, width: 120, height: 40, }; let (modal_rect, _, _) = layout::calculate_modal_layout(area); // Modal should be centered within offset area assert!(modal_rect.x >= area.x); assert!(modal_rect.y >= area.y); assert!(modal_rect.x + modal_rect.width <= area.x + area.width); assert!(modal_rect.y + modal_rect.height <= area.y + area.height); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/tabs/services.rs
src/ui/modals/preflight/tabs/services.rs
use ratatui::{ prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, }; use crate::i18n; use crate::state::AppState; use crate::state::modal::{ServiceImpact, ServiceRestartDecision}; use crate::theme::theme; /// What: Render the Services tab content for the preflight modal. /// /// Inputs: /// - `app`: Application state for i18n and data access. /// - `service_info`: Service impact information. /// - `service_selected`: Currently selected service index (mutable). /// - `services_loaded`: Whether services are loaded. /// - `services_error`: Optional error message. /// - `content_rect`: Content area rectangle. /// /// Output: /// - Returns a vector of lines to render. /// /// Details: /// - Shows service impacts with restart decisions. /// - Supports viewport-based rendering for large service lists. #[allow(clippy::too_many_arguments)] pub fn render_services_tab( app: &AppState, service_info: &[ServiceImpact], service_selected: &mut usize, services_loaded: bool, services_error: Option<&String>, content_rect: Rect, ) -> Vec<Line<'static>> { let th = theme(); let mut lines = Vec::new(); if app.services_resolving { lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.services.updating"), Style::default().fg(th.yellow), ))); } else if let Some(err_msg) = services_error { // Display error with retry hint lines.push(Line::from(Span::styled( i18n::t_fmt1(app, "app.modals.preflight.services.error", err_msg), Style::default().fg(th.red), ))); lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.services.retry_hint"), Style::default().fg(th.subtext1), ))); } else if !services_loaded { lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.services.resolving"), Style::default().fg(th.subtext1), ))); } else if service_info.is_empty() { lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.services.no_services"), Style::default().fg(th.green), ))); } else { // Performance optimization: Only render visible items (viewport-based rendering) // This prevents performance issues with large service lists let available_height = content_rect.height.saturating_sub(6) as usize; let visible = available_height.max(1); let selected = (*service_selected).min(service_info.len().saturating_sub(1)); if *service_selected != selected { *service_selected = selected; } let start = if service_info.len() <= visible { 0 } else { selected .saturating_sub(visible / 2) .min(service_info.len() - visible) }; let end = (start + visible).min(service_info.len()); // Render only visible services (viewport-based rendering) for (idx, svc) in service_info .iter() .enumerate() .skip(start) .take(end - start) { let is_selected = idx == selected; let mut spans = Vec::new(); let name_style = if is_selected { Style::default() .fg(th.crust) .bg(th.sapphire) .add_modifier(Modifier::BOLD) } else { Style::default().fg(th.text) }; spans.push(Span::styled(svc.unit_name.clone(), name_style)); spans.push(Span::raw(" ")); let status_span = if svc.is_active { if svc.needs_restart { Span::styled( i18n::t( app, "app.modals.preflight.services.active_restart_recommended", ), Style::default().fg(th.yellow), ) } else { Span::styled( i18n::t(app, "app.modals.preflight.services.active"), Style::default().fg(th.green), ) } } else { Span::styled( i18n::t(app, "app.modals.preflight.services.inactive"), Style::default().fg(th.subtext1), ) }; spans.push(status_span); spans.push(Span::raw(" ")); let decision_span = match svc.restart_decision { ServiceRestartDecision::Restart => Span::styled( i18n::t(app, "app.modals.preflight.services.restart"), Style::default().fg(th.green), ), ServiceRestartDecision::Defer => Span::styled( i18n::t(app, "app.modals.preflight.services.defer"), Style::default().fg(th.yellow), ), }; spans.push(decision_span); if !svc.providers.is_empty() { spans.push(Span::raw(" • ")); spans.push(Span::styled( svc.providers.join(", "), Style::default().fg(th.overlay1), )); } lines.push(Line::from(spans)); } if end < service_info.len() { lines.push(Line::from(Span::styled( i18n::t_fmt1( app, "app.modals.preflight.services.more_services", service_info.len() - end, ), Style::default().fg(th.subtext1), ))); } } lines }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/tabs/sandbox.rs
src/ui/modals/preflight/tabs/sandbox.rs
use ratatui::{ prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, }; use crate::i18n; use crate::state::{AppState, PackageItem}; use crate::theme::theme; use crate::ui::helpers::ChangeLogger; use std::collections::{HashMap, HashSet}; use std::fmt::Write; use std::sync::{Mutex, OnceLock}; /// What: Type alias for sandbox display items. /// /// Inputs: None /// /// Output: None /// /// Details: /// - Represents a display item in the sandbox tab. /// - Format: (`is_header`, `package_name`, `Option<`(`dep_type`, `dep_name`, `dep_info`)`>`) type SandboxDisplayItem = ( bool, String, Option<( &'static str, // "depends", "makedepends", "checkdepends", "optdepends" String, // dependency name crate::logic::sandbox::DependencyDelta, )>, ); /// What: Context struct grouping Sandbox tab fields to reduce data flow complexity. /// /// Inputs: None (constructed from parameters). /// /// Output: Groups related fields together for passing to render functions. /// /// Details: Reduces individual field extractions and uses, lowering data flow complexity. pub struct SandboxTabContext<'a> { /// Package items for the operation. pub items: &'a [PackageItem], /// Sandbox information for packages. pub sandbox_info: &'a [crate::logic::sandbox::SandboxInfo], /// Set of expanded package names in the tree view. pub sandbox_tree_expanded: &'a HashSet<String>, /// Whether sandbox data has been loaded. pub sandbox_loaded: bool, /// Optional error message if sandbox loading failed. pub sandbox_error: Option<&'a String>, /// Selected optional dependencies by package name. pub selected_optdepends: &'a HashMap<String, HashSet<String>>, /// Content area rectangle for rendering. pub content_rect: Rect, } /// What: Enum representing the current render state of the sandbox tab. /// /// Inputs: None /// /// Output: None /// /// Details: /// - Used to determine what should be rendered (error, loading, analyzing, etc.). /// - Reduces data flow complexity by centralizing state checking logic. enum SandboxRenderState { /// Error state with error message. Error(String), /// Loading sandbox data. Loading, /// Analyzing sandbox information. Analyzing, /// No AUR packages to analyze. NoAurPackages, /// Ready to display sandbox information. Ready, } /// What: State tracking for sandbox tab logging. /// /// Inputs: None (constructed from current state). /// /// Output: Captures current sandbox state for logging. /// /// Details: Used to track and log sandbox tab state changes. #[derive(Clone, PartialEq, Eq)] struct SandboxLogState { /// Number of package items. items_len: usize, /// Number of sandbox info entries. sandbox_info_len: usize, /// Whether sandbox data has been loaded. sandbox_loaded: bool, /// Currently selected sandbox item index. sandbox_selected: usize, /// Number of expanded items in the tree. expanded_len: usize, /// Bitmask for tracking which items are being resolved. resolving_mask: u8, /// Whether there is an error state. has_error: bool, } fn log_sandbox_state(state: &SandboxLogState) { static LOGGER: OnceLock<Mutex<ChangeLogger<SandboxLogState>>> = OnceLock::new(); let mut logger = LOGGER .get_or_init(|| Mutex::new(ChangeLogger::new())) .lock() .expect("Sandbox log state mutex poisoned"); if logger.should_log(state) { tracing::debug!( "[UI] render_sandbox_tab: items={}, sandbox_info={}, sandbox_loaded={}, sandbox_selected={}, expanded={}, resolving={}/{}, error={}", state.items_len, state.sandbox_info_len, state.sandbox_loaded, state.sandbox_selected, state.expanded_len, state.resolving_mask & 1 != 0, state.resolving_mask & 2 != 0, state.has_error ); } } /// What: Pre-computed render data to reduce data flow complexity. /// /// Inputs: None /// /// Output: None /// /// Details: /// - Groups derived values that are computed once and reused. /// - Reduces intermediate variable assignments in the main function. struct SandboxRenderData { /// Display items for rendering. display_items: Vec<SandboxDisplayItem>, /// Viewport (`start_index`, `end_index`). viewport: (usize, usize), /// Available height for rendering. available_height: usize, /// Total number of items. total_items: usize, } /// What: Determine the current render state of the sandbox tab. /// /// Inputs: /// - `app`: Application state for checking resolving flags. /// - `ctx`: Sandbox tab context. /// /// Output: /// - Returns `SandboxRenderState` enum indicating what should be rendered. /// /// Details: /// - Centralizes state checking logic to reduce data flow complexity. /// - Checks error, loading, analyzing, and no-AUR-packages states. fn determine_sandbox_state(app: &AppState, ctx: &SandboxTabContext) -> SandboxRenderState { // Check if there are any AUR packages at all let has_aur = ctx .items .iter() .any(|i| matches!(i.source, crate::state::Source::Aur)); if !has_aur { return SandboxRenderState::NoAurPackages; } // Handle error/loading/analyzing states if let Some(err) = ctx.sandbox_error { return SandboxRenderState::Error(err.clone()); } else if app.preflight_sandbox_resolving || app.sandbox_resolving { return SandboxRenderState::Loading; } else if !ctx.sandbox_loaded || ctx.sandbox_info.is_empty() { return SandboxRenderState::Analyzing; } SandboxRenderState::Ready } /// What: Pre-compute render data to reduce data flow complexity. /// /// Inputs: /// - `ctx`: Sandbox tab context. /// - `sandbox_selected`: Mutable reference to selected index (for viewport calculation). /// /// Output: /// - Returns `SandboxRenderData` with pre-computed values. /// /// Details: /// - Computes display items, viewport, and other derived values once. /// - Reduces intermediate variable assignments in the main function. fn compute_render_data(ctx: &SandboxTabContext, sandbox_selected: &mut usize) -> SandboxRenderData { // Build flat list of display items: package headers + dependencies (only if expanded) let display_items = build_display_items(ctx.items, ctx.sandbox_info, ctx.sandbox_tree_expanded); // Calculate viewport based on selected index (like Deps/Files tabs) // Performance optimization: Only render visible items (viewport-based rendering) // This prevents performance issues with large dependency lists let available_height = (ctx.content_rect.height as usize).saturating_sub(6); let total_items = display_items.len(); let viewport = calculate_viewport( total_items, *sandbox_selected, available_height, sandbox_selected, ); SandboxRenderData { display_items, viewport, available_height, total_items, } } /// What: Render error state for sandbox tab. /// /// Inputs: /// - `app`: Application state for i18n. /// - `error`: Error message to display. /// /// Output: /// - Returns vector of lines for error display. /// /// Details: /// - Shows error message and retry hint. fn render_error_state(app: &AppState, error: &str) -> Vec<Line<'static>> { let th = theme(); let mut lines = Vec::new(); tracing::warn!("[UI] render_sandbox_tab: Displaying error: {}", error); lines.push(Line::from(Span::styled( i18n::t_fmt1(app, "app.modals.preflight.sandbox.error", error), Style::default().fg(th.red), ))); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.sandbox.retry_hint"), Style::default().fg(th.subtext0), ))); lines.push(Line::from("")); lines } /// What: Render AUR package headers. /// /// Inputs: /// - `items`: Packages to render headers for. /// /// Output: /// - Returns vector of lines with package headers. /// /// Details: /// - Only renders headers for AUR packages. fn render_aur_package_headers(items: &[PackageItem]) -> Vec<Line<'static>> { let th = theme(); let mut lines = Vec::new(); for item in items { let is_aur = matches!(item.source, crate::state::Source::Aur); if is_aur { let item_name = &item.name; lines.push(Line::from(Span::styled( format!("▶ {item_name} "), Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD), ))); } } lines } /// What: Render loading state for sandbox tab. /// /// Inputs: /// - `app`: Application state for i18n. /// - `items`: Packages to show headers for. /// /// Output: /// - Returns vector of lines for loading display. /// /// Details: /// - Shows AUR package headers and loading message. fn render_loading_state(app: &AppState, items: &[PackageItem]) -> Vec<Line<'static>> { let th = theme(); let mut lines = render_aur_package_headers(items); lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.sandbox.updating"), Style::default().fg(th.yellow), ))); lines } /// What: Render analyzing state for sandbox tab. /// /// Inputs: /// - `app`: Application state for i18n. /// - `items`: Packages to show headers for. /// /// Output: /// - Returns vector of lines for analyzing display. /// /// Details: /// - Shows AUR package headers and analyzing message. fn render_analyzing_state(app: &AppState, items: &[PackageItem]) -> Vec<Line<'static>> { let th = theme(); let mut lines = render_aur_package_headers(items); lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.sandbox.analyzing"), Style::default().fg(th.subtext0), ))); lines } /// What: Render message when all packages are official (no sandbox needed). /// /// Inputs: /// - `app`: Application state for i18n. /// /// Output: /// - Returns vector of lines for no AUR packages display. /// /// Details: /// - Shows informational message that sandbox is only for AUR packages. fn render_no_aur_packages_state(app: &AppState) -> Vec<Line<'static>> { let th = theme(); vec![ Line::from(Span::styled( i18n::t(app, "app.modals.preflight.sandbox.no_aur_packages"), Style::default().fg(th.subtext1), )), Line::from(""), Line::from(Span::styled( i18n::t(app, "app.modals.preflight.sandbox.sandbox_only_for_aur"), Style::default().fg(th.subtext0), )), ] } /// What: Build flat list of display items from packages and sandbox info. /// /// Inputs: /// - `items`: Packages under review. /// - `sandbox_info`: Sandbox information. /// - `sandbox_tree_expanded`: Set of expanded package names. /// /// Output: /// - Returns vector of display items. /// /// Details: /// - Creates flat list with package headers and dependencies (only if expanded). fn build_display_items( items: &[PackageItem], sandbox_info: &[crate::logic::sandbox::SandboxInfo], sandbox_tree_expanded: &HashSet<String>, ) -> Vec<SandboxDisplayItem> { let mut display_items = Vec::new(); for item in items { let is_aur = matches!(item.source, crate::state::Source::Aur); let is_expanded = sandbox_tree_expanded.contains(&item.name); // Add package header display_items.push((true, item.name.clone(), None)); // Add dependencies only if expanded and AUR if is_expanded && is_aur && let Some(info) = sandbox_info.iter().find(|s| s.package_name == item.name) { tracing::debug!( "[UI] render_sandbox_tab: Expanding package '{}' with {} depends, {} makedepends, {} checkdepends, {} optdepends", item.name, info.depends.len(), info.makedepends.len(), info.checkdepends.len(), info.optdepends.len() ); // Runtime dependencies (depends) for dep in &info.depends { display_items.push(( false, item.name.clone(), Some(("depends", dep.name.clone(), dep.clone())), )); } // Build dependencies (makedepends) for dep in &info.makedepends { display_items.push(( false, item.name.clone(), Some(("makedepends", dep.name.clone(), dep.clone())), )); } // Test dependencies (checkdepends) for dep in &info.checkdepends { display_items.push(( false, item.name.clone(), Some(("checkdepends", dep.name.clone(), dep.clone())), )); } // Optional dependencies (optdepends) for dep in &info.optdepends { display_items.push(( false, item.name.clone(), Some(("optdepends", dep.name.clone(), dep.clone())), )); } } else if is_aur && is_expanded { // AUR package is expanded but no sandbox info found - log warning tracing::warn!( "[UI] render_sandbox_tab: Package '{}' is AUR and expanded but no sandbox info found", item.name ); } } display_items } /// What: Calculate viewport range for visible items. /// /// Inputs: /// - `total_items`: Total number of display items. /// - `selected_idx`: Currently selected item index. /// - `available_height`: Available height for rendering. /// - `sandbox_selected`: Mutable reference to selected index (for clamping). /// /// Output: /// - Returns (`start_idx`, `end_idx`) viewport range. /// /// Details: /// - Ensures selected item is always visible. /// - Accounts for section headers that add extra lines. fn calculate_viewport( total_items: usize, selected_idx: usize, available_height: usize, sandbox_selected: &mut usize, ) -> (usize, usize) { // Validate and clamp selected index to prevent out-of-bounds access let sandbox_selected_clamped = if total_items > 0 { selected_idx.min(total_items.saturating_sub(1)) } else { 0 }; if *sandbox_selected != sandbox_selected_clamped { tracing::warn!( "[UI] render_sandbox_tab: Clamping sandbox_selected from {} to {} (total_items={})", *sandbox_selected, sandbox_selected_clamped, total_items ); *sandbox_selected = sandbox_selected_clamped; } if total_items <= available_height { // All items fit on screen return (0, total_items); } // Ensure selected item is always visible - keep it within [start_idx, end_idx) // Try to center it, but adjust if needed to keep it visible // Reduce available_height slightly to account for section headers that add extra lines let effective_height = available_height.saturating_sub(2); // Reserve space for section headers let mut start_idx = sandbox_selected_clamped .saturating_sub(effective_height / 2) .max(0) .min(total_items.saturating_sub(effective_height)); let mut end_idx = (start_idx + effective_height).min(total_items); // Ensure selected item is within bounds - adjust if necessary if sandbox_selected_clamped < start_idx { // Selected item is before start - move start to include it start_idx = sandbox_selected_clamped; end_idx = (start_idx + effective_height).min(total_items); } else if sandbox_selected_clamped >= end_idx { // Selected item is at or beyond end - position it at bottom of viewport // Make sure to include it even if section headers take up space end_idx = (sandbox_selected_clamped + 1).min(total_items); start_idx = end_idx.saturating_sub(effective_height).max(0); end_idx = (start_idx + effective_height).min(total_items); // Final check: ensure selected item is visible if sandbox_selected_clamped >= end_idx { end_idx = sandbox_selected_clamped + 1; start_idx = end_idx.saturating_sub(effective_height).max(0); } } (start_idx, end_idx) } /// What: Get dependency status icon based on dependency state. /// /// Inputs: /// - `dep`: Dependency delta information. /// - `dep_type`: Type of dependency. /// - `is_optdep_selected`: Whether optional dependency is selected. /// /// Output: /// - Returns status icon string. /// /// Details: /// - Returns appropriate icon based on installation and version status. fn get_dependency_status_icon( dep: &crate::logic::sandbox::DependencyDelta, dep_type: &str, is_optdep_selected: bool, ) -> &'static str { if dep.is_installed { if dep.version_satisfied { "✓" } else { "⚠" } } else { match dep_type { "optdepends" => { if is_optdep_selected { "☑" // Checkbox checked } else { "☐" // Checkbox unchecked } } "checkdepends" => "○", _ => "✗", } } } /// What: Get dependency status color based on dependency state. /// /// Inputs: /// - `dep`: Dependency delta information. /// - `dep_type`: Type of dependency. /// - `is_optdep_selected`: Whether optional dependency is selected. /// /// Output: /// - Returns color from theme. /// /// Details: /// - Returns appropriate color based on installation and version status. fn get_dependency_status_color( dep: &crate::logic::sandbox::DependencyDelta, dep_type: &str, is_optdep_selected: bool, ) -> ratatui::style::Color { let th = theme(); if dep.is_installed { if dep.version_satisfied { th.green } else { th.yellow } } else { match dep_type { "optdepends" => { if is_optdep_selected { th.sapphire // Highlight selected optdepends } else { th.subtext0 } } "checkdepends" => th.subtext0, _ => th.red, } } } /// What: Render package header line. /// /// Inputs: /// - `app`: Application state for i18n. /// - `item`: Package item to render. /// - `is_expanded`: Whether package is expanded. /// - `is_selected`: Whether package is selected. /// /// Output: /// - Returns line for package header. /// /// Details: /// - Formats package header with source and expansion indicator. fn render_package_header( app: &AppState, item: &PackageItem, is_expanded: bool, is_selected: bool, ) -> Line<'static> { let th = theme(); let is_aur = matches!(item.source, crate::state::Source::Aur); let arrow_symbol = if is_aur && is_expanded { "▼" } else if is_aur { "▶" } else { "" }; let header_style = if is_selected { Style::default() .fg(th.crust) .bg(th.sapphire) .add_modifier(Modifier::BOLD) } else { Style::default() .fg(th.sapphire) .add_modifier(Modifier::BOLD) }; let source_str = match &item.source { crate::state::Source::Aur => "AUR".to_string(), crate::state::Source::Official { repo, .. } => repo.clone(), }; let mut header_text = i18n::t_fmt( app, "app.modals.preflight.sandbox.package_label", &[&item.name, &source_str], ); if !arrow_symbol.is_empty() { header_text = format!("{arrow_symbol} {header_text}"); } Line::from(Span::styled(header_text, header_style)) } /// What: Render package header details (messages for official/collapsed packages). /// /// Inputs: /// - `app`: Application state for i18n. /// - `pkg_name`: Package name. /// - `is_aur`: Whether package is from AUR. /// - `is_expanded`: Whether package is expanded. /// - `sandbox_info`: Sandbox information to get dependency counts. /// /// Output: /// - Returns vector of lines for package details. /// /// Details: /// - Shows message for official packages or dependency count for collapsed AUR packages. fn render_package_header_details( app: &AppState, pkg_name: &str, is_aur: bool, is_expanded: bool, sandbox_info: &[crate::logic::sandbox::SandboxInfo], ) -> Vec<Line<'static>> { let th = theme(); let mut lines = Vec::new(); // Show message for official packages or collapsed AUR packages if !is_aur { lines.push(Line::from(Span::styled( format!( " {}", i18n::t( app, "app.modals.preflight.sandbox.official_packages_prebuilt" ) ), Style::default().fg(th.subtext0), ))); } else if !is_expanded { // Show dependency count for collapsed AUR packages if let Some(info) = sandbox_info.iter().find(|s| s.package_name == pkg_name) { let dep_count = info.depends.len() + info.makedepends.len() + info.checkdepends.len() + info.optdepends.len(); if dep_count > 0 { lines.push(Line::from(Span::styled( format!( " {}", i18n::t_fmt1( app, "app.modals.preflight.sandbox.dependencies_expand_hint", dep_count.to_string() ) ), Style::default().fg(th.subtext1), ))); } else { lines.push(Line::from(Span::styled( format!( " {}", i18n::t(app, "app.modals.preflight.sandbox.no_build_dependencies") ), Style::default().fg(th.green), ))); } } else { // AUR package but no sandbox info - this shouldn't happen but handle gracefully tracing::debug!( "[UI] render_sandbox_tab: AUR package '{}' collapsed but no sandbox info found", pkg_name ); } } lines } /// What: Render dependency section header when dependency type changes. /// /// Inputs: /// - `app`: Application state for i18n. /// - `dep_type`: Type of dependency. /// /// Output: /// - Returns optional line for section header. /// /// Details: /// - Returns section header line if `dep_type` is valid. fn render_dependency_section_header(app: &AppState, dep_type: &str) -> Option<Line<'static>> { let th = theme(); let section_name = match dep_type { "depends" => i18n::t(app, "app.modals.preflight.sandbox.runtime_dependencies"), "makedepends" => i18n::t(app, "app.modals.preflight.sandbox.build_dependencies"), "checkdepends" => i18n::t(app, "app.modals.preflight.sandbox.test_dependencies"), "optdepends" => i18n::t(app, "app.modals.preflight.sandbox.optional_dependencies"), _ => return None, }; Some(Line::from(Span::styled( section_name, Style::default() .fg(th.sapphire) .add_modifier(Modifier::BOLD), ))) } /// What: Render dependency line. /// /// Inputs: /// - `dep_name`: Dependency name. /// - `dep`: Dependency delta information. /// - `dep_type`: Type of dependency. /// - `is_optdep_selected`: Whether optional dependency is selected. /// - `is_selected`: Whether dependency is selected. /// /// Output: /// - Returns line for dependency. /// /// Details: /// - Formats dependency line with status icon and version info. fn render_dependency_line( dep_name: &str, dep: &crate::logic::sandbox::DependencyDelta, dep_type: &str, is_optdep_selected: bool, is_selected: bool, ) -> Line<'static> { let th = theme(); let status_icon = get_dependency_status_icon(dep, dep_type, is_optdep_selected); let status_color = get_dependency_status_color(dep, dep_type, is_optdep_selected); let dep_style = if is_selected { Style::default() .fg(th.crust) .bg(th.sapphire) .add_modifier(Modifier::BOLD) } else { Style::default().fg(status_color) }; let mut dep_line = format!(" {status_icon} {dep_name}"); if let Some(ref version) = dep.installed_version { let _ = write!(dep_line, " (installed: {version})"); } if dep_type == "optdepends" && is_optdep_selected { dep_line.push_str(" [selected]"); } Line::from(Span::styled(dep_line, dep_style)) } /// What: Render visible display items in the viewport. /// /// Inputs: /// - `app`: Application state for i18n. /// - `ctx`: Sandbox tab context. /// - `render_data`: Pre-computed render data. /// - `selected_idx`: Currently selected item index. /// /// Output: /// - Returns vector of lines for visible items. /// /// Details: /// - Renders only items within the viewport range. /// - Handles package headers and dependency items. /// - Tracks dependency section headers. fn render_display_items( app: &AppState, ctx: &SandboxTabContext, render_data: &SandboxRenderData, selected_idx: usize, ) -> Vec<Line<'static>> { let mut lines = Vec::new(); let (start_idx, end_idx) = render_data.viewport; // Track which packages we've seen to group dependencies properly let mut last_dep_type: Option<&str> = None; // Render visible items for (idx, (is_header, pkg_name, dep_opt)) in render_data .display_items .iter() .enumerate() .skip(start_idx) .take(end_idx - start_idx) { let is_selected = idx == selected_idx; if *is_header { // Package header let Some(item) = ctx.items.iter().find(|p| p.name == *pkg_name) else { tracing::warn!( "[UI] render_sandbox_tab: Package '{}' not found in items list, skipping", pkg_name ); continue; }; let is_aur = matches!(item.source, crate::state::Source::Aur); let is_expanded = ctx.sandbox_tree_expanded.contains(pkg_name); lines.push(render_package_header(app, item, is_expanded, is_selected)); last_dep_type = None; // Show message for official packages or collapsed AUR packages lines.extend(render_package_header_details( app, pkg_name, is_aur, is_expanded, ctx.sandbox_info, )); } else if let Some((dep_type, dep_name, dep)) = dep_opt { // Dependency item (indented) // Show section header when dep_type changes if last_dep_type != Some(dep_type) { if let Some(header_line) = render_dependency_section_header(app, dep_type) { lines.push(header_line); } last_dep_type = Some(dep_type); } // Check if this is a selected optional dependency let is_optdep_selected = if *dep_type == "optdepends" { ctx.selected_optdepends.get(pkg_name).is_some_and(|set| { // Extract package name from dependency spec (may include version or description) let pkg_name_from_dep = crate::logic::sandbox::extract_package_name(dep_name); set.contains(dep_name) || set.contains(&pkg_name_from_dep) }) } else { false }; lines.push(render_dependency_line( dep_name, dep, dep_type, is_optdep_selected, is_selected, )); } } lines } /// What: Render the Sandbox tab content for the preflight modal. /// /// Inputs: /// - `app`: Application state for i18n and data access. /// - `ctx`: Sandbox tab context containing all render parameters. /// - `sandbox_selected`: Currently selected sandbox item index (mutable). /// /// Output: /// - Returns a vector of lines to render. /// /// Details: /// - Shows sandbox dependency analysis for AUR packages. /// - Supports viewport-based rendering for large dependency lists. /// - Uses context struct to reduce data flow complexity. pub fn render_sandbox_tab( app: &AppState, ctx: &SandboxTabContext, sandbox_selected: &mut usize, ) -> Vec<Line<'static>> { let th = theme(); let resolving_mask = u8::from(app.preflight_sandbox_resolving) | (u8::from(app.sandbox_resolving) << 1); log_sandbox_state(&SandboxLogState { items_len: ctx.items.len(), sandbox_info_len: ctx.sandbox_info.len(), sandbox_loaded: ctx.sandbox_loaded, sandbox_selected: *sandbox_selected, expanded_len: ctx.sandbox_tree_expanded.len(), resolving_mask, has_error: ctx.sandbox_error.is_some(), }); // Determine render state (reduces data flow complexity by centralizing state checks) let render_state = determine_sandbox_state(app, ctx); // Handle early return states match render_state { SandboxRenderState::NoAurPackages => { tracing::debug!( "[UI] render_sandbox_tab: No AUR packages in list (all {} packages are official), showing info message", ctx.items.len() ); return render_no_aur_packages_state(app); } SandboxRenderState::Error(err) => { return render_error_state(app, &err); } SandboxRenderState::Loading => { let aur_count = ctx .items .iter() .filter(|i| matches!(i.source, crate::state::Source::Aur)) .count(); tracing::debug!( "[UI] render_sandbox_tab: Showing loading state (resolving={}/{}, {} AUR packages)", app.preflight_sandbox_resolving, app.sandbox_resolving, aur_count ); return render_loading_state(app, ctx.items); } SandboxRenderState::Analyzing => { tracing::debug!( "[UI] render_sandbox_tab: Not loaded or empty (loaded={}, info_len={}), showing analyzing message", ctx.sandbox_loaded, ctx.sandbox_info.len() ); return render_analyzing_state(app, ctx.items); } SandboxRenderState::Ready => { // Continue with normal rendering } } // Pre-compute render data (reduces data flow complexity) let render_data = compute_render_data(ctx, sandbox_selected); tracing::debug!( "[UI] render_sandbox_tab: Rendering data - total_items={}, sandbox_selected={}, items={}, sandbox_info={}, expanded_count={}, available_height={}", render_data.total_items, *sandbox_selected, ctx.items.len(), ctx.sandbox_info.len(), ctx.sandbox_tree_expanded.len(), render_data.available_height ); // Render visible items (extracted to reduce complexity) let mut lines = render_display_items(app, ctx, &render_data, *sandbox_selected); // Show indicator if there are more items below let (_, end_idx) = render_data.viewport; if end_idx < render_data.total_items { lines.push(Line::from(Span::styled( format!( "… {} more item{}", render_data.total_items - end_idx, if render_data.total_items - end_idx == 1 { "" } else { "s" } ), Style::default().fg(th.subtext1), ))); } // If no packages at all if ctx.items.is_empty() { lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.sandbox.no_packages"), Style::default().fg(th.subtext0), ))); } lines }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/tabs/deps.rs
src/ui/modals/preflight/tabs/deps.rs
use ratatui::{ prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, }; use crate::i18n; use crate::state::modal::{DependencyInfo, DependencySource, DependencyStatus}; use crate::state::{AppState, PackageItem, PreflightAction}; use crate::theme::theme; use crate::ui::modals::preflight::helpers::format_count_with_indicator; use std::collections::{HashMap, HashSet}; /// Known meta-packages in Arch Linux that have no reverse dependencies /// but are important system components. const META_PACKAGES: &[&str] = &[ "base", "base-devel", "xorg", "xorg-apps", "xorg-drivers", "xorg-fonts", "plasma", "plasma-meta", "plasma-desktop", "gnome", "gnome-extra", "kde-applications", "kde-applications-meta", "lxde", "lxqt", "mate", "mate-extra", "xfce4", "xfce4-goodies", "cinnamon", "budgie-desktop", "deepin", "deepin-extra", "i3", "sway", ]; /// What: Dependency statistics grouped by status. /// /// Inputs: None (struct fields). /// /// Output: None (struct fields). /// /// Details: Contains counts of dependencies by their status type. struct DepStats { /// Total number of dependencies. total: usize, /// Number of already installed dependencies. installed: usize, /// Number of dependencies to install. to_install: usize, /// Number of dependencies to upgrade. to_upgrade: usize, /// Number of conflicting dependencies. conflict: usize, /// Number of missing dependencies. missing: usize, } /// What: Calculate dependency statistics from unique dependencies. /// /// Inputs: /// - `unique_deps`: Map of unique dependency names to their info. /// /// Output: /// - Returns `DepStats` with counts by status. /// /// Details: /// - Counts each dependency only once regardless of how many packages require it. fn calculate_dep_stats(unique_deps: &HashMap<String, &DependencyInfo>) -> DepStats { DepStats { total: unique_deps.len(), installed: unique_deps .values() .filter(|d| matches!(d.status, DependencyStatus::Installed { .. })) .count(), to_install: unique_deps .values() .filter(|d| matches!(d.status, DependencyStatus::ToInstall)) .count(), to_upgrade: unique_deps .values() .filter(|d| matches!(d.status, DependencyStatus::ToUpgrade { .. })) .count(), conflict: unique_deps .values() .filter(|d| matches!(d.status, DependencyStatus::Conflict { .. })) .count(), missing: unique_deps .values() .filter(|d| matches!(d.status, DependencyStatus::Missing)) .count(), } } /// What: Check if dependency data is incomplete based on resolution state and heuristics. /// /// Inputs: /// - `app`: Application state for resolution flags. /// - `total_deps`: Total number of unique dependencies. /// - `items`: Packages under review. /// - `deps`: All dependency info to check package representation. /// /// Output: /// - Returns true if data appears incomplete. /// /// Details: /// - Data is incomplete if resolving with some data, or if heuristic suggests partial data. fn has_incomplete_data( app: &AppState, total_deps: usize, items: &[PackageItem], deps: &[DependencyInfo], ) -> bool { let is_resolving = app.preflight_deps_resolving || app.deps_resolving; tracing::debug!( "[UI] compute_is_resolving: preflight_deps_resolving={}, deps_resolving={}, is_resolving={}, total_deps={}, items={}, deps={}", app.preflight_deps_resolving, app.deps_resolving, is_resolving, total_deps, items.len(), deps.len() ); if is_resolving && total_deps > 0 { return true; } if total_deps == 0 { return false; } let packages_with_deps: HashSet<String> = deps .iter() .flat_map(|d| d.required_by.iter()) .cloned() .collect(); let packages_with_deps_count = packages_with_deps.len(); packages_with_deps_count < items.len() && total_deps < items.len() } /// What: Render summary header lines for dependencies. /// /// Inputs: /// - `app`: Application state for i18n. /// - `action`: Whether install or remove. /// - `stats`: Dependency statistics. /// - `items_count`: Number of packages. /// - `has_incomplete`: Whether data is incomplete. /// /// Output: /// - Returns vector of header lines. /// /// Details: /// - Shows different headers for install vs remove actions. fn render_summary_header( app: &AppState, action: PreflightAction, stats: &DepStats, items_count: usize, has_incomplete: bool, ) -> Vec<Line<'static>> { let th = theme(); let mut lines = Vec::new(); if stats.total == 0 { return lines; } if matches!(action, PreflightAction::Remove) { let count_text = format_count_with_indicator(stats.total, items_count, has_incomplete); lines.push(Line::from(Span::styled( i18n::t_fmt1( app, "app.modals.preflight.deps.dependents_rely_on", count_text, ), Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD), ))); } else { let mut summary_parts = Vec::new(); let total_text = format_count_with_indicator(stats.total, items_count, has_incomplete); summary_parts.push(i18n::t_fmt1( app, "app.modals.preflight.deps.total", total_text, )); if stats.installed > 0 { let count_text = format_count_with_indicator(stats.installed, stats.total, has_incomplete); summary_parts.push(i18n::t_fmt1( app, "app.modals.preflight.deps.installed", count_text, )); } if stats.to_install > 0 { let count_text = format_count_with_indicator(stats.to_install, stats.total, has_incomplete); summary_parts.push(i18n::t_fmt1( app, "app.modals.preflight.deps.to_install", count_text, )); } if stats.to_upgrade > 0 { let count_text = format_count_with_indicator(stats.to_upgrade, stats.total, has_incomplete); summary_parts.push(i18n::t_fmt1( app, "app.modals.preflight.deps.to_upgrade", count_text, )); } if stats.conflict > 0 { let count_text = format_count_with_indicator(stats.conflict, stats.total, has_incomplete); summary_parts.push(i18n::t_fmt1( app, "app.modals.preflight.deps.conflicts", count_text, )); } if stats.missing > 0 { let count_text = format_count_with_indicator(stats.missing, stats.total, has_incomplete); summary_parts.push(i18n::t_fmt1( app, "app.modals.preflight.deps.missing", count_text, )); } lines.push(Line::from(Span::styled( i18n::t_fmt1( app, "app.modals.preflight.deps.dependencies_label", summary_parts.join(", "), ), Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD), ))); } lines.push(Line::from("")); lines } /// What: Render empty state when no dependencies are found. /// /// Inputs: /// - `app`: Application state for i18n. /// - `action`: Whether install or remove. /// - `items`: Packages under review. /// - `is_resolving`: Whether resolution is in progress. /// - `deps_error`: Optional error message. /// /// Output: /// - Returns vector of empty state lines. /// /// Details: /// - Shows different messages for install vs remove, with error handling. fn render_empty_state( app: &AppState, action: PreflightAction, items: &[PackageItem], is_resolving: bool, deps_error: Option<&String>, ) -> Vec<Line<'static>> { tracing::debug!( "[UI] render_empty_state: action={:?}, items={}, is_resolving={}, deps_error={:?}, preflight_deps_resolving={}, deps_resolving={}", action, items.len(), is_resolving, deps_error.is_some(), app.preflight_deps_resolving, app.deps_resolving ); let th = theme(); let mut lines = Vec::new(); // Handle error state first (applies to both Install and Remove) if let Some(err_msg) = deps_error { lines.push(Line::from(Span::styled( i18n::t_fmt1(app, "app.modals.preflight.deps.error", err_msg), Style::default().fg(th.red), ))); lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.deps.retry_hint"), Style::default().fg(th.subtext1), ))); return lines; } // Handle resolving state (applies to both Install and Remove) if is_resolving { for pkg_name in items.iter().map(|p| &p.name) { let mut spans = Vec::new(); spans.push(Span::styled( format!("▶ {pkg_name} "), Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD), )); let deps_label = if matches!(action, PreflightAction::Remove) { "(resolving dependents...)" } else { "(0 deps)" }; spans.push(Span::styled(deps_label, Style::default().fg(th.subtext1))); lines.push(Line::from(spans)); } lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.deps.resolving"), Style::default().fg(th.yellow), ))); return lines; } // Handle completed resolution with no dependencies found if matches!(action, PreflightAction::Remove) { // For Remove: no reverse dependencies means packages can be safely removed lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.deps.no_deps_for_removal"), Style::default().fg(th.green), ))); // Check for meta-packages and add warnings for item in items { if META_PACKAGES.contains(&item.name.as_str()) { lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t_fmt1( app, "app.modals.preflight.deps.meta_package_warning", &item.name, ), Style::default().fg(th.yellow), ))); } } return lines; } // For Install: show packages with zero dependencies for pkg_name in items.iter().map(|p| &p.name) { let mut spans = Vec::new(); spans.push(Span::styled( format!("▶ {pkg_name} "), Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD), )); spans.push(Span::styled("(0 deps)", Style::default().fg(th.subtext1))); lines.push(Line::from(spans)); } lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.deps.resolving"), Style::default().fg(th.subtext1), ))); lines } /// What: Build display items list with package headers and dependencies. /// /// Inputs: /// - `items`: Packages under review. /// - `grouped`: Dependencies grouped by package name. /// - `dep_tree_expanded`: Set of expanded package names. /// /// Output: /// - Returns vector of (`is_header`, `header_name`, `optional_dep`) tuples. /// /// Details: /// - Includes all packages even if they have no dependencies. fn build_display_items<'a>( items: &[PackageItem], grouped: &'a HashMap<String, Vec<&'a DependencyInfo>>, dep_tree_expanded: &HashSet<String>, ) -> Vec<(bool, String, Option<&'a DependencyInfo>)> { let mut display_items = Vec::new(); for pkg_name in items.iter().map(|p| &p.name) { let is_expanded = dep_tree_expanded.contains(pkg_name); display_items.push((true, pkg_name.clone(), None)); if is_expanded && let Some(pkg_deps) = grouped.get(pkg_name) { let mut seen_deps = HashSet::new(); for dep in pkg_deps { if seen_deps.insert(dep.name.as_str()) { display_items.push((false, String::new(), Some(*dep))); } } } } display_items } /// What: Calculate viewport range for visible items. /// /// Inputs: /// - `available_height`: Available screen height. /// - `total_items`: Total number of display items. /// - `dep_selected`: Currently selected index (mutable). /// /// Output: /// - Returns (`start_idx`, `end_idx`) tuple for viewport range. /// /// Details: /// - Clamps selected index and calculates centered viewport. fn calculate_viewport( available_height: usize, total_items: usize, dep_selected: &mut usize, ) -> (usize, usize) { let dep_selected_clamped = (*dep_selected).min(total_items.saturating_sub(1)); if *dep_selected != dep_selected_clamped { tracing::debug!( "[UI] Deps tab: clamping dep_selected from {} to {} (total_items={})", *dep_selected, dep_selected_clamped, total_items ); *dep_selected = dep_selected_clamped; } let start_idx = dep_selected_clamped .saturating_sub(available_height / 2) .min(total_items.saturating_sub(available_height)); let end_idx = (start_idx + available_height).min(total_items); (start_idx, end_idx) } /// What: Render a package header line. /// /// Inputs: /// - `header_name`: Package name. /// - `is_expanded`: Whether package tree is expanded. /// - `is_selected`: Whether this item is selected. /// - `grouped`: Dependencies grouped by package name. /// - `th`: Theme colors. /// /// Output: /// - Returns vector of spans for the header line. /// /// Details: /// - Shows arrow symbol, package name, and dependency count. fn render_package_header( header_name: &str, is_expanded: bool, is_selected: bool, grouped: &HashMap<String, Vec<&DependencyInfo>>, th: &crate::theme::Theme, ) -> Vec<Span<'static>> { let mut spans = Vec::new(); let arrow_symbol = if is_expanded { "▼" } else { "▶" }; let header_style = if is_selected { Style::default() .fg(th.crust) .bg(th.lavender) .add_modifier(Modifier::BOLD) } else { Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD) }; spans.push(Span::styled( format!("{arrow_symbol} {header_name} "), header_style, )); if let Some(pkg_deps) = grouped.get(header_name) { let mut seen_deps = HashSet::new(); let dep_count = pkg_deps .iter() .filter(|dep| seen_deps.insert(dep.name.as_str())) .count(); spans.push(Span::styled( format!("({dep_count} deps)"), Style::default().fg(th.subtext1), )); } else { spans.push(Span::styled("(0 deps)", Style::default().fg(th.subtext1))); } spans } /// What: Render a dependency item line. /// /// Inputs: /// - `dep`: Dependency information. /// - `is_selected`: Whether this item is selected. /// - `app`: Application state for i18n. /// - `th`: Theme colors. /// /// Output: /// - Returns vector of spans for the dependency line. /// /// Details: /// - Shows status icon, name, version, source badge, and additional status info. fn render_dependency_item( dep: &DependencyInfo, is_selected: bool, app: &AppState, th: &crate::theme::Theme, ) -> Vec<Span<'static>> { let mut spans = Vec::new(); spans.push(Span::styled(" ", Style::default())); let (status_icon, status_color) = match &dep.status { DependencyStatus::Installed { .. } => ("✓", th.green), DependencyStatus::ToInstall => ("+", th.yellow), DependencyStatus::ToUpgrade { .. } => ("↑", th.yellow), DependencyStatus::Conflict { .. } => ("⚠", th.red), DependencyStatus::Missing => ("?", th.red), }; spans.push(Span::styled( format!("{status_icon} "), Style::default().fg(status_color), )); let name_style = if is_selected { Style::default() .fg(th.crust) .bg(th.lavender) .add_modifier(Modifier::BOLD) } else { Style::default().fg(th.text) }; spans.push(Span::styled(dep.name.clone(), name_style)); if !dep.version.is_empty() { spans.push(Span::styled( format!(" {}", dep.version), Style::default().fg(th.overlay2), )); } let (source_badge, badge_color) = match &dep.source { DependencySource::Official { repo } => { let repo_lower = repo.to_lowercase(); let color = if crate::index::is_eos_repo(&repo_lower) || crate::index::is_cachyos_repo(&repo_lower) { th.sapphire } else { th.green }; (format!(" [{repo}]"), color) } DependencySource::Aur => (" [AUR]".to_string(), th.yellow), DependencySource::Local => (" [local]".to_string(), th.overlay1), }; spans.push(Span::styled(source_badge, Style::default().fg(badge_color))); if dep.is_core { spans.push(Span::styled( " [CORE]", Style::default().fg(th.red).add_modifier(Modifier::BOLD), )); } else if dep.is_system { spans.push(Span::styled( " [SYSTEM]", Style::default().fg(th.yellow).add_modifier(Modifier::BOLD), )); } match &dep.status { DependencyStatus::Installed { version } => { spans.push(Span::styled( i18n::t_fmt1(app, "app.modals.preflight.deps.installed_version", version), Style::default().fg(th.subtext1), )); } DependencyStatus::ToUpgrade { current, required } => { spans.push(Span::styled( format!(" ({current} → {required})"), Style::default().fg(th.yellow), )); } DependencyStatus::Conflict { reason } => { spans.push(Span::styled( format!(" ({reason})"), Style::default().fg(th.red), )); } _ => {} } spans } /// What: Render the Dependencies tab content for the preflight modal. /// /// Inputs: /// - `app`: Application state for i18n and data access. /// - `items`: Packages under review. /// - `action`: Whether install or remove. /// - `dependency_info`: Dependency information. /// - `dep_selected`: Currently selected dependency index (mutable). /// - `dep_tree_expanded`: Set of expanded package names. /// - `deps_error`: Optional error message. /// - `content_rect`: Content area rectangle. /// /// Output: /// - Returns a vector of lines to render. /// /// Details: /// - Shows dependency statistics and grouped dependency tree. /// - Supports viewport-based rendering for large lists. #[allow(clippy::too_many_arguments)] pub fn render_deps_tab( app: &AppState, items: &[PackageItem], action: PreflightAction, dependency_info: &[DependencyInfo], dep_selected: &mut usize, dep_tree_expanded: &HashSet<String>, deps_error: Option<&String>, content_rect: Rect, ) -> Vec<Line<'static>> { let th = theme(); let mut lines = Vec::new(); // Group dependencies by the packages that require them and deduplicate let mut grouped: HashMap<String, Vec<&DependencyInfo>> = HashMap::new(); let mut unique_deps: HashMap<String, &DependencyInfo> = HashMap::new(); for dep in dependency_info { unique_deps.entry(dep.name.clone()).or_insert(dep); for req_by in &dep.required_by { grouped.entry(req_by.clone()).or_default().push(dep); } } // Calculate statistics and check for incomplete data let stats = calculate_dep_stats(&unique_deps); let has_incomplete = has_incomplete_data(app, stats.total, items, dependency_info); // Render summary header or empty state if stats.total > 0 { lines.extend(render_summary_header( app, action, &stats, items.len(), has_incomplete, )); } else if dependency_info.is_empty() { let is_resolving = app.preflight_deps_resolving || app.deps_resolving; lines.extend(render_empty_state( app, action, items, is_resolving, deps_error, )); // Return early - empty state already shows packages, don't render them again return lines; } // Build display items and render viewport let display_items = build_display_items(items, &grouped, dep_tree_expanded); let available_height = (content_rect.height as usize).saturating_sub(6); let total_items = display_items.len(); tracing::debug!( "[UI] Deps tab: total_items={}, dep_selected={}, items={}, deps={}, expanded_count={}", total_items, *dep_selected, items.len(), dependency_info.len(), dep_tree_expanded.len() ); let (start_idx, end_idx) = calculate_viewport(available_height, total_items, dep_selected); // Render visible items for (idx, (is_header, header_name, dep)) in display_items .iter() .enumerate() .skip(start_idx) .take(end_idx - start_idx) { let is_selected = idx == *dep_selected; let spans = if *is_header { let is_expanded = dep_tree_expanded.contains(header_name); render_package_header(header_name, is_expanded, is_selected, &grouped, &th) } else if let Some(dep) = dep { render_dependency_item(dep, is_selected, app, &th) } else { continue; }; lines.push(Line::from(spans)); } // Show range indicator if needed if total_items > available_height { lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t_fmt( app, "app.modals.preflight.deps.showing_range", &[ &(start_idx + 1).to_string(), &end_idx.to_string(), &total_items.to_string(), ], ), Style::default().fg(th.subtext1), ))); } lines }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/tabs/summary.rs
src/ui/modals/preflight/tabs/summary.rs
use ratatui::{ prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, }; use crate::i18n; use crate::state::modal::{ CascadeMode, DependencyInfo, DependencySource, DependencyStatus, PreflightHeaderChips, PreflightSummaryData, }; use crate::state::{AppState, PackageItem, PreflightAction}; use crate::theme::theme; use crate::ui::helpers::ChangeLogger; use std::fmt::Write; use std::sync::{Mutex, OnceLock}; /// What: Bit flags for tracking incomplete preflight data. /// /// Inputs: None (default constructed). /// /// Output: Bit flags indicating which preflight data is incomplete. /// /// Details: Uses a u16 to store multiple boolean flags efficiently. #[derive(Clone, Copy, PartialEq, Eq, Default)] struct IncompleteFlags(u16); impl IncompleteFlags { /// Flag indicating preflight dependencies are incomplete. const PREFLIGHT_DEPS: u16 = 1 << 0; /// Flag indicating dependencies are incomplete. const DEPS: u16 = 1 << 1; /// Flag indicating computed dependencies are incomplete. const COMPUTED_DEPS: u16 = 1 << 2; /// Flag indicating preflight files are incomplete. const PREFLIGHT_FILES: u16 = 1 << 3; /// Flag indicating files are incomplete. const FILES: u16 = 1 << 4; /// Flag indicating preflight sandbox data is incomplete. const PREFLIGHT_SANDBOX: u16 = 1 << 5; /// Flag indicating sandbox data is incomplete. const SANDBOX: u16 = 1 << 6; /// Flag indicating dependencies are incomplete (alternative flag). const DEPS_INCOMPLETE: u16 = 1 << 7; /// Flag to show dependencies indicator. const SHOW_DEPS_INDICATOR: u16 = 1 << 8; /// Flag to show files indicator. const SHOW_FILES_INDICATOR: u16 = 1 << 9; /// Flag to show sandbox indicator. const SHOW_SANDBOX_INDICATOR: u16 = 1 << 10; /// What: Set or clear a flag bit. /// /// Inputs: /// - `bit`: The bit flag to set or clear. /// - `enabled`: Whether to set (true) or clear (false) the bit. /// /// Output: Modifies the flags in place. /// /// Details: Uses bitwise operations to set or clear the specified bit. const fn set(&mut self, bit: u16, enabled: bool) { if enabled { self.0 |= bit; } else { self.0 &= !bit; } } /// What: Check if a flag bit is set. /// /// Inputs: /// - `bit`: The bit flag to check. /// /// Output: Returns true if the bit is set, false otherwise. /// /// Details: Uses bitwise AND to check if the specified bit is set. const fn is_set(self, bit: u16) -> bool { self.0 & bit != 0 } } /// What: State tracking for incomplete preflight data logging. /// /// Inputs: None (constructed from current state). /// /// Output: Captures current incomplete state for logging. /// /// Details: Used to track and log which preflight data is incomplete. #[derive(Clone, PartialEq, Eq)] struct IncompleteLogState { /// Incomplete flags indicating what data is missing. flags: IncompleteFlags, /// Total number of items. item_count: usize, /// Number of packages with dependencies. packages_with_deps_count: usize, /// Number of dependency info entries. dependency_info_count: usize, } fn log_incomplete_state(state: &IncompleteLogState) { static LOGGER: OnceLock<Mutex<ChangeLogger<IncompleteLogState>>> = OnceLock::new(); let mut logger = LOGGER .get_or_init(|| Mutex::new(ChangeLogger::new())) .lock() .expect("Incomplete log state mutex poisoned"); if logger.should_log(state) { let flags = state.flags; tracing::debug!( "[UI] render_incomplete_data_indicator: preflight_deps_resolving={}, deps_resolving={}, computed_deps_resolving={}, files_resolving={}/{}, sandbox_resolving={}/{}, deps_incomplete={}, items={}, packages_with_deps={}, dependency_info={}, show_deps_indicator={}, show_files_indicator={}, show_sandbox_indicator={}", flags.is_set(IncompleteFlags::PREFLIGHT_DEPS), flags.is_set(IncompleteFlags::DEPS), flags.is_set(IncompleteFlags::COMPUTED_DEPS), flags.is_set(IncompleteFlags::PREFLIGHT_FILES), flags.is_set(IncompleteFlags::FILES), flags.is_set(IncompleteFlags::PREFLIGHT_SANDBOX), flags.is_set(IncompleteFlags::SANDBOX), flags.is_set(IncompleteFlags::DEPS_INCOMPLETE), state.item_count, state.packages_with_deps_count, state.dependency_info_count, flags.is_set(IncompleteFlags::SHOW_DEPS_INDICATOR), flags.is_set(IncompleteFlags::SHOW_FILES_INDICATOR), flags.is_set(IncompleteFlags::SHOW_SANDBOX_INDICATOR) ); } } /// What: Get source badge text and color for a dependency source. /// /// Inputs: /// - `source`: The dependency source. /// /// Output: /// - Returns a tuple of (`badge_text`, `color`). /// /// Details: /// - Formats repository names, AUR, and local sources with appropriate colors. fn get_source_badge(source: &DependencySource) -> (String, ratatui::style::Color) { let th = theme(); match source { DependencySource::Official { repo } => { let repo_lower = repo.to_lowercase(); let color = if crate::index::is_eos_repo(&repo_lower) || crate::index::is_cachyos_repo(&repo_lower) { th.sapphire } else { th.green }; (format!(" [{repo}]"), color) } DependencySource::Aur => (" [AUR]".to_string(), th.yellow), DependencySource::Local => (" [local]".to_string(), th.overlay1), } } /// What: Render summary data section (risk factors). /// /// Inputs: /// - `app`: Application state for i18n. /// - `summary_data`: Summary data to render. /// - `header_chips`: Header chip data for risk level. /// /// Output: /// - Returns a vector of lines to render. /// /// Details: /// - Shows risk factors if available. fn render_summary_data( app: &AppState, summary_data: &PreflightSummaryData, header_chips: &PreflightHeaderChips, ) -> Vec<Line<'static>> { let th = theme(); let mut lines = Vec::new(); let risk_color = match header_chips.risk_level { crate::state::modal::RiskLevel::Low => th.green, crate::state::modal::RiskLevel::Medium => th.yellow, crate::state::modal::RiskLevel::High => th.red, }; if !summary_data.risk_reasons.is_empty() { lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.summary.risk_factors"), Style::default().fg(risk_color).add_modifier(Modifier::BOLD), ))); for reason in &summary_data.risk_reasons { let bullet = format!(" • {reason}"); lines.push(Line::from(Span::styled( bullet, Style::default().fg(th.subtext1), ))); } } lines.push(Line::from("")); lines } /// What: Render incomplete data indicator if data is still resolving. /// /// Inputs: /// - `app`: Application state for i18n and resolution flags. /// - `items`: Packages under review. /// - `dependency_info`: Dependency information. /// /// Output: /// - Returns a vector of lines to render, or empty if no incomplete data. /// /// Details: /// - Checks for resolving dependencies, files, and sandbox data. fn render_incomplete_data_indicator( app: &AppState, items: &[PackageItem], dependency_info: &[DependencyInfo], ) -> Vec<Line<'static>> { let th = theme(); let mut lines = Vec::new(); let item_names: std::collections::HashSet<String> = items.iter().map(|i| i.name.clone()).collect(); let packages_with_deps: std::collections::HashSet<String> = dependency_info .iter() .flat_map(|d| d.required_by.iter()) .cloned() .collect(); let packages_with_deps_count = packages_with_deps.len(); // Check if deps data is incomplete for current items (when not resolving) let deps_resolving = app.preflight_deps_resolving || app.deps_resolving; let deps_incomplete = !deps_resolving && !item_names.is_empty() && packages_with_deps_count < items.len() && dependency_info.len() < items.len(); // Check if we actually need to wait for data for the current items // Only show loading indicator if: // 1. Preflight-specific resolution is running (preflight_*_resolving), OR // 2. Global resolution is running (files_resolving, deps_resolving, etc.) // 3. We're missing data for current items (deps_incomplete heuristic) let files_resolving = app.preflight_files_resolving || app.files_resolving; let sandbox_resolving = app.preflight_sandbox_resolving || app.sandbox_resolving; // Show deps indicator when deps are resolving (matches render_deps_tab logic) let show_deps_indicator = deps_resolving || (deps_incomplete && dependency_info.is_empty()); // Show files indicator when files are resolving (matches render_files_tab logic) let show_files_indicator = files_resolving; // Show sandbox indicator when sandbox is resolving let show_sandbox_indicator = sandbox_resolving; let mut flags = IncompleteFlags::default(); flags.set( IncompleteFlags::PREFLIGHT_DEPS, app.preflight_deps_resolving, ); flags.set(IncompleteFlags::DEPS, app.deps_resolving); flags.set(IncompleteFlags::COMPUTED_DEPS, deps_resolving); flags.set( IncompleteFlags::PREFLIGHT_FILES, app.preflight_files_resolving, ); flags.set(IncompleteFlags::FILES, app.files_resolving); flags.set( IncompleteFlags::PREFLIGHT_SANDBOX, app.preflight_sandbox_resolving, ); flags.set(IncompleteFlags::SANDBOX, app.sandbox_resolving); flags.set(IncompleteFlags::DEPS_INCOMPLETE, deps_incomplete); flags.set(IncompleteFlags::SHOW_DEPS_INDICATOR, show_deps_indicator); flags.set(IncompleteFlags::SHOW_FILES_INDICATOR, show_files_indicator); flags.set( IncompleteFlags::SHOW_SANDBOX_INDICATOR, show_sandbox_indicator, ); log_incomplete_state(&IncompleteLogState { flags, item_count: items.len(), packages_with_deps_count, dependency_info_count: dependency_info.len(), }); let has_incomplete_data = show_deps_indicator || show_files_indicator || show_sandbox_indicator || deps_incomplete; if has_incomplete_data { let mut resolving_parts = Vec::new(); if show_deps_indicator { resolving_parts.push(i18n::t(app, "app.modals.preflight.summary.resolving_deps")); } if show_files_indicator { resolving_parts.push(i18n::t(app, "app.modals.preflight.summary.resolving_files")); } if show_sandbox_indicator { resolving_parts.push(i18n::t( app, "app.modals.preflight.summary.resolving_sandbox", )); } if !resolving_parts.is_empty() { lines.push(Line::from("")); let resolving_text = resolving_parts.join(", "); lines.push(Line::from(Span::styled( format!("⟳ {resolving_text}"), Style::default() .fg(th.sapphire) .add_modifier(Modifier::BOLD), ))); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.summary.data_will_update"), Style::default().fg(th.subtext1), ))); } } lines } /// What: Render dependency spans for a conflict or upgrade status. /// /// Inputs: /// - `dep`: Dependency information. /// /// Output: /// - Returns a vector of spans to render. /// /// Details: /// - Formats conflict or upgrade status with appropriate styling. fn render_dependency_spans(dep: &DependencyInfo) -> Option<Vec<Span<'static>>> { let th = theme(); let mut spans = Vec::new(); spans.push(Span::styled(" ", Style::default())); // Indentation match &dep.status { DependencyStatus::Conflict { reason } => { spans.push(Span::styled("⚠ ", Style::default().fg(th.red))); spans.push(Span::styled(dep.name.clone(), Style::default().fg(th.text))); if !dep.version.is_empty() { spans.push(Span::styled( format!(" {}", dep.version), Style::default().fg(th.overlay2), )); } let (source_badge, badge_color) = get_source_badge(&dep.source); spans.push(Span::styled(source_badge, Style::default().fg(badge_color))); spans.push(Span::styled( format!(" ({reason})"), Style::default().fg(th.red), )); } DependencyStatus::ToUpgrade { current, required } => { spans.push(Span::styled("↑ ", Style::default().fg(th.yellow))); spans.push(Span::styled(dep.name.clone(), Style::default().fg(th.text))); if !dep.version.is_empty() { let dep_version = &dep.version; spans.push(Span::styled( format!(" {dep_version}"), Style::default().fg(th.overlay2), )); } let (source_badge, badge_color) = get_source_badge(&dep.source); spans.push(Span::styled(source_badge, Style::default().fg(badge_color))); spans.push(Span::styled( format!(" ({current} → {required})"), Style::default().fg(th.yellow), )); } _ => return None, } Some(spans) } /// What: Filter installed packages from items list. /// /// Inputs: /// - `items`: List of packages to check. /// /// Output: /// - Vector of references to packages that are already installed. fn filter_installed_packages(items: &[PackageItem]) -> Vec<&PackageItem> { items .iter() .filter(|item| crate::index::is_installed(&item.name)) .collect() } /// What: Filter important dependencies (conflicts and upgrades). /// /// Inputs: /// - `dependency_info`: List of dependency information. /// /// Output: /// - Vector of references to dependencies with conflicts or upgrades. fn filter_important_deps(dependency_info: &[DependencyInfo]) -> Vec<&DependencyInfo> { dependency_info .iter() .filter(|d| { matches!( d.status, DependencyStatus::Conflict { .. } | DependencyStatus::ToUpgrade { .. } ) }) .collect() } /// What: Group dependencies by the packages that require them. /// /// Inputs: /// - `important_deps`: List of important dependencies. /// /// Output: /// - `HashMap` mapping package names to their dependencies. fn group_dependencies_by_package<'a>( important_deps: &[&'a DependencyInfo], ) -> std::collections::HashMap<String, Vec<&'a DependencyInfo>> { use std::collections::HashMap; let mut grouped: HashMap<String, Vec<&DependencyInfo>> = HashMap::new(); for dep in important_deps { for req_by in &dep.required_by { grouped.entry(req_by.clone()).or_default().push(*dep); } } grouped } /// What: Build summary parts for conflicts, upgrades, and installed packages. /// /// Inputs: /// - `app`: Application state for i18n. /// - `conflict_count`: Number of conflicts. /// - `upgrade_count`: Number of upgrades. /// - `installed_count`: Number of installed packages. /// /// Output: /// - Vector of formatted summary strings. fn build_summary_parts( app: &AppState, conflict_count: usize, upgrade_count: usize, installed_count: usize, ) -> Vec<String> { let mut summary_parts = Vec::new(); if conflict_count > 0 { summary_parts.push(i18n::t_fmt1( app, "app.modals.preflight.summary.conflict_singular", conflict_count, )); } if upgrade_count > 0 { summary_parts.push(i18n::t_fmt1( app, "app.modals.preflight.summary.upgrade_singular", upgrade_count, )); } if installed_count > 0 { summary_parts.push(i18n::t_fmt1( app, "app.modals.preflight.summary.installed_singular", installed_count, )); } summary_parts } /// What: Build display items list for rendering. /// /// Inputs: /// - `items`: List of packages. /// - `grouped`: Dependencies grouped by package. /// - `installed_packages`: List of installed packages. /// /// Output: /// - Vector of (`is_header`, `package_name`, `optional_dependency`) tuples. fn build_display_items<'a>( items: &[PackageItem], grouped: &std::collections::HashMap<String, Vec<&'a DependencyInfo>>, installed_packages: &[&PackageItem], ) -> Vec<(bool, String, Option<&'a DependencyInfo>)> { use std::collections::HashSet; let mut display_items: Vec<(bool, String, Option<&DependencyInfo>)> = Vec::new(); for pkg_name in items.iter().map(|p| &p.name) { if let Some(pkg_deps) = grouped.get(pkg_name) { display_items.push((true, pkg_name.clone(), None)); let mut seen_deps = HashSet::new(); for dep in pkg_deps { if seen_deps.insert(dep.name.as_str()) { display_items.push((false, String::new(), Some(*dep))); } } } } for installed_pkg in installed_packages { if !grouped.contains_key(&installed_pkg.name) { display_items.push((true, installed_pkg.name.clone(), None)); display_items.push((false, installed_pkg.name.clone(), None)); } } display_items } /// What: Render install action dependencies (conflicts and upgrades). /// /// Inputs: /// - `app`: Application state for i18n. /// - `items`: Packages under review. /// - `dependency_info`: Dependency information. /// - `summary_data`: Optional summary data containing package notes. /// /// Output: /// - Returns a vector of lines to render. /// /// Details: /// - Shows conflicts and upgrades grouped by package. /// - Displays installed packages separately. /// - Shows package notes (e.g., "Required by installed packages") from summary data. fn render_install_dependencies( app: &AppState, items: &[PackageItem], dependency_info: &[DependencyInfo], summary_data: Option<&PreflightSummaryData>, ) -> Vec<Line<'static>> { let th = theme(); let mut lines = Vec::new(); let installed_packages = filter_installed_packages(items); let important_deps = filter_important_deps(dependency_info); if important_deps.is_empty() && installed_packages.is_empty() { lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.summary.no_conflicts_or_upgrades"), Style::default().fg(th.green), ))); return lines; } let grouped = group_dependencies_by_package(&important_deps); let conflict_count = important_deps .iter() .filter(|d| matches!(d.status, DependencyStatus::Conflict { .. })) .count(); let upgrade_count = important_deps .iter() .filter(|d| matches!(d.status, DependencyStatus::ToUpgrade { .. })) .count(); let installed_count = installed_packages.len(); let summary_parts = build_summary_parts(app, conflict_count, upgrade_count, installed_count); let header_text = if conflict_count > 0 || installed_count > 0 { i18n::t_fmt1( app, "app.modals.preflight.summary.issues", summary_parts.join(", "), ) } else if upgrade_count > 0 { i18n::t_fmt1( app, "app.modals.preflight.summary.summary_label", summary_parts.join(", "), ) } else { i18n::t(app, "app.modals.preflight.summary.summary_no_conflicts") }; lines.push(Line::from(Span::styled( header_text, Style::default() .fg(if conflict_count > 0 || installed_count > 0 { th.red } else { th.yellow }) .add_modifier(Modifier::BOLD), ))); lines.push(Line::from("")); let display_items = build_display_items(items, &grouped, &installed_packages); // Render all items (no viewport - mouse scrolling handles it) for (is_header, pkg_name, dep) in &display_items { if *is_header { let style = Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD); lines.push(Line::from(Span::styled(format!("▶ {pkg_name}"), style))); // Show package notes from summary data (e.g., "Required by installed packages") if let Some(summary) = summary_data && let Some(pkg_summary) = summary.packages.iter().find(|p| p.name == *pkg_name) { for note in &pkg_summary.notes { // Show notes about dependent packages if note.contains("Required by") { lines.push(Line::from(Span::styled( format!(" ⚠ {note}"), Style::default().fg(th.yellow), ))); } } } } else if let Some(dep) = dep { if let Some(spans) = render_dependency_spans(dep) { lines.push(Line::from(spans)); } } else if !pkg_name.is_empty() && installed_packages.iter().any(|p| p.name == *pkg_name) { // This is an installed package entry (not a real dependency) // Show "installed" status let spans = vec![ Span::styled(" ", Style::default()), Span::styled("✓ ", Style::default().fg(th.green)), Span::styled(pkg_name.clone(), Style::default().fg(th.text)), Span::styled(" (installed)", Style::default().fg(th.subtext1)), ]; lines.push(Line::from(spans)); } } lines } /// Maximum number of cascade preview items to display. const CASCADE_PREVIEW_MAX: usize = 8; /// What: Context data for cascade rendering operations. /// /// Inputs: /// - `removal_targets`: Set of package names to be removed (lowercase). /// - `allows_dependents`: Cached value of `cascade_mode.allows_dependents()`. /// /// Output: /// - Returns a `CascadeRenderingContext` struct. /// /// Details: /// - Groups related data to reduce parameter passing and variable scope. struct CascadeRenderingContext { /// Set of package names to be removed (lowercase). removal_targets: std::collections::HashSet<String>, /// Whether the cascade mode allows dependents. allows_dependents: bool, } impl CascadeRenderingContext { /// What: Create a new cascade rendering context. /// /// Inputs: /// - `items`: Packages to remove. /// - `cascade_mode`: Removal cascade mode. /// /// Output: /// - Returns a `CascadeRenderingContext`. /// /// Details: /// - Pre-computes removal targets and `allows_dependents` flag. fn new(items: &[PackageItem], cascade_mode: CascadeMode) -> Self { let removal_targets: std::collections::HashSet<String> = items .iter() .map(|pkg| pkg.name.to_ascii_lowercase()) .collect(); let allows_dependents = cascade_mode.allows_dependents(); Self { removal_targets, allows_dependents, } } /// What: Check if a dependency is directly dependent on removal targets. /// /// Inputs: /// - `dep`: Dependency information. /// /// Output: /// - Returns true if dependency is directly dependent. /// /// Details: /// - Checks if any parent in `depends_on` is in `removal_targets`. fn is_direct_dependent(&self, dep: &DependencyInfo) -> bool { dep.depends_on .iter() .any(|parent| self.removal_targets.contains(&parent.to_ascii_lowercase())) } } /// What: Display information for a cascade candidate dependency. /// /// Inputs: /// - `bullet`: Bullet character to display. /// - `name_color`: Color for the dependency name. /// - `detail`: Detail text about the dependency status. /// - `roots`: Formatted string of packages that require this dependency. /// /// Output: /// - Returns a `DependencyDisplayInfo` struct. /// /// Details: /// - Groups all display-related data for a dependency. struct DependencyDisplayInfo { /// Bullet character for display. bullet: &'static str, /// Color for the package name. name_color: ratatui::style::Color, /// Detail text to display. detail: String, /// Root packages text. roots: String, } /// What: Get bullet character and name color for a dependency based on cascade mode. /// /// Inputs: /// - `allows_dependents`: Whether cascade mode allows dependents. /// - `is_direct`: Whether dependency is directly dependent. /// - `th`: Theme colors. /// /// Output: /// - Returns a tuple of (`bullet`, `name_color`). /// /// Details: /// - Simplifies conditional logic for bullet and color selection. const fn get_bullet_and_color( allows_dependents: bool, is_direct: bool, th: &crate::theme::Theme, ) -> (&'static str, ratatui::style::Color) { if allows_dependents { if is_direct { ("● ", th.red) } else { ("○ ", th.yellow) } } else if is_direct { ("⛔ ", th.red) } else { ("⚠ ", th.yellow) } } /// What: Get detail text for a dependency status. /// /// Inputs: /// - `app`: Application state for i18n. /// - `status`: Dependency status. /// /// Output: /// - Returns detail text string. /// /// Details: /// - Extracts status-to-text conversion logic. fn get_dependency_detail(app: &AppState, status: &DependencyStatus) -> String { match status { DependencyStatus::Conflict { reason } => reason.clone(), DependencyStatus::ToUpgrade { .. } => { i18n::t(app, "app.modals.preflight.summary.requires_version_change") } DependencyStatus::Installed { .. } => { i18n::t(app, "app.modals.preflight.summary.already_satisfied") } DependencyStatus::ToInstall => { i18n::t(app, "app.modals.preflight.summary.not_currently_installed") } DependencyStatus::Missing => i18n::t(app, "app.modals.preflight.summary.missing"), } } /// What: Build dependency display information. /// /// Inputs: /// - `app`: Application state for i18n. /// - `dep`: Dependency information. /// - `ctx`: Cascade rendering context. /// - `th`: Theme colors. /// - `is_direct`: Pre-computed flag indicating if dependency is directly dependent. /// /// Output: /// - Returns `DependencyDisplayInfo`. /// /// Details: /// - Prepares all display data for a dependency in one place. /// - Uses pre-computed `is_direct` to avoid recalculation. fn build_dependency_display_info( app: &AppState, dep: &DependencyInfo, ctx: &CascadeRenderingContext, th: &crate::theme::Theme, is_direct: bool, ) -> DependencyDisplayInfo { let (bullet, name_color) = get_bullet_and_color(ctx.allows_dependents, is_direct, th); let detail = get_dependency_detail(app, &dep.status); let roots = if dep.required_by.is_empty() { String::new() } else { i18n::t_fmt1( app, "app.modals.preflight.summary.targets_label", dep.required_by.join(", "), ) }; DependencyDisplayInfo { bullet, name_color, detail, roots, } } /// What: Build spans for a cascade candidate dependency. /// /// Inputs: /// - `dep`: Dependency information. /// - `display_info`: Display information for the dependency. /// - `th`: Theme colors. /// /// Output: /// - Returns a vector of spans. /// /// Details: /// - Uses builder pattern to construct dependency spans. fn build_cascade_dependency_spans( dep: &DependencyInfo, display_info: &DependencyDisplayInfo, th: &crate::theme::Theme, ) -> Vec<Span<'static>> { let mut spans = Vec::new(); spans.push(Span::styled( display_info.bullet, Style::default().fg(th.subtext0), )); spans.push(Span::styled( dep.name.clone(), Style::default() .fg(display_info.name_color) .add_modifier(Modifier::BOLD), )); if !display_info.detail.is_empty() { spans.push(Span::styled(" — ", Style::default().fg(th.subtext1))); spans.push(Span::styled( display_info.detail.clone(), Style::default().fg(th.subtext1), )); } if !display_info.roots.is_empty() { spans.push(Span::styled( display_info.roots.clone(), Style::default().fg(th.overlay1), )); } spans } /// What: Render cascade mode header. /// /// Inputs: /// - `app`: Application state for i18n. /// - `cascade_mode`: Removal cascade mode. /// /// Output: /// - Returns a vector of lines to render. /// /// Details: /// - Renders the cascade mode information header. fn render_cascade_mode_header(app: &AppState, cascade_mode: CascadeMode) -> Vec<Line<'static>> { let th = theme(); let mode_line = i18n::t_fmt( app, "app.modals.preflight.summary.cascade_mode", &[&cascade_mode.flag(), &cascade_mode.description()], ); vec![ Line::from(Span::styled( mode_line, Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), )), Line::from(""), ] } /// What: Render removal plan command. /// /// Inputs: /// - `app`: Application state for i18n and `dry_run` flag. /// - `items`: Packages to remove. /// - `cascade_mode`: Removal cascade mode. /// /// Output: /// - Returns a vector of lines to render. /// /// Details: /// - Renders the removal plan preview with command. fn render_removal_plan( app: &AppState, items: &[PackageItem], cascade_mode: CascadeMode, ) -> Vec<Line<'static>> { let th = theme(); let removal_names: Vec<&str> = items.iter().map(|pkg| pkg.name.as_str()).collect(); let plan_header_style = Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD); let mut plan_command = format!( "sudo pacman {} --noconfirm {}", cascade_mode.flag(), removal_names.join(" ") ); if app.dry_run { plan_command = i18n::t_fmt1( app, "app.modals.preflight.summary.dry_run_prefix", plan_command, ); } vec![ Line::from(Span::styled( i18n::t(app, "app.modals.preflight.summary.removal_plan_preview"), plan_header_style, )), Line::from(Span::styled(plan_command, Style::default().fg(th.text))), ] } /// What: Get dependent summary text and style. /// /// Inputs: /// - `app`: Application state for i18n. /// - `dependent_count`: Number of dependent packages. /// - `allows_dependents`: Whether cascade mode allows dependents. /// /// Output: /// - Returns a tuple of (text, style). /// /// Details: /// - Determines summary message based on dependent count and cascade mode. fn get_dependent_summary( app: &AppState, dependent_count: usize, allows_dependents: bool, ) -> (String, Style) { let th = theme(); if dependent_count == 0 { ( i18n::t(app, "app.modals.preflight.summary.no_dependents"), Style::default().fg(th.green), ) } else if allows_dependents { ( i18n::t_fmt1( app, "app.modals.preflight.summary.cascade_will_include", dependent_count, ), Style::default().fg(th.yellow), ) } else { ( i18n::t_fmt1( app, "app.modals.preflight.summary.dependents_block_removal", dependent_count, ), Style::default().fg(th.red), ) } } /// What: Render dependent summary section. /// /// Inputs: /// - `app`: Application state for i18n. /// - `dependent_count`: Number of dependent packages. /// - `allows_dependents`: Whether cascade mode allows dependents. /// /// Output: /// - Returns a vector of lines to render. /// /// Details: /// - Renders the summary of dependent packages. fn render_dependent_summary( app: &AppState, dependent_count: usize, allows_dependents: bool, ) -> Vec<Line<'static>> { let (summary_text, summary_style) =
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
true
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/tabs/mod.rs
src/ui/modals/preflight/tabs/mod.rs
/// Dependencies tab rendering for preflight modal. pub mod deps; /// Files tab rendering for preflight modal. pub mod files; /// Sandbox tab rendering for preflight modal. pub mod sandbox; /// Services tab rendering for preflight modal. pub mod services; /// Summary tab rendering for preflight modal. pub mod summary; pub use deps::render_deps_tab; pub use files::render_files_tab; pub use sandbox::{SandboxTabContext, render_sandbox_tab}; pub use services::render_services_tab; pub use summary::render_summary_tab;
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/modals/preflight/tabs/files.rs
src/ui/modals/preflight/tabs/files.rs
use ratatui::{ prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, }; use crate::i18n; use crate::state::modal::{FileChangeType, PackageFileInfo}; use crate::state::{AppState, PackageItem}; use crate::theme::theme; use crate::ui::helpers::ChangeLogger; use crate::ui::modals::preflight::helpers::format_count_with_indicator; use std::sync::{Mutex, OnceLock}; /// Type alias for file display item tuple. /// /// Tuple structure: /// - Field 0 (bool): Whether the package entry is expanded to show files. /// - Field 1 (String): Package name. /// - Field 2 (Option<(`FileChangeType`, String, bool, bool, bool)>): Optional file information. /// When Some, contains: (`change_type`, `file_path`, `is_new`, `is_changed`, `is_removed`). type FileDisplayItem = ( bool, String, Option<(FileChangeType, String, bool, bool, bool)>, ); /// Summary of file changes for a single package. #[derive(Clone, PartialEq, Eq)] struct FilePackageSummary { /// Package name. name: String, /// Total number of file changes. total: usize, /// Number of new files. new_count: usize, /// Number of changed files. changed_count: usize, /// Number of removed files. removed_count: usize, /// Number of configuration files. config_count: usize, /// Total number of file entries. file_entries: usize, } /// State tracking for files tab logging. #[derive(Clone, PartialEq, Eq)] struct FilesLogState { /// Number of package items. items_len: usize, /// Number of file info entries. file_info_len: usize, /// Currently selected file index. file_selected: usize, /// Number of expanded tree nodes. expanded_len: usize, /// Whether preflight file resolution is in progress. preflight_resolving: bool, /// Whether global file resolution is in progress. global_resolving: bool, /// Whether an error occurred. has_error: bool, /// Package summaries for file changes. package_summaries: Vec<FilePackageSummary>, } fn log_files_state(state: &FilesLogState) { static LOGGER: OnceLock<Mutex<ChangeLogger<FilesLogState>>> = OnceLock::new(); let mut logger = LOGGER .get_or_init(|| Mutex::new(ChangeLogger::new())) .lock() .expect("Files log state mutex poisoned"); if logger.should_log(state) { let package_text = if state.package_summaries.is_empty() { "no file details".to_string() } else { state .package_summaries .iter() .map(|p| { format!( "{}: total={}, new={}, changed={}, removed={}, config={}, files={}", p.name, p.total, p.new_count, p.changed_count, p.removed_count, p.config_count, p.file_entries ) }) .collect::<Vec<_>>() .join(" | ") }; tracing::debug!( "[UI] render_files_tab: items={}, file_info={}, file_selected={}, expanded={}, resolving={}/{}, error={}, packages=[{}]", state.items_len, state.file_info_len, state.file_selected, state.expanded_len, state.preflight_resolving, state.global_resolving, state.has_error, package_text ); } } /// What: Render loading/resolving state with package headers. /// /// Inputs: /// - `app`: Application state for i18n. /// - `items`: Packages under review. /// - `message_key`: i18n key for the message to display. /// - `message_color`: Color for the message text. /// /// Output: /// - Returns a vector of lines to render. fn render_loading_state( app: &AppState, items: &[PackageItem], message_key: &str, message_color: ratatui::style::Color, ) -> Vec<Line<'static>> { let th = theme(); let mut lines = Vec::new(); for item in items { let mut spans = Vec::new(); spans.push(Span::styled( format!("▶ {} ", item.name), Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD), )); spans.push(Span::styled("(0 files)", Style::default().fg(th.subtext1))); lines.push(Line::from(spans)); } lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t(app, message_key), Style::default().fg(message_color), ))); lines } /// What: Render error state with retry hint. /// /// Inputs: /// - `app`: Application state for i18n. /// - `err_msg`: Error message to display. /// /// Output: /// - Returns a vector of lines to render. fn render_error_state(app: &AppState, err_msg: &str) -> Vec<Line<'static>> { let th = theme(); vec![ Line::from(Span::styled( i18n::t_fmt1(app, "app.modals.preflight.files.error", err_msg), Style::default().fg(th.red), )), Line::from(""), Line::from(Span::styled( i18n::t(app, "app.modals.preflight.files.retry_hint"), Style::default().fg(th.subtext1), )), ] } /// What: Build flat list of display items from file info. /// /// Inputs: /// - `items`: All packages under review. /// - `file_info`: File information. /// - `file_tree_expanded`: Set of expanded package names. /// /// Output: /// - Returns a vector of display items (headers and files). /// /// Details: /// - Always shows ALL packages from items, even if they have no files. /// - This ensures packages that failed to resolve files (e.g., due to conflicts) are still visible. fn build_display_items( items: &[PackageItem], file_info: &[PackageFileInfo], file_tree_expanded: &std::collections::HashSet<String>, ) -> Vec<FileDisplayItem> { use std::collections::HashMap; // Create a map for quick lookup of file info by package name let file_info_map: HashMap<String, &PackageFileInfo> = file_info .iter() .map(|info| (info.name.clone(), info)) .collect(); let mut display_items = Vec::new(); // Always show ALL packages from items, even if they have no file info for item in items { let pkg_name = &item.name; let is_expanded = file_tree_expanded.contains(pkg_name); display_items.push((true, pkg_name.clone(), None)); // Package header if is_expanded { // Show files if available if let Some(pkg_info) = file_info_map.get(pkg_name) { for file in &pkg_info.files { display_items.push(( false, String::new(), Some(( file.change_type.clone(), file.path.clone(), file.is_config, file.predicted_pacnew, file.predicted_pacsave, )), )); } } } } display_items } /// What: Render sync timestamp line. /// /// Inputs: /// - `app`: Application state for i18n. /// - `sync_info`: Optional sync info tuple (`age_days`, `date_str`, `color_category`). /// /// Output: /// - Returns optional line and number of lines added (0 or 2). fn render_sync_timestamp( app: &AppState, sync_info: Option<&(u64, String, u8)>, ) -> (Option<Line<'static>>, usize) { let th = theme(); if let Some((_age_days, date_str, color_category)) = sync_info { let (sync_color, sync_text) = match color_category { 0 => ( th.green, i18n::t_fmt1(app, "app.modals.preflight.files.files_updated_on", date_str), ), 1 => ( th.yellow, i18n::t_fmt1(app, "app.modals.preflight.files.files_updated_on", date_str), ), _ => ( th.red, i18n::t_fmt1(app, "app.modals.preflight.files.files_updated_on", date_str), ), }; ( Some(Line::from(Span::styled( sync_text, Style::default().fg(sync_color), ))), 2, ) } else { (None, 0) } } /// What: Render empty state when no files are found. /// /// Inputs: /// - `app`: Application state for i18n. /// - `items`: Packages under review. /// - `file_info`: File information. /// - `is_stale`: Whether file database is stale. /// - `sync_info`: Optional sync info. /// /// Output: /// - Returns a vector of lines to render. fn render_empty_state( app: &AppState, items: &[PackageItem], file_info: &[PackageFileInfo], is_stale: Option<&bool>, sync_info: Option<&(u64, String, u8)>, ) -> Vec<Line<'static>> { let th = theme(); let mut lines = Vec::new(); let has_aur_packages = items .iter() .any(|p| matches!(p.source, crate::state::Source::Aur)); let has_official_packages = items .iter() .any(|p| matches!(p.source, crate::state::Source::Official { .. })); let mut unresolved_packages = Vec::new(); for pkg_info in file_info { if pkg_info.files.is_empty() { unresolved_packages.push(pkg_info.name.clone()); } } if file_info.is_empty() { lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.files.file_resolution_progress"), Style::default().fg(th.subtext1), ))); } else if unresolved_packages.is_empty() { lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.files.no_file_changes_display"), Style::default().fg(th.subtext1), ))); } else { lines.push(Line::from(Span::styled( i18n::t_fmt1( app, "app.modals.preflight.files.no_file_changes", unresolved_packages.len(), ), Style::default().fg(th.subtext1), ))); lines.push(Line::from("")); if has_official_packages { lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.files.file_db_sync_note"), Style::default().fg(th.subtext0), ))); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.files.sync_file_db_hint"), Style::default().fg(th.subtext0), ))); } if has_aur_packages { lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.files.aur_file_note"), Style::default().fg(th.subtext0), ))); } } if matches!(is_stale, Some(true)) { lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.files.file_db_stale"), Style::default().fg(th.yellow), ))); lines.push(Line::from(Span::styled( i18n::t(app, "app.modals.preflight.files.sync_file_db_root"), Style::default().fg(th.subtext0), ))); } let (sync_line, _) = render_sync_timestamp(app, sync_info); if let Some(line) = sync_line { lines.push(Line::from("")); lines.push(line); } lines } /// What: Render package header line. /// /// Inputs: /// - `app`: Application state for i18n. /// - `pkg_info`: Package file information. /// - `pkg_name`: Package name. /// - `is_expanded`: Whether package is expanded. /// - `is_selected`: Whether package is selected. /// /// Output: /// - Returns a line to render. fn render_package_header( app: &AppState, pkg_info: &PackageFileInfo, pkg_name: &str, is_expanded: bool, is_selected: bool, ) -> Line<'static> { let th = theme(); let arrow_symbol = if is_expanded { "▼" } else { "▶" }; let header_style = if is_selected { Style::default() .fg(th.crust) .bg(th.lavender) .add_modifier(Modifier::BOLD) } else { Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD) }; let total_count = pkg_info.total_count; let mut spans = vec![ Span::styled(format!("{arrow_symbol} {pkg_name} "), header_style), Span::styled( format!("({total_count} files"), Style::default().fg(th.subtext1), ), ]; if pkg_info.new_count > 0 { spans.push(Span::styled( format!( ", {}", i18n::t_fmt1(app, "app.modals.preflight.files.new", pkg_info.new_count) ), Style::default().fg(th.green), )); } if pkg_info.changed_count > 0 { let changed_count = pkg_info.changed_count; spans.push(Span::styled( format!(", {changed_count} changed"), Style::default().fg(th.yellow), )); } if pkg_info.removed_count > 0 { let removed_count = pkg_info.removed_count; spans.push(Span::styled( format!(", {removed_count} removed"), Style::default().fg(th.red), )); } if pkg_info.config_count > 0 { let config_count = pkg_info.config_count; spans.push(Span::styled( format!(", {config_count} config"), Style::default().fg(th.mauve), )); } if pkg_info.pacnew_candidates > 0 { let pacnew_candidates = pkg_info.pacnew_candidates; spans.push(Span::styled( format!(", {pacnew_candidates} pacnew"), Style::default().fg(th.yellow), )); } if pkg_info.pacsave_candidates > 0 { let pacsave_candidates = pkg_info.pacsave_candidates; spans.push(Span::styled( format!(", {pacsave_candidates} pacsave"), Style::default().fg(th.red), )); } spans.push(Span::styled(")", Style::default().fg(th.subtext1))); Line::from(spans) } /// What: Aggregated file totals across all packages. /// /// Details: /// - Contains sums of all file counts from package file information. struct FileTotals { /// Total number of files. files: usize, /// Number of new files. new: usize, /// Number of changed files. changed: usize, /// Number of removed files. removed: usize, /// Number of config files. config: usize, /// Number of .pacnew files. pacnew: usize, /// Number of .pacsave files. pacsave: usize, } /// What: Calculate file totals from package file information in a single pass. /// /// Inputs: /// - `file_info`: File information for all packages. /// /// Output: /// - Returns aggregated file totals. /// /// Details: /// - Performs a single iteration over `file_info` to calculate all totals. fn calculate_file_totals(file_info: &[PackageFileInfo]) -> FileTotals { file_info.iter().fold( FileTotals { files: 0, new: 0, changed: 0, removed: 0, config: 0, pacnew: 0, pacsave: 0, }, |acc, p| FileTotals { files: acc.files + p.total_count, new: acc.new + p.new_count, changed: acc.changed + p.changed_count, removed: acc.removed + p.removed_count, config: acc.config + p.config_count, pacnew: acc.pacnew + p.pacnew_candidates, pacsave: acc.pacsave + p.pacsave_candidates, }, ) } /// What: Build summary parts for file list header. /// /// Inputs: /// - `app`: Application state for i18n. /// - `totals`: Aggregated file totals. /// - `items_len`: Number of packages. /// - `has_incomplete_data`: Whether data is incomplete. /// /// Output: /// - Returns vector of formatted summary strings. /// /// Details: /// - Formats counts with indicators when data is incomplete. fn build_summary_parts( app: &AppState, totals: &FileTotals, items_len: usize, has_incomplete_data: bool, ) -> Vec<String> { let total_files_text = format_count_with_indicator(totals.files, items_len * 10, has_incomplete_data); let mut summary_parts = vec![i18n::t_fmt1( app, "app.modals.preflight.files.total", total_files_text, )]; if totals.new > 0 { let count_text = format_count_with_indicator(totals.new, totals.files, has_incomplete_data); summary_parts.push(i18n::t_fmt1( app, "app.modals.preflight.files.new", count_text, )); } if totals.changed > 0 { let count_text = format_count_with_indicator(totals.changed, totals.files, has_incomplete_data); summary_parts.push(i18n::t_fmt1( app, "app.modals.preflight.files.changed", count_text, )); } if totals.removed > 0 { let count_text = format_count_with_indicator(totals.removed, totals.files, has_incomplete_data); summary_parts.push(i18n::t_fmt1( app, "app.modals.preflight.files.removed", count_text, )); } if totals.config > 0 { let count_text = format_count_with_indicator(totals.config, totals.files, has_incomplete_data); summary_parts.push(i18n::t_fmt1( app, "app.modals.preflight.files.config", count_text, )); } if totals.pacnew > 0 { summary_parts.push(i18n::t_fmt1( app, "app.modals.preflight.files.pacnew", totals.pacnew, )); } if totals.pacsave > 0 { summary_parts.push(i18n::t_fmt1( app, "app.modals.preflight.files.pacsave", totals.pacsave, )); } summary_parts } /// What: Calculate viewport range for scrolling file list. /// /// Inputs: /// - `total_items`: Total number of display items. /// - `available_height`: Available height in lines. /// - `file_selected`: Currently selected file index (mutable, will be clamped). /// /// Output: /// - Returns tuple of (`start_idx`, `end_idx`) for visible range. /// /// Details: /// - Centers selected item when possible. /// - Ensures selected item is always visible. /// - Clamps `file_selected` to valid range. fn calculate_viewport( total_items: usize, available_height: usize, file_selected: &mut usize, ) -> (usize, usize) { let file_selected_clamped = (*file_selected).min(total_items.saturating_sub(1)); if *file_selected != file_selected_clamped { *file_selected = file_selected_clamped; } if total_items <= available_height { // All items fit on screen (0, total_items) } else { // Try to center the selected item let start = file_selected_clamped .saturating_sub(available_height / 2) .min(total_items.saturating_sub(available_height)); let end = (start + available_height).min(total_items); // Safety check: ensure selected item is always visible if file_selected_clamped < start { // Selected is before start - adjust to include it ( file_selected_clamped, (file_selected_clamped + available_height).min(total_items), ) } else if file_selected_clamped >= end { // Selected is at or beyond end - position it at bottom let new_end = (file_selected_clamped + 1).min(total_items); (new_end.saturating_sub(available_height).max(0), new_end) } else { (start, end) } } } /// What: Render header for package with no file info. /// /// Inputs: /// - `pkg_name`: Package name. /// - `is_expanded`: Whether package is expanded. /// - `is_selected`: Whether package is selected. /// /// Output: /// - Returns a line to render. /// /// Details: /// - Used when package file info is not yet available. fn render_missing_package_header( pkg_name: &str, is_expanded: bool, is_selected: bool, ) -> Line<'static> { let th = theme(); let arrow_symbol = if is_expanded { "▼" } else { "▶" }; let header_style = if is_selected { Style::default() .fg(th.crust) .bg(th.lavender) .add_modifier(Modifier::BOLD) } else { Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD) }; let spans = vec![ Span::styled(format!("{arrow_symbol} {pkg_name} "), header_style), Span::styled("(0 files)", Style::default().fg(th.subtext1)), ]; Line::from(spans) } /// What: Render display items within viewport range. /// /// Inputs: /// - `app`: Application state for i18n. /// - `display_items`: Flat list of display items. /// - `file_info`: File information for packages. /// - `file_tree_expanded`: Set of expanded package names. /// - `file_selected`: Currently selected file index. /// - `start_idx`: Start index of viewport. /// - `end_idx`: End index of viewport. /// /// Output: /// - Returns a vector of lines to render. /// /// Details: /// - Renders only items within the viewport range. /// - Handles both package headers and file entries. fn render_display_items( app: &AppState, display_items: &[FileDisplayItem], file_info: &[PackageFileInfo], file_tree_expanded: &std::collections::HashSet<String>, file_selected: usize, start_idx: usize, end_idx: usize, ) -> Vec<Line<'static>> { let mut lines = Vec::new(); for (display_idx, (is_header, pkg_name, file_opt)) in display_items .iter() .enumerate() .skip(start_idx) .take(end_idx - start_idx) { let is_selected = display_idx == file_selected; if *is_header { let is_expanded = file_tree_expanded.contains(pkg_name); // Handle packages that may not have file info yet if let Some(pkg_info) = file_info.iter().find(|p| p.name == *pkg_name) { lines.push(render_package_header( app, pkg_info, pkg_name, is_expanded, is_selected, )); } else { lines.push(render_missing_package_header( pkg_name, is_expanded, is_selected, )); } } else if let Some((change_type, path, is_config, predicted_pacnew, predicted_pacsave)) = file_opt { lines.push(render_file_entry( app, change_type, path, *is_config, *predicted_pacnew, *predicted_pacsave, is_selected, )); } } lines } /// What: Context for rendering file list. /// /// Details: /// - Groups related parameters to reduce function signature complexity. struct FileListContext<'a> { /// Package file information. file_info: &'a [PackageFileInfo], /// Package items. items: &'a [PackageItem], /// Display items for rendering. display_items: &'a [FileDisplayItem], /// Set of expanded package names in the tree view. file_tree_expanded: &'a std::collections::HashSet<String>, /// Optional sync information tuple: (`download_size`, `package_name`, `risk_level`). sync_info: &'a Option<(u64, String, u8)>, } /// What: Render file entry line. /// /// Inputs: /// - `app`: Application state for i18n. /// - `change_type`: Type of file change. /// - `path`: File path. /// - `is_config`: Whether file is a config file. /// - `predicted_pacnew`: Whether pacnew is predicted. /// - `predicted_pacsave`: Whether pacsave is predicted. /// - `is_selected`: Whether file is selected. /// /// Output: /// - Returns a line to render. #[allow(clippy::fn_params_excessive_bools)] fn render_file_entry( app: &AppState, change_type: &FileChangeType, path: &str, is_config: bool, predicted_pacnew: bool, predicted_pacsave: bool, is_selected: bool, ) -> Line<'static> { let th = theme(); let (icon, color) = match change_type { FileChangeType::New => ("+", th.green), FileChangeType::Changed => ("~", th.yellow), FileChangeType::Removed => ("-", th.red), }; let highlight_bg = if is_selected { Some(th.lavender) } else { None }; let icon_style = highlight_bg.map_or_else( || Style::default().fg(color), |bg| Style::default().fg(color).bg(bg), ); let mut spans = vec![Span::styled(format!(" {icon} "), icon_style)]; if is_config { let cfg_style = highlight_bg.map_or_else( || Style::default().fg(th.mauve), |bg| Style::default().fg(th.mauve).bg(bg), ); spans.push(Span::styled("⚙ ", cfg_style)); } if predicted_pacnew { let pacnew_style = highlight_bg.map_or_else( || Style::default().fg(th.yellow), |bg| Style::default().fg(th.yellow).bg(bg), ); spans.push(Span::styled( i18n::t(app, "app.modals.preflight.files.pacnew_label"), pacnew_style, )); } if predicted_pacsave { let pacsave_style = highlight_bg.map_or_else( || Style::default().fg(th.red), |bg| Style::default().fg(th.red).bg(bg), ); spans.push(Span::styled( i18n::t(app, "app.modals.preflight.files.pacsave_label"), pacsave_style, )); } let path_style = highlight_bg.map_or_else( || Style::default().fg(th.text), |bg| { Style::default() .fg(th.crust) .bg(bg) .add_modifier(Modifier::BOLD) }, ); spans.push(Span::styled(path.to_string(), path_style)); Line::from(spans) } /// What: Render file list with summary and scrolling. /// /// Inputs: /// - `app`: Application state for i18n. /// - `ctx`: File list context containing related parameters. /// - `file_selected`: Currently selected file index (mutable). /// - `content_rect`: Content area rectangle. /// /// Output: /// - Returns a vector of lines to render. fn render_file_list( app: &AppState, ctx: &FileListContext, file_selected: &mut usize, content_rect: Rect, ) -> Vec<Line<'static>> { let th = theme(); let mut lines = Vec::new(); // Option 1: Single-pass aggregation let totals = calculate_file_totals(ctx.file_info); // Option 6: Simplify incomplete data check let has_incomplete_data = ctx.file_info.len() < ctx.items.len(); // Option 2: Extract summary building let summary_parts = build_summary_parts(app, &totals, ctx.items.len(), has_incomplete_data); lines.push(Line::from(Span::styled( i18n::t_fmt1( app, "app.modals.preflight.files.files_label", summary_parts.join(", "), ), Style::default() .fg(th.overlay1) .add_modifier(Modifier::BOLD), ))); lines.push(Line::from("")); let (sync_line, sync_timestamp_lines) = render_sync_timestamp(app, ctx.sync_info.as_ref()); if let Some(line) = sync_line { lines.push(line); lines.push(Line::from("")); } let header_lines = 4 + sync_timestamp_lines; let available_height = (content_rect.height.saturating_sub(1) as usize) .saturating_sub(header_lines) .max(1); let total_items = ctx.display_items.len(); // Option 3: Extract viewport calculation let (start_idx, end_idx) = calculate_viewport(total_items, available_height, file_selected); // Option 4: Extract rendering loop let mut item_lines = render_display_items( app, ctx.display_items, ctx.file_info, ctx.file_tree_expanded, *file_selected, start_idx, end_idx, ); lines.append(&mut item_lines); if total_items > available_height { lines.push(Line::from("")); lines.push(Line::from(Span::styled( i18n::t_fmt( app, "app.modals.preflight.files.showing_range_items", &[ &(start_idx + 1).to_string(), &end_idx.to_string(), &total_items.to_string(), ], ), Style::default().fg(th.subtext1), ))); } lines } /// What: Render the Files tab content for the preflight modal. /// /// Inputs: /// - `app`: Application state for i18n and data access. /// - `items`: Packages under review. /// - `file_info`: File information. /// - `file_selected`: Currently selected file index (mutable). /// - `file_tree_expanded`: Set of expanded package names. /// - `files_error`: Optional error message. /// - `content_rect`: Content area rectangle. /// /// Output: /// - Returns a vector of lines to render. /// /// Details: /// - Shows file changes grouped by package with expand/collapse. /// - Supports viewport-based rendering for large file lists. #[allow(clippy::too_many_arguments)] pub fn render_files_tab( app: &AppState, items: &[PackageItem], file_info: &[PackageFileInfo], file_selected: &mut usize, file_tree_expanded: &std::collections::HashSet<String>, files_error: Option<&String>, content_rect: Rect, ) -> Vec<Line<'static>> { const STALE_THRESHOLD_DAYS: u64 = 7; let is_resolving = app.preflight_files_resolving || app.files_resolving; let package_summaries = file_info .iter() .map(|pkg| FilePackageSummary { name: pkg.name.clone(), total: pkg.total_count, new_count: pkg.new_count, changed_count: pkg.changed_count, removed_count: pkg.removed_count, config_count: pkg.config_count, file_entries: pkg.files.len(), }) .collect(); log_files_state(&FilesLogState { items_len: items.len(), file_info_len: file_info.len(), file_selected: *file_selected, expanded_len: file_tree_expanded.len(), preflight_resolving: app.preflight_files_resolving, global_resolving: app.files_resolving, has_error: files_error.is_some(), package_summaries, }); if is_resolving { let th = theme(); return render_loading_state(app, items, "app.modals.preflight.files.updating", th.yellow); } if let Some(err_msg) = files_error { return render_error_state(app, err_msg); } if file_info.is_empty() { let th = theme(); return render_loading_state( app, items, "app.modals.preflight.files.resolving", th.subtext1, ); } let display_items = build_display_items(items, file_info, file_tree_expanded); let sync_info = crate::logic::files::get_file_db_sync_info(); let is_stale = crate::logic::files::is_file_db_stale(STALE_THRESHOLD_DAYS); if display_items.is_empty() { render_empty_state(app, items, file_info, is_stale.as_ref(), sync_info.as_ref()) } else { let ctx = FileListContext { file_info, items, display_items: &display_items, file_tree_expanded, sync_info: &sync_info, }; render_file_list(app, &ctx, file_selected, content_rect) } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/helpers/tests.rs
src/ui/helpers/tests.rs
//! Test module for UI helpers. use super::*; /// What: Initialize details field translations for tests. /// /// Inputs: /// - `translations`: Mutable reference to translations map. /// /// Output: /// - Adds details field translations to the map. fn init_details_translations(translations: &mut std::collections::HashMap<String, String>) { translations.insert( "app.details.fields.repository".to_string(), "Repository".to_string(), ); translations.insert( "app.details.fields.package_name".to_string(), "Package Name".to_string(), ); translations.insert( "app.details.fields.version".to_string(), "Version".to_string(), ); translations.insert( "app.details.fields.description".to_string(), "Description".to_string(), ); translations.insert( "app.details.fields.architecture".to_string(), "Architecture".to_string(), ); translations.insert("app.details.fields.url".to_string(), "URL".to_string()); translations.insert( "app.details.fields.licences".to_string(), "Licences".to_string(), ); translations.insert( "app.details.fields.provides".to_string(), "Provides".to_string(), ); translations.insert( "app.details.fields.depends_on".to_string(), "Depends on".to_string(), ); translations.insert( "app.details.fields.optional_dependencies".to_string(), "Optional dependencies".to_string(), ); translations.insert( "app.details.fields.required_by".to_string(), "Required by".to_string(), ); translations.insert( "app.details.fields.optional_for".to_string(), "Optional for".to_string(), ); translations.insert( "app.details.fields.conflicts_with".to_string(), "Conflicts with".to_string(), ); translations.insert( "app.details.fields.replaces".to_string(), "Replaces".to_string(), ); translations.insert( "app.details.fields.download_size".to_string(), "Download size".to_string(), ); translations.insert( "app.details.fields.install_size".to_string(), "Install size".to_string(), ); translations.insert( "app.details.fields.package_owner".to_string(), "Package Owner".to_string(), ); translations.insert( "app.details.fields.build_date".to_string(), "Build date".to_string(), ); translations.insert( "app.details.fields.not_available".to_string(), "N/A".to_string(), ); translations.insert( "app.details.show_pkgbuild".to_string(), "Show PKGBUILD".to_string(), ); translations.insert( "app.details.hide_pkgbuild".to_string(), "Hide PKGBUILD".to_string(), ); translations.insert("app.details.url_label".to_string(), "URL:".to_string()); } /// What: Initialize results translations for tests. /// /// Inputs: /// - `translations`: Mutable reference to translations map. /// /// Output: /// - Adds results translations to the map. fn init_results_translations(translations: &mut std::collections::HashMap<String, String>) { translations.insert("app.results.title".to_string(), "Results".to_string()); translations.insert("app.results.buttons.sort".to_string(), "Sort".to_string()); translations.insert( "app.results.buttons.options".to_string(), "Options".to_string(), ); translations.insert( "app.results.buttons.panels".to_string(), "Panels".to_string(), ); translations.insert( "app.results.buttons.config_lists".to_string(), "Config/Lists".to_string(), ); translations.insert("app.results.buttons.menu".to_string(), "Menu".to_string()); translations.insert("app.results.filters.aur".to_string(), "AUR".to_string()); translations.insert("app.results.filters.core".to_string(), "core".to_string()); translations.insert("app.results.filters.extra".to_string(), "extra".to_string()); translations.insert( "app.results.filters.multilib".to_string(), "multilib".to_string(), ); translations.insert("app.results.filters.eos".to_string(), "EOS".to_string()); translations.insert( "app.results.filters.cachyos".to_string(), "CachyOS".to_string(), ); translations.insert("app.results.filters.artix".to_string(), "Artix".to_string()); translations.insert( "app.results.filters.artix_omniverse".to_string(), "OMNI".to_string(), ); translations.insert( "app.results.filters.artix_universe".to_string(), "UNI".to_string(), ); translations.insert( "app.results.filters.artix_lib32".to_string(), "LIB32".to_string(), ); translations.insert( "app.results.filters.artix_galaxy".to_string(), "GALAXY".to_string(), ); translations.insert( "app.results.filters.artix_world".to_string(), "WORLD".to_string(), ); translations.insert( "app.results.filters.artix_system".to_string(), "SYSTEM".to_string(), ); translations.insert( "app.results.filters.manjaro".to_string(), "Manjaro".to_string(), ); } /// What: Initialize minimal English translations for tests. /// /// Inputs: /// - `app`: `AppState` to populate with translations /// /// Output: /// - Populates `app.translations` and `app.translations_fallback` with minimal English translations /// /// Details: /// - Sets up only the translations needed for tests to pass fn init_test_translations(app: &mut crate::state::AppState) { use std::collections::HashMap; let mut translations = HashMap::new(); init_details_translations(&mut translations); init_results_translations(&mut translations); app.translations = translations.clone(); app.translations_fallback = translations; } /// What: Create a test `PackageItem` for an official repository package. /// /// Inputs: /// - `name`: Package name /// - `repo`: Repository name (e.g., "extra", "core") /// /// Output: /// - Returns a `PackageItem` with default test values for an official package. /// /// Details: /// - Sets version to "1.0", creates a default description, and sets architecture to `x86_64`. /// - Used in tests to create mock official packages. fn item_official(name: &str, repo: &str) -> crate::state::PackageItem { crate::state::PackageItem { name: name.to_string(), version: "1.0".to_string(), description: format!("{name} desc"), source: crate::state::Source::Official { repo: repo.to_string(), arch: "x86_64".to_string(), }, popularity: None, out_of_date: None, orphaned: false, } } #[test] /// What: Validate helper functions that filter recent/install indices and toggle details labels. /// /// Inputs: /// - Recent list with pane find queries, install list search term, and details populated with metadata. /// /// Output: /// - Filtered indices match expectations and the details footer alternates between `Show`/`Hide PKGBUILD` labels. /// /// Details: /// - Covers the case-insensitive dedupe path plus button label toggling when PKGBUILD visibility flips. fn filtered_indices_and_details_lines() { let mut app = crate::state::AppState::default(); init_test_translations(&mut app); app.load_recent_items(&[ "alpha".to_string(), "bravo".to_string(), "charlie".to_string(), ]); assert_eq!(filtered_recent_indices(&app), vec![0, 1, 2]); app.focus = crate::state::Focus::Recent; app.pane_find = Some("a".into()); let inds = filtered_recent_indices(&app); assert_eq!(inds, vec![0, 1, 2]); app.install_list = vec![ item_official("ripgrep", "extra"), crate::state::PackageItem { name: "fd".into(), version: "1".into(), description: String::new(), source: crate::state::Source::Aur, popularity: None, out_of_date: None, orphaned: false, }, ]; app.focus = crate::state::Focus::Install; app.pane_find = Some("rip".into()); let inds2 = filtered_install_indices(&app); assert_eq!(inds2, vec![0]); app.details = crate::state::PackageDetails { repository: "extra".into(), name: "ripgrep".into(), version: "14".into(), description: "desc".into(), architecture: "x86_64".into(), url: "https://example.com".into(), licenses: vec!["MIT".into()], groups: vec![], provides: vec![], depends: vec![], opt_depends: vec![], required_by: vec![], optional_for: vec![], conflicts: vec![], replaces: vec![], download_size: None, install_size: None, owner: "owner".into(), build_date: "date".into(), popularity: None, out_of_date: None, orphaned: false, }; let th = crate::theme::theme(); let lines = format_details_lines(&app, 80, &th); assert!( lines .last() .expect("lines should not be empty in test") .spans[0] .content .contains("Show PKGBUILD") ); let mut app2 = crate::state::AppState::default(); init_test_translations(&mut app2); app2.details = app.details.clone(); app2.pkgb_visible = true; let lines2 = format_details_lines(&app2, 80, &th); assert!( lines2 .last() .expect("lines2 should not be empty in test") .spans[0] .content .contains("Hide PKGBUILD") ); } #[test] /// What: Ensure filtered recent indices use news history when in news mode. /// /// Inputs: /// - App mode set to News with dedicated news recent entries and pane find. /// /// Output: /// - Indices reflect the news history and respect pane find filtering. fn filtered_recent_indices_use_news_history() { let mut app = crate::state::AppState::default(); init_test_translations(&mut app); app.app_mode = crate::state::types::AppMode::News; app.load_news_recent_items(&["alpha".to_string(), "beta".to_string(), "gamma".to_string()]); assert_eq!(filtered_recent_indices(&app), vec![0, 1, 2]); app.focus = crate::state::Focus::Recent; app.pane_find = Some("be".into()); let inds = filtered_recent_indices(&app); assert_eq!(inds, vec![1]); } #[test] /// What: Ensure details rendering formats lists and byte sizes into human-friendly strings. /// /// Inputs: /// - `PackageDetails` with empty license list, multiple provides, and a non-zero install size. /// /// Output: /// - Renders `N/A` for missing values, formats bytes into `1.5 KiB`, and joins lists with commas. /// /// Details: /// - Confirms string composition matches UI expectations for optional fields. fn details_lines_sizes_and_lists() { let mut app = crate::state::AppState::default(); init_test_translations(&mut app); app.details = crate::state::PackageDetails { repository: "extra".into(), name: "ripgrep".into(), version: "14".into(), description: "desc".into(), architecture: "x86_64".into(), url: String::new(), licenses: vec![], groups: vec![], provides: vec!["prov1".into(), "prov2".into()], depends: vec![], opt_depends: vec![], required_by: vec![], optional_for: vec![], conflicts: vec![], replaces: vec![], download_size: None, install_size: Some(1536), owner: String::new(), build_date: String::new(), popularity: None, out_of_date: None, orphaned: false, }; let th = crate::theme::theme(); let lines = format_details_lines(&app, 80, &th); assert!( lines .iter() .any(|l| l.spans.iter().any(|s| s.content.contains("N/A"))) ); assert!( lines .iter() .any(|l| l.spans.iter().any(|s| s.content.contains("1.5 KiB"))) ); assert!(lines.iter().any(|l| { l.spans .iter() .any(|s| s.content.contains("Licences") || s.content.contains('-')) })); assert!( lines .iter() .any(|l| l.spans.iter().any(|s| s.content.contains("prov1, prov2"))) ); } #[tokio::test] /// What: Ensure the recent preview trigger becomes a no-op when focus or selection is invalid. /// /// Inputs: /// - `app`: Focus initially outside Recent, then Recent with no selection, then Recent with a filtered-out entry. /// - `tx`: Preview channel observed for emitted messages across each scenario. /// /// Output: /// - Each invocation leaves the channel empty, showing no preview requests were issued. /// /// Details: /// - Applies a short timeout for each check to guard against unexpected asynchronous sends. async fn trigger_recent_preview_noop_when_not_recent_or_invalid() { let mut app = crate::state::AppState::default(); let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel(); app.focus = crate::state::Focus::Search; trigger_recent_preview(&app, &tx); let none1 = tokio::time::timeout(std::time::Duration::from_millis(30), rx.recv()) .await .ok() .flatten(); assert!(none1.is_none()); app.focus = crate::state::Focus::Recent; app.load_recent_items(&["abc".to_string()]); app.history_state.select(None); trigger_recent_preview(&app, &tx); let none2 = tokio::time::timeout(std::time::Duration::from_millis(30), rx.recv()) .await .ok() .flatten(); assert!(none2.is_none()); app.history_state.select(Some(0)); app.pane_find = Some("zzz".into()); trigger_recent_preview(&app, &tx); let none3 = tokio::time::timeout(std::time::Duration::from_millis(30), rx.recv()) .await .ok() .flatten(); assert!(none3.is_none()); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/helpers/filter.rs
src/ui/helpers/filter.rs
//! Filtering utilities for pane-specific index calculations. //! //! This module provides functions for filtering indices in the Recent and Install panes //! based on pane-find queries. use crate::state::types::AppMode; use crate::state::{AppState, Focus}; /// What: Produce visible indices into `app.recent` considering pane-find when applicable. /// /// Inputs: /// - `app`: Application state (focus, `pane_find`, recent list) /// /// Output: /// - Vector of indices in ascending order without modifying application state. /// /// # Panics /// - Panics if `pane_find` is `Some` but becomes `None` between the check and the `expect` call (should not happen in single-threaded usage) /// /// Details: /// - Applies pane find filtering only when the Recent pane is focused and the finder string is /// non-empty; otherwise returns the full range. #[must_use] pub fn filtered_recent_indices(app: &AppState) -> Vec<usize> { let apply = matches!(app.focus, Focus::Recent) && app.pane_find.as_ref().is_some_and(|s| !s.is_empty()); let recents = if matches!(app.app_mode, AppMode::News) { app.news_recent_values() } else { app.recent_values() }; if !apply { return (0..recents.len()).collect(); } let pat = app .pane_find .as_ref() .expect("pane_find should be Some when apply is true") .to_lowercase(); recents .iter() .enumerate() .filter_map(|(i, s)| { if s.to_lowercase().contains(&pat) { Some(i) } else { None } }) .collect() } /// What: Produce visible indices into `app.install_list` with optional pane-find filtering. /// /// Inputs: /// - `app`: Application state (focus, `pane_find`, install list) /// /// Output: /// - Vector of indices in ascending order without modifying application state. /// /// # Panics /// - Panics if `pane_find` is `Some` but becomes `None` between the check and the `expect` call (should not happen in single-threaded usage) /// /// Details: /// - Restricts matches to name or description substrings when the Install pane is focused and a /// pane-find expression is active; otherwise surfaces all indices. #[must_use] pub fn filtered_install_indices(app: &AppState) -> Vec<usize> { let apply = matches!(app.focus, Focus::Install) && app.pane_find.as_ref().is_some_and(|s| !s.is_empty()); if !apply { return (0..app.install_list.len()).collect(); } let pat = app .pane_find .as_ref() .expect("pane_find should be Some when apply is true") .to_lowercase(); app.install_list .iter() .enumerate() .filter_map(|(i, p)| { let name = p.name.to_lowercase(); let desc = p.description.to_lowercase(); if name.contains(&pat) || desc.contains(&pat) { Some(i) } else { None } }) .collect() }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/helpers/preflight.rs
src/ui/helpers/preflight.rs
//! Preflight resolution status utilities. //! //! This module provides functions for checking preflight resolution status of packages. use crate::state::AppState; /// What: Check if a package is currently being processed by any preflight resolver. /// /// Inputs: /// - `app`: Application state containing preflight resolution queues and flags. /// - `package_name`: Name of the package to check. /// /// Output: /// - `true` if the package is in any preflight resolution queue and the corresponding resolver is active. /// /// Details: /// - Checks if the package name appears in any of the preflight queues (summary, deps, files, services, sandbox) /// and if the corresponding resolving flag is set to true. /// - Also checks install list resolution (when preflight modal is not open) by checking if the package /// is in `app.install_list` and any resolver is active. #[must_use] pub fn is_package_loading_preflight(app: &AppState, package_name: &str) -> bool { // Check summary resolution (preflight-specific) if app.preflight_summary_resolving && let Some((ref items, _)) = app.preflight_summary_items && items.iter().any(|p| p.name == package_name) { return true; } // Check dependency resolution // First check preflight-specific queue (when modal is open) if app.preflight_deps_resolving && let Some((ref items, _action)) = app.preflight_deps_items && items.iter().any(|p| p.name == package_name) { return true; } // Then check install list resolution (when modal is not open) // Only show indicator if deps are actually resolving AND package is in install list if app.deps_resolving && !app.preflight_deps_resolving && app.install_list.iter().any(|p| p.name == package_name) { return true; } // Check file resolution // First check preflight-specific queue (when modal is open) if app.preflight_files_resolving && let Some(ref items) = app.preflight_files_items && items.iter().any(|p| p.name == package_name) { return true; } // Then check install list resolution (when modal is not open) // Only show indicator if files are actually resolving AND preflight is not resolving if app.files_resolving && !app.preflight_files_resolving && app.install_list.iter().any(|p| p.name == package_name) { return true; } // Check service resolution // First check preflight-specific queue (when modal is open) if app.preflight_services_resolving && let Some(ref items) = app.preflight_services_items && items.iter().any(|p| p.name == package_name) { return true; } // Then check install list resolution (when modal is not open) // Only show indicator if services are actually resolving AND preflight is not resolving if app.services_resolving && !app.preflight_services_resolving && app.install_list.iter().any(|p| p.name == package_name) { return true; } // Check sandbox resolution // First check preflight-specific queue (when modal is open) if app.preflight_sandbox_resolving && let Some(ref items) = app.preflight_sandbox_items && items.iter().any(|p| p.name == package_name) { return true; } // Then check install list resolution (when modal is not open) // Note: sandbox only applies to AUR packages // Only show indicator if sandbox is actually resolving AND preflight is not resolving if app.sandbox_resolving && !app.preflight_sandbox_resolving && app .install_list .iter() .any(|p| p.name == package_name && matches!(p.source, crate::state::Source::Aur)) { return true; } false }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/helpers/mod.rs
src/ui/helpers/mod.rs
//! UI helper utilities for formatting and pane-specific behaviors. //! //! This module contains small, focused helpers used by the TUI layer: //! //! - Formatting package details into rich `ratatui` lines //! - Human-readable byte formatting //! - In-pane filtering for Recent and Install panes //! - Triggering background preview fetches for Recent selections //! - Resolving a query string to a best-effort first matching package pub mod filter; pub mod format; /// Logging utilities for change tracking and debugging. pub mod logging; pub mod preflight; pub mod query; pub use filter::{filtered_install_indices, filtered_recent_indices}; pub use format::{format_bytes, format_details_lines, format_signed_bytes, human_bytes}; pub use logging::ChangeLogger; pub use preflight::is_package_loading_preflight; pub use query::{fetch_first_match_for_query, trigger_recent_preview}; #[cfg(test)] mod tests;
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/helpers/format.rs
src/ui/helpers/format.rs
//! Formatting utilities for UI display. //! //! This module provides functions for formatting package details, byte sizes, and other //! UI elements into human-readable strings and ratatui lines. use ratatui::{ style::{Modifier, Style}, text::{Line, Span}, }; use crate::{i18n, state::AppState, theme::Theme}; /// What: Format the current [`AppState::details`] into themed `ratatui` lines. /// /// Inputs: /// - `app`: Read-only application state; uses `app.details` to render fields /// - `_area_width`: Reserved for future wrapping/layout needs (currently unused) /// - `th`: Active theme for colors/styles /// /// Output: /// - Vector of formatted lines for the Details pane, ending with a Show/Hide PKGBUILD action line. /// /// Details: /// - Applies repo-specific heuristics, formats numeric sizes via `human_bytes`, and appends a /// clickable PKGBUILD toggle line using accent styling. pub fn format_details_lines(app: &AppState, _area_width: u16, th: &Theme) -> Vec<Line<'static>> { /// What: Build a themed key-value line for the details pane. /// /// Inputs: /// - `key`: Label to display (styled in accent color) /// - `val`: Value text rendered in primary color /// - `th`: Active theme for colors/modifiers /// /// Output: /// - `Line` combining the key/value segments with appropriate styling. /// /// Details: /// - Renders the key in bold accent with a trailing colon and the value in standard text color. fn kv(key: &str, val: String, th: &Theme) -> Line<'static> { Line::from(vec![ Span::styled( format!("{key}: "), Style::default() .fg(th.sapphire) .add_modifier(Modifier::BOLD), ), Span::styled(val, Style::default().fg(th.text)), ]) } let d = &app.details; // Compute display repository using unified Manjaro detection (name prefix or owner). let repo_display = if crate::index::is_manjaro_name_or_owner(&d.name, &d.owner) { "manjaro".to_string() } else { d.repository.clone() }; // Each line is a label/value pair derived from the current details view. let mut lines = vec![ kv( &i18n::t(app, "app.details.fields.repository"), repo_display, th, ), kv( &i18n::t(app, "app.details.fields.package_name"), d.name.clone(), th, ), kv( &i18n::t(app, "app.details.fields.version"), d.version.clone(), th, ), kv( &i18n::t(app, "app.details.fields.description"), d.description.clone(), th, ), kv( &i18n::t(app, "app.details.fields.architecture"), d.architecture.clone(), th, ), kv(&i18n::t(app, "app.details.fields.url"), d.url.clone(), th), kv( &i18n::t(app, "app.details.fields.licences"), join(&d.licenses), th, ), kv( &i18n::t(app, "app.details.fields.provides"), join(&d.provides), th, ), kv( &i18n::t(app, "app.details.fields.depends_on"), join(&d.depends), th, ), kv( &i18n::t(app, "app.details.fields.optional_dependencies"), join(&d.opt_depends), th, ), kv( &i18n::t(app, "app.details.fields.required_by"), join(&d.required_by), th, ), kv( &i18n::t(app, "app.details.fields.optional_for"), join(&d.optional_for), th, ), kv( &i18n::t(app, "app.details.fields.conflicts_with"), join(&d.conflicts), th, ), kv( &i18n::t(app, "app.details.fields.replaces"), join(&d.replaces), th, ), kv( &i18n::t(app, "app.details.fields.download_size"), d.download_size.map_or_else( || i18n::t(app, "app.details.fields.not_available"), human_bytes, ), th, ), kv( &i18n::t(app, "app.details.fields.install_size"), d.install_size.map_or_else( || i18n::t(app, "app.details.fields.not_available"), human_bytes, ), th, ), kv( &i18n::t(app, "app.details.fields.package_owner"), d.owner.clone(), th, ), kv( &i18n::t(app, "app.details.fields.build_date"), d.build_date.clone(), th, ), ]; // Add a clickable helper line to Show/Hide PKGBUILD below Build date let pkgb_label = if app.pkgb_visible { i18n::t(app, "app.details.hide_pkgbuild") } else { i18n::t(app, "app.details.show_pkgbuild") }; lines.push(Line::from(vec![Span::styled( pkgb_label, Style::default() .fg(th.mauve) .add_modifier(Modifier::UNDERLINED | Modifier::BOLD), )])); // Add a clickable helper line to Show/Hide Comments below PKGBUILD button (AUR packages only) let is_aur = app .results .get(app.selected) .is_some_and(|item| matches!(item.source, crate::state::Source::Aur)); if is_aur { let comments_label = if app.comments_visible { i18n::t(app, "app.details.hide_comments") } else { i18n::t(app, "app.details.show_comments") }; lines.push(Line::from(vec![Span::styled( comments_label, Style::default() .fg(th.mauve) .add_modifier(Modifier::UNDERLINED | Modifier::BOLD), )])); } lines } /// What: Join a slice of strings with `", "`, falling back to "-" when empty. /// /// Inputs: /// - `list`: Slice of strings to format /// /// Output: /// - Joined string or "-" when no entries are present. /// /// Details: /// - Keeps the details pane compact by representing empty lists with a single dash. pub(crate) fn join(list: &[String]) -> String { if list.is_empty() { "-".into() } else { list.join(", ") } } /// What: Format bytes into human-readable string with appropriate unit. /// /// Inputs: /// - `value`: Number of bytes to format. /// /// Output: /// - Returns a formatted string like "1.5 MiB" or "1024 B". /// /// Details: /// - Uses binary units (KiB, MiB, GiB, etc.) and shows integer for bytes < 1024, otherwise 1 decimal place. #[must_use] pub fn format_bytes(value: u64) -> String { const UNITS: [&str; 6] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]; #[allow(clippy::cast_precision_loss)] let mut size = value as f64; let mut unit_index = 0usize; while size >= 1024.0 && unit_index < UNITS.len() - 1 { size /= 1024.0; unit_index += 1; } if unit_index == 0 { format!("{value} {}", UNITS[unit_index]) } else { format!("{size:.1} {}", UNITS[unit_index]) } } /// What: Format signed bytes into human-readable string with +/- prefix. /// /// Inputs: /// - `value`: Signed number of bytes to format. /// /// Output: /// - Returns a formatted string like "+1.5 MiB" or "-512 KiB" or "0 B". /// /// Details: /// - Uses `format_bytes` for magnitude and adds +/- prefix based on sign. #[must_use] pub fn format_signed_bytes(value: i64) -> String { if value == 0 { return "0 B".to_string(); } let magnitude = value.unsigned_abs(); if value > 0 { format!("+{}", format_bytes(magnitude)) } else { format!("-{}", format_bytes(magnitude)) } } /// What: Format a byte count using binary units with one decimal place. /// /// Inputs: /// - `n`: Raw byte count to format /// /// Output: /// - Size string such as "1.5 KiB" using 1024-based units. /// /// Details: /// - Iteratively divides by 1024 up to PiB, retaining one decimal place for readability. /// - Always shows decimal place (unlike `format_bytes` which shows integer for bytes < 1024). #[must_use] pub fn human_bytes(n: u64) -> String { const UNITS: [&str; 6] = ["B", "KiB", "MiB", "GiB", "TiB", "PiB"]; #[allow(clippy::cast_precision_loss)] let mut v = n as f64; let mut i = 0; while v >= 1024.0 && i < UNITS.len() - 1 { v /= 1024.0; i += 1; } format!("{v:.1} {}", UNITS[i]) }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/helpers/query.rs
src/ui/helpers/query.rs
//! Query resolution and preview utilities. //! //! This module provides functions for resolving query strings to packages and triggering //! asynchronous preview fetches. use super::filter::filtered_recent_indices; use crate::state::AppState; /// What: Resolve a free-form query string to a best-effort matching package. /// /// Inputs: /// - `q`: Query string to resolve /// /// Output: /// - `Some(PackageItem)` per the priority rules below; `None` if nothing usable is found. /// /// Details (selection priority): /// 1) Exact-name match from the official index; /// 2) Exact-name match from AUR; /// 3) First official result; /// 4) Otherwise, first AUR result. /// /// Performs network I/O for AUR; tolerates errors. pub async fn fetch_first_match_for_query(q: String) -> Option<crate::state::PackageItem> { // Prefer exact match from official index, then from AUR, else first official, then first AUR // Use normal substring search for this helper (not fuzzy) let official_results = crate::index::search_official(&q, false); let official: Vec<crate::state::PackageItem> = official_results.into_iter().map(|(item, _)| item).collect(); if let Some(off) = official .iter() .find(|it| it.name.eq_ignore_ascii_case(&q)) .cloned() { return Some(off); } let (aur, _errors) = crate::sources::fetch_all_with_errors(q.clone()).await; if let Some(a) = aur .iter() .find(|it| it.name.eq_ignore_ascii_case(&q)) .cloned() { return Some(a); } if let Some(off) = official.first().cloned() { return Some(off); } aur.into_iter().next() } /// What: Trigger an asynchronous preview fetch for the selected Recent query when applicable. /// /// Inputs: /// - `app`: Application state (focus, selection, recent list) /// - `preview_tx`: Channel to send the preview `PackageItem` /// /// Output: /// - Spawns a task to resolve and send a preview item; no return payload; exits early when inapplicable. /// /// Details: /// - Requires: focus on Recent, a valid selection within the filtered view, and a query string present. /// - Resolves via [`fetch_first_match_for_query`] and sends over `preview_tx`; ignores send errors. pub fn trigger_recent_preview( app: &AppState, preview_tx: &tokio::sync::mpsc::UnboundedSender<crate::state::PackageItem>, ) { if !matches!(app.focus, crate::state::Focus::Recent) || matches!(app.app_mode, crate::state::types::AppMode::News) { return; } let Some(idx) = app.history_state.selected() else { return; }; let inds = filtered_recent_indices(app); if idx >= inds.len() { return; } let Some(q) = app.recent_value_at(inds[idx]) else { return; }; let tx = preview_tx.clone(); tokio::spawn(async move { if let Some(item) = fetch_first_match_for_query(q).await { let _ = tx.send(item); } }); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/helpers/logging.rs
src/ui/helpers/logging.rs
/// What: Track the last logged state to avoid repeating identical debug lines. /// /// Inputs: /// - `T`: A clonable, comparable state type to track between log attempts. /// /// Output: /// - `ChangeLogger`: Helper that indicates whether a new log should be emitted. /// /// Details: /// - Calling `should_log` updates the cached state and returns `true` only when /// the provided state differs from the previous one. /// - `clear` resets the cached state, forcing the next call to log. pub struct ChangeLogger<T> { /// Last logged state value. last: Option<T>, } impl<T: PartialEq + Clone> Default for ChangeLogger<T> { fn default() -> Self { Self::new() } } impl<T: PartialEq + Clone> ChangeLogger<T> { /// What: Create a new `ChangeLogger` with no cached state. /// /// Inputs: /// - None /// /// Output: /// - A `ChangeLogger` ready to track state changes. /// /// Details: /// - The first call to `should_log` after construction will return `true`. #[must_use] pub const fn new() -> Self { Self { last: None } } /// What: Decide whether a log should be emitted for the provided state. /// /// Inputs: /// - `next`: The next state to compare against the cached state. /// /// Output: /// - `true` when the state differs from the cached value; otherwise `false`. /// /// Details: /// - Updates the cached state when it changes. #[must_use] pub fn should_log(&mut self, next: &T) -> bool { if self.last.as_ref() == Some(next) { return false; } self.last = Some(next.clone()); true } /// What: Reset the cached state so the next call logs. /// /// Inputs: /// - None /// /// Output: /// - None /// /// Details: /// - Useful for tests or after major UI transitions. pub fn clear(&mut self) { self.last = None; } } #[cfg(test)] mod tests { use super::ChangeLogger; #[test] /// What: Ensure `ChangeLogger` only triggers when state changes. /// /// Inputs: /// - Sequence of repeated and differing states. /// /// Output: /// - Boolean results from `should_log` reflecting change detection. /// /// Details: /// - First call logs, repeat skips, new value logs, clear resets behavior. fn change_logger_emits_only_on_change() { let mut logger = ChangeLogger::new(); assert!(logger.should_log(&"a")); assert!(!logger.should_log(&"a")); assert!(logger.should_log(&"b")); assert!(!logger.should_log(&"b")); logger.clear(); assert!(logger.should_log(&"b")); } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/results/dropdowns.rs
src/ui/results/dropdowns.rs
use ratatui::{ Frame, prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap}, }; use unicode_width::{UnicodeWidthChar, UnicodeWidthStr}; use crate::i18n; use crate::state::AppState; use crate::theme::theme; /// What: Calculate menu dimensions based on options and available space. /// /// Inputs: /// - `opts`: Menu option strings /// - `results_area`: Available area for positioning /// - `extra_width`: Additional width needed (e.g., for checkboxes) /// /// Output: /// - Tuple of (`width`, `height`, `max_number_width`) /// /// Details: /// - Uses Unicode display width for accurate sizing with wide characters. fn calculate_menu_dimensions( opts: &[String], results_area: Rect, extra_width: u16, ) -> (u16, u16, u16) { let widest = opts .iter() .map(|s| u16::try_from(s.width()).map_or(u16::MAX, |x| x)) .max() .unwrap_or(0); let max_num_width = u16::try_from(format!("{}", opts.len()).len()).unwrap_or(u16::MAX); let w = widest .saturating_add(max_num_width) .saturating_add(2) // spacing between text and number .saturating_add(extra_width) .min(results_area.width.saturating_sub(2)); let h = u16::try_from(opts.len()) .unwrap_or(u16::MAX) .saturating_add(2); // borders (w, h, max_num_width) } /// What: Calculate menu rectangle position aligned to a button. /// /// Inputs: /// - `button_rect`: Optional button rectangle (x, y, width, height) /// - `menu_width`: Calculated menu width /// - `menu_height`: Calculated menu height /// - `results_area`: Available area for positioning /// /// Output: /// - Menu rectangle and inner hit-test rectangle /// /// Details: /// - Aligns menu below button, clamps to viewport boundaries. fn calculate_menu_rect( button_rect: Option<(u16, u16, u16, u16)>, menu_width: u16, menu_height: u16, results_area: Rect, ) -> (Rect, (u16, u16, u16, u16)) { let rect_w = menu_width.saturating_add(2); let max_x = results_area.x + results_area.width.saturating_sub(rect_w); let button_x = button_rect.map_or(max_x, |(x, _, _, _)| x); let menu_x = button_x.min(max_x); let menu_y = results_area.y.saturating_add(1); let rect = Rect { x: menu_x, y: menu_y, width: rect_w, height: menu_height, }; let inner_rect = ( rect.x + 1, rect.y + 1, menu_width, menu_height.saturating_sub(2), ); (rect, inner_rect) } /// What: Build menu lines with right-aligned row numbers. /// /// Inputs: /// - `opts`: Menu option strings /// - `widest`: Width of widest option /// - `max_num_width`: Maximum width needed for numbers /// - `total_line_width`: Target display width for each line /// - `spacing`: Spacing between text and numbers /// - `th`: Theme colors /// /// Output: /// - Vector of styled lines ready for rendering /// /// Details: /// - Handles Unicode display width for accurate alignment with wide characters. fn build_numbered_menu_lines( opts: &[String], widest: u16, max_num_width: u16, total_line_width: u16, spacing: u16, th: crate::theme::Theme, ) -> Vec<Line<'static>> { let num_start_col = widest + spacing; let mut lines: Vec<Line> = Vec::new(); for (i, text) in opts.iter().enumerate() { let num_str = format!("{}", i + 1); let num_width = u16::try_from(num_str.len()).unwrap_or(u16::MAX); let num_padding = max_num_width.saturating_sub(num_width); let padded_num = format!("{}{}", " ".repeat(num_padding as usize), num_str); let text_display_width = u16::try_from(text.width()).unwrap_or(u16::MAX); let text_padding = widest.saturating_sub(text_display_width); let mut complete_line = format!( "{}{}{}{}", text, " ".repeat(text_padding as usize), " ".repeat(spacing as usize), padded_num ); let current_width = u16::try_from(complete_line.width()).unwrap_or(u16::MAX); if current_width < total_line_width { complete_line.push_str(&" ".repeat((total_line_width - current_width) as usize)); } else if current_width > total_line_width { let mut truncated = String::new(); let mut width_so_far = 0u16; for ch in complete_line.chars() { let ch_width = u16::try_from(ch.width().unwrap_or(0)).unwrap_or(u16::MAX); if width_so_far + ch_width > total_line_width { break; } truncated.push(ch); width_so_far += ch_width; } complete_line = truncated; } let mut text_part = String::new(); let mut width_so_far = 0u16; for ch in complete_line.chars() { let ch_width = u16::try_from(ch.width().unwrap_or(0)).unwrap_or(u16::MAX); if width_so_far + ch_width > num_start_col { break; } text_part.push(ch); width_so_far += ch_width; } let num_part = complete_line .chars() .skip(text_part.chars().count()) .collect::<String>(); lines.push(Line::from(vec![ Span::styled(text_part, Style::default().fg(th.text)), Span::styled(num_part, Style::default().fg(th.overlay1)), ])); } lines } /// What: Build menu lines with checkbox indicators. /// /// Inputs: /// - `opts`: Menu options with enabled state /// - `menu_width`: Target width for each line /// - `th`: Theme colors /// /// Output: /// - Vector of styled lines ready for rendering fn build_checkbox_menu_lines( opts: &[(String, bool)], menu_width: u16, th: crate::theme::Theme, ) -> Vec<Line<'static>> { let mut lines: Vec<Line> = Vec::new(); for (text, enabled) in opts { let indicator = if *enabled { "✓ " } else { " " }; let pad = menu_width .saturating_sub(u16::try_from(text.len()).unwrap_or(u16::MAX)) .saturating_sub(u16::try_from(indicator.len()).unwrap_or(u16::MAX)); let padding = " ".repeat(pad as usize); lines.push(Line::from(vec![ Span::styled( indicator.to_string(), Style::default().fg(if *enabled { th.green } else { th.overlay1 }), ), Span::styled(text.clone(), Style::default().fg(th.text)), Span::raw(padding), ])); } lines } /// What: Create a styled menu block with title. /// /// Inputs: /// - `lines`: Menu lines to display /// - `title_first_letter_key`: i18n key for first letter of title /// - `title_suffix_key`: i18n key for suffix of title /// - `app`: Application state for i18n /// - `th`: Theme colors /// /// Output: /// - Styled Paragraph widget ready for rendering fn create_menu_block( lines: Vec<Line<'static>>, title_first_letter_key: &str, title_suffix_key: &str, app: &AppState, th: crate::theme::Theme, ) -> Paragraph<'static> { let first_letter = i18n::t(app, title_first_letter_key); let suffix = i18n::t(app, title_suffix_key); Paragraph::new(lines) .style(Style::default().fg(th.text).bg(th.base)) .wrap(Wrap { trim: false }) .block( Block::default() .style(Style::default().bg(th.base)) .title(Line::from(vec![ Span::styled(" ", Style::default().fg(th.overlay1)), Span::styled( first_letter, Style::default() .fg(th.overlay1) .add_modifier(Modifier::UNDERLINED), ), Span::styled(suffix, Style::default().fg(th.overlay1)), ])) .borders(Borders::ALL) .border_type(BorderType::Rounded) .border_style(Style::default().fg(th.mauve)), ) } /// What: Render Config/Lists dropdown menu. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state /// - `results_area`: Available area for positioning /// - `th`: Theme colors /// /// Output: /// - Updates `app.config_menu_rect` if menu is rendered fn render_config_menu( f: &mut Frame, app: &mut AppState, results_area: Rect, th: crate::theme::Theme, ) { app.config_menu_rect = None; if !app.config_menu_open { return; } let opts: Vec<String> = vec![ i18n::t(app, "app.results.config_menu.options.settings"), i18n::t(app, "app.results.config_menu.options.theme"), i18n::t(app, "app.results.config_menu.options.keybindings"), ]; let widest = opts .iter() .map(|s| u16::try_from(s.width()).map_or(u16::MAX, |x| x)) .max() .unwrap_or(0); let (w, h, max_num_width) = calculate_menu_dimensions(&opts, results_area, 0); let (rect, inner_rect) = calculate_menu_rect(app.config_button_rect, w, h, results_area); app.config_menu_rect = Some(inner_rect); let spacing = 2u16; let lines = build_numbered_menu_lines(&opts, widest, max_num_width, w, spacing, th); let menu = create_menu_block( lines, "app.results.menus.config_lists.first_letter", "app.results.menus.config_lists.suffix", app, th, ); f.render_widget(Clear, rect); f.render_widget(menu, rect); } /// What: Render Panels dropdown menu. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state /// - `results_area`: Available area for positioning /// - `th`: Theme colors /// /// Output: /// - Updates `app.panels_menu_rect` if menu is rendered fn render_panels_menu( f: &mut Frame, app: &mut AppState, results_area: Rect, th: crate::theme::Theme, ) { app.panels_menu_rect = None; if !app.panels_menu_open { return; } let news_mode = matches!(app.app_mode, crate::state::types::AppMode::News); let opts: Vec<String> = if news_mode { let label_history = if app.show_news_history_pane { i18n::t(app, "app.results.panels_menu.hide_history") } else { i18n::t(app, "app.results.panels_menu.show_history") }; let label_bookmarks = if app.show_news_bookmarks_pane { i18n::t(app, "app.results.panels_menu.hide_bookmarks") } else { i18n::t(app, "app.results.panels_menu.show_bookmarks") }; let label_keybinds = if app.show_keybinds_footer { i18n::t(app, "app.results.panels_menu.hide_keybinds") } else { i18n::t(app, "app.results.panels_menu.show_keybinds") }; vec![label_history, label_bookmarks, label_keybinds] } else { let label_recent = if app.show_recent_pane { i18n::t(app, "app.results.panels_menu.hide_recent") } else { i18n::t(app, "app.results.panels_menu.show_recent") }; let label_install = if app.show_install_pane { i18n::t(app, "app.results.panels_menu.hide_install_list") } else { i18n::t(app, "app.results.panels_menu.show_install_list") }; let label_keybinds = if app.show_keybinds_footer { i18n::t(app, "app.results.panels_menu.hide_keybinds") } else { i18n::t(app, "app.results.panels_menu.show_keybinds") }; vec![label_recent, label_install, label_keybinds] }; let widest = opts .iter() .map(|s| u16::try_from(s.width()).map_or(u16::MAX, |x| x)) .max() .unwrap_or(0); let (w, h, max_num_width) = calculate_menu_dimensions(&opts, results_area, 0); let (rect, inner_rect) = calculate_menu_rect(app.panels_button_rect, w, h, results_area); app.panels_menu_rect = Some(inner_rect); let spacing = 2u16; let lines = build_numbered_menu_lines(&opts, widest, max_num_width, w, spacing, th); let menu = create_menu_block( lines, "app.results.menus.panels.first_letter", "app.results.menus.panels.suffix", app, th, ); f.render_widget(Clear, rect); f.render_widget(menu, rect); } /// What: Render Options dropdown menu. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state /// - `results_area`: Available area for positioning /// - `th`: Theme colors /// /// Output: /// - Updates `app.options_menu_rect` if menu is rendered fn render_options_menu( f: &mut Frame, app: &mut AppState, results_area: Rect, th: crate::theme::Theme, ) { app.options_menu_rect = None; if !app.options_menu_open { return; } let news_mode = matches!(app.app_mode, crate::state::types::AppMode::News); let mode_toggle_label = if news_mode { i18n::t(app, "app.results.options_menu.package_mode") } else { i18n::t(app, "app.results.options_menu.news_management") }; let mut opts: Vec<String> = Vec::new(); if !news_mode { let label_toggle = if app.installed_only_mode { i18n::t(app, "app.results.options_menu.list_all_packages") } else { i18n::t(app, "app.results.options_menu.list_installed_packages") }; opts.push(label_toggle); } opts.push(i18n::t(app, "app.results.options_menu.update_system")); opts.push(i18n::t(app, "app.results.options_menu.tui_optional_deps")); opts.push(mode_toggle_label); let widest = opts .iter() .map(|s| u16::try_from(s.width()).map_or(u16::MAX, |x| x)) .max() .unwrap_or(0); let (w, h, max_num_width) = calculate_menu_dimensions(&opts, results_area, 0); let (rect, inner_rect) = calculate_menu_rect(app.options_button_rect, w, h, results_area); app.options_menu_rect = Some(inner_rect); let spacing = 2u16; let lines = build_numbered_menu_lines(&opts, widest, max_num_width, w, spacing, th); let menu = create_menu_block( lines, "app.results.menus.options.first_letter", "app.results.menus.options.suffix", app, th, ); f.render_widget(Clear, rect); f.render_widget(menu, rect); } /// What: Render Artix filter dropdown menu. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state /// - `results_area`: Available area for positioning /// - `th`: Theme colors /// /// Output: /// - Updates `app.artix_filter_menu_rect` if menu is rendered fn render_artix_filter_menu( f: &mut Frame, app: &mut AppState, results_area: Rect, th: crate::theme::Theme, ) { app.artix_filter_menu_rect = None; if !app.artix_filter_menu_open { return; } let has_hidden_filters = app.results_filter_artix_omniverse_rect.is_none() && app.results_filter_artix_universe_rect.is_none() && app.results_filter_artix_lib32_rect.is_none() && app.results_filter_artix_galaxy_rect.is_none() && app.results_filter_artix_world_rect.is_none() && app.results_filter_artix_system_rect.is_none(); if !has_hidden_filters { return; } let all_on = app.results_filter_show_artix_omniverse && app.results_filter_show_artix_universe && app.results_filter_show_artix_lib32 && app.results_filter_show_artix_galaxy && app.results_filter_show_artix_world && app.results_filter_show_artix_system; let opts: Vec<(String, bool)> = vec![ (i18n::t(app, "app.results.filters.artix"), all_on), ( i18n::t(app, "app.results.filters.artix_omniverse"), app.results_filter_show_artix_omniverse, ), ( i18n::t(app, "app.results.filters.artix_universe"), app.results_filter_show_artix_universe, ), ( i18n::t(app, "app.results.filters.artix_lib32"), app.results_filter_show_artix_lib32, ), ( i18n::t(app, "app.results.filters.artix_galaxy"), app.results_filter_show_artix_galaxy, ), ( i18n::t(app, "app.results.filters.artix_world"), app.results_filter_show_artix_world, ), ( i18n::t(app, "app.results.filters.artix_system"), app.results_filter_show_artix_system, ), ]; let widest = opts .iter() .map(|(s, _)| u16::try_from(s.len()).map_or(u16::MAX, |x| x)) .max() .unwrap_or(0); let w = widest .saturating_add(4) // space for checkbox indicator .saturating_add(2) .min(results_area.width.saturating_sub(2)); let h = u16::try_from(opts.len()) .unwrap_or(u16::MAX) .saturating_add(2); let (rect, inner_rect) = calculate_menu_rect(app.results_filter_artix_rect, w, h, results_area); app.artix_filter_menu_rect = Some(inner_rect); let lines = build_checkbox_menu_lines(&opts, w, th); let menu = Paragraph::new(lines) .style(Style::default().fg(th.text).bg(th.base)) .wrap(Wrap { trim: true }) .block( Block::default() .style(Style::default().bg(th.base)) .title(Line::from(vec![Span::styled( "Artix Filters", Style::default().fg(th.overlay1), )])) .borders(Borders::ALL) .border_type(BorderType::Rounded) .border_style(Style::default().fg(th.mauve)), ); f.render_widget(Clear, rect); f.render_widget(menu, rect); } /// What: Render collapsed menu dropdown (contains Config/Lists, Panels, Options). /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state /// - `results_area`: Available area for positioning /// - `th`: Theme colors /// /// Output: /// - Updates `app.collapsed_menu_rect` if menu is rendered /// /// Details: /// - Menu is right-aligned to the button's right edge. fn render_collapsed_menu( f: &mut Frame, app: &mut AppState, results_area: Rect, th: crate::theme::Theme, ) { app.collapsed_menu_rect = None; if !app.collapsed_menu_open { return; } let opts: Vec<String> = vec![ i18n::t(app, "app.results.collapsed_menu.options.config_lists"), i18n::t(app, "app.results.collapsed_menu.options.panels"), i18n::t(app, "app.results.collapsed_menu.options.options"), ]; let widest = opts .iter() .map(|s| u16::try_from(s.width()).map_or(u16::MAX, |x| x)) .max() .unwrap_or(0); let (w, h, max_num_width) = calculate_menu_dimensions(&opts, results_area, 0); // Right-align menu to where "Options" button would be (rightmost position) let rect_w = w.saturating_add(2); // Calculate where Options button would be positioned (rightmost) // Match the calculation from title.rs: inner_width = area.width - 2, opt_x = area.x + 1 + inner_width - options_w let options_button_label = format!("{} v", i18n::t(app, "app.results.buttons.options")); let options_w = u16::try_from(options_button_label.width()).unwrap_or(u16::MAX); let inner_width = results_area.width.saturating_sub(2); let opt_x = results_area .x .saturating_add(1) // left border inset .saturating_add(inner_width.saturating_sub(options_w)); // Position menu so its right edge aligns with Options button's right edge let opt_right = opt_x.saturating_add(options_w); let menu_x = opt_right.saturating_sub(rect_w); // Clamp to viewport boundaries let min_x = results_area.x.saturating_add(1); let max_x = results_area .x .saturating_add(results_area.width) .saturating_sub(rect_w); let menu_x = menu_x.max(min_x).min(max_x); let menu_y = results_area.y.saturating_add(1); let rect = Rect { x: menu_x, y: menu_y, width: rect_w, height: h, }; let inner_rect = (rect.x + 1, rect.y + 1, w, h.saturating_sub(2)); app.collapsed_menu_rect = Some(inner_rect); let spacing = 2u16; let lines = build_numbered_menu_lines(&opts, widest, max_num_width, w, spacing, th); let menu = create_menu_block( lines, "app.results.menus.menu.first_letter", "app.results.menus.menu.suffix", app, th, ); f.render_widget(Clear, rect); f.render_widget(menu, rect); } /// What: Render dropdown menus (Config/Lists, Panels, Options) on the overlay layer. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state (tracks menu open flags and rects) /// - `results_area`: Rect of the results pane used for positioning /// /// Output: /// - Draws any open dropdowns and records their inner rectangles for hit-testing. /// /// Details: /// - Aligns menus with their buttons, clamps width to viewport, clears background, and numbers rows /// for keyboard shortcuts while ensuring menus render above other content. pub fn render_dropdowns(f: &mut Frame, app: &mut AppState, results_area: Rect) { let th = theme(); render_config_menu(f, app, results_area, th); render_panels_menu(f, app, results_area, th); render_options_menu(f, app, results_area, th); render_artix_filter_menu(f, app, results_area, th); render_collapsed_menu(f, app, results_area, th); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/results/list.rs
src/ui/results/list.rs
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 whether it's an optional repo (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 color = 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 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), )); } // 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_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; } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/results/status.rs
src/ui/results/status.rs
use ratatui::{ Frame, prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, widgets::Paragraph, }; use unicode_width::{UnicodeWidthChar, UnicodeWidthStr}; use crate::i18n; use crate::state::AppState; use crate::theme::{KeyChord, theme}; /// What: Draw the status label on the bottom border line of the Results block. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state (reads status info, updates rect) /// - `area`: Target rectangle for the results block /// /// Output: /// - Renders the status badge/text and records the clickable rect for opening the status page. /// /// Details: /// - Shows optional shortcut when Search normal mode is active, centers text within the border, and /// colors the status dot based on [`AppState::arch_status_color`]. #[allow(clippy::missing_const_for_fn)] pub fn render_status(f: &mut Frame, app: &mut AppState, area: Rect) { let th = theme(); // Bottom border y coordinate is area.y + area.height - 1 // Append the Normal-mode keybind used to open the status page only when Search Normal mode is active let key_label_opt = app .keymap .search_normal_open_status .first() .map(KeyChord::label); let show_key = matches!(app.focus, crate::state::Focus::Search) && app.search_normal_mode && key_label_opt.is_some(); let status_text = if show_key { i18n::t_fmt( app, "app.results.status_with_key", &[ &app.arch_status_text, &key_label_opt.expect("key_label_opt should be Some when show_key is true"), ], ) } else { format!( "{} {}", i18n::t(app, "app.results.status_label"), app.arch_status_text ) }; let sx = area.x.saturating_add(2); // a bit of left padding after corner let sy = area.y.saturating_add(area.height.saturating_sub(1)); let maxw = area.width.saturating_sub(4); // avoid right corner let mut content = status_text; // Truncate by display width, not byte length, to handle wide characters if u16::try_from(content.width()).unwrap_or(u16::MAX) > maxw { let mut truncated = String::new(); let mut width_so_far = 0u16; for ch in content.chars() { let ch_width = u16::try_from(ch.width().unwrap_or(0)).unwrap_or(u16::MAX); if width_so_far + ch_width > maxw { break; } truncated.push(ch); width_so_far += ch_width; } content = truncated; } // Compute style to blend with border line // Compose a dot + text with color depending on status let mut dot = ""; let mut dot_color = th.overlay1; match app.arch_status_color { crate::state::ArchStatusColor::Operational => { dot = "●"; dot_color = th.green; } crate::state::ArchStatusColor::IncidentToday => { dot = "●"; dot_color = th.yellow; } crate::state::ArchStatusColor::IncidentSevereToday => { dot = "●"; dot_color = th.red; } crate::state::ArchStatusColor::None => { // If we have a nominal message, still show a green dot if app .arch_status_text .to_lowercase() .contains("arch systems nominal") { dot = "●"; dot_color = th.green; } } } let style_text = Style::default() .fg(th.mauve) .bg(th.base) .add_modifier(Modifier::BOLD | Modifier::UNDERLINED); let line = Paragraph::new(Line::from(vec![ Span::styled( dot.to_string(), Style::default() .fg(dot_color) .bg(th.base) .add_modifier(Modifier::BOLD), ), Span::raw(" "), Span::styled(content.clone(), style_text), ])); // Record clickable rect centered within the available width // Use Unicode display width, not byte length, to handle wide characters let dot_width = u16::try_from(dot.width()).unwrap_or(u16::MAX); let content_width = u16::try_from(content.width()).unwrap_or(u16::MAX); let cw = (content_width + dot_width + 1).min(maxw); // +1 for the space let pad_left = maxw.saturating_sub(cw) / 2; let start_x = sx.saturating_add(pad_left); // Clickable rect only over the text portion, not the dot or space let click_start_x = start_x.saturating_add(dot_width + 1); app.arch_status_rect = Some(( click_start_x, sy, content_width.min(maxw.saturating_sub(dot_width + 1)), 1, )); let rect = ratatui::prelude::Rect { x: start_x, y: sy, width: cw, height: 1, }; f.render_widget(line, rect); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/results/sort_menu.rs
src/ui/results/sort_menu.rs
use ratatui::{ Frame, prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, widgets::{Block, BorderType, Borders, Clear, Paragraph, Wrap}, }; use crate::i18n; use crate::state::types::{AppMode, NewsSortMode}; use crate::state::{AppState, SortMode}; use crate::theme::theme; /// What: Render the sort dropdown overlay near the Sort button. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state (uses `sort_menu_open`, updates rect) /// - `area`: Target rectangle for the results block /// - `btn_x`: X coordinate of the Sort button /// /// Output: /// - Draws the dropdown when open and records its inner hit-test rectangle. /// /// Details: /// - Highlights the active sort mode, clamps placement within `area`, and clears the region before /// drawing to avoid overlapping artifacts. pub fn render_sort_menu(f: &mut Frame, app: &mut AppState, area: Rect, btn_x: u16) { let th = theme(); app.sort_menu_rect = None; if app.sort_menu_open { let opts: Vec<(String, bool)> = if matches!(app.app_mode, AppMode::News) { vec![ ( "Date (newest)".to_string(), app.news_sort_mode == NewsSortMode::DateDesc, ), ( "Date (oldest)".to_string(), app.news_sort_mode == NewsSortMode::DateAsc, ), ( "Title".to_string(), app.news_sort_mode == NewsSortMode::Title, ), ( "Source".to_string(), app.news_sort_mode == NewsSortMode::SourceThenTitle, ), ( "Severity (critical first)".to_string(), app.news_sort_mode == NewsSortMode::SeverityThenDate, ), ( "Unread first".to_string(), app.news_sort_mode == NewsSortMode::UnreadThenDate, ), ] } else { vec![ ( i18n::t(app, "app.results.sort_menu.options.alphabetical"), matches!(app.sort_mode, SortMode::RepoThenName), ), ( i18n::t(app, "app.results.sort_menu.options.aur_popularity"), matches!(app.sort_mode, SortMode::AurPopularityThenOfficial), ), ( i18n::t(app, "app.results.sort_menu.options.best_matches"), matches!(app.sort_mode, SortMode::BestMatches), ), ] }; let widest = opts .iter() .map(|(s, _)| u16::try_from(s.len()).map_or(u16::MAX, |x| x)) .max() .unwrap_or(0); let w = widest.saturating_add(2).min(area.width.saturating_sub(2)); // Place menu just under the title, aligned to button if possible let rect_w = w.saturating_add(2); let max_x = area.x + area.width.saturating_sub(rect_w); let menu_x = btn_x.min(max_x); let menu_y = area.y.saturating_add(1); // just below top border let h = u16::try_from(opts.len()) .unwrap_or(u16::MAX) .saturating_add(2); // borders let rect = ratatui::prelude::Rect { x: menu_x, y: menu_y, width: rect_w, height: h, }; // Record inner list area for hit-testing (exclude borders) app.sort_menu_rect = Some((rect.x + 1, rect.y + 1, w, h.saturating_sub(2))); // Build lines with current mode highlighted let mut lines: Vec<Line> = Vec::new(); for (text, selected) in &opts { let is_selected = *selected; let mark = if is_selected { "✔ " } else { " " }; let style = if is_selected { Style::default() .fg(th.crust) .bg(th.lavender) .add_modifier(Modifier::BOLD) } else { Style::default().fg(th.text) }; lines.push(Line::from(vec![ Span::styled(mark.to_string(), Style::default().fg(th.overlay1)), Span::styled(text.clone(), style), ])); } let menu = Paragraph::new(lines) .style(Style::default().fg(th.text).bg(th.base)) .wrap(Wrap { trim: true }) .block( Block::default() .title(Span::styled( format!(" {} ", i18n::t(app, "app.results.sort_menu.title")), Style::default().fg(th.overlay1), )) .borders(Borders::ALL) .border_type(BorderType::Rounded) .border_style(Style::default().fg(th.surface2)), ); f.render_widget(Clear, rect); f.render_widget(menu, rect); } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/results/utils.rs
src/ui/results/utils.rs
use ratatui::prelude::Rect; use super::{FilterStates, MenuStates, OptionalRepos, RenderContext}; use crate::state::{AppState, Source}; /// What: Detect availability of optional repos from the unfiltered results set. /// /// Inputs: /// - `app`: Application state providing `all_results` /// /// Output: /// - Tuple `(has_eos, has_cachyos, has_artix, has_artix_repos, has_manjaro)` indicating which repo chips to show. /// `has_artix_repos` is a tuple of (omniverse, universe, lib32, galaxy, world, system) booleans. /// /// Details: /// - Scans official result sources and package names to infer EOS/CachyOS/Artix/Manjaro presence, short /// circuiting once all are detected. #[allow(clippy::type_complexity)] pub fn detect_optional_repos( app: &AppState, ) -> (bool, bool, bool, (bool, bool, bool, bool, bool, bool), bool) { let mut eos = false; let mut cach = false; let mut artix = false; let mut artix_omniverse = false; let mut artix_universe = false; let mut artix_lib32 = false; let mut artix_galaxy = false; let mut artix_world = false; let mut artix_system = false; let mut manj = false; for it in &app.all_results { if let Source::Official { repo, .. } = &it.source { let r = repo.to_lowercase(); if !eos && crate::index::is_eos_repo(&r) { eos = true; } if !cach && crate::index::is_cachyos_repo(&r) { cach = true; } if !artix && crate::index::is_artix_repo(&r) { artix = true; } if !artix_omniverse && crate::index::is_artix_omniverse(&r) { artix_omniverse = true; } if !artix_universe && crate::index::is_artix_universe(&r) { artix_universe = true; } if !artix_lib32 && crate::index::is_artix_lib32(&r) { artix_lib32 = true; } if !artix_galaxy && crate::index::is_artix_galaxy(&r) { artix_galaxy = true; } if !artix_world && crate::index::is_artix_world(&r) { artix_world = true; } if !artix_system && crate::index::is_artix_system(&r) { artix_system = true; } } // Treat presence by name prefix rather than repo value if !manj && crate::index::is_name_manjaro(&it.name) { manj = true; } if eos && cach && artix && manj && artix_omniverse && artix_universe && artix_lib32 && artix_galaxy && artix_world && artix_system { break; } } ( eos, cach, artix, ( artix_omniverse, artix_universe, artix_lib32, artix_galaxy, artix_world, artix_system, ), manj, ) } /// What: Keep the results selection centered within the visible viewport when possible. /// /// Inputs: /// - `app`: Mutable application state containing the list state and results /// - `area`: Rect describing the results block (used to derive viewport rows) /// /// Output: /// - Adjusts `app.list_state` offset/selection to keep the highlight in view. /// /// Details: /// - Recenters around the selected index for long lists, resets offset for short lists, and ensures /// the selection is applied even when the filtered list shrinks. pub fn center_selection(app: &mut AppState, area: Rect) { let viewport_rows = area.height.saturating_sub(2) as usize; // account for borders let len = app.results.len(); let selected_idx = if app.results.is_empty() { None } else { Some(app.selected.min(len - 1)) }; if viewport_rows > 0 && len > viewport_rows { let selected = selected_idx.unwrap_or(0); let max_offset = len.saturating_sub(viewport_rows); let desired = selected.saturating_sub(viewport_rows / 2).min(max_offset); if app.list_state.offset() == desired { // ensure selection is set app.list_state.select(selected_idx); } else { let mut st = ratatui::widgets::ListState::default().with_offset(desired); st.select(selected_idx); app.list_state = st; } } else { // Small lists: ensure offset is 0 and selection is applied if app.list_state.offset() != 0 { let mut st = ratatui::widgets::ListState::default().with_offset(0); st.select(selected_idx); app.list_state = st; } else { app.list_state.select(selected_idx); } } } /// What: Extract all data needed for rendering from `AppState` in one operation. /// /// Inputs: /// - `app`: Application state to extract data from /// /// Output: /// - `RenderContext` containing all extracted values /// /// Details: /// - Reduces data flow complexity by extracting all needed values in a single function call /// instead of multiple individual field accesses. pub fn extract_render_context(app: &AppState) -> RenderContext { let (has_eos, has_cachyos, has_artix, has_artix_repos, has_manjaro) = detect_optional_repos(app); let ( has_artix_omniverse, has_artix_universe, has_artix_lib32, has_artix_galaxy, has_artix_world, has_artix_system, ) = has_artix_repos; RenderContext { results_len: app.results.len(), optional_repos: OptionalRepos { has_eos, has_cachyos, has_artix, has_artix_omniverse, has_artix_universe, has_artix_lib32, has_artix_galaxy, has_artix_world, has_artix_system, has_manjaro, }, menu_states: MenuStates { sort_menu_open: app.sort_menu_open, config_menu_open: app.config_menu_open, panels_menu_open: app.panels_menu_open, options_menu_open: app.options_menu_open, collapsed_menu_open: app.collapsed_menu_open, }, filter_states: FilterStates { show_aur: app.results_filter_show_aur, show_core: app.results_filter_show_core, show_extra: app.results_filter_show_extra, show_multilib: app.results_filter_show_multilib, show_eos: app.results_filter_show_eos, show_cachyos: app.results_filter_show_cachyos, show_artix: app.results_filter_show_artix, show_artix_omniverse: app.results_filter_show_artix_omniverse, show_artix_universe: app.results_filter_show_artix_universe, show_artix_lib32: app.results_filter_show_artix_lib32, show_artix_galaxy: app.results_filter_show_artix_galaxy, show_artix_world: app.results_filter_show_artix_world, show_artix_system: app.results_filter_show_artix_system, show_manjaro: app.results_filter_show_manjaro, }, } } /// What: Record the inner results rect for mouse hit-testing (inside borders). /// /// Inputs: /// - `app`: Mutable application state receiving the results rect /// - `area`: Rect of the overall results block /// /// Output: /// - Updates `app.results_rect` with the inner content rectangle. /// /// Details: /// - Offsets by one cell to exclude borders and reduces width/height accordingly for accurate /// click detection. #[allow(clippy::missing_const_for_fn)] pub fn record_results_rect(app: &mut AppState, area: Rect) { // Record inner results rect for mouse hit-testing (inside borders) app.results_rect = Some(( area.x + 1, area.y + 1, area.width.saturating_sub(2), area.height.saturating_sub(2), )); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/results/mod.rs
src/ui/results/mod.rs
use crate::state::AppState; use crate::state::types::AppMode; use crate::theme::theme; use ratatui::{ Frame, prelude::Rect, style::Style, text::Line, widgets::{Block, BorderType, Borders, List, ListItem}, }; /// Dropdown menu rendering module. mod dropdowns; /// Search results list rendering module. mod list; /// News feed rendering module. mod news; /// Sort menu rendering module. mod sort_menu; /// Status bar rendering module. mod status; /// Title bar rendering module. mod title; /// Utility functions for results rendering. mod utils; /// What: Context struct containing all extracted values needed for rendering. /// /// Inputs: Values extracted from `AppState` to avoid borrow conflicts. /// /// Output: Grouped context data. /// /// Details: Reduces data flow complexity by grouping related values together. pub struct RenderContext { /// Number of search results. pub results_len: usize, /// Optional repositories configuration. pub optional_repos: OptionalRepos, /// Menu states for dropdowns and menus. pub menu_states: MenuStates, /// Filter states for search results. pub filter_states: FilterStates, } /// What: Optional repository availability flags. /// /// Inputs: Individual boolean flags for each optional repo. /// /// Output: Struct containing all optional repo flags. /// /// Details: Used to pass multiple optional repo flags as a single parameter. #[allow(clippy::struct_excessive_bools)] pub struct OptionalRepos { /// Whether `EndeavourOS` repository is available. pub has_eos: bool, /// Whether `CachyOS` repository is available. pub has_cachyos: bool, /// Whether `Artix` repository is available. pub has_artix: bool, /// Whether `Artix Omniverse` repository is available. pub has_artix_omniverse: bool, /// Whether `Artix Universe` repository is available. pub has_artix_universe: bool, /// Whether `Artix Lib32` repository is available. pub has_artix_lib32: bool, /// Whether `Artix Galaxy` repository is available. pub has_artix_galaxy: bool, /// Whether `Artix World` repository is available. pub has_artix_world: bool, /// Whether `Artix System` repository is available. pub has_artix_system: bool, /// Whether `Manjaro` repository is available. pub has_manjaro: bool, } /// What: Menu open/closed states. /// /// Inputs: Individual boolean flags for each menu. /// /// Output: Struct containing all menu states. /// /// Details: Used to pass multiple menu states as a single parameter. #[allow(clippy::struct_excessive_bools)] pub struct MenuStates { /// Whether the sort menu is open. pub sort_menu_open: bool, /// Whether the config menu is open. pub config_menu_open: bool, /// Whether the panels menu is open. pub panels_menu_open: bool, /// Whether the options menu is open. pub options_menu_open: bool, /// Whether the collapsed menu is open. pub collapsed_menu_open: bool, } /// What: Filter toggle states. /// /// Inputs: Individual boolean flags for each filter. /// /// Output: Struct containing all filter states. /// /// Details: Used to pass multiple filter states as a single parameter. #[allow(clippy::struct_excessive_bools)] pub struct FilterStates { /// Whether to show AUR packages. pub show_aur: bool, /// Whether to show core repository packages. pub show_core: bool, /// Whether to show extra repository packages. pub show_extra: bool, /// Whether to show multilib repository packages. pub show_multilib: bool, /// Whether to show `EndeavourOS` repository packages. pub show_eos: bool, /// Whether to show `CachyOS` repository packages. pub show_cachyos: bool, /// Whether to show `Artix` repository packages. pub show_artix: bool, /// Whether to show `Artix Omniverse` repository packages. pub show_artix_omniverse: bool, /// Whether to show `Artix Universe` repository packages. pub show_artix_universe: bool, /// Whether to show `Artix Lib32` repository packages. pub show_artix_lib32: bool, /// Whether to show `Artix Galaxy` repository packages. pub show_artix_galaxy: bool, /// Whether to show `Artix World` repository packages. pub show_artix_world: bool, /// Whether to show `Artix System` repository packages. pub show_artix_system: bool, /// Whether to show `Manjaro` repository packages. pub show_manjaro: bool, } /// What: Render the top results list and title controls. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state (results, selection, rects) /// - `area`: Target rectangle for the results block /// /// Output: /// - Draws the results list and updates hit-test rectangles for Sort/Filters/Buttons and status. /// /// Details: /// - Keeps selection centered when possible; shows repo/labels, versions, descriptions, and /// install markers. /// - Builds the title with Sort button, filter toggles, and right-aligned options/config/panels. /// - Renders dropdown overlays for Sort/Options/Config/Panels when open, and records rects. /// - Reduces data flow complexity by extracting all data in one operation and batching mutations. pub fn render_results(f: &mut Frame, app: &mut AppState, area: Rect) { if matches!(app.app_mode, AppMode::News) { render_news_results(f, app, area); return; } // Keep selection centered within the visible results list when possible utils::center_selection(app, area); // Extract all data needed for rendering in one operation to reduce data flow complexity let ctx = utils::extract_render_context(app); // Build title and record rects (mutates app) let title_spans = title::build_title_spans_from_context(app, &ctx, area); title::record_title_rects_from_context(app, &ctx, area); // Render list widget render_list_widget(f, app, area, &title_spans); // Render status and sort menu, record rects (all mutate app) status::render_status(f, app, area); let btn_x = app.sort_button_rect.map_or(area.x, |(x, _, _, _)| x); sort_menu::render_sort_menu(f, app, area, btn_x); utils::record_results_rect(app, area); } /// What: Render the list widget with title and items. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Application state for list items and `list_state` /// - `area`: Target rectangle for the results block /// - `title_spans`: Pre-built title spans /// /// Output: /// - Renders the list widget with items and title. /// /// Details: /// - Builds list items only for visible viewport to improve performance. /// - Mutates `app.list_state` during rendering. fn render_list_widget( f: &mut Frame, app: &mut AppState, area: Rect, title_spans: &[ratatui::text::Span<'static>], ) { let th = theme(); let list_offset = app.list_state.offset(); let viewport_rows = area.height.saturating_sub(2) as usize; let start = list_offset; let end = std::cmp::min(app.results.len(), start + viewport_rows); // Settings are cached; avoid per-frame reloads by fetching once and cloning. let prefs = crate::theme::settings(); let items: Vec<ListItem> = app .results .iter() .enumerate() .map(|(i, p)| { let in_viewport = i >= start && i < end; list::build_list_item(p, app, &th, &prefs, in_viewport) }) .collect(); let list = List::new(items) .style(Style::default().fg(th.text).bg(th.base)) .block( Block::default() .title(Line::from(title_spans.to_vec())) .borders(Borders::ALL) .border_type(BorderType::Rounded) .border_style(Style::default().fg(th.surface2)), ) .highlight_style(Style::default().bg(th.surface1)) .highlight_symbol("> "); f.render_stateful_widget(list, area, &mut app.list_state); } /// What: Render dropdown menus (Config/Lists, Panels, Options) on top layer. /// /// This function should be called after all other UI elements are rendered /// to ensure dropdowns appear on top. pub use dropdowns::render_dropdowns; /// What: Render news results in the results area. /// /// Inputs: /// - `f`: Frame to render into. /// - `app`: Application state. /// - `area`: Area to render within. /// /// Output: Renders news feed items as a list. /// /// Details: Renders news feed items from `app.news_results` as a list with source labels. fn render_news_results(f: &mut Frame, app: &mut AppState, area: Rect) { let th = theme(); // Record results rect first (before any other mutations) app.results_rect = Some((area.x, area.y, area.width, area.height)); // Extract all immutable data we need first (clone to avoid borrowing) let news_loading = app.news_loading; let news_results = app.news_results.clone(); let news_read_ids = app.news_read_ids.clone(); let news_read_urls = app.news_read_urls.clone(); let needs_select_none = news_loading && news_results.is_empty(); // Now do all mutable operations first // Handle news_list_state mutation if needs_select_none { app.news_list_state.select(None); } // Build title spans and record rects (mutates app button/filter rects) let title_spans = news::build_news_title_spans_and_record_rects(app, area); // Build and render list inline to avoid storing items across mutable operations f.render_stateful_widget( List::new( news::build_news_list_items( app, news_loading, &news_results, &news_read_ids, &news_read_urls, ) .0, ) .style(Style::default().fg(th.text).bg(th.base)) .block( Block::default() .title(Line::from(title_spans)) .borders(Borders::ALL) .border_type(BorderType::Rounded) .border_style(Style::default().fg(th.surface2)), ) .highlight_style(Style::default().bg(th.surface1)) .highlight_symbol("> "), area, &mut app.news_list_state, ); let btn_x = app.sort_button_rect.map_or(area.x, |(x, _, _, _)| x); sort_menu::render_sort_menu(f, app, area, btn_x); } #[cfg(test)] mod tests { use super::*; use crate::state::types::NewsFeedSource; /// What: Ensure rendering results populates button rectangles and status overlays without panic. /// /// Inputs: /// - Single search result plus an operational status message. /// /// Output: /// - Sort, Options, Config, Panels button rectangles, along with status and results rects, become `Some`. /// /// Details: /// - Uses a `TestBackend` terminal to exercise layout code and verify hit-test regions are recorded. /// /// What: Initialize minimal English translations for tests. /// /// Inputs: /// - `app`: `AppState` to populate with translations /// /// Output: /// - Populates `app.translations` and `app.translations_fallback` with minimal English translations /// /// Details: /// - Sets up only the translations needed for tests to pass fn init_test_translations(app: &mut crate::state::AppState) { use std::collections::HashMap; let mut translations = HashMap::new(); translations.insert("app.results.title".to_string(), "Results".to_string()); translations.insert("app.results.buttons.sort".to_string(), "Sort".to_string()); translations.insert( "app.results.buttons.options".to_string(), "Options".to_string(), ); translations.insert( "app.results.buttons.panels".to_string(), "Panels".to_string(), ); translations.insert( "app.results.buttons.config_lists".to_string(), "Config/Lists".to_string(), ); translations.insert("app.results.buttons.menu".to_string(), "Menu".to_string()); translations.insert("app.results.filters.aur".to_string(), "AUR".to_string()); translations.insert("app.results.filters.core".to_string(), "core".to_string()); translations.insert("app.results.filters.extra".to_string(), "extra".to_string()); translations.insert( "app.results.filters.multilib".to_string(), "multilib".to_string(), ); translations.insert("app.results.filters.eos".to_string(), "EOS".to_string()); translations.insert( "app.results.filters.cachyos".to_string(), "CachyOS".to_string(), ); translations.insert("app.results.filters.artix".to_string(), "Artix".to_string()); translations.insert( "app.results.filters.artix_omniverse".to_string(), "OMNI".to_string(), ); translations.insert( "app.results.filters.artix_universe".to_string(), "UNI".to_string(), ); translations.insert( "app.results.filters.artix_lib32".to_string(), "LIB32".to_string(), ); translations.insert( "app.results.filters.artix_galaxy".to_string(), "GALAXY".to_string(), ); translations.insert( "app.results.filters.artix_world".to_string(), "WORLD".to_string(), ); translations.insert( "app.results.filters.artix_system".to_string(), "SYSTEM".to_string(), ); translations.insert( "app.results.filters.manjaro".to_string(), "Manjaro".to_string(), ); translations.insert("app.news.filters.arch".to_string(), "Arch".to_string()); translations.insert( "app.news.filters.advisories".to_string(), "Advisories".to_string(), ); translations.insert( "app.news.filters.installed_only".to_string(), "Installed".to_string(), ); app.translations = translations.clone(); app.translations_fallback = translations; } #[test] fn results_sets_title_button_rects_and_status_rect() { use ratatui::{Terminal, backend::TestBackend}; let backend = TestBackend::new(120, 20); let mut term = Terminal::new(backend).expect("failed to create test terminal"); let mut app = crate::state::AppState::default(); init_test_translations(&mut app); // Seed minimal results to render app.results = vec![crate::state::PackageItem { name: "pkg".into(), version: "1".into(), description: String::new(), source: crate::state::Source::Aur, popularity: Some(1.0), out_of_date: None, orphaned: false, }]; app.arch_status_text = "All systems operational".into(); app.arch_status_color = crate::state::ArchStatusColor::Operational; term.draw(|f| { let area = f.area(); render_results(f, &mut app, area); }) .expect("failed to draw test terminal"); assert!(app.sort_button_rect.is_some()); assert!(app.options_button_rect.is_some()); assert!(app.config_button_rect.is_some()); assert!(app.panels_button_rect.is_some()); assert!(app.arch_status_rect.is_some()); assert!(app.results_rect.is_some()); } #[test] fn news_filters_leave_gap_between_aur_comments_and_read_toggle() { use ratatui::{Terminal, backend::TestBackend}; let backend = TestBackend::new(160, 10); let mut term = Terminal::new(backend).expect("failed to create test terminal"); let mut app = crate::state::AppState::default(); init_test_translations(&mut app); app.app_mode = AppMode::News; app.news_results = vec![crate::state::types::NewsFeedItem { id: "1".into(), date: "2025-01-01".into(), title: "Example update".into(), summary: None, url: None, source: NewsFeedSource::AurComment, severity: None, packages: Vec::new(), }]; term.draw(|f| { let area = f.area(); render_results(f, &mut app, area); }) .expect("failed to draw test terminal"); let buffer = term.backend().buffer(); let mut title_line = String::new(); for x in 0..buffer.area.width { title_line.push_str(buffer[(x, 0)].symbol()); } let trimmed = title_line.trim_end(); assert!( trimmed.contains("[AUR Comments] [All]"), "expected spacing between AUR comments and read filters, saw: {trimmed}" ); } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/results/news.rs
src/ui/results/news.rs
use crate::i18n; use crate::state::AppState; use crate::state::types::{NewsFeedSource, NewsReadFilter}; use crate::theme::theme; use ratatui::{ prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, widgets::ListItem, }; use unicode_width::UnicodeWidthStr; /// What: Build list items for news feed results. /// /// Inputs: /// - `app`: Application state for i18n translations /// - `news_loading`: Whether news is currently loading /// - `news_results`: Reference to news results /// - `news_read_ids`: Set of read news IDs /// - `news_read_urls`: Set of read news URLs /// /// Output: /// - Tuple of `(Vec<ListItem>, bool)` where the boolean indicates if `app.news_list_state.select(None)` should be called. /// /// Details: /// - Shows "Loading..." if loading and no cached items exist /// - Otherwise builds items from `news_results` with read/unread indicators /// - Applies keyword highlighting to titles for Arch News items pub fn build_news_list_items<'a>( app: &AppState, news_loading: bool, news_results: &'a [crate::state::types::NewsFeedItem], news_read_ids: &'a std::collections::HashSet<String>, news_read_urls: &'a std::collections::HashSet<String>, ) -> (Vec<ListItem<'a>>, bool) { let th = theme(); let prefs = crate::theme::settings(); if news_loading && news_results.is_empty() { // Only show "Loading..." if no cached items exist (first-time load) // Show additional info that first load may take longer due to rate limiting // and that it may affect package management operations ( vec![ ListItem::new(Line::from(ratatui::text::Span::styled( i18n::t(app, "app.loading.news"), Style::default().fg(th.overlay1), ))), ListItem::new(Line::from(ratatui::text::Span::styled( i18n::t(app, "app.loading.news_first_load_hint"), Style::default().fg(th.subtext0), ))), ListItem::new(Line::from(ratatui::text::Span::styled( i18n::t(app, "app.loading.news_pkg_impact_hint"), Style::default().fg(th.yellow), ))), ], true, // needs to select None ) } else { // Show cached items immediately (even while loading fresh news) ( news_results .iter() .map(|item| build_news_list_item(item, news_read_ids, news_read_urls, &th, &prefs)) .collect(), false, // doesn't need to select None ) } } /// What: Build a single list item for a news feed item. /// /// Inputs: /// - `item`: News feed item to render /// - `app`: Application state for read status /// - `th`: Theme for colors /// - `prefs`: Theme preferences for symbols /// /// Output: /// - `ListItem` widget for the news feed item /// /// Details: /// - Determines read/unread status and applies appropriate styling /// - Applies keyword highlighting to titles for Arch News items fn build_news_list_item( item: &crate::state::types::NewsFeedItem, news_read_ids: &std::collections::HashSet<String>, news_read_urls: &std::collections::HashSet<String>, th: &crate::theme::Theme, prefs: &crate::theme::Settings, ) -> ListItem<'static> { let is_read = news_read_ids.contains(&item.id) || item .url .as_ref() .is_some_and(|u| news_read_urls.contains(u)); let read_symbol = if is_read { prefs.news_read_symbol.clone() } else { prefs.news_unread_symbol.clone() }; let read_style = if is_read { Style::default().fg(th.overlay1) } else { Style::default().fg(th.green) }; let (source_label, source_color) = match item.source { NewsFeedSource::ArchNews => ("Arch", th.sapphire), NewsFeedSource::SecurityAdvisory => ("Advisory", th.yellow), NewsFeedSource::InstalledPackageUpdate => ("Update", th.green), NewsFeedSource::AurPackageUpdate => ("AUR Upd", th.mauve), NewsFeedSource::AurComment => ("AUR Cmt", th.yellow), }; let sev = item .severity .as_ref() .map_or_else(String::new, |s| format!("{s:?}")); // Apply keyword highlighting to title for Arch News let highlight_style = ratatui::style::Style::default() .fg(th.yellow) .add_modifier(Modifier::BOLD); let title_spans = if matches!(item.source, NewsFeedSource::ArchNews) { render_aur_comment_keywords(&item.title, th, highlight_style) } else { vec![ratatui::text::Span::raw(item.title.clone())] }; let mut spans = vec![ ratatui::text::Span::styled( format!("{read_symbol} "), read_style.add_modifier(Modifier::BOLD), ), ratatui::text::Span::styled( format!("[{source_label}]"), Style::default().fg(source_color), ), ratatui::text::Span::raw(" "), ratatui::text::Span::raw(item.date.clone()), ratatui::text::Span::raw(" "), ]; spans.extend(title_spans); if !sev.is_empty() { spans.push(ratatui::text::Span::raw(" ")); spans.push(ratatui::text::Span::styled( format!("[{sev}]"), Style::default().fg(th.yellow), )); } if let Some(summary) = item.summary.as_ref() { spans.push(ratatui::text::Span::raw(" – ")); spans.extend(render_summary_spans(summary, th, item.source)); } let item_style = if is_read { Style::default().fg(th.subtext1) } else { Style::default().fg(th.text) }; ListItem::new(Line::from(spans)).style(item_style) } /// What: Context struct containing data needed for building news title spans. /// /// Inputs: Extracted data from `AppState` for title building. /// /// Output: Grouped context data. /// /// Details: Reduces data flow complexity by grouping related values together. #[allow(clippy::struct_excessive_bools)] struct NewsTitleContext { /// Title text showing news feed status and count title_text: String, /// Sort button label text sort_label: String, /// Date filter button label text date_label: String, /// Options menu button label text options_label: String, /// Panels menu button label text panels_label: String, /// Config menu button label text config_label: String, /// Arch news filter label text arch_filter_label: String, /// Security advisories filter label text advisory_filter_label: String, /// Package updates filter label text updates_filter_label: String, /// AUR updates filter label text aur_updates_filter_label: String, /// AUR comments filter label text aur_comments_filter_label: String, /// Read status filter label text read_filter_label: String, /// Whether sort menu is currently open sort_menu_open: bool, /// Whether options menu is currently open options_menu_open: bool, /// Whether panels menu is currently open panels_menu_open: bool, /// Whether config menu is currently open config_menu_open: bool, /// Whether to show Arch news filter news_filter_show_arch_news: bool, /// Whether to show advisories filter news_filter_show_advisories: bool, /// Whether to show package updates filter news_filter_show_pkg_updates: bool, /// Whether to show AUR updates filter news_filter_show_aur_updates: bool, /// Whether to show AUR comments filter news_filter_show_aur_comments: bool, /// Current read status filter setting news_filter_read_status: NewsReadFilter, } /// What: Extract context data needed for building news title spans. /// /// Inputs: /// - `app`: Application state /// /// Output: /// - `NewsTitleContext` with all extracted data /// /// Details: /// - Extracts all data needed for title building to reduce data flow complexity fn extract_news_title_context(app: &AppState) -> NewsTitleContext { let title_text = if app.news_loading { "News Feed (loading...)".to_string() } else { format!("News Feed ({})", app.news_results.len()) }; let age_label = app .news_max_age_days .map_or_else(|| "All".to_string(), |d| format!("{d} Days")); let sort_label = format!("{} v", i18n::t(app, "app.results.buttons.sort")); let date_label = format!("Date: {age_label}"); let options_label = format!("{} v", i18n::t(app, "app.results.buttons.options")); let panels_label = format!("{} v", i18n::t(app, "app.results.buttons.panels")); let config_label = format!("{} v", i18n::t(app, "app.results.buttons.config_lists")); let arch_filter_label = format!("[{}]", i18n::t(app, "app.news.filters.arch")); let advisory_filter_label = if !app.news_filter_show_advisories { "[Advisories Off]".to_string() } else if app.news_filter_installed_only { "[Advisories Installed]".to_string() } else { "[Advisories All]".to_string() }; let updates_filter_label = "[Updates]".to_string(); let aur_updates_filter_label = "[AUR Upd]".to_string(); let aur_comments_filter_label = "[AUR Comments]".to_string(); let read_filter_label = match app.news_filter_read_status { NewsReadFilter::All => "[All]".to_string(), NewsReadFilter::Read => "[Read]".to_string(), NewsReadFilter::Unread => "[Unread]".to_string(), }; NewsTitleContext { title_text, sort_label, date_label, options_label, panels_label, config_label, arch_filter_label, advisory_filter_label, updates_filter_label, aur_updates_filter_label, aur_comments_filter_label, read_filter_label, sort_menu_open: app.sort_menu_open, options_menu_open: app.options_menu_open, panels_menu_open: app.panels_menu_open, config_menu_open: app.config_menu_open, news_filter_show_arch_news: app.news_filter_show_arch_news, news_filter_show_advisories: app.news_filter_show_advisories, news_filter_show_pkg_updates: app.news_filter_show_pkg_updates, news_filter_show_aur_updates: app.news_filter_show_aur_updates, news_filter_show_aur_comments: app.news_filter_show_aur_comments, news_filter_read_status: app.news_filter_read_status, } } /// What: Calculate widths for all UI elements in the title bar. /// /// Inputs: /// - `ctx`: Title context with labels /// /// Output: /// - Struct containing all calculated widths /// /// Details: /// - Calculates Unicode-aware widths for proper layout positioning struct TitleWidths { /// Width of the title text span title: u16, /// Width of the Arch news filter span arch: u16, /// Width of the advisory filter span advisory: u16, /// Width of the updates filter span updates: u16, /// Width of the AUR updates filter span aur_updates: u16, /// Width of the AUR comments filter span aur_comments: u16, /// Width of the read filter span read: u16, /// Width of the date button span date: u16, /// Width of the sort button span sort: u16, /// Width of the options button span options: u16, /// Width of the panels button span panels: u16, /// Width of the config button span config: u16, } /// Calculate display widths for all UI elements in the title bar. /// /// What: Computes Unicode-aware widths for proper layout positioning. /// /// Inputs: /// - `ctx`: Title context containing all label texts /// /// Output: /// - `TitleWidths` struct with calculated widths for all elements /// /// Details: /// - Uses `unicode_width` to handle multi-byte characters correctly /// - Returns `u16::MAX` for any calculation that fails (extremely unlikely) fn calculate_title_widths(ctx: &NewsTitleContext) -> TitleWidths { TitleWidths { title: u16::try_from(ctx.title_text.width()).unwrap_or(u16::MAX), arch: u16::try_from(ctx.arch_filter_label.width()).unwrap_or(u16::MAX), advisory: u16::try_from(ctx.advisory_filter_label.width()).unwrap_or(u16::MAX), updates: u16::try_from(ctx.updates_filter_label.width()).unwrap_or(u16::MAX), aur_updates: u16::try_from(ctx.aur_updates_filter_label.width()).unwrap_or(u16::MAX), aur_comments: u16::try_from(ctx.aur_comments_filter_label.width()).unwrap_or(u16::MAX), read: u16::try_from(ctx.read_filter_label.width()).unwrap_or(u16::MAX), date: u16::try_from(ctx.date_label.width()).unwrap_or(u16::MAX), sort: u16::try_from(ctx.sort_label.width()).unwrap_or(u16::MAX), options: u16::try_from(ctx.options_label.width()).unwrap_or(u16::MAX), panels: u16::try_from(ctx.panels_label.width()).unwrap_or(u16::MAX), config: u16::try_from(ctx.config_label.width()).unwrap_or(u16::MAX), } } /// What: Build all styled spans for buttons and filters. /// /// Inputs: /// - `ctx`: Title context with labels and states /// - `th`: Theme for styling /// /// Output: /// - Struct containing all styled spans /// /// Details: /// - Creates styled spans for all buttons and filters in the title bar struct TitleSpans { /// Title span showing news feed status title: Span<'static>, /// Sort button spans sort_button: Vec<Span<'static>>, /// Arch news filter span arch_filter: Span<'static>, /// Advisory filter span advisory_filter: Span<'static>, /// Package updates filter span updates_filter: Span<'static>, /// AUR updates filter span aur_updates_filter: Span<'static>, /// AUR comments filter span aur_comments_filter: Span<'static>, /// Read filter span read_filter: Span<'static>, /// Date button spans date_button: Vec<Span<'static>>, /// Config button spans config_button: Vec<Span<'static>>, /// Panels button spans panels_button: Vec<Span<'static>>, /// Options button spans options_button: Vec<Span<'static>>, } /// Build styled spans for all buttons and filters in the title bar. /// /// What: Creates ratatui spans with proper styling and theming. /// /// Inputs: /// - `ctx`: Title context containing labels and state information /// /// Output: /// - `TitleSpans` struct containing all styled spans ready for rendering /// /// Details: /// - Applies theme colors and styles based on menu states /// - Handles button underlining and filter highlighting /// - Uses consistent styling patterns across all UI elements fn build_title_spans(ctx: &NewsTitleContext) -> TitleSpans { let th = theme(); let button_style = |is_open: bool| -> Style { if is_open { Style::default() .fg(th.crust) .bg(th.mauve) .add_modifier(Modifier::BOLD) } else { Style::default() .fg(th.mauve) .bg(th.surface2) .add_modifier(Modifier::BOLD) } }; let render_button = |label: &str, is_open: bool| -> Vec<Span<'static>> { let style = button_style(is_open); let mut spans = Vec::new(); if let Some(first) = label.chars().next() { let rest = &label[first.len_utf8()..]; spans.push(Span::styled( first.to_string(), style.add_modifier(Modifier::UNDERLINED), )); spans.push(Span::styled(rest.to_string(), style)); } else { spans.push(Span::styled(label.to_string(), style)); } spans }; let render_filter = |label: &str, active: bool| -> Span<'static> { let (fg, bg) = if active { (th.crust, th.green) } else { (th.mauve, th.surface2) }; Span::styled( label.to_string(), Style::default().fg(fg).bg(bg).add_modifier(Modifier::BOLD), ) }; TitleSpans { title: Span::styled(ctx.title_text.clone(), Style::default().fg(th.overlay1)), sort_button: render_button(&ctx.sort_label, ctx.sort_menu_open), arch_filter: render_filter(&ctx.arch_filter_label, ctx.news_filter_show_arch_news), advisory_filter: render_filter(&ctx.advisory_filter_label, ctx.news_filter_show_advisories), updates_filter: render_filter(&ctx.updates_filter_label, ctx.news_filter_show_pkg_updates), aur_updates_filter: render_filter( &ctx.aur_updates_filter_label, ctx.news_filter_show_aur_updates, ), aur_comments_filter: render_filter( &ctx.aur_comments_filter_label, ctx.news_filter_show_aur_comments, ), read_filter: render_filter( &ctx.read_filter_label, !matches!(ctx.news_filter_read_status, NewsReadFilter::All), ), date_button: render_button(&ctx.date_label, false), config_button: render_button(&ctx.config_label, ctx.config_menu_open), panels_button: render_button(&ctx.panels_label, ctx.panels_menu_open), options_button: render_button(&ctx.options_label, ctx.options_menu_open), } } /// What: Build title spans for news feed title bar and record hit-test rectangles. /// /// Inputs: /// - `app`: Application state for filter states and labels (mutated to record rects) /// - `area`: Rendering area for width calculations /// /// Output: /// - Vector of `Span` widgets for the title bar /// /// Details: /// - Builds title with loading indicator, filters, buttons, and right-aligned controls /// - Records hit-test rectangles for buttons and filters in `app` /// - Calculates layout positions for proper spacing pub fn build_news_title_spans_and_record_rects( app: &mut AppState, area: Rect, ) -> Vec<Span<'static>> { // Extract context data to reduce data flow complexity let ctx = extract_news_title_context(app); let widths = calculate_title_widths(&ctx); let spans = build_title_spans(&ctx); let inner_width = area.width.saturating_sub(2); // Build the left side of the title bar let mut title_spans: Vec<Span<'static>> = Vec::new(); title_spans.push(spans.title); title_spans.push(Span::raw(" ")); // Position cursor after title let mut x_cursor = area .x .saturating_add(1) .saturating_add(widths.title) .saturating_add(2); // Add sort button title_spans.extend(spans.sort_button); x_cursor = x_cursor.saturating_add(widths.sort).saturating_add(2); title_spans.push(Span::raw(" ")); // Add filters with spacing title_spans.push(spans.arch_filter); x_cursor = x_cursor.saturating_add(widths.arch).saturating_add(1); title_spans.push(Span::raw(" ")); title_spans.push(spans.advisory_filter); x_cursor = x_cursor.saturating_add(widths.advisory).saturating_add(1); title_spans.push(Span::raw(" ")); title_spans.push(spans.updates_filter); x_cursor = x_cursor.saturating_add(widths.updates).saturating_add(1); title_spans.push(Span::raw(" ")); title_spans.push(spans.aur_updates_filter); x_cursor = x_cursor .saturating_add(widths.aur_updates) .saturating_add(1); title_spans.push(Span::raw(" ")); title_spans.push(spans.aur_comments_filter); x_cursor = x_cursor.saturating_add(widths.aur_comments); title_spans.push(Span::raw(" ")); x_cursor = x_cursor.saturating_add(2); title_spans.push(spans.read_filter); x_cursor = x_cursor.saturating_add(widths.read); title_spans.push(Span::raw(" ")); x_cursor = x_cursor.saturating_add(2); // Calculate right-aligned button positions let options_x = area .x .saturating_add(1) .saturating_add(inner_width.saturating_sub(widths.options)); let panels_x = options_x.saturating_sub(1).saturating_sub(widths.panels); let config_x = panels_x.saturating_sub(1).saturating_sub(widths.config); let date_x = x_cursor; let gap_after_date = config_x.saturating_sub(date_x.saturating_add(widths.date)); // Add right-aligned buttons with gap title_spans.extend(spans.date_button); title_spans.push(Span::raw(" ".repeat(gap_after_date as usize))); title_spans.extend(spans.config_button); title_spans.push(Span::raw(" ")); title_spans.extend(spans.panels_button); title_spans.push(Span::raw(" ")); title_spans.extend(spans.options_button); // Record hit-test rectangles for buttons and filters let mut x_cursor_rect = area .x .saturating_add(1) .saturating_add(widths.title) .saturating_add(2); app.sort_button_rect = Some((x_cursor_rect, area.y, widths.sort, 1)); x_cursor_rect = x_cursor_rect.saturating_add(widths.sort).saturating_add(2); app.news_filter_arch_rect = Some((x_cursor_rect, area.y, widths.arch, 1)); x_cursor_rect = x_cursor_rect.saturating_add(widths.arch).saturating_add(1); app.news_filter_advisory_rect = Some((x_cursor_rect, area.y, widths.advisory, 1)); x_cursor_rect = x_cursor_rect .saturating_add(widths.advisory) .saturating_add(1); app.news_filter_updates_rect = Some((x_cursor_rect, area.y, widths.updates, 1)); x_cursor_rect = x_cursor_rect .saturating_add(widths.updates) .saturating_add(1); app.news_filter_aur_updates_rect = Some((x_cursor_rect, area.y, widths.aur_updates, 1)); x_cursor_rect = x_cursor_rect .saturating_add(widths.aur_updates) .saturating_add(1); app.news_filter_aur_comments_rect = Some((x_cursor_rect, area.y, widths.aur_comments, 1)); x_cursor_rect = x_cursor_rect .saturating_add(widths.aur_comments) .saturating_add(2); app.news_filter_read_rect = Some((x_cursor_rect, area.y, widths.read, 1)); let _ = x_cursor_rect.saturating_add(widths.read).saturating_add(2); app.news_age_button_rect = Some((date_x, area.y, widths.date, 1)); app.config_button_rect = Some((config_x, area.y, widths.config, 1)); app.panels_button_rect = Some((panels_x, area.y, widths.panels, 1)); app.options_button_rect = Some((options_x, area.y, widths.options, 1)); title_spans } /// What: Render summary spans with source-aware highlighting (updates vs AUR comments vs Arch News). /// /// Inputs: /// - `summary`: Summary text to render /// - `th`: Theme for colors /// - `source`: News feed source type /// /// Output: /// - Vector of styled spans for the summary /// /// Details: /// - Applies different highlighting based on source type /// - Updates get full highlight, AUR comments and Arch News get keyword highlighting pub fn render_summary_spans( summary: &str, th: &crate::theme::Theme, source: NewsFeedSource, ) -> Vec<ratatui::text::Span<'static>> { let highlight_style = ratatui::style::Style::default() .fg(th.yellow) .add_modifier(Modifier::BOLD); let normal = ratatui::style::Style::default().fg(th.subtext1); if matches!( source, NewsFeedSource::InstalledPackageUpdate | NewsFeedSource::AurPackageUpdate ) { return vec![ratatui::text::Span::styled( summary.to_string(), highlight_style, )]; } if matches!(source, NewsFeedSource::AurComment) { return render_aur_comment_keywords(summary, th, highlight_style); } // Apply keyword highlighting to Arch News (same as AUR comments) if matches!(source, NewsFeedSource::ArchNews) { return render_aur_comment_keywords(summary, th, highlight_style); } vec![ratatui::text::Span::styled( summary.to_string(), normal.add_modifier(Modifier::BOLD), )] } /// What: Highlight AUR comment summaries and Arch News with red/green keywords and normal text. /// /// Inputs: /// - `summary`: Text to highlight /// - `th`: Theme for colors /// - `base`: Base style for normal text /// /// Output: /// - Vector of styled spans with keyword highlighting /// /// Details: /// - Highlights negative words (crash, bug, error, etc.) in red /// - Highlights positive words (fix, patch, resolve, etc.) in green /// - Other text uses the base style pub fn render_aur_comment_keywords( summary: &str, th: &crate::theme::Theme, base: ratatui::style::Style, ) -> Vec<ratatui::text::Span<'static>> { let normal = base; let neg = ratatui::style::Style::default() .fg(th.red) .add_modifier(Modifier::BOLD); let pos = ratatui::style::Style::default() .fg(th.green) .add_modifier(Modifier::BOLD); let negative_words = [ "crash", "crashed", "crashes", "critical", "bug", "bugs", "fail", "fails", "failed", "failure", "failures", "issue", "issues", "trouble", "troubles", "panic", "segfault", "broken", "regression", "hang", "freeze", "unstable", "error", "errors", "require manual intervention", "requires manual intervention", "corrupting", ]; let positive_words = [ "fix", "fixed", "fixes", "patch", "patched", "solve", "solved", "solves", "solution", "resolve", "resolved", "resolves", "workaround", ]; let neg_set: std::collections::HashSet<&str> = negative_words.into_iter().collect(); let pos_set: std::collections::HashSet<&str> = positive_words.into_iter().collect(); let mut spans = Vec::new(); for token in summary.split_inclusive(' ') { let cleaned = token .trim_matches(|c: char| !c.is_alphanumeric() && c != '-' && c != '_') .to_ascii_lowercase(); let style = if pos_set.contains(cleaned.as_str()) { pos } else if neg_set.contains(cleaned.as_str()) { neg } else { normal.add_modifier(Modifier::BOLD) }; spans.push(ratatui::text::Span::styled(token.to_string(), style)); } spans }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/results/title/i18n.rs
src/ui/results/title/i18n.rs
use crate::i18n; use crate::state::AppState; use super::types::TitleI18nStrings; /// What: Build `TitleI18nStrings` from `AppState`. /// /// Inputs: /// - `app`: Application state for i18n /// /// Output: `TitleI18nStrings` containing all pre-computed i18n strings. /// /// Details: Extracts all i18n strings needed for title rendering in one place. pub(super) fn build_title_i18n_strings(app: &AppState) -> TitleI18nStrings { TitleI18nStrings { results_title: i18n::t(app, "app.results.title"), sort_button: i18n::t(app, "app.results.buttons.sort"), options_button: i18n::t(app, "app.results.buttons.options"), panels_button: i18n::t(app, "app.results.buttons.panels"), config_button: i18n::t(app, "app.results.buttons.config_lists"), menu_button: i18n::t(app, "app.results.buttons.menu"), filter_aur: i18n::t(app, "app.results.filters.aur"), filter_core: i18n::t(app, "app.results.filters.core"), filter_extra: i18n::t(app, "app.results.filters.extra"), filter_multilib: i18n::t(app, "app.results.filters.multilib"), filter_eos: i18n::t(app, "app.results.filters.eos"), filter_cachyos: i18n::t(app, "app.results.filters.cachyos"), filter_artix: i18n::t(app, "app.results.filters.artix"), filter_artix_omniverse: i18n::t(app, "app.results.filters.artix_omniverse"), filter_artix_universe: i18n::t(app, "app.results.filters.artix_universe"), filter_artix_lib32: i18n::t(app, "app.results.filters.artix_lib32"), filter_artix_galaxy: i18n::t(app, "app.results.filters.artix_galaxy"), filter_artix_world: i18n::t(app, "app.results.filters.artix_world"), filter_artix_system: i18n::t(app, "app.results.filters.artix_system"), filter_manjaro: i18n::t(app, "app.results.filters.manjaro"), } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/results/title/rects.rs
src/ui/results/title/rects.rs
use ratatui::prelude::Rect; use unicode_width::UnicodeWidthStr; use crate::state::AppState; use super::super::OptionalRepos; use super::i18n::build_title_i18n_strings; use super::layout::calculate_title_layout_info; use super::types::{CoreFilterLabels, LayoutState, OptionalReposLabels, TitleLayoutInfo}; /// What: Record rectangles for core filter buttons (AUR, core, extra, multilib). /// /// Inputs: /// - `app`: Mutable application state (rects will be updated) /// - `layout`: Layout state tracker /// - `core_labels`: Labels for core filters /// /// Output: Updates app with core filter rectangles. /// /// Details: Records rectangles for the four core filter buttons in sequence. fn record_core_filter_rects( app: &mut AppState, layout: &mut LayoutState, core_labels: &CoreFilterLabels, ) { // Use Unicode display width, not byte length, to handle wide characters app.results_filter_aur_rect = Some(layout.record_rect(&core_labels.aur)); layout.advance( u16::try_from(core_labels.aur.width()).unwrap_or(u16::MAX), 1, ); app.results_filter_core_rect = Some(layout.record_rect(&core_labels.core)); layout.advance( u16::try_from(core_labels.core.width()).unwrap_or(u16::MAX), 1, ); app.results_filter_extra_rect = Some(layout.record_rect(&core_labels.extra)); layout.advance( u16::try_from(core_labels.extra.width()).unwrap_or(u16::MAX), 1, ); app.results_filter_multilib_rect = Some(layout.record_rect(&core_labels.multilib)); layout.advance( u16::try_from(core_labels.multilib.width()).unwrap_or(u16::MAX), 1, ); } /// What: Record rectangles for optional repository filters. /// /// Inputs: /// - `app`: Mutable application state (rects will be updated) /// - `layout`: Layout state tracker /// - `optional_repos`: Optional repository availability flags /// - `optional_labels`: Labels for optional repos /// - `show_artix_specific_repos`: Whether to show Artix-specific repo filters /// /// Output: Updates app with optional repo filter rectangles. /// /// Details: Records rectangles for `EOS`, `CachyOS`, `Artix`, Artix-specific repos, and `Manjaro` filters. fn record_optional_repo_rects( app: &mut AppState, layout: &mut LayoutState, optional_repos: &OptionalRepos, optional_labels: &OptionalReposLabels, show_artix_specific_repos: bool, ) { // Record EOS filter // Use Unicode display width, not byte length, to handle wide characters if optional_repos.has_eos { app.results_filter_eos_rect = Some(layout.record_rect(&optional_labels.eos)); layout.advance( u16::try_from(optional_labels.eos.width()).unwrap_or(u16::MAX), 1, ); } else { app.results_filter_eos_rect = None; } // Record CachyOS filter if optional_repos.has_cachyos { app.results_filter_cachyos_rect = Some(layout.record_rect(&optional_labels.cachyos)); layout.advance( u16::try_from(optional_labels.cachyos.width()).unwrap_or(u16::MAX), 1, ); } else { app.results_filter_cachyos_rect = None; } // Record Artix filter (with dropdown indicator if specific filters are hidden) if optional_repos.has_artix { let artix_label_with_indicator = if show_artix_specific_repos { optional_labels.artix.clone() } else { format!("{} v", optional_labels.artix) }; app.results_filter_artix_rect = Some(layout.record_rect(&artix_label_with_indicator)); layout.advance( u16::try_from(artix_label_with_indicator.width()).unwrap_or(u16::MAX), 1, ); } else { app.results_filter_artix_rect = None; } // Record Artix-specific repo filter rects only if there's space if show_artix_specific_repos { let artix_rects = [ ( optional_repos.has_artix_omniverse, &optional_labels.artix_omniverse, &mut app.results_filter_artix_omniverse_rect, ), ( optional_repos.has_artix_universe, &optional_labels.artix_universe, &mut app.results_filter_artix_universe_rect, ), ( optional_repos.has_artix_lib32, &optional_labels.artix_lib32, &mut app.results_filter_artix_lib32_rect, ), ( optional_repos.has_artix_galaxy, &optional_labels.artix_galaxy, &mut app.results_filter_artix_galaxy_rect, ), ( optional_repos.has_artix_world, &optional_labels.artix_world, &mut app.results_filter_artix_world_rect, ), ( optional_repos.has_artix_system, &optional_labels.artix_system, &mut app.results_filter_artix_system_rect, ), ]; for (has_repo, label, rect_field) in artix_rects { if has_repo { *rect_field = Some(layout.record_rect(label)); // Use Unicode display width, not byte length, to handle wide characters layout.advance(u16::try_from(label.width()).unwrap_or(u16::MAX), 1); } else { *rect_field = None; } } } else { // Hide Artix-specific repo filter rects when space is tight app.results_filter_artix_omniverse_rect = None; app.results_filter_artix_universe_rect = None; app.results_filter_artix_lib32_rect = None; app.results_filter_artix_galaxy_rect = None; app.results_filter_artix_world_rect = None; app.results_filter_artix_system_rect = None; } // Record Manjaro filter if optional_repos.has_manjaro { app.results_filter_manjaro_rect = Some(layout.record_rect(&optional_labels.manjaro)); } else { app.results_filter_manjaro_rect = None; } } /// What: Record rectangles for right-aligned buttons (Config/Lists, Panels, Options) or collapsed Menu button. /// /// Inputs: /// - `app`: Mutable application state (rects will be updated) /// - `area`: Target rectangle for the results block /// - `layout_info`: Title layout information /// - `btn_y`: Y position for buttons /// /// Output: Updates app with right-aligned button rectangles. /// /// Details: Records rectangles for either all three buttons or the collapsed Menu button based on available space. fn record_right_aligned_button_rects( app: &mut AppState, area: Rect, layout_info: &TitleLayoutInfo, btn_y: u16, ) { if layout_info.use_collapsed_menu { // Record collapsed menu button rect if we have space for it if layout_info.menu_pad >= 1 { let menu_w = u16::try_from(layout_info.menu_button_label.width()).unwrap_or(u16::MAX); let menu_x = area .x .saturating_add(1) // left border inset .saturating_add(layout_info.inner_width.saturating_sub(menu_w)); app.collapsed_menu_button_rect = Some((menu_x, btn_y, menu_w, 1)); } else { app.collapsed_menu_button_rect = None; } // Clear individual button rects app.config_button_rect = None; app.options_button_rect = None; app.panels_button_rect = None; } else if layout_info.pad >= 1 { // Record clickable rects at the computed right edge (Panels to the left of Options) // Use Unicode display width, not byte length, to handle wide characters let options_w = u16::try_from(layout_info.options_button_label.width()).unwrap_or(u16::MAX); let panels_w = u16::try_from(layout_info.panels_button_label.width()).unwrap_or(u16::MAX); let config_w = u16::try_from(layout_info.config_button_label.width()).unwrap_or(u16::MAX); let opt_x = area .x .saturating_add(1) // left border inset .saturating_add(layout_info.inner_width.saturating_sub(options_w)); let pan_x = opt_x.saturating_sub(1).saturating_sub(panels_w); let cfg_x = pan_x.saturating_sub(1).saturating_sub(config_w); app.config_button_rect = Some((cfg_x, btn_y, config_w, 1)); app.options_button_rect = Some((opt_x, btn_y, options_w, 1)); app.panels_button_rect = Some((pan_x, btn_y, panels_w, 1)); // Clear collapsed menu button rect app.collapsed_menu_button_rect = None; } else { app.config_button_rect = None; app.options_button_rect = None; app.panels_button_rect = None; app.collapsed_menu_button_rect = None; } } /// What: Record clickable rectangles for title bar controls. /// /// Inputs: /// - `app`: Mutable application state (rects will be updated) /// - `area`: Target rectangle for the results block /// - `optional_repos`: Optional repository availability flags /// /// Output: /// - Updates `app` with rectangles for filters, buttons, and optional repo chips. /// /// Details: /// - Mirrors title layout calculations to align rects with rendered elements and clears entries when /// controls cannot fit in the available width. /// - Uses shared layout calculation logic and helper functions to reduce complexity. pub(super) fn record_title_rects(app: &mut AppState, area: Rect, optional_repos: &OptionalRepos) { let inner_width = area.width.saturating_sub(2); // exclude borders let i18n = build_title_i18n_strings(app); // Calculate shared layout information let layout_info = calculate_title_layout_info(&i18n, app.results.len(), inner_width, optional_repos); // Initialize layout state starting after title and sort button // Use Unicode display width, not byte length, to handle wide characters let btn_y = area.y; // top border row let initial_x = area .x .saturating_add(1) // left border inset .saturating_add(u16::try_from(layout_info.results_title_text.width()).unwrap_or(u16::MAX)) .saturating_add(2) // two spaces before Sort .saturating_add(u16::try_from(layout_info.sort_button_label.width()).unwrap_or(u16::MAX)) .saturating_add(2); // space after sort let mut layout = LayoutState::new(initial_x, btn_y); // Record sort button rect let sort_btn_x = area .x .saturating_add(1) .saturating_add(u16::try_from(layout_info.results_title_text.width()).unwrap_or(u16::MAX)) .saturating_add(2); app.sort_button_rect = Some(( sort_btn_x, btn_y, u16::try_from(layout_info.sort_button_label.width()).unwrap_or(u16::MAX), 1, )); // Record core filter rects record_core_filter_rects(app, &mut layout, &layout_info.core_labels); // Record optional repo filter rects record_optional_repo_rects( app, &mut layout, optional_repos, &layout_info.optional_labels, layout_info.show_artix_specific_repos, ); // Record right-aligned button rects record_right_aligned_button_rects(app, area, &layout_info, btn_y); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/results/title/rendering.rs
src/ui/results/title/rendering.rs
use ratatui::{ style::{Modifier, Style}, text::Span, }; use crate::theme::theme; use super::super::{FilterStates, MenuStates, OptionalRepos}; use super::types::TitleI18nStrings; /// What: Get button style based on menu open state. /// /// Inputs: /// - `is_open`: Whether the menu is open /// /// Output: Styled button appearance. /// /// Details: Returns active style when open, inactive style when closed. fn get_button_style(is_open: bool) -> Style { let th = theme(); if is_open { Style::default() .fg(th.crust) .bg(th.mauve) .add_modifier(Modifier::BOLD) } else { Style::default() .fg(th.mauve) .bg(th.surface2) .add_modifier(Modifier::BOLD) } } /// What: Render a button with underlined first character. /// /// Inputs: /// - `label`: Button label text /// - `style`: Style to apply /// /// Output: Vector of spans for the button. /// /// Details: First character is underlined, rest uses normal style. fn render_button_with_underline(label: &str, style: Style) -> Vec<Span<'static>> { let mut spans = Vec::new(); if let Some(first) = label.chars().next() { let rest = &label[first.len_utf8()..]; spans.push(Span::styled( first.to_string(), style.add_modifier(Modifier::UNDERLINED), )); spans.push(Span::styled(rest.to_string(), style)); } else { spans.push(Span::styled(label.to_string(), style)); } spans } /// What: Create filter rendering closure. /// /// Inputs: None (uses theme). /// /// Output: Closure that renders a filter label with styling. /// /// Details: Returns a closure that applies theme styling based on active state. fn create_filter_renderer() -> impl Fn(&str, bool) -> Span<'static> { let th = theme(); move |label: &str, on: bool| -> Span<'static> { let (fg, bg) = if on { (th.crust, th.green) } else { (th.mauve, th.surface2) }; Span::styled( format!("[{label}]"), Style::default().fg(fg).bg(bg).add_modifier(Modifier::BOLD), ) } } /// What: Render optional filter if available. /// /// Inputs: /// - `has_repo`: Whether repo is available /// - `label`: Pre-computed filter label /// - `is_active`: Whether filter is active /// - `filt`: Filter rendering closure /// /// Output: Option containing filter span, or None if not available. /// /// Details: Returns Some(span) if repo is available, None otherwise. fn render_optional_filter( has_repo: bool, label: &str, is_active: bool, filt: &dyn Fn(&str, bool) -> Span<'static>, ) -> Option<Span<'static>> { if has_repo { Some(filt(label, is_active)) } else { None } } /// What: Render title prefix (title text with count). /// /// Inputs: /// - `i18n`: Pre-computed i18n strings /// - `results_len`: Number of results /// /// Output: Vector of spans for the title prefix. /// /// Details: Renders the "Results (N)" text with styling. pub(super) fn render_title_prefix( i18n: &TitleI18nStrings, results_len: usize, ) -> Vec<Span<'static>> { let th = theme(); let results_title_text = format!("{} ({})", i18n.results_title, results_len); vec![Span::styled( results_title_text, Style::default().fg(th.overlay1), )] } /// What: Render sort button. /// /// Inputs: /// - `i18n`: Pre-computed i18n strings /// - `is_open`: Whether sort menu is open /// /// Output: Vector of spans for the sort button. /// /// Details: Renders the sort button with appropriate styling based on menu state. pub(super) fn render_sort_button(i18n: &TitleI18nStrings, is_open: bool) -> Vec<Span<'static>> { let sort_button_label = format!("{} v", i18n.sort_button); let btn_style = get_button_style(is_open); vec![Span::styled(sort_button_label, btn_style)] } /// What: Render core filter buttons (AUR, core, extra, multilib). /// /// Inputs: /// - `i18n`: Pre-computed i18n strings /// - `filter_states`: Filter toggle states /// /// Output: Vector of spans for core filters. /// /// Details: Renders the four core filter buttons with spacing. pub(super) fn render_core_filters( i18n: &TitleI18nStrings, filter_states: &FilterStates, ) -> Vec<Span<'static>> { let filt = create_filter_renderer(); vec![ filt(&i18n.filter_aur, filter_states.show_aur), Span::raw(" "), filt(&i18n.filter_core, filter_states.show_core), Span::raw(" "), filt(&i18n.filter_extra, filter_states.show_extra), Span::raw(" "), filt(&i18n.filter_multilib, filter_states.show_multilib), ] } /// What: Render optional `EOS` and `CachyOS` filters. /// /// Inputs: /// - `i18n`: Pre-computed i18n strings /// - `optional_repos`: Optional repository availability flags /// - `filter_states`: Filter toggle states /// /// Output: Vector of spans for optional filters. /// /// Details: Renders `EOS` and `CachyOS` filters if available. pub(super) fn render_optional_eos_cachyos_filters( i18n: &TitleI18nStrings, optional_repos: &OptionalRepos, filter_states: &FilterStates, ) -> Vec<Span<'static>> { let filt = create_filter_renderer(); let mut spans = Vec::new(); if let Some(span) = render_optional_filter( optional_repos.has_eos, &i18n.filter_eos, filter_states.show_eos, &filt, ) { spans.push(Span::raw(" ")); spans.push(span); } if let Some(span) = render_optional_filter( optional_repos.has_cachyos, &i18n.filter_cachyos, filter_states.show_cachyos, &filt, ) { spans.push(Span::raw(" ")); spans.push(span); } spans } /// What: Render Artix filter with optional dropdown indicator. /// /// Inputs: /// - `i18n`: Pre-computed i18n strings /// - `optional_repos`: Optional repository availability flags /// - `filter_states`: Filter toggle states /// - `show_artix_specific_repos`: Whether Artix-specific repos are shown /// /// Output: Vector of spans for Artix filter. /// /// Details: Renders Artix filter with dropdown indicator if specific repos are hidden. pub(super) fn render_artix_filter( i18n: &TitleI18nStrings, optional_repos: &OptionalRepos, filter_states: &FilterStates, show_artix_specific_repos: bool, ) -> Vec<Span<'static>> { let mut spans = Vec::new(); if optional_repos.has_artix { spans.push(Span::raw(" ")); let artix_text = if show_artix_specific_repos { format!("[{}]", i18n.filter_artix) } else { format!("[{}] v", i18n.filter_artix) }; let th = theme(); let (fg, bg) = if filter_states.show_artix { (th.crust, th.green) } else { (th.mauve, th.surface2) }; spans.push(Span::styled( artix_text, Style::default().fg(fg).bg(bg).add_modifier(Modifier::BOLD), )); } spans } /// What: Render Artix-specific repository filters. /// /// Inputs: /// - `i18n`: Pre-computed i18n strings /// - `optional_repos`: Optional repository availability flags /// - `filter_states`: Filter toggle states /// /// Output: Vector of spans for Artix-specific filters. /// /// Details: Renders all Artix-specific repo filters if available. pub(super) fn render_artix_specific_filters( i18n: &TitleI18nStrings, optional_repos: &OptionalRepos, filter_states: &FilterStates, ) -> Vec<Span<'static>> { let filt = create_filter_renderer(); let mut spans = Vec::new(); let artix_filters = [ ( optional_repos.has_artix_omniverse, &i18n.filter_artix_omniverse, filter_states.show_artix_omniverse, ), ( optional_repos.has_artix_universe, &i18n.filter_artix_universe, filter_states.show_artix_universe, ), ( optional_repos.has_artix_lib32, &i18n.filter_artix_lib32, filter_states.show_artix_lib32, ), ( optional_repos.has_artix_galaxy, &i18n.filter_artix_galaxy, filter_states.show_artix_galaxy, ), ( optional_repos.has_artix_world, &i18n.filter_artix_world, filter_states.show_artix_world, ), ( optional_repos.has_artix_system, &i18n.filter_artix_system, filter_states.show_artix_system, ), ]; for (has_repo, label, is_active) in artix_filters { if let Some(span) = render_optional_filter(has_repo, label, is_active, &filt) { spans.push(Span::raw(" ")); spans.push(span); } } spans } /// What: Render Manjaro filter. /// /// Inputs: /// - `i18n`: Pre-computed i18n strings /// - `optional_repos`: Optional repository availability flags /// - `filter_states`: Filter toggle states /// /// Output: Vector of spans for Manjaro filter. /// /// Details: Renders Manjaro filter if available. pub(super) fn render_manjaro_filter( i18n: &TitleI18nStrings, optional_repos: &OptionalRepos, filter_states: &FilterStates, ) -> Vec<Span<'static>> { let filt = create_filter_renderer(); let mut spans = Vec::new(); if let Some(span) = render_optional_filter( optional_repos.has_manjaro, &i18n.filter_manjaro, filter_states.show_manjaro, &filt, ) { spans.push(Span::raw(" ")); spans.push(span); } spans } /// What: Render right-aligned buttons (Config/Lists, Panels, Options) or collapsed Menu button. /// /// Inputs: /// - `i18n`: Pre-computed i18n strings /// - `menu_states`: Menu open/closed states /// - `pad`: Padding space before buttons (for all three buttons case) /// - `use_collapsed_menu`: Whether to render collapsed menu button instead of individual buttons /// - `menu_button_label`: Label for the collapsed menu button /// - `menu_pad`: Padding space for collapsed menu button (calculated separately) /// /// Output: Vector of spans for right-aligned buttons. /// /// Details: Renders either all three buttons or a single collapsed Menu button based on available space. pub(super) fn render_right_aligned_buttons( i18n: &TitleI18nStrings, menu_states: &MenuStates, pad: u16, use_collapsed_menu: bool, menu_button_label: &str, menu_pad: u16, ) -> Vec<Span<'static>> { let mut spans = Vec::new(); if use_collapsed_menu { // Render collapsed menu button if we have space for it if menu_pad >= 1 { spans.push(Span::raw(" ".repeat(menu_pad as usize))); let menu_btn_style = get_button_style(menu_states.collapsed_menu_open); spans.extend(render_button_with_underline( menu_button_label, menu_btn_style, )); } } else if pad >= 1 { // Render all three buttons if we have space spans.push(Span::raw(" ".repeat(pad as usize))); let config_button_label = format!("{} v", i18n.config_button); let cfg_btn_style = get_button_style(menu_states.config_menu_open); spans.extend(render_button_with_underline( &config_button_label, cfg_btn_style, )); spans.push(Span::raw(" ")); let panels_button_label = format!("{} v", i18n.panels_button); let pan_btn_style = get_button_style(menu_states.panels_menu_open); spans.extend(render_button_with_underline( &panels_button_label, pan_btn_style, )); spans.push(Span::raw(" ")); let options_button_label = format!("{} v", i18n.options_button); let opt_btn_style = get_button_style(menu_states.options_menu_open); spans.extend(render_button_with_underline( &options_button_label, opt_btn_style, )); } spans }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/results/title/types.rs
src/ui/results/title/types.rs
/// What: Pre-computed i18n strings for title rendering. /// /// Inputs: Individual i18n strings from `AppState`. /// /// Output: Struct containing all i18n strings needed for title rendering. /// /// Details: Reduces data flow complexity by pre-computing all i18n strings upfront. pub(super) struct TitleI18nStrings { /// Translated "Results" title text. pub(super) results_title: String, /// Translated sort button text. pub(super) sort_button: String, /// Translated options button text. pub(super) options_button: String, /// Translated panels button text. pub(super) panels_button: String, /// Translated config button text. pub(super) config_button: String, /// Translated menu button text. pub(super) menu_button: String, /// Translated AUR filter text. pub(super) filter_aur: String, /// Translated core repository filter text. pub(super) filter_core: String, /// Translated extra repository filter text. pub(super) filter_extra: String, /// Translated multilib repository filter text. pub(super) filter_multilib: String, /// Translated `EndeavourOS` repository filter text. pub(super) filter_eos: String, /// Translated `CachyOS` repository filter text. pub(super) filter_cachyos: String, /// Translated Artix repository filter text. pub(super) filter_artix: String, /// Translated Artix Omniverse repository filter text. pub(super) filter_artix_omniverse: String, /// Translated Artix Universe repository filter text. pub(super) filter_artix_universe: String, /// Translated Artix Lib32 repository filter text. pub(super) filter_artix_lib32: String, /// Translated Artix Galaxy repository filter text. pub(super) filter_artix_galaxy: String, /// Translated Artix World repository filter text. pub(super) filter_artix_world: String, /// Translated Artix System repository filter text. pub(super) filter_artix_system: String, /// Translated Manjaro repository filter text. pub(super) filter_manjaro: String, } /// What: Represents pre-formatted label strings for optional repos. /// /// Inputs: Individual label strings. /// /// Output: Struct containing all label strings. /// /// Details: Used to pass multiple label strings as a single parameter. pub(super) struct OptionalReposLabels { /// `EndeavourOS` repository label. pub(super) eos: String, /// `CachyOS` repository label. pub(super) cachyos: String, /// Artix repository label. pub(super) artix: String, /// Artix Omniverse repository label. pub(super) artix_omniverse: String, /// Artix Universe repository label. pub(super) artix_universe: String, /// Artix Lib32 repository label. pub(super) artix_lib32: String, /// Artix Galaxy repository label. pub(super) artix_galaxy: String, /// Artix World repository label. pub(super) artix_world: String, /// Artix System repository label. pub(super) artix_system: String, /// Manjaro repository label. pub(super) manjaro: String, } /// What: Represents labels for core filters. /// /// Inputs: Individual label strings. /// /// Output: Struct containing core filter labels. /// /// Details: Used to pass core filter labels as a single parameter. pub(super) struct CoreFilterLabels { /// AUR filter label. pub(super) aur: String, /// Core repository filter label. pub(super) core: String, /// Extra repository filter label. pub(super) extra: String, /// Multilib repository filter label. pub(super) multilib: String, } /// What: Shared layout calculation information for title bar. /// /// Inputs: Calculated values from title text, button labels, and area dimensions. /// /// Output: Struct containing all layout calculation results. /// /// Details: Used to share layout calculations between rendering and rect recording functions. pub(super) struct TitleLayoutInfo { /// Title text with result count. pub(super) results_title_text: String, /// Sort button label. pub(super) sort_button_label: String, /// Options button label. pub(super) options_button_label: String, /// Panels button label. pub(super) panels_button_label: String, /// Config/Lists button label. pub(super) config_button_label: String, /// Menu button label. pub(super) menu_button_label: String, /// Core filter labels (AUR/core/extra/multilib). pub(super) core_labels: CoreFilterLabels, /// Optional repository filter labels. pub(super) optional_labels: OptionalReposLabels, /// Available inner width for rendering. pub(super) inner_width: u16, /// Whether to show Artix-specific repositories. pub(super) show_artix_specific_repos: bool, /// Padding between elements. pub(super) pad: u16, /// Whether collapsed menu is used. pub(super) use_collapsed_menu: bool, /// Padding reserved for menu button area. pub(super) menu_pad: u16, } /// What: Layout state tracker for recording rectangles. /// /// Inputs: Initial x position and y position. /// /// Output: Struct that tracks current x cursor position and y position. /// /// Details: Encapsulates layout state to avoid manual `x_cursor` tracking. pub(super) struct LayoutState { /// Current x cursor position. pub(super) x: u16, /// Y position for all elements. pub(super) y: u16, } impl LayoutState { /// What: Create a new layout state. /// /// Inputs: /// - `x`: Initial x position /// - `y`: Y position (constant) /// /// Output: New `LayoutState` instance. /// /// Details: Initializes layout state with starting position. pub(super) const fn new(x: u16, y: u16) -> Self { Self { x, y } } /// What: Advance x cursor by label width plus spacing. /// /// Inputs: /// - `label_width`: Width of the label in characters /// - `spacing`: Number of spaces after the label (default 1) /// /// Output: Updated x position. /// /// Details: Moves x cursor forward by label width plus spacing. #[allow(clippy::missing_const_for_fn)] pub(super) fn advance(&mut self, label_width: u16, spacing: u16) -> u16 { self.x = self.x.saturating_add(label_width).saturating_add(spacing); self.x } /// What: Record a rectangle at current position. /// /// Inputs: /// - `label`: Label text to measure /// /// Output: Rectangle tuple (x, y, width, height). /// /// Details: Creates rectangle at current x position with label width. /// Uses Unicode display width, not byte length, to handle wide characters. pub(super) fn record_rect(&self, label: &str) -> (u16, u16, u16, u16) { use unicode_width::UnicodeWidthStr; ( self.x, self.y, u16::try_from(label.width()).unwrap_or(u16::MAX), 1, ) } } /// What: Context for adjusting Artix visibility calculations. /// /// Inputs: Grouped parameters for visibility calculations. /// /// Output: Struct containing calculation parameters. /// /// Details: Reduces function argument count by grouping related parameters. pub(super) struct ArtixVisibilityContext { /// Left space consumed so far. pub(super) consumed_left: u16, /// Final left space consumed. pub(super) final_consumed_left: u16, /// Inner width available. pub(super) inner_width: u16, /// Menu width. pub(super) menu_w: u16, /// Base consumed space. pub(super) base_consumed: u16, }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/results/title/mod.rs
src/ui/results/title/mod.rs
use ratatui::{prelude::Rect, text::Span}; use crate::state::AppState; use super::{FilterStates, MenuStates, OptionalRepos, RenderContext}; /// What: Internationalization (i18n) string building for title rendering. /// /// Details: Provides functions to build pre-computed i18n strings for title bar elements. /// What: Internationalization (i18n) string building for title rendering. /// /// Details: Provides functions to build pre-computed i18n strings for title bar elements. mod i18n; /// What: Layout calculation for title bar elements. /// /// Details: Calculates positions and dimensions for title bar components. mod layout; /// What: Rectangle recording for title bar clickable areas. /// /// Details: Records clickable rectangles for title bar controls. mod rects; /// What: Rendering functions for title bar elements. /// /// Details: Provides focused rendering functions for individual title bar components. mod rendering; /// What: Type definitions for title rendering. /// /// Details: Defines structs and types used for title bar rendering and layout. mod types; /// What: Width calculation utilities for title bar. /// /// Details: Provides functions to calculate widths for title bar elements. mod width; use i18n::build_title_i18n_strings; use layout::calculate_title_layout_info; use rects::record_title_rects; use rendering::{ render_artix_filter, render_artix_specific_filters, render_core_filters, render_manjaro_filter, render_optional_eos_cachyos_filters, render_right_aligned_buttons, render_sort_button, render_title_prefix, }; /// What: Build title spans with Sort button, filter toggles, and right-aligned buttons. /// /// This version takes a context struct to reduce data flow complexity. /// /// Inputs: /// - `app`: Application state for i18n /// - `ctx`: Render context containing all extracted values /// - `area`: Target rectangle for the results block /// /// Output: /// - Vector of `Span` widgets forming the title line /// /// Details: /// - Applies theme styling for active buttons, ensures right-side buttons align within the title, /// and toggles optional repo chips based on availability flags. /// - Uses pre-computed i18n strings and focused rendering functions to reduce complexity. pub fn build_title_spans_from_context( app: &AppState, ctx: &RenderContext, area: Rect, ) -> Vec<Span<'static>> { let inner_width = area.width.saturating_sub(2); // exclude borders build_title_spans_from_values( app, ctx.results_len, inner_width, &ctx.optional_repos, &ctx.menu_states, &ctx.filter_states, ) } /// What: Build title spans with Sort button, filter toggles, and right-aligned buttons. /// /// This version takes structs instead of individual values to reduce data flow complexity. /// /// Inputs: /// - `app`: Application state for i18n /// - `results_len`: Number of results /// - `inner_width`: Inner width of the area (excluding borders) /// - `optional_repos`: Optional repository availability flags /// - `menu_states`: Menu open/closed states /// - `filter_states`: Filter toggle states /// /// Output: /// - Vector of `Span` widgets forming the title line /// /// Details: /// - Applies theme styling for active buttons, ensures right-side buttons align within the title, /// and toggles optional repo chips based on availability flags. /// - Uses pre-computed i18n strings and focused rendering functions to reduce complexity. /// - Reuses layout calculation logic from `calculate_title_layout_info`. fn build_title_spans_from_values( app: &AppState, results_len: usize, inner_width: u16, optional_repos: &OptionalRepos, menu_states: &MenuStates, filter_states: &FilterStates, ) -> Vec<Span<'static>> { // Pre-compute all i18n strings to reduce data flow complexity let i18n = build_title_i18n_strings(app); // Reuse layout calculation logic let layout_info = calculate_title_layout_info(&i18n, results_len, inner_width, optional_repos); // Build title spans using focused rendering functions let mut title_spans = render_title_prefix(&i18n, results_len); title_spans.push(Span::raw(" ")); title_spans.extend(render_sort_button(&i18n, menu_states.sort_menu_open)); title_spans.push(Span::raw(" ")); title_spans.extend(render_core_filters(&i18n, filter_states)); title_spans.extend(render_optional_eos_cachyos_filters( &i18n, optional_repos, filter_states, )); title_spans.extend(render_artix_filter( &i18n, optional_repos, filter_states, layout_info.show_artix_specific_repos, )); if layout_info.show_artix_specific_repos { title_spans.extend(render_artix_specific_filters( &i18n, optional_repos, filter_states, )); } title_spans.extend(render_manjaro_filter(&i18n, optional_repos, filter_states)); title_spans.extend(render_right_aligned_buttons( &i18n, menu_states, layout_info.pad, layout_info.use_collapsed_menu, &layout_info.menu_button_label, layout_info.menu_pad, )); title_spans } /// What: Record clickable rectangles for title bar controls. /// /// This version takes a context struct to reduce data flow complexity. /// /// Inputs: /// - `app`: Mutable application state (rects will be updated) /// - `ctx`: Render context containing all extracted values /// - `area`: Target rectangle for the results block /// /// Output: /// - Updates `app` with rectangles for filters, buttons, and optional repo chips. /// /// Details: /// - Mirrors title layout calculations to align rects with rendered elements and clears entries when /// controls cannot fit in the available width. /// - Extracts values from context and delegates to `record_title_rects`. pub fn record_title_rects_from_context(app: &mut AppState, ctx: &RenderContext, area: Rect) { record_title_rects(app, area, &ctx.optional_repos); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/results/title/layout.rs
src/ui/results/title/layout.rs
use unicode_width::UnicodeWidthStr; use super::super::OptionalRepos; use super::types::{ ArtixVisibilityContext, CoreFilterLabels, OptionalReposLabels, TitleI18nStrings, TitleLayoutInfo, }; use super::width::{ calculate_base_consumed_space, calculate_consumed_without_specific, calculate_optional_repos_width, create_repos_without_specific, }; /// What: Determine if Artix-specific repos should be shown initially. /// /// Inputs: /// - `base_consumed`: Base consumed space /// - `consumed_left`: Consumed space with all filters /// - `inner_width`: Available width /// - `right_w`: Width needed for right-aligned buttons /// - `optional_repos`: Optional repository flags /// - `optional_labels`: Labels for optional repos /// /// Output: Tuple of (`show_artix_specific_repos`, `final_consumed_left`, `pad`). /// /// Details: Determines initial visibility of Artix-specific repos based on available space. fn determine_initial_artix_visibility( base_consumed: u16, consumed_left: u16, inner_width: u16, right_w: u16, optional_repos: &OptionalRepos, optional_labels: &OptionalReposLabels, ) -> (bool, u16, u16) { let pad = inner_width.saturating_sub(consumed_left.saturating_add(right_w)); if pad >= 1 { return (true, consumed_left, pad); } // Not enough space, try without Artix-specific repos let repos_without_specific = create_repos_without_specific(optional_repos); let consumed_without_specific = calculate_consumed_without_specific( base_consumed, &repos_without_specific, optional_labels, optional_repos.has_artix, ); let new_pad = inner_width.saturating_sub(consumed_without_specific.saturating_add(right_w)); if new_pad >= 1 { (false, consumed_without_specific, new_pad) } else { (true, consumed_left, pad) } } /// What: Adjust Artix visibility for collapsed menu scenario. /// /// Inputs: /// - `show_artix_specific_repos`: Current visibility state /// - `ctx`: Context containing calculation parameters /// - `optional_repos`: Optional repository flags /// - `optional_labels`: Labels for optional repos /// /// Output: Tuple of (`show_artix_specific_repos`, `final_consumed_left`). /// /// Details: Adjusts Artix visibility when collapsed menu might be used. fn adjust_artix_visibility_for_collapsed_menu( show_artix_specific_repos: bool, ctx: &ArtixVisibilityContext, optional_repos: &OptionalRepos, optional_labels: &OptionalReposLabels, ) -> (bool, u16) { if !show_artix_specific_repos { return (false, ctx.final_consumed_left); } let space_with_filters = ctx .consumed_left .saturating_add(ctx.menu_w) .saturating_add(1); let repos_without_specific = create_repos_without_specific(optional_repos); let consumed_without_specific = calculate_consumed_without_specific( ctx.base_consumed, &repos_without_specific, optional_labels, optional_repos.has_artix, ); let space_without_filters = consumed_without_specific .saturating_add(ctx.menu_w) .saturating_add(1); if ctx.inner_width < space_with_filters && ctx.inner_width >= space_without_filters { (false, consumed_without_specific) } else { (show_artix_specific_repos, ctx.final_consumed_left) } } /// What: Finalize Artix visibility when menu can't fit. /// /// Inputs: /// - `show_artix_specific_repos`: Current visibility state /// - `consumed_left`: Consumed space with all filters /// - `inner_width`: Available width /// - `menu_w`: Menu button width /// - `base_consumed`: Base consumed space /// - `optional_repos`: Optional repository flags /// - `optional_labels`: Labels for optional repos /// /// Output: Tuple of (`show_artix_specific_repos`, `final_consumed_left`). /// /// Details: Hides Artix-specific repos if there's not enough space even without menu. fn finalize_artix_visibility_when_menu_cant_fit( show_artix_specific_repos: bool, consumed_left: u16, inner_width: u16, menu_w: u16, base_consumed: u16, optional_repos: &OptionalRepos, optional_labels: &OptionalReposLabels, ) -> (bool, u16) { if !show_artix_specific_repos { return (false, consumed_left); } let space_needed_with_filters = consumed_left.saturating_add(menu_w).saturating_add(1); if inner_width >= space_needed_with_filters { return (true, consumed_left); } // Not enough space, hide Artix-specific repos let repos_without_specific = create_repos_without_specific(optional_repos); let consumed_without_specific = calculate_consumed_without_specific( base_consumed, &repos_without_specific, optional_labels, optional_repos.has_artix, ); (false, consumed_without_specific) } /// What: Calculate shared layout information for title bar. /// /// Inputs: /// - `i18n`: Pre-computed i18n strings /// - `results_len`: Number of results /// - `inner_width`: Inner width of the area (excluding borders) /// - `optional_repos`: Optional repository availability flags /// /// Output: `TitleLayoutInfo` containing all calculated layout values. /// /// Details: Performs all layout calculations shared between rendering and rect recording. /// Uses helper functions to reduce data flow complexity. pub(super) fn calculate_title_layout_info( i18n: &TitleI18nStrings, results_len: usize, inner_width: u16, optional_repos: &OptionalRepos, ) -> TitleLayoutInfo { let results_title_text = format!("{} ({})", i18n.results_title, results_len); let sort_button_label = format!("{} v", i18n.sort_button); let options_button_label = format!("{} v", i18n.options_button); let panels_button_label = format!("{} v", i18n.panels_button); let config_button_label = format!("{} v", i18n.config_button); let menu_button_label = format!("{} v", i18n.menu_button); let core_labels = CoreFilterLabels { aur: format!("[{}]", i18n.filter_aur), core: format!("[{}]", i18n.filter_core), extra: format!("[{}]", i18n.filter_extra), multilib: format!("[{}]", i18n.filter_multilib), }; let optional_labels = OptionalReposLabels { eos: format!("[{}]", i18n.filter_eos), cachyos: format!("[{}]", i18n.filter_cachyos), artix: format!("[{}]", i18n.filter_artix), artix_omniverse: format!("[{}]", i18n.filter_artix_omniverse), artix_universe: format!("[{}]", i18n.filter_artix_universe), artix_lib32: format!("[{}]", i18n.filter_artix_lib32), artix_galaxy: format!("[{}]", i18n.filter_artix_galaxy), artix_world: format!("[{}]", i18n.filter_artix_world), artix_system: format!("[{}]", i18n.filter_artix_system), manjaro: format!("[{}]", i18n.filter_manjaro), }; // Calculate consumed space with all filters first let base_consumed = calculate_base_consumed_space(&results_title_text, &sort_button_label, &core_labels); let optional_consumed = calculate_optional_repos_width(optional_repos, &optional_labels); let consumed_left = base_consumed.saturating_add(optional_consumed); // Use Unicode display width, not byte length, to handle wide characters let options_w = u16::try_from(options_button_label.width()).unwrap_or(u16::MAX); let panels_w = u16::try_from(panels_button_label.width()).unwrap_or(u16::MAX); let config_w = u16::try_from(config_button_label.width()).unwrap_or(u16::MAX); let menu_w = u16::try_from(menu_button_label.width()).unwrap_or(u16::MAX); let right_w = config_w .saturating_add(1) .saturating_add(panels_w) .saturating_add(1) .saturating_add(options_w); // Determine initial Artix visibility and consumed space let (mut show_artix_specific_repos, mut final_consumed_left, pad) = determine_initial_artix_visibility( base_consumed, consumed_left, inner_width, right_w, optional_repos, &optional_labels, ); // Adjust Artix visibility for collapsed menu scenario if pad < 1 && show_artix_specific_repos { let ctx = ArtixVisibilityContext { consumed_left, final_consumed_left, inner_width, menu_w, base_consumed, }; let (new_show, new_consumed) = adjust_artix_visibility_for_collapsed_menu( show_artix_specific_repos, &ctx, optional_repos, &optional_labels, ); show_artix_specific_repos = new_show; final_consumed_left = new_consumed; } // Determine if we should use collapsed menu instead of individual buttons // Decision logic: // - pad is the remaining space after accounting for final_consumed_left + right_w // - If pad >= 1: we have space for all three buttons (use_collapsed_menu = false) // - If pad < 1: check if we have space for collapsed menu // Calculate space needed for collapsed menu: final_consumed_left + menu_w // If inner_width >= (final_consumed_left + menu_w + 1): use collapsed menu // Otherwise: show nothing let use_collapsed_menu = if pad < 1 { let space_needed_for_menu = final_consumed_left.saturating_add(menu_w).saturating_add(1); inner_width >= space_needed_for_menu } else { false }; // If collapsed menu can't fit, ensure Artix filters stay hidden when space is very tight // This prevents filters from expanding when the menu dropdown vanishes if !use_collapsed_menu && pad < 1 { let (new_show, new_consumed) = finalize_artix_visibility_when_menu_cant_fit( show_artix_specific_repos, consumed_left, inner_width, menu_w, base_consumed, optional_repos, &optional_labels, ); show_artix_specific_repos = new_show; final_consumed_left = new_consumed; } // Calculate padding for collapsed menu (space after accounting for consumed_left + menu_w) let menu_pad = if use_collapsed_menu { inner_width.saturating_sub(final_consumed_left.saturating_add(menu_w)) } else { pad }; TitleLayoutInfo { results_title_text, sort_button_label, options_button_label, panels_button_label, config_button_label, menu_button_label, core_labels, optional_labels, inner_width, show_artix_specific_repos, pad, use_collapsed_menu, menu_pad, } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/results/title/width.rs
src/ui/results/title/width.rs
use unicode_width::UnicodeWidthStr; use super::super::OptionalRepos; use super::types::{CoreFilterLabels, OptionalReposLabels}; /// What: Calculate consumed horizontal space for optional repos. /// /// Inputs: /// - `repos`: Optional repository flags /// - `labels`: Pre-formatted label strings for each repo /// /// Output: Total consumed width in characters. /// /// Details: Sums up the width of all available optional repos plus spacing. /// Uses Unicode display width, not byte length, to handle wide characters. pub(super) fn calculate_optional_repos_width( repos: &OptionalRepos, labels: &OptionalReposLabels, ) -> u16 { let mut width = 0u16; if repos.has_eos { width = width.saturating_add(1 + u16::try_from(labels.eos.width()).unwrap_or(u16::MAX)); } if repos.has_cachyos { width = width.saturating_add(1 + u16::try_from(labels.cachyos.width()).unwrap_or(u16::MAX)); } if repos.has_artix { width = width.saturating_add(1 + u16::try_from(labels.artix.width()).unwrap_or(u16::MAX)); } if repos.has_artix_omniverse { width = width .saturating_add(1 + u16::try_from(labels.artix_omniverse.width()).unwrap_or(u16::MAX)); } if repos.has_artix_universe { width = width .saturating_add(1 + u16::try_from(labels.artix_universe.width()).unwrap_or(u16::MAX)); } if repos.has_artix_lib32 { width = width.saturating_add(1 + u16::try_from(labels.artix_lib32.width()).unwrap_or(u16::MAX)); } if repos.has_artix_galaxy { width = width .saturating_add(1 + u16::try_from(labels.artix_galaxy.width()).unwrap_or(u16::MAX)); } if repos.has_artix_world { width = width.saturating_add(1 + u16::try_from(labels.artix_world.width()).unwrap_or(u16::MAX)); } if repos.has_artix_system { width = width .saturating_add(1 + u16::try_from(labels.artix_system.width()).unwrap_or(u16::MAX)); } if repos.has_manjaro { width = width.saturating_add(1 + u16::try_from(labels.manjaro.width()).unwrap_or(u16::MAX)); } width } /// What: Calculate base consumed space (title, sort button, core filters). /// /// Inputs: /// - `results_title_text`: Title text with count /// - `sort_button_label`: Sort button label /// - `core_labels`: Labels for core filters (AUR, core, extra, multilib) /// /// Output: Base consumed width in display columns. /// /// Details: Calculates space for fixed elements that are always present. /// Uses Unicode display width, not byte length, to handle wide characters. pub(super) fn calculate_base_consumed_space( results_title_text: &str, sort_button_label: &str, core_labels: &CoreFilterLabels, ) -> u16 { u16::try_from( results_title_text.width() + 2 // spaces before Sort + sort_button_label.width() + 2 // spaces after Sort + core_labels.aur.width() + 1 // space + core_labels.core.width() + 1 // space + core_labels.extra.width() + 1 // space + core_labels.multilib.width(), ) .unwrap_or(u16::MAX) } /// What: Create `OptionalRepos` without Artix-specific repos. /// /// Inputs: /// - `optional_repos`: Original optional repos /// /// Output: `OptionalRepos` with all Artix-specific repos set to false. /// /// Details: Helper to create a copy without Artix-specific repos for space calculations. #[allow(clippy::missing_const_for_fn)] // Cannot be const due to reference parameter pub(super) fn create_repos_without_specific(optional_repos: &OptionalRepos) -> OptionalRepos { OptionalRepos { has_eos: optional_repos.has_eos, has_cachyos: optional_repos.has_cachyos, has_artix: optional_repos.has_artix, has_artix_omniverse: false, has_artix_universe: false, has_artix_lib32: false, has_artix_galaxy: false, has_artix_world: false, has_artix_system: false, has_manjaro: optional_repos.has_manjaro, } } /// What: Calculate consumed space without Artix-specific repos. /// /// Inputs: /// - `base_consumed`: Base consumed space /// - `repos_without_specific`: Optional repos without Artix-specific repos /// - `optional_labels`: Labels for optional repos /// - `has_artix`: Whether Artix filter is present (for dropdown indicator) /// /// Output: Total consumed space without Artix-specific repos. /// /// Details: Calculates consumed space and adds 3 chars for dropdown indicator if Artix is present. pub(super) fn calculate_consumed_without_specific( base_consumed: u16, repos_without_specific: &OptionalRepos, optional_labels: &OptionalReposLabels, has_artix: bool, ) -> u16 { let mut consumed = base_consumed.saturating_add(calculate_optional_repos_width( repos_without_specific, optional_labels, )); if has_artix { consumed = consumed.saturating_add(3); // " v" dropdown indicator } consumed }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/details/comments.rs
src/ui/details/comments.rs
//! AUR package comments viewer rendering. use ratatui::{ Frame, prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, widgets::{Block, BorderType, Borders, List, ListItem}, }; use unicode_width::UnicodeWidthStr; use crate::i18n; use crate::state::AppState; use crate::theme::theme; /// What: Detect URLs in text and return vector of (`start_pos`, `end_pos`, `url_string`). /// /// Inputs: /// - `text`: Text to search for URLs. /// /// Output: /// - Vector of tuples: (`start_byte_pos`, `end_byte_pos`, `url_string`). /// /// Details: /// - Detects http://, https://, and www. URLs. /// - Returns positions in byte offsets for string slicing. fn detect_urls(text: &str) -> Vec<(usize, usize, String)> { let mut urls = Vec::new(); let text_bytes = text.as_bytes(); let mut i = 0; while i < text_bytes.len() { // Look for http:// or https:// // Look for http:// or https:// let is_http = i + 7 < text_bytes.len() && &text_bytes[i..i + 7] == b"http://"; let is_https = i + 8 < text_bytes.len() && &text_bytes[i..i + 8] == b"https://"; if is_http || is_https { let offset = if is_https { 8 } else { 7 }; if let Some(end) = find_url_end(text, i + offset) { let url = text[i..end].to_string(); urls.push((i, end, url)); i = end; continue; } } // Look for www. (must be at word boundary) if i + 4 < text_bytes.len() && (i == 0 || text_bytes[i - 1].is_ascii_whitespace()) && &text_bytes[i..i + 4] == b"www." && let Some(end) = find_url_end(text, i + 4) { let url = format!("https://{}", &text[i..end]); urls.push((i, end, url)); i = end; continue; } i += 1; } urls } /// What: Find the end position of a URL in text. /// /// Inputs: /// - `text`: Text containing the URL. /// - `start`: Starting byte position of the URL. /// /// Output: /// - `Some(usize)` with end byte position, or `None` if URL is invalid. /// /// Details: /// - URL ends at whitespace, closing parenthesis, or end of string. /// - Removes trailing punctuation that's not part of the URL. fn find_url_end(text: &str, start: usize) -> Option<usize> { let mut end = start; let text_bytes = text.as_bytes(); // Find the end of the URL (stop at whitespace or closing paren) while end < text_bytes.len() { let byte = text_bytes[end]; if byte.is_ascii_whitespace() || byte == b')' || byte == b']' || byte == b'>' { break; } end += 1; } // Remove trailing punctuation that's likely not part of the URL while end > start { let last_char = text_bytes[end - 1]; if matches!(last_char, b'.' | b',' | b';' | b':' | b'!' | b'?') { end -= 1; } else { break; } } if end > start { Some(end) } else { None } } /// What: Detect markdown-style links in text: [text](url) /// /// Inputs: /// - `text`: Text to search for markdown links /// /// Output: /// - Vector of (`start_pos`, `end_pos`, `url_string`) tuples fn detect_markdown_links(text: &str) -> Vec<(usize, usize, String)> { let mut links = Vec::new(); let text_bytes = text.as_bytes(); let mut i = 0; while i < text_bytes.len() { // Look for [text](url) pattern if text_bytes[i] == b'[' && let Some(bracket_end) = text[i + 1..].find(']') { let bracket_end = i + 1 + bracket_end; if bracket_end + 1 < text_bytes.len() && text_bytes[bracket_end + 1] == b'(' && let Some(paren_end) = text[bracket_end + 2..].find(')') { let paren_end = bracket_end + 2 + paren_end; let url = text[bracket_end + 2..paren_end].to_string(); links.push((i, paren_end + 1, url)); i = paren_end + 1; continue; } } i += 1; } links } /// What: Render content with markdown-like formatting (bold, italic, code, links). /// /// Handles URL detection, markdown formatting, and word wrapping. fn render_content_with_formatting<'a>( content: &'a str, urls: &[(usize, usize, String)], content_width: usize, th: &'a crate::theme::Theme, start_x: u16, start_y: u16, url_positions: &mut Vec<(u16, u16, u16, String)>, ) -> Vec<Line<'a>> { // Parse markdown-like formatting and create styled segments let segments = parse_markdown_segments(content, urls, th); // Build lines with word wrapping let mut lines = Vec::new(); let mut current_line_spans: Vec<Span> = Vec::new(); let mut current_line_width = 0; let mut current_y = start_y; for (text, style, is_url, url_string) in segments { let words: Vec<&str> = text.split_whitespace().collect(); for word in words { let word_width = word.width(); let separator_width = usize::from(current_line_width > 0); let test_width = current_line_width + separator_width + word_width; if test_width > content_width && !current_line_spans.is_empty() { // Wrap to new line lines.push(Line::from(current_line_spans.clone())); current_line_spans.clear(); current_line_width = 0; current_y += 1; } // Track URL position if this is a URL if is_url && let Some(ref url) = url_string { let url_x = start_x + u16::try_from(current_line_width).unwrap_or(u16::MAX) + u16::from(current_line_width > 0); let url_width = u16::try_from(word_width).unwrap_or(u16::MAX); url_positions.push((url_x, current_y, url_width, url.clone())); } if current_line_width > 0 { current_line_spans.push(Span::raw(" ")); current_line_width += 1; } current_line_spans.push(Span::styled(word.to_string(), style)); current_line_width += word_width; } } // Add final line if not empty if !current_line_spans.is_empty() { lines.push(Line::from(current_line_spans)); } lines } /// Parse markdown-like syntax and return segments with styling information. /// Returns: (text, style, `is_url`, `url_string_opt`) fn parse_markdown_segments<'a>( content: &'a str, urls: &[(usize, usize, String)], th: &'a crate::theme::Theme, ) -> Vec<(String, Style, bool, Option<String>)> { use ratatui::style::{Modifier, Style}; let mut segments = Vec::new(); let mut i = 0; let content_bytes = content.as_bytes(); while i < content_bytes.len() { // Check if we're at a URL position if let Some((start, end, url)) = urls.iter().find(|(s, _e, _)| *s == i) { segments.push(( content[*start..*end].to_string(), Style::default() .fg(th.mauve) .add_modifier(Modifier::UNDERLINED | Modifier::BOLD), true, Some(url.clone()), )); i = *end; continue; } // Check for code blocks: ```...``` if i + 3 <= content_bytes.len() && &content_bytes[i..i + 3] == b"```" && let Some(end) = content[i + 3..].find("```") { let end = i + 3 + end + 3; let code = content[i + 3..end - 3].trim(); segments.push(( code.to_string(), Style::default() .fg(th.sapphire) .add_modifier(Modifier::BOLD), false, None, )); i = end; continue; } // Check for inline code: `code` if content_bytes[i] == b'`' && let Some(end) = content[i + 1..].find('`') { let end = i + 1 + end + 1; let code = content[i + 1..end - 1].trim(); segments.push(( code.to_string(), Style::default() .fg(th.sapphire) .add_modifier(Modifier::BOLD), false, None, )); i = end; continue; } // Check for bold: **text** if i + 2 <= content_bytes.len() && &content_bytes[i..i + 2] == b"**" && let Some(end) = content[i + 2..].find("**") { let end = i + 2 + end + 2; let text = content[i + 2..end - 2].trim(); segments.push(( text.to_string(), Style::default().fg(th.text).add_modifier(Modifier::BOLD), false, None, )); i = end; continue; } // Check for italic: *text* (but not **text**) if content_bytes[i] == b'*' && (i + 1 >= content_bytes.len() || content_bytes[i + 1] != b'*') && let Some(end) = content[i + 1..].find('*') { let end = i + 1 + end + 1; let text = content[i + 1..end - 1].trim(); segments.push(( text.to_string(), Style::default().fg(th.text).add_modifier(Modifier::ITALIC), false, None, )); i = end; continue; } // Regular text - find next formatting marker let next_marker = find_next_marker(content, i); let end = next_marker.unwrap_or(content.len()); if end > i { let text = content[i..end].trim(); if !text.is_empty() { segments.push((text.to_string(), Style::default().fg(th.text), false, None)); } } i = end.max(i + 1); } segments } /// Find the next markdown formatting marker position. fn find_next_marker(content: &str, start: usize) -> Option<usize> { let markers = ["**", "`", "```", "["]; let mut min_pos = None; for marker in &markers { if let Some(pos) = content[start..].find(marker) { let pos = start + pos; min_pos = Some(min_pos.map_or(pos, |m: usize| m.min(pos))); } } min_pos } /// What: Build a loading state list item. /// /// Inputs: /// - `app`: Application state for i18n. /// /// Output: /// - List item with loading message. fn build_loading_item(app: &AppState) -> ListItem<'static> { ListItem::new(Line::from(i18n::t(app, "app.details.loading_comments"))) } /// What: Build an error state list item. /// /// Inputs: /// - `error`: Error message to display. /// - `th`: Theme for styling. /// /// Output: /// - List item with error message styled in red. fn build_error_item(error: &str, th: &crate::theme::Theme) -> ListItem<'static> { ListItem::new(Line::from(Span::styled( error.to_string(), Style::default().fg(th.red), ))) } /// What: Build an empty state list item. /// /// Inputs: /// - `app`: Application state for i18n. /// /// Output: /// - List item with empty state message. fn build_empty_item(app: &AppState) -> ListItem<'static> { ListItem::new(Line::from(i18n::t(app, "app.details.no_comments"))) } /// What: Build comment header line with author and date, tracking positions. /// /// Inputs: /// - `comment`: Comment to build header for. /// - `th`: Theme for styling. /// - `content_x`: X coordinate for position tracking. /// - `comment_y`: Y coordinate for position tracking. /// - `app`: Application state to track author/date positions. /// /// Output: /// - Tuple of (`header_line`, `pin_offset`) where `pin_offset` is the width of pin indicator. /// /// Details: /// - Tracks author position for click detection. /// - Tracks date position if date has URL. fn build_comment_header( comment: &crate::state::types::AurComment, th: &crate::theme::Theme, content_x: u16, comment_y: u16, app: &mut AppState, ) -> (Line<'static>, u16) { let author_style = Style::default() .fg(th.sapphire) .add_modifier(Modifier::BOLD | Modifier::UNDERLINED); let date_style = if comment.date_url.is_some() { Style::default() .fg(th.mauve) .add_modifier(Modifier::BOLD | Modifier::UNDERLINED) } else { Style::default().fg(th.overlay2) }; let mut header_spans = Vec::new(); let pin_offset = if comment.pinned { let pinned_style = Style::default().fg(th.yellow).add_modifier(Modifier::BOLD); let pin_text = "📌 "; header_spans.push(Span::styled(pin_text, pinned_style)); u16::try_from(pin_text.width()).unwrap_or(3) } else { 0 }; header_spans.push(Span::styled(comment.author.clone(), author_style)); header_spans.push(Span::raw(" • ")); header_spans.push(Span::styled(comment.date.clone(), date_style)); let author_x = content_x + pin_offset; let author_width = u16::try_from(comment.author.width()).unwrap_or(u16::MAX); app.comments_authors .push((author_x, comment_y, author_width, comment.author.clone())); if let Some(ref date_url) = comment.date_url { let separator_width = 3; let date_x = author_x .saturating_add(author_width) .saturating_add(separator_width); let date_width = u16::try_from(comment.date.width()).unwrap_or(u16::MAX); app.comments_dates .push((date_x, comment_y, date_width, date_url.clone())); } (Line::from(header_spans), pin_offset) } /// What: Build comment content lines with URL detection and formatting. /// /// Inputs: /// - `content`: Comment content text. /// - `content_width`: Maximum width for wrapping. /// - `th`: Theme for styling. /// - `content_x`: X coordinate for URL position tracking. /// - `content_y`: Y coordinate for URL position tracking. /// - `app`: Application state to track URL positions. /// /// Output: /// - Vector of content lines (owned). /// /// Details: /// - Detects URLs and markdown links. /// - Renders with markdown-like formatting. /// - Returns empty comment placeholder if content is empty. fn build_comment_content( content: &str, content_width: usize, th: &crate::theme::Theme, content_x: u16, content_y: u16, app: &mut AppState, ) -> Vec<Line<'static>> { if content.is_empty() { return vec![Line::from(Span::styled( "(empty comment)", Style::default().fg(th.overlay2), ))]; } let urls = detect_urls(content); let markdown_urls = detect_markdown_links(content); let all_urls: Vec<_> = urls.into_iter().chain(markdown_urls).collect(); // Convert to owned lines since we're creating owned data render_content_with_formatting( content, &all_urls, content_width, th, content_x, content_y, &mut app.comments_urls, ) .into_iter() .map(|line| { // Convert line to owned by converting all spans to owned Line::from( line.spans .iter() .map(|span| Span::styled(span.content.to_string(), span.style)) .collect::<Vec<_>>(), ) }) .collect() } /// What: Render a single comment as a list item. /// /// Inputs: /// - `comment`: Comment to render. /// - `th`: Theme for styling. /// - `content_x`: X coordinate for position tracking. /// - `content_width`: Maximum width for wrapping. /// - `current_y`: Current Y coordinate (updated by this function). /// - `app`: Application state to track positions. /// /// Output: /// - Tuple of (`list_item`, `new_y`) where `new_y` is the Y coordinate after rendering. /// /// Details: /// - Builds header, content, and separator lines. /// - Tracks author, date, and URL positions. fn render_single_comment( comment: &crate::state::types::AurComment, th: &crate::theme::Theme, content_x: u16, content_width: usize, current_y: u16, app: &mut AppState, ) -> (ListItem<'static>, u16) { let mut lines = Vec::new(); let mut y = current_y; let (header_line, _pin_offset) = build_comment_header(comment, th, content_x, y, app); lines.push(header_line); y += 1; let content_lines = build_comment_content(&comment.content, content_width, th, content_x, y, app); y += u16::try_from(content_lines.len()).unwrap_or(u16::MAX); lines.extend(content_lines); lines.push(Line::from(Span::styled( "─".repeat(content_width.min(20)), Style::default().fg(th.surface2), ))); y += 1; (ListItem::new(lines), y) } /// What: Build list items for all comments. /// /// Inputs: /// - `app`: Application state with comments and scroll offset. /// - `th`: Theme for styling. /// - `comments_area`: Rect assigned to the comments pane. /// /// Output: /// - Vector of list items for comments. /// /// Details: /// - Applies scroll offset by skipping items from top. /// - Renders each comment with header, content, and separator. fn build_comment_items( app: &mut AppState, th: &crate::theme::Theme, comments_area: Rect, ) -> Vec<ListItem<'static>> { let mut current_y = comments_area.y + 1; let content_x = comments_area.x + 1; let content_width = comments_area.width.saturating_sub(4) as usize; let scroll_offset = app.comments_scroll as usize; // Clone comments to avoid borrowing conflicts with mutable app access let comments_to_render: Vec<_> = app.comments[scroll_offset..].to_vec(); let mut items = Vec::new(); for comment in comments_to_render { let (item, new_y) = render_single_comment(&comment, th, content_x, content_width, current_y, app); current_y = new_y; items.push(item); } items } /// What: Render the comments viewer pane with scroll support. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state (comments, scroll, cached rects) /// - `comments_area`: Rect assigned to the comments pane /// /// Output: /// - Draws comments list and updates content rectangle for hit-testing. /// /// Details: /// - Applies scroll offset by skipping items from top /// - Shows loading state, error message, or comments list /// - Records content rect for mouse interactions (scrolling) pub fn render_comments(f: &mut Frame, app: &mut AppState, comments_area: Rect) { let th = theme(); app.comments_rect = Some(( comments_area.x + 1, comments_area.y + 1, comments_area.width.saturating_sub(2), comments_area.height.saturating_sub(2), )); app.comments_urls.clear(); app.comments_authors.clear(); app.comments_dates.clear(); let title_text = i18n::t(app, "app.titles.comments"); let title_span = Span::styled(&title_text, Style::default().fg(th.overlay1)); let items: Vec<ListItem<'static>> = if app.comments_loading { vec![build_loading_item(app)] } else if let Some(ref error) = app.comments_error { vec![build_error_item(error, &th)] } else if app.comments.is_empty() { vec![build_empty_item(app)] } else { build_comment_items(app, &th, comments_area) }; let list = List::new(items) .style(Style::default().fg(th.text).bg(th.base)) .block( Block::default() .title(Line::from(title_span)) .borders(Borders::ALL) .border_type(BorderType::Rounded) .border_style(Style::default().fg(th.surface2)), ); f.render_widget(list, comments_area); }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/details/footer.rs
src/ui/details/footer.rs
use ratatui::{ Frame, prelude::Rect, style::{Modifier, Style}, text::{Line, Span}, widgets::{Block, Paragraph, Wrap}, }; use crate::i18n; use crate::state::{AppState, Focus, RightPaneFocus}; use crate::theme::{KeyChord, Theme, theme}; /// What: Determine label color based on focus state. /// /// Inputs: /// - `is_focused`: Whether the section is currently focused /// /// Output: /// - Returns mauve if focused, overlay1 otherwise. /// /// Details: /// - Used to highlight active sections in the footer. const fn get_label_color(is_focused: bool, th: &Theme) -> ratatui::style::Color { if is_focused { th.mauve } else { th.overlay1 } } /// What: Add a single keybind entry to spans if key exists. /// /// Inputs: /// - `spans`: Mutable reference to spans vector to append to /// - `key_opt`: Optional key chord /// - `key_style`: Style for the key label /// - `text`: Text to display after the key /// - `sep_style`: Style for the separator /// /// Output: /// - Appends keybind entry to spans if key exists. /// /// Details: /// - Only adds entry if key is present, reducing conditional complexity. fn add_keybind_entry( spans: &mut Vec<Span<'static>>, key_opt: Option<&KeyChord>, key_style: Style, text: &str, sep_style: Style, ) { if let Some(k) = key_opt { spans.extend([ Span::styled(format!("[{}]", k.label()), key_style), Span::raw(format!(" {text}")), Span::styled(" | ", sep_style), ]); } } /// What: Add a dual keybind entry (up/down) to spans if both keys exist. /// /// Inputs: /// - `spans`: Mutable reference to spans vector to append to /// - `up_opt`: Optional up key chord /// - `down_opt`: Optional down key chord /// - `key_style`: Style for the key label /// - `text`: Text to display after the keys /// - `sep_style`: Style for the separator /// /// Output: /// - Appends dual keybind entry to spans if both keys exist. /// /// Details: /// - Only adds entry if both keys are present. fn add_dual_keybind_entry( spans: &mut Vec<Span<'static>>, up_opt: Option<&KeyChord>, down_opt: Option<&KeyChord>, key_style: Style, text: &str, sep_style: Style, ) { if let (Some(up), Some(dn)) = (up_opt, down_opt) { spans.extend([ Span::styled(format!("[{} / {}]", up.label(), dn.label()), key_style), Span::raw(format!(" {text}")), Span::styled(" | ", sep_style), ]); } } /// What: Add multiple keybind labels joined by " / " to spans. /// /// Inputs: /// - `spans`: Mutable reference to spans vector to append to /// - `keys`: Vector of key chords /// - `key_style`: Style for the key label /// - `text`: Text to display after the keys /// - `sep_style`: Style for the separator /// /// Output: /// - Appends multi-keybind entry to spans if keys exist. /// /// Details: /// - Only adds entry if keys vector is not empty. fn add_multi_keybind_entry( spans: &mut Vec<Span<'static>>, keys: &[KeyChord], key_style: Style, text: &str, sep_style: Style, ) { if !keys.is_empty() { let keys_str = keys .iter() .map(KeyChord::label) .collect::<Vec<_>>() .join(" / "); spans.extend([ Span::styled(format!("[{keys_str}]"), key_style), Span::raw(format!(" {text}")), Span::styled(" | ", sep_style), ]); } } /// What: Build section header span with label and color. /// /// Inputs: /// - `label`: Section label text /// - `label_color`: Color for the label /// /// Output: /// - Returns vector with styled label span and spacing. /// /// Details: /// - Creates bold, colored label followed by spacing. fn build_section_header(label: String, label_color: ratatui::style::Color) -> Vec<Span<'static>> { vec![ Span::styled( label, Style::default() .fg(label_color) .add_modifier(Modifier::BOLD), ), Span::raw(" "), ] } /// What: Build GLOBALS section spans. /// /// Inputs: /// - `app`: Application state /// - `th`: Theme /// - `key_style`: Style for keys /// - `sep_style`: Style for separator /// /// Output: /// - Returns vector of spans for GLOBALS section. /// /// Details: /// - Includes exit, help, reload theme, show pkgbuild, show comments, change sort, and normal mode toggle. fn build_globals_section( app: &AppState, th: &Theme, key_style: Style, sep_style: Style, ) -> Vec<Span<'static>> { let km = &app.keymap; let mut spans = build_section_header( format!("{} ", i18n::t(app, "app.headings.globals")), th.overlay1, ); add_keybind_entry( &mut spans, km.exit.first(), key_style, &i18n::t(app, "app.actions.exit"), sep_style, ); add_keybind_entry( &mut spans, km.help_overlay.first(), key_style, &i18n::t(app, "app.actions.help"), sep_style, ); add_keybind_entry( &mut spans, km.reload_config.first(), key_style, &i18n::t(app, "app.actions.reload_config"), sep_style, ); add_keybind_entry( &mut spans, km.show_pkgbuild.first(), key_style, &i18n::t(app, "app.actions.show_hide_pkgbuild"), sep_style, ); add_keybind_entry( &mut spans, km.comments_toggle.first(), key_style, &i18n::t(app, "app.actions.show_hide_comments"), sep_style, ); add_keybind_entry( &mut spans, km.change_sort.first(), key_style, &i18n::t(app, "app.actions.change_sort_mode"), sep_style, ); add_keybind_entry( &mut spans, km.search_normal_toggle.first(), key_style, &i18n::t(app, "app.actions.insert_mode"), sep_style, ); spans } /// What: Build SEARCH section spans. /// /// Inputs: /// - `app`: Application state /// - `th`: Theme /// - `key_style`: Style for keys /// - `sep_style`: Style for separator /// /// Output: /// - Returns vector of spans for SEARCH section. /// /// Details: /// - Includes move, page, add, and install actions. fn build_search_section( app: &AppState, th: &Theme, key_style: Style, sep_style: Style, ) -> Vec<Span<'static>> { let km = &app.keymap; let search_label_color = get_label_color(matches!(app.focus, Focus::Search), th); let mut spans = build_section_header( format!("{} ", i18n::t(app, "app.headings.search")), search_label_color, ); add_dual_keybind_entry( &mut spans, km.search_move_up.first(), km.search_move_down.first(), key_style, &i18n::t(app, "app.actions.move"), sep_style, ); add_dual_keybind_entry( &mut spans, km.search_page_up.first(), km.search_page_down.first(), key_style, &i18n::t(app, "app.actions.move_page"), sep_style, ); let add_text = if app.installed_only_mode { i18n::t(app, "app.actions.add_to_remove") } else { i18n::t(app, "app.actions.add_to_install") }; add_keybind_entry( &mut spans, km.search_add.first(), key_style, &add_text, sep_style, ); if app.installed_only_mode { spans.extend([ Span::styled("[Ctrl+Space]", key_style), Span::raw(format!(" {}", i18n::t(app, "app.actions.add_to_downgrade"))), Span::styled(" | ", sep_style), ]); } add_keybind_entry( &mut spans, km.search_install.first(), key_style, &i18n::t(app, "app.actions.install"), sep_style, ); // Show toggle based on search mode: toggle_normal label when fuzzy is active, toggle_fuzzy label when normal is active // Both use the same keybind (toggle_fuzzy) but with different labels if app.fuzzy_search_enabled { add_keybind_entry( &mut spans, km.toggle_fuzzy.first(), key_style, &i18n::t(app, "app.modals.help.key_labels.toggle_normal"), sep_style, ); } else { add_keybind_entry( &mut spans, km.toggle_fuzzy.first(), key_style, &i18n::t(app, "app.modals.help.key_labels.toggle_fuzzy"), sep_style, ); } // Show clear keybind based on mode: insert_clear for insert mode, normal_clear for normal mode if app.search_normal_mode { add_keybind_entry( &mut spans, km.search_normal_clear.first(), key_style, &i18n::t(app, "app.modals.help.key_labels.clear_input"), sep_style, ); } else { add_keybind_entry( &mut spans, km.search_insert_clear.first(), key_style, &i18n::t(app, "app.modals.help.key_labels.clear_input"), sep_style, ); } spans } /// What: Build common right-pane action spans (install/downgrade/remove). /// /// Inputs: /// - `app`: Application state /// - `label`: Section label /// - `label_color`: Color for label /// - `confirm_text`: Text for confirm action /// - `key_style`: Style for keys /// - `sep_style`: Style for separator /// /// Output: /// - Returns vector of spans for right-pane section. /// /// Details: /// - Includes move, confirm, remove, clear, find, and go to search actions. fn build_right_pane_spans( app: &AppState, label: String, label_color: ratatui::style::Color, confirm_text: &str, key_style: Style, sep_style: Style, ) -> Vec<Span<'static>> { let km = &app.keymap; let mut spans = build_section_header(label, label_color); add_dual_keybind_entry( &mut spans, km.install_move_up.first(), km.install_move_down.first(), key_style, &i18n::t(app, "app.actions.move"), sep_style, ); add_keybind_entry( &mut spans, km.install_confirm.first(), key_style, confirm_text, sep_style, ); add_multi_keybind_entry( &mut spans, &km.install_remove, key_style, &i18n::t(app, "app.actions.remove_from_list"), sep_style, ); add_keybind_entry( &mut spans, km.install_clear.first(), key_style, &i18n::t(app, "app.actions.clear"), sep_style, ); add_keybind_entry( &mut spans, km.install_find.first(), key_style, &i18n::t(app, "app.details.footer.search_hint"), sep_style, ); add_keybind_entry( &mut spans, km.install_to_search.first(), key_style, &i18n::t(app, "app.actions.go_to_search"), sep_style, ); spans } /// What: Build INSTALL section spans (or DOWNGRADE/REMOVE in installed-only mode). /// /// Inputs: /// - `app`: Application state /// - `th`: Theme /// - `key_style`: Style for keys /// - `sep_style`: Style for separator /// /// Output: /// - Returns tuple: (install line option, split lines option for downgrade/remove). /// /// Details: /// - Returns split lines in installed-only mode, single install line otherwise. fn build_install_section( app: &AppState, th: &Theme, key_style: Style, sep_style: Style, ) -> ( Option<Line<'static>>, Option<(Line<'static>, Line<'static>)>, ) { if app.installed_only_mode { let downgrade_color = get_label_color( matches!(app.focus, Focus::Install) && matches!(app.right_pane_focus, RightPaneFocus::Downgrade), th, ); let remove_color = get_label_color( matches!(app.focus, Focus::Install) && matches!(app.right_pane_focus, RightPaneFocus::Remove), th, ); let d_spans = build_right_pane_spans( app, format!("{}:", i18n::t(app, "app.headings.downgrade")), downgrade_color, &i18n::t(app, "app.details.footer.confirm_downgrade"), key_style, sep_style, ); let r_spans = build_right_pane_spans( app, format!("{}: ", i18n::t(app, "app.headings.remove")), remove_color, &i18n::t(app, "app.details.footer.confirm_removal"), key_style, sep_style, ); (None, Some((Line::from(d_spans), Line::from(r_spans)))) } else { let install_color = get_label_color(matches!(app.focus, Focus::Install), th); let i_spans = build_right_pane_spans( app, format!("{} ", i18n::t(app, "app.headings.install")), install_color, &i18n::t(app, "app.details.footer.confirm_installation"), key_style, sep_style, ); (Some(Line::from(i_spans)), None) } } /// What: Build RECENT section spans. /// /// Inputs: /// - `app`: Application state /// - `th`: Theme /// - `key_style`: Style for keys /// - `sep_style`: Style for separator /// /// Output: /// - Returns vector of spans for RECENT section. /// /// Details: /// - Includes move, use, remove, clear, add, find, and go to search actions. fn build_recent_section( app: &AppState, th: &Theme, key_style: Style, sep_style: Style, ) -> Vec<Span<'static>> { let km = &app.keymap; let recent_label_color = get_label_color(matches!(app.focus, Focus::Recent), th); let mut spans = build_section_header( format!("{} ", i18n::t(app, "app.headings.recent")), recent_label_color, ); add_dual_keybind_entry( &mut spans, km.recent_move_up.first(), km.recent_move_down.first(), key_style, &i18n::t(app, "app.actions.move"), sep_style, ); add_keybind_entry( &mut spans, km.recent_use.first(), key_style, &i18n::t(app, "app.actions.add_to_search"), sep_style, ); add_multi_keybind_entry( &mut spans, &km.recent_remove, key_style, &i18n::t(app, "app.actions.remove_from_list"), sep_style, ); add_keybind_entry( &mut spans, km.recent_clear.first(), key_style, &i18n::t(app, "app.actions.clear"), sep_style, ); add_keybind_entry( &mut spans, km.recent_add.first(), key_style, &i18n::t(app, "app.actions.add_first_match_to_install"), sep_style, ); add_keybind_entry( &mut spans, km.recent_find.first(), key_style, &i18n::t(app, "app.actions.search_hint_enter_next_esc_cancel"), sep_style, ); add_keybind_entry( &mut spans, km.recent_to_search.first(), key_style, &i18n::t(app, "app.actions.go_to_search"), sep_style, ); spans } /// What: Build Normal Mode section spans. /// /// Inputs: /// - `app`: Application state /// - `th`: Theme /// - `key_style`: Style for keys /// /// Output: /// - Returns vector of lines for Normal Mode section (may be empty). /// /// Details: /// - Returns two lines: base normal mode help and optional menus/import-export line. fn build_normal_mode_section(app: &AppState, th: &Theme, key_style: Style) -> Vec<Line<'static>> { let km = &app.keymap; let mut lines = Vec::new(); let label = |v: &Vec<KeyChord>, def: &str| v.first().map_or_else(|| def.to_string(), KeyChord::label); let toggle_label = label(&km.search_normal_toggle, "Esc"); let insert_label = label(&km.search_normal_insert, "i"); let clear_label = label(&km.search_normal_clear, "Shift+Del"); let normal_mode_label = i18n::t(app, "app.modals.help.normal_mode.label"); let insert_mode_text = i18n::t(app, "app.modals.help.normal_mode.insert_mode"); let move_text = i18n::t(app, "app.modals.help.normal_mode.move"); let page_text = i18n::t(app, "app.modals.help.normal_mode.page"); let clear_input_text = i18n::t(app, "app.modals.help.normal_mode.clear_input"); let n_spans: Vec<Span> = vec![ Span::styled( normal_mode_label, Style::default().fg(th.mauve).add_modifier(Modifier::BOLD), ), Span::raw(" "), Span::styled(format!("[{toggle_label} / {insert_label}]"), key_style), Span::raw(insert_mode_text), Span::styled("[j / k]", key_style), Span::raw(move_text), Span::styled("[Ctrl+d / Ctrl+u]", key_style), Span::raw(page_text), Span::styled(format!("[{clear_label}]"), key_style), Span::raw(clear_input_text), ]; lines.push(Line::from(n_spans)); // Second line: menus and import/export (if any) let mut second_line_spans: Vec<Span> = Vec::new(); if !km.config_menu_toggle.is_empty() || !km.options_menu_toggle.is_empty() || !km.panels_menu_toggle.is_empty() { let open_config_list_text = i18n::t(app, "app.modals.help.normal_mode.open_config_list"); let open_options_text = i18n::t(app, "app.modals.help.normal_mode.open_options"); let open_panels_text = i18n::t(app, "app.modals.help.normal_mode.open_panels"); if let Some(k) = km.config_menu_toggle.first() { second_line_spans.push(Span::raw(" • ")); second_line_spans.push(Span::styled(format!("[{}]", k.label()), key_style)); second_line_spans.push(Span::raw(open_config_list_text)); } if let Some(k) = km.options_menu_toggle.first() { second_line_spans.push(Span::raw(" • ")); second_line_spans.push(Span::styled(format!("[{}]", k.label()), key_style)); second_line_spans.push(Span::raw(open_options_text)); } if let Some(k) = km.panels_menu_toggle.first() { second_line_spans.push(Span::raw(" • ")); second_line_spans.push(Span::styled(format!("[{}]", k.label()), key_style)); second_line_spans.push(Span::raw(open_panels_text)); } } if !app.installed_only_mode && (!km.search_normal_import.is_empty() || !km.search_normal_export.is_empty() || !km.search_normal_updates.is_empty()) { let install_list_text = i18n::t(app, "app.modals.help.normal_mode.install_list"); let import_text = i18n::t(app, "app.modals.help.normal_mode.import"); let export_text = i18n::t(app, "app.modals.help.normal_mode.export"); let updates_text = i18n::t(app, "app.modals.help.normal_mode.updates"); second_line_spans.push(Span::raw(install_list_text)); if let Some(k) = km.search_normal_import.first() { second_line_spans.push(Span::styled(format!("[{}]", k.label()), key_style)); second_line_spans.push(Span::raw(import_text)); if let Some(k2) = km.search_normal_export.first() { second_line_spans.push(Span::raw(", ")); second_line_spans.push(Span::styled(format!("[{}]", k2.label()), key_style)); second_line_spans.push(Span::raw(export_text)); } if let Some(k3) = km.search_normal_updates.first() { second_line_spans.push(Span::raw(", ")); second_line_spans.push(Span::styled(format!("[{}]", k3.label()), key_style)); second_line_spans.push(Span::raw(updates_text)); } } else if let Some(k) = km.search_normal_export.first() { second_line_spans.push(Span::styled(format!("[{}]", k.label()), key_style)); second_line_spans.push(Span::raw(export_text)); if let Some(k2) = km.search_normal_updates.first() { second_line_spans.push(Span::raw(", ")); second_line_spans.push(Span::styled(format!("[{}]", k2.label()), key_style)); second_line_spans.push(Span::raw(updates_text)); } } else if let Some(k) = km.search_normal_updates.first() { second_line_spans.push(Span::styled(format!("[{}]", k.label()), key_style)); second_line_spans.push(Span::raw(updates_text)); } } if !second_line_spans.is_empty() { lines.push(Line::from(second_line_spans)); } lines } /// What: Render the keybind help footer inside the Package Info pane. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Application state providing focus, keymap, and pane flags /// - `bottom_container`: Overall rect covering the package info + footer region /// - `help_h`: Calculated footer height in rows /// /// Output: /// - Draws footer content and updates no state beyond rendering; uses rect geometry only locally. /// /// Details: /// - Highlights sections based on focused pane, reflects installed-only mode splits, and emits /// optional Normal Mode help when active; fills background to avoid bleed-through. pub fn render_footer(f: &mut Frame, app: &AppState, bottom_container: Rect, help_h: u16) { let th = theme(); // Footer occupies the bottom rows of the bottom container using reserved height above let footer_container = bottom_container; if footer_container.height > help_h + 2 { let x = footer_container.x + 1; // inside border let y_top = footer_container.y + footer_container.height.saturating_sub(help_h); let w = footer_container.width.saturating_sub(2); let h = help_h; let footer_rect = Rect { x, y: y_top, width: w, height: h, }; let key_style = Style::default() .fg(th.text) .bg(th.surface2) .add_modifier(Modifier::BOLD); let sep_style = Style::default().fg(th.overlay2); // Build all sections let g_spans = build_globals_section(app, &th, key_style, sep_style); let s_spans = build_search_section(app, &th, key_style, sep_style); let (right_lines_install, right_lines_split) = build_install_section(app, &th, key_style, sep_style); let r_spans = build_recent_section(app, &th, key_style, sep_style); // Assemble lines based on focus let mut lines: Vec<Line<'static>> = vec![Line::from(g_spans)]; if matches!(app.focus, Focus::Search) { lines.push(Line::from(s_spans)); } if matches!(app.focus, Focus::Install) { if let Some(i_line) = right_lines_install { lines.push(i_line); } if let Some((d_line, rm_line)) = right_lines_split { match app.right_pane_focus { RightPaneFocus::Downgrade => lines.push(d_line), RightPaneFocus::Remove => lines.push(rm_line), RightPaneFocus::Install => {} } } } if matches!(app.focus, Focus::Recent) { lines.push(Line::from(r_spans)); } if matches!(app.focus, Focus::Search) && app.search_normal_mode { lines.extend(build_normal_mode_section(app, &th, key_style)); } // Bottom-align the content within the reserved footer area // Use full footer height (including buffer) for the keybind viewer let content_lines: u16 = h; let content_y = y_top; let content_rect = Rect { x, y: content_y, width: w, height: content_lines, }; // Fill the whole reserved footer area with a uniform background f.render_widget( Block::default().style(Style::default().bg(th.base)), footer_rect, ); let footer = Paragraph::new(lines) .style(Style::default().fg(th.subtext1)) .wrap(Wrap { trim: true }); f.render_widget(footer, content_rect); } } /// What: Build the lines for the news keybind footer (global, navigation, menus, news actions, optional normal mode). /// /// Inputs: /// - `app`: Application state providing keymap, focus, and mode flags /// - `th`: Theme for styling /// /// Output: /// - Vector of lines ready to render in the news footer /// /// Details: /// - Always includes Global/Nav/Menus/News actions on the first line /// - Adds Normal Mode helper lines when search is focused and normal mode is active fn build_news_footer_lines(app: &AppState, th: &Theme) -> Vec<Line<'static>> { let key_style = Style::default() .fg(th.text) .bg(th.surface2) .add_modifier(Modifier::BOLD); let sep_style = Style::default().fg(th.overlay2); let mut lines: Vec<Line<'static>> = Vec::new(); // Line 1: Global/help let mut global_spans: Vec<Span<'static>> = Vec::new(); global_spans.extend(build_section_header("Global".to_string(), th.overlay1)); add_keybind_entry( &mut global_spans, app.keymap.help_overlay.first(), key_style, "Help", sep_style, ); add_keybind_entry( &mut global_spans, app.keymap.exit.first(), key_style, "Exit", sep_style, ); lines.push(Line::from(global_spans)); // Line 2: Navigation and Menus let mut nav_menus_spans: Vec<Span<'static>> = Vec::new(); nav_menus_spans.extend(build_section_header("Nav".to_string(), th.overlay1)); add_dual_keybind_entry( &mut nav_menus_spans, app.keymap.search_move_up.first(), app.keymap.search_move_down.first(), key_style, "Move", sep_style, ); add_dual_keybind_entry( &mut nav_menus_spans, app.keymap.search_page_up.first(), app.keymap.search_page_down.first(), key_style, "Page", sep_style, ); nav_menus_spans.extend(build_section_header("Menus".to_string(), th.overlay1)); add_keybind_entry( &mut nav_menus_spans, app.keymap.options_menu_toggle.first(), key_style, "Options", sep_style, ); add_keybind_entry( &mut nav_menus_spans, app.keymap.panels_menu_toggle.first(), key_style, "Panels", sep_style, ); add_keybind_entry( &mut nav_menus_spans, app.keymap.config_menu_toggle.first(), key_style, "Config/Lists", sep_style, ); lines.push(Line::from(nav_menus_spans)); // Line 3: News actions let mut news_spans: Vec<Span<'static>> = Vec::new(); news_spans.extend(build_section_header("News".to_string(), th.overlay1)); add_multi_keybind_entry( &mut news_spans, &app.keymap.news_mark_read_feed, key_style, "Mark read", sep_style, ); add_multi_keybind_entry( &mut news_spans, &app.keymap.news_mark_unread_feed, key_style, "Mark unread", sep_style, ); add_multi_keybind_entry( &mut news_spans, &app.keymap.news_toggle_read_feed, key_style, "Toggle read", sep_style, ); lines.push(Line::from(news_spans)); // Normal mode specific help when search pane is focused if matches!(app.focus, Focus::Search) { if app.search_normal_mode { lines.extend(build_normal_mode_section(app, th, key_style)); } else { let label = |v: &Vec<KeyChord>, def: &str| { v.first().map_or_else(|| def.to_string(), KeyChord::label) }; let toggle_label = label(&app.keymap.search_normal_toggle, "Esc"); let clear_label = label(&app.keymap.search_insert_clear, "Shift+Del"); let fuzzy_label = label(&app.keymap.toggle_fuzzy, "Ctrl+f"); let change_sort_label = label(&app.keymap.change_sort, "Shift+Tab"); let mut insert_spans = build_section_header( i18n::t(app, "app.modals.help.normal_mode.insert_mode"), th.mauve, ); insert_spans.push(Span::styled(format!("[{toggle_label}]"), key_style)); insert_spans.push(Span::raw(format!( " {}", i18n::t(app, "app.modals.help.key_labels.toggle_normal") ))); insert_spans.push(Span::styled(" | ", sep_style)); insert_spans.push(Span::styled(format!("[{clear_label}]"), key_style)); insert_spans.push(Span::raw(format!( " {}", i18n::t(app, "app.modals.help.key_labels.clear_input") ))); insert_spans.push(Span::styled(" | ", sep_style)); insert_spans.push(Span::styled(format!("[{fuzzy_label}]"), key_style)); insert_spans.push(Span::raw(format!( " {}", i18n::t(app, "app.modals.help.key_labels.toggle_fuzzy") ))); insert_spans.push(Span::styled(" | ", sep_style)); insert_spans.push(Span::styled(format!("[{change_sort_label}]"), key_style)); insert_spans.push(Span::raw(format!( " {}", i18n::t(app, "app.actions.change_sort_mode") ))); lines.push(Line::from(insert_spans)); } } lines } /// What: Render a simplified keybind footer for news management mode. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Application state (keymap, focus) /// - `area`: Full area of the news details pane /// - `footer_height`: Reserved footer height /// /// Output: /// - Draws news-relevant keybinds (navigation, menus, mark read) along the bottom. pub fn render_news_footer(f: &mut Frame, app: &AppState, area: Rect, footer_height: u16) { if footer_height == 0 || area.height < footer_height { return; } let th = theme(); let lines = build_news_footer_lines(app, &th); if lines.is_empty() { return; } let footer_rect = Rect { x: area.x + 1, // inside border y: area .y .saturating_add(area.height.saturating_sub(footer_height)), width: area.width.saturating_sub(2), height: footer_height, }; // Fill the whole reserved footer area with a uniform background f.render_widget( Block::default().style(Style::default().bg(th.base)), Rect { x: area.x, y: footer_rect.y, width: area.width, height: footer_height, }, ); let paragraph = Paragraph::new(lines) .style(Style::default().fg(th.subtext1)) .wrap(Wrap { trim: true }); f.render_widget(paragraph, footer_rect); } /// What: Compute the preferred height (in rows) for the news keybind footer. /// /// Inputs: /// - `app`: Application state (determines whether normal mode lines are included) /// /// Output: /// - Height in rows needed to render the footer without truncation (minimum 1 when enabled) pub fn news_footer_height(app: &AppState) -> u16 { let th = theme(); let line_count = build_news_footer_lines(app, &th).len(); u16::try_from(line_count.max(1)).unwrap_or(1) }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/details/pkgbuild_highlight.rs
src/ui/details/pkgbuild_highlight.rs
//! Syntax highlighting for PKGBUILD files using syntect with incremental reuse. //! //! This module provides functions to highlight PKGBUILD content using syntect //! and convert the highlighted spans to ratatui-compatible Spans, reusing cached //! results for unchanged prefixes to reduce re-render latency. use ratatui::{ style::{Color, Modifier, Style}, text::Line, }; use std::sync::{Mutex, OnceLock}; use syntect::{ easy::HighlightLines, highlighting::ThemeSet, parsing::SyntaxSet, util::LinesWithEndings, }; use crate::theme::Theme; /// Lazy-loaded syntax set for bash/shell syntax highlighting. static SYNTAX_SET: std::sync::OnceLock<SyntaxSet> = std::sync::OnceLock::new(); /// Lazy-loaded theme set for syntax highlighting. static THEME_SET: std::sync::OnceLock<ThemeSet> = std::sync::OnceLock::new(); /// What: Initialize the syntax set and theme set for syntax highlighting. /// /// Output: /// - Initializes static syntax and theme sets if not already initialized. /// /// Details: /// - Uses `OnceLock` to ensure initialization happens only once. /// - Loads bash syntax definition and a dark theme suitable for TUI. fn init_syntax() { SYNTAX_SET.get_or_init(|| { // Load syntax definitions (includes bash) SyntaxSet::load_defaults_newlines() }); THEME_SET.get_or_init(|| { // Load theme set (includes various themes) ThemeSet::load_defaults() }); } /// What: Map syntect color to theme colors based on color characteristics. /// /// Inputs: /// - `sc`: Syntect color (RGBA) - syntect already assigns colors based on scope matching /// - `th`: Application theme for color mapping /// /// Output: /// - `ratatui::style::Color` mapped from theme colors /// /// Details: /// - Syntect already does scope-based highlighting internally and assigns appropriate colors. /// - We map syntect's colors to our theme colors based on color characteristics. /// - Only handles edge cases (too dark/light colors). fn map_syntect_color(sc: syntect::highlighting::Color, th: &Theme) -> Color { let r = sc.r; let g = sc.g; let b = sc.b; let max_rgb = r.max(g).max(b); let min_rgb = r.min(g).min(b); let avg_rgb = (u16::from(r) + u16::from(g) + u16::from(b)) / 3; // If color is very dark (close to black), use theme text color if max_rgb < 30 { return th.text; } // If color is too light (close to white), use theme text color if r > 200 && g > 200 && b > 200 { return th.text; } // Map syntect's scope-based colors to theme colors based on color characteristics // Check color characteristics first (more specific) // Green-ish colors -> green (strings, comments with green tint) if g > r + 20 && g > b + 20 && g > 60 { return th.green; } // Purple/magenta-ish colors -> mauve (keywords, control flow) if ((r > 120 && b > 120 && g < r.min(b) + 40) || (r > 150 && b > 150)) && max_rgb > 60 { return th.mauve; } // Blue-ish colors -> sapphire (variables, functions, commands) if b > r + 20 && b > g + 20 && b > 60 { return th.sapphire; } // Yellow/orange-ish colors -> yellow (numbers, constants) if r > 150 && g > 120 && b < 120 && max_rgb > 60 { return th.yellow; } // Red-ish colors -> red (errors, warnings) if r > g + 30 && r > b + 30 && r > 60 { return th.red; } // Grey-ish colors (medium grey) -> subtext0 (comments, muted text) if max_rgb > 40 && max_rgb < 200 && (max_rgb - min_rgb) < 50 { return th.subtext0; } // Dark colors that don't match specific characteristics // Map to appropriate theme colors based on slight color hints if max_rgb < 100 { // Very dark colors - try to detect slight color hints if b > r + 10 && b > g + 10 { return th.sapphire; // Slight blue tint -> sapphire } if g > r + 10 && g > b + 10 { return th.green; // Slight green tint -> green } if r > g + 10 && r > b + 10 && b < 50 { return th.yellow; // Slight yellow/orange tint -> yellow } if r > 80 && b > 80 && g < 60 { return th.mauve; // Slight purple tint -> mauve } // Default dark colors -> subtext0 (muted) return th.subtext0; } // Medium brightness colors that don't match specific characteristics // Default to sapphire for commands/functions if avg_rgb > 100 && avg_rgb < 180 { return th.sapphire; } // Use syntect color directly for bright, well-defined colors Color::Rgb(r, g, b) } /// What: Cache entry for highlighted PKGBUILD text. /// /// Inputs: Created from PKGBUILD text and highlighting. /// /// Output: Cached highlighted lines for reuse. /// /// Details: Stores the original text and pre-highlighted lines to avoid re-highlighting unchanged text. #[derive(Clone)] struct PkgbHighlightCache { /// Original PKGBUILD text. text: String, /// Pre-highlighted lines. lines: Vec<Line<'static>>, } /// Global cache for PKGBUILD highlighting to enable dirty-region reuse across renders. static PKGB_CACHE: OnceLock<Mutex<Option<PkgbHighlightCache>>> = OnceLock::new(); /// What: Get the global PKGBUILD highlight cache lock. /// /// Inputs: None. /// /// Output: Reference to the cache mutex. /// /// Details: Returns the global cache mutex, initializing it if necessary. fn cache_lock() -> &'static Mutex<Option<PkgbHighlightCache>> { PKGB_CACHE.get_or_init(|| Mutex::new(None)) } /// What: Highlight PKGBUILD text using syntect and convert to ratatui Spans. /// /// Inputs: /// - `text`: PKGBUILD content to highlight /// - `th`: Application theme for color mapping /// /// Output: /// - `Vec<ratatui::text::Line>` containing highlighted lines ready for rendering /// /// Details: /// - Uses bash syntax definition for highlighting. /// - Falls back to plain text if highlighting fails. /// - Reuses cached highlighted prefixes and recomputes from the first differing line to preserve /// syntect state; falls back to plain text per-line on parse errors. pub fn highlight_pkgbuild(text: &str, th: &Theme) -> Vec<Line<'static>> { init_syntax(); let syntax_set = SYNTAX_SET.get().expect("syntax set should be initialized"); let theme_set = THEME_SET.get().expect("theme set should be initialized"); // Try to find bash syntax, fallback to plain text if not found let syntax = syntax_set .find_syntax_by_extension("sh") .or_else(|| syntax_set.find_syntax_by_extension("bash")) .or_else(|| syntax_set.find_syntax_by_name("Bash")) .unwrap_or_else(|| syntax_set.find_syntax_plain_text()); // Use a dark theme suitable for TUI (InspiredGitHub or similar) let theme = theme_set .themes .get("InspiredGitHub") .or_else(|| theme_set.themes.values().next()) .expect("at least one theme should be available"); // Fast path: identical text to cache if let Ok(cache_guard) = cache_lock().lock() && let Some(cache) = cache_guard.as_ref() && cache.text == text { return cache.lines.clone(); } // Snapshot old cache (if any) and release lock for work let old_cache = cache_lock().lock().ok().and_then(|c| c.clone()); let new_lines_raw: Vec<String> = LinesWithEndings::from(text).map(str::to_string).collect(); let old_lines_raw: Vec<String> = old_cache .as_ref() .map(|c| { LinesWithEndings::from(c.text.as_str()) .map(str::to_string) .collect() }) .unwrap_or_default(); let prefix_len = new_lines_raw .iter() .zip(&old_lines_raw) .take_while(|(a, b)| a == b) .count(); // Syntect highlighter (stateful; must process lines in order) let mut highlighter = HighlightLines::new(syntax, theme); let mut highlighted_lines: Vec<Line<'static>> = Vec::with_capacity(new_lines_raw.len()); // Replay unchanged prefix to advance syntect state; reuse cached spans when present for line in new_lines_raw.iter().take(prefix_len) { match highlighter.highlight_line(line, syntax_set) { Ok(highlighted_line) => { if let Some(cache) = old_cache.as_ref() && cache.lines.len() > highlighted_lines.len() { highlighted_lines.push(cache.lines[highlighted_lines.len()].clone()); } else { highlighted_lines.push(to_ratatui_line(&highlighted_line, th, line)); } } Err(_) => highlighted_lines.push(Line::from(line.clone())), } } // Highlight remaining (changed) region onward for line in new_lines_raw.iter().skip(prefix_len) { match highlighter.highlight_line(line, syntax_set) { Ok(highlighted_line) => { highlighted_lines.push(to_ratatui_line(&highlighted_line, th, line)); } Err(_) => highlighted_lines.push(Line::from(line.clone())), } } // Update cache if let Ok(mut cache_guard) = cache_lock().lock() { *cache_guard = Some(PkgbHighlightCache { text: text.to_string(), lines: highlighted_lines.clone(), }); } highlighted_lines } /// What: Convert syntect highlighted line to ratatui Line. /// /// Inputs: /// - `highlighted_line`: Syntect style-text pairs. /// - `th`: Theme for color conversion. /// - `fallback`: Fallback text if conversion fails. /// /// Output: ratatui Line with styled spans. /// /// Details: Converts syntect highlighting styles to ratatui-compatible spans with theme colors. fn to_ratatui_line( highlighted_line: &[(syntect::highlighting::Style, &str)], th: &Theme, fallback: &str, ) -> Line<'static> { let mut spans = Vec::new(); for (style, text) in highlighted_line { let color = map_syntect_color(style.foreground, th); let mut ratatui_style = Style::default().fg(color); if style .font_style .contains(syntect::highlighting::FontStyle::BOLD) { ratatui_style = ratatui_style.add_modifier(Modifier::BOLD); } if style .font_style .contains(syntect::highlighting::FontStyle::ITALIC) { ratatui_style = ratatui_style.add_modifier(Modifier::ITALIC); } if style .font_style .contains(syntect::highlighting::FontStyle::UNDERLINE) { ratatui_style = ratatui_style.add_modifier(Modifier::UNDERLINED); } spans.push(ratatui::text::Span::styled( (*text).to_string(), ratatui_style, )); } if spans.is_empty() { spans.push(ratatui::text::Span::raw(fallback.to_string())); } Line::from(spans) } #[cfg(test)] mod tests { use super::*; use crate::theme::theme; #[test] /// What: Ensure identical text hits the cache and returns lines without recomputing content. /// /// Inputs: /// - Two invocations with the same PKGBUILD text. /// /// Output: /// - Highlighted lines are equal across calls, demonstrating cache reuse. fn highlight_pkgbuild_cache_hit() { reset_cache(); let th = theme(); let pkgbuild = "pkgname=test\npkgver=1\n"; let first = highlight_pkgbuild(pkgbuild, &th); let second = highlight_pkgbuild(pkgbuild, &th); assert_eq!(first.len(), second.len()); assert_eq!(first[0].to_string(), second[0].to_string()); } #[test] /// What: Ensure changes late in the file avoid re-highlighting unchanged prefixes. /// /// Inputs: /// - Initial text, then an appended line. /// /// Output: /// - Highlighting succeeds and yields expected total line count. fn highlight_pkgbuild_incremental_appends() { reset_cache(); let th = theme(); let base = "pkgname=test\npkgver=1\n"; let appended = "pkgname=test\npkgver=1\n# comment\n"; let first = highlight_pkgbuild(base, &th); let second = highlight_pkgbuild(appended, &th); assert_eq!(second.len(), 3); assert_eq!(first.len(), 2); } #[test] /// What: Ensure empty text returns an empty or single-line result. fn test_highlight_pkgbuild_empty() { reset_cache(); let th = theme(); let lines = highlight_pkgbuild("", &th); assert!(lines.is_empty() || lines.len() == 1); } #[test] fn test_highlight_pkgbuild_basic() { reset_cache(); let th = theme(); let pkgbuild = r"pkgname=test pkgver=1.0.0 # This is a comment depends=('bash') "; let lines = highlight_pkgbuild(pkgbuild, &th); assert!(!lines.is_empty()); } fn reset_cache() { if let Ok(mut guard) = cache_lock().lock() { *guard = None; } } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/details/package_info.rs
src/ui/details/package_info.rs
use ratatui::{ Frame, prelude::Rect, style::{Modifier, Style}, text::Line, widgets::{Block, BorderType, Borders, Paragraph, Wrap}, }; use unicode_width::UnicodeWidthStr; use crate::i18n; use crate::state::AppState; use crate::theme::theme; /// What: Calculate content layout dimensions from a details area rect. /// /// Inputs: /// - `details_area`: Rect assigned to the Package Info pane content /// /// Output: /// - Tuple of (`content_x`, `content_y`, `inner_w`) representing layout dimensions. /// /// Details: /// - Accounts for border inset and calculates inner content dimensions. const fn calculate_content_layout(details_area: Rect) -> (u16, u16, u16) { let border_inset = 1u16; let content_x = details_area.x.saturating_add(border_inset); let content_y = details_area.y.saturating_add(border_inset); let inner_w = details_area.width.saturating_sub(2); (content_x, content_y, inner_w) } /// What: Style URL text in details lines as a clickable link. /// /// Inputs: /// - `details_lines`: Mutable reference to formatted details lines /// - `url_label`: Localized label for the URL field /// - `url_text`: The URL text to style /// - `th`: Theme colors /// /// Output: /// - Modifies `details_lines` in place, styling the URL span. /// /// Details: /// - Finds the URL line and applies link styling (mauve, underlined, bold) if URL is non-empty. fn style_url_in_lines( details_lines: &mut [Line], url_label: &str, url_text: &str, th: &crate::theme::Theme, ) { for line in details_lines.iter_mut() { if line.spans.len() >= 2 { let key_txt = line.spans[0].content.to_string(); if key_txt.starts_with(url_label) { let style = if url_text.is_empty() { Style::default().fg(th.text) } else { Style::default() .fg(th.mauve) .add_modifier(Modifier::UNDERLINED | Modifier::BOLD) }; line.spans[1] = ratatui::text::Span::styled(url_text.to_string(), style); } } } } /// What: Calculate the number of rows a line occupies when wrapped. /// /// Inputs: /// - `line_len`: Total character length of the line /// - `inner_w`: Available width for wrapping /// /// Output: /// - Number of rows (at least 1) the line will occupy. /// /// Details: /// - Handles zero-width case and calculates wrapping using `div_ceil`. fn calculate_wrapped_line_rows(line_len: usize, inner_w: u16) -> u16 { if inner_w == 0 { 1 } else { u16::try_from(line_len) .unwrap_or(u16::MAX) .div_ceil(inner_w) .max(1) } } /// What: Calculate the URL button rectangle position. /// /// Inputs: /// - `key_txt`: The label text before the URL /// - `url_txt`: The URL text /// - `content_x`: X coordinate of content area /// - `cur_y`: Current Y coordinate /// - `inner_w`: Available inner width /// /// Output: /// - Optional button rectangle (x, y, width, height) if URL is non-empty and fits. /// /// Details: /// - Positions button after the label text, constrained to available width. fn calculate_url_button_rect( key_txt: &str, url_txt: &str, content_x: u16, cur_y: u16, inner_w: u16, ) -> Option<(u16, u16, u16, u16)> { if url_txt.is_empty() { return None; } // Use Unicode display width, not byte length, to handle wide characters let key_len = u16::try_from(key_txt.width()).unwrap_or(u16::MAX); let x_start = content_x.saturating_add(key_len); let max_w = inner_w.saturating_sub(key_len); let w = u16::try_from(url_txt.width().min(max_w as usize)).unwrap_or(u16::MAX); if w > 0 { Some((x_start, cur_y, w, 1)) } else { None } } /// What: Calculate the PKGBUILD button rectangle position. /// /// Inputs: /// - `txt`: The button text /// - `content_x`: X coordinate of content area /// - `cur_y`: Current Y coordinate /// - `inner_w`: Available inner width /// /// Output: /// - Optional button rectangle (x, y, width, height) if text fits. /// /// Details: /// - Positions button at content start, constrained to available width. fn calculate_pkgbuild_button_rect( txt: &str, content_x: u16, cur_y: u16, inner_w: u16, ) -> Option<(u16, u16, u16, u16)> { // Use Unicode display width, not byte length, to handle wide characters let w = u16::try_from(txt.width().min(inner_w as usize)).unwrap_or(u16::MAX); if w > 0 { Some((content_x, cur_y, w, 1)) } else { None } } /// What: Context for calculating button rectangles. /// /// Details: /// - Groups layout and URL parameters for button calculation. struct ButtonContext<'a> { /// X coordinate of content area content_x: u16, /// Y coordinate of content area start content_y: u16, /// Available inner width inner_w: u16, /// Localized label for the URL field url_label: &'a str, /// The URL text url_text: &'a str, } /// What: Calculate button rectangles for URL and PKGBUILD based on visible lines. /// /// Inputs: /// - `details_lines`: All formatted details lines /// - `visible_lines`: Only the visible lines after scroll offset /// - `scroll_offset`: Number of lines skipped from top /// - `ctx`: Button calculation context (layout and URL info) /// - `app`: Application state to update button rects /// /// Output: /// - Updates `app.url_button_rect` and `app.pkgb_button_rect` with calculated positions. /// /// Details: /// - Iterates through visible lines, calculates button positions, and accounts for text wrapping. fn calculate_button_rects( details_lines: &[Line], visible_lines: &[Line], scroll_offset: usize, ctx: &ButtonContext<'_>, app: &mut AppState, ) { app.url_button_rect = None; app.pkgb_button_rect = None; app.comments_button_rect = None; let show_pkgb = crate::i18n::t(app, "app.details.show_pkgbuild").to_lowercase(); let hide_pkgb = crate::i18n::t(app, "app.details.hide_pkgbuild").to_lowercase(); let show_comments = crate::i18n::t(app, "app.details.show_comments").to_lowercase(); let hide_comments = crate::i18n::t(app, "app.details.hide_comments").to_lowercase(); let mut cur_y = ctx.content_y; for (vis_idx, vis_line) in visible_lines.iter().enumerate() { let line_idx = vis_idx + scroll_offset; let original_line = &details_lines[line_idx]; // Check for URL button if original_line.spans.len() >= 2 { let key_txt = original_line.spans[0].content.to_string(); if key_txt.starts_with(ctx.url_label) && let Some(rect) = calculate_url_button_rect( &key_txt, ctx.url_text, ctx.content_x, cur_y, ctx.inner_w, ) { app.url_button_rect = Some(rect); } } // Check for PKGBUILD button if original_line.spans.len() == 1 { let txt = original_line.spans[0].content.to_string(); let lowered = txt.to_lowercase(); if (lowered.contains(&show_pkgb) || lowered.contains(&hide_pkgb)) && let Some(rect) = calculate_pkgbuild_button_rect(&txt, ctx.content_x, cur_y, ctx.inner_w) { app.pkgb_button_rect = Some(rect); } else if (lowered.contains(&show_comments) || lowered.contains(&hide_comments)) && let Some(rect) = calculate_pkgbuild_button_rect(&txt, ctx.content_x, cur_y, ctx.inner_w) { app.comments_button_rect = Some(rect); } } // Advance y accounting for wrapping let line_len: usize = vis_line.spans.iter().map(|s| s.content.len()).sum(); let rows = calculate_wrapped_line_rows(line_len, ctx.inner_w); cur_y = cur_y.saturating_add(rows); } } /// What: Render the Package Info pane with scroll support and interactive buttons. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state (details, scroll offsets, cached rects) /// - `details_area`: Rect assigned to the Package Info pane content /// /// Output: /// - Draws package details and updates mouse hit-test rects for URL/PKGBUILD elements. /// /// Details: /// - Applies scroll offsets, styles the URL as a link when present, records button rectangles, and /// enables text selection by marking `mouse_disabled_in_details`. pub fn render_package_info(f: &mut Frame, app: &mut AppState, details_area: Rect) { let th = theme(); let url_label = crate::i18n::t(app, "app.details.url_label"); let url_text = app.details.url.clone(); let mut details_lines = crate::ui::helpers::format_details_lines(app, details_area.width, &th); // Record details inner rect for mouse hit-testing app.details_rect = Some(( details_area.x + 1, details_area.y + 1, details_area.width.saturating_sub(2), details_area.height.saturating_sub(2), )); // Style URL in lines style_url_in_lines(&mut details_lines, &url_label, &url_text, &th); // Apply scroll offset by skipping lines from the top let scroll_offset = app.details_scroll as usize; let visible_lines: Vec<_> = details_lines.iter().skip(scroll_offset).cloned().collect(); // Calculate layout dimensions let (content_x, content_y, inner_w) = calculate_content_layout(details_area); // Calculate button positions based on visible lines let button_ctx = ButtonContext { content_x, content_y, inner_w, url_label: &url_label, url_text: &url_text, }; calculate_button_rects( &details_lines, &visible_lines, scroll_offset, &button_ctx, app, ); // Render the widget let package_info_title = i18n::t(app, "app.headings.package_info"); let details_block = Block::default() .title(ratatui::text::Span::styled( &package_info_title, Style::default().fg(th.overlay1), )) .borders(Borders::ALL) .border_type(BorderType::Rounded) .border_style(Style::default().fg(th.surface2)); let details = Paragraph::new(visible_lines) .style(Style::default().fg(th.text).bg(th.base)) .wrap(Wrap { trim: true }) .block(details_block); f.render_widget(details, details_area); // Allow terminal to mark/select text in details: ignore clicks within details by default app.mouse_disabled_in_details = true; }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/details/mod.rs
src/ui/details/mod.rs
use ratatui::{Frame, prelude::Rect, widgets::Wrap}; use crate::state::AppState; /// Comments viewer rendering. mod comments; /// Footer rendering for details pane. mod footer; /// Layout calculation for details pane. mod layout; /// Package information rendering. mod package_info; /// PKGBUILD viewer rendering. mod pkgbuild; /// PKGBUILD syntax highlighting. mod pkgbuild_highlight; /// What: Render the bottom details pane, footer, optional PKGBUILD viewer, and optional comments viewer. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Mutable application state (details, PKGBUILD, comments, footer flags) /// - `area`: Target rectangle for the details section /// /// Output: /// - Draws package information, optional PKGBUILD, optional comments, and footer while updating mouse hit-test rects. /// /// Details: /// - Computes layout splits for details, PKGBUILD, comments, and footer; records rects on [`AppState`] for /// URL/PKGBUILD/comments interaction and toggles footer visibility based on available height. pub fn render_details(f: &mut Frame, app: &mut AppState, area: Rect) { // Calculate footer height and layout areas let footer_height = layout::calculate_footer_height(app, area); let (_content_container, details_area, pkgb_area_opt, comments_area_opt, show_keybinds) = layout::calculate_layout_areas(app, area, footer_height); // Render Package Info pane package_info::render_package_info(f, app, details_area); // Render PKGBUILD pane if visible if let Some(pkgb_area) = pkgb_area_opt { pkgbuild::render_pkgbuild(f, app, pkgb_area); } // Render comments pane if visible if let Some(comments_area) = comments_area_opt { comments::render_comments(f, app, comments_area); } // Render footer/keybinds if enabled and there's space if show_keybinds { footer::render_footer(f, app, area, footer_height); } } /// What: Render news feed details pane when in news mode. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Application state (news results/selection) /// - `area`: Target rectangle for details /// /// Output: /// - Draws selected news item metadata and body. // Track last-logged news selection to avoid log spam. static LAST_LOGGED_NEWS_SEL: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(usize::MAX); /// What: Render news details (title, metadata, article content) with code highlighting. /// /// Inputs: /// - `f`: Frame to render into /// - `app`: Application state (news results, selection, content cache) /// - `area`: Target rectangle for the details pane /// /// Output: /// - Draws the news details pane, records clickable URL rect, and supports scroll/wrap. pub fn render_news_details(f: &mut Frame, app: &mut AppState, area: Rect) { use std::sync::atomic::Ordering; let th = crate::theme::theme(); let selected = app.news_results.get(app.news_selected).cloned(); // Only log when selection changes (tracked via static) if LAST_LOGGED_NEWS_SEL.swap(app.news_selected, Ordering::Relaxed) != app.news_selected { tracing::debug!( news_selected = app.news_selected, news_results_len = app.news_results.len(), selected_title = selected.as_ref().map(|s| s.title.as_str()), "render_news_details: selection changed" ); } let lines = selected.map_or_else( || vec![ratatui::text::Line::from("No news selected")], |item| build_news_body(app, &item, area, &th), ); let footer_h: u16 = if app.show_keybinds_footer { footer::news_footer_height(app).min(area.height) } else { 0 }; let content_height = area.height.saturating_sub(footer_h); let content_area = Rect { x: area.x, y: area.y, width: area.width, height: content_height, }; let paragraph = ratatui::widgets::Paragraph::new(lines) .style(ratatui::style::Style::default().fg(th.text).bg(th.base)) .block( ratatui::widgets::Block::default() .title(ratatui::text::Span::styled( crate::i18n::t(app, "app.results.options_menu.news"), ratatui::style::Style::default().fg(th.mauve), )) .borders(ratatui::widgets::Borders::ALL) .border_type(ratatui::widgets::BorderType::Rounded) .border_style(ratatui::style::Style::default().fg(th.surface2)), ) .wrap(Wrap { trim: true }) .scroll((app.news_content_scroll, 0)); f.render_widget(paragraph, content_area); app.details_rect = Some(( content_area.x, content_area.y, content_area.width, content_area.height, )); if footer_h > 0 && area.height >= footer_h { footer::render_news_footer(f, app, area, footer_h); } } /// What: Build the lines for news metadata and content (without rendering). /// /// Inputs: /// - `app`: Application state (used for URL rects and content state) /// - `item`: Selected news item /// - `area`: Target rectangle (for URL hit-test geometry) /// - `th`: Theme for styling /// /// Output: /// - Vector of lines ready to render in the details pane. fn build_news_body( app: &mut AppState, item: &crate::state::types::NewsFeedItem, area: Rect, th: &crate::theme::Theme, ) -> Vec<ratatui::text::Line<'static>> { let mut body: Vec<ratatui::text::Line<'static>> = Vec::new(); body.push(ratatui::text::Line::from(ratatui::text::Span::styled( item.title.clone(), ratatui::style::Style::default() .fg(th.mauve) .add_modifier(ratatui::style::Modifier::BOLD), ))); body.push(ratatui::text::Line::from("")); body.push(ratatui::text::Line::from(format!("Date: {}", item.date))); body.push(ratatui::text::Line::from(format!( "Source: {:?}", item.source ))); if let Some(sev) = item.severity { body.push(ratatui::text::Line::from(format!("Severity: {sev:?}"))); } if !item.packages.is_empty() { body.push(ratatui::text::Line::from(format!( "Packages: {}", item.packages.join(", ") ))); } if let Some(summary) = item.summary.clone() { body.push(ratatui::text::Line::from("")); body.push(ratatui::text::Line::from(summary)); } if let Some(url) = item.url.clone() { let link_label = crate::i18n::t(app, "app.details.open_url_label"); body.push(ratatui::text::Line::from("")); body.push(ratatui::text::Line::from(vec![ ratatui::text::Span::styled( link_label.clone(), ratatui::style::Style::default() .fg(th.mauve) .add_modifier(ratatui::style::Modifier::UNDERLINED) .add_modifier(ratatui::style::Modifier::BOLD), ), ])); app.details.url.clone_from(&url); let line_idx = body.len().saturating_sub(1); let y = area .y .saturating_add(1 + u16::try_from(line_idx).unwrap_or(0)); let x = area.x.saturating_add(1); let w = u16::try_from(link_label.len()).unwrap_or(20); app.url_button_rect = Some((x, y, w, 1)); } else { app.details.url.clear(); app.url_button_rect = None; } body.push(ratatui::text::Line::from("")); body.push(ratatui::text::Line::from(ratatui::text::Span::styled( "─── Article Content ───", ratatui::style::Style::default().fg(th.surface2), ))); body.push(ratatui::text::Line::from("")); if app.news_content_loading { body.push(ratatui::text::Line::from(ratatui::text::Span::styled( "Loading content...", ratatui::style::Style::default().fg(th.overlay1), ))); return body; } let Some(content) = &app.news_content else { body.push(ratatui::text::Line::from(ratatui::text::Span::styled( "Content not available", ratatui::style::Style::default().fg(th.overlay1), ))); return body; }; if content.is_empty() { body.push(ratatui::text::Line::from(ratatui::text::Span::styled( "Content not available", ratatui::style::Style::default().fg(th.overlay1), ))); return body; } body.extend(render_news_content_lines(content, th)); body } /// What: Render article content into styled lines, supporting fenced and inline code. /// /// Inputs: /// - `content`: Plaintext article content /// - `th`: Theme to style normal and code text /// /// Output: /// - Vector of lines with code highlighting applied. fn render_news_content_lines( content: &str, th: &crate::theme::Theme, ) -> Vec<ratatui::text::Line<'static>> { let code_block_style = ratatui::style::Style::default() .fg(th.lavender) .bg(th.surface1) .add_modifier(ratatui::style::Modifier::BOLD); let inline_code_style = ratatui::style::Style::default() .fg(th.lavender) .add_modifier(ratatui::style::Modifier::ITALIC); let link_style = ratatui::style::Style::default() .fg(th.sapphire) .add_modifier(ratatui::style::Modifier::UNDERLINED | ratatui::style::Modifier::BOLD); let normal_style = ratatui::style::Style::default().fg(th.text); let mut rendered: Vec<ratatui::text::Line<'static>> = Vec::new(); let mut in_code_block = false; for line in content.lines() { let trimmed = line.trim(); if trimmed.starts_with("```") { in_code_block = !in_code_block; rendered.push(ratatui::text::Line::from("")); continue; } if in_code_block { rendered.push(ratatui::text::Line::from(ratatui::text::Span::styled( line.to_string(), code_block_style, ))); continue; } let mut spans: Vec<ratatui::text::Span> = Vec::new(); let mut is_code = false; for (i, part) in line.split('`').enumerate() { if i > 0 { is_code = !is_code; } if part.is_empty() { continue; } if is_code { spans.push(ratatui::text::Span::styled( part.to_string(), inline_code_style, )); } else { spans.extend(style_links(part, normal_style, link_style)); } } if spans.is_empty() { rendered.push(ratatui::text::Line::from(ratatui::text::Span::styled( line.to_string(), normal_style, ))); } else { rendered.push(ratatui::text::Line::from(spans)); } } rendered } /// What: Style inline links within a text segment by underlining URLs. /// /// Inputs: /// - `segment`: Raw text segment (outside of code spans) to scan. /// - `normal_style`: Style applied to non-link text. /// - `link_style`: Style applied to detected URLs. /// /// Output: /// - Spans with URLs underlined/bold for better visibility; whitespace preserved. fn style_links( segment: &str, normal_style: ratatui::style::Style, link_style: ratatui::style::Style, ) -> Vec<ratatui::text::Span<'static>> { let mut spans: Vec<ratatui::text::Span> = Vec::new(); let mut current = String::new(); let flush_current = |spans: &mut Vec<ratatui::text::Span>, cur: &mut String| { if !cur.is_empty() { spans.push(ratatui::text::Span::styled(cur.clone(), normal_style)); cur.clear(); } }; let mut word = String::new(); for ch in segment.chars() { if ch.is_whitespace() { if !word.is_empty() { let span_style = if word.starts_with("http://") || word.starts_with("https://") { link_style } else { normal_style }; flush_current(&mut spans, &mut current); spans.push(ratatui::text::Span::styled(word.clone(), span_style)); word.clear(); } current.push(ch); continue; } if !current.is_empty() { flush_current(&mut spans, &mut current); } word.push(ch); } if !word.is_empty() { let span_style = if word.starts_with("http://") || word.starts_with("https://") { link_style } else { normal_style }; flush_current(&mut spans, &mut current); spans.push(ratatui::text::Span::styled(word, span_style)); } flush_current(&mut spans, &mut current); spans } #[cfg(test)] mod tests { /// What: Initialize minimal English translations for tests. /// /// Inputs: /// - `app`: `AppState` to populate with translations /// /// Output: /// - Populates `app.translations` and `app.translations_fallback` with minimal English translations /// /// Details: /// - Sets up only the translations needed for tests to pass fn init_test_translations(app: &mut crate::state::AppState) { use std::collections::HashMap; let mut translations = HashMap::new(); translations.insert("app.details.fields.url".to_string(), "URL".to_string()); translations.insert("app.details.url_label".to_string(), "URL:".to_string()); translations.insert( "app.details.open_url_label".to_string(), "[Open in Browser]".to_string(), ); translations.insert( "app.results.options_menu.news".to_string(), "News".to_string(), ); app.translations = translations.clone(); app.translations_fallback = translations; } /// What: Confirm rendering the details pane records hit-test rectangles and disables mouse interactions when appropriate. /// /// Inputs: /// - `AppState` containing package details with a URL and an expanded PKGBUILD view. /// /// Output: /// - Details, URL button, PKGBUILD toggle, and PKGBUILD area rectangles become `Some`, and the mouse flag toggles off. /// /// Details: /// - Uses a `TestBackend` terminal to drive layout without user interaction, ensuring the renderer updates state. #[test] fn details_sets_url_and_pkgb_rects() { use ratatui::{Terminal, backend::TestBackend}; let backend = TestBackend::new(80, 20); let mut term = Terminal::new(backend).expect("failed to create test terminal"); let mut app = crate::state::AppState::default(); init_test_translations(&mut app); app.details = crate::state::PackageDetails { repository: "extra".into(), name: "ripgrep".into(), version: "14".into(), description: String::new(), architecture: "x86_64".into(), url: "https://example.com".into(), licenses: vec![], groups: vec![], provides: vec![], depends: vec![], opt_depends: vec![], required_by: vec![], optional_for: vec![], conflicts: vec![], replaces: vec![], download_size: None, install_size: None, owner: String::new(), build_date: String::new(), popularity: None, out_of_date: None, orphaned: false, }; // Show PKGBUILD area app.pkgb_visible = true; app.pkgb_text = Some("line1\nline2\nline3".into()); term.draw(|f| { let area = f.area(); super::render_details(f, &mut app, area); }) .expect("failed to draw test terminal"); assert!(app.details_rect.is_some()); assert!(app.url_button_rect.is_some()); assert!(app.pkgb_button_rect.is_some()); assert!(app.pkgb_check_button_rect.is_some()); assert!(app.pkgb_rect.is_some()); assert!(app.mouse_disabled_in_details); } }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false
Firstp1ck/Pacsea
https://github.com/Firstp1ck/Pacsea/blob/c433ad6a837b7985d8b99ba9afd8f07a93d046f4/src/ui/details/layout.rs
src/ui/details/layout.rs
use ratatui::prelude::Rect; use crate::state::{AppState, Focus}; use crate::theme::KeyChord; use std::fmt::Write; /// What: Calculate the number of rows required for the footer/keybinds section. /// /// Inputs: /// - `app`: Application state with keymap, focus, and footer visibility flags /// - `bottom_container`: Rect available for the details pane and footer /// /// Output: /// - Row count (including padding) reserved for footer content when rendered. /// /// Details: /// - Accounts for baseline GLOBALS + focused pane lines and optionally Search Normal Mode help /// while respecting available width in `bottom_container`. pub fn calculate_footer_height(app: &AppState, bottom_container: Rect) -> u16 { // Reserve footer height: baseline lines + optional Normal Mode line // Baseline: always 2 lines visible by default: GLOBALS + currently focused pane let baseline_lines: u16 = 2; // Compute adaptive extra rows for Search Normal Mode footer based on available width let km = &app.keymap; let footer_w: u16 = bottom_container.width.saturating_sub(2); let nm_rows: u16 = if matches!(app.focus, Focus::Search) && app.search_normal_mode { // Build the same labels used in the footer let toggle_label = km .search_normal_toggle .first() .map_or_else(|| "Esc".to_string(), KeyChord::label); let insert_label = km .search_normal_insert .first() .map_or_else(|| "i".to_string(), KeyChord::label); let left_label = km .search_normal_select_left .first() .map_or_else(|| "h".to_string(), KeyChord::label); let right_label = km .search_normal_select_right .first() .map_or_else(|| "l".to_string(), KeyChord::label); let delete_label = km .search_normal_delete .first() .map_or_else(|| "d".to_string(), KeyChord::label); let clear_label = km .search_normal_clear .first() .map_or_else(|| "Shift+Del".to_string(), KeyChord::label); let line1 = format!( "Normal Mode (Focused Search Window): [{toggle_label}/{insert_label}] Insert Mode, [j / k] move, [Ctrl+d / Ctrl+u] page, [{left_label} / {right_label}] Select text, [{delete_label}] Delete text, [{clear_label}] Clear input" ); // Menus and Import/Export on an additional line when present let mut line2 = String::new(); if !km.config_menu_toggle.is_empty() || !km.options_menu_toggle.is_empty() || !km.panels_menu_toggle.is_empty() || (!app.installed_only_mode && (!km.search_normal_import.is_empty() || !km.search_normal_export.is_empty())) { // Menus if !km.config_menu_toggle.is_empty() || !km.options_menu_toggle.is_empty() || !km.panels_menu_toggle.is_empty() { line2.push_str(" • Open Menus: "); if let Some(k) = km.config_menu_toggle.first() { let _ = write!(line2, "[{}] Config", k.label()); } if let Some(k) = km.options_menu_toggle.first() { if !line2.ends_with("menus: ") { line2.push_str(", "); } let _ = write!(line2, "[{}] Options", k.label()); } if let Some(k) = km.panels_menu_toggle.first() { if !line2.ends_with("menus: ") { line2.push_str(", "); } let _ = write!(line2, "[{}] Panels", k.label()); } } // Import / Export if !app.installed_only_mode && (!km.search_normal_import.is_empty() || !km.search_normal_export.is_empty()) { line2.push_str(" • "); if let Some(k) = km.search_normal_import.first() { let _ = write!(line2, "[{}] Import", k.label()); if let Some(k2) = km.search_normal_export.first() { let _ = write!(line2, ", [{}] Export", k2.label()); } } else if let Some(k) = km.search_normal_export.first() { let _ = write!(line2, "[{}] Export", k.label()); } } } let w = if footer_w == 0 { 1 } else { footer_w }; let rows1 = (u16::try_from(line1.len()).unwrap_or(u16::MAX).div_ceil(w)).max(1); let rows2 = if line2.is_empty() { 0 } else { (u16::try_from(line2.len()).unwrap_or(u16::MAX).div_ceil(w)).max(1) }; rows1 + rows2 } else { 0 }; // Calculate required keybinds height let base_help_h: u16 = if app.show_keybinds_footer { baseline_lines } else { 0 }; base_help_h.saturating_add(nm_rows).saturating_add(2) } /// What: Compute layout rectangles for package details, PKGBUILD, comments, and optional footer. /// /// Inputs: /// - `app`: Application state controlling PKGBUILD and comments visibility and footer toggle /// - `bottom_container`: Rect covering the full details section (including footer space) /// - `footer_height`: Height previously reserved for the footer /// /// Output: /// - Tuple of `(content_container, details_area, pkgb_area_opt, comments_area_opt, show_keybinds)` describing splits. /// /// Details: /// - Reserves footer space only when toggled on and space allows /// - When only PKGBUILD visible: Package info 50%, PKGBUILD 50% /// - When only comments visible: Package info 50%, Comments 50% /// - When both visible: Package info 50%, remaining 50% split vertically between PKGBUILD and Comments (25% each) pub fn calculate_layout_areas( app: &AppState, bottom_container: Rect, footer_height: u16, ) -> (Rect, Rect, Option<Rect>, Option<Rect>, bool) { use ratatui::layout::{Constraint, Direction, Layout}; // Minimum height for Package Info content (including borders: 2 lines) const MIN_PACKAGE_INFO_H: u16 = 3; // 1 visible line + 2 borders // Keybinds vanish first: only show if there's enough space for Package Info + Keybinds // Package Info needs at least MIN_PACKAGE_INFO_H, so keybinds only show if: // bottom_container.height >= MIN_PACKAGE_INFO_H + footer_height let show_keybinds = app.show_keybinds_footer && bottom_container.height >= MIN_PACKAGE_INFO_H + footer_height; let help_h: u16 = if show_keybinds { footer_height } else { 0 }; let content_container = Rect { x: bottom_container.x, y: bottom_container.y, width: bottom_container.width, height: bottom_container.height.saturating_sub(help_h), }; let (details_area, pkgb_area_opt, comments_area_opt) = match (app.pkgb_visible, app.comments_visible) { (true, true) => { // Both visible: Package info 50%, PKGBUILD 25%, Comments 25% let split = Layout::default() .direction(Direction::Horizontal) .constraints([ Constraint::Percentage(50), Constraint::Percentage(25), Constraint::Percentage(25), ]) .split(content_container); (split[0], Some(split[1]), Some(split[2])) } (true, false) => { // Only PKGBUILD visible: Package info 50%, PKGBUILD 50% let split = Layout::default() .direction(Direction::Horizontal) .constraints([Constraint::Percentage(50), Constraint::Percentage(50)]) .split(content_container); (split[0], Some(split[1]), None) } (false, true) => { // Only comments visible: Package info 50%, Comments 50% let split = Layout::default() .direction(Direction::Horizontal) .constraints([Constraint::Percentage(50), Constraint::Percentage(50)]) .split(content_container); (split[0], None, Some(split[1])) } (false, false) => { // Neither visible: Package info takes full width (content_container, None, None) } }; ( content_container, details_area, pkgb_area_opt, comments_area_opt, show_keybinds, ) }
rust
MIT
c433ad6a837b7985d8b99ba9afd8f07a93d046f4
2026-01-04T20:14:32.225407Z
false