-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathapp.rs
More file actions
2049 lines (1873 loc) · 72.7 KB
/
app.rs
File metadata and controls
2049 lines (1873 loc) · 72.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use ratatui::layout::Rect;
use ratatui::widgets::TableState;
use crate::backend::WingetBackend;
use crate::config::Config;
use crate::models::{
OpResult, Operation, Package, PackageDetail, PackagePin, PinFilter, SortDir, SortField,
SourceFilter,
};
/// Stores UI layout regions for mouse hit-testing
#[derive(Debug, Default, Clone)]
pub struct LayoutRegions {
pub tab_bar: Rect,
pub search_bar: Rect,
pub package_list: Rect,
pub detail_panel: Rect,
/// Y offset where the first data row starts in the package list (after header + border)
pub list_content_y: u16,
/// Tab click regions: (start_x, end_x, mode)
pub tab_regions: Vec<(u16, u16, AppMode)>,
}
/// Which panel currently has keyboard focus
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum FocusZone {
PackageList,
DetailPanel,
}
impl FocusZone {
pub fn toggle(self) -> Self {
match self {
Self::PackageList => Self::DetailPanel,
Self::DetailPanel => Self::PackageList,
}
}
}
/// Messages sent from background tasks back to the UI
#[derive(Debug)]
pub enum AppMessage {
PackagesLoaded {
generation: u64,
packages: Vec<Package>,
},
DetailLoaded {
generation: u64,
detail: PackageDetail,
},
OperationComplete(OpResult),
StatusUpdate(String),
Error(String),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AppMode {
Search,
Installed,
Upgrades,
}
impl AppMode {
pub fn cycle(&self) -> Self {
match self {
Self::Search => Self::Installed,
Self::Installed => Self::Upgrades,
Self::Upgrades => Self::Search,
}
}
pub fn cycle_back(&self) -> Self {
match self {
Self::Search => Self::Upgrades,
Self::Installed => Self::Search,
Self::Upgrades => Self::Installed,
}
}
#[allow(dead_code)]
pub fn label(&self) -> &'static str {
match self {
Self::Search => "Search",
Self::Installed => "Installed",
Self::Upgrades => "Upgrades",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum InputMode {
Normal,
Search,
/// Inline prompt for typing a specific version before installing
VersionInput,
/// In-memory filtering for Installed/Upgrades views using the existing list.
LocalFilter,
}
/// Confirmation dialog state
#[derive(Debug, Clone)]
pub struct ConfirmDialog {
pub message: String,
pub operation: Operation,
}
pub struct App {
pub mode: AppMode,
pub input_mode: InputMode,
pub focus: FocusZone,
pub source_filter: SourceFilter,
pub pin_filter: PinFilter,
pub search_query: String,
pub local_filter: String,
pub packages: Vec<Package>,
pub filtered_packages: Vec<Package>,
pub selected: usize,
pub detail: Option<PackageDetail>,
pub detail_loading: bool,
pub status_message: String,
pub loading: bool,
pub confirm: Option<ConfirmDialog>,
/// Version string being edited in the VersionInput prompt
pub version_input: String,
pub show_help: bool,
pub should_quit: bool,
pub layout: LayoutRegions,
/// Sort field for the package list table.
pub sort_field: SortField,
/// Sort direction for the package list table.
pub sort_dir: SortDir,
/// Persistent table widget state (preserves viewport offset across frames)
pub table_state: TableState,
/// Scroll offset of the detail panel (in rendered lines)
pub detail_scroll: usize,
/// Total rendered line count of the detail panel (set during rendering)
pub detail_content_lines: usize,
/// Tick counter for animations (spinner, etc.)
pub tick: usize,
/// Incremented on each view refresh; stale results are discarded
pub view_generation: u64,
/// Incremented on each detail load; stale results are discarded
pub detail_generation: u64,
/// Cache of package details to avoid repeated winget show calls
pub detail_cache: HashMap<String, PackageDetail>,
/// Indices into filtered_packages that are selected for batch operations
pub selected_packages: HashSet<usize>,
/// A high-signal status message to restore after the next list refresh completes.
pub post_refresh_status: Option<String>,
pub backend: Arc<dyn WingetBackend>,
pub message_tx: tokio::sync::mpsc::UnboundedSender<AppMessage>,
pub message_rx: tokio::sync::mpsc::UnboundedReceiver<AppMessage>,
}
/// Compare two package version strings numerically, component by component.
///
/// Version strings are split on `.`, `-`, and `+`. Each component is compared
/// numerically when both sides parse as `u64`; otherwise lexicographically.
/// This avoids the lexicographic pitfall where `"10.0"` sorts before `"2.0"`.
#[derive(Debug, Clone, Eq, PartialEq)]
struct VersionPart {
num: Option<u64>,
src: String,
}
impl Ord for VersionPart {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
match (self.num, other.num) {
(Some(left), Some(right)) => left.cmp(&right),
_ => self.src.cmp(&other.src),
}
}
}
impl PartialOrd for VersionPart {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
fn version_key(v: &str) -> Vec<VersionPart> {
v.split(['.', '-', '+'])
.map(|part| VersionPart {
num: part.parse::<u64>().ok(),
src: part.to_string(),
})
.collect()
}
#[cfg(test)]
fn compare_versions(a: &str, b: &str) -> std::cmp::Ordering {
version_key(a).cmp(&version_key(b))
}
impl App {
fn annotate_pins(packages: &mut [Package], pins: Vec<PackagePin>) {
let pin_map: HashMap<String, _> = pins
.into_iter()
.map(|pin| (pin.id, pin.pin_state))
.collect();
for pkg in packages {
if let Some(pin_state) = pin_map.get(&pkg.id) {
pkg.pin_state = pin_state.clone();
}
}
}
pub fn new(backend: Arc<dyn WingetBackend>, cfg: Config) -> Self {
let (message_tx, message_rx) = tokio::sync::mpsc::unbounded_channel();
Self {
mode: cfg.default_view,
input_mode: InputMode::Normal,
focus: FocusZone::PackageList,
source_filter: cfg.default_source,
pin_filter: PinFilter::All,
search_query: String::new(),
local_filter: String::new(),
packages: Vec::new(),
filtered_packages: Vec::new(),
selected: 0,
detail: None,
detail_loading: false,
status_message: "Loading...".to_string(),
loading: false,
confirm: None,
version_input: String::new(),
show_help: false,
should_quit: false,
layout: LayoutRegions::default(),
sort_field: SortField::None,
sort_dir: SortDir::Asc,
table_state: TableState::default(),
detail_scroll: 0,
detail_content_lines: 0,
tick: 0,
view_generation: 0,
detail_generation: 0,
detail_cache: HashMap::new(),
selected_packages: HashSet::new(),
post_refresh_status: None,
backend,
message_tx,
message_rx,
}
}
pub fn apply_filter(&mut self) {
// When a source filter is active, winget already filters server-side
// (and omits the Source column), so accept all returned packages.
// Backfill the source field when winget omitted it (single-source query).
self.filtered_packages = self.packages.clone();
if let Some(src) = self.source_filter.as_arg() {
for pkg in &mut self.filtered_packages {
if pkg.source.is_empty() {
pkg.source = src.to_string();
}
}
}
if self.mode != AppMode::Search && !self.local_filter.is_empty() {
let query = self.local_filter.to_lowercase();
self.filtered_packages.retain(|pkg| {
pkg.name.to_lowercase().contains(&query) || pkg.id.to_lowercase().contains(&query)
});
}
if self.mode != AppMode::Search {
self.filtered_packages
.retain(|pkg| self.pin_filter.matches(&pkg.pin_state));
}
// Apply sort if a field is selected.
// sort_by_cached_key computes the key exactly once per element (O(N))
// rather than on every comparison (O(N log N)), avoiding repeated heap
// allocations from to_lowercase() for Name and Id sorts.
match self.sort_field {
SortField::None => {}
SortField::Name => {
self.filtered_packages
.sort_by_cached_key(|p| p.name.to_lowercase());
if self.sort_dir == SortDir::Desc {
self.filtered_packages.reverse();
}
}
SortField::Id => {
self.filtered_packages
.sort_by_cached_key(|p| p.id.to_lowercase());
if self.sort_dir == SortDir::Desc {
self.filtered_packages.reverse();
}
}
SortField::Version => {
self.filtered_packages
.sort_by_cached_key(|pkg| version_key(&pkg.version));
if self.sort_dir == SortDir::Desc {
self.filtered_packages.reverse();
}
}
}
// Keep selection in bounds
if self.selected >= self.filtered_packages.len() {
self.selected = self.filtered_packages.len().saturating_sub(1);
}
// Clear multi-select since indices are now stale
self.selected_packages.clear();
}
pub fn selected_package(&self) -> Option<&Package> {
self.filtered_packages.get(self.selected)
}
pub fn move_selection(&mut self, delta: isize) {
if self.filtered_packages.is_empty() {
return;
}
let len = self.filtered_packages.len() as isize;
let new = (self.selected as isize + delta).rem_euclid(len);
self.selected = new as usize;
self.ensure_selection_visible();
}
/// Number of package rows visible in the rendered package table.
pub fn package_list_viewport_rows(&self) -> usize {
// Border top + top padding + header row + border bottom.
self.layout.package_list.height.saturating_sub(4) as usize
}
/// Adjust the table viewport offset so the selected row is visible.
pub fn ensure_selection_visible(&mut self) {
let viewport_rows = self.package_list_viewport_rows();
if viewport_rows == 0 {
return;
}
let offset = self.table_state.offset();
if self.selected < offset {
*self.table_state.offset_mut() = self.selected;
} else if self.selected >= offset + viewport_rows {
*self.table_state.offset_mut() = self.selected - viewport_rows + 1;
}
}
/// Scroll the detail panel by `delta` lines, clamped to valid range.
pub fn scroll_detail(&mut self, delta: isize) {
let viewport = self.layout.detail_panel.height.saturating_sub(3) as usize;
let max = self.detail_content_lines.saturating_sub(viewport);
self.detail_scroll = (self.detail_scroll as isize + delta).clamp(0, max as isize) as usize;
}
pub fn set_status(&mut self, msg: impl Into<String>) {
self.status_message = msg.into();
}
/// Advance through sort states: None → Name↑ → Name↓ → ID↑ → ID↓ → Version↑ → Version↓ → None → …
pub fn cycle_sort(&mut self) {
use crate::models::{SortDir, SortField};
let (next_field, next_dir) = match (self.sort_field, self.sort_dir) {
(SortField::None, _) => (SortField::Name, SortDir::Asc),
(SortField::Name, SortDir::Asc) => (SortField::Name, SortDir::Desc),
(SortField::Name, SortDir::Desc) => (SortField::Id, SortDir::Asc),
(SortField::Id, SortDir::Asc) => (SortField::Id, SortDir::Desc),
(SortField::Id, SortDir::Desc) => (SortField::Version, SortDir::Asc),
(SortField::Version, SortDir::Asc) => (SortField::Version, SortDir::Desc),
(SortField::Version, SortDir::Desc) => (SortField::None, SortDir::Asc),
};
self.sort_field = next_field;
self.sort_dir = next_dir;
self.apply_filter();
let label = match self.sort_field {
SortField::None => "Sort: none".to_string(),
f => format!("Sort: {}{}", f, self.sort_dir.indicator()),
};
self.set_status(label);
}
pub fn cycle_pin_filter(&mut self) {
self.pin_filter = self.pin_filter.cycle();
self.selected = 0;
self.apply_filter();
self.ensure_selection_visible();
self.set_status(format!("{}", self.pin_filter));
}
pub fn spinner(&self) -> char {
const FRAMES: &[char] = &['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
FRAMES[self.tick % FRAMES.len()]
}
fn ensure_detail_hint(detail: &mut PackageDetail) {
if !detail.description.is_empty()
|| !detail.publisher.is_empty()
|| !detail.homepage.is_empty()
|| !detail.license.is_empty()
{
return;
}
let source = if detail.source.is_empty() {
"the configured winget sources"
} else if detail.source.eq_ignore_ascii_case("local") {
"local install records"
} else {
"the package manifest"
};
detail.description =
format!("Additional metadata is not available from {source} for this package.");
}
pub fn refresh_view(&mut self) {
self.view_generation += 1;
let generation = self.view_generation;
let backend = self.backend.clone();
let tx = self.message_tx.clone();
let mode = self.mode;
let query = self.search_query.clone();
let source_arg = self.source_filter.as_arg();
tokio::spawn(async move {
let result = match mode {
AppMode::Search => {
if query.is_empty() {
Ok(Vec::new())
} else {
backend.search(&query, source_arg).await
}
}
AppMode::Installed => backend.list_installed(source_arg).await,
AppMode::Upgrades => backend.list_upgrades(source_arg).await,
};
match result {
Ok(mut packages) => {
if mode != AppMode::Search {
match backend.list_pins().await {
Ok(pins) => Self::annotate_pins(&mut packages, pins),
Err(e) => {
let _ = tx.send(AppMessage::StatusUpdate(format!(
"Pin info unavailable: {}",
e
)));
}
}
}
let _ = tx.send(AppMessage::PackagesLoaded {
generation,
packages,
});
}
Err(e) => {
let _ = tx.send(AppMessage::Error(e.to_string()));
}
}
});
}
pub fn load_detail(&mut self, id: &str) {
// Always increment generation to invalidate any in-flight detail requests.
self.detail_generation += 1;
// Return cached detail immediately if available
if let Some(cached) = self.detail_cache.get(id) {
self.detail = Some(cached.clone());
self.detail_loading = false;
return;
}
// Determine if this package can be looked up via `winget show --exact`.
// Truncated IDs, ARP entries, and MSIX sideloads have no manifest so the
// call would always fail. Show a local detail stub instead.
let is_truncated = id.ends_with('…') || id.ends_with("...");
let is_local = id.starts_with("ARP\\") || id.starts_with("MSIX\\");
let pkg_source_empty = self
.filtered_packages
.iter()
.find(|p| p.id == id)
.is_some_and(|p| p.source.is_empty());
if is_truncated || is_local || pkg_source_empty {
if let Some(pkg) = self.filtered_packages.iter().find(|p| p.id == id) {
let kind = if is_truncated {
"Package ID was truncated by winget"
} else if id.starts_with("ARP\\") {
"Installed via Windows registry (Add/Remove Programs)"
} else if id.starts_with("MSIX\\") {
"Installed as an MSIX/AppX package"
} else {
"Installed locally (not from a winget source)"
};
let detail = PackageDetail {
id: pkg.id.clone(),
name: pkg.name.clone(),
version: pkg.version.clone(),
source: if pkg.source.is_empty() {
"local".to_string()
} else {
pkg.source.clone()
},
pin_state: pkg.pin_state.clone(),
description: format!(
"{}\n\n\
This package has no manifest in any configured winget source. \
Detailed metadata (publisher, homepage, license) is not available.\n\n\
To manage this package, use its original installer or \
the Windows Settings > Apps panel.",
kind
),
..PackageDetail::default()
};
self.detail_cache.insert(id.to_string(), detail.clone());
self.detail = Some(detail);
}
self.detail_loading = false;
return;
}
// Pre-populate from Package list data for instant feedback
if let Some(pkg) = self.filtered_packages.iter().find(|p| p.id == id) {
self.detail = Some(PackageDetail {
id: pkg.id.clone(),
name: pkg.name.clone(),
version: pkg.version.clone(),
source: pkg.source.clone(),
pin_state: pkg.pin_state.clone(),
..PackageDetail::default()
});
}
self.detail_loading = true;
let generation = self.detail_generation;
let backend = self.backend.clone();
let tx = self.message_tx.clone();
let id = id.to_string();
tokio::spawn(async move {
match backend.show(&id).await {
Ok(detail) => {
let _ = tx.send(AppMessage::DetailLoaded { generation, detail });
}
Err(e) => {
let _ = tx.send(AppMessage::Error(e.to_string()));
}
}
});
}
pub fn execute_operation(&self, op: Operation) {
let backend = self.backend.clone();
let tx = self.message_tx.clone();
tokio::spawn(async move {
let result = match &op {
Operation::Install { id, version } => backend.install(id, version.as_deref()).await,
Operation::Uninstall { id } => backend.uninstall(id).await,
Operation::Upgrade { id } => backend.upgrade(id).await,
Operation::Pin { id } => backend.pin(id).await,
Operation::Unpin { id } => backend.unpin(id).await,
Operation::BatchUpgrade { ids } => {
// Execute sequentially to avoid Windows Installer conflicts
let total = ids.len();
let mut failures: Vec<String> = Vec::new();
for (i, id) in ids.iter().enumerate() {
let _ = tx.send(AppMessage::StatusUpdate(format!(
"Upgrading {}/{}: {}...",
i + 1,
total,
id
)));
if let Err(e) = backend.upgrade(id).await {
failures.push(format!("{}: {}", id, e));
}
}
if failures.is_empty() {
Ok(format!("All {} packages upgraded successfully", total))
} else {
Err(anyhow::anyhow!(
"{}/{} succeeded, {} failed: {}",
total - failures.len(),
total,
failures.len(),
failures.join("; ")
))
}
}
};
let op_result = match result {
Ok(msg) => OpResult {
operation: op,
success: true,
message: msg,
},
Err(e) => OpResult {
operation: op,
success: false,
message: e.to_string(),
},
};
let _ = tx.send(AppMessage::OperationComplete(op_result));
});
}
/// Export the currently visible package list to a CSV file in the working directory.
pub fn export_list_csv(&self) -> Result<String, String> {
if self.filtered_packages.is_empty() {
return Err("Nothing to export: list is empty".to_string());
}
let filename = match self.mode {
AppMode::Installed => "winget-installed.csv",
AppMode::Upgrades => "winget-upgrades.csv",
AppMode::Search => "winget-search.csv",
};
let file = std::fs::File::create(filename)
.map_err(|e| format!("Cannot create {filename}: {e}"))?;
let mut writer = std::io::BufWriter::new(file);
let include_available = self.mode == AppMode::Upgrades;
self.write_csv(&mut writer, include_available)
.map_err(|e| format!("Cannot write {filename}: {e}"))?;
Ok(filename.to_string())
}
fn write_csv(
&self,
writer: &mut dyn std::io::Write,
include_available: bool,
) -> std::io::Result<()> {
if include_available {
writeln!(writer, "Name,Id,Version,Source,AvailableVersion")?;
} else {
writeln!(writer, "Name,Id,Version,Source")?;
}
for pkg in &self.filtered_packages {
if include_available {
writeln!(
writer,
"{},{},{},{},{}",
csv_escape(&pkg.name),
csv_escape(&pkg.id),
csv_escape(&pkg.version),
csv_escape(&pkg.source),
csv_escape(&pkg.available_version)
)?;
} else {
writeln!(
writer,
"{},{},{},{}",
csv_escape(&pkg.name),
csv_escape(&pkg.id),
csv_escape(&pkg.version),
csv_escape(&pkg.source)
)?;
}
}
Ok(())
}
pub fn process_messages(&mut self) {
while let Ok(msg) = self.message_rx.try_recv() {
match msg {
AppMessage::PackagesLoaded {
generation,
packages,
} => {
// Discard stale results from a previous view/search
if generation < self.view_generation {
continue;
}
// Remember the currently selected package so we can
// re-anchor the cursor after the list is replaced.
let prev_id = self.selected_package().map(|p| p.id.clone());
self.packages = packages;
self.apply_filter();
// Restore cursor to the same package (if it is still present)
// so that pressing 'r' to refresh does not jump the cursor.
if let Some(id) = prev_id {
if let Some(idx) = self.filtered_packages.iter().position(|p| p.id == id) {
self.selected = idx;
self.ensure_selection_visible();
}
}
self.loading = false;
let count = self.filtered_packages.len();
if let Some(status) = self.post_refresh_status.take() {
self.set_status(status);
} else {
self.set_status(format!(
"{count} package{} found",
if count == 1 { "" } else { "s" }
));
}
// Auto-load detail for the (restored) selected package
if let Some(pkg) = self.selected_package() {
let id = pkg.id.clone();
self.load_detail(&id);
}
}
AppMessage::DetailLoaded { generation, detail } => {
// Discard stale detail from a previous selection
if generation < self.detail_generation {
continue;
}
// Merge: if winget show returned empty fields, keep pre-populated data
let merged = if let Some(existing) = &self.detail {
detail.merge_over(existing)
} else {
detail
};
let mut merged = merged;
// `winget show` returns the latest manifest version, not the
// installed version. Restore the installed version from the
// package list so the detail pane shows the correct value.
if let Some(pkg) = self.filtered_packages.iter().find(|p| p.id == merged.id) {
if !pkg.version.is_empty() {
merged.version = pkg.version.clone();
}
}
Self::ensure_detail_hint(&mut merged);
// Cache for instant retrieval on revisit
if !merged.id.is_empty() {
self.detail_cache.insert(merged.id.clone(), merged.clone());
}
self.detail = Some(merged);
self.detail_loading = false;
}
AppMessage::OperationComplete(result) => {
// Invalidate cache for the affected package(s)
match &result.operation {
Operation::Install { id, .. }
| Operation::Uninstall { id }
| Operation::Upgrade { id }
| Operation::Pin { id }
| Operation::Unpin { id } => {
self.detail_cache.remove(id);
}
Operation::BatchUpgrade { ids } => {
for id in ids {
self.detail_cache.remove(id);
}
self.selected_packages.clear();
}
}
let status = if result.success {
let detail = result.message.trim();
if detail.is_empty() {
format!("{} — done", result.operation)
} else {
format!("{} — {}", result.operation, detail)
}
} else {
format!("{} — failed: {}", result.operation, result.message)
};
self.set_status(status.clone());
self.loading = false;
// Refresh after successful mutations, or after a batch-upgrade
// attempt where some items may still have changed state.
if result.success || matches!(result.operation, Operation::BatchUpgrade { .. })
{
self.post_refresh_status = Some(status);
self.loading = true;
self.refresh_view();
}
}
AppMessage::Error(msg) => {
self.post_refresh_status = None;
self.set_status(format!("Error: {msg}"));
self.loading = false;
self.detail_loading = false;
if let Some(detail) = &mut self.detail {
Self::ensure_detail_hint(detail);
}
}
AppMessage::StatusUpdate(msg) => {
self.set_status(msg);
}
}
}
}
}
fn csv_escape(s: &str) -> String {
if s.contains(',') || s.contains('"') || s.contains('\n') || s.contains('\r') {
format!("\"{}\"", s.replace('"', "\"\""))
} else {
s.to_string()
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use anyhow::Result;
use async_trait::async_trait;
use super::*;
use crate::backend::WingetBackend;
use crate::models::{Package, PackageDetail, PackagePin, PinState, Source};
/// Minimal backend that records `show` calls
struct SpyBackend {
show_calls: std::sync::Mutex<Vec<String>>,
}
impl SpyBackend {
fn new() -> Arc<Self> {
Arc::new(Self {
show_calls: std::sync::Mutex::new(Vec::new()),
})
}
fn show_calls(&self) -> Vec<String> {
self.show_calls.lock().unwrap().clone()
}
}
#[async_trait]
impl WingetBackend for SpyBackend {
async fn search(&self, _: &str, _: Option<&str>) -> Result<Vec<Package>> {
Ok(vec![])
}
async fn list_installed(&self, _: Option<&str>) -> Result<Vec<Package>> {
Ok(vec![])
}
async fn list_upgrades(&self, _: Option<&str>) -> Result<Vec<Package>> {
Ok(vec![])
}
async fn show(&self, id: &str) -> Result<PackageDetail> {
self.show_calls.lock().unwrap().push(id.to_string());
Ok(PackageDetail::default())
}
async fn install(&self, _: &str, _: Option<&str>) -> Result<String> {
Ok(String::new())
}
async fn uninstall(&self, _: &str) -> Result<String> {
Ok(String::new())
}
async fn upgrade(&self, _: &str) -> Result<String> {
Ok(String::new())
}
async fn list_pins(&self) -> Result<Vec<PackagePin>> {
Ok(vec![])
}
async fn pin(&self, _: &str) -> Result<String> {
Ok(String::new())
}
async fn unpin(&self, _: &str) -> Result<String> {
Ok(String::new())
}
async fn list_sources(&self) -> Result<Vec<Source>> {
Ok(vec![])
}
}
fn make_app(backend: Arc<dyn WingetBackend>) -> App {
App::new(backend, crate::config::Config::default())
}
fn pkg(id: &str) -> Package {
Package {
id: id.to_string(),
name: id.to_string(),
version: "1.0".to_string(),
source: "winget".to_string(),
available_version: String::new(),
pin_state: PinState::None,
}
}
/// Simulate receiving a PackagesLoaded message synchronously (bypasses tokio channel).
fn deliver_packages(app: &mut App, packages: Vec<Package>) {
let gen = app.view_generation;
app.message_tx
.send(AppMessage::PackagesLoaded {
generation: gen,
packages,
})
.unwrap();
app.process_messages();
}
#[tokio::test]
async fn packages_loaded_preserves_selection_by_id() {
let spy = SpyBackend::new();
let mut app = make_app(spy as Arc<dyn WingetBackend>);
// Load an initial list; select the second package (index 1 = VS Code)
app.view_generation = 1;
deliver_packages(
&mut app,
vec![
pkg("Google.Chrome"),
pkg("Microsoft.VisualStudioCode"),
pkg("7zip.7zip"),
],
);
app.selected = 1;
assert_eq!(
app.selected_package().unwrap().id,
"Microsoft.VisualStudioCode"
);
// Simulate refresh: list comes back re-ordered (Chrome is now at index 1)
app.view_generation = 2;
deliver_packages(
&mut app,
vec![
pkg("7zip.7zip"),
pkg("Google.Chrome"),
pkg("Microsoft.VisualStudioCode"),
],
);
// Cursor must follow VS Code to its new index (2), not stay at index 1
assert_eq!(
app.selected, 2,
"cursor should follow the package to its new position"
);
assert_eq!(
app.selected_package().unwrap().id,
"Microsoft.VisualStudioCode",
"selected package must remain VS Code after refresh"
);
}
#[tokio::test]
async fn packages_loaded_keeps_bounds_when_selected_package_disappears() {
let spy = SpyBackend::new();
let mut app = make_app(spy as Arc<dyn WingetBackend>);
// Select the last package (index 2 = 7zip)
app.view_generation = 1;
deliver_packages(
&mut app,
vec![
pkg("Google.Chrome"),
pkg("Microsoft.VisualStudioCode"),
pkg("7zip.7zip"),
],
);
app.selected = 2;
// After refresh, 7zip is gone (e.g. it was uninstalled)
app.view_generation = 2;
deliver_packages(
&mut app,
vec![pkg("Google.Chrome"), pkg("Microsoft.VisualStudioCode")],
);
// selected must be clamped to the last valid index
assert!(
app.selected < app.filtered_packages.len(),
"selection must remain in bounds after package disappears"
);
}
#[test]
fn load_detail_skips_truncated_id() {
let spy = SpyBackend::new();
let mut app = make_app(spy.clone() as Arc<dyn WingetBackend>);
let truncated = "MSIX\\bsky.app-C52C8C38_1.0.0.0_neutr\u{2026}";
app.load_detail(truncated);
// No show call should have been enqueued
assert!(
spy.show_calls().is_empty(),
"winget show must not be called for truncated id"
);
assert!(
!app.detail_loading,
"should not be loading for truncated id"
);
}
#[test]
fn load_detail_skips_ascii_dot_truncated_id() {
let spy = SpyBackend::new();
let mut app = make_app(spy.clone() as Arc<dyn WingetBackend>);
// winget produces "..." ASCII truncation on some terminals
let truncated = "Microsoft.Sysinternals.R...";
app.load_detail(truncated);
assert!(
spy.show_calls().is_empty(),
"winget show must not be called for ASCII-dot truncated id"
);
assert!(
!app.detail_loading,
"should not be loading for ASCII-dot truncated id"
);
}
#[tokio::test]
async fn load_detail_proceeds_for_normal_id() {
let spy = SpyBackend::new();
let mut app = make_app(spy.clone() as Arc<dyn WingetBackend>);
app.load_detail("Google.Chrome");
// detail_generation was incremented — an async fetch was started
assert_eq!(