bigtext 0.11.0

Free editor for huge text and log files (1-50+ GB): opens instantly, never freezes, 2.5 GB/s search, atomic save
Documentation
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
//! Update check (from Help, and once a day when the user agreed to it) and the update dialog.
//! Nothing goes out on its own until the user answers the question asked at the first start.
//! The dialog shows the release notes first and installs only after the user agrees; "Skip this
//! version" keeps the automatic check from offering that version again.

use std::mem;
use std::path::PathBuf;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use egui::RichText;

use bigtext::jobs::{self, human_bytes, CancelToken, Progress};
use bigtext::update::{self, Block, Manager, Method, Span, Version};

use super::extras::{self, Persisted};
use super::i18n::{tr, trf};
use super::{BigTextApp, Msg};

/// Automatic checks run at most this often (seconds).
const CHECK_INTERVAL: u64 = 24 * 60 * 60;
/// The next try after an automatic check failed (offline, say).
const RETRY_AFTER: Duration = Duration::from_secs(60 * 60);

pub enum Event {
    Checked(Result<Option<Box<Offer>>, String>),
    Downloaded(Result<Pending, String>),
}

/// A newer release, ready to show.
pub struct Offer {
    version: Version,
    page: String,
    /// "What's new" of every release newer than the running one, newest first.
    notes: Vec<(Version, Vec<Block>)>,
    method: Method,
}

/// A downloaded update that takes effect when BigText restarts.
pub enum Pending {
    /// The executable was replaced; a restart runs the new one.
    Replaced { version: Version, exe: PathBuf },
    /// The installer runs when BigText exits.
    Installer { version: Version, setup: PathBuf },
}

#[derive(Default)]
enum Stage {
    #[default]
    Idle,
    /// The first start: may BigText check on its own?
    Ask,
    /// A check the user asked for is running.
    Checking,
    Offer(Box<Offer>),
    Downloading {
        offer: Box<Offer>,
        progress: Progress,
        cancel: CancelToken,
    },
    /// `UpdateUi::pending` is set: restart now or later.
    Ready,
    UpToDate,
    Failed {
        title: &'static str,
        message: String,
    },
}

pub struct UpdateUi {
    stage: Stage,
    /// A check is running on a worker.
    running: bool,
    /// Check automatically (saved; only after the user said so).
    pub auto: bool,
    /// The user has chosen whether to check automatically (saved).
    pub asked: bool,
    /// The question was put off for this session (Escape).
    ask_later: bool,
    /// "Skip this version" (saved).
    pub skipped: Option<Version>,
    /// Unix time of the last successful check (saved).
    pub last_check: u64,
    retry_at: Option<Instant>,
    pending: Option<Pending>,
    /// "Restart now" was chosen: on exit the update is applied and BigText starts again.
    pub restart: bool,
}

impl Default for UpdateUi {
    fn default() -> Self {
        UpdateUi {
            stage: Stage::Idle,
            running: false,
            auto: false,
            asked: false,
            ask_later: false,
            skipped: None,
            last_check: 0,
            retry_at: None,
            pending: None,
            restart: false,
        }
    }
}

impl UpdateUi {
    pub fn restore(&mut self, p: &Persisted) {
        // Settings from before the question: having turned the check off is an answer; having
        // left it on (the old default) is not.
        self.asked = p.update_asked.unwrap_or(p.update_check == Some(false));
        self.auto = self.asked && p.update_check.unwrap_or(false);
        self.skipped = p.skip_version.as_deref().and_then(Version::parse);
        self.last_check = p.update_checked.unwrap_or(0);
    }

    pub fn dialog_open(&self) -> bool {
        !matches!(self.stage, Stage::Idle)
    }

    /// Self-test: the first start's question (the self-test never saves, so it is not asked).
    pub(crate) fn test_ask(&mut self) {
        self.stage = Stage::Ask;
    }

    /// Self-test: (asked, put off for this session, the question on screen).
    pub(crate) fn test_state(&self) -> (bool, bool, bool) {
        (self.asked, self.ask_later, matches!(self.stage, Stage::Ask))
    }

