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
//! The status bar: every field is a control (Ln/Col goes to a line, the encoding reopens, the
//! line ending picks the one to save with, READ-ONLY turns it off), and right-click or … chooses
//! which fields are shown.

use std::time::Duration;

use egui::{Align, CursorIcon, Layout, RichText};

use bigtext::encoding::{Encoding, LineEnding};
use bigtext::file;
use bigtext::jobs::human_bytes;

use super::commands::Cmd;
use super::i18n::{tr, trf};
use super::{filter_panel, follow_id, marks, BigTextApp};

/// Which fields the status bar shows.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct StatusFields {
    pub offset: bool,
    /// Lines, characters and bytes selected.
    pub sel: bool,
    /// Time since the previous line, and across the selection.
    pub dt: bool,
    /// A merged log's files in their colours (otherwise "N files").
    pub legend: bool,
    /// How the file is read (mapped, chunked).
    pub kind: bool,
    pub index_time: bool,
    pub path: bool,
}

impl Default for StatusFields {
    fn default() -> Self {
        StatusFields {
            offset: true,
            sel: true,
            dt: true,
            legend: true,
            kind: false,
            index_time: false,
            path: false,
        }
    }
}

impl StatusFields {
    /// Names in a `status=` line.
    const NAMES: [&'static str; 7] = [
        "offset",
        "selection",
        "time",
        "legend",
        "access",
        "index-time",
        "path",
    ];

    fn flags(&mut self) -> [&mut bool; 7] {
        [
            &mut self.offset,
            &mut self.sel,
            &mut self.dt,
            &mut self.legend,
            &mut self.kind,
            &mut self.index_time,
            &mut self.path,
        ]
    }

    /// The fields shown, "offset,selection,…".
    pub fn to_line(mut self) -> String {
        Self::NAMES
            .iter()
            .zip(self.flags())
            .filter(|(_, on)| **on)
            .map(|(n, _)| *n)
            .collect::<Vec<_>>()
            .join(",")
    }

    pub fn from_line(v: &str) -> StatusFields {
        let on: Vec<&str> = v.split(',').map(str::trim).collect();
        let mut f = StatusFields::default();
        for (n, flag) in Self::NAMES.iter().zip(f.flags()) {
            *flag = on.contains(n);
        }
        f
    }

    /// The checkboxes of the field menu: returns the new choice when one was flipped.
    fn menu(mut self, ui: &mut egui::Ui) -> Option<StatusFields> {
        let old = self;
        ui.label(RichText::new(tr("Show in the status bar")).strong());
        let labels = [
            tr("Byte offset"),
            tr("Selection size"),
            tr("Time since the previous line"),
            tr("Merged log's files"),
            tr("File access (mapped or chunked)"),
            tr("Indexing time"),
            tr("File path"),
        ];
        for (label, flag) in labels.into_iter().zip(self.flags()) {
            ui.checkbox(flag, label);
        }
        (self != old).then_some(self)
    }
}

/// Whether a file mixes lone CRs into LF line breaks, so that a conversion can turn them into
/// line breaks too.
pub(crate) fn lone_cr_applies(d: &super::document::Document) -> bool {
    d.line_ending == LineEnding::Mixed && d.buf.codec.nl == bigtext::encoding::NlByte::Lf
}

/// What a click in the status bar asks for, done once the bar is drawn.
#[derive(Clone, Debug, PartialEq)]
pub(crate) enum StatusAct {
    GotoLine,
    GotoOffset,
    Reopen(Option<Encoding>),
    Eol(Option<LineEnding>),
    LoneCr(bool),
    ToggleReadOnly,
    CopyPath,
    Fields(StatusFields),
    /// The skew of a link by time, in milliseconds.
    Skew(i64),
    /// A part of the JSON path: go to it (when the text is still that version).
    JsonGoto {
        version: u64,
        off: u64,
    },
    CopyText(String),
    Alerts,
}

