Skip to main content

todo/
todo.rs

1//! A list of things to do: the app the fourth chapter of the book builds, step by step
2//! (`docs/04-a-real-small-app.md`). Tasks are added, ticked, renamed and taken away; the list
3//! shows all of them, those left, or those done; and it is kept in a file between runs,
4//! together with where the window was.
5//!   cargo run -p taut --example todo
6use std::path::PathBuf;
7use taut::{Align, Icon, Key, Mods, Theme, Ui, Window, WindowPlacement};
8
9const PEN: Icon = Icon::line("M3.5 12.5 4 10 10.5 3.5 12.5 5.5 6 12zM9 5l2 2");
10const CROSS: Icon = Icon::line("M4.5 4.5 11.5 11.5M11.5 4.5 4.5 11.5");
11/// Which tasks the list shows.
12const SHOWN: [&str; 3] = ["All", "To do", "Done"];
13
14/// One thing to do.
15struct Task {
16    /// What it is known by, whatever its place in the list.
17    id: u64,
18    text: String,
19    done: bool,
20}
21
22/// Everything the app keeps.
23struct App {
24    tasks: Vec<Task>,
25    /// What is typed into the box for a new task, so far.
26    draft: String,
27    /// Which tasks show: the number of one of `SHOWN`.
28    shown: usize,
29    /// The task being renamed, and its new name so far.
30    renaming: Option<(u64, String)>,
31    /// The number the next new task is known by.
32    next: u64,
33    /// Where the window is, as it last reported.
34    placement: Option<WindowPlacement>,
35    /// The file the list is kept in.
36    file: PathBuf,
37}
38
39fn describe(app: &mut App, ui: &mut Ui) {
40    ui.theme = if ui.system_dark() { Theme::dark() } else { Theme::light() };
41    app.placement = ui.window_placement().or(app.placement);
42    let mut changed = adding(app, ui);
43    showing(app, ui);
44    changed |= list(app, ui);
45    changed |= renaming(app, ui);
46    if changed && app.save().is_err() {
47        ui.notice("The list could not be saved");
48    }
49}
50
51/// The box a new task is typed into, and the button that adds it. Says whether one was added.
52fn adding(app: &mut App, ui: &mut Ui) -> bool {
53    ui.row().pad(12.0).gap(8.0).open();
54    let typed = ui.text_box(&mut app.draft, "Something to do");
55    let add = ui.primary_button("Add").clicked || typed.focused && ui.key(Key::Enter, Mods::NONE);
56    ui.close();
57    // When the keyboard is on nothing (as the app starts), it goes to this box.
58    if ui.focus() == 0 && app.renaming.is_none() {
59        ui.set_focus(typed.id);
60    }
61    if !add || app.draft.trim().is_empty() {
62        return false;
63    }
64    app.tasks.push(Task { id: app.next, text: app.draft.trim().into(), done: false });
65    app.next += 1;
66    app.draft.clear();
67    true
68}
69
70/// Which tasks show, and how many are left to do.
71fn showing(app: &mut App, ui: &mut Ui) {
72    let left = app.tasks.iter().filter(|task| !task.done).count();
73    ui.row().pad((12.0, 0.0)).gap(8.0).open();
74    ui.segmented(&mut app.shown, &SHOWN);
75    ui.spacer();
76    ui.note(&format!("{left} left to do"));
77    ui.close();
78}
79
80/// The tasks that show, each with a tick box and buttons to rename it and to take it away.
81/// Says whether one was ticked or taken away.
82fn list(app: &mut App, ui: &mut Ui) -> bool {
83    let t = ui.theme;
84    let (mut changed, mut gone, mut none) = (false, None, true);
85    ui.column().grow().scroll().pad(12.0).gap(4.0).open();
86    for task in app.tasks.iter_mut().filter(|task| [true, !task.done, task.done][app.shown]) {
87        none = false;
88        ui.row().key(task.id).pad((10.0, 4.0)).gap(4.0).fill(t.panel).radius(6.0).open();
89        changed |= ui.checkbox(&mut task.done, &task.text).changed;
90        ui.spacer();
91        if ui.icon_button(PEN, "Rename").clicked {
92            app.renaming = Some((task.id, task.text.clone()));
93        }
94        if ui.icon_button(CROSS, "Take away").clicked {
95            gone = Some(task.id);
96        }
97        ui.close();
98    }
99    if none {
100        ui.note(["Nothing to do yet.", "Nothing left to do.", "Nothing done yet."][app.shown]);
101    }
102    ui.close();
103    app.tasks.retain(|task| Some(task.id) != gone);
104    changed || gone.is_some()
105}
106
107/// The dialog a task is renamed in, while one is. Says whether a task got a new name.
108fn renaming(app: &mut App, ui: &mut Ui) -> bool {
109    let Some((id, name)) = &mut app.renaming else { return false };
110    let t = ui.theme;
111    let beside = ui.dialog();
112    ui.text("Rename the task", t.font.bold(), t.text);
113    let field = ui.text_box(name, "What is to be done");
114    // (As the dialog opens, the keyboard goes into its box, with the old name selected.)
115    if ui.focus() == 0 {
116        ui.set_focus(field.id);
117        ui.select_all();
118    }
119    ui.row().gap(8.0).align(Align::End, Align::Center).open();
120    let cancel = ui.button("Cancel").clicked || ui.key(Key::Escape, Mods::NONE) || beside.clicked;
121    let keep = ui.primary_button("Rename").clicked || ui.key(Key::Enter, Mods::NONE);
122    ui.close();
123    ui.close();
124    let renamed = keep && !name.trim().is_empty();
125    if let Some(task) = app.tasks.iter_mut().find(|task| task.id == *id).filter(|_| renamed) {
126        task.text = name.trim().into();
127    }
128    if keep || cancel {
129        app.renaming = None;
130    }
131    renamed
132}
133
134impl App {
135    /// The list as it was left in `file`, or an empty one the first time.
136    fn load(file: PathBuf) -> App {
137        let text = std::fs::read_to_string(&file).unwrap_or_default();
138        let mut lines = text.lines();
139        let placement = lines.next().and_then(|line| line.parse().ok());
140        let tasks: Vec<Task> = lines.enumerate().map(|(at, line)| Task { id: at as u64, done: line.starts_with("x "), text: line.get(2..).unwrap_or("").into() }).collect();
141        App { next: tasks.len() as u64, tasks, draft: String::new(), shown: 0, renaming: None, placement, file }
142    }
143
144    /// Writes the list into its file: where the window is on the first line, then a line for
145    /// each task, with `x` before one that is done and `-` before one that is not.
146    fn save(&self) -> std::io::Result<()> {
147        let mut text = self.placement.map_or(String::new(), |placement| placement.to_string());
148        for task in &self.tasks {
149            text += &format!("\n{} {}", if task.done { "x" } else { "-" }, task.text);
150        }
151        std::fs::write(&self.file, text)
152    }
153}
154
155/// When the window closes, the app goes with it, and the list is written once more: now with
156/// where the window was left. (Nobody is left to tell if that fails.)
157impl Drop for App {
158    fn drop(&mut self) {
159        let _ = self.save();
160    }
161}
162
163/// Where the list is kept: in the folder the system keeps the settings of programs in.
164fn file() -> PathBuf {
165    let folder = std::env::var_os("APPDATA").or_else(|| std::env::var_os("XDG_CONFIG_HOME")).map(PathBuf::from);
166    let home = || std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".config"));
167    folder.or_else(home).unwrap_or_default().join("taut-todo.txt")
168}
169
170fn main() {
171    let mut app = App::load(file());
172    let window = Window { title: "To do", width: 400.0, height: 480.0, min_width: 280.0, min_height: 220.0, ..Default::default() };
173    taut::run(window.with_placement(app.placement), move |ui| describe(&mut app, ui));
174}