bigtext 0.14.0

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
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
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
//! A journal of unsaved edits, so that a crash or a power cut does not lose them. A couple of
//! seconds after a pause in editing (or every 30 s of typing), a modified document's piece list
//! and the bytes typed into it are written next to the settings: a few KB for a thousand edits
//! to a 50 GB file. The next start offers to restore them, once the file on disk is checked to
//! be the same. Each running BigText holds a lock, so another one's journals are left alone.

use std::collections::HashMap;
use std::fs::{self, File};
use std::io::{self, Write};
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};

use bigtext::encoding::{Codec, Encoding, NlByte};
use bigtext::file::{OpenMode, Source};
use bigtext::index::LineIndex;
use bigtext::jobs;
use bigtext::text::{Buf, TextBuf};

use super::document::{Banner, DocState};
use super::i18n::{tr, trf};
use super::tasks::{self, TaskOutcome};
use super::{BigTextApp, Msg};

/// Typed bytes kept in a journal at most (a huge paste is not journaled).
const ADD_MAX: usize = 256 << 20;

/// A journal on disk.
#[derive(Clone, Debug, PartialEq)]
pub struct Journal {
    /// `<pid>-<document id>`.
    pub id: String,
    pub title: String,
    pub path: Option<PathBuf>,
    /// The file's length and change time when the edits were made.
    pub len: u64,
    pub mtime: Option<Duration>,
    pub codec: Codec,
    pub pieces: Vec<(Buf, u64, u64)>,
    pub add_len: u64,
    pub saved: Option<SystemTime>,
}

/// The journal folder: next to the settings (`BIGTEXT_RECOVERY_DIR` for tests).
pub fn default_dir() -> Option<PathBuf> {
    if let Some(d) = std::env::var_os("BIGTEXT_RECOVERY_DIR") {
        return Some(PathBuf::from(d));
    }
    Some(super::extras::state_file()?.parent()?.join("recovery"))
}

fn pieces_path(dir: &Path, id: &str) -> PathBuf {
    dir.join(format!("{id}.pieces"))
}

fn add_path(dir: &Path, id: &str) -> PathBuf {
    dir.join(format!("{id}.add"))
}

/// Deletes a journal's files.
pub fn remove(dir: &Path, id: &str) {
    let _ = fs::remove_file(pieces_path(dir, id));
    let _ = fs::remove_file(add_path(dir, id));
}

fn mtime_of(t: Option<SystemTime>) -> Option<Duration> {
    t.and_then(|t| t.duration_since(UNIX_EPOCH).ok())
}

/// The text of a journal's `.pieces` file.
pub fn format(j: &Journal) -> String {
    let mut s = String::from("bigtext-journal 1\n");
    s.push_str(&format!("title={}\n", j.title));
    if let Some(p) = &j.path {
        s.push_str(&format!("path={}\n", p.display()));
    }
    s.push_str(&format!("len={}\n", j.len));
    if let Some(m) = j.mtime {
        s.push_str(&format!("mtime={}.{:09}\n", m.as_secs(), m.subsec_nanos()));
    }
    let nl = if j.codec.nl == NlByte::Cr { "cr" } else { "lf" };
    s.push_str(&format!(
        "codec={}|{nl}|{}\n",
        j.codec.enc.name(),
        j.codec.bom_len
    ));
    s.push_str(&format!("add={}\n", j.add_len));
    for &(b, start, len) in &j.pieces {
        s.push_str(&format!(
            "{} {start} {len}\n",
            if b == Buf::Orig { 'o' } else { 'a' }
        ));
    }
    s
}

/// Reads a `.pieces` file back; `None` when it is not one.
pub fn parse(id: &str, text: &str) -> Option<Journal> {
    let mut lines = text.lines();
    if lines.next()? != "bigtext-journal 1" {
        return None;
    }
    let mut j = Journal {
        id: id.to_string(),
        title: String::new(),
        path: None,
        len: 0,
        mtime: None,
        codec: Codec::utf8(),
        pieces: Vec::new(),
        add_len: 0,
        saved: None,
    };
    for l in lines {
        if let Some((k, v)) = l.split_once('=') {
            match k {
                "title" => j.title = v.to_string(),
                "path" => j.path = Some(PathBuf::from(v)),
                "len" => j.len = v.parse().ok()?,
                "mtime" => {
                    let (s, n) = v.split_once('.')?;
                    j.mtime = Some(Duration::new(s.parse().ok()?, n.parse().ok()?));
                }
                "codec" => {
                    let mut it = v.split('|');
                    let enc = it.next()?;
                    let enc = Encoding::ALL.into_iter().find(|e| e.name() == enc)?;
                    let nl = if it.next()? == "cr" {
                        NlByte::Cr
                    } else {
                        NlByte::Lf
                    };
                    j.codec = Codec::new(enc, nl, it.next()?.parse().ok()?);
                }
                "add" => j.add_len = v.parse().ok()?,
                _ => {}
            }
            continue;
        }
        let mut it = l.split(' ');
        let b = match it.next()? {
            "o" => Buf::Orig,
            "a" => Buf::Add,
            _ => return None,
        };
        j.pieces
            .push((b, it.next()?.parse().ok()?, it.next()?.parse().ok()?));
    }
    Some(j)
}

/// The edited text of a journal over `source` (an empty one for an untitled document).
fn rebuild(dir: &Path, j: &Journal, source: Arc<Source>) -> Option<TextBuf> {
    let mut add = fs::read(add_path(dir, &j.id)).ok()?;
    if (add.len() as u64) < j.add_len {
        return None;
    }
    add.truncate(j.add_len as usize);
    let index = LineIndex::new(source.len());
    TextBuf::with_pieces(source, index, j.codec, &j.pieces, add)
}

