bigtext 0.16.3

Free editor for huge text and log files (1-50+ GB): opens them without loading them into memory, 4 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
//! Interface languages. The English text in the code is the key: [`tr`] returns its translation
//! for the chosen language, or the English text when there is none.

use std::collections::HashMap;
use std::sync::atomic::{AtomicU8, Ordering};
use std::sync::OnceLock;

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Lang {
    En,
    Ru,
    Uz,
    /// Simplified Chinese.
    Zh,
    Es,
    /// Brazilian Portuguese.
    Pt,
    De,
    Tr,
}

impl Lang {
    pub const ALL: [Lang; 8] = [
        Lang::En,
        Lang::Ru,
        Lang::Uz,
        Lang::Zh,
        Lang::Es,
        Lang::Pt,
        Lang::De,
        Lang::Tr,
    ];

    /// Native name, shown in the language menu.
    pub fn name(self) -> &'static str {
        match self {
            Lang::En => "English",
            Lang::Ru => "Русский",
            Lang::Uz => "O'zbekcha",
            Lang::Zh => "简体中文",
            Lang::Es => "Español",
            Lang::Pt => "Português",
            Lang::De => "Deutsch",
            Lang::Tr => "Türkçe",
        }
    }

    pub fn code(self) -> &'static str {
        match self {
            Lang::En => "en",
            Lang::Ru => "ru",
            Lang::Uz => "uz",
            Lang::Zh => "zh",
            Lang::Es => "es",
            Lang::Pt => "pt",
            Lang::De => "de",
            Lang::Tr => "tr",
        }
    }

    pub fn from_code(s: &str) -> Option<Lang> {
        Lang::ALL.into_iter().find(|l| l.code() == s)
    }
}

static LANG: AtomicU8 = AtomicU8::new(0);

pub fn set_lang(l: Lang) {
    LANG.store(l as u8, Ordering::Relaxed);
}

pub fn lang() -> Lang {
    Lang::ALL
        .get(LANG.load(Ordering::Relaxed) as usize)
        .copied()
        .unwrap_or(Lang::En)
}

/// The language the system is set to, when BigText speaks it (for a first start).
pub fn system_lang() -> Option<Lang> {
    let tag = os_locale()?;
    let primary = tag.split(['-', '_', '.', '@']).next()?.to_ascii_lowercase();
    Lang::from_code(&primary)
}

#[cfg(windows)]
fn os_locale() -> Option<String> {
    use windows_sys::Win32::Globalization::GetUserDefaultLocaleName;
    let mut buf = [0u16; 85];
    // SAFETY: the buffer is as long as the length passed.
    let n = unsafe { GetUserDefaultLocaleName(buf.as_mut_ptr(), buf.len() as i32) };
    (n > 1).then(|| String::from_utf16_lossy(&buf[..n as usize - 1]))
}

#[cfg(not(windows))]
fn os_locale() -> Option<String> {
    ["LC_ALL", "LC_MESSAGES", "LANG"].iter().find_map(|k| {
        std::env::var(k)
            .ok()
            .filter(|v| !v.is_empty() && v != "C" && v != "POSIX")
    })
}

type Table = HashMap<&'static str, &'static str>;

fn table(l: Lang) -> Option<&'static Table> {
    static TABLES: [OnceLock<Table>; 8] = [const { OnceLock::new() }; 8];
    let column = |col: usize| -> Table {
        TEXTS
            .iter()
            .map(|t| (t[0], t[col]))
            .filter(|(_, v)| !v.is_empty())
            .collect()
    };
    let pairs = |p: &'static [(&'static str, &'static str)]| -> Table {
        p.iter().copied().filter(|(_, v)| !v.is_empty()).collect()
    };
    let cell = &TABLES[l as usize];
    Some(match l {
        Lang::En => return None,
        Lang::Ru => cell.get_or_init(|| column(1)),
        Lang::Uz => cell.get_or_init(|| column(2)),
        Lang::Zh => cell.get_or_init(|| pairs(super::i18n_zh::ZH)),
        Lang::Es => cell.get_or_init(|| pairs(super::i18n_es::ES)),
        Lang::Pt => cell.get_or_init(|| pairs(super::i18n_pt::PT)),
        Lang::De => cell.get_or_init(|| pairs(super::i18n_de::DE)),
        Lang::Tr => cell.get_or_init(|| pairs(super::i18n_tr::TR)),
    })
}