/// The JSON path, `$ › items › [3] › city` (the last four parts): a click goes to that part, a
/// right-click copies the whole path. Greyed while it is for an older caret or version.
fn crumb(
    ui: &mut egui::Ui,
    c: &super::json_crumb::JsonCrumb,
    stale: bool,
    acts: &mut Vec<StatusAct>,
) {
    let path = c.path();
    let tip = format!(
        "{path}\n{}",
        tr("Click a part to go to it; right-click copies the path")
    );
    let short = |s: String| {
        if s.chars().count() > 24 {
            s.chars().take(23).chain(['…']).collect()
        } else {
            s
        }
    };
    let parts: Vec<String> = c
        .steps
        .iter()
        .map(|(s, _)| {
            short(match s {
                bigtext::json::Step::Key(k) => k.clone(),
                bigtext::json::Step::Index(i) => format!("[{i}]"),
            })
        })
        .collect();
    let skip = parts.len().saturating_sub(4);
    ui.spacing_mut().item_spacing.x = 3.0;
    let mut part = |ui: &mut egui::Ui, text: String, off: u64| {
        let text = if stale {
            RichText::new(text).weak()
        } else {
            RichText::new(text)
        };
        let r = ui.add(egui::Link::new(text)).on_hover_text(&tip);
        if r.clicked() {
            acts.push(StatusAct::JsonGoto {
                version: c.version,
                off,
            });
        }
        if r.secondary_clicked() {
            acts.push(StatusAct::CopyText(path.clone()));
        }
    };
    part(ui, "$".into(), 0);
    if skip > 0 {
        ui.weak("› …").on_hover_text(&tip);
    }
    for (i, p) in parts.into_iter().enumerate().skip(skip) {
        ui.weak("›");
        part(ui, p, c.steps[i].1);
    }
    if let Some((_, _, p)) = &c.building {
        ui.add(egui::ProgressBar::new(p.fraction()).desired_width(60.0))
            .on_hover_text(tr("Reading the JSON's structure"));
    }
}

/// A field that does something when clicked.
fn field(ui: &mut egui::Ui, text: impl Into<egui::WidgetText>, tip: &str) -> egui::Response {
    ui.add(egui::Button::new(text).frame(false))
        .on_hover_cursor(CursorIcon::PointingHand)
        .on_hover_text(tip)
}

/// A field that opens a menu.
fn field_menu(
    ui: &mut egui::Ui,
    text: impl Into<egui::WidgetText>,
    tip: &str,
    content: impl FnOnce(&mut egui::Ui),
) {
    let (r, _) =
        egui::containers::menu::MenuButton::from_button(egui::Button::new(text).frame(false))
            .ui(ui, content);
    r.on_hover_cursor(CursorIcon::PointingHand)
        .on_hover_text(tip);
}

