odox-ui 0.7.0

The shared window of the odox OpenDocument editors: style mapping, document rendering, editing and chrome
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
//! The window around a document: opening one, saving it, saying what went
//! wrong, and the menu and keys that are the same in all three applications.
//!
//! The shell owns every read from and write to the disk. A view is handed
//! bytes and hands bytes back, so the one place that knows a path is here, and
//! so is the one place that asks before throwing changes away.
//
// Author: David M. Anderson
// Built with AI assistance (Claude, Anthropic)

use std::path::{Path, PathBuf};

use eframe::egui::{self, Key, KeyboardShortcut, Modifiers, Ui};
use odox_core::Document;

use crate::edit::{Caret, Editing};
use crate::find::Replaced;
use crate::find_bar::{FindBar, Replace, Step};
use crate::i18n::{fill, t};
use crate::settings::Settings;

/// What an application tells the shell about itself.
///
/// The identifiers are not translated: a desktop entry, a window class and a file
/// extension are the same in every language.
pub struct Product {
    /// The binary's name, which is also the `.desktop` entry's basename and the
    /// Wayland application id. The compositor matches the three to find the
    /// window's icon, so they have to agree.
    pub id: &'static str,
    /// The file extension the application opens.
    pub extension: &'static str,
    /// What the file dialog and the empty window call that kind of file.
    ///
    /// The English, which is the message id: it is looked up through [`t`] where
    /// it is shown, because a `Product` is built before `run` puts a catalogue in
    /// force and a translation looked up here would be the English every time.
    pub format: &'static str,
    /// The application's icon directory, for the one platform with no other way
    /// to give a window its icon.
    ///
    /// Windows takes a window's icon from a resource compiled into the
    /// executable, and there is no resource compiler in this build, so the file
    /// travels in the binary instead. Empty everywhere else, and empty in a
    /// build made from a published crate, where the file is not there to stage:
    /// see each application's `build.rs`.
    pub icon: &'static [u8],
}

/// What the shell needs from the view that draws a particular format.
pub trait View {
    /// Take a document's bytes. The path is for the window's title and for
    /// reloading, and is never read from here: this is given the bytes.
    ///
    /// The context is for the work a new document makes necessary before it can
    /// be drawn — loading the font faces its styles name, which rebuilds egui's
    /// glyph atlas and so belongs to opening rather than to drawing.
    ///
    /// # Errors
    ///
    /// A message to show the person, already translated.
    fn open(&mut self, ctx: &egui::Context, bytes: &[u8], path: &Path) -> Result<(), String>;

    /// Forget the document.
    fn close(&mut self);

    /// Whether a document is open.
    fn is_open(&self) -> bool;

    /// What the document calls itself, for the window's title.
    fn title(&self) -> Option<String>;

    /// The document, for saving and for undo. `None` while nothing is open.
    fn document_mut(&mut self) -> Option<&mut Document>;

    /// The content tree was replaced under the document, by undo or redo.
    /// A view that derives anything from the tree rebuilds it here.
    fn reindex(&mut self) {}

    /// Where the caret is, for a view that has one, so that an undo can
    /// bring it back there.
    fn caret(&self) -> Option<Caret> {
        None
    }

    /// Put the caret where an undo or a redo says it was, after
    /// [`Self::reindex`].
    fn restore_caret(&mut self, _caret: Caret) {}

    /// Draw the view's own menus, after Edit: each a `menu_button` of its
    /// own. A command chosen is kept by the view and applied when it next
    /// draws its page, where the document and the editing state are.
    fn menus(&mut self, _ui: &mut Ui, _editing: &Editing) {}

    /// Whether the view is showing the document full screen and nothing else,
    /// as a slideshow does: the shell takes its menu, its panels and its keys
    /// away until it is not.
    fn presenting(&self) -> bool {
        false
    }

    /// Look for text in the document and keep what is found, to draw
    /// highlighted; an empty query forgets the search. Answers how many
    /// matches there are. Asked again whenever the query or the text changes,
    /// and the current match is kept if there are still that many.
    fn find(&mut self, _query: &str) -> usize {
        0
    }

    /// Whether the search bar offers to replace: where the document can be
    /// changed now.
    fn can_replace(&self, _editing: &Editing) -> bool {
        false
    }

    /// Replace the current match, or every match, with a text, as one step to
    /// undo, and answer how many were replaced and how many left alone.
    fn replace(&mut self, _with: &str, _all: bool, _editing: &mut Editing) -> Replaced {
        Replaced::default()
    }

    /// Make one of the matches the current one, and bring it into view.
    fn show_match(&mut self, _index: usize) {}