/// Writes a journal: the typed bytes first (only the new ones when `append`), synced, then the
/// piece list through a synced temporary file and a rename, so that a crash or a power cut
/// leaves the old journal or the new one. Stops before the rename when `cancel` is set.
fn write_journal(
    dir: &Path,
    j: &Journal,
    append: bool,
    delta: &[u8],
    cancel: &AtomicBool,
) -> io::Result<()> {
    let temp = dir.join(format!("{}.pieces.tmp", j.id));
    let r = (|| {
        let mut f = File::options()
            .create(true)
            .write(true)
            .append(append)
            .truncate(!append)
            .open(add_path(dir, &j.id))?;
        f.write_all(delta)?;
        f.sync_data()?;
        let mut f = File::create(&temp)?;
        f.write_all(format(j).as_bytes())?;
        f.sync_all()?;
        drop(f);
        if cancel.load(Ordering::Relaxed) {
            return Err(io::Error::other("journal dropped"));
        }
        fs::rename(&temp, pieces_path(dir, &j.id))
    })();
    if r.is_err() {
        let _ = fs::remove_file(&temp);
    }
    r
}

/// The text typed into a journal's document, piece after piece in document order, each on
/// lines of its own: all that can be saved of edits whose file changed on disk since.
fn typed_text(dir: &Path, j: &Journal) -> Option<Vec<u8>> {
    let add = fs::read(add_path(dir, &j.id)).ok()?;
    let nl = j.codec.encode("\n");
    let mut out = Vec::new();
    for &(b, start, len) in &j.pieces {
        if b != Buf::Add {
            continue;
        }
        let s = usize::try_from(start).ok()?;
        let e = s.checked_add(usize::try_from(len).ok()?)?;
        out.extend_from_slice(add.get(s..e)?);
        if !out.ends_with(&nl) {
            out.extend_from_slice(&nl);
        }
    }
    Some(out)
}

/// Whether the journal's document has bytes of its file in it (an untitled one has none).
fn uses_file(j: &Journal) -> bool {
    j.path.is_some() && j.pieces.iter().any(|p| p.0 == Buf::Orig)
}

/// Whether the file is still the one the edits were made to.
fn unchanged(j: &Journal) -> bool {
    let Some(p) = &j.path else { return true };
    match fs::metadata(p) {
        Ok(m) => m.len() == j.len && (j.mtime.is_none() || mtime_of(m.modified().ok()) == j.mtime),
        Err(_) => false,
    }
}

/// A document's journal as last written.
#[derive(Default)]
pub struct Entry {
    /// The document version seen, when it changed, and since when edits wait to be written.
    seen: u64,
    changed_at: Option<Instant>,
    waiting_since: Option<Instant>,
    written: u64,
    add_written: u64,
    writing: bool,
    /// Journaled at all (so there are files to delete).
    exists: bool,
    /// A write failed part way: the next one writes both files whole.
    rewrite: bool,
    /// The journal is no longer wanted but a write is still running: its files go when it ends.
    drop_pending: bool,
    /// Set when the journal is dropped, so a write still running does not leave files behind.
    cancel: Arc<AtomicBool>,
    /// The journal is in the folder used before the journals moved (`RecoveryState::old_dir`):
    /// it goes from there once it is written whole in the new one.
    in_old: bool,
    /// The write running when the journals moved goes to the old folder.
    old_write: bool,
}

/// Stops journaling a document: its files go now, or when the write in flight ends (a write
/// finishing after the files were deleted would bring them back).
fn drop_journal(entries: &mut HashMap<u64, Entry>, dir: &Path, old: Option<&Path>, doc: u64) {
    let Some(e) = entries.get_mut(&doc) else {
        return;
    };
    e.cancel.store(true, Ordering::Relaxed);
    if e.writing {
        e.drop_pending = true;
        return;
    }
    if e.exists {
        remove(dir, &RecoveryState::id(doc));
    }
    if let (true, Some(old)) = (e.in_old, old) {
        remove(old, &RecoveryState::id(doc));
    }
    entries.remove(&doc);
}

/// Copies a file and makes sure the copy is on the disk.
fn copy_synced(from: &Path, to: &Path) -> io::Result<()> {
    fs::copy(from, to)?;
    File::options().write(true).open(to)?.sync_all()
}

/// Moves a journal to another folder (on another drive, too): the typed bytes, then the piece
/// list through a temporary file, both copied and synced before anything is deleted, so that a
/// failure or a crash part way leaves the whole journal in one folder or the other. A journal of
/// the same name in `to` is not overwritten.
fn move_journal(from: &Path, to: &Path, id: &str) -> io::Result<()> {
    let target = pieces_path(to, id);
    if target.exists() {
        return Err(io::ErrorKind::AlreadyExists.into());
    }
    let temp = to.join(format!("{id}.pieces.tmp"));
    let r = (|| {
        if add_path(from, id).exists() {
            copy_synced(&add_path(from, id), &add_path(to, id))?;
        }
        copy_synced(&pieces_path(from, id), &temp)?;
        fs::rename(&temp, &target)
    })();
    if let Err(e) = r {
        let _ = fs::remove_file(&temp);
        let _ = fs::remove_file(add_path(to, id));
        return Err(e);
    }
    // The piece list first: typed bytes a crash leaves without one are no journal and go.
    let _ = fs::remove_file(pieces_path(from, id));
    let _ = fs::remove_file(add_path(from, id));
    Ok(())
}

