helix-toolbox 1.25.4

Build, configure and optimize a Linux machine from a terminal menu: installs, dotfiles, updates, backups and health checks, every change planned and confirmed first.
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
//! The catalog areas, search, Favorites, the Install Plan and the command palette.

use super::*;

impl App {
    pub(in crate::tui::app) fn draw_area(&mut self, frame: &mut Frame, area: Rect) {
        let Some(index) = self.current_area() else {
            return;
        };
        let name = self.catalog.tabs[index].name.clone();
        let trail: Vec<String> = {
            let tab = &self.catalog.tabs[index];
            let mut names = Vec::new();
            let mut items = tab.items.as_slice();
            for (group, _) in &self.areas[index].path {
                if let Some(Item::Group(group)) = items.get(*group) {
                    names.push(group.name.clone());
                    items = &group.items;
                }
            }
            names
        };
        let subtitle = if trail.is_empty() {
            format!("{} entries", self.catalog.tabs[index].entries().len())
        } else {
            trail.join(" › ")
        };
        let content = self.page(frame, area, &name, &subtitle);
        let parts = Layout::vertical([Constraint::Length(3), Constraint::Min(1)]).split(content);
        self.draw_search(frame, parts[0]);
        self.draw_list(frame, parts[1]);
    }

    fn draw_search(&self, frame: &mut Frame, area: Rect) {
        let searching = self.focus == Focus::Search;
        let prefix = self.icon_gap(Icon::Search);
        let mut spans = vec![Span::styled(
            prefix.clone(),
            Style::default().fg(if searching {
                self.theme.focused()
            } else {
                self.theme.muted()
            }),
        )];
        if !searching && self.search.is_empty() {
            spans.push(Span::styled(
                "Type to search every area (/)",
                Style::default().fg(self.theme.muted()),
            ));
        } else {
            spans.push(Span::styled(
                self.search.iter().collect::<String>(),
                Style::default().fg(self.theme.focused()).bold(),
            ));
            if let Some(completion) = &self.completion {
                spans.push(Span::styled(
                    completion.clone(),
                    Style::default().fg(self.theme.muted()),
                ));
            }
        }
        let color = if searching {
            self.theme.focused()
        } else {
            self.theme.line()
        };
        let block = Block::bordered()
            .border_set(border::ROUNDED)
            .border_style(Style::default().fg(color))
            .padding(Padding::horizontal(1));
        self.fill(frame, area);
        if searching {
            let inner = block.inner(area);
            let x =
                inner.x + prefix.chars().count() as u16 + self.search[..self.cursor].len() as u16;
            frame.set_cursor_position((x.min(inner.right().saturating_sub(1)), inner.y));
        }
        frame.render_widget(Paragraph::new(Line::from(spans)).block(block), area);
    }