    /// Draw the document. The shell has already put a scroll area or a panel
    /// around whatever this needs. The editing state says whether edit mode is
    /// on and takes the snapshot an edit records before it changes the tree.
    fn central(&mut self, ui: &mut Ui, zoom: f32, editing: &mut Editing);

    /// Draw the panel beside the document — an outline, a sheet list, a slide
    /// list — and answer whether there is one to draw.
    fn side(&mut self, _ui: &mut Ui) -> bool {
        false
    }

    /// Add the application's own items to the View menu.
    fn view_menu(&mut self, _ui: &mut Ui) {}

    /// Add the application's own items to the File menu, after saving: what
    /// the document can be written out as. Given the file the document was
    /// read from, which is where such a file is offered to go.
    fn file_menu(&mut self, _ui: &mut Ui, _path: Option<&Path>) {}

    /// Something the view has to tell the person, for the bar at the foot of
    /// the window, once.
    fn take_notice(&mut self) -> Option<Notice> {
        None
    }
}

/// A message a view hands the window to show at its foot.
pub enum Notice {
    /// Something finished, and what came of it.
    Done(String),
    /// Something could not be done, and why.
    Problem(String),
}

/// The window: chrome, keys, errors, and one view inside it.
pub struct Shell<V: View> {
    view: V,
    product: Product,
    path: Option<PathBuf>,
    error: Option<String>,
    /// What the view last said had finished, until it is dismissed.
    notice: Option<String>,
    /// Set when a document was opened during a frame, cleared at the end of it.
    ///
    /// See the comment where it is read in [`eframe::App::ui`].
    settling: bool,
    zoom: f32,
    show_side: bool,
    editing: Editing,
    settings: Settings,
    find: FindBar,
    /// Whether the window has been made to fill the screen for a slideshow.
    screen: Screen,
    /// What was asked for while the document had unsaved changes, waiting on
    /// the person's answer.
    pending: Option<Pending>,
    /// The person has answered that the window may close, so the next request
    /// to close it is not asked about again.
    closing: bool,
}

/// How much of the screen the window has.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Screen {
    Window,
    Full,
}

/// Something that would throw away unsaved changes, held until the person
/// says whether to save them, discard them, or not do it after all.
#[derive(Clone, Copy)]
enum Pending {
    AskForAFile,
    Reload,
    Close,
    Quit,
}

/// How far a zoom step moves, and the limits.
const ZOOM_STEP: f32 = 1.1;
const ZOOM_MIN: f32 = 0.4;
const ZOOM_MAX: f32 = 4.0;

impl<V: View> Shell<V> {
    /// A window with nothing open.
    pub fn new(product: Product, view: V) -> Self {
        Self {
            view,
            product,
            path: None,
            error: None,
            notice: None,
            settling: false,
            zoom: 1.0,
            show_side: true,
            editing: Editing::default(),
            settings: Settings::load(),
            find: FindBar::default(),
            screen: Screen::Window,
            pending: None,
            closing: false,
        }
    }

    /// Open a path, reading it here so that the view never touches the file
    /// system.
    ///
    /// Unconditional: the document that was open is gone. [`Self::request`]
    /// is the way in for anything a person asked for, and it asks first.
    pub fn open(&mut self, ctx: &egui::Context, path: &Path) {
        match std::fs::read(path) {
            Ok(bytes) => match self.view.open(ctx, &bytes, path) {
                Ok(()) => {
                    self.path = Some(path.to_path_buf());
                    self.error = None;
                    self.settling = true;
                    self.editing.reset();
                    self.editing.on = self.settings.open_in_edit_mode;
                }
                Err(message) => {
                    self.view.close();
                    self.path = None;
                    self.error = Some(message);
                    self.editing.reset();
                }
            },
            Err(e) => {
                self.error = Some(fill(
                    t("{file} could not be read: {reason}"),
                    &[("file", &name_of(path)), ("reason", &e.to_string())],
                ));
            }
        }
    }

    /// Do something that would lose unsaved changes, or ask first.
    ///
    /// With nothing to lose it is done now. Otherwise it waits on the answer
    /// to the question [`Self::ask_about_changes`] draws, and is done, or not,
    /// from there.
    fn request(&mut self, ctx: &egui::Context, action: Pending) {
        if self.editing.modified() {
            self.pending = Some(action);
        } else {
            self.perform(ctx, action);
        }
    }