    /// Self-test: offers the next patch version, updated by `method`, with one note.
    pub(crate) fn test_offer(&mut self, method: Method) {
        let Version(a, b, c) = Version::current();
        let version = Version(a, b, c + 1);
        let notes = vec![(version, update::parse_notes("- **A note**: what changed."))];
        self.stage = Stage::Offer(Box::new(Offer {
            version,
            page: update::RELEASES_PAGE.into(),
            notes,
            method,
        }));
    }

    /// Self-test: closes the dialog.
    pub(crate) fn test_close(&mut self) {
        self.stage = Stage::Idle;
    }
}

/// What the offer says to a copy a package manager installed: the sentence and the command.
fn package_hint(m: Manager) -> (String, &'static str) {
    let text = match m {
        Manager::Aur => tr("This copy was installed from the AUR. Update it with your AUR helper, for example:").to_owned(),
        Manager::Deb => tr("This copy was installed from the .deb package. Download the new package, then install it with:").to_owned(),
        _ => trf("This copy was installed with {manager}. To update it, run:", &[("manager", m.name())]),
    };
    (text, m.command())
}

/// The offer's buttons besides "Remind me later" and "Skip": (Update now, Open download page).
fn offer_buttons(method: &Method) -> (bool, bool) {
    match method {
        Method::Replace { .. } | Method::Installer { .. } => (true, false),
        Method::Manual | Method::Package(Manager::Deb) => (false, true),
        Method::Package(_) => (false, false),
    }
}

/// Removes what an earlier update left behind (on a worker: it touches the file system).
pub fn cleanup_in_background() {
    jobs::spawn("update-cleanup", || {
        if let Ok(exe) = update::current_exe() {
            update::cleanup(&exe);
        }
    });
}

fn now() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_secs())
        .unwrap_or(0)
}

fn find_update() -> Result<Option<Box<Offer>>, String> {
    let releases = update::check(Version::current())?;
    let Some(latest) = releases.first() else {
        return Ok(None);
    };
    let method = match update::current_exe() {
        Ok(exe) => update::method(latest, &exe),
        Err(_) => Method::Manual,
    };
    let notes = releases
        .iter()
        .map(|r| (r.version, update::parse_notes(update::whats_new(&r.notes))))
        .collect();
    Ok(Some(Box::new(Offer {
        version: latest.version,
        page: latest.page.clone(),
        notes,
        method,
    })))
}

enum Action {
    Update,
    Close,
    Skip,
    Cancel,
    Restart,
    /// The answer to the first start's question.
    Auto(bool),
    Open(String),
    Copy(&'static str),
}

impl BigTextApp {
    /// Starts the automatic check when it is due; called every frame.
    pub(super) fn update_tick(&mut self) {
        let u = &self.update;
        // The first start asks before anything goes out (benchmarks and the self-test do not).
        if !u.asked && !u.ask_later && self.persist && !u.dialog_open() {
            self.update.stage = Stage::Ask;
            return;
        }
        // Debug builds (development), benchmarks and the self-test never check on their own.
        if !u.auto
            || !self.persist
            || cfg!(debug_assertions)
            || u.running
            || u.pending.is_some()
            || u.dialog_open()
        {
            return;
        }
        if u.retry_at.is_none_or(|t| Instant::now() >= t)
            && now().abs_diff(u.last_check) >= CHECK_INTERVAL
        {
            self.check_for_updates(false);
        }
    }

    /// Help > Check for updates (`manual`: the dialog shows the answer, even "up to date"),
    /// or the automatic check.
    pub(super) fn check_for_updates(&mut self, manual: bool) {
        let u = &mut self.update;
        if manual {
            if u.pending.is_some() {
                u.stage = Stage::Ready;
                return;
            }
            u.stage = Stage::Checking;
        }
        if u.running {
            return;
        }
        u.running = true;
        let (tx, waker) = (self.tx.clone(), self.waker.clone());
        jobs::spawn("update-check", move || {
            let _ = tx.send(Msg::Update(Event::Checked(find_update())));
            waker();
        });
    }