    fn draw_list(&mut self, frame: &mut Frame, area: Rect) {
        let focused = self.focus == Focus::Main;
        let title = match (self.searching(), self.screen) {
            (true, _) => "Results",
            (false, Screen::Favorites) => "Favorites",
            (false, _) => "Entries",
        };
        let title = match self.filter {
            Filter::All => title.to_string(),
            filter => format!("{title} · {}", filter.label()),
        };
        let block = self.card(&title).title(
            Line::styled(" STATUS · FLAGS ", Style::default().fg(self.theme.muted()))
                .right_aligned(),
        );
        let marker = self.marker(focused);
        let content_width =
            (block.inner(area).width as usize).saturating_sub(marker.chars().count());
        let group = self.glyph(Icon::Group);
        let searching = self.searching();
        let lines: Vec<Line> = self
            .rows
            .iter()
            .map(|row| match row {
                Row::Up => Line::from(format!("{group}  .."))
                    .style(Style::default().fg(self.theme.group())),
                Row::Group {
                    name,
                    description,
                    count,
                    ..
                } => {
                    // Its name, what it holds, and how many, as the window shows a group.
                    let left = format!("{group}  {name}");
                    let number = format!("{count} ");
                    let room = content_width
                        .saturating_sub(left.chars().count() + number.chars().count() + 2);
                    let about = if description.is_empty() || room < 8 {
                        String::new()
                    } else {
                        format!("  {}", clipped(description, room))
                    };
                    let gap = " ".repeat(content_width.saturating_sub(
                        left.chars().count() + about.chars().count() + number.chars().count(),
                    ));
                    Line::from(vec![
                        Span::styled(left, Style::default().fg(self.theme.group())),
                        Span::styled(about, Style::default().fg(self.theme.faint())),
                        Span::raw(gap),
                        Span::styled(number, Style::default().fg(self.theme.muted())),
                    ])
                }
                Row::Entry(entry) => {
                    let queued = self.is_queued(entry);
                    let (style, icon_color) = if queued {
                        (
                            Style::default().fg(self.theme.focused()).bold(),
                            self.theme.success(),
                        )
                    } else {
                        (Style::default().fg(self.theme.entry()), self.theme.muted())
                    };
                    // An entry that cannot be queued is marked as running on its own.
                    let icon = if queued {
                        self.glyph(Icon::Queued)
                    } else if entry.multi_select {
                        self.glyph(Icon::Entry)
                    } else {
                        self.glyph(Icon::Alone)
                    };
                    // Without icons, a queued entry is marked after its name; a pinned one
                    // always is.
                    let pinned = if self.favorites.contains(&entry.id) {
                        " ★"
                    } else {
                        ""
                    };
                    let suffix =
                        format!("{}{pinned}", if queued && !self.icons { " *" } else { "" });
                    let left = format!("{icon}  {}{suffix}", entry.name);
                    let flags = format!("  {} ", entry.flags);
                    // The status word, then where from, dropped first when short of room.
                    let (word, detail, color) = match self.statuses.get(&entry.id) {
                        Some(status) => (
                            status.label().to_string(),
                            status.detail(),
                            self.status_color(status),
                        ),
                        None => (String::new(), String::new(), self.theme.muted()),
                    };
                    let room = content_width.saturating_sub(left.chars().count() + 2);
                    let mut detail = if detail.is_empty() {
                        detail
                    } else {
                        format!("  {detail}")
                    };
                    let width = |detail: &str| {
                        word.chars().count() + detail.chars().count() + flags.chars().count()
                    };
                    if width(&detail) > room {
                        detail.clear();
                    }
                    let flags = if width(&detail) > room {
                        " ".to_string()
                    } else {
                        flags
                    };
                    let right =
                        word.chars().count() + detail.chars().count() + flags.chars().count();
                    // Between them, where it fits: where a search result is
                    // listed, then the description, as the window's rows show.
                    let room = content_width.saturating_sub(left.chars().count() + right + 3);
                    let place = if searching {
                        self.place_label(&entry.id)
                    } else {
                        None
                    };
                    let about = match (place, entry.description.is_empty()) {
                        (Some(place), true) => place,
                        (Some(place), false) => format!("{place} · {}", entry.description),
                        (None, _) => entry.description.clone(),
                    };
                    let about = if about.is_empty() || room < 8 {
                        String::new()
                    } else {
                        format!("  {}", clipped(&about, room))
                    };
                    let gap = " ".repeat(
                        content_width
                            .saturating_sub(left.chars().count() + about.chars().count() + right),
                    );
                    Line::from(vec![
                        Span::styled(icon.to_string(), Style::default().fg(icon_color)),
                        Span::styled(format!("  {}{suffix}", entry.name), style),
                        Span::styled(about, Style::default().fg(self.theme.faint())),
                        Span::raw(gap),
                        Span::styled(word, Style::default().fg(color)),
                        Span::styled(detail, Style::default().fg(self.theme.faint())),
                        Span::styled(flags, Style::default().fg(self.theme.muted())),
                    ])
                }
            })
            .collect();
        self.fill(frame, area);
        let list = List::new(self.measure(lines))
            .block(block)
            .highlight_style(self.highlight(focused))
            .highlight_symbol(marker)
            .scroll_padding(1);
        bordered_list(frame, list, area, &mut self.main_state, &self.hits);
    }