    fn perform(&mut self, ctx: &egui::Context, action: Pending) {
        match action {
            Pending::AskForAFile => self.ask_for_a_file(ctx),
            Pending::Reload => {
                if let Some(path) = self.path.clone() {
                    self.open(ctx, &path);
                }
            }
            Pending::Close => self.close(),
            Pending::Quit => {
                self.closing = true;
                ctx.send_viewport_cmd(egui::ViewportCommand::Close);
            }
        }
    }

    fn ask_for_a_file(&mut self, ctx: &egui::Context) {
        let file = rfd::FileDialog::new()
            .add_filter(t(self.product.format), &[self.product.extension])
            .pick_file();
        if let Some(path) = file {
            self.open(ctx, &path);
        }
    }

    fn close(&mut self) {
        self.view.close();
        self.path = None;
        self.error = None;
        self.notice = None;
        self.editing.reset();
    }

    /// Write the document over the file it was read from.
    ///
    /// Answers whether it was written, which is what a pending action waits
    /// on: a save that failed is not a reason to go on and close the window.
    fn save(&mut self) -> bool {
        match self.path.clone() {
            Some(path) => self.write_to(&path),
            None => self.save_as(),
        }
    }

    /// Ask where to write the document, and write it there.
    fn save_as(&mut self) -> bool {
        let mut dialog =
            rfd::FileDialog::new().add_filter(t(self.product.format), &[self.product.extension]);
        if let Some(path) = &self.path {
            dialog = dialog.set_file_name(name_of(path));
            if let Some(directory) = path.parent() {
                dialog = dialog.set_directory(directory);
            }
        }
        let Some(mut path) = dialog.save_file() else {
            return false;
        };
        // A name typed without an extension gets the format's, because the
        // desktop finds the application by the extension and a file without
        // one opens nowhere.
        if path.extension().is_none() {
            path.set_extension(self.product.extension);
        }
        if self.write_to(&path) {
            self.path = Some(path);
            true
        } else {
            false
        }
    }

    /// Serialize the document, prove it reads back, and put it on disk.
    /// DESIGN.md §11.
    fn write_to(&mut self, path: &Path) -> bool {
        let Some(document) = self.view.document_mut() else {
            return false;
        };
        let written = document
            .write_verified()
            .map_err(|e| e.to_string())
            .and_then(|bytes| replace_file(path, &bytes).map_err(|e| e.to_string()));
        match written {
            Ok(()) => {
                self.editing.mark_saved();
                self.error = None;
                true
            }
            Err(reason) => {
                self.error = Some(fill(
                    t("{file} could not be saved: {reason}"),
                    &[("file", &name_of(path)), ("reason", &reason)],
                ));
                false
            }
        }
    }

    fn undo(&mut self) {
        let caret = self.view.caret();
        if let Some(document) = self.view.document_mut()
            && let Some((previous, caret)) = self.editing.undo(&document.content, caret)
        {
            document.content = previous;
            self.after_history(caret);
        }
    }

    fn redo(&mut self) {
        let caret = self.view.caret();
        if let Some(document) = self.view.document_mut()
            && let Some((next, caret)) = self.editing.redo(&document.content, caret)
        {
            document.content = next;
            self.after_history(caret);
        }
    }

    /// The tree was replaced by undo or redo: the view rebuilds from it, and
    /// the caret goes where the state it returned to had it.
    fn after_history(&mut self, caret: Option<Caret>) {
        self.view.reindex();
        if let Some(caret) = caret {
            self.view.restore_caret(caret);
        }
    }

    /// The window's title: the document's own title, or its file name, marked
    /// when it has changes the file does not.
    fn window_title(&self) -> String {
        let document = self
            .view
            .title()
            .filter(|title| !title.trim().is_empty())
            .or_else(|| self.path.as_deref().map(name_of));
        let mark = if self.editing.modified() { "● " } else { "" };
        match document {
            Some(name) => format!("{mark}{name} — {}", self.product.id),
            None => self.product.id.to_owned(),
        }
    }

    /// The question a pending action waits on, drawn over the window.
    fn ask_about_changes(&mut self, ctx: &egui::Context) {
        if self.pending.is_none() {
            return;
        }
        let file = self.path.as_deref().map(name_of).unwrap_or_default();
        // Save, discard, or neither. `None` until the person answers.
        let mut answer = None;
        egui::Modal::new(egui::Id::new("unsaved")).show(ctx, |ui| {
            ui.heading(fill(t("Save changes to {file}?"), &[("file", &file)]));
            ui.label(t("The document has changes that are not saved."));
            ui.add_space(8.0);
            ui.horizontal(|ui| {
                if ui.button(t("Save")).clicked() || ui.input(|i| i.key_pressed(Key::Enter)) {
                    answer = Some(Some(true));
                }
                if ui.button(t("Discard")).clicked() {
                    answer = Some(Some(false));
                }
                if ui.button(t("Cancel")).clicked() || ui.input(|i| i.key_pressed(Key::Escape)) {
                    answer = Some(None);
                }
            });
        });
        let Some(answer) = answer else {
            return;
        };
        let Some(action) = self.pending.take() else {
            return;
        };
        match answer {
            Some(true) => {
                if self.save() {
                    self.perform(ctx, action);
                }
            }
            Some(false) => self.perform(ctx, action),
            None => {}
        }
    }
}