impl BigTextApp {
    pub(super) fn status_bar(&mut self, ui: &mut egui::Ui) {
        let ids = self.caret_ids();
        let delta = self.caret_time_delta();
        let fields = self.settings.status;
        let json_crumb = self.settings.json_crumb;
        // The command a field runs, with its shortcut.
        let tip = |cmd: Cmd| match self.keymap.get(cmd) {
            Some(k) => format!("{} ({})", tr(cmd.label()), super::commands::key_text(k)),
            None => tr(cmd.label()).to_string(),
        };
        let (line_tip, offset_tip) = (tip(Cmd::GotoLine), tip(Cmd::GotoOffset));
        let mut follow = None;
        let mut acts = Vec::new();
        // A horizontal layout's response only hovers: the scope takes the right-click.
        let bar = ui.scope_builder(egui::UiBuilder::new().sense(egui::Sense::click()), |ui| {
            ui.horizontal(|ui| {
                if let Some(d) = self.docs.get(self.active).filter(|d| d.is_ready()) {
                    let caret = d.view.caret;
                    let (line, exact) = d.buf.line_of(caret);
                    let col = match d.buf.line_start(line) {
                        Some((ls, true)) if caret >= ls && caret - ls <= 128 * 1024 => {
                            let b = d.buf.read(ls..caret);
                            b.map(|b| format!("{}", bigtext::text::rows::cell_width(&d.buf.codec, &b, ls) + 1)).unwrap_or_else(|| "…".into())
                        }
                        Some((ls, _)) if caret >= ls => format!("~{}", caret - ls + 1),
                        _ => "?".into(),
                    };
                    let pos = trf("Ln {line}, Col {col}", &[("line", &format!("{}{}", if exact { "" } else { "~" }, line + 1)), ("col", &col)]);
                    if field(ui, pos, &line_tip).clicked() {
                        acts.push(StatusAct::GotoLine);
                    }
                    if let Some(ms) = delta.filter(|_| fields.dt) {
                        ui.separator();
                        ui.label(format!("Δ {}", bigtext::timestamp::format_delta(ms))).on_hover_text(tr("Time since the previous line with a timestamp"));
                    }
                    if !d.view.extra.is_empty() {
                        ui.separator();
                        ui.label(trf("{n} cursors", &[("n", &(d.view.extra.len() + 1).to_string())])).on_hover_text(tr("Esc: back to one cursor"));
                    }
                    if fields.offset {
                        ui.separator();
                        if field(ui, trf("Offset {n}", &[("n", &format!("{caret} (0x{caret:X})"))]), &offset_tip).clicked() {
                            acts.push(StatusAct::GotoOffset);
                        }
                    }
                    if let Some(c) = d.json_crumb.as_ref().filter(|c| json_crumb && !c.steps.is_empty() && c.version != u64::MAX) {
                        ui.separator();
                        crumb(ui, c, c.version != d.version || c.caret != d.view.caret || c.error, &mut acts);
                    }
                    if let Some((lines, exact, chars, bytes)) = d.selection_stats().filter(|_| fields.sel) {
                        ui.separator();
                        let n = |x: u64| filter_panel::fmt_count(x);
                        let lines = format!("{}{}", if exact { "" } else { "~" }, n(lines));
                        let text = match chars {
                            Some(c) => trf("Sel: {lines} lines, {chars} chars, {bytes} bytes", &[("lines", &lines), ("chars", &n(c)), ("bytes", &n(bytes))]),
                            None => trf("Sel: {lines} lines, {bytes} bytes", &[("lines", &lines), ("bytes", &n(bytes))]),
                        };
                        ui.label(text);
                        if let Some(ms) = d.selection_time_delta().filter(|_| fields.dt) {
                            ui.separator();
                            ui.label(format!("Δt {}", bigtext::timestamp::format_delta(ms))).on_hover_text(tr("Time between the timestamps of the first and last selected lines"));
                        }
                    }
                    if let Some(b) = d.view.block {
                        let (lo, hi) = b.cells();
                        ui.separator();
                        ui.label(trf("Block: {cols} columns wide", &[("cols", &(hi - lo).to_string())]));
                    }
                    let (lines, lexact) = d.buf.line_count();
                    ui.separator();
                    ui.label(trf("{n} lines", &[("n", &format!("{}{}", if lexact { "" } else { "~" }, lines))]));
                    if !ids.is_empty() {
                        ui.separator();
                        follow = follow_id::id_chips(ui, &ids);
                    }
                    // The colours of a merged log's files.
                    if let Some(t) = &d.merged {
                        ui.separator();
                        let dark = ui.visuals().dark_mode;
                        if fields.legend {
                            for (i, l) in t.labels.iter().enumerate() {
                                ui.label(RichText::new(l).background_color(marks::fill(i, dark)));
                            }
                        } else {
                            ui.label(trf("{n} files", &[("n", &t.labels.len().to_string())])).on_hover_ui(|ui| {
                                for (i, l) in t.labels.iter().enumerate() {
                                    ui.label(RichText::new(l).background_color(marks::fill(i, dark)));
                                }
                            });
                        }
                    }
                }
                ui.with_layout(Layout::right_to_left(Align::Center), |ui| {
                    // For trackpads, where a right-click is awkward.
                    field_menu(ui, "…", tr("Choose the fields of the status bar"), |ui| {
                        if let Some(f) = fields.menu(ui) {
                            acts.push(StatusAct::Fields(f));
                        }
                    });
                    self.tasks_status(ui);
                    let Some(d) = self.docs.get(self.active) else { return };
                    if let Some((p, c)) = &d.growing {
                        if ui.small_button(tr("Cancel")).on_hover_text(tr("Stop unpacking; what is unpacked stays open")).clicked() {
                            c.cancel();
                        }
                        ui.add(egui::ProgressBar::new(p.fraction()).desired_width(140.0).text(format!("{} {:.0}%", tr("Unpacking"), p.fraction() * 100.0)));
                        ui.ctx().request_repaint_after(Duration::from_millis(250));
                        ui.separator();
                    }
                    if let Some(j) = &d.save_job {
                        if ui.small_button(tr("Cancel")).clicked() {
                            j.cancel.cancel();
                        }
                        ui.add(egui::ProgressBar::new(j.progress.fraction()).desired_width(160.0).text(format!("{} {:.0}%", j.label, j.progress.fraction() * 100.0)));
                        ui.separator();
                    }
                    if d.follow {
                        let label = if d.rotations > 0 { format!("{} ×{}", tr("FOLLOW"), d.rotations + 1) } else { tr("FOLLOW").to_string() };
                        ui.label(RichText::new(label).color(super::theme::ok_text(ui))).on_hover_text(trf("Following the file; it was rotated {n} times so far", &[("n", &d.rotations.to_string())]));
                        ui.separator();
                    }
                    if let Some(a) = &d.alerts {
                        let text = RichText::new(format!("🔔 {}", super::filter_panel::fmt_count(a.total)));
                        let text = if a.total > 0 { text.color(super::theme::warn_text(ui)) } else { text };
                        let tip = trf("Alerts on new lines: {n} patterns; click to see the lines that matched", &[("n", &a.patterns.len().to_string())]);
                        if ui.add(egui::Label::new(text).sense(egui::Sense::click())).on_hover_text(tip).clicked() {
                            acts.push(StatusAct::Alerts);
                        }
                        ui.separator();
                    }
                    if let Some(l) = d.link.as_ref().filter(|l| l.mode == super::time_link::LinkMode::Time) {
                        let mut secs = l.skew_ms as f64 / 1000.0;
                        let r = ui.add(egui::DragValue::new(&mut secs).speed(0.1).suffix(" s").max_decimals(3));
                        if r.on_hover_text(tr("Added to this log's times before they are looked up in the linked one")).changed() {
                            acts.push(StatusAct::Skew((secs * 1000.0).round() as i64));
                        }
                        ui.label(tr("Skew"));
                        ui.separator();
                    }
                    if d.table && !d.hex {
                        let delim = d.table_state.dialect.map(|x| tr(x.name())).unwrap_or("…");
                        ui.label(RichText::new(format!("{} · {delim}", tr("TABLE"))).color(super::theme::info_text(ui)));
                        ui.separator();
                    }
                    if let Some(r) = d.results.as_ref().filter(|r| r.is_running()) {
                        ui.add(egui::ProgressBar::new(r.progress.fraction()).desired_width(140.0).text(format!("{} {:.0}%", tr("Searching"), r.progress.fraction() * 100.0)));
                        ui.separator();
                    } else if d.find_job.is_some() {
                        ui.label(tr("Searching…"));
                        ui.separator();
                    }
                    if d.read_only {
                        let text = RichText::new(tr("READ-ONLY")).color(super::theme::warn_text(ui));
                        // A merged log has no file of its own to edit.
                        if d.merged.is_some() || d.growing.is_some() {
                            ui.label(text);
                        } else if field(ui, text, tr("Click to allow editing")).clicked() {
                            acts.push(StatusAct::ToggleReadOnly);
                        }
                        ui.separator();
                    }
                    if fields.kind {
                        ui.label(d.buf.source.kind_name());
                        ui.separator();
                    }
                    ui.label(human_bytes(d.buf.len()));
                    ui.separator();
                    let eol = match d.eol_on_save {
                        Some(to) if to != d.line_ending => format!("{} → {}", d.line_ending.name(), to.name()),
                        _ => d.line_ending.name().to_string(),
                    };
                    field_menu(ui, eol, tr("Line endings on save"), |ui| {
                        for (to, label) in [(None, "Keep as is"), (Some(LineEnding::Lf), "Convert to LF"), (Some(LineEnding::CrLf), "Convert to CRLF"), (Some(LineEnding::Cr), "Convert to CR")] {
                            if ui.radio(d.eol_on_save == to, tr(label)).clicked() {
                                acts.push(StatusAct::Eol(to));
                            }
                        }
                        if lone_cr_applies(d) {
                            ui.separator();
                            let mut on = d.eol_lone_cr;
                            let can = matches!(d.eol_on_save, Some(LineEnding::Lf | LineEnding::CrLf));
                            if ui.add_enabled(can, egui::Checkbox::new(&mut on, tr("Lone CR characters become line breaks too"))).on_hover_text(tr("Otherwise a CR not followed by LF (shown as ←) stays as it is")).changed() {
                                acts.push(StatusAct::LoneCr(on));
                            }
                        }
                    });
                    ui.separator();
                    field_menu(ui, d.buf.codec.enc.name(), tr("Reopen with encoding"), |ui| {
                        if ui.add_enabled(d.forced_enc.is_some(), egui::Button::new(tr("Auto-detect (forget)"))).clicked() {
                            acts.push(StatusAct::Reopen(None));
                        }
                        ui.separator();
                        for enc in Encoding::ALL {
                            if ui.radio(d.forced_enc == Some(enc), enc.name()).clicked() {
                                acts.push(StatusAct::Reopen(Some(enc)));
                            }
                        }
                    });
                    if d.is_ready() && d.buf.source.is_remote() {
                        // Read in place: how much of the remote file came over so far.
                        ui.separator();
                        let read = d.buf.source.bytes_read();
                        ui.label(trf("{read} of {size} read", &[("read", &human_bytes(read)), ("size", &human_bytes(d.buf.source.len()))]))
                            .on_hover_text(tr("A remote file read in place: only what is shown, and what a search reaches, is downloaded."));
                        if d.buf.source.has_io_error() {
                            ui.colored_label(ui.visuals().error_fg_color, tr("read failed"));
                        }
                    } else if d.is_ready() && !d.buf.index.is_done() && !d.buf.is_empty() {
                        ui.separator();
                        ui.add(egui::ProgressBar::new(d.buf.index.progress()).desired_width(120.0).text(format!("{} {:.0}%", tr("Indexing"), d.buf.index.progress() * 100.0)));
                    } else if let Some(t) = d.buf.index.finished_after().filter(|t| fields.index_time && *t > Duration::ZERO) {
                        ui.separator();
                        ui.label(trf("Indexed in {t}s", &[("t", &format!("{:.2}", t.as_secs_f32()))]));
                    }
                    if let Some(p) = d.unpacked_from.as_deref().or(d.path.as_deref()).filter(|_| fields.path) {
                        ui.separator();
                        let r = ui.add(egui::Label::new(file::display_path(p)).truncate().sense(egui::Sense::click()));
                        if r.on_hover_cursor(CursorIcon::PointingHand).on_hover_text(tr("Click to copy the path")).clicked() {
                            acts.push(StatusAct::CopyPath);
                        }
                    }
                });
            });
        });
        if let Some(t) = &self.announcement {
            crate::view::a11y::live_region(ui.ctx(), egui::Id::new("bigtext-announcement"), t);
        }
        bar.response.context_menu(|ui| {
            if let Some(f) = fields.menu(ui) {
                acts.push(StatusAct::Fields(f));
            }
        });
        let ctx = ui.ctx().clone();
        for a in acts {
            self.status_act(&ctx, a);
        }
        if let Some(id) = follow {
            self.follow_id(&id);
        }
    }