#[derive(Default)]
pub struct RecoveryState {
    pub enabled: bool,
    pub dir: Option<PathBuf>,
    /// This instance's lock, held while it runs.
    lock: Option<File>,
    entries: HashMap<u64, Entry>,
    /// Journals left by a BigText that did not close properly.
    pub offered: Vec<Journal>,
    /// The journal waiting for its document to open.
    pending: HashMap<u64, Journal>,
    /// Restored journals (by the document they went into), deleted once that document's own
    /// journal is written or no longer needed: a crash right after a restore keeps them.
    superseded: HashMap<u64, String>,
    /// The folder the journals were in before they moved with the settings (Make portable), and
    /// this instance's lock there, held while journals of its documents are still in it.
    old_dir: Option<PathBuf>,
    old_lock: Option<File>,
}

impl RecoveryState {
    /// Journaling on (it starts once a folder is known).
    pub fn new() -> RecoveryState {
        RecoveryState {
            enabled: true,
            ..Default::default()
        }
    }

    fn id(doc: u64) -> String {
        format!("{}-{doc}", std::process::id())
    }
}

/// Journals named after this process's id when it starts were left by an earlier BigText that
/// had the same id and crashed. They get a name of their own (`<pid>.<time>-<doc>`), so that
/// they are offered rather than skipped as this instance's, and this instance's own journals
/// do not overwrite them.
fn keep_reused_pid_journals(dir: &Path) {
    let prefix = format!("{}-", std::process::id());
    let stamp = SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    for e in fs::read_dir(dir).into_iter().flatten().flatten() {
        let name = e.file_name().to_string_lossy().into_owned();
        if let Some(rest) = name.strip_prefix(&prefix) {
            let pid = std::process::id();
            let _ = fs::rename(e.path(), dir.join(format!("{pid}.{stamp}-{rest}")));
        }
    }
}

/// Whether the BigText that wrote journals with this process id still runs.
fn running(dir: &Path, pid: &str) -> bool {
    let p = dir.join(format!("{pid}.lock"));
    match File::options().write(true).open(&p) {
        Ok(f) => f.try_lock().is_err(),
        Err(_) => false,
    }
}

impl BigTextApp {
    /// Starts journaling into `dir` (taking this instance's lock) and finds what crashed
    /// instances left.
    pub(crate) fn start_recovery(&mut self, dir: Option<PathBuf>) {
        let Some(dir) = dir else { return };
        if fs::create_dir_all(&dir).is_err() {
            return;
        }
        if self.recovery.dir.is_none() {
            keep_reused_pid_journals(&dir);
        }
        let lock = File::create(dir.join(format!("{}.lock", std::process::id())))
            .ok()
            .filter(|f| f.try_lock().is_ok());
        self.recovery.lock = lock;
        self.recovery.dir = Some(dir);
        self.scan_recovery();
    }

    pub(crate) fn scan_recovery(&mut self) {
        let Some(dir) = self.recovery.dir.clone() else {
            return;
        };
        let mine = std::process::id().to_string();
        let mut found = Vec::new();
        for e in fs::read_dir(&dir).into_iter().flatten().flatten() {
            let name = e.file_name().to_string_lossy().into_owned();
            let Some(id) = name.strip_suffix(".pieces") else {
                continue;
            };
            let pid = id.split('-').next().unwrap_or("");
            if pid == mine
                || running(&dir, pid)
                || self.recovery.superseded.values().any(|s| s == id)
            {
                continue;
            }
            if let Some(mut j) = fs::read_to_string(e.path())
                .ok()
                .and_then(|t| parse(id, &t))
            {
                j.saved = e.metadata().and_then(|m| m.modified()).ok();
                found.push(j);
            }
        }
        // Lock files of instances that are gone, and what a crash left of their journals
        // without a piece list: typed bytes or a half-written piece list are no journal.
        for e in fs::read_dir(&dir).into_iter().flatten().flatten() {
            let name = e.file_name().to_string_lossy().into_owned();
            if let Some(pid) = name.strip_suffix(".lock") {
                if pid != mine
                    && !running(&dir, pid)
                    && !found.iter().any(|j| j.id.starts_with(&format!("{pid}-")))
                {
                    let _ = fs::remove_file(e.path());
                }
                continue;
            }
            let id = name
                .strip_suffix(".add")
                .or_else(|| name.strip_suffix(".pieces.tmp"));
            if let Some(id) = id {
                let pid = id.split('-').next().unwrap_or("");
                if pid != mine && !running(&dir, pid) && !pieces_path(&dir, id).exists() {
                    let _ = fs::remove_file(e.path());
                }
            }
        }
        found.sort_by(|a, b| a.id.cmp(&b.id));
        self.recovery.offered = found;
    }