impl<V: View> eframe::App for Shell<V> {
    fn ui(&mut self, ui: &mut Ui, _frame: &mut eframe::Frame) {
        let ctx = ui.ctx().clone();

        // The window's own close button, which asks like Quit does. The close
        // is cancelled and asked for again when the person has answered.
        if ctx.input(|i| i.viewport().close_requested()) && !self.closing && self.editing.modified()
        {
            ctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
            self.pending = Some(Pending::Quit);
        }

        // Nothing is taken while the question is up, so an answer typed at it
        // reaches it and nothing else; and nothing is taken while a text field
        // has the focus, so Ctrl+Z inside a cell undoes the typing and not the
        // document. The page editor is not such a field: its typing is the
        // document's, and so is its Ctrl+Z.
        let presenting = self.view.presenting();
        let screen = if presenting {
            Screen::Full
        } else {
            Screen::Window
        };
        if screen != self.screen {
            self.screen = screen;
            ctx.send_viewport_cmd(egui::ViewportCommand::Fullscreen(presenting));
        }
        self.editing.asking = self.pending.is_some();
        let field_focused = ctx
            .memory(egui::Memory::focused)
            .is_some_and(|id| id != crate::flow_model::page_editor_id());
        if self.pending.is_none() && !presenting {
            self.find_keys(&ctx);
        }
        if self.pending.is_none() && !field_focused && !presenting {
            self.keys(&ctx);
        }

        // A document macOS asked for, which reaches here rather than through
        // the command line. Taken rather than read, so one event opens one
        // document instead of reopening it on every frame after.
        #[cfg(target_os = "macos")]
        if let Some(path) = crate::opened_document::taken() {
            self.open(&ctx, &path);
        }

        ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.window_title()));

        if !presenting {
            self.chrome(ui, &ctx);
        }

        // **A document opened during this frame is not drawn until the next
        // one.** Opening one registers the font families it names, and
        // `Context::set_fonts` takes effect at the start of the following pass,
        // so laying the document out now would ask for a family the definitions
        // still in force do not carry. egui does not fall back for that: it
        // panics, and a panic inside the macOS event callback cannot unwind, so
        // the process aborts.
        //
        // Every way of opening a document but one goes through a frame:
        // Ctrl+O, Reload, and the Apple Event. The exception is the path on the
        // command line, which is opened in eframe's creation closure before any
        // pass has begun, and is why this went unnoticed until a runner opened a
        // document through Launch Services. `tests/fonts_midframe.rs` pins the
        // hazard.
        //
        // One frame, and the repaint is asked for rather than waited for, so
        // the document appears immediately rather than when the pointer next
        // moves.
        let settling = self.settling;
        if settling {
            self.settling = false;
            ctx.request_repaint();
        }

        let central = if presenting {
            egui::CentralPanel::default().frame(egui::Frame::NONE.fill(egui::Color32::BLACK))
        } else {
            egui::CentralPanel::default_margins()
        };
        central.show(ui, |ui| {
            if settling {
                // Deliberately blank, and for one frame. Drawing the
                // nothing-open message here instead would flash it between a
                // double-click and the document.
            } else if self.view.is_open() {
                self.view.central(ui, self.zoom, &mut self.editing);
            } else {
                self.nothing_open(ui);
            }
        });

        self.ask_about_changes(&ctx);
    }
}