    pub(in crate::tui::app) fn draw_plan(&mut self, frame: &mut Frame, area: Rect) {
        let inner = self.page(
            frame,
            area,
            "Install Plan",
            "Review planned changes before they run.",
        );
        if self.queue.is_empty() {
            frame.render_widget(
                Paragraph::new(
                    "Nothing is queued. In an area, press Space on an entry to add it here.",
                )
                .style(Style::default().fg(self.theme.muted()))
                .wrap(Wrap { trim: true }),
                inner,
            );
            return;
        }
        let ids: Vec<String> = self.queue.iter().map(|entry| entry.id.clone()).collect();
        let fresh = self
            .planned
            .as_ref()
            .is_some_and(|cache| cache.ids == ids && cache.made.elapsed() < PLAN_KEPT);
        if !fresh {
            let result = plan(self.queue.iter(), &self.platform, &|id| {
                self.catalog.find(id)
            })
            .map_err(|error| error.to_string());
            let findings = match &result {
                Ok(planned) => self.findings(planned),
                Err(_) => Vec::new(),
            };
            self.planned = Some(PlanCache {
                ids,
                made: std::time::Instant::now(),
                result,
                findings,
            });
        }
        let planned = self
            .planned
            .as_ref()
            .map(|cache| cache.result.clone())
            .unwrap_or_else(|| Err("not planned".to_string()));
        let summary = match &planned {
            Ok(planned) => {
                let mut lines = vec![format!(
                    "{} step{}, risk {}{}",
                    planned.steps.len(),
                    if planned.steps.len() == 1 { "" } else { "s" },
                    planned.risk.label(),
                    if planned.privileged {
                        ", asks for your password"
                    } else {
                        ""
                    }
                )];
                if !planned.requirements.is_empty() {
                    lines.push(format!("Needs: {}", planned.requirements.join(", ")));
                }
                lines.extend(
                    self.planned
                        .iter()
                        .flat_map(|cache| cache.findings.iter().map(preflight::Finding::line)),
                );
                lines.extend(planned.notes.iter().cloned());
                lines.extend(
                    planned
                        .blocked
                        .iter()
                        .map(|blocked| format!("Not run: {blocked}")),
                );
                lines
            }
            Err(error) => vec![format!("Cannot plan: {error}")],
        };
        let summary_height = summary.len() as u16 + 2;
        let parts = Layout::vertical([
            Constraint::Length(summary_height),
            Constraint::Length(1),
            Constraint::Min(1),
        ])
        .split(inner);
        self.fill(frame, parts[0]);
        frame.render_widget(
            Paragraph::new(Text::from(
                summary.into_iter().map(Line::from).collect::<Vec<_>>(),
            ))
            .block(self.card("Summary"))
            .wrap(Wrap { trim: true }),
            parts[0],
        );
        let focused = self.focus == Focus::Main;
        let steps = planned.map(|planned| planned.steps).unwrap_or_default();
        let block = self.card(&format!("Queued entries · {}", self.queue.len()));
        let marker = self.marker(focused);
        let width = (block.inner(parts[2]).width as usize).saturating_sub(marker.chars().count());
        // Each entry in two lines, as the window's rows: its number, name,
        // status and flags, then where it is listed, its kind and its step.
        let items: Vec<ListItem> = self
            .queue
            .iter()
            .enumerate()
            .map(|(index, entry)| {
                let command = steps
                    .iter()
                    .find(|step| step.id() == entry.id)
                    .map(|step| step.display())
                    .unwrap_or_else(|| "nothing to do".to_string());
                let icon = self.icon_gap(Icon::Queued);
                let number = format!("{}. ", index + 1);
                let (word, color) = match self.statuses.get(&entry.id) {
                    Some(status) => (status.label().to_string(), self.status_color(status)),
                    None => (String::new(), self.theme.muted()),
                };
                let flags = format!("  {} ", entry.flags.trim());
                let left = icon.chars().count() + number.len() + entry.name.chars().count();
                let gap = " ".repeat(
                    width.saturating_sub(left + word.chars().count() + flags.chars().count()),
                );
                let indent = " ".repeat(icon.chars().count() + number.len());
                let mut about = vec![kind_label(&entry.action).to_string()];
                if let Some(place) = self.place_label(&entry.id) {
                    about.insert(0, place);
                }
                let about = about.join(" · ");
                let room = width.saturating_sub(indent.len() + about.chars().count() + 3);
                ListItem::new(Text::from(vec![
                    Line::from(vec![
                        Span::styled(icon, Style::default().fg(self.theme.success())),
                        Span::styled(number, Style::default().fg(self.theme.faint())),
                        Span::styled(
                            entry.name.clone(),
                            Style::default().fg(self.theme.entry()).bold(),
                        ),
                        Span::raw(gap),
                        Span::styled(word, Style::default().fg(color)),
                        Span::styled(flags, Style::default().fg(self.theme.muted())),
                    ]),
                    Line::from(vec![
                        Span::raw(indent),
                        Span::styled(about, Style::default().fg(self.theme.faint())),
                        Span::styled(
                            format!("   {}", clipped(&command, room)),
                            Style::default().fg(self.theme.muted()),
                        ),
                    ]),
                ]))
            })
            .collect();
        self.fill(frame, parts[2]);
        let list = List::new(self.measure(items))
            .block(block)
            .highlight_style(self.highlight(focused))
            .highlight_symbol(self.marker(focused));
        bordered_list(frame, list, parts[2], &mut self.main_state, &self.hits);
    }