    /// Zen mode's menu bar, floating over the text while the pointer is at the top edge (a panel
    /// would move the text), it is hovered or one of its menus is open.
    pub(super) fn zen_menu(&mut self, ctx: &egui::Context) {
        let id = egui::Id::new("zen-menu");
        let near_top = ctx.input(|i| i.pointer.hover_pos().is_some_and(|p| p.y <= 4.0));
        let was_shown = ctx.data(|d| d.get_temp::<bool>(id).unwrap_or(false));
        let hovered = was_shown
            && ctx.input(|i| i.pointer.hover_pos()).is_some_and(|p| {
                ctx.layer_id_at(p)
                    .is_some_and(|l| l.id == id || l.order == egui::Order::Foreground)
            });
        let show = near_top || hovered || egui::Popup::is_any_open(ctx);
        ctx.data_mut(|d| d.insert_temp(id, show));
        // How to get out, for a few seconds after going in.
        let since = ctx.data(|d| d.get_temp::<std::time::Instant>(egui::Id::new("zen-hint")));
        if let Some(t) = since.filter(|t| t.elapsed() < Duration::from_secs(4)) {
            let key = self
                .keymap
                .get(Cmd::Zen)
                .map(super::commands::key_text)
                .unwrap_or_else(|| tr(Cmd::Zen.label()).to_string());
            let hint = trf(
                "Zen mode: Esc or {key} leaves it; move the pointer to the top edge for the menu.",
                &[("key", &key)],
            );
            egui::Area::new(egui::Id::new("zen-hint-area"))
                .order(egui::Order::Tooltip)
                .anchor(egui::Align2::CENTER_TOP, egui::vec2(0.0, 12.0))
                .interactable(false)
                .show(ctx, |ui| {
                    egui::Frame::popup(ui.style()).show(ui, |ui| ui.label(hint));
                });
            ctx.request_repaint_after(Duration::from_secs(4).saturating_sub(t.elapsed()));
        }
        if !show {
            return;
        }
        let width = ctx.content_rect().width();
        egui::Area::new(id)
            .order(egui::Order::Foreground)
            .fixed_pos(egui::pos2(0.0, 0.0))
            .show(ctx, |ui| {
                egui::Frame::side_top_panel(ui.style()).show(ui, |ui| {
                    ui.set_width(width);
                    self.menu_bar(ui);
                });
            });
    }