impl<V: View> Shell<V> {
    /// What is around the document: the menu, the search bar, an error and
    /// the view's side panel.
    fn chrome(&mut self, ui: &mut Ui, ctx: &egui::Context) {
        egui::Panel::top("menu").show(ui, |ui| self.menu_bar(ui, ctx));
        self.search(ui);

        match self.view.take_notice() {
            Some(Notice::Done(message)) => {
                self.notice = Some(message);
                self.error = None;
            }
            Some(Notice::Problem(message)) => {
                self.error = Some(message);
                self.notice = None;
            }
            None => {}
        }
        if let Some(message) = self.notice.clone() {
            egui::Panel::bottom("notice").show(ui, |ui| {
                ui.horizontal_wrapped(|ui| {
                    ui.label(message);
                    if ui.button(t("Dismiss")).clicked() {
                        self.notice = None;
                    }
                });
            });
        }
        if let Some(message) = self.error.clone() {
            egui::Panel::bottom("error").show(ui, |ui| {
                ui.horizontal_wrapped(|ui| {
                    ui.colored_label(ui.visuals().error_fg_color, "\u{26a0}");
                    ui.label(message);
                    if ui.button(t("Dismiss")).clicked() {
                        self.error = None;
                    }
                });
            });
        }

        if self.show_side && self.view.is_open() {
            // The view answers whether it has anything to put beside the
            // document, so that a format with nothing there gets no empty panel
            // rather than a blank one a person has to close.
            let mut drew = false;
            egui::Panel::left("side")
                .resizable(true)
                .default_size(220.0)
                .min_size(120.0)
                .show(ui, |ui| {
                    egui::ScrollArea::both().show(ui, |ui| {
                        drew = self.view.side(ui);
                    });
                });
            if !drew {
                self.show_side = false;
            }
        }
    }