    /// Moves journaling to `to`, where the settings went (Make portable): the next start looks
    /// for journals there only. What crashed instances left is moved along; this instance's
    /// journals are written whole in `to` and their old copies deleted once that is done, so
    /// none is ever missing from both folders. A running BigText's journals are its own and
    /// stay. Returns how many journals could not be moved: they stay where they are.
    pub(crate) fn move_recovery(&mut self, to: PathBuf) -> usize {
        let Some(from) = self.recovery.dir.clone() else {
            return 0;
        };
        if from == to || fs::create_dir_all(&to).is_err() {
            return 0;
        }
        keep_reused_pid_journals(&to);
        let mine = std::process::id().to_string();
        let crashed: Vec<String> = fs::read_dir(&from)
            .into_iter()
            .flatten()
            .flatten()
            .filter_map(|e| {
                let name = e.file_name().to_string_lossy().into_owned();
                let id = name.strip_suffix(".pieces")?;
                let pid = id.split('-').next().unwrap_or("");
                (pid != mine && !running(&from, pid)).then(|| id.to_string())
            })
            .collect();
        let left: Vec<String> = crashed
            .into_iter()
            .filter(|id| move_journal(&from, &to, id).is_err())
            .collect();
        // Those are not in the folder the journals are read from any more.
        let r = &mut self.recovery;
        r.offered.retain(|j| !left.contains(&j.id));
        r.pending.retain(|_, j| !left.contains(&j.id));
        r.superseded.retain(|_, id| !left.contains(id));
        for e in r.entries.values_mut() {
            if e.exists || e.writing {
                e.in_old = true;
                e.old_write = e.writing;
                e.exists = false;
                e.rewrite = true;
                // Written again even if the document does not change (a journaled document's
                // version is at least 1).
                e.written = 0;
            }
        }
        let lock = File::create(to.join(format!("{mine}.lock")))
            .ok()
            .filter(|f| f.try_lock().is_ok());
        r.old_lock = std::mem::replace(&mut r.lock, lock);
        r.old_dir = Some(from);
        r.dir = Some(to);
        left.len()
    }

    /// Lets go of the old folder once none of this instance's journals is left in it.
    fn release_old_dir(&mut self) {
        let r = &mut self.recovery;
        if r.old_dir.is_none() || r.entries.values().any(|e| e.in_old) {
            return;
        }
        r.old_lock = None;
        if let Some(old) = r.old_dir.take() {
            let _ = fs::remove_file(old.join(format!("{}.lock", std::process::id())));
        }
    }

    /// Writes the journals of documents that changed and settled, and drops those of documents
    /// that are saved, unchanged or closed (every frame).
    pub(super) fn journal_tick(&mut self) {
        let Some(dir) = self.recovery.dir.clone() else {
            return;
        };
        let old = self.recovery.old_dir.clone();
        let now = Instant::now();
        let ids: Vec<u64> = self.docs.iter().map(|d| d.id).collect();
        let gone: Vec<u64> = self
            .recovery
            .entries
            .keys()
            .copied()
            .filter(|id| !ids.contains(id))
            .collect();
        for id in gone {
            drop_journal(&mut self.recovery.entries, &dir, old.as_deref(), id);
        }
        let superseded: Vec<u64> = self
            .recovery
            .superseded
            .keys()
            .copied()
            .filter(|id| {
                !self
                    .docs
                    .iter()
                    .any(|d| d.id == *id && d.is_modified() && !d.temporary)
            })
            .collect();
        for id in superseded {
            if let Some(old) = self.recovery.superseded.remove(&id) {
                remove(&dir, &old);
            }
        }
        for d in &self.docs {
            let keep = self.recovery.enabled
                && d.is_modified()
                && !d.temporary
                && d.buf.add_len() as usize <= ADD_MAX;
            if !keep {
                drop_journal(&mut self.recovery.entries, &dir, old.as_deref(), d.id);
                continue;
            }
            // While a save runs (or after it failed and left the document in an error state)
            // the last journal stays as it is: it goes once the document is saved and so no
            // longer modified, and a crash or a failed save in between still has it.
            if !d.is_ready() || d.save_job.is_some() || matches!(d.state, DocState::Finalizing(_)) {
                continue;
            }
            let e = self.recovery.entries.entry(d.id).or_default();
            if e.drop_pending {
                continue;
            }
            if e.seen != d.version {
                e.seen = d.version;
                e.changed_at = Some(now);
                e.waiting_since.get_or_insert(now);
            }
            let settled = e
                .changed_at
                .is_some_and(|t| now - t >= Duration::from_secs(2))
                || e.waiting_since
                    .is_some_and(|t| now - t >= Duration::from_secs(30));
            if e.writing || e.written == d.version || !settled {
                continue;
            }
            e.writing = true;
            let add_len = d.buf.add_len();
            // Only the new typed bytes are appended; a smaller add buffer is written again.
            let (append, delta) = if !e.rewrite && e.exists && add_len >= e.add_written {
                (true, d.buf.add_bytes_from(e.add_written))
            } else {
                (false, d.buf.add_bytes_from(0))
            };
            let j = Journal {
                id: RecoveryState::id(d.id),
                title: d.title.clone(),
                path: d.path.clone(),
                len: d.buf.source.len(),
                mtime: mtime_of(d.buf.source.modified()),
                codec: d.buf.codec,
                pieces: d.buf.pieces().map(|p| (p.buf, p.start, p.len)).collect(),
                add_len,
                saved: None,
            };
            let (doc, version, dir, tx, waker, cancel) = (
                d.id,
                d.version,
                dir.clone(),
                self.tx.clone(),
                self.waker.clone(),
                e.cancel.clone(),
            );
            jobs::spawn("journal", move || {
                let r = write_journal(&dir, &j, append, &delta, &cancel);
                if cancel.load(Ordering::Relaxed) {
                    // Dropped while this ran (saved, closed, exit): nothing may stay behind.
                    remove(&dir, &j.id);
                }
                let _ = tx.send(Msg::Journaled {
                    doc,
                    version,
                    add_len: j.add_len,
                    ok: r.is_ok(),
                });
                waker();
            });
        }
        self.release_old_dir();
    }

