Skip to main content

editor/
editor.rs

1//! A text editor: files in tabs that close and reorder; a find and replace bar that selects its
2//! matches; a status line with cursor position, length and saved state; menus with shortcuts
3//! for everything, including the Edit menu's undo, redo, cut, copy and paste. A file with
4//! unsaved changes is never closed without asking.
5//!   cargo run -p taut --example editor [-- <file> ...]
6#![windows_subsystem = "windows"]
7use std::path::PathBuf;
8use taut::{Align, FileDialog, Id, Key, Length, Mods, TextCommand, Ui, Window};
9
10/// What the editor can be asked to do: from its menus, and by keys.
11#[derive(Clone, Copy, Debug, PartialEq)]
12enum Command {
13    New,
14    Open,
15    Save,
16    SaveAs,
17    Close,
18    Quit,
19    Undo,
20    Redo,
21    Cut,
22    Copy,
23    Paste,
24    SelectAll,
25    Find,
26    Replace,
27    FindNext,
28    FindBefore,
29    NextTab,
30    TabBefore,
31}
32use Command::*;
33
34/// The rows of the menus: what each says, after a tab the keys that do the same, and the
35/// command. The keys are asked for from these same words, so a row and its keys never
36/// part ways.
37const FILE: [(&str, Command); 6] =
38    [("New\tCtrl+N", New), ("Open\u{2026}\tCtrl+O", Open), ("Save\tCtrl+S", Save), ("Save as\u{2026}\tCtrl+Shift+S", SaveAs), ("Close tab\tCtrl+W", Close), ("Quit\tCtrl+Q", Quit)];
39const EDIT: [(&str, Command); 10] = [
40    ("Undo\tCtrl+Z", Undo),
41    ("Redo\tCtrl+Y", Redo),
42    ("Cut\tCtrl+X", Cut),
43    ("Copy\tCtrl+C", Copy),
44    ("Paste\tCtrl+V", Paste),
45    ("Select all\tCtrl+A", SelectAll),
46    ("Find\u{2026}\tCtrl+F", Find),
47    ("Replace\u{2026}\tCtrl+H", Replace),
48    ("Find next\tF3", FindNext),
49    ("Find the one before\tShift+F3", FindBefore),
50];
51/// Keys that are in no menu.
52const TABS: [(&str, Command); 2] = [("\tCtrl+Tab", NextTab), ("\tCtrl+Shift+Tab", TabBefore)];
53
54/// One file that is open.
55pub struct Paper {
56    /// What it is known by from run to run: its tab follows it.
57    id: u64,
58    /// Where it is kept: nowhere, until it is saved.
59    path: Option<PathBuf>,
60    text: String,
61    /// The text as it was last saved.
62    saved: String,
63}
64
65/// A tab: the paper it is for, and the name on it.
66pub struct Tab {
67    id: u64,
68    name: String,
69}
70
71/// What is to be answered before a paper is closed, or the editor is.
72#[derive(Clone, Copy, PartialEq)]
73enum Asking {
74    /// Whether to save the changes to the paper with this id, which is to be closed.
75    Close(u64),
76    /// Whether to quit with changes that are not saved.
77    Quit,
78}
79
80/// Everything the editor keeps.
81pub struct Editor {
82    papers: Vec<Paper>,
83    /// The tabs, in their order, and which is in front.
84    tabs: Vec<Tab>,
85    front: usize,
86    /// The bar to find in is open, and with it the row to replace with.
87    finding: bool,
88    replacing: bool,
89    find: String,
90    replace: String,
91    /// Which of the places what is looked for is found at is the one meant, by number.
92    found: usize,
93    /// The keyboard is to go to the box to find in, which has just opened; and the place
94    /// found is to be selected in the paper.
95    to_find: bool,
96    to_select: bool,
97    asking: Option<Asking>,
98    /// The box the paper in front is typed into, as of the last run.
99    typed: Id,
100    /// The dialog that selects a file to open, or says where to save; and which paper it is
101    /// saving, while it is.
102    dialog: FileDialog,
103    saving: Option<u64>,
104    /// The number of the next paper.
105    ids: u64,
106    /// The editor is done with: `main` closes its window.
107    quit: bool,
108}
109
110impl Editor {
111    /// An editor with these files open; with none, an empty paper.
112    pub fn new(files: &[PathBuf]) -> Editor {
113        let (find, replace, dialog) = (String::new(), String::new(), FileDialog::default());
114        let mut editor = Editor {
115            papers: Vec::new(),
116            tabs: Vec::new(),
117            front: 0,
118            finding: false,
119            replacing: false,
120            find,
121            replace,
122            found: 0,
123            to_find: false,
124            to_select: false,
125            asking: None,
126            typed: 0,
127            dialog,
128            saving: None,
129            ids: 0,
130            quit: false,
131        };
132        for file in files {
133            editor.open(file.clone());
134        }
135        if editor.papers.is_empty() {
136            editor.add(None, String::new());
137        }
138        editor
139    }
140
141    /// Opens a paper for a file, or with nothing in it, and puts it in front.
142    fn add(&mut self, path: Option<PathBuf>, text: String) {
143        let name = path.as_ref().and_then(|path| path.file_name()).map_or_else(|| format!("Untitled {}", self.ids + 1), |name| name.to_string_lossy().into_owned());
144        self.papers.push(Paper { id: self.ids, path, saved: text.clone(), text });
145        self.tabs.push(Tab { id: self.ids, name });
146        (self.front, self.ids) = (self.tabs.len() - 1, self.ids + 1);
147    }
148    fn open(&mut self, path: PathBuf) {
149        if let Ok(text) = std::fs::read_to_string(&path) {
150            self.add(Some(path), text);
151        }
152    }
153
154    /// The paper with this id, and the tab for it.
155    fn paper(&mut self, id: u64) -> &mut Paper {
156        let at = self.papers.iter().position(|paper| paper.id == id).unwrap_or(0);
157        &mut self.papers[at]
158    }
159    fn tab(&mut self, id: u64) -> &mut Tab {
160        let at = self.tabs.iter().position(|tab| tab.id == id).unwrap_or(0);
161        &mut self.tabs[at]
162    }
163    /// The id of the paper in front.
164    fn front(&self) -> u64 {
165        self.tabs[self.front].id
166    }
167    fn unsaved(&mut self, id: u64) -> bool {
168        let paper = self.paper(id);
169        paper.text != paper.saved
170    }
171
172    /// Saves a paper where it is kept; for one that is kept nowhere yet, asks where.
173    fn save(&mut self, id: u64) {
174        let Some(path) = self.paper(id).path.clone() else {
175            let name = self.tab(id).name.clone() + ".txt";
176            self.dialog.save(std::env::home_dir().unwrap_or_default(), &name);
177            self.saving = Some(id);
178            return;
179        };
180        let paper = self.paper(id);
181        if std::fs::write(&path, &paper.text).is_ok() {
182            paper.saved = paper.text.clone();
183        }
184    }
185
186    /// Closes a paper; one with changes that are not saved is asked about first, unless
187    /// that is what was `answered`.
188    fn close(&mut self, id: u64, answered: bool) {
189        if self.unsaved(id) && !answered {
190            self.asking = Some(Asking::Close(id));
191            return;
192        }
193        let at = self.tabs.iter().position(|tab| tab.id == id).unwrap_or(0);
194        self.papers.retain(|paper| paper.id != id);
195        self.tabs.retain(|tab| tab.id != id);
196        self.front = self.front.saturating_sub((at < self.front) as usize).min(self.tabs.len().saturating_sub(1));
197        if self.papers.is_empty() {
198            self.add(None, String::new());
199        }
200    }
201
202    /// Where in the paper in front what is looked for is found: from where to where, in bytes.
203    fn places(&mut self) -> Vec<(usize, usize)> {
204        let (find, front) = (self.find.clone(), self.front());
205        match find.is_empty() {
206            true => Vec::new(),
207            false => self.paper(front).text.match_indices(&find).map(|(at, found)| (at, at + found.len())).collect(),
208        }
209    }
210
211    fn command(&mut self, command: Command, ui: &mut Ui) {
212        let (front, count, places) = (self.front(), self.tabs.len(), self.places().len().max(1));
213        match command {
214            New => self.add(None, String::new()),
215            Open => self.dialog.pick(std::env::home_dir().unwrap_or_default()),
216            Save => self.save(front),
217            SaveAs => {
218                self.paper(front).path = None;
219                self.save(front);
220            }
221            Close => self.close(front, false),
222            Quit if self.papers.iter().any(|paper| paper.text != paper.saved) => self.asking = Some(Asking::Quit),
223            Quit => self.quit = true,
224            // (What the box typed into does by its own keys, asked of it by the menu.)
225            Undo => ui.text_command(self.typed, TextCommand::Undo),
226            Redo => ui.text_command(self.typed, TextCommand::Redo),
227            Cut => ui.text_command(self.typed, TextCommand::Cut),
228            Copy => ui.text_command(self.typed, TextCommand::Copy),
229            Paste => ui.text_command(self.typed, TextCommand::Paste),
230            SelectAll => ui.text_command(self.typed, TextCommand::SelectAll),
231            Find | Replace => (self.finding, self.replacing, self.to_find) = (true, command == Replace || self.replacing, true),
232            FindNext => (self.found, self.to_select) = ((self.found + 1) % places, true),
233            FindBefore => (self.found, self.to_select) = ((self.found + places - 1) % places, true),
234            NextTab => self.front = (self.front + 1) % count,
235            TabBefore => self.front = (self.front + count - 1) % count,
236        }
237        ui.rerun();
238    }
239}
240
241pub fn describe(app: &mut Editor, ui: &mut Ui) {
242    let t = ui.theme;
243    let mut asked = menus(app.typed, ui);
244    ui.column().grow().open();
245
246    // The tabs. The cross on one closes its paper, but one with changes is asked about:
247    // a tab that went is put back until that is answered.
248    let before: Vec<(u64, String)> = app.tabs.iter().map(|tab| (tab.id, tab.name.clone())).collect();
249    ui.row().fill(t.panel).pad((6.0, 4.0, 6.0, 0.0)).open();
250    ui.tabs_of(&mut app.front, &mut app.tabs, |tab| tab.name.as_str());
251    ui.close();
252    if let Some((at, (id, name))) = before.into_iter().enumerate().find(|(_, (id, _))| !app.tabs.iter().any(|tab| tab.id == *id)) {
253        app.tabs.insert(at, Tab { id, name });
254        app.front = at;
255        app.close(id, false);
256    }
257
258    find_bar(app, ui);
259
260    // The paper in front: a page of text that fills the room left. (Each paper's box is its
261    // own, by its id: so is where its cursor is, and what can be undone in it.)
262    let id = app.front();
263    ui.column().key(id).grow().open();
264    app.typed = ui.text_page(&mut app.paper(id).text, "").id;
265    ui.close();
266
267    // The line at the bottom: where the cursor is, how long the text is, and whether it is
268    // saved.
269    let typing = ui.text_edit_state(app.typed);
270    let text = &app.paper(id).text;
271    let (lines, words, letters) = (text.lines().count().max(1), text.split_whitespace().count(), text.chars().count());
272    let at = typing.map_or(String::new(), |typing| format!("Line {}, column {}   ", typing.line_column(text).0, typing.line_column(text).1));
273    let state = if app.unsaved(id) { "Not saved" } else { "Saved" };
274    ui.row().h(Length::Px(24.0)).pad((10.0, 0.0)).gap(16.0).fill(t.panel).align(Align::Start, Align::Center).open();
275    ui.note(&format!("{at}Lines: {lines}   Words: {words}   Characters: {letters}"));
276    ui.spacer();
277    ui.note(state);
278    ui.close();
279    ui.close();
280
281    // What the dialogs answer: a file to open or where to save, and what to do with changes.
282    if let Some(path) = ui.file_dialog(&mut app.dialog) {
283        match app.saving.take() {
284            Some(id) => {
285                app.tab(id).name = path.file_name().map_or(String::new(), |name| name.to_string_lossy().into_owned());
286                app.paper(id).path = Some(path);
287                app.save(id);
288            }
289            None => app.open(path),
290        }
291        ui.rerun();
292    }
293    app.saving = app.saving.filter(|_| app.dialog.shown);
294    ask(app, ui);
295    // The keys of every command, asked for once what is typed into has had its own.
296    for (words, command) in FILE.iter().chain(&EDIT).chain(&TABS) {
297        asked = asked.or(words.split_once('\t').filter(|(_, keys)| ui.keys(keys)).map(|_| *command));
298    }
299    if let Some(command) = asked {
300        app.command(command, ui);
301    }
302}
303
304/// The bar of menus, for the box typed into `typed`. Gives back the command whose row was
305/// clicked.
306fn menus(typed: Id, ui: &mut Ui) -> Option<Command> {
307    let mut clicked = None;
308    ui.menu_bar();
309    if ui.menu_button("File") {
310        for (words, command) in FILE {
311            clicked = clicked.or(ui.menu_item(words).clicked.then_some(command));
312        }
313        ui.close();
314    }
315    if ui.menu_button("Edit") {
316        // (What there is nothing to do for is switched off: nothing to undo, nothing selected.)
317        let typing = ui.text_edit_state(typed).unwrap_or_default();
318        let can = |command: Command| match command {
319            Undo => typing.can_undo,
320            Redo => typing.can_redo,
321            Cut | Copy => !typing.range().is_empty(),
322            _ => true,
323        };
324        for (words, command) in EDIT {
325            ui.set_enabled(can(command));
326            clicked = clicked.or(ui.menu_item(words).clicked.then_some(command));
327            if command == Paste {
328                ui.separator();
329            }
330        }
331        ui.set_enabled(true);
332        ui.close();
333    }
334    ui.close();
335    clicked
336}
337
338/// The bar to find and replace in, while it is open.
339fn find_bar(app: &mut Editor, ui: &mut Ui) {
340    let t = ui.theme;
341    if !app.finding {
342        return;
343    }
344    let places = app.places();
345    app.found = app.found.min(places.len().saturating_sub(1));
346    ui.grid(4).pad(6.0).gap(6.0).fill(t.raised).open();
347    let find = ui.text_box(&mut app.find, "Find");
348    // (Enter goes to the place found: the keyboard goes into the paper, with it selected.)
349    let enter = find.focused && ui.key(Key::Enter, Mods::NONE);
350    let next = ui.button("Next").clicked;
351    let count = match (places.len(), app.find.is_empty()) {
352        (_, true) => String::new(),
353        (0, false) => "Not found".into(),
354        (found, false) => format!("{} of {found}", app.found + 1),
355    };
356    ui.note(&count);
357    let done = ui.button("Done").clicked || ui.key(Key::Escape, Mods::NONE);
358    let (mut one, mut all) = (false, false);
359    if app.replacing {
360        ui.text_box(&mut app.replace, "Replace with");
361        one = ui.button("Replace").clicked;
362        all = ui.button("Replace all").clicked;
363    }
364    ui.close();
365    if std::mem::take(&mut app.to_find) {
366        ui.set_focus(find.id);
367        ui.select_all();
368    }
369    app.found = if find.changed { 0 } else { app.found };
370    // The place found, selected in the paper: what the keys of the menu go on from.
371    if let Some(&(from, to)) = places.get(app.found).filter(|_| std::mem::take(&mut app.to_select) || enter) {
372        ui.select_text(app.typed, [from, to]);
373    }
374    let (front, find, replace, found) = (app.front(), app.find.clone(), app.replace.clone(), places.get(app.found).copied());
375    let text = &mut app.paper(front).text;
376    match (next, one, all) {
377        (true, ..) => (app.found, app.to_select) = ((app.found + 1) % places.len().max(1), true),
378        (_, true, _) if found.is_some() => text.replace_range(found.map_or(0..0, |(from, to)| from..to), &replace),
379        (.., true) => *text = text.replace(find.as_str(), &replace),
380        _ if done => (app.finding, app.replacing) = (false, false),
381        _ => return,
382    }
383    ui.rerun();
384}
385
386/// The dialog that asks what to do with changes that are not saved, while one is asked.
387fn ask(app: &mut Editor, ui: &mut Ui) {
388    let t = ui.theme;
389    let Some(asking) = app.asking else { return };
390    let question = match asking {
391        Asking::Close(id) => format!("Save the changes to {} before it is closed?", app.tab(id).name),
392        Asking::Quit => "Some files have changes that are not saved. Quit all the same?".into(),
393    };
394    let beside = ui.dialog();
395    ui.text("Changes not saved", t.font.bold(), t.text);
396    ui.paragraph(&question);
397    ui.row().gap(8.0).align(Align::End, Align::Center).open();
398    let cancel = ui.button("Cancel").clicked || beside.clicked || ui.key(Key::Escape, Mods::NONE);
399    let lose = ui.button(if asking == Asking::Quit { "Quit" } else { "Don't save" }).clicked;
400    let save = asking != Asking::Quit && ui.primary_button("Save").clicked;
401    ui.close();
402    ui.close();
403    if !(cancel || lose || save) {
404        return;
405    }
406    app.asking = None;
407    ui.rerun();
408    match (asking, lose, save) {
409        (Asking::Close(id), true, _) => app.close(id, true),
410        (Asking::Close(id), _, true) => {
411            app.save(id);
412            if !app.unsaved(id) {
413                app.close(id, true);
414            }
415        }
416        (Asking::Quit, true, _) => app.quit = true,
417        _ => {}
418    }
419}
420
421fn main() {
422    let files: Vec<PathBuf> = std::env::args_os().skip(1).map(PathBuf::from).collect();
423    let mut app = Editor::new(&files);
424    let window = Window { title: "Editor", width: 820.0, height: 560.0, min_width: 360.0, min_height: 240.0, ..Default::default() };
425    taut::run(window, move |ui| {
426        describe(&mut app, ui);
427        if app.quit {
428            ui.quit();
429        }
430    });
431}
432
433#[cfg(test)]
434mod tests {
435    use super::*;
436    use taut::Role;
437    use taut::testing::Trial;
438
439    #[test]
440    fn papers_are_written_found_in_replaced_saved_and_closed_with_care() {
441        let folder = std::env::temp_dir().join(format!("taut-editor-{}", std::process::id()));
442        _ = std::fs::remove_dir_all(&folder);
443        std::fs::create_dir_all(&folder).unwrap();
444        let file = folder.join("poem.txt");
445        std::fs::write(&file, "The cat sat.\nThe cat ran.\n").unwrap();
446        let mut trial = Trial::new(Editor::new(std::slice::from_ref(&file)), describe);
447        trial.resize(640.0, 400.0, 1.0);
448        assert!(trial.has(Role::Tab, "poem.txt") && trial.has(Role::Text, "Lines: 2   Words: 6   Characters: 26"));
449        // The page fills the room between the tabs and the line at the bottom.
450        let page = trial.find(Role::TextBox, "").rect;
451        assert!(page.h > 300.0, "{page:?}");
452
453        // Typed into, the paper is no longer saved; Ctrl+S saves it where it is kept.
454        let text = trial.center_of(Role::TextBox, "");
455        trial.click(text);
456        trial.key("Ctrl+End");
457        trial.type_text("The end.");
458        assert!(trial.has(Role::Text, "Not saved") && trial.has(Role::Text, "Line 3, column 9   Lines: 3   Words: 8   Characters: 34"), "{}", trial.dump());
459        trial.key("Ctrl+S");
460        assert_eq!(std::fs::read_to_string(&file).unwrap(), "The cat sat.\nThe cat ran.\nThe end.");
461        assert!(trial.has(Role::Text, "Saved"));
462
463        // Found and replaced: one at a time, and all at once.
464        trial.key("Ctrl+H");
465        trial.type_text("cat");
466        assert!(trial.has(Role::Text, "1 of 2"), "{}", trial.dump());
467        trial.key("F3");
468        assert!(trial.has(Role::Text, "2 of 2"));
469        // What was found is selected in the paper (the second "cat").
470        assert_eq!(trial.ui.text_edit_state(trial.app.typed).map(|typing| typing.range()), Some(17..20));
471        trial.fill("Replace with", "dog");
472        trial.press(Role::Button, "Replace");
473        assert_eq!(trial.app.papers[0].text, "The cat sat.\nThe dog ran.\nThe end.");
474        trial.press(Role::Button, "Replace all");
475        assert_eq!(trial.app.papers[0].text, "The dog sat.\nThe dog ran.\nThe end.");
476        assert!(trial.has(Role::Text, "Not found"));
477        trial.looks_like("tests/looks/editor.png");
478        trial.press(Role::Button, "Done");
479        assert!(!trial.has(Role::TextBox, "Find"));
480
481        // A new paper, by its key; Ctrl+Tab goes from tab to tab.
482        trial.key("Ctrl+N");
483        assert!(trial.has(Role::Tab, "Untitled 2") && trial.app.front == 1);
484        trial.key("Ctrl+Tab");
485        assert_eq!(trial.app.front, 0);
486
487        // Closing a paper with changes asks first: Cancel keeps it, Don't save closes it.
488        trial.key("Ctrl+W");
489        assert!(trial.has(Role::Text, "Save the changes to poem.txt before it is closed?"));
490        trial.press(Role::Button, "Cancel");
491        assert_eq!(trial.app.tabs.len(), 2);
492        trial.key("Ctrl+W");
493        trial.press(Role::Button, "Don't save");
494        assert_eq!((trial.app.tabs.len(), trial.app.tabs[0].name.as_str()), (1, "Untitled 2"));
495        assert_eq!(std::fs::read_to_string(&file).unwrap(), "The cat sat.\nThe cat ran.\nThe end.", "the changes were not saved");
496
497        // Select all, from the menu, takes all of the paper: what is typed then takes its place.
498        trial.click(text);
499        trial.type_text("one two");
500        trial.press(Role::Fold, "Edit");
501        assert!(!trial.find(Role::MenuItem, "Cut").enabled && trial.find(Role::MenuItem, "Undo").enabled, "nothing to cut, something to undo");
502        trial.press(Role::MenuItem, "Select all");
503        trial.type_text("three");
504        assert_eq!(trial.app.papers[0].text, "three");
505        // Cut, paste and undo from the menu reach the paper as its own keys do.
506        trial.key("Ctrl+A");
507        trial.press(Role::Fold, "Edit");
508        trial.press(Role::MenuItem, "Cut");
509        assert_eq!(trial.app.papers[0].text, "");
510        trial.press(Role::Fold, "Edit");
511        trial.press(Role::MenuItem, "Paste");
512        trial.press(Role::Fold, "Edit");
513        trial.press(Role::MenuItem, "Paste");
514        assert_eq!(trial.app.papers[0].text, "threethree");
515        trial.press(Role::Fold, "Edit");
516        trial.press(Role::MenuItem, "Undo");
517        assert_eq!(trial.app.papers[0].text, "three");
518
519        // Quitting with changes asks. The cross on a tab asks as Ctrl+W does.
520        trial.key("Ctrl+Q");
521        assert!(trial.has(Role::Button, "Quit") && !trial.app.quit);
522        trial.key("Escape");
523        trial.key("Ctrl+N");
524        trial.click(text);
525        trial.type_text("more");
526        let tab = trial.find(Role::Tab, "Untitled 3").rect;
527        trial.click(taut::geom::pt(tab.right() - 12.0, tab.y + 14.0));
528        assert!(trial.has(Role::Text, "Save the changes to Untitled 3 before it is closed?"), "{}", trial.dump());
529        trial.press(Role::Button, "Don't save");
530        assert_eq!(trial.app.tabs.len(), 1);
531        _ = std::fs::remove_dir_all(&folder);
532    }
533}