/// The interface text `s` in the current language.
pub fn tr(s: &'static str) -> &'static str {
    match table(lang()) {
        Some(t) => t.get(s).copied().unwrap_or(s),
        None => s,
    }
}

/// [`tr`] with `{name}` placeholders filled in.
pub fn trf(s: &'static str, args: &[(&str, &str)]) -> String {
    let mut out = tr(s).to_string();
    for (k, v) in args {
        out = out.replace(&format!("{{{k}}}"), v);
    }
    out
}

use super::i18n_texts::TEXTS;

impl super::BigTextApp {
    /// View → Language.
    pub(super) fn language_menu(&mut self, ui: &mut egui::Ui) {
        ui.menu_button(format!("{} (Language)", tr("Language")), |ui| {
            for l in Lang::ALL {
                if ui.radio(lang() == l, l.name()).clicked() {
                    set_lang(l);
                    // Chinese needs a font with its characters.
                    let _ = super::fonts::apply_font(ui.ctx(), self.settings.font_path.as_deref());
                    self.persist_state();
                    ui.close();
                }
            }
        });
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::app::commands::Cmd;

    macro_rules! sources {
        ($($dir:literal / $file:literal),* $(,)?) => {
            &[$((concat!($dir, "/", $file), include_str!(concat!("../", $dir, "/", $file)))),*]
        };
    }

    /// The scanned files (path under `src`, content).
    const SOURCES: &[(&str, &str)] = sources![
        "app" / "mod.rs",
        "app" / "welcome.rs",
        "app" / "archive.rs",
        "app" / "column_chart.rs",
        "app" / "clipboard.rs",
        "app" / "column_editor.rs",
        "app" / "columns.rs",
        "app" / "copy_as.rs",
        "app" / "commands.rs",
        "app" / "convert.rs",
        "app" / "csv_tools.rs",
        "app" / "derive_column.rs",
        "app" / "document.rs",
        "app" / "export.rs",
        "app" / "extras.rs",
        "app" / "fields_panel.rs",
        "app" / "filter_panel.rs",
        "app" / "find_in_files.rs",
        "app" / "file_ops.rs",
        "app" / "folder_tree.rs",
        "app" / "quick_open.rs",
        "app" / "remote.rs",
        "app" / "symbols.rs",
        "app" / "fold.rs",
        "app" / "follow_id.rs",
        "app" / "gaps_panel.rs",
        "app" / "fonts.rs",
        "app" / "join_tables.rs",
        "app" / "json_crumb.rs",
        "app" / "json_diff_panel.rs",
        "app" / "json_fields_window.rs",
        "app" / "json_panel.rs",
        "app" / "json_validate.rs",
        "app" / "keynav.rs",
        "app" / "levels.rs",
        "app" / "lines_edit.rs",
        "app" / "marks.rs",
        "app" / "match_bracket.rs",
        "app" / "match_values.rs",
        "app" / "merge_logs.rs",
        "app" / "multi_cursor.rs",
        "app" / "nav.rs",
        "app" / "only_in.rs",
        "app" / "ops.rs",
        "app" / "patterns_window.rs",
        "app" / "log_report.rs",
        "app" / "log_sources.rs",
        "app" / "alerts.rs",
        "app" / "share.rs",
        "app" / "sql_dump.rs",
        "app" / "pivot.rs",
        "app" / "portable.rs",
        "app" / "properties.rs",
        "app" / "recovery.rs",
        "app" / "problems_panel.rs",
        "app" / "run_command.rs",
        "app" / "saved_searches.rs",
        "app" / "search_panel.rs",
        "app" / "table_compare.rs",
        "app" / "sessions.rs",
        "app" / "shell.rs",
        "app" / "status_bar.rs",
        "app" / "tabs.rs",
        "app" / "tasks.rs",
        "app" / "theme.rs",
        "app" / "time_link.rs",
        "app" / "text_tools.rs",
        "app" / "time_range.rs",
        "app" / "timeline.rs",
        "app" / "update.rs",
        "view" / "block.rs",
        "view" / "hex_view.rs",
        "view" / "table_view.rs",
        "view" / "text_view.rs",
    ];

    #[test]
    fn every_file_with_texts_is_scanned() {
        let src = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("src");
        for dir in ["app", "view"] {
            for e in std::fs::read_dir(src.join(dir)).unwrap().flatten() {
                let name = format!("{dir}/{}", e.file_name().to_string_lossy());
                let text = std::fs::read_to_string(e.path()).unwrap_or_default();
                let uses = !keys_in(&text).is_empty();
                assert!(
                    !uses || name == "app/i18n.rs" || SOURCES.iter().any(|s| s.0 == name),
                    "add {name} to SOURCES in i18n.rs"
                );
            }
        }
    }

    /// Texts translated through a variable rather than a literal at the call.
    const DYNAMIC: &[&str] = &[
        "MySQL / MariaDB dump",
        "PostgreSQL dump",
        "SQLite dump",
        "SQL dump",
        "nginx / Apache access log",
        "AWS Application Load Balancer log",
        "AWS Classic Load Balancer log",
        "IIS log (W3C)",
        "syslog",
        "syslog (RFC 5424)",
        "Top URLs",
        "5xx per minute",
        "Slowest requests",
        "Count rows",
        "Sum",
        "Mean",
        "Minimum",
        "Maximum",
        "Each value",
        "By hour",
        "By day",
        "By month",
        "By time",
        "By line number",
        "By position in the file",
        "Link scrolling with this tab",
        "Unlink",
        "Tab 1",
        "Tab 2",
        "Tab 3",
        "Tab 4",
        "Tab 5",
        "Tab 6",
        "Tab 7",
        "Tab 8",
        "Last tab",
        "Comma",
        "Semicolon",
        "Tab",
        "Pipe",
        "Other",
        "Discard",
        "Replace on disk",
        "Copy",
        "Delete",
        "Rewrite",
        "Could not check for updates",
        "The update failed",
        "Saving",
        "Replacing",
        "Deleting columns",
        "Rewriting",
        "Go to line",
        "Go to byte offset",
        "Go to time",
        "UTF-8 with BOM",
        "GitHub",
        "Repository",
        "Telegram",
        "E-mail",
        "Word movement / delete word",
        "Line start (smart) / end, document start / end",
        "Zoom",
        "Select word / line",
        "Column (block) selection",
        "Add a cursor",
        "Back to one cursor",
        "Search history",
        "Language",
        "Errors",
        "Search matches",
        "Lines only",
        "contains",
        "does not contain",
        "is",
        "is not",
        ">",
        "<",
        "is empty",
        "is not empty",
        "JSON",
        "JSON Lines",
        "Markdown table",
        "Excel workbook (.xlsx)",
        "Pin tab",
        "Unpin tab",
        "Close",
        "Close tabs to the right",
        "Copy path",
        "Show in folder",
        "Open terminal here",
        "Open with the default app",
    ];

    /// String literals in `span` (escapes resolved).
    fn literals(span: &str) -> Vec<String> {
        let mut out = Vec::new();
        let mut it = span.chars().peekable();
        let mut prev = ' ';
        while let Some(c) = it.next() {
            if c == '"' && prev != '\'' {
                let mut s = String::new();
                while let Some(c) = it.next() {
                    match c {
                        '"' => break,
                        '\\' => match it.next() {
                            Some('n') => s.push('\n'),
                            Some('t') => s.push('\t'),
                            Some(o) => s.push(o),
                            None => {}
                        },
                        _ => s.push(c),
                    }
                }
                out.push(s);
                prev = '"';
            } else {
                prev = c;
            }
        }
        out
    }

    /// Texts passed to `tr(…)` (every literal) and `trf(…)` / `tr_f(…)` (the first argument).
    fn keys_in(src: &str) -> Vec<String> {
        let b: Vec<char> = src.chars().collect();
        let mut keys = Vec::new();
        let mut i = 0;
        while i < b.len() {
            let name_len = ["tr_f(", "trf(", "tr("]
                .iter()
                .find(|n| b[i..].starts_with(&n.chars().collect::<Vec<_>>()))
                .map(|n| n.len());
            let word_start = i == 0 || !(b[i - 1].is_alphanumeric() || b[i - 1] == '_');
            let (Some(n), true) = (name_len, word_start) else {
                i += 1;
                continue;
            };
            let first_only = n > 3;
            let mut j = i + n;
            let (mut depth, mut in_str, mut first_end) = (1, false, None);
            while j < b.len() && depth > 0 {
                let c = b[j];
                if in_str {
                    if c == '\\' {
                        j += 1;
                    } else if c == '"' {
                        in_str = false;
                    }
                } else if c == '"' && b[j - 1] != '\'' {
                    in_str = true;
                } else if c == '(' || c == '[' || c == '{' {
                    depth += 1;
                } else if c == ')' || c == ']' || c == '}' {
                    depth -= 1;
                } else if c == ',' && depth == 1 && first_end.is_none() {
                    first_end = Some(j);
                }
                j += 1;
            }
            let end = if first_only {
                first_end.unwrap_or(j - 1)
            } else {
                j - 1
            };
            keys.extend(
                literals(&b[i + n..end].iter().collect::<String>())
                    .into_iter()
                    .filter(|s| !s.is_empty()),
            );
            i += n;
        }
        keys
    }

    fn placeholders(s: &str) -> Vec<String> {
        let mut v: Vec<String> = s
            .split('{')
            .skip(1)
            .filter_map(|p| p.split_once('}').map(|x| x.0.to_string()))
            .collect();
        v.sort();
        v.dedup();
        v
    }

    #[test]
    fn every_text_is_translated() {
        let mut keys: Vec<String> = SOURCES.iter().flat_map(|s| keys_in(s.1)).collect();
        keys.extend(
            Cmd::all()
                .flat_map(|c| [c.label(), c.group()])
                .map(String::from),
        );
        keys.extend(DYNAMIC.iter().map(|s| s.to_string()));
        let known: HashMap<&str, &[&str; 3]> = TEXTS.iter().map(|t| (t[0], t)).collect();
        let mut missing: Vec<&String> = keys
            .iter()
            .filter(|k| !known.contains_key(k.as_str()))
            .collect();
        missing.sort();
        missing.dedup();
        assert!(
            missing.is_empty(),
            "texts without a translation: {missing:#?}"
        );
        assert!(keys.len() > 300, "the scan found only {} texts", keys.len());
    }

    #[test]
    fn translations_are_complete_and_keep_placeholders() {
        let mut seen = std::collections::HashSet::new();
        for t in TEXTS {
            assert!(seen.insert(t[0]), "duplicate entry {:?}", t[0]);
            for (i, x) in t.iter().enumerate().skip(1) {
                assert!(!x.trim().is_empty(), "{:?}: empty translation {i}", t[0]);
                assert_eq!(placeholders(x), placeholders(t[0]), "{:?} → {x:?}", t[0]);
            }
        }
    }

    #[test]
    fn every_language_has_every_text() {
        let tables: [(&str, &[(&str, &str)]); 5] = [
            ("zh", crate::app::i18n_zh::ZH),
            ("es", crate::app::i18n_es::ES),
            ("pt", crate::app::i18n_pt::PT),
            ("de", crate::app::i18n_de::DE),
            ("tr", crate::app::i18n_tr::TR),
        ];
        let english: std::collections::HashSet<&str> = TEXTS.iter().map(|t| t[0]).collect();
        for (code, table) in tables {
            let map: HashMap<&str, &str> = table.iter().copied().collect();
            assert_eq!(map.len(), table.len(), "{code}: a text is there twice");
            let mut missing: Vec<&&str> =
                english.iter().filter(|k| !map.contains_key(*k)).collect();
            missing.sort();
            assert!(
                missing.is_empty(),
                "{code}: texts without a translation: {missing:#?}"
            );
            for (k, v) in table {
                assert!(english.contains(k), "{code}: {k:?} is not an English text");
                assert!(
                    !v.trim().is_empty(),
                    "{code}: {k:?} has an empty translation"
                );
                assert_eq!(placeholders(v), placeholders(k), "{code}: {k:?} → {v:?}");
            }
        }
        for l in Lang::ALL {
            assert_eq!(Lang::from_code(l.code()), Some(l));
        }
    }

    #[test]
    fn lookup_and_fill() {
        set_lang(Lang::Ru);
        assert_eq!(tr("File"), "Файл");
        assert_eq!(trf("{n} lines", &[("n", "5")]), "строк: 5");
        set_lang(Lang::Uz);
        assert_eq!(tr("Not in the table"), "Not in the table");
        set_lang(Lang::En);
        assert_eq!(tr("File"), "File");
    }
}