1use crossterm::event::KeyEvent;
2use tokio::sync::mpsc;
3
4use crate::state::{AppState, PackageItem};
5use std::time::Instant;
6
7#[must_use]
20pub fn matches_any(ke: &KeyEvent, list: &[crate::theme::KeyChord]) -> bool {
21 list.iter().any(|c| {
22 if (c.code, c.mods) == (ke.code, ke.modifiers) {
23 return true;
24 }
25 match (c.code, ke.code) {
26 (crossterm::event::KeyCode::Char(cfg_ch), crossterm::event::KeyCode::Char(ev_ch)) => {
27 let cfg_has_shift = c.mods.contains(crossterm::event::KeyModifiers::SHIFT);
28 if !cfg_has_shift {
29 return false;
30 }
31 if ev_ch == cfg_ch.to_ascii_uppercase() {
33 return true;
34 }
35 if ke.modifiers.contains(crossterm::event::KeyModifiers::SHIFT)
37 && ev_ch.to_ascii_lowercase() == cfg_ch
38 {
39 return true;
40 }
41 false
42 }
43 _ => false,
44 }
45 })
46}
47
48#[must_use]
55pub fn char_count(s: &str) -> usize {
56 s.chars().count()
57}
58
59#[must_use]
67pub fn byte_index_for_char(s: &str, ci: usize) -> usize {
68 let cc = char_count(s);
69 if ci == 0 {
70 return 0;
71 }
72 if ci >= cc {
73 return s.len();
74 }
75 s.char_indices().map(|(i, _)| i).nth(ci).unwrap_or(s.len())
76}
77
78pub fn find_in_recent(app: &mut AppState, forward: bool) {
86 let Some(pattern) = app.pane_find.clone() else {
87 return;
88 };
89 let inds = crate::ui::helpers::filtered_recent_indices(app);
90 if inds.is_empty() {
91 return;
92 }
93 let start = app.history_state.selected().unwrap_or(0);
94 let mut vi = start;
95 let n = inds.len();
96 for _ in 0..n {
97 vi = if forward {
98 (vi + 1) % n
99 } else if vi == 0 {
100 n - 1
101 } else {
102 vi - 1
103 };
104 let i = inds[vi];
105 if let Some(s) = app.recent_value_at(i)
106 && s.to_lowercase().contains(&pattern.to_lowercase())
107 {
108 app.history_state.select(Some(vi));
109 break;
110 }
111 }
112}
113
114pub fn find_in_install(app: &mut AppState, forward: bool) {
122 let Some(pattern) = app.pane_find.clone() else {
123 return;
124 };
125 let inds = crate::ui::helpers::filtered_install_indices(app);
126 if inds.is_empty() {
127 return;
128 }
129 let start = app.install_state.selected().unwrap_or(0);
130 let mut vi = start;
131 let n = inds.len();
132 for _ in 0..n {
133 vi = if forward {
134 (vi + 1) % n
135 } else if vi == 0 {
136 n - 1
137 } else {
138 vi - 1
139 };
140 let i = inds[vi];
141 if let Some(p) = app.install_list.get(i)
142 && (p.name.to_lowercase().contains(&pattern.to_lowercase())
143 || p.description
144 .to_lowercase()
145 .contains(&pattern.to_lowercase()))
146 {
147 app.install_state.select(Some(vi));
148 break;
149 }
150 }
151}
152
153pub fn refresh_selected_details(
161 app: &mut AppState,
162 details_tx: &mpsc::UnboundedSender<PackageItem>,
163) {
164 if let Some(item) = app.results.get(app.selected).cloned() {
165 app.details_scroll = 0;
167 if let Some(cached) = app.details_cache.get(&item.name).cloned() {
168 app.details = cached;
169 } else {
170 let _ = details_tx.send(item);
171 }
172 queue_selected_aur_vote_state_check(app);
173 }
174}
175
176pub fn queue_selected_aur_vote_state_check(app: &mut AppState) {
189 let settings = crate::theme::settings();
190 if !settings.aur_vote_enabled {
191 return;
192 }
193 if !app.aur_vote_state_lookup_supported {
194 return;
195 }
196 let Some(item) = app.results.get(app.selected) else {
197 return;
198 };
199 if !matches!(item.source, crate::state::Source::Aur) {
200 return;
201 }
202
203 let pkgbase = item.name.clone();
204 if let Some(previous) = app.pending_aur_vote_state_request.replace(pkgbase.clone())
205 && previous != pkgbase
206 && matches!(
207 app.aur_vote_state_by_pkgbase.get(&previous),
208 Some(crate::state::app_state::AurVoteStateUi::Loading)
209 )
210 {
211 app.aur_vote_state_by_pkgbase
212 .insert(previous, crate::state::app_state::AurVoteStateUi::Unknown);
213 }
214 let should_mark_loading = !matches!(
215 app.aur_vote_state_by_pkgbase.get(&pkgbase),
216 Some(
217 crate::state::app_state::AurVoteStateUi::Voted
218 | crate::state::app_state::AurVoteStateUi::NotVoted
219 )
220 );
221 if should_mark_loading {
222 app.aur_vote_state_by_pkgbase
223 .insert(pkgbase, crate::state::app_state::AurVoteStateUi::Loading);
224 }
225}
226
227pub fn move_sel_cached_with_vote_state(
242 app: &mut AppState,
243 delta: isize,
244 details_tx: &mpsc::UnboundedSender<PackageItem>,
245 comments_tx: &mpsc::UnboundedSender<String>,
246) {
247 crate::logic::move_sel_cached(app, delta, details_tx, comments_tx);
248 queue_selected_aur_vote_state_check(app);
249}
250
251pub fn move_news_selection(app: &mut AppState, delta: isize) {
253 if app.news_results.is_empty() {
254 app.news_selected = 0;
255 app.news_list_state.select(None);
256 app.details.url.clear();
257 return;
258 }
259 let len = app.news_results.len();
260 if app.news_selected >= len {
261 app.news_selected = len.saturating_sub(1);
262 }
263 app.news_list_state.select(Some(app.news_selected));
264 let steps = delta.unsigned_abs();
265 for _ in 0..steps {
266 if delta.is_negative() {
267 app.news_list_state.select_previous();
268 } else {
269 app.news_list_state.select_next();
270 }
271 }
272 let sel = app.news_list_state.selected().unwrap_or(0);
273 app.news_selected = std::cmp::min(sel, len.saturating_sub(1));
274 app.news_list_state.select(Some(app.news_selected));
275 update_news_url(app);
276}
277
278#[must_use]
297pub fn compute_updates_modal_scroll_for_selection(
298 entry_line_starts: &[u16],
299 total_lines: u16,
300 content_rect: Option<(u16, u16, u16, u16)>,
301 selected: usize,
302 total_items: usize,
303 _current_scroll: u16,
304) -> u16 {
305 let selected_line = entry_line_starts
306 .get(selected)
307 .copied()
308 .unwrap_or_else(|| u16::try_from(selected).unwrap_or(u16::MAX));
309 let visible_lines = content_rect.map_or(1, |(_, _, _, h)| h.max(1));
310 let half = visible_lines / 2;
311 let ideal = selected_line.saturating_sub(half);
312
313 let fallback_total = u16::try_from(total_items).unwrap_or(u16::MAX);
314 let max_scroll = total_lines
315 .max(fallback_total)
316 .saturating_sub(visible_lines);
317 ideal.min(max_scroll)
318}
319
320#[must_use]
334pub fn compute_updates_filtered_indices(
335 entries: &[(String, String, String)],
336 query: &str,
337) -> Vec<usize> {
338 let normalized = query.trim();
339 if normalized.is_empty() {
340 return (0..entries.len()).collect();
341 }
342
343 let query_lower = normalized.to_lowercase();
344
345 entries
346 .iter()
347 .enumerate()
348 .filter_map(|(idx, (name, _, _))| {
349 let source_label = if crate::index::find_package_by_name(name).is_some() {
350 "pacman"
351 } else {
352 "aur"
353 };
354 let name_lower = name.to_lowercase();
355 let matches_name = crate::util::fuzzy_match_rank(&name_lower, &query_lower).is_some();
356 let matches_source =
357 crate::util::fuzzy_match_rank(source_label, &query_lower).is_some();
358 if matches_name || matches_source {
359 Some(idx)
360 } else {
361 None
362 }
363 })
364 .collect()
365}
366
367pub fn update_news_url(app: &mut AppState) {
370 if let Some(item) = app.news_results.get(app.news_selected)
371 && let Some(url) = &item.url
372 {
373 app.details.url.clone_from(url);
374 let mut cached = app.news_content_cache.get(url).cloned();
376 if let Some(ref c) = cached
377 && url.contains("://archlinux.org/packages/")
378 && !c.starts_with("Package Info:")
379 {
380 cached = None;
382 tracing::debug!(
383 url,
384 "news content cache missing package metadata; will refetch"
385 );
386 }
387 app.news_content = cached;
388 if app.news_content.is_some() {
389 tracing::debug!(url, "news content served from cache");
390 } else {
391 app.news_content_debounce_timer = Some(std::time::Instant::now());
393 tracing::debug!(url, "news content not cached, setting debounce timer");
394 }
395 app.news_content_scroll = 0;
396 } else {
397 app.details.url.clear();
398 app.news_content = None;
399 app.news_content_debounce_timer = None;
400 }
401 app.news_content_loading = false;
402}
403
404pub fn maybe_request_news_content(
407 app: &mut AppState,
408 news_content_req_tx: &mpsc::UnboundedSender<String>,
409) {
410 if !matches!(app.app_mode, crate::state::types::AppMode::News) {
412 tracing::trace!("news_content: skip request, not in news mode");
413 return;
414 }
415 if app.news_content_loading {
416 tracing::debug!(
417 selected = app.news_selected,
418 "news_content: skip request, already loading"
419 );
420 return;
421 }
422 if let Some(item) = app.news_results.get(app.news_selected)
423 && let Some(url) = &item.url
424 && app.news_content.is_none()
425 && !app.news_content_cache.contains_key(url)
426 {
427 const DEBOUNCE_DELAY_MS: u64 = 500;
431 if let Some(timer) = app.news_content_debounce_timer {
432 #[allow(clippy::cast_possible_truncation)]
434 let elapsed = timer.elapsed().as_millis() as u64;
435 if elapsed < DEBOUNCE_DELAY_MS {
436 tracing::trace!(
438 selected = app.news_selected,
439 url,
440 elapsed_ms = elapsed,
441 remaining_ms = DEBOUNCE_DELAY_MS - elapsed,
442 "news_content: debounce timer not expired, waiting"
443 );
444 return;
445 }
446 app.news_content_debounce_timer = None;
448 } else {
449 app.news_content_debounce_timer = Some(std::time::Instant::now());
451 tracing::debug!(
452 selected = app.news_selected,
453 url,
454 "news_content: no debounce timer, setting one now"
455 );
456 return;
457 }
458
459 app.news_content_loading = true;
460 app.news_content_loading_since = Some(Instant::now());
461 tracing::debug!(
462 selected = app.news_selected,
463 title = item.title,
464 url,
465 "news_content: requesting article content (debounce expired)"
466 );
467 if let Err(e) = news_content_req_tx.send(url.clone()) {
468 tracing::warn!(
469 error = %e,
470 selected = app.news_selected,
471 title = item.title,
472 url,
473 "news_content: failed to enqueue content request"
474 );
475 app.news_content_loading = false;
476 app.news_content_loading_since = None;
477 app.news_content = Some(format!("Failed to load content: {e}"));
478 app.toast_message = Some("News content request failed".to_string());
479 app.toast_expires_at = Some(Instant::now() + std::time::Duration::from_secs(3));
480 }
481 } else {
482 tracing::trace!(
483 selected = app.news_selected,
484 has_item = app.news_results.get(app.news_selected).is_some(),
485 has_url = app
486 .news_results
487 .get(app.news_selected)
488 .and_then(|it| it.url.as_ref())
489 .is_some(),
490 content_cached = app
491 .news_results
492 .get(app.news_selected)
493 .and_then(|it| it.url.as_ref())
494 .is_some_and(|u| app.news_content_cache.contains_key(u)),
495 has_content = app.news_content.is_some(),
496 "news_content: skip request (cached/absent URL/already loaded)"
497 );
498 }
499}
500
501pub fn refresh_install_details(
509 app: &mut AppState,
510 details_tx: &mpsc::UnboundedSender<PackageItem>,
511) {
512 let Some(vsel) = app.install_state.selected() else {
513 return;
514 };
515 let inds = crate::ui::helpers::filtered_install_indices(app);
516 if inds.is_empty() || vsel >= inds.len() {
517 return;
518 }
519 let i = inds[vsel];
520 if let Some(item) = app.install_list.get(i).cloned() {
521 app.details_scroll = 0;
523 app.details_focus = Some(item.name.clone());
525
526 app.details.name.clone_from(&item.name);
528 app.details.version.clone_from(&item.version);
529 app.details.description.clear();
530 match &item.source {
531 crate::state::Source::Official { repo, arch } => {
532 app.details.repository.clone_from(repo);
533 app.details.architecture.clone_from(arch);
534 }
535 crate::state::Source::Aur => {
536 app.details.repository = "AUR".to_string();
537 app.details.architecture = "any".to_string();
538 }
539 }
540
541 if let Some(cached) = app.details_cache.get(&item.name).cloned() {
542 app.details = cached;
543 } else {
544 let _ = details_tx.send(item);
545 }
546 }
547}
548
549pub fn refresh_remove_details(app: &mut AppState, details_tx: &mpsc::UnboundedSender<PackageItem>) {
557 let Some(vsel) = app.remove_state.selected() else {
558 return;
559 };
560 if app.remove_list.is_empty() || vsel >= app.remove_list.len() {
561 return;
562 }
563 if let Some(item) = app.remove_list.get(vsel).cloned() {
564 app.details_scroll = 0;
566 app.details_focus = Some(item.name.clone());
567 app.details.name.clone_from(&item.name);
568 app.details.version.clone_from(&item.version);
569 app.details.description.clear();
570 match &item.source {
571 crate::state::Source::Official { repo, arch } => {
572 app.details.repository.clone_from(repo);
573 app.details.architecture.clone_from(arch);
574 }
575 crate::state::Source::Aur => {
576 app.details.repository = "AUR".to_string();
577 app.details.architecture = "any".to_string();
578 }
579 }
580 if let Some(cached) = app.details_cache.get(&item.name).cloned() {
581 app.details = cached;
582 } else {
583 let _ = details_tx.send(item);
584 }
585 }
586}
587
588pub fn refresh_downgrade_details(
596 app: &mut AppState,
597 details_tx: &mpsc::UnboundedSender<PackageItem>,
598) {
599 let Some(vsel) = app.downgrade_state.selected() else {
600 return;
601 };
602 if app.downgrade_list.is_empty() || vsel >= app.downgrade_list.len() {
603 return;
604 }
605 if let Some(item) = app.downgrade_list.get(vsel).cloned() {
606 app.details_scroll = 0;
608 app.details_focus = Some(item.name.clone());
609 app.details.name.clone_from(&item.name);
610 app.details.version.clone_from(&item.version);
611 app.details.description.clear();
612 match &item.source {
613 crate::state::Source::Official { repo, arch } => {
614 app.details.repository.clone_from(repo);
615 app.details.architecture.clone_from(arch);
616 }
617 crate::state::Source::Aur => {
618 app.details.repository = "AUR".to_string();
619 app.details.architecture = "any".to_string();
620 }
621 }
622 if let Some(cached) = app.details_cache.get(&item.name).cloned() {
623 app.details = cached;
624 } else {
625 let _ = details_tx.send(item);
626 }
627 }
628}
629
630#[cfg(test)]
631mod tests {
632 use super::*;
633
634 fn new_app() -> AppState {
645 AppState::default()
646 }
647
648 #[test]
649 fn char_count_basic() {
660 assert_eq!(char_count("abc"), 3);
661 assert_eq!(char_count("π"), 1);
662 assert_eq!(char_count("aπb"), 3);
663 }
664
665 #[test]
666 fn byte_index_for_char_basic() {
677 let s = "aπb";
678 assert_eq!(byte_index_for_char(s, 0), 0);
679 assert_eq!(byte_index_for_char(s, 1), 1);
680 assert_eq!(byte_index_for_char(s, 2), 1 + "π".len());
681 assert_eq!(byte_index_for_char(s, 3), s.len());
682 }
683
684 #[test]
685 fn find_in_recent_basic() {
696 let mut app = new_app();
697 app.load_recent_items(&["alpha".to_string(), "beta".to_string(), "gamma".to_string()]);
698 app.pane_find = Some("a".into());
699 app.history_state.select(Some(0));
700 find_in_recent(&mut app, true);
701 assert!(app.history_state.selected().is_some());
702 }
703
704 #[test]
705 fn find_in_install_basic() {
716 let mut app = new_app();
717 app.install_list = vec![
718 crate::state::PackageItem {
719 name: "ripgrep".into(),
720 version: "1".into(),
721 description: "fast search".into(),
722 source: crate::state::Source::Aur,
723 popularity: None,
724 out_of_date: None,
725 orphaned: false,
726 },
727 crate::state::PackageItem {
728 name: "fd".into(),
729 version: "1".into(),
730 description: "find".into(),
731 source: crate::state::Source::Aur,
732 popularity: None,
733 out_of_date: None,
734 orphaned: false,
735 },
736 ];
737 app.pane_find = Some("rip".into());
738 app.install_state.select(Some(1));
740 find_in_install(&mut app, true);
741 assert_eq!(app.install_state.selected(), Some(0));
742 }
743
744 #[test]
745 fn refresh_selected_details_requests_when_missing() {
756 let mut app = new_app();
757 app.results = vec![crate::state::PackageItem {
758 name: "rg".into(),
759 version: "1".into(),
760 description: String::new(),
761 source: crate::state::Source::Aur,
762 popularity: None,
763 out_of_date: None,
764 orphaned: false,
765 }];
766 app.selected = 0;
767 let (tx, mut rx) = mpsc::unbounded_channel();
768 refresh_selected_details(&mut app, &tx);
769 let got = rx.try_recv().ok();
770 assert!(got.is_some());
771 }
772
773 #[test]
774 fn queue_vote_state_check_skips_when_lookup_unsupported() {
786 let mut app = new_app();
787 app.results = vec![crate::state::PackageItem {
788 name: "pacsea-bin".into(),
789 version: "1".into(),
790 description: String::new(),
791 source: crate::state::Source::Aur,
792 popularity: None,
793 out_of_date: None,
794 orphaned: false,
795 }];
796 app.selected = 0;
797 app.aur_vote_state_lookup_supported = false;
798 app.aur_vote_state_by_pkgbase.insert(
799 "pacsea-bin".into(),
800 crate::state::app_state::AurVoteStateUi::Voted,
801 );
802
803 queue_selected_aur_vote_state_check(&mut app);
804
805 assert!(app.pending_aur_vote_state_request.is_none());
806 assert!(matches!(
807 app.aur_vote_state_by_pkgbase.get("pacsea-bin"),
808 Some(crate::state::app_state::AurVoteStateUi::Voted)
809 ));
810 }
811
812 #[test]
813 fn queue_vote_state_check_preserves_stable_cached_state() {
824 let mut app = new_app();
825 app.results = vec![crate::state::PackageItem {
826 name: "pacsea-bin".into(),
827 version: "1".into(),
828 description: String::new(),
829 source: crate::state::Source::Aur,
830 popularity: None,
831 out_of_date: None,
832 orphaned: false,
833 }];
834 app.selected = 0;
835 app.aur_vote_state_by_pkgbase.insert(
836 "pacsea-bin".into(),
837 crate::state::app_state::AurVoteStateUi::Voted,
838 );
839
840 queue_selected_aur_vote_state_check(&mut app);
841
842 assert_eq!(
843 app.pending_aur_vote_state_request,
844 Some("pacsea-bin".to_string())
845 );
846 assert!(matches!(
847 app.aur_vote_state_by_pkgbase.get("pacsea-bin"),
848 Some(crate::state::app_state::AurVoteStateUi::Voted)
849 ));
850 }
851
852 #[test]
853 fn updates_scroll_fallback_visible_lines_when_rect_missing() {
864 let scroll = compute_updates_modal_scroll_for_selection(&[0, 3, 5], 7, None, 1, 3, 0);
865 assert_eq!(scroll, 3);
866 }
867
868 #[test]
869 fn updates_scroll_handles_tiny_viewport_heights() {
880 let height_one = Some((0, 0, 40, 1));
881 let scroll_one =
882 compute_updates_modal_scroll_for_selection(&[0, 3, 5], 7, height_one, 1, 3, 0);
883 assert_eq!(scroll_one, 3);
884
885 let height_two = Some((0, 0, 40, 2));
886 let scroll_two =
887 compute_updates_modal_scroll_for_selection(&[0, 3, 5], 7, height_two, 2, 3, 0);
888 assert_eq!(scroll_two, 4);
889 }
890
891 #[test]
892 fn updates_scroll_centers_selection_in_viewport() {
903 let starts: Vec<u16> = (0..10).collect();
904 let rect = Some((0, 0, 40, 5));
905 let scroll = compute_updates_modal_scroll_for_selection(&starts, 10, rect, 4, 10, 0);
906 assert_eq!(scroll, 2);
907 }
908
909 #[test]
910 fn updates_scroll_clamps_to_zero_when_viewport_exceeds_total() {
921 let large_rect = Some((0, 0, 40, 20));
922 let scroll =
923 compute_updates_modal_scroll_for_selection(&[0, 3, 5], 7, large_rect, 2, 3, 10);
924 assert_eq!(scroll, 0);
925 }
926
927 #[test]
928 fn updates_filter_returns_all_indices_for_empty_query() {
939 let entries = vec![
940 ("ripgrep".to_string(), "13".to_string(), "14".to_string()),
941 ("fd".to_string(), "8".to_string(), "9".to_string()),
942 ("bat".to_string(), "1".to_string(), "2".to_string()),
943 ];
944 let indices = compute_updates_filtered_indices(&entries, "");
945 assert_eq!(indices, vec![0, 1, 2]);
946 }
947
948 #[test]
949 fn updates_filter_matches_package_name_fuzzy_case_insensitive() {
960 let entries = vec![
961 ("ripgrep".to_string(), "13".to_string(), "14".to_string()),
962 ("fd".to_string(), "8".to_string(), "9".to_string()),
963 ];
964 let indices = compute_updates_filtered_indices(&entries, "RG");
965 assert_eq!(indices, vec![0]);
966 }
967
968 #[test]
969 fn updates_filter_matches_source_label() {
980 let entries = vec![
981 (
982 "pacsea-bin".to_string(),
983 "0.9".to_string(),
984 "1.0".to_string(),
985 ),
986 (
987 "pacsea-git".to_string(),
988 "0.9".to_string(),
989 "1.0".to_string(),
990 ),
991 ];
992 let indices = compute_updates_filtered_indices(&entries, "aur");
993 assert!(
994 !indices.is_empty(),
995 "expected at least one AUR package available in fixture"
996 );
997 for idx in indices {
998 let (name, _, _) = &entries[idx];
999 assert!(crate::index::find_package_by_name(name).is_none());
1000 }
1001 }
1002}