    pub(super) fn on_update_event(&mut self, event: Event) {
        let u = &mut self.update;
        match event {
            Event::Checked(result) => {
                u.running = false;
                // The user is waiting for this answer (Help > Check for updates).
                let waiting = matches!(u.stage, Stage::Checking);
                match result {
                    Ok(found) => {
                        u.last_check = now();
                        u.retry_at = None;
                        match found {
                            Some(offer)
                                if waiting
                                    || (!u.dialog_open() && u.skipped != Some(offer.version)) =>
                            {
                                u.stage = Stage::Offer(offer)
                            }
                            None if waiting => u.stage = Stage::UpToDate,
                            _ => {}
                        }
                        self.persist_state();
                    }
                    Err(message) => {
                        u.retry_at = Some(Instant::now() + RETRY_AFTER);
                        if waiting {
                            u.stage = Stage::Failed {
                                title: "Could not check for updates",
                                message,
                            };
                        }
                    }
                }
            }
            Event::Downloaded(result) => {
                if !matches!(u.stage, Stage::Downloading { .. }) {
                    return;
                }
                let Stage::Downloading { offer, cancel, .. } = mem::take(&mut u.stage) else {
                    return;
                };
                u.stage = match result {
                    Ok(p) => {
                        u.pending = Some(p);
                        Stage::Ready
                    }
                    Err(_) if cancel.is_cancelled() => Stage::Offer(offer),
                    Err(message) => Stage::Failed {
                        title: "The update failed",
                        message,
                    },
                };
            }
        }
    }

    fn start_update(&mut self) {
        let Stage::Offer(offer) = mem::take(&mut self.update.stage) else {
            return;
        };
        let (progress, cancel) = (Progress::default(), CancelToken::new());
        let (method, version) = (offer.method.clone(), offer.version);
        let (p, c, tx, waker) = (
            progress.clone(),
            cancel.clone(),
            self.tx.clone(),
            self.waker.clone(),
        );
        jobs::spawn("update-download", move || {
            let result = match method {
                Method::Replace { asset, exe } => update::update_exe(&asset, &exe, &p, &c)
                    .map(|()| Pending::Replaced { version, exe }),
                Method::Installer { asset } => {
                    let setup = update::download_dir().join(&asset.name);
                    update::download(&asset, &setup, &p, &c)
                        .map(|()| Pending::Installer { version, setup })
                }
                Method::Package(_) | Method::Manual => {
                    Err(tr("This copy of BigText cannot update itself.").into())
                }
            };
            let _ = tx.send(Msg::Update(Event::Downloaded(result)));
            waker();
        });
        self.update.stage = Stage::Downloading {
            offer,
            progress,
            cancel,
        };
    }

    /// On exit: runs the downloaded installer, or starts the new version after "Restart now".
    pub(super) fn apply_update_on_exit(&mut self) {
        let restart = self.update.restart;
        let Some(p) = self.update.pending.take() else {
            return;
        };
        if matches!(p, Pending::Replaced { .. }) && !restart {
            return;
        }
        if restart && self.persist {
            // The new process restores this session, so it has to be on disk first.
            extras::save_now(self.persisted());
        }
        let result = match &p {
            Pending::Replaced { exe, .. } => update::relaunch(exe),
            Pending::Installer { setup, .. } => update::run_installer(setup, restart),
        };
        if let Err(e) = result {
            // The window is gone by now.
            rfd::MessageDialog::new()
                .set_level(rfd::MessageLevel::Error)
                .set_title("BigText")
                .set_description(trf(
                    "Could not start the update: {e}",
                    &[("e", &e.to_string())],
                ))
                .set_buttons(rfd::MessageButtons::Ok)
                .show();
        }
    }