    /// Pin the selected entry, or unpin it, and remember it.
    pub(in crate::tui::app) fn toggle_favorite(&mut self) {
        let Some(entry) = self.selected_entry().cloned() else {
            return;
        };
        match self.favorites.iter().position(|id| *id == entry.id) {
            Some(position) => {
                self.favorites.remove(position);
            }
            None => self.favorites.push(entry.id.clone()),
        }
        if let Some(path) = &self.favorites_path
            && let Err(error) = settings::save_favorites(path, &self.favorites)
        {
            tracing::warn!(%error, "the favorites were not saved");
        }
        if self.screen == Screen::Favorites {
            self.update_rows();
        }
    }

    /// The entries run recently, newest first, from the history.
    pub(in crate::tui::app) fn reload_recent(&mut self) {
        self.take_recent(self.host.history(50));
    }

    pub(in crate::tui::app) fn take_recent(&mut self, records: Vec<history::Record>) {
        let mut recent: Vec<String> = Vec::new();
        for record in records {
            for id in record.entries {
                if !recent.contains(&id) && self.catalog.find(&id).is_some() {
                    recent.push(id);
                }
            }
            if recent.len() >= 10 {
                break;
            }
        }
        recent.truncate(10);
        self.recent = recent;
    }

    pub(in crate::tui::app) fn filter_hint(&self) -> &'static str {
        match self.filter {
            Filter::All => "Show: all",
            Filter::Installed => "Show: installed",
            Filter::Updates => "Show: updates",
        }
    }

    pub(in crate::tui::app) fn draw_favorites(&mut self, frame: &mut Frame, area: Rect) {
        let content = self.page(
            frame,
            area,
            "Favorites",
            "Entries pinned with *, then the ones run recently.",
        );
        if self.rows.is_empty() {
            self.fill(frame, content);
            frame.render_widget(
                Paragraph::new(if self.filter == Filter::All {
                    "Nothing here yet. Press * on an entry anywhere to pin it here; entries you run appear here too."
                } else {
                    "Nothing here matches the filter; i changes it."
                })
                .block(self.card("Favorites"))
                .style(Style::default().fg(self.theme.muted()))
                .wrap(Wrap { trim: true }),
                content,
            );
            return;
        }
        self.draw_list(frame, content);
    }

    pub(in crate::tui::app) fn toggle_queue(&mut self) {
        let Some(entry) = self.selected_entry().cloned() else {
            return;
        };
        self.toggle_queued(entry);
    }

    /// Add an entry to the Install Plan, or take it out.
    pub(in crate::tui::app) fn toggle_queued(&mut self, entry: Entry) {
        screens::toggle_queued(&mut self.queue, &mut self.popup, entry);
    }

    /// Move the selected Install Plan entry earlier (-1) or later (1), as
    /// the window's arrows do; the selection follows it.
    pub(in crate::tui::app) fn move_queued(&mut self, by: isize) {
        let Some(selected) = self.main_state.selected() else {
            return;
        };
        let Some(target) = selected.checked_add_signed(by) else {
            return;
        };
        if selected >= self.queue.len() || target >= self.queue.len() {
            return;
        }
        self.queue.swap(selected, target);
        self.main_state.select(Some(target));
    }

    /// Queue the selected profile's entries one by one, those not queued
    /// yet, to change the plan before it runs; then show the Install Plan.
    pub(in crate::tui::app) fn queue_profile_entries(&mut self) {
        let Some(entry) = self.selected_entry().cloned() else {
            return;
        };
        let Action::Profile { entries } = &entry.action else {
            return;
        };
        let mut added = 0;
        for id in entries {
            if let Some(found) = self.catalog.find(id).cloned()
                && found.multi_select
                && !self.queue.iter().any(|queued| queued.id == found.id)
            {
                self.queue.push(found);
                added += 1;
            }
        }
        self.open_screen(Screen::Plan);
        self.focus = Focus::Main;
        let text = if added == 0 {
            "Its entries are already in the Install Plan.".to_string()
        } else {
            format!("{added} of its entries were added to the Install Plan. Nothing has run.")
        };
        self.popup = Some(Popup::Text(TextPopup::new(entry.name.clone(), text, true)));
    }

    pub(in crate::tui::app) fn preview(&mut self) {
        let Some(entry) = self.selected_entry() else {
            return;
        };
        let text = match &entry.action {
            Action::Script { file, .. } => std::fs::read_to_string(file)
                .unwrap_or_else(|error| format!("The script cannot be read: {error}")),
            Action::Command { line } => line.clone(),
            _ => match plan([entry], &self.platform, &|id| self.catalog.find(id)) {
                Ok(planned) => {
                    let mut lines = planned.notes.clone();
                    for step in &planned.steps {
                        lines.push(step.display());
                        lines.extend(step.fallbacks());
                    }
                    lines.join("\n")
                }
                Err(error) => error.to_string(),
            },
        };
        self.popup = Some(Popup::Text(TextPopup::new(
            format!("Preview: {}", entry.name),
            text,
            false,
        )));
    }

    pub(in crate::tui::app) fn describe(&mut self) {
        let Some(entry) = self.selected_entry() else {
            return;
        };
        // As the window's details: where it is, what kind, whether it asks.
        let mut tags = vec![kind_label(&entry.action).to_string()];
        if matches!(
            entry.action,
            Action::Script {
                interactive: true,
                ..
            }
        ) {
            tags.push("Asks questions".to_string());
        }
        if !entry.multi_select {
            tags.push("Runs on its own".to_string());
        }
        let mut text = String::new();
        if let Some(place) = self.place_label(&entry.id) {
            text.push_str(&format!("{place}\n"));
        }
        text.push_str(&tags.join(" · "));
        text.push_str("\n\n");
        text.push_str(if entry.description.is_empty() {
            "This entry has no description."
        } else {
            &entry.description
        });
        if let Some(status) = self.statuses.get(&entry.id) {
            let detail = status.detail();
            text.push_str(&format!("\n\nStatus: {}", status.label()));
            if !detail.is_empty() {
                text.push_str(&format!("\nInstalled from: {detail}"));
            }
            if let Status::Update { .. } = status {
                text.push_str(
                    "\nThe repository metadata on this machine has a newer version: u updates it (on Arch, with the whole system).",
                );
            }
        }
        if let Action::Profile { entries } = &entry.action
            && !entries.is_empty()
        {
            text.push_str("\n\nRuns, in order:");
            for (number, id) in entries.iter().enumerate() {
                let name = self
                    .catalog
                    .find(id)
                    .map_or(id.as_str(), |found| found.name.as_str());
                text.push_str(&format!("\n  {}. {name}", number + 1));
            }
            text.push_str("\n\ne puts its entries in the Install Plan one by one, to change the plan before it runs.");
        }
        let meanings = flag_meanings(&entry.flags);
        if !meanings.is_empty() {
            text.push_str("\n\nWhat it does:");
            for (flag, meaning) in meanings {
                text.push_str(&format!("\n  {flag:<4}{meaning}"));
            }
        }
        self.popup = Some(Popup::Text(TextPopup::new(entry.name.clone(), text, true)));
    }

    /// Every screen, action and entry, with what each does.
    pub(in crate::tui::app) fn palette_choices(&self) -> (Vec<Choice>, Vec<Act>) {
        let mut choices = Vec::new();
        let mut acts = Vec::new();
        let mut add = |label: String, detail: &str, keywords: &str, listed: bool, act: Act| {
            choices.push(Choice {
                label,
                detail: detail.to_string(),
                keywords: keywords.to_string(),
                listed,
            });
            acts.push(act);
        };
        for item in &self.menu {
            add(
                format!("Open {}", item.label),
                "screen",
                "go to show",
                true,
                Act::Open(item.screen),
            );
        }
        let actions: [(&str, &str, Act); 18] = [
            (
                "Check updates online",
                "updates refresh",
                Act::UpdatesOnline,
            ),
            (
                "Run the health checks",
                "doctor diagnostics",
                Act::Doctor(None),
            ),
            (
                "Run DNS diagnostics",
                "doctor dns name resolution",
                Act::Doctor(Some("dns")),
            ),
            (
                "Check the network",
                "doctor internet connection route",
                Act::Doctor(Some("network")),
            ),
            (
                "Check disk space",
                "doctor free storage",
                Act::Doctor(Some("disk-space")),
            ),
            (
                "Check failed services",
                "doctor systemd units",
                Act::Doctor(Some("services")),
            ),
            (
                "Save this machine as a baseline",
                "drift snapshot record",
                Act::SaveBaseline,
            ),
            ("Run the Install Plan", "queue", Act::RunPlan),
            ("Clear the Install Plan", "queue empty", Act::ClearPlan),
            (
                "Save the Install Plan as a profile",
                "queue",
                Act::SaveProfile,
            ),
            ("Import a profile", "profile file", Act::ImportProfile),
            ("Make a bug report", "issue problem report", Act::Report),
            (
                "Update every entry with an update",
                "upgrade packages",
                Act::UpdateEntries,
            ),
            (
                "Check again what is installed",
                "status refresh packages installed",
                Act::CheckStatuses,
            ),
            ("Change the theme", "colors colors look", Act::Theme),
            (
                "Set up this machine",
                "wizard first run workstation",
                Act::Wizard,
            ),
            (
                if self.icons {
                    "Turn icons off"
                } else {
                    "Turn icons on"
                },
                "nerd font plain",
                Act::Icons,
            ),
            (
                if self.mouse {
                    "Turn the mouse off"
                } else {
                    "Turn the mouse on"
                },
                "mouse click wheel scroll select text",
                Act::Mouse,
            ),
        ];
        for (label, keywords, act) in actions {
            add(label.to_string(), "action", keywords, true, act);
        }
        add(
            "Show the keys".to_string(),
            "action",
            "help",
            true,
            Act::Help,
        );
        add(
            "Quit Helix Toolbox".to_string(),
            "action",
            "exit close",
            true,
            Act::Quit,
        );
        for tab in &self.catalog.tabs {
            for entry in tab.entries() {
                let verb = match (&entry.action, self.statuses.get(&entry.id)) {
                    (_, Some(Status::Absent { .. })) => "Install",
                    (Action::Package { .. }, None) => "Install",
                    (Action::Profile { .. }, _) => "Run profile",
                    _ => "Run",
                };
                add(
                    format!("{verb} {}", entry.name),
                    &tab.name,
                    &entry.id,
                    false,
                    Act::Entry(entry.id.clone()),
                );
                add(
                    format!("Inspect {}", entry.name),
                    "trust and testing",
                    &entry.id,
                    false,
                    Act::Inspect(entry.id.clone()),
                );
            }
        }
        (choices, acts)
    }

    pub(in crate::tui::app) fn open_palette(&mut self) {
        let (choices, acts) = self.palette_choices();
        self.palette_acts = acts;
        self.popup = Some(Popup::Palette(Palette::new(choices)));
    }

    /// Do what a palette choice says; false quits.
    pub(in crate::tui::app) fn act(&mut self, act: Act) -> bool {
        match act {
            Act::Open(screen) => {
                self.open_screen(screen);
                if screen != Screen::Dashboard {
                    self.focus = Focus::Main;
                }
            }
            Act::Entry(id) => {
                if let Some(entry) = self.catalog.find(&id).cloned() {
                    self.confirm(vec![entry]);
                }
            }
            Act::Inspect(id) => self.inspect(&id),
            Act::UpdatesOnline => {
                self.open_screen(Screen::Updates);
                self.focus = Focus::Main;
                self.with_screens(|screens, cx| screens.updates.gather(cx, true));
            }
            Act::Doctor(wanted) => {
                self.open_screen(Screen::Doctor);
                self.focus = Focus::Main;
                self.with_screens(|screens, cx| screens.doctor.want(cx, wanted));
            }
            Act::SaveBaseline => {
                self.open_screen(Screen::Drift);
                self.focus = Focus::Main;
                self.popup = Some(Popup::BaselineName(InputPopup::new(
                    "Save this machine as a baseline",
                    "A name for the baseline (it is saved in ~/.config/helix-toolbox/baselines):",
                )));
            }
            Act::Wizard => self.open_wizard(false),
            Act::RunPlan => {
                self.open_screen(Screen::Plan);
                self.focus = Focus::Main;
                self.confirm(self.queue.clone());
            }
            Act::ClearPlan => {
                self.queue.clear();
                self.clamp_main();
            }
            Act::SaveProfile => {
                self.open_screen(Screen::Plan);
                self.focus = Focus::Main;
                if !self.queue.is_empty() {
                    self.popup = Some(Popup::ProfileName(InputPopup::new(
                        "Save as a profile",
                        "A name for this profile (it is saved in ~/.config/helix-toolbox/profiles):",
                    )));
                }
            }
            Act::ImportProfile => {
                if let Some(index) = self
                    .catalog
                    .tabs
                    .iter()
                    .position(|tab| tab.id == "profiles")
                {
                    self.open_screen(Screen::Area(index));
                    self.focus = Focus::Main;
                    self.handle_main_key(&KeyEvent::new(KeyCode::Char('o'), KeyModifiers::NONE));
                }
            }
            Act::Report => self.make_report(),
            Act::CheckStatuses => self.check_again(),
            Act::UpdateEntries => {
                let waiting: Vec<Entry> = self
                    .catalog
                    .entries()
                    .into_iter()
                    .filter(|entry| {
                        matches!(self.statuses.get(&entry.id), Some(Status::Update { .. }))
                    })
                    .cloned()
                    .collect();
                if waiting.is_empty() {
                    self.popup = Some(Popup::Text(TextPopup::new(
                        "Nothing to update",
                        "No package entry has an update in the repository metadata on this machine.",
                        true,
                    )));
                } else {
                    self.update(waiting);
                }
            }
            Act::Theme => {
                self.theme = self.theme.next();
                self.saved_theme = self.theme;
                self.save_look();
            }
            Act::Icons => {
                self.icons = !self.icons;
                self.save_look();
            }
            Act::Mouse => {
                self.mouse = !self.mouse;
                self.save_look();
            }
            Act::Help => {
                self.popup = Some(Popup::Text(TextPopup::new("Keys", HELP, false)));
            }
            Act::Quit => return false,
        }
        true
    }

    /// This build's testing record, read on first use.
    pub(in crate::tui::app) fn evidence(&self) -> reliability::Evidence {
        screens::evidence(&self.evidence, &self.catalog)
    }

    pub(in crate::tui::app) fn run_history(&self) -> Vec<history::Record> {
        self.host.history(1000)
    }

    /// The trust inspector for an entry.
    pub(in crate::tui::app) fn inspect(&mut self, id: &str) {
        let Some(entry) = self.catalog.find(id).cloned() else {
            return;
        };
        let evidence = self.evidence();
        let records = self.run_history();
        // How this copy was installed is the running program's, which is on
        // this machine only.
        let build = if self.host.is_here() {
            crate::inspect::build()
        } else {
            helix_toolbox_engine::trust::Build {
                version: crate::VERSION.to_string(),
                release: false,
                commit: None,
                install: helix_toolbox_engine::updates::Install::Other,
            }
        };
        let found = helix_toolbox_engine::trust::inspect(
            &entry,
            self.catalog.root(),
            &self.platform,
            &build,
            &self.host,
            &evidence,
            &records,
        );
        self.popup = Some(Popup::Text(TextPopup::new(
            format!("Trust: {}", entry.name),
            crate::inspect::text(&found),
            true,
        )));
    }

    /// The change preview of a plan.
    pub(in crate::tui::app) fn show_effects(&mut self, planned: &Plan, from_confirmation: bool) {
        let look = helix_toolbox_engine::preview::Look::of(
            &self.host,
            &self.catalog.root().join("scripts"),
        );
        let steps = helix_toolbox_engine::preview::preview(
            planned,
            &|id| self.catalog.find(id),
            &self.platform,
            &look,
        );
        let download = helix_toolbox_engine::preview::sources_for(planned)
            .into_iter()
            .any(|name| {
                matches!(
                    (look.pinned)(name),
                    helix_toolbox_engine::preview::Pinned::Missing { .. }
                )
            });
        self.popup = Some(Popup::Effects(EffectsPopup::new(
            steps,
            from_confirmation,
            planned.clone(),
            download,
        )));
    }

    /// Download the pinned sources a plan reads, which changes nothing
    /// else, then show its changes again.
    pub(in crate::tui::app) fn download_sources(
        &mut self,
        planned: &Plan,
        from_confirmation: bool,
    ) {
        let scripts = self.catalog.root().join("scripts");
        for name in helix_toolbox_engine::preview::sources_for(planned) {
            if let Err(why) = helix_toolbox_engine::preview::fetch_source(&scripts, name) {
                self.popup = Some(Popup::Text(TextPopup::new(
                    "Cannot download",
                    format!("{name}: {why}"),
                    true,
                )));
                return;
            }
        }
        self.show_effects(planned, from_confirmation);
    }

    /// Check the selected entry now, read-only: what it installs and its
    /// checks of files, settings and services.
    pub(in crate::tui::app) fn check_selected(&mut self) {
        let Some(entry) = self.selected_entry().cloned() else {
            return;
        };
        let rebooted = helix_toolbox_engine::verification::rebooted_since(
            &self.host,
            &self.run_history(),
            &entry.id,
        );
        let checks = helix_toolbox_engine::verification::check_entry(
            &entry,
            &self.platform,
            rebooted,
            &|probe| probe.holds_on(&self.host),
            &|tool| self.host.which(tool).is_some(),
            &self.host,
        );
        let text = if checks.is_empty() {
            format!(
                "{} declares no checks and installs nothing Helix Toolbox can find, so there is nothing to check.",
                entry.name
            )
        } else {
            let failed = checks.iter().filter(|check| !check.passed).count();
            let mut text = match failed {
                0 => "Everything that can be checked here is as it should be.\n\n".to_string(),
                1 => "One check found it not as it should be.\n\n".to_string(),
                count => format!("{count} checks found it not as it should be.\n\n"),
            };
            for check in &checks {
                text.push_str(&format!(
                    "{}: {}\n  {}\n",
                    check.label(),
                    check.name,
                    check.detail
                ));
            }
            text
        };
        self.popup = Some(Popup::Text(TextPopup::new(
            format!("Checks: {}", entry.name),
            text,
            true,
        )));
    }
}