    /// The menu bar: the File and Edit menus that are the same in every
    /// application, the View menu with the application's own items after the
    /// shell's, and on the right what mode the window is in and how far it is
    /// zoomed.
    fn menu_bar(&mut self, ui: &mut Ui, ctx: &egui::Context) {
        egui::MenuBar::new().ui(ui, |ui| {
            ui.menu_button(t("File"), |ui| {
                if ui.button(t("Open…")).clicked() {
                    ui.close();
                    self.request(ctx, Pending::AskForAFile);
                }
                let open = self.path.is_some();
                if ui
                    .add_enabled(open, egui::Button::new(t("Reload")))
                    .clicked()
                {
                    ui.close();
                    self.request(ctx, Pending::Reload);
                }
                if ui
                    .add_enabled(open, egui::Button::new(t("Close")))
                    .clicked()
                {
                    ui.close();
                    self.request(ctx, Pending::Close);
                }
                ui.separator();
                let modified = open && self.editing.modified();
                if ui
                    .add_enabled(modified, egui::Button::new(t("Save")))
                    .clicked()
                {
                    ui.close();
                    self.save();
                }
                if ui
                    .add_enabled(open, egui::Button::new(t("Save as…")))
                    .clicked()
                {
                    ui.close();
                    self.save_as();
                }
                if self.view.is_open() {
                    self.view.file_menu(ui, self.path.as_deref());
                }
                ui.separator();
                if ui.button(t("Quit")).clicked() {
                    ui.close();
                    self.request(ctx, Pending::Quit);
                }
            });
            ui.menu_button(t("Edit"), |ui| self.edit_menu(ui));
            if self.view.is_open() {
                self.view.menus(ui, &self.editing);
            }
            ui.menu_button(t("View"), |ui| {
                if ui.button(t("Zoom in")).clicked() {
                    self.zoom = (self.zoom * ZOOM_STEP).min(ZOOM_MAX);
                }
                if ui.button(t("Zoom out")).clicked() {
                    self.zoom = (self.zoom / ZOOM_STEP).max(ZOOM_MIN);
                }
                if ui.button(t("Actual size")).clicked() {
                    self.zoom = 1.0;
                }
                ui.separator();
                ui.checkbox(&mut self.show_side, t("Show the side panel"));
                self.view.view_menu(ui);
            });
            ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
                #[allow(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
                let percent = (self.zoom * 100.0).round() as u32;
                ui.label(fill(t("{percent}%"), &[("percent", &percent.to_string())]));
                if self.editing.on && self.view.is_open() {
                    ui.separator();
                    ui.strong(t("Editing"));
                }
            });
        });
    }

    /// The Edit menu: undo and redo, search, and the two preferences about
    /// editing.
    fn edit_menu(&mut self, ui: &mut Ui) {
        if ui
            .add_enabled(self.editing.can_undo(), egui::Button::new(t("Undo")))
            .clicked()
        {
            ui.close();
            self.undo();
        }
        if ui
            .add_enabled(self.editing.can_redo(), egui::Button::new(t("Redo")))
            .clicked()
        {
            ui.close();
            self.redo();
        }
        ui.separator();
        if ui
            .add_enabled(self.view.is_open(), egui::Button::new(t("Find…")))
            .clicked()
        {
            ui.close();
            self.find.open();
        }
        if ui
            .add_enabled(
                self.view.is_open() && self.view.can_replace(&self.editing),
                egui::Button::new(t("Replace…")),
            )
            .clicked()
        {
            ui.close();
            self.find.open_replacing();
        }
        ui.separator();
        ui.checkbox(&mut self.editing.on, t("Edit mode"));
        if ui
            .checkbox(
                &mut self.settings.open_in_edit_mode,
                t("Open documents in edit mode"),
            )
            .changed()
            && let Err(e) = self.settings.save()
        {
            self.error = Some(fill(
                t("The setting could not be saved: {reason}"),
                &[("reason", &e.to_string())],
            ));
        }
    }

    /// The search bar, when it is open, and the view's matches kept in step
    /// with what it says and with the document.
    fn search(&mut self, ui: &mut Ui) {
        if !self.find.is_open() || !self.view.is_open() {
            if self.find.searching {
                self.find.searching = false;
                self.find.count = 0;
                self.view.find("");
            }
            return;
        }
        let can_replace = self.view.can_replace(&self.editing);
        let mut pressed = crate::find_bar::Pressed::default();
        egui::Panel::top("find").show(ui, |ui| pressed = self.find.ui(ui, can_replace));
        if !self.find.is_open() {
            return;
        }
        if let Some(query_changed) = self.find.due(self.editing.revision()) {
            self.find.searching = true;
            self.find.count = self.view.find(self.find.query());
            if query_changed {
                self.find.current = 0;
                if self.find.count > 0 {
                    self.view.show_match(0);
                }
            } else {
                self.find.current = self.find.current.min(self.find.count.saturating_sub(1));
            }
        }
        if let Some(step) = pressed.step {
            self.step_match(step);
        }
        if let Some(which) = pressed.replace {
            self.replace(which);
        }
    }

    fn replace(&mut self, which: Replace) {
        let with = self.find.replacement().to_owned();
        let done = self
            .view
            .replace(&with, which == Replace::All, &mut self.editing);
        // A replacement that still matches the query is the match it replaced,
        // so the next one is the one after.
        if which == Replace::One
            && done.replaced > 0
            && !crate::find::ranges(&with, self.find.query()).is_empty()
        {
            self.find.current += 1;
        }
        let replaced = done.replaced.to_string();
        self.find.say(if done.skipped == 0 {
            fill(t("{replaced} replaced"), &[("replaced", &replaced)])
        } else {
            fill(
                t("{replaced} replaced, {skipped} left"),
                &[
                    ("replaced", &replaced),
                    ("skipped", &done.skipped.to_string()),
                ],
            )
        });
    }

    fn step_match(&mut self, step: Step) {
        let count = self.find.count;
        if count == 0 {
            return;
        }
        self.find.current = match step {
            Step::Next => (self.find.current + 1) % count,
            Step::Previous => (self.find.current + count - 1) % count,
        };
        self.view.show_match(self.find.current);
    }

    /// What the window says before a document is opened.
    fn nothing_open(&mut self, ui: &mut Ui) {
        ui.vertical_centered(|ui| {
            ui.add_space(ui.available_height() * 0.3);
            // The application's own name, which is not translated, and the name
            // of the format, which is: Comma's German has said
            // `OpenDocument-Tabellendokument` since it shipped.
            ui.heading(self.product.id);
            ui.label(t(self.product.format));
            ui.add_space(12.0);
            if ui.button(t("Open a document…")).clicked() {
                let ctx = ui.ctx().clone();
                self.ask_for_a_file(&ctx);
            }
        });
    }

    /// Ctrl+F and F3, which a text field has no use for and so are taken
    /// whether or not one has the keyboard.
    fn find_keys(&mut self, ctx: &egui::Context) {
        if !self.view.is_open() {
            return;
        }
        let pressed = |modifiers, key| {
            ctx.input_mut(|input| input.consume_shortcut(&KeyboardShortcut::new(modifiers, key)))
        };
        if pressed(Modifiers::COMMAND, Key::F) {
            self.find.open();
        }
        if pressed(Modifiers::COMMAND, Key::H) {
            self.find.open_replacing();
        }
        if pressed(Modifiers::SHIFT, Key::F3) {
            self.step_match(Step::Previous);
        }
        if pressed(Modifiers::NONE, Key::F3) {
            if self.find.is_open() {
                self.step_match(Step::Next);
            } else {
                self.find.open();
            }
        }
    }

    fn keys(&mut self, ctx: &egui::Context) {
        let pressed = |key| {
            ctx.input_mut(|input| {
                input.consume_shortcut(&KeyboardShortcut::new(Modifiers::COMMAND, key))
            })
        };
        let shifted = |key| {
            ctx.input_mut(|input| {
                input.consume_shortcut(&KeyboardShortcut::new(
                    Modifiers::COMMAND | Modifiers::SHIFT,
                    key,
                ))
            })
        };
        // The shifted pair first, because Ctrl+Shift+S is not Ctrl+S.
        if shifted(Key::S) {
            self.save_as();
        }
        if shifted(Key::Z) || pressed(Key::Y) {
            self.redo();
        }
        if pressed(Key::S) && self.editing.modified() {
            self.save();
        }
        if pressed(Key::Z) {
            self.undo();
        }
        if pressed(Key::E) && self.view.is_open() {
            self.editing.on = !self.editing.on;
        }
        if pressed(Key::O) {
            self.request(ctx, Pending::AskForAFile);
        }
        if pressed(Key::R) {
            self.request(ctx, Pending::Reload);
        }
        if pressed(Key::W) {
            self.request(ctx, Pending::Close);
        }
        // `Plus` is what the key sends with shift held and `Equals` without, and
        // a person pressing the same physical key means the same thing either way.
        if pressed(Key::Plus) || pressed(Key::Equals) {
            self.zoom = (self.zoom * ZOOM_STEP).min(ZOOM_MAX);
        }
        if pressed(Key::Minus) {
            self.zoom = (self.zoom / ZOOM_STEP).max(ZOOM_MIN);
        }
        if pressed(Key::Num0) {
            self.zoom = 1.0;
        }
    }
}