    pub(super) fn on_journaled(&mut self, doc: u64, version: u64, add_len: u64, ok: bool) {
        let Some(dir) = self.recovery.dir.clone() else {
            return;
        };
        let Some(e) = self.recovery.entries.get_mut(&doc) else {
            return;
        };
        e.writing = false;
        let old_write = std::mem::take(&mut e.old_write);
        let old = self.recovery.old_dir.as_deref();
        if e.drop_pending {
            remove(&dir, &RecoveryState::id(doc));
            if let (true, Some(old)) = (e.in_old, old) {
                remove(old, &RecoveryState::id(doc));
            }
            self.recovery.entries.remove(&doc);
            return;
        }
        if old_write {
            // Written to the old folder, where the journal stays until it is written whole in
            // the new one (the next write: the journals moved since this one started).
            return;
        }
        if ok {
            e.written = version;
            e.add_written = add_len;
            e.exists = true;
            e.rewrite = false;
            e.waiting_since = None;
            // The journal is whole in the new folder: its copy in the old one can go.
            if let (true, Some(old)) = (std::mem::take(&mut e.in_old), old) {
                remove(old, &RecoveryState::id(doc));
            }
            // The document's own journal is there now: the one it was restored from can go.
            if let Some(old) = self.recovery.superseded.remove(&doc) {
                remove(&dir, &old);
            }
        } else {
            // The files may be half written (an append that went through and a rename that did
            // not would leave typed bytes in twice): the next write, after the usual pause,
            // writes both whole.
            let now = Instant::now();
            e.exists = true;
            e.rewrite = true;
            e.changed_at = Some(now);
            e.waiting_since = Some(now);
        }
    }

    /// A clean exit: this instance's journals and lock go.
    pub(super) fn end_recovery(&mut self) {
        let Some(dir) = self.recovery.dir.clone() else {
            return;
        };
        let old = self.recovery.old_dir.clone();
        for (id, e) in self.recovery.entries.drain() {
            e.cancel.store(true, Ordering::Relaxed);
            if e.exists || e.writing {
                remove(&dir, &RecoveryState::id(id));
            }
            if let (true, Some(old)) = (e.in_old, &old) {
                remove(old, &RecoveryState::id(id));
            }
        }
        for (_, old) in self.recovery.superseded.drain() {
            remove(&dir, &old);
        }
        self.recovery.lock = None;
        let _ = fs::remove_file(dir.join(format!("{}.lock", std::process::id())));
        self.release_old_dir();
    }

    /// Opens the journal's file (or a new document) with the edits put back.
    pub(crate) fn restore_journal(&mut self, i: usize) {
        let Some(dir) = self.recovery.dir.clone() else {
            return;
        };
        if i >= self.recovery.offered.len() {
            return;
        }
        let j = self.recovery.offered.remove(i);
        match &j.path {
            None => {
                self.new_doc();
                let Some(buf) = rebuild(&dir, &j, Arc::new(Source::empty())) else {
                    self.error =
                        Some(tr("The journal is damaged; nothing could be restored.").into());
                    return;
                };
                match self.docs.get_mut(self.active) {
                    Some(d) => {
                        d.restore_edits(buf);
                        d.title = j.title.clone();
                        self.recovery.superseded.insert(d.id, j.id.clone());
                    }
                    None => remove(&dir, &j.id),
                }
            }
            Some(p) => {
                if !unchanged(&j) {
                    self.error = Some(trf("{file} changed on disk after these edits were made; putting them back would scramble it. Save text as… keeps the text you typed.", &[("file", &bigtext::file::display_path(p))]));
                    self.recovery.offered.insert(i, j);
                    return;
                }
                self.open_path(p.clone());
                if let Some(d) = self.docs.get(self.active) {
                    self.recovery.pending.insert(d.id, j);
                }
                self.apply_pending_journal();
            }
        }
    }

    /// Puts back the journal waiting for a document that has opened (every frame).
    pub(super) fn apply_pending_journal(&mut self) {
        if self.recovery.pending.is_empty() {
            return;
        }
        let Some(dir) = self.recovery.dir.clone() else {
            return;
        };
        let ready: Vec<u64> = self
            .docs
            .iter()
            .filter(|d| d.is_ready() && self.recovery.pending.contains_key(&d.id))
            .map(|d| d.id)
            .collect();
        for id in ready {
            let Some(j) = self.recovery.pending.remove(&id) else {
                continue;
            };
            let Some(d) = self.docs.iter_mut().find(|d| d.id == id) else {
                continue;
            };
            if d.is_modified() || d.buf.source.len() != j.len {
                self.error = Some(tr("The document changed before the edits could be put back; nothing was restored.").into());
                continue;
            }
            match rebuild(&dir, &j, d.buf.source.clone()) {
                Some(buf) => {
                    d.restore_edits(buf);
                    d.banner = Some(Banner::Info(
                        tr("Unsaved edits from the last session were put back. Save to keep them.")
                            .into(),
                    ));
                    self.recovery.superseded.insert(id, j.id.clone());
                }
                None => {
                    self.error =
                        Some(tr("The journal is damaged; nothing could be restored.").into())
                }
            }
        }
    }