    /// Says `text` to screen readers.
    pub(crate) fn announce(&mut self, text: impl Into<String>) {
        self.announcement = Some(text.into());
    }

    /// Announces how many matches a Find All found once it is done.
    pub(super) fn announce_results(&mut self) {
        let Some(d) = self.docs.get(self.active) else {
            return;
        };
        let running = d.results.as_ref().is_some_and(|r| r.is_running());
        if !std::mem::replace(&mut self.results_running, running) || running {
            return;
        }
        if let Some(n) = d
            .results
            .as_ref()
            .map(|r| r.data.lock().unwrap().matches.len())
        {
            self.announce(trf("{n} matches", &[("n", &n.to_string())]));
        }
    }

    pub(crate) fn status_act(&mut self, ctx: &egui::Context, a: StatusAct) {
        match a {
            StatusAct::GotoLine => self.run(ctx, Cmd::GotoLine),
            StatusAct::Alerts => self.open_alerts(),
            StatusAct::GotoOffset => self.run(ctx, Cmd::GotoOffset),
            StatusAct::Reopen(enc) => self.reopen_with(enc),
            StatusAct::Eol(to) => {
                if let Some(d) = self.docs.get_mut(self.active) {
                    d.eol_on_save = to;
                }
            }
            StatusAct::LoneCr(on) => {
                if let Some(d) = self.docs.get_mut(self.active) {
                    d.eol_lone_cr = on;
                }
            }
            StatusAct::ToggleReadOnly => self.run(ctx, Cmd::ReadOnly),
            StatusAct::CopyPath => {
                if let Some(p) = self
                    .docs
                    .get(self.active)
                    .and_then(|d| d.unpacked_from.as_deref().or(d.path.as_deref()))
                {
                    ctx.copy_text(file::display_path(p));
                }
            }
            StatusAct::JsonGoto { version, off } => {
                if let Some(d) = self
                    .docs
                    .get_mut(self.active)
                    .filter(|d| d.version == version)
                {
                    d.goto_offset(off);
                }
            }
            StatusAct::CopyText(t) => {
                ctx.copy_text(t);
                self.announce(tr("Copied"));
            }
            StatusAct::Skew(ms) => {
                if let Some(l) = self.docs.get_mut(self.active).and_then(|d| d.link.as_mut()) {
                    l.skew_ms = ms;
                    l.synced = None;
                }
            }
            StatusAct::Fields(f) => {
                self.settings.status = f;
                self.persist_state();
            }
        }
    }
}

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

    #[test]
    fn fields_line() {
        let d = StatusFields::default();
        assert_eq!(d.to_line(), "offset,selection,time,legend");
        assert_eq!(StatusFields::from_line(&d.to_line()), d);
        let f = StatusFields {
            offset: false,
            path: true,
            index_time: true,
            ..d
        };
        assert_eq!(StatusFields::from_line(&f.to_line()), f);
        assert_eq!(
            StatusFields::from_line(""),
            StatusFields {
                offset: false,
                sel: false,
                dt: false,
                legend: false,
                kind: false,
                index_time: false,
                path: false
            }
        );
    }
}