/// A file's name without its directory, for a title or a message.
fn name_of(path: &Path) -> String {
    path.file_name().map_or_else(
        || path.display().to_string(),
        |name| name.to_string_lossy().into_owned(),
    )
}

/// Put bytes where a file is, so that the file is either what it was or what
/// was written and never half of each.
///
/// The bytes go into a temporary file beside the target, which is then renamed
/// over it: a rename within one filesystem is atomic, and a crash before it
/// leaves the original untouched and a stray `.part` file to delete. The
/// target's permissions are carried over, because the rename replaces the
/// inode and would otherwise leave a document writable by whoever the
/// temporary file's default said.
///
/// **macOS writes in place.** The sandbox grant a person gives by choosing a
/// file covers the file and not its directory, so a temporary file beside it
/// is refused with *Operation not permitted*. The safe rewrite there goes
/// through `NSItemReplacementDirectory` and `replaceItemAtURL:`, which is a
/// platform arm this build cannot verify and does not carry yet.
///
/// # Errors
///
/// The file could not be written, or not renamed into place.
pub fn replace_file(path: &Path, bytes: &[u8]) -> std::io::Result<()> {
    #[cfg(target_os = "macos")]
    {
        std::fs::write(path, bytes)
    }
    #[cfg(not(target_os = "macos"))]
    {
        use std::io::Write as _;
        let temporary = path.with_file_name(format!("{}.part", name_of(path)));
        let mut file = std::fs::File::create(&temporary)?;
        let written = file
            .write_all(bytes)
            .and_then(|()| file.sync_all())
            .and_then(|()| match std::fs::metadata(path) {
                Ok(existing) => std::fs::set_permissions(&temporary, existing.permissions()),
                Err(_) => Ok(()),
            })
            .and_then(|()| std::fs::rename(&temporary, path));
        if written.is_err() {
            // Best effort: the error the person sees is the one that stopped
            // the write, not the one about tidying up after it.
            let _ = std::fs::remove_file(&temporary);
        }
        written
    }
}