    /// Writes the journal's edited text to a file the user picks.
    fn save_journal_as(&mut self, i: usize) {
        let Some(dir) = self.recovery.dir.clone() else {
            return;
        };
        let Some(j) = self.recovery.offered.get(i).cloned() else {
            return;
        };
        let name = j
            .path
            .as_deref()
            .and_then(|p| p.file_name())
            .map(|n| format!("{} (recovered)", n.to_string_lossy()))
            .unwrap_or_else(|| format!("{}.txt", j.title));
        let Some(target) = rfd::FileDialog::new()
            .set_title(tr("Save text as"))
            .set_file_name(name)
            .save_file()
        else {
            return;
        };
        self.recovery.offered.remove(i);
        self.spawn_task(
            tr("Saving the recovered text").into(),
            move |progress, cancel| {
                // The edits are positions in the file as it was: over a file that changed since
                // they would scramble it, so only the typed text is saved then.
                if uses_file(&j) && !unchanged(&j) {
                    let Some(text) = typed_text(&dir, &j) else {
                        return TaskOutcome::Failed(
                            tr("The journal is damaged; nothing could be restored.").into(),
                        );
                    };
                    let file = j
                        .path
                        .as_deref()
                        .map(bigtext::file::display_path)
                        .unwrap_or_default();
                    let out = tasks::write_via_temp(&target, |w| {
                        w.write_all(&text)?;
                        Ok(Some(trf(
                            "{file} changed on disk, so only the text you typed was saved, to {target}.",
                            &[
                                ("file", &file),
                                ("target", &super::filter_panel::file_name(&target)),
                            ],
                        )))
                    });
                    if matches!(out, TaskOutcome::Done { .. }) {
                        remove(&dir, &j.id);
                    }
                    return out;
                }
                let source = match &j.path {
                    Some(p) => match Source::open(p, OpenMode::Auto) {
                        Ok(s) => Arc::new(s),
                        Err(e) => return TaskOutcome::Failed(super::friendly_io(&e, p)),
                    },
                    None => Arc::new(Source::empty()),
                };
                let Some(buf) = rebuild(&dir, &j, source) else {
                    return TaskOutcome::Failed(
                        tr("The journal is damaged; nothing could be restored.").into(),
                    );
                };
                let snap = buf.snapshot();
                progress.set_total(snap.len());
                let out = tasks::write_via_temp(&target, |w| {
                    let mut stopped = false;
                    snap.for_each_chunk(0..snap.len(), |base, b| {
                        if cancel.is_cancelled() || w.write_all(b).is_err() {
                            stopped = true;
                            return false;
                        }
                        progress.set_done(base + b.len() as u64);
                        true
                    })
                    .ok_or_else(|| io::Error::other("reading failed"))?;
                    Ok((!stopped).then(|| {
                        trf(
                            "Saved the recovered text to {file}.",
                            &[("file", &super::filter_panel::file_name(&target))],
                        )
                    }))
                });
                if matches!(out, TaskOutcome::Done { .. }) {
                    remove(&dir, &j.id);
                }
                out
            },
        );
    }