    pub(super) fn update_dialog(&mut self, ctx: &egui::Context) {
        // Waits behind the other dialogs (unsaved changes, errors).
        if !self.update.dialog_open() || self.confirm.is_some() || self.error.is_some() {
            return;
        }
        let current = Version::current();
        let mut action = None;
        let u = &mut self.update;
        let auto = u.auto;
        let modal = egui::Modal::new(egui::Id::new("update")).show(ctx, |ui| {
            ui.set_width(560.0);
            match &u.stage {
                Stage::Idle => {}
                Stage::Ask => {
                    ui.heading(tr("Check for updates automatically?"));
                    ui.label(tr("BigText can ask GitHub once a day whether a newer version is out. Only that request goes out, with BigText's version; nothing about you or your files."));
                    ui.add_space(4.0);
                    ui.weak(tr("Help → Check for updates… works either way, and the Help menu changes this choice later."));
                    ui.add_space(6.0);
                    ui.horizontal(|ui| {
                        if ui.button(RichText::new(tr("Check automatically")).strong()).clicked() {
                            action = Some(Action::Auto(true));
                        }
                        if ui.button(tr("Don't check")).clicked() {
                            action = Some(Action::Auto(false));
                        }
                    });
                }
                Stage::Checking => {
                    ui.horizontal(|ui| {
                        ui.spinner();
                        ui.label(tr("Checking for updates…"));
                    });
                    ui.add_space(6.0);
                    if ui.button(tr("Cancel")).clicked() {
                        action = Some(Action::Close);
                    }
                }
                Stage::Offer(o) => {
                    ui.heading(tr("Update available"));
                    ui.label(trf("BigText {new} is available. You have {current}.", &[("new", &o.version.to_string()), ("current", &current.to_string())]));
                    ui.add_space(6.0);
                    notes_ui(ui, o);
                    ui.add_space(6.0);
                    match &o.method {
                        Method::Package(m) => {
                            let (text, command) = package_hint(*m);
                            ui.label(text);
                            ui.horizontal(|ui| {
                                ui.code(command);
                                if ui.small_button(tr("Copy")).clicked() {
                                    action = Some(Action::Copy(command));
                                }
                            });
                        }
                        Method::Manual => {
                            ui.label(tr("This release has no download for your platform."));
                        }
                        Method::Replace { .. } | Method::Installer { .. } => {}
                    }
                    let (update_now, download_page) = offer_buttons(&o.method);
                    ui.horizontal(|ui| {
                        if update_now && ui.button(RichText::new(tr("Update now")).strong()).clicked() {
                            action = Some(Action::Update);
                        }
                        if download_page && ui.button(tr("Open download page")).clicked() {
                            action = Some(Action::Open(o.page.clone()));
                        }
                        if ui.button(tr("Remind me later")).clicked() {
                            action = Some(Action::Close);
                        }
                        if ui.button(tr("Skip this version")).clicked() {
                            action = Some(Action::Skip);
                        }
                    });
                    ui.add_space(2.0);
                    ui.checkbox(&mut u.auto, tr("Check for updates automatically"));
                }
                Stage::Downloading { offer, progress, cancel } => {
                    ui.heading(trf("Downloading BigText {v}", &[("v", &offer.version.to_string())]));
                    ui.add_space(6.0);
                    let text = trf("{done} of {total}", &[("done", &human_bytes(progress.done())), ("total", &human_bytes(progress.total()))]);
                    ui.add(egui::ProgressBar::new(progress.fraction()).text(text));
                    ui.add_space(6.0);
                    if cancel.is_cancelled() {
                        ui.add_enabled(false, egui::Button::new(tr("Cancelling…")));
                    } else if ui.button(tr("Cancel")).clicked() {
                        action = Some(Action::Cancel);
                    }
                    ui.ctx().request_repaint_after(Duration::from_millis(100));
                }
                Stage::Ready => {
                    let (version, text) = match &u.pending {
                        Some(Pending::Replaced { version, .. }) => {
                            (*version, tr("The new version starts the next time you open BigText. Restart now to switch to it; your open files reopen."))
                        }
                        Some(Pending::Installer { version, .. }) => {
                            (*version, tr("The installer runs when BigText closes. Restart now to install it; BigText then reopens with your files."))
                        }
                        None => (current, ""),
                    };
                    ui.heading(trf("BigText {v} is ready", &[("v", &version.to_string())]));
                    ui.label(text);
                    ui.add_space(6.0);
                    ui.horizontal(|ui| {
                        if ui.button(RichText::new(tr("Restart now")).strong()).clicked() {
                            action = Some(Action::Restart);
                        }
                        if ui.button(tr("Later")).clicked() {
                            action = Some(Action::Close);
                        }
                    });
                }
                Stage::UpToDate => {
                    ui.heading(tr("BigText is up to date"));
                    ui.label(trf("You have the latest version, {v}.", &[("v", &current.to_string())]));
                    ui.add_space(6.0);
                    if ui.button(tr("OK")).clicked() {
                        action = Some(Action::Close);
                    }
                }
                Stage::Failed { title, message } => {
                    ui.heading(tr(title));
                    ui.label(message);
                    ui.add_space(6.0);
                    ui.horizontal(|ui| {
                        if ui.button(tr("Open download page")).clicked() {
                            action = Some(Action::Open(update::RELEASES_PAGE.into()));
                        }
                        if ui.button(tr("Close")).clicked() {
                            action = Some(Action::Close);
                        }
                    });
                }
            }
        });
        // Escape or a click outside: the same as "Remind me later" / "Later" / "Close"; the first
        // start's question comes back next time.
        if action.is_none() && modal.should_close() && !matches!(u.stage, Stage::Downloading { .. })
        {
            u.ask_later |= matches!(u.stage, Stage::Ask);
            action = Some(Action::Close);
        }
        if u.auto != auto {
            u.asked = true;
            self.persist_state();
        }
        match action {
            Some(Action::Update) => self.start_update(),
            Some(Action::Close) => self.update.stage = Stage::Idle,
            Some(Action::Skip) => {
                if let Stage::Offer(o) = mem::take(&mut self.update.stage) {
                    self.update.skipped = Some(o.version);
                    self.persist_state();
                }
            }
            Some(Action::Cancel) => {
                if let Stage::Downloading { cancel, .. } = &self.update.stage {
                    cancel.cancel();
                }
            }
            Some(Action::Restart) => {
                if self.writes_in_progress() {
                    self.error = Some(
                        tr("A file is being saved. Restart BigText when saving has finished.")
                            .into(),
                    );
                } else {
                    self.update.stage = Stage::Idle;
                    self.update.restart = true;
                    ctx.send_viewport_cmd(egui::ViewportCommand::Close);
                }
            }
            Some(Action::Auto(on)) => {
                let u = &mut self.update;
                (u.auto, u.asked, u.stage) = (on, true, Stage::Idle);
                self.persist_state();
            }
            Some(Action::Open(url)) => {
                ctx.open_url(egui::OpenUrl::new_tab(url));
                self.update.stage = Stage::Idle;
            }
            Some(Action::Copy(text)) => ctx.copy_text(text.into()),
            None => {}
        }
    }
}

fn notes_ui(ui: &mut egui::Ui, o: &Offer) {
    versions_ui(ui, &o.notes, 360.0);
    ui.hyperlink_to(tr("Full release notes on GitHub"), &o.page);
}

/// "What's new in X.Y.Z" and its notes for each version, newest first, in a scrolling box.
pub(super) fn versions_ui(ui: &mut egui::Ui, notes: &[(Version, Vec<Block>)], max_height: f32) {
    egui::Frame::new()
        .fill(ui.visuals().extreme_bg_color)
        .corner_radius(4.0)
        .inner_margin(10.0)
        .show(ui, |ui| {
            egui::ScrollArea::vertical()
                .max_height(max_height)
                .auto_shrink([false, true])
                .show(ui, |ui| {
                    for (v, blocks) in notes {
                        ui.label(
                            RichText::new(trf("What's new in {v}", &[("v", &v.to_string())]))
                                .strong()
                                .size(16.0),
                        );
                        if blocks.is_empty() {
                            ui.weak(tr("No release notes."));
                        }
                        for b in blocks {
                            block_ui(ui, b);
                        }
                        ui.add_space(10.0);
                    }
                });
        });
}

pub(super) fn block_ui(ui: &mut egui::Ui, b: &Block) {
    match b {
        Block::Heading(spans) => {
            ui.add_space(4.0);
            spans_ui(ui, spans, true);
        }
        Block::Paragraph(spans) => spans_ui(ui, spans, false),
        Block::Item(depth, spans) => {
            // Numbered items carry their number in the text.
            let numbered = matches!(spans.first(), Some(Span::Text(t)) if t.split_once(". ").is_some_and(|(n, _)| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit())));
            ui.horizontal(|ui| {
                ui.add_space(4.0 + 16.0 * *depth as f32);
                if !numbered {
                    ui.label("•");
                }
                spans_ui(ui, spans, false);
            });
        }
        Block::Code(text) => {
            ui.label(RichText::new(text.trim_end()).monospace());
        }
    }
}