/// Open a window for a product, with the paths given on the command line.
///
/// # Errors
///
/// The window could not be created, which is eframe's answer and not this
/// application's.
pub fn run<V: View + 'static>(
    product: Product,
    build: impl FnOnce(&egui::Context) -> V + 'static,
) -> eframe::Result {
    crate::i18n::start();

    let id = product.id;
    let viewport = egui::ViewportBuilder::default()
        // How a Wayland compositor finds the window's icon and its name: it
        // matches this against the basename of the `.desktop` entry.
        .with_app_id(id)
        .with_title(id)
        .with_inner_size([1000.0, 760.0])
        .with_min_inner_size([420.0, 320.0]);

    // **Naming no icon is not neutral on macOS, and it costs the Dock.** The
    // bundle carries the `.icns` and `CFBundleIconFile` points at it, which is
    // where a macOS application's icon comes from, so this looks like an arm
    // with nothing to do. It has something to do: eframe substitutes its own
    // logo for a viewport that names no icon and hands that to
    // `setApplicationIconImage:`, which outranks the bundle. Finder, Launch
    // Services and every API still resolve the right drawing, so nothing short
    // of a person looking at the Dock finds it, and it caught two of the
    // sibling applications before it was written down.
    //
    // An empty `IconData` declines the icon rather than replacing it:
    // eframe turns one into `None` and the macOS arm only calls the selector
    // where there is an image. Handing the drawing over again would also work
    // and would carry a second copy of it in the binary to overwrite the
    // bundle's with a worse-scaled equal.
    //
    // One line for three windows, because all three come through here.
    // **Unverified from Linux**: it compiles for the target and nothing else
    // about it can be checked without looking at a Dock.
    #[cfg(target_os = "macos")]
    let viewport = viewport.with_icon(egui::IconData::default());

    // Windows, which is the other half of the same question. Here an icon has
    // to be given, because the shell reads one out of a resource and this build
    // compiles no resource.
    #[cfg(target_os = "windows")]
    let viewport = match window_icon(product.icon) {
        Some(icon) => viewport.with_icon(icon),
        None => viewport,
    };

    let options = eframe::NativeOptions {
        viewport,
        ..eframe::NativeOptions::default()
    };

    // Before `eframe`, because macOS dispatches the document that launched this
    // process before the creation closure is reached and AppKit's own handler
    // refuses it there. `opened_document` has the measurement.
    #[cfg(target_os = "macos")]
    crate::opened_document::watch();

    let first = std::env::args_os().nth(1).map(PathBuf::from);
    eframe::run_native(
        id,
        options,
        Box::new(move |cc| {
            crate::system_theme::follow(&cc.egui_ctx);
            // Now that there is a context, a document that arrives has
            // somewhere to wake.
            #[cfg(target_os = "macos")]
            crate::opened_document::wake_with(&cc.egui_ctx);
            let mut shell = Shell::new(product, build(&cc.egui_ctx));
            if let Some(path) = first {
                shell.open(&cc.egui_ctx, &path);
            }
            Ok(Box::new(shell))
        }),
    )
}

/// The 64-pixel entry of an icon directory, as a window icon.
///
/// 64 because it is the largest size no scaling has to enlarge, and every
/// smaller one the shell wants is a reduction of it. `None` where the directory
/// is empty, which is what a build from a published crate has, or where it does
/// not decode, which is a broken artefact rather than a reason to refuse to
/// open a window.
#[cfg(target_os = "windows")]
fn window_icon(bytes: &'static [u8]) -> Option<egui::IconData> {
    if bytes.is_empty() {
        return None;
    }
    let directory = ico::IconDir::read(std::io::Cursor::new(bytes)).ok()?;
    let entry = directory
        .entries()
        .iter()
        .find(|entry| entry.width() == 64)
        .or_else(|| directory.entries().last())?;
    let image = entry.decode().ok()?;
    Some(egui::IconData {
        width: image.width(),
        height: image.height(),
        rgba: image.rgba_data().to_vec(),
    })
}

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

    /// The document on disk is what was written, with the permissions it had,
    /// and nothing is left beside it.
    #[test]
    fn a_file_is_replaced_whole() {
        let directory = std::env::temp_dir().join(format!("odox-replace-{}", std::process::id()));
        std::fs::create_dir_all(&directory).expect("a scratch directory");
        let path = directory.join("document.odt");
        std::fs::write(&path, b"before").expect("the original");
        let mode = std::fs::metadata(&path)
            .expect("its metadata")
            .permissions();

        replace_file(&path, b"after").expect("the replacement");

        assert_eq!(std::fs::read(&path).expect("the file"), b"after");
        assert_eq!(
            std::fs::metadata(&path)
                .expect("its metadata")
                .permissions(),
            mode
        );
        let left: Vec<_> = std::fs::read_dir(&directory)
            .expect("the directory")
            .filter_map(Result::ok)
            .map(|entry| entry.file_name())
            .collect();
        assert_eq!(left, vec![std::ffi::OsString::from("document.odt")]);
        std::fs::remove_dir_all(directory).expect("tidy");
    }

    /// A target that cannot be written leaves nothing behind and says so.
    #[test]
    fn a_failed_write_leaves_no_part_file() {
        let directory = std::env::temp_dir().join(format!("odox-refuse-{}", std::process::id()));
        std::fs::create_dir_all(&directory).expect("a scratch directory");
        let missing = directory.join("nowhere").join("document.odt");
        assert!(replace_file(&missing, b"x").is_err());
        assert_eq!(
            std::fs::read_dir(&directory)
                .expect("the directory")
                .count(),
            0
        );
        std::fs::remove_dir_all(directory).expect("tidy");
    }
}