    pub(super) fn recovery_window(&mut self, ctx: &egui::Context) {
        if self.recovery.offered.is_empty() {
            return;
        }
        let Some(dir) = self.recovery.dir.clone() else {
            return;
        };
        let (mut restore, mut save, mut discard) = (None, None, None);
        egui::Window::new(tr("Unsaved edits from the last session")).collapsible(false).resizable(false).show(ctx, |ui| {
            ui.label(tr("BigText did not close properly. These documents had edits that were not saved:"));
            ui.separator();
            for (i, j) in self.recovery.offered.iter().enumerate() {
                ui.horizontal(|ui| {
                    let name = j.path.as_deref().map(bigtext::file::display_path).unwrap_or_else(|| j.title.clone());
                    ui.strong(name);
                    if let Some(t) = j.saved {
                        ui.weak(super::archive::date(t));
                    }
                });
                ui.horizontal(|ui| {
                    let ok = unchanged(j);
                    if ui.add_enabled(ok, egui::Button::new(tr("Restore"))).on_disabled_hover_text(tr("The file changed on disk since; Save text as… keeps the text you typed.")).clicked() {
                        restore = Some(i);
                    }
                    if ui.button(tr("Save text as…")).clicked() {
                        save = Some(i);
                    }
                    if ui.button(tr("Discard")).clicked() {
                        discard = Some(i);
                    }
                });
                ui.add_space(4.0);
            }
        });
        if let Some(i) = restore {
            self.restore_journal(i);
        } else if let Some(i) = save {
            self.save_journal_as(i);
        } else if let Some(i) = discard {
            let j = self.recovery.offered.remove(i);
            remove(&dir, &j.id);
        }
    }
}

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

    #[test]
    fn journal_round_trip() {
        let j = Journal {
            id: "12-3".into(),
            title: "app.log".into(),
            path: Some(PathBuf::from(r"D:\logs\app.log")),
            len: 1 << 40,
            mtime: Some(Duration::new(1_761_000_000, 123_456_789)),
            codec: Codec::new(Encoding::Utf16Le, NlByte::Lf, 2),
            pieces: vec![
                (Buf::Orig, 0, 100),
                (Buf::Add, 0, 5),
                (Buf::Orig, 100, (1 << 40) - 100),
            ],
            add_len: 5,
            saved: None,
        };
        assert_eq!(parse("12-3", &format(&j)), Some(j.clone()));
        let untitled = Journal {
            path: None,
            mtime: None,
            codec: Codec::utf8(),
            ..j
        };
        assert_eq!(parse("12-3", &format(&untitled)), Some(untitled));
        assert_eq!(parse("x", "not a journal\n"), None);
    }

    fn untitled(id: &str, pieces: Vec<(Buf, u64, u64)>, add_len: u64) -> Journal {
        Journal {
            id: id.into(),
            title: "Untitled".into(),
            path: None,
            len: 0,
            mtime: None,
            codec: Codec::utf8(),
            pieces,
            add_len,
            saved: None,
        }
    }

    fn text_of(dir: &Path, id: &str) -> Option<String> {
        let j = parse(id, &fs::read_to_string(pieces_path(dir, id)).ok()?)?;
        let buf = rebuild(dir, &j, Arc::new(Source::empty()))?;
        Some(String::from_utf8(buf.read(0..buf.len())?.to_vec()).unwrap())
    }

    /// A write that fails after appending its typed bytes must not leave them in twice: the
    /// next write (the one after a failure writes both files whole) restores the right text.
    #[test]
    fn a_failed_journal_write_is_written_whole_next_time() {
        let dir = tempfile::tempdir().unwrap();
        let d = dir.path();
        let no = AtomicBool::new(false);
        let j1 = untitled("1-2", vec![(Buf::Add, 0, 3)], 3);
        write_journal(d, &j1, false, b"abc", &no).unwrap();
        assert_eq!(text_of(d, "1-2").as_deref(), Some("abc"));
        // The piece list cannot be written: the typed bytes went in, the rename did not.
        fs::create_dir(d.join("1-2.pieces.tmp")).unwrap();
        let j2 = untitled("1-2", vec![(Buf::Add, 0, 6)], 6);
        assert!(write_journal(d, &j2, true, b"def", &no).is_err());
        assert_eq!(fs::read(add_path(d, "1-2")).unwrap(), b"abcdef");
        fs::remove_dir(d.join("1-2.pieces.tmp")).unwrap();
        // Appending again, as before the fix, would give "abcdefdefgh".
        let j3 = untitled("1-2", vec![(Buf::Add, 0, 8)], 8);
        write_journal(d, &j3, false, b"abcdefgh", &no).unwrap();
        assert_eq!(text_of(d, "1-2").as_deref(), Some("abcdefgh"));
    }

    #[test]
    fn a_dropped_journal_write_leaves_no_piece_list() {
        let dir = tempfile::tempdir().unwrap();
        let d = dir.path();
        let j = untitled("1-3", vec![(Buf::Add, 0, 2)], 2);
        assert!(write_journal(d, &j, false, b"hi", &AtomicBool::new(true)).is_err());
        assert!(!pieces_path(d, "1-3").exists());
        assert!(!d.join("1-3.pieces.tmp").exists());
    }

    #[test]
    fn typed_text_of_edits_to_a_changed_file() {
        let dir = tempfile::tempdir().unwrap();
        let d = dir.path();
        fs::write(add_path(d, "1-4"), b"FIRST\nsecond").unwrap();
        let j = Journal {
            path: Some(d.join("gone.log")),
            len: 1000,
            pieces: vec![
                (Buf::Orig, 0, 10),
                (Buf::Add, 0, 6),
                (Buf::Orig, 10, 500),
                (Buf::Add, 6, 6),
                (Buf::Orig, 510, 490),
            ],
            ..untitled("1-4", vec![], 12)
        };
        assert!(uses_file(&j));
        assert!(!unchanged(&j));
        assert_eq!(typed_text(d, &j).unwrap(), b"FIRST\nsecond\n");
        // A piece outside the typed bytes is a damaged journal, not a panic.
        let bad = Journal {
            pieces: vec![(Buf::Add, 10, 5)],
            ..j
        };
        assert_eq!(typed_text(d, &bad), None);
    }

    #[test]
    fn journals_of_an_earlier_process_with_this_id_are_kept_apart() {
        let dir = tempfile::tempdir().unwrap();
        let d = dir.path();
        let pid = std::process::id();
        let j = untitled(&format!("{pid}-2"), vec![(Buf::Add, 0, 2)], 2);
        write_journal(d, &j, false, b"ok", &AtomicBool::new(false)).unwrap();
        fs::write(d.join(format!("{}-2.pieces", pid + 1)), "other").unwrap();
        keep_reused_pid_journals(d);
        let names: Vec<String> = fs::read_dir(d)
            .unwrap()
            .flatten()
            .map(|e| e.file_name().to_string_lossy().into_owned())
            .collect();
        assert!(!names.contains(&format!("{pid}-2.pieces")), "{names:?}");
        let moved = names
            .iter()
            .find_map(|n| {
                n.strip_suffix(".pieces")
                    .filter(|id| id.starts_with(&format!("{pid}.")))
            })
            .unwrap_or_else(|| panic!("{names:?}"));
        assert_eq!(text_of(d, moved).as_deref(), Some("ok"));
        assert!(names.contains(&format!("{}-2.pieces", pid + 1)));
    }

    /// As if the pause in editing were over: the next tick writes the journals.
    fn settle(app: &mut BigTextApp) {
        app.journal_tick();
        let past = Instant::now().checked_sub(Duration::from_secs(3)).unwrap();
        for e in app.recovery.entries.values_mut() {
            e.changed_at = Some(past);
        }
    }

    fn wait_written(app: &mut BigTextApp) {
        let deadline = Instant::now() + Duration::from_secs(20);
        while app.recovery.entries.values().any(|e| e.writing) {
            assert!(Instant::now() < deadline, "the journal was not written");
            std::thread::sleep(Duration::from_millis(5));
            app.poll_messages();
        }
    }

    fn journal_now(app: &mut BigTextApp) {
        settle(app);
        app.journal_tick();
        wait_written(app);
    }

    fn offered(app: &BigTextApp) -> Vec<String> {
        app.recovery.offered.iter().map(|j| j.id.clone()).collect()
    }

    fn typed(app: &mut BigTextApp, at: u64, text: &[u8]) {
        let d = &mut app.docs[app.active];
        d.edit(at..at, text, crate::app::document::EditKind::Typing);
    }

    /// Make portable moves the settings: the next start looks for journals next to them, so
    /// the journals go there too, and none is lost on the way.
    #[test]
    fn journals_move_with_the_settings() {
        let tmp = tempfile::tempdir().unwrap();
        let (old, new) = (tmp.path().join("old"), tmp.path().join("new"));
        let no = AtomicBool::new(false);
        let mut app = crate::app::test_app();
        app.start_recovery(Some(old.clone()));
        typed(&mut app, 0, b"typed");
        journal_now(&mut app);
        let mine = RecoveryState::id(app.docs[app.active].id);
        assert_eq!(text_of(&old, &mine).as_deref(), Some("typed"));
        // What a crashed BigText left (offered), and the journal of one that still runs.
        let crashed = untitled("999999-7", vec![(Buf::Add, 0, 4)], 4);
        write_journal(&old, &crashed, false, b"lost", &no).unwrap();
        let running = File::create(old.join("999998.lock")).unwrap();
        running.try_lock().unwrap();
        let other = untitled("999998-1", vec![(Buf::Add, 0, 5)], 5);
        write_journal(&old, &other, false, b"other", &no).unwrap();
        app.scan_recovery();
        assert_eq!(offered(&app), ["999999-7"]);

        assert_eq!(app.move_recovery(new.clone()), 0);
        assert_eq!(app.recovery.dir.as_deref(), Some(new.as_path()));
        // The crashed one is whole in the new folder, and still offered from there.
        assert_eq!(text_of(&new, "999999-7").as_deref(), Some("lost"));
        assert!(!pieces_path(&old, "999999-7").exists());
        assert!(!add_path(&old, "999999-7").exists());
        assert_eq!(offered(&app), ["999999-7"]);
        // The running BigText's stays with it.
        assert_eq!(text_of(&old, "999998-1").as_deref(), Some("other"));
        assert!(!pieces_path(&new, "999998-1").exists());
        // This instance's stays in the old folder, still locked, until written in the new one.
        let lock = format!("{}.lock", std::process::id());
        assert!(pieces_path(&old, &mine).exists());
        assert!(old.join(&lock).exists() && new.join(&lock).exists());
        journal_now(&mut app);
        assert_eq!(text_of(&new, &mine).as_deref(), Some("typed"));
        assert!(!pieces_path(&old, &mine).exists());
        assert!(!add_path(&old, &mine).exists());
        app.journal_tick();
        assert!(!old.join(&lock).exists());
        // Later edits are journaled in the new folder only.
        typed(&mut app, 5, b"!");
        journal_now(&mut app);
        assert_eq!(text_of(&new, &mine).as_deref(), Some("typed!"));
        assert!(!pieces_path(&old, &mine).exists());
        app.end_recovery();
        assert!(!pieces_path(&new, &mine).exists() && !new.join(&lock).exists());
    }

    /// A write that was running when the journals moved lands in the old folder: the journal
    /// is written again in the new one before that copy goes.
    #[test]
    fn a_journal_written_while_the_journals_move_is_written_again() {
        let tmp = tempfile::tempdir().unwrap();
        let (old, new) = (tmp.path().join("old"), tmp.path().join("new"));
        let mut app = crate::app::test_app();
        app.start_recovery(Some(old.clone()));
        typed(&mut app, 0, b"abc");
        settle(&mut app);
        app.journal_tick();
        let mine = RecoveryState::id(app.docs[app.active].id);
        assert!(app.recovery.entries.values().any(|e| e.writing));
        app.move_recovery(new.clone());
        wait_written(&mut app);
        assert_eq!(text_of(&old, &mine).as_deref(), Some("abc"));
        assert!(!pieces_path(&new, &mine).exists());
        journal_now(&mut app);
        assert_eq!(text_of(&new, &mine).as_deref(), Some("abc"));
        assert!(!pieces_path(&old, &mine).exists());
    }

    /// A journal that cannot be moved stays whole where it was (and is not offered from a
    /// folder it is not in); nothing half copied is left in the new folder.
    #[test]
    fn a_journal_that_cannot_be_moved_stays_whole() {
        let tmp = tempfile::tempdir().unwrap();
        let (old, new) = (tmp.path().join("old"), tmp.path().join("new"));
        let no = AtomicBool::new(false);
        let mut app = crate::app::test_app();
        app.start_recovery(Some(old.clone()));
        let kept = untitled("999999-8", vec![(Buf::Add, 0, 4)], 4);
        write_journal(&old, &kept, false, b"kept", &no).unwrap();
        let moved = untitled("999999-9", vec![(Buf::Add, 0, 5)], 5);
        write_journal(&old, &moved, false, b"moved", &no).unwrap();
        app.scan_recovery();
        // Its piece list cannot be written in the new folder.
        fs::create_dir_all(new.join("999999-8.pieces.tmp")).unwrap();
        assert_eq!(app.move_recovery(new.clone()), 1);
        assert_eq!(text_of(&old, "999999-8").as_deref(), Some("kept"));
        assert!(!add_path(&new, "999999-8").exists());
        assert!(!pieces_path(&new, "999999-8").exists());
        assert_eq!(text_of(&new, "999999-9").as_deref(), Some("moved"));
        assert_eq!(offered(&app), ["999999-9"]);
    }
}