/// One wrapped paragraph of inline spans.
fn spans_ui(ui: &mut egui::Ui, spans: &[Span], strong: bool) {
    ui.horizontal_wrapped(|ui| {
        ui.spacing_mut().item_spacing.x = 0.0;
        for s in spans {
            match s {
                Span::Text(t) if strong => {
                    ui.label(RichText::new(t).strong());
                }
                Span::Text(t) => {
                    ui.label(t);
                }
                Span::Strong(t) => {
                    ui.label(RichText::new(t).strong());
                }
                Span::Code(t) => {
                    ui.label(RichText::new(t).code());
                }
                Span::Link(t, url) => {
                    ui.hyperlink_to(t, url);
                }
            }
        }
    });
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn checks_on_its_own_only_after_the_user_agreed() {
        let restored = |check: Option<bool>, asked: Option<bool>| {
            let mut u = UpdateUi::default();
            u.restore(&Persisted {
                update_check: check,
                update_asked: asked,
                ..Default::default()
            });
            (u.asked, u.auto)
        };
        // A first start, and settings saved before the question with the old default (on): ask.
        assert_eq!(restored(None, None), (false, false));
        assert_eq!(restored(Some(true), None), (false, false));
        // Turned off before the question: that is an answer.
        assert_eq!(restored(Some(false), None), (true, false));
        assert_eq!(restored(Some(true), Some(true)), (true, true));
        assert_eq!(restored(Some(false), Some(true)), (true, false));
    }

    #[test]
    fn a_package_managers_copy_is_told_its_command() {
        let (scoop, cmd) = package_hint(Manager::Scoop);
        assert_eq!(
            (scoop.as_str(), cmd),
            (
                "This copy was installed with Scoop. To update it, run:",
                "scoop update bigtext"
            )
        );
        assert!(package_hint(Manager::Homebrew).0.contains("Homebrew"));
        assert!(package_hint(Manager::Deb)
            .0
            .contains("Download the new package"));
        assert!(package_hint(Manager::Aur).0.contains("AUR helper"));
        // Only a copy BigText can replace gets "Update now"; the .deb gets the download page.
        let asset = update::Asset {
            name: "bigtext-linux-x64.AppImage".into(),
            url: String::new(),
            size: 1,
            sha256: None,
        };
        assert_eq!(
            offer_buttons(&Method::Replace {
                asset: asset.clone(),
                exe: PathBuf::from("/a/b.AppImage")
            }),
            (true, false)
        );
        assert_eq!(offer_buttons(&Method::Installer { asset }), (true, false));
        assert_eq!(
            offer_buttons(&Method::Package(Manager::Scoop)),
            (false, false)
        );
        assert_eq!(offer_buttons(&Method::Package(Manager::Deb)), (false, true));
        assert_eq!(offer_buttons(&Method::Manual), (false, true));
    }
}