Skip to main content

book/
book.rs

1//! Draws every picture of the book (the chapters in `docs/`) into a folder, with no window
2//! anywhere: each is a small window described by the code its chapter shows, used the way a
3//! person would use it, and drawn into a `Surface` (with the feature `emoji`, for the emoji in
4//! colour of the sixth chapter).
5//!   cargo run -p taut --features emoji --example book -- docs/pictures [a part of a name: only those pictures]
6//!
7//! Each module below holds, before the line that says "The picture of it", the very code of a
8//! block in the chapter named over it (the book's test holds the two against each other); after
9//! that line, what the person does before the picture is taken.
10#![allow(dead_code)] // the chapters' programs have a `main`, which is never called here
11use std::path::{Path, PathBuf};
12use std::time::Duration;
13use taut::geom::{Point, Size, pt};
14use taut::{Button, Event, Key, LocalClipboard, Mods, Rect, Surface, Ui};
15
16/// One thing the person does before a picture is taken. A thing is found by its name, the
17/// way a screen reader finds it: the words on a button, the hint in an empty text box.
18#[derive(Clone, Copy)]
19enum Step {
20    /// The pointer goes to the thing, and the left button is pressed and let go there.
21    Click(&'static str),
22    /// The left button is pressed and let go at this place, in units.
23    ClickAt(f32, f32),
24    /// The same with the right button.
25    RightClick(&'static str),
26    /// The pointer goes to the thing, and stays there.
27    Hover(&'static str),
28    /// Text is typed into whatever the keyboard is on.
29    Type(&'static str),
30    /// A key is pressed.
31    Press(Key, Mods),
32    /// The wheel is turned over the thing, this far down.
33    Wheel(&'static str, f32),
34}
35
36/// A picture of the book: its name (the file is `<name>.png`), how big the window is in units,
37/// what the person does first, and the window's description.
38struct Shot {
39    name: &'static str,
40    size: [f32; 2],
41    steps: Vec<Step>,
42    describe: Box<dyn FnMut(&mut Ui)>,
43    /// The part of the window the last step had drawn again is marked on the picture.
44    marked: bool,
45    /// How many pixels a unit is.
46    scale: f32,
47    /// The picture is laid over one of a game's, as a texture is.
48    over_a_game: bool,
49}
50
51impl Shot {
52    fn new(name: &'static str, size: [f32; 2], describe: impl FnMut(&mut Ui) + 'static) -> Shot {
53        Shot { name, size, steps: Vec::new(), describe: Box::new(describe), marked: false, scale: 1.0, over_a_game: false }
54    }
55    fn steps(self, steps: &[Step]) -> Shot {
56        Shot { steps: steps.to_vec(), ..self }
57    }
58    fn marked(self) -> Shot {
59        Shot { marked: true, ..self }
60    }
61    fn scale(self, scale: f32) -> Shot {
62        Shot { scale, ..self }
63    }
64    fn over_a_game(self) -> Shot {
65        Shot { over_a_game: true, ..self }
66    }
67}
68
69/// Where the thing called `name` is in the window, as a screen reader is told.
70fn find(ui: &Ui, name: &str) -> Rect {
71    let found = ui.visible_access_nodes().iter().find(|node| node.name == name);
72    found.unwrap_or_else(|| panic!("nothing called {name:?} is in the window")).rect
73}
74
75fn middle(of: Rect) -> Point {
76    pt(of.x + of.w / 2.0, of.y + of.h / 2.0)
77}
78
79/// Takes in one thing that happened, runs the interface, and gives back what it drew again.
80fn happens(ui: &mut Ui, describe: &mut dyn FnMut(&mut Ui), screen: &mut Surface, event: Event) -> Rect {
81    ui.event(event);
82    let changed = ui.run(describe);
83    screen.redraw(ui, changed);
84    changed
85}
86
87/// Does one step, and gives back what the interface drew again for it.
88fn take(ui: &mut Ui, describe: &mut dyn FnMut(&mut Ui), screen: &mut Surface, step: Step) -> Rect {
89    let events = match step {
90        Step::Click(name) => vec![Event::Move(middle(find(ui, name))), Event::Press(Button::Left, Mods::NONE), Event::Release(Button::Left)],
91        Step::ClickAt(x, y) => vec![Event::Move(pt(x, y)), Event::Press(Button::Left, Mods::NONE), Event::Release(Button::Left)],
92        Step::RightClick(name) => vec![Event::Move(middle(find(ui, name))), Event::Press(Button::Right, Mods::NONE), Event::Release(Button::Right)],
93        Step::Hover(name) => vec![Event::Move(middle(find(ui, name)))],
94        Step::Type(text) => vec![Event::Text(text.into())],
95        Step::Press(key, mods) => vec![Event::Key(key, mods)],
96        Step::Wheel(name, down) => vec![Event::Move(middle(find(ui, name))), Event::Wheel(0.0, down)],
97    };
98    let mut changed = Rect::EMPTY;
99    for event in events {
100        changed = changed.union(happens(ui, describe, screen, event));
101    }
102    changed
103}
104
105/// Takes the picture: the window is described, the steps are taken one after another (a
106/// second apart, so that what slides has come to rest), and it is written as a PNG file.
107fn shoot(folder: &Path, mut shot: Shot) {
108    let mut ui = Ui::new(taut::platform::system_text(), Box::new(LocalClipboard::default()));
109    ui.resize(Size { w: shot.size[0], h: shot.size[1] }, shot.scale);
110    ui.set_screen_reader(true);
111    ui.run(&mut shot.describe);
112    ui.run(&mut shot.describe);
113    let mut screen = Surface::draw(&mut ui, 64);
114    let mut changed = Rect::EMPTY;
115    for (at, step) in shot.steps.iter().enumerate() {
116        ui.set_time(Duration::from_secs(at as u64 + 1));
117        changed = take(&mut ui, &mut shot.describe, &mut screen, *step);
118    }
119    ui.set_time(Duration::from_secs(shot.steps.len() as u64 + 2));
120    let rest = ui.run(&mut shot.describe);
121    screen.redraw(&mut ui, rest);
122    if shot.marked {
123        mark(&mut screen, changed.snap_to_pixels(shot.scale));
124    }
125    if shot.over_a_game {
126        lay_over_a_game(&mut screen);
127    }
128    let file = folder.join(format!("{}.png", shot.name));
129    std::fs::write(&file, screen.to_png()).expect("the picture could not be written");
130    println!("{} ({} by {})", file.display(), screen.width, screen.height);
131}
132
133/// Draws a line two pixels thick around `area`, in a red that stands out on either theme.
134fn mark(screen: &mut Surface, area: Rect) {
135    let [left, top] = [area.x.max(0.0) as usize, area.y.max(0.0) as usize];
136    let [right, bottom] = [(area.right() as usize).min(screen.width), (area.bottom() as usize).min(screen.height)];
137    for y in top..bottom {
138        for x in left..right {
139            if x < left + 2 || x + 2 >= right || y < top + 2 || y + 2 >= bottom {
140                screen.pixels[y * screen.width + x] = 0xffe0_3c3c;
141            }
142        }
143    }
144}
145
146/// Lays the picture over one a game might show (a sky, and hills under it), the way a
147/// renderer lays a texture whose colours are multiplied by how solid they are over what it
148/// drew: each colour, plus what is under it as far as the picture lets it through.
149fn lay_over_a_game(screen: &mut Surface) {
150    let (wide, high) = (screen.width as f32, screen.height as f32);
151    for (at, pixel) in screen.pixels.iter_mut().enumerate() {
152        let (x, y) = ((at % screen.width) as f32, (at / screen.width) as f32);
153        let hill = high * 0.62 + (x / wide * 9.0).sin() * high * 0.08 + (x / wide * 23.0).cos() * high * 0.03;
154        let under = if y > hill { [40.0 + y / high * 30.0, 110.0 - y / high * 40.0, 60.0] } else { [90.0 + y / high * 80.0, 150.0 + y / high * 60.0, 225.0] };
155        let let_through = 255 - (*pixel >> 24);
156        let channel = |shift: u32, game: f32| ((*pixel >> shift & 0xff) + (game as u32 * let_through) / 255).min(255) << shift;
157        *pixel = 0xff00_0000 | channel(16, under[0]) | channel(8, under[1]) | channel(0, under[2]);
158    }
159}
160
161fn main() {
162    let folder = PathBuf::from(std::env::args().nth(1).unwrap_or_else(|| "docs/pictures".into()));
163    std::fs::create_dir_all(&folder).expect("the folder could not be made");
164    let wanted = std::env::args().nth(2).unwrap_or_default();
165    let shots = [
166        first_window::shot(),
167        first_window::drawn(),
168        a_row::shot(),
169        a_column::shot(),
170        three_sizes::shot(),
171        sharing::shot(),
172        aligned::shot(),
173        placed::shot(),
174        a_grid::shot(),
175        wrapping::shot(),
176        giving_way::shot(),
177        scrolling::shot(),
178        layered::shot(),
179        chips::shot(),
180        a_list::shot(),
181        a_table::shot(),
182        a_long_list::shot(),
183        a_tree::shot(),
184        menus::shot(),
185        a_dock::shot(),
186        a_chart::shot(),
187        a_panel::shot(),
188        a_palette::shot(),
189        a_notice::shot(),
190        kinds_of_text::shot(),
191        emoji::shot(),
192        pictures::shot(),
193        drawing::shot(),
194        a_scene::shot(),
195        an_overlay::shot(),
196        a_whole_screen::shot(),
197    ];
198    for shot in shots.into_iter().chain(todo::shots()).chain(a_form::shots()).filter(|shot| shot.name.contains(&wanted)) {
199        shoot(&folder, shot);
200    }
201}
202
203// docs/01-a-first-window.md
204mod first_window {
205    use taut::{Ui, Window};
206
207    struct App {
208        count: u32,
209    }
210
211    fn describe(app: &mut App, ui: &mut Ui) {
212        ui.row().pad(16.0).gap(12.0).open();
213        ui.label(&format!("Pressed {} times", app.count));
214        if ui.button("Press me").clicked {
215            app.count += 1;
216        }
217        ui.close();
218    }
219
220    fn main() {
221        let mut app = App { count: 0 };
222        taut::run(Window { title: "A first window", width: 320.0, height: 120.0, ..Default::default() }, move |ui| describe(&mut app, ui));
223    }
224
225    // The picture of it:
226    use super::{Shot, Step::Click};
227    pub(super) fn shot() -> Shot {
228        let mut app = App { count: 0 };
229        Shot::new("01-first-window", [320.0, 120.0], move |ui| describe(&mut app, ui)).steps(&[Click("Press me"), Click("Press me"), Click("Press me")])
230    }
231    pub(super) fn drawn() -> Shot {
232        let mut app = App { count: 0 };
233        Shot::new("01-drawn-again", [320.0, 120.0], move |ui| describe(&mut app, ui)).steps(&[Click("Press me"), Click("Press me"), Click("Press me")]).marked()
234    }
235}
236
237// docs/02-boxes-and-layout.md
238mod a_row {
239    use taut::Ui;
240
241    fn describe(ui: &mut Ui) {
242        ui.row().pad(12.0).gap(8.0).open();
243        ui.button("One");
244        ui.button("Two");
245        ui.button("Three");
246        ui.close();
247    }
248
249    // The picture of it:
250    pub(super) fn shot() -> super::Shot {
251        super::Shot::new("02-a-row", [360.0, 52.0], describe)
252    }
253}
254
255// docs/02-boxes-and-layout.md
256mod a_column {
257    use taut::Ui;
258
259    fn describe(ui: &mut Ui) {
260        ui.column().pad(12.0).gap(8.0).open();
261        ui.button("One");
262        ui.button("Two");
263        ui.button("Three");
264        ui.close();
265    }
266
267    // The picture of it:
268    pub(super) fn shot() -> super::Shot {
269        super::Shot::new("02-a-column", [360.0, 124.0], describe)
270    }
271}
272
273// docs/02-boxes-and-layout.md
274mod three_sizes {
275    use taut::{Length, Ui};
276
277    fn describe(ui: &mut Ui) {
278        let t = ui.theme;
279        ui.row().pad(12.0).gap(8.0).open();
280        ui.el().text("Fit", t.font, t.text).pad(8.0).fill(t.raised).border(t.line_strong, 1.0).show();
281        ui.el().w(Length::Px(120.0)).text("Px(120.0)", t.font, t.text).pad(8.0).fill(t.raised).border(t.line_strong, 1.0).show();
282        ui.el().w(Length::Grow(1.0)).text("Grow(1.0)", t.font, t.text).pad(8.0).fill(t.raised).border(t.line_strong, 1.0).show();
283        ui.close();
284    }
285
286    // The picture of it:
287    pub(super) fn shot() -> super::Shot {
288        super::Shot::new("02-three-sizes", [420.0, 58.0], describe)
289    }
290}
291
292// docs/02-boxes-and-layout.md
293mod sharing {
294    use taut::{Length, Ui};
295
296    fn describe(ui: &mut Ui) {
297        let t = ui.theme;
298        ui.column().pad(12.0).gap(8.0).open();
299        ui.row().gap(8.0).open();
300        ui.el().w(Length::Grow(1.0)).text("Grow(1.0)", t.font, t.text).pad(8.0).fill(t.raised).border(t.line_strong, 1.0).show();
301        ui.el().w(Length::Grow(2.0)).text("Grow(2.0)", t.font, t.text).pad(8.0).fill(t.raised).border(t.line_strong, 1.0).show();
302        ui.close();
303        ui.row().gap(8.0).open();
304        ui.button("Back");
305        ui.spacer();
306        ui.button("Cancel");
307        ui.primary_button("Save");
308        ui.close();
309        ui.close();
310    }
311
312    // The picture of it:
313    pub(super) fn shot() -> super::Shot {
314        super::Shot::new("02-sharing", [420.0, 102.0], describe)
315    }
316}
317
318// docs/02-boxes-and-layout.md
319mod aligned {
320    use taut::{Align, Length, Ui};
321
322    fn describe(ui: &mut Ui) {
323        let t = ui.theme;
324        ui.column().pad(12.0).gap(8.0).open();
325        for (name, along) in [("Start", Align::Start), ("Center", Align::Center), ("End", Align::End), ("Spread", Align::Spread)] {
326            ui.row().h(Length::Px(40.0)).pad(4.0).gap(4.0).align(along, Align::Center).fill(t.panel).border(t.line, 1.0).open();
327            ui.button(name);
328            ui.button("and");
329            ui.button("more");
330            ui.close();
331        }
332        ui.close();
333    }
334
335    // The picture of it:
336    pub(super) fn shot() -> super::Shot {
337        super::Shot::new("02-aligned", [420.0, 216.0], describe)
338    }
339}
340
341// docs/02-boxes-and-layout.md
342mod placed {
343    use taut::{Align, Length, Ui};
344
345    fn describe(ui: &mut Ui) {
346        let t = ui.theme;
347        ui.column().pad(12.0).gap(8.0).open();
348        ui.button("Stretched across, as a column has its boxes");
349        ui.el().place(Align::End).text("At the end", t.font, t.text).pad(8.0).fill(t.raised).border(t.line_strong, 1.0).show();
350        ui.row().h(Length::Px(56.0)).gap(8.0).fill(t.panel).border(t.line, 1.0).open();
351        ui.button("In the middle of the height");
352        ui.el().place(Align::Start).text("At the top", t.font, t.text).pad(8.0).fill(t.raised).border(t.line_strong, 1.0).show();
353        ui.close();
354        ui.close();
355    }
356
357    // The picture of it:
358    pub(super) fn shot() -> super::Shot {
359        super::Shot::new("02-placed", [420.0, 160.0], describe)
360    }
361}
362
363// docs/02-boxes-and-layout.md
364mod a_grid {
365    use taut::{Align, Ui};
366
367    struct Form {
368        name: String,
369        place: String,
370        rows: usize,
371    }
372
373    fn describe(form: &mut Form, ui: &mut Ui) {
374        ui.grid(2).pad(12.0).gap(8.0).align(Align::Start, Align::Center).open();
375        ui.label("Name");
376        ui.text_box(&mut form.name, "Your name");
377        ui.label("Where it is kept");
378        ui.text_box(&mut form.place, "A folder");
379        ui.label("Rows");
380        ui.select(&mut form.rows, &["Roomy", "Tight"]);
381        ui.close();
382    }
383
384    // The picture of it:
385    pub(super) fn shot() -> super::Shot {
386        let mut form = Form { name: "Ada".into(), place: String::new(), rows: 0 };
387        super::Shot::new("02-a-grid", [420.0, 132.0], move |ui| describe(&mut form, ui))
388    }
389}
390
391// docs/02-boxes-and-layout.md
392mod wrapping {
393    use taut::Ui;
394
395    fn describe(ui: &mut Ui) {
396        let t = ui.theme;
397        ui.wrapping_row().pad(12.0).gap(6.0).open();
398        for tag in ["layout", "drawing", "text", "tables", "menus", "docks", "scenes", "screen readers", "fonts", "pictures"] {
399            ui.el().text(tag, t.small_font, t.text_dim).pad((8.0, 3.0)).fill(t.raised).border(t.line, 1.0).radius(10.0).show();
400        }
401        ui.close();
402    }
403
404    // The picture of it:
405    pub(super) fn shot() -> super::Shot {
406        super::Shot::new("02-wrapping", [300.0, 100.0], describe)
407    }
408}
409
410// docs/02-boxes-and-layout.md
411mod giving_way {
412    use taut::{Length, Ui};
413
414    fn file(ui: &mut Ui, name: &str, folder: &str) {
415        let t = ui.theme;
416        ui.row().gap(8.0).pad((10.0, 6.0)).fill(t.panel).radius(6.0).open();
417        ui.el().text(name, t.font, t.text).shrink(1).show();
418        ui.el().text(folder, t.small_font, t.text_dim).shrink(2).show();
419        ui.spacer();
420        ui.button("Open");
421        ui.close();
422    }
423
424    fn describe(ui: &mut Ui) {
425        ui.column().pad(12.0).gap(8.0).open();
426        for width in [420.0, 300.0, 200.0] {
427            ui.column().w(Length::Px(width)).open();
428            file(ui, "a report with a long name.txt", "D:\\Work\\Reports\\2026\\November");
429            ui.close();
430        }
431        ui.close();
432    }
433
434    // The picture of it:
435    pub(super) fn shot() -> super::Shot {
436        super::Shot::new("02-giving-way", [444.0, 148.0], describe)
437    }
438}
439
440// docs/02-boxes-and-layout.md
441mod scrolling {
442    use taut::{Length, Ui};
443
444    fn describe(ui: &mut Ui) {
445        let t = ui.theme;
446        ui.column().h(Length::Px(160.0)).scroll().pad(12.0).gap(4.0).open();
447        ui.el().text("Kept at the top", t.font.bold(), t.text).pad((0.0, 4.0)).fill(t.bg).frozen().show();
448        for row in 1..=30 {
449            ui.row().pad((10.0, 6.0)).fill(t.panel).radius(4.0).open();
450            ui.label(&format!("Row {row}"));
451            ui.close();
452        }
453        ui.close();
454    }
455
456    // The picture of it:
457    use super::Step::Wheel;
458    pub(super) fn shot() -> super::Shot {
459        super::Shot::new("02-scrolling", [300.0, 160.0], describe).steps(&[Wheel("Row 2", 130.0)])
460    }
461}
462
463// docs/02-boxes-and-layout.md
464mod layered {
465    use taut::{Align, Flow, Length, Ui};
466
467    fn describe(ui: &mut Ui) {
468        let t = ui.theme;
469        ui.row().pad(16.0).open();
470        ui.el().flow(Flow::Stack).size(220.0, 90.0).open();
471        ui.column().grow().pad(12.0).gap(4.0).fill(t.panel).border(t.line, 1.0).radius(8.0).open();
472        ui.text("Inbox", t.font.bold(), t.text);
473        ui.note("Everything that came today");
474        ui.close();
475        ui.el().place((Align::End, Align::Start)).offset(6.0, -6.0).text("12", t.small_font, t.on_accent).pad((7.0, 2.0)).fill(t.red).radius(9.0).show();
476        ui.el().place(Align::End).h(Length::Px(4.0)).w(Length::Px(60.0)).offset(-12.0, -12.0).fill(t.accent).radius(2.0).show();
477        ui.close();
478        ui.close();
479    }
480
481    // The picture of it:
482    pub(super) fn shot() -> super::Shot {
483        super::Shot::new("02-layered", [300.0, 130.0], describe)
484    }
485}
486
487// docs/03-parts-and-state.md
488mod chips {
489    use taut::{Cursor, Response, Role, Ui};
490
491    /// A small rounded word that is on or off: a tag to pick.
492    fn chip(ui: &mut Ui, on: &mut bool, name: &str) -> Response {
493        let t = ui.theme;
494        let mut state = ui.press(ui.next_id());
495        if state.clicked {
496            (*on, state.changed) = (!*on, true);
497        }
498        if state.hovered {
499            ui.set_cursor(Cursor::Hand);
500        }
501        let (fill, ink) = match (*on, state.hovered) {
502            (true, _) => (t.accent, t.on_accent),
503            (false, true) => (t.hover, t.text),
504            (false, false) => (t.raised, t.text_dim),
505        };
506        ui.el().text(name, t.font, ink).pad((12.0, 5.0)).fill(fill).border(t.line, 1.0).radius(14.0).sense().focusable().show();
507        ui.tell(&state, Role::CheckBox, Some(*on), "");
508        state
509    }
510
511    struct Shopping {
512        wanted: [bool; 6],
513    }
514
515    fn describe(shopping: &mut Shopping, ui: &mut Ui) {
516        ui.wrapping_row().pad(12.0).gap(6.0).open();
517        for (on, name) in shopping.wanted.iter_mut().zip(["Fruit", "Bread", "Cheese", "Tea", "Rice", "Soap"]) {
518            chip(ui, on, name);
519        }
520        ui.close();
521    }
522
523    // The picture of it:
524    use super::Step::{Click, Hover};
525    pub(super) fn shot() -> super::Shot {
526        let mut shopping = Shopping { wanted: [false; 6] };
527        super::Shot::new("03-chips", [360.0, 92.0], move |ui| describe(&mut shopping, ui)).steps(&[Click("Bread"), Click("Tea"), Hover("Rice")])
528    }
529}
530
531// docs/04-a-real-small-app.md
532mod a_list {
533    use taut::{Ui, Window};
534
535    struct Task {
536        text: String,
537        done: bool,
538    }
539
540    fn list(tasks: &mut [Task], ui: &mut Ui) {
541        let t = ui.theme;
542        ui.column().grow().scroll().pad(12.0).gap(4.0).open();
543        for task in tasks.iter_mut() {
544            ui.row().pad((10.0, 4.0)).fill(t.panel).radius(6.0).open();
545            ui.checkbox(&mut task.done, &task.text);
546            ui.close();
547        }
548        ui.close();
549    }
550
551    fn main() {
552        let task = |text: &str, done| Task { text: text.into(), done };
553        let mut tasks = vec![task("Buy bread", true), task("Write to Ada", false), task("Fix the gate", false)];
554        taut::run(Window { title: "To do", width: 400.0, height: 200.0, ..Default::default() }, move |ui| list(&mut tasks, ui));
555    }
556
557    // The picture of it:
558    pub(super) fn shot() -> super::Shot {
559        let task = |text: &str, done| Task { text: text.into(), done };
560        let mut tasks = vec![task("Buy bread", true), task("Write to Ada", false), task("Fix the gate", false)];
561        super::Shot::new("04-a-list", [400.0, 200.0], move |ui| list(&mut tasks, ui))
562    }
563}
564
565// docs/04-a-real-small-app.md
566mod todo {
567    //! A list of things to do: the app the fourth chapter of the book builds, step by step
568    //! (`docs/04-a-real-small-app.md`). Tasks are added, ticked, renamed and taken away; the list
569    //! shows all of them, those left, or those done; and it is kept in a file between runs,
570    //! together with where the window was.
571    //!   cargo run -p taut --example todo
572    use std::path::PathBuf;
573    use taut::{Align, Icon, Key, Mods, Theme, Ui, Window, WindowPlacement};
574
575    const PEN: Icon = Icon::line("M3.5 12.5 4 10 10.5 3.5 12.5 5.5 6 12zM9 5l2 2");
576    const CROSS: Icon = Icon::line("M4.5 4.5 11.5 11.5M11.5 4.5 4.5 11.5");
577    /// Which tasks the list shows.
578    const SHOWN: [&str; 3] = ["All", "To do", "Done"];
579
580    /// One thing to do.
581    struct Task {
582        /// What it is known by, whatever its place in the list.
583        id: u64,
584        text: String,
585        done: bool,
586    }
587
588    /// Everything the app keeps.
589    struct App {
590        tasks: Vec<Task>,
591        /// What is typed into the box for a new task, so far.
592        draft: String,
593        /// Which tasks show: the number of one of `SHOWN`.
594        shown: usize,
595        /// The task being renamed, and its new name so far.
596        renaming: Option<(u64, String)>,
597        /// The number the next new task is known by.
598        next: u64,
599        /// Where the window is, as it last reported.
600        placement: Option<WindowPlacement>,
601        /// The file the list is kept in.
602        file: PathBuf,
603    }
604
605    fn describe(app: &mut App, ui: &mut Ui) {
606        ui.theme = if ui.system_dark() { Theme::dark() } else { Theme::light() };
607        app.placement = ui.window_placement().or(app.placement);
608        let mut changed = adding(app, ui);
609        showing(app, ui);
610        changed |= list(app, ui);
611        changed |= renaming(app, ui);
612        if changed && app.save().is_err() {
613            ui.notice("The list could not be saved");
614        }
615    }
616
617    /// The box a new task is typed into, and the button that adds it. Says whether one was added.
618    fn adding(app: &mut App, ui: &mut Ui) -> bool {
619        ui.row().pad(12.0).gap(8.0).open();
620        let typed = ui.text_box(&mut app.draft, "Something to do");
621        let add = ui.primary_button("Add").clicked || typed.focused && ui.key(Key::Enter, Mods::NONE);
622        ui.close();
623        // When the keyboard is on nothing (as the app starts), it goes to this box.
624        if ui.focus() == 0 && app.renaming.is_none() {
625            ui.set_focus(typed.id);
626        }
627        if !add || app.draft.trim().is_empty() {
628            return false;
629        }
630        app.tasks.push(Task { id: app.next, text: app.draft.trim().into(), done: false });
631        app.next += 1;
632        app.draft.clear();
633        true
634    }
635
636    /// Which tasks show, and how many are left to do.
637    fn showing(app: &mut App, ui: &mut Ui) {
638        let left = app.tasks.iter().filter(|task| !task.done).count();
639        ui.row().pad((12.0, 0.0)).gap(8.0).open();
640        ui.segmented(&mut app.shown, &SHOWN);
641        ui.spacer();
642        ui.note(&format!("{left} left to do"));
643        ui.close();
644    }
645
646    /// The tasks that show, each with a tick box and buttons to rename it and to take it away.
647    /// Says whether one was ticked or taken away.
648    fn list(app: &mut App, ui: &mut Ui) -> bool {
649        let t = ui.theme;
650        let (mut changed, mut gone, mut none) = (false, None, true);
651        ui.column().grow().scroll().pad(12.0).gap(4.0).open();
652        for task in app.tasks.iter_mut().filter(|task| [true, !task.done, task.done][app.shown]) {
653            none = false;
654            ui.row().key(task.id).pad((10.0, 4.0)).gap(4.0).fill(t.panel).radius(6.0).open();
655            changed |= ui.checkbox(&mut task.done, &task.text).changed;
656            ui.spacer();
657            if ui.icon_button(PEN, "Rename").clicked {
658                app.renaming = Some((task.id, task.text.clone()));
659            }
660            if ui.icon_button(CROSS, "Take away").clicked {
661                gone = Some(task.id);
662            }
663            ui.close();
664        }
665        if none {
666            ui.note(["Nothing to do yet.", "Nothing left to do.", "Nothing done yet."][app.shown]);
667        }
668        ui.close();
669        app.tasks.retain(|task| Some(task.id) != gone);
670        changed || gone.is_some()
671    }
672
673    /// The dialog a task is renamed in, while one is. Says whether a task got a new name.
674    fn renaming(app: &mut App, ui: &mut Ui) -> bool {
675        let Some((id, name)) = &mut app.renaming else { return false };
676        let t = ui.theme;
677        let beside = ui.dialog();
678        ui.text("Rename the task", t.font.bold(), t.text);
679        let field = ui.text_box(name, "What is to be done");
680        // (As the dialog opens, the keyboard goes into its box, with the old name selected.)
681        if ui.focus() == 0 {
682            ui.set_focus(field.id);
683            ui.select_all();
684        }
685        ui.row().gap(8.0).align(Align::End, Align::Center).open();
686        let cancel = ui.button("Cancel").clicked || ui.key(Key::Escape, Mods::NONE) || beside.clicked;
687        let keep = ui.primary_button("Rename").clicked || ui.key(Key::Enter, Mods::NONE);
688        ui.close();
689        ui.close();
690        let renamed = keep && !name.trim().is_empty();
691        if let Some(task) = app.tasks.iter_mut().find(|task| task.id == *id).filter(|_| renamed) {
692            task.text = name.trim().into();
693        }
694        if keep || cancel {
695            app.renaming = None;
696        }
697        renamed
698    }
699
700    impl App {
701        /// The list as it was left in `file`, or an empty one the first time.
702        fn load(file: PathBuf) -> App {
703            let text = std::fs::read_to_string(&file).unwrap_or_default();
704            let mut lines = text.lines();
705            let placement = lines.next().and_then(|line| line.parse().ok());
706            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();
707            App { next: tasks.len() as u64, tasks, draft: String::new(), shown: 0, renaming: None, placement, file }
708        }
709
710        /// Writes the list into its file: where the window is on the first line, then a line for
711        /// each task, with `x` before one that is done and `-` before one that is not.
712        fn save(&self) -> std::io::Result<()> {
713            let mut text = self.placement.map_or(String::new(), |placement| placement.to_string());
714            for task in &self.tasks {
715                text += &format!("\n{} {}", if task.done { "x" } else { "-" }, task.text);
716            }
717            std::fs::write(&self.file, text)
718        }
719    }
720
721    /// When the window closes, the app goes with it, and the list is written once more: now with
722    /// where the window was left. (Nobody is left to tell if that fails.)
723    impl Drop for App {
724        fn drop(&mut self) {
725            let _ = self.save();
726        }
727    }
728
729    /// Where the list is kept: in the folder the system keeps the settings of programs in.
730    fn file() -> PathBuf {
731        let folder = std::env::var_os("APPDATA").or_else(|| std::env::var_os("XDG_CONFIG_HOME")).map(PathBuf::from);
732        let home = || std::env::var_os("HOME").map(|home| PathBuf::from(home).join(".config"));
733        folder.or_else(home).unwrap_or_default().join("taut-todo.txt")
734    }
735
736    fn main() {
737        let mut app = App::load(file());
738        let window = Window { title: "To do", width: 400.0, height: 480.0, min_width: 280.0, min_height: 220.0, ..Default::default() };
739        taut::run(window.with_placement(app.placement), move |ui| describe(&mut app, ui));
740    }
741
742    // The picture of it:
743    use super::Step::{Click, Type};
744
745    /// The app with a few tasks in it, kept in a file of the book's own.
746    fn sample() -> App {
747        let tasks = [("Buy bread", true), ("Write to Ada", false), ("Fix the gate", false), ("Book the train", true), ("Plan the garden", false)];
748        let tasks = tasks.iter().enumerate().map(|(id, (text, done))| Task { id: id as u64, text: text.to_string(), done: *done }).collect();
749        App { tasks, draft: String::new(), shown: 0, renaming: None, next: 5, placement: None, file: std::env::temp_dir().join("taut-book-todo.txt") }
750    }
751
752    pub(super) fn shots() -> Vec<super::Shot> {
753        let (mut first, mut second, mut third) = (sample(), sample(), sample());
754        vec![
755            super::Shot::new("04-the-app", [400.0, 480.0], move |ui| describe(&mut first, ui)).steps(&[Type("Water the plants")]),
756            super::Shot::new("04-to-do", [400.0, 480.0], move |ui| describe(&mut second, ui)).steps(&[Click("To do")]),
757            super::Shot::new("04-renaming", [400.0, 480.0], move |ui| (ui.set_preferences(taut::Preferences { dark: true, ..Default::default() }), describe(&mut third, ui)).1)
758                .steps(&[Click("Rename")]),
759        ]
760    }
761}
762
763// docs/05-larger-parts.md
764mod a_table {
765    use std::cmp::Ordering;
766    use taut::{Align, Column, Selection, Table, Ui};
767
768    const COLUMNS: [Column; 3] = [Column::new("Name"), Column::new("Size").px(90.0).align(Align::End), Column::new("Kind").px(80.0)];
769
770    struct File {
771        name: String,
772        size: u64,
773        kind: &'static str,
774    }
775
776    struct App {
777        files: Vec<File>,
778        table: Table,
779        selection: Selection,
780    }
781
782    fn describe(app: &mut App, ui: &mut Ui) {
783        if ui.table(&mut app.table, &COLUMNS).changed {
784            let by = app.table.sort.clone();
785            app.files.sort_by(|a, b| order(a, b, &by));
786            app.selection.clear();
787        }
788        for row in ui.rows(app.files.len(), 24.0) {
789            if ui.selectable_row(row, app.selection.contains(row)).clicked {
790                app.selection.click(row, ui.mods());
791            }
792            let file = &app.files[row];
793            ui.label(&file.name);
794            ui.label(&format!("{} KB", file.size));
795            ui.label(file.kind);
796            ui.close();
797        }
798        ui.close();
799        ui.close();
800    }
801
802    /// How two files compare in the order the headings ask for: by the column that counts
803    /// most, and where that is the same, by the next.
804    fn order(a: &File, b: &File, by: &[(usize, bool)]) -> Ordering {
805        for &(column, large_first) in by {
806            let (a, b) = if large_first { (b, a) } else { (a, b) };
807            let order = match column {
808                0 => a.name.cmp(&b.name),
809                1 => a.size.cmp(&b.size),
810                _ => a.kind.cmp(b.kind),
811            };
812            if order.is_ne() {
813                return order;
814            }
815        }
816        Ordering::Equal
817    }
818
819    // The picture of it:
820    use super::Step::{Click, ClickAt};
821    pub(super) fn shot() -> super::Shot {
822        let kinds = ["text", "picture", "sound", "folder"];
823        let files = (0..500u64).map(|n| File { name: format!("file {n:03}"), size: n * 7919 % 4096 + 1, kind: kinds[n as usize * 5 % 4] }).collect();
824        let mut app = App { files, table: Table::default(), selection: Selection::default() };
825        super::Shot::new("05-a-table", [420.0, 220.0], move |ui| describe(&mut app, ui)).steps(&[Click("Size"), Click("Size"), ClickAt(200.0, 116.0)])
826    }
827}
828
829// docs/05-larger-parts.md
830mod a_long_list {
831    use taut::Ui;
832
833    fn describe(ui: &mut Ui) {
834        for row in ui.list(100_000, 24.0) {
835            ui.row().pad((12.0, 0.0)).open();
836            ui.label(&format!("Row {} of 100000", row + 1));
837            ui.close();
838        }
839        ui.close();
840    }
841
842    // The picture of it:
843    use taut::{Key, Mods};
844    pub(super) fn shot() -> super::Shot {
845        super::Shot::new("05-a-long-list", [300.0, 130.0], describe).steps(&[super::Step::Press(Key::End, Mods::NONE)])
846    }
847}
848
849// docs/05-larger-parts.md
850mod a_tree {
851    use taut::{Length, Ui};
852
853    struct Folders {
854        open: [bool; 3],
855        selected: usize,
856    }
857
858    fn describe(app: &mut Folders, ui: &mut Ui) {
859        ui.column().w(Length::Px(260.0)).pad(12.0).gap(2.0).open();
860        ui.tree(&mut app.open[0], "Pictures");
861        if app.open[0] {
862            ui.tree(&mut app.open[1], "Holidays");
863            if app.open[1] {
864                leaf(app, ui, 0, "Beach.jpg");
865                leaf(app, ui, 1, "Hills.jpg");
866                ui.close();
867            }
868            ui.tree(&mut app.open[2], "Family");
869            if app.open[2] {
870                leaf(app, ui, 2, "Ada.png");
871                ui.close();
872            }
873            leaf(app, ui, 3, "Cat.png");
874            ui.close();
875        }
876        ui.close();
877    }
878
879    fn leaf(app: &mut Folders, ui: &mut Ui, number: usize, name: &str) {
880        if ui.selectable(app.selected == number, name).clicked {
881            app.selected = number;
882        }
883    }
884
885    // The picture of it:
886    pub(super) fn shot() -> super::Shot {
887        let mut app = Folders { open: [true, true, false], selected: 1 };
888        super::Shot::new("05-a-tree", [300.0, 210.0], move |ui| describe(&mut app, ui))
889    }
890}
891
892// docs/05-larger-parts.md
893mod menus {
894    use taut::Ui;
895
896    struct Editor {
897        wrap: bool,
898        status: String,
899    }
900
901    fn describe(app: &mut Editor, ui: &mut Ui) {
902        ui.menu_bar();
903        if ui.menu_button("File") {
904            if ui.menu_item("New\tCtrl+N").clicked {
905                app.status = "A new file".into();
906            }
907            if ui.submenu("Open again") {
908                for name in ["notes.txt", "plan.md"] {
909                    if ui.menu_item(name).clicked {
910                        app.status = format!("Opened {name}");
911                    }
912                }
913                ui.close();
914            }
915            ui.separator();
916            ui.menu_checkbox(&mut app.wrap, "Wrap long lines");
917            ui.separator();
918            if ui.menu_item("Quit\tCtrl+Q").clicked {
919                ui.quit();
920            }
921            ui.close();
922        }
923        if ui.menu_button("Help") {
924            ui.menu_item("About");
925            ui.close();
926        }
927        ui.close();
928        // The keys the menu shows are the app's to ask for.
929        if ui.keys("Ctrl+N") {
930            app.status = "A new file".into();
931        }
932        if ui.keys("Ctrl+Q") {
933            ui.quit();
934        }
935        ui.column().pad(12.0).open();
936        ui.label(&app.status);
937        ui.close();
938    }
939
940    // The picture of it:
941    use super::Step::{Click, Hover};
942    pub(super) fn shot() -> super::Shot {
943        let mut app = Editor { wrap: true, status: "Nothing yet".into() };
944        super::Shot::new("05-menus", [420.0, 220.0], move |ui| describe(&mut app, ui)).steps(&[Click("File"), Hover("Open again")])
945    }
946}
947
948// docs/05-larger-parts.md
949mod a_dock {
950    use taut::{Dock, Ui};
951
952    /// How the panels lie the first time: the files at the left, a quarter of the width; the
953    /// editor and the notes behind tabs, over the log.
954    fn first() -> Dock {
955        Dock::of(&["Files"]).beside(Dock::of(&["Editor", "Notes"]).above(Dock::of(&["Log"]), 0.7), 0.25)
956    }
957
958    fn describe(dock: &mut Dock, ui: &mut Ui) {
959        ui.dock(dock);
960        for name in ["Files", "Editor", "Notes", "Log"] {
961            if ui.docked(dock, name) {
962                ui.paragraph(&format!("What the {name} panel shows"));
963                ui.close();
964            }
965        }
966        ui.close();
967    }
968
969    // The picture of it:
970    pub(super) fn shot() -> super::Shot {
971        let mut dock = first();
972        super::Shot::new("05-a-dock", [560.0, 300.0], move |ui| describe(&mut dock, ui))
973    }
974}
975
976// docs/05-larger-parts.md
977mod a_chart {
978    use taut::{Chart, Series, Ui};
979
980    fn describe(ui: &mut Ui) {
981        let t = ui.theme;
982        let sold = [12.0, 18.0, 9.0, 22.0, 30.0, 26.0, 14.0];
983        let back = [2.0, 3.0, 1.0, 4.0, 6.0, 3.0, 2.0];
984        let rows = [Series::bars("Sold", &sold), Series::line("Brought back", &back).color(t.red)];
985        let days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"];
986        ui.column().pad(12.0).open();
987        ui.chart(&Chart::of(&rows).categories(&days), 420.0, 200.0);
988        ui.close();
989    }
990
991    // The picture of it:
992    use super::Step::Hover;
993    pub(super) fn shot() -> super::Shot {
994        super::Shot::new("05-a-chart", [444.0, 224.0], describe).steps(&[Hover("Sold, Brought back")])
995    }
996}
997
998// docs/05-larger-parts.md
999mod a_panel {
1000    use taut::{Panel, Ui};
1001
1002    struct App {
1003        tools: Panel,
1004        size: f32,
1005        grid: bool,
1006    }
1007
1008    fn describe(app: &mut App, ui: &mut Ui) {
1009        ui.column().grow().pad(12.0).open();
1010        ui.paragraph("The page, under the panel. The panel is moved by its title, stretched by its edges and corners, folded by its arrow and closed by its cross.");
1011        ui.close();
1012        if ui.panel(&mut app.tools, "Tools") {
1013            ui.label("Brush size");
1014            ui.slider(&mut app.size, 1.0..=10.0);
1015            ui.checkbox(&mut app.grid, "Show the grid");
1016            ui.close();
1017        }
1018    }
1019
1020    // The picture of it:
1021    pub(super) fn shot() -> super::Shot {
1022        let mut app = App { tools: Panel::new(150.0, 70.0, 240.0, 150.0), size: 4.0, grid: true };
1023        super::Shot::new("05-a-panel", [420.0, 240.0], move |ui| describe(&mut app, ui))
1024    }
1025}
1026
1027// docs/05-larger-parts.md
1028mod a_palette {
1029    use taut::Ui;
1030
1031    const COMMANDS: [&str; 6] = ["New file\tCtrl+N", "Open a file\tCtrl+O", "Save\tCtrl+S", "Save as\u{2026}", "Search the files\tCtrl+Shift+F", "Settings"];
1032
1033    struct App {
1034        finding: bool,
1035        status: String,
1036    }
1037
1038    fn describe(app: &mut App, ui: &mut Ui) {
1039        app.finding |= ui.keys("Ctrl+K");
1040        if let Some(command) = ui.command_palette(&mut app.finding, &COMMANDS) {
1041            app.status = format!("Picked: {}", COMMANDS[command].split('\t').next().unwrap_or(""));
1042        }
1043        ui.column().pad(12.0).open();
1044        ui.label(&app.status);
1045        ui.close();
1046    }
1047
1048    // The picture of it:
1049    use super::Step::Type;
1050    pub(super) fn shot() -> super::Shot {
1051        let mut app = App { finding: true, status: "Ctrl+K finds a command".into() };
1052        super::Shot::new("05-a-palette", [460.0, 260.0], move |ui| describe(&mut app, ui)).steps(&[Type("sa")])
1053    }
1054}
1055
1056// docs/05-larger-parts.md
1057mod a_notice {
1058    use taut::Ui;
1059
1060    fn describe(ui: &mut Ui) {
1061        ui.row().pad(12.0).open();
1062        if ui.button("Save").clicked {
1063            ui.notice("Saved");
1064        }
1065        ui.close();
1066    }
1067
1068    // The picture of it:
1069    use super::Step::Click;
1070    pub(super) fn shot() -> super::Shot {
1071        super::Shot::new("05-a-notice", [320.0, 130.0], describe).steps(&[Click("Save")])
1072    }
1073}
1074
1075// docs/06-text-and-pictures.md
1076mod kinds_of_text {
1077    use taut::{Font, Length, Ui};
1078
1079    fn describe(ui: &mut Ui) {
1080        let t = ui.theme;
1081        ui.column().pad(12.0).gap(6.0).open();
1082        ui.label("A label: one line, in the theme's font and colour");
1083        ui.note("A note: smaller and quieter");
1084        ui.text("Bold, in the colour that stands out", t.font.bold(), t.accent);
1085        ui.text("Letters of one width, for code: let x = 1;", t.font.mono(), t.text);
1086        ui.text("Struck through: no longer so", t.font.strikethrough(), t.text_dim);
1087        ui.text("Larger", Font::new(20.0), t.text);
1088        ui.paragraph("A paragraph breaks into as many lines as the width it is given needs, between its words.");
1089        ui.el().w(Length::Px(220.0)).clip().text("Text that is too long for its box ends in dots", t.font, t.text).show();
1090        ui.wrapping_row().open();
1091        ui.words("Words of ", t.font, t.text);
1092        ui.words("several kinds", t.font.bold(), t.text);
1093        ui.words(" in one paragraph, with a ", t.font, t.text);
1094        ui.link("link");
1095        ui.words(" among them.", t.font, t.text);
1096        ui.close();
1097        ui.close();
1098    }
1099
1100    // The picture of it:
1101    pub(super) fn shot() -> super::Shot {
1102        super::Shot::new("06-kinds-of-text", [420.0, 270.0], describe)
1103    }
1104}
1105
1106// docs/06-text-and-pictures.md
1107mod emoji {
1108    use taut::Ui;
1109
1110    fn describe(note: &mut String, ui: &mut Ui) {
1111        ui.column().pad(12.0).gap(8.0).open();
1112        ui.label("In colour, at the size of the letters: 🙂 👍🏽 👩‍🚀 ❤️ 🇳🇴");
1113        ui.button("🎉 Done");
1114        ui.text_box(note, "Typed into a box, too");
1115        ui.close();
1116    }
1117
1118    // The picture of it:
1119    pub(super) fn shot() -> super::Shot {
1120        let mut note = "Pizza 🍕 on Friday".to_string();
1121        super::Shot::new("06-emoji", [420.0, 124.0], move |ui| describe(&mut note, ui))
1122    }
1123}
1124
1125// docs/06-text-and-pictures.md
1126mod pictures {
1127    use taut::{Drawing, Picture, Ui};
1128
1129    /// A sun, as an SVG file says it: its rays take the colour they are shown in.
1130    const SUN: &str = r##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
1131      <circle cx="12" cy="12" r="5" fill="#f5b400"/>
1132      <path d="M12 1.5v3M12 19.5v3M1.5 12h3M19.5 12h3M4.6 4.6l2.1 2.1M17.3 17.3l2.1 2.1M4.6 19.4l2.1-2.1M17.3 6.7l2.1-2.1"
1133        stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
1134    </svg>"##;
1135
1136    struct App {
1137        pixels: Option<Picture>,
1138        sun: Option<Drawing>,
1139    }
1140
1141    fn describe(app: &mut App, ui: &mut Ui) {
1142        let t = ui.theme;
1143        // Handed over once, kept by the library from then on.
1144        if app.pixels.is_none() {
1145            // Sixteen by sixteen pixels: red grows to the right, green downwards.
1146            let pixels = (0..256u32).map(|i| 0xff00_0080 | (i % 16 * 17) << 16 | (i / 16 * 17) << 8).collect();
1147            app.pixels = Some(ui.add_picture(16, pixels));
1148            app.sun = ui.add_drawing(SUN);
1149        }
1150        ui.row().pad(12.0).gap(16.0).open();
1151        if let Some(pixels) = app.pixels {
1152            ui.picture(pixels);
1153            ui.el().picture(pixels).size(96.0, 96.0).show();
1154        }
1155        if let Some(sun) = app.sun {
1156            ui.el().drawing(sun, t.text).size(24.0, 24.0).show();
1157            ui.el().drawing(sun, t.accent).size(96.0, 96.0).show();
1158        }
1159        ui.close();
1160    }
1161
1162    // The picture of it:
1163    pub(super) fn shot() -> super::Shot {
1164        let mut app = App { pixels: None, sun: None };
1165        super::Shot::new("06-pictures", [300.0, 120.0], move |ui| describe(&mut app, ui))
1166    }
1167}
1168
1169// docs/06-text-and-pictures.md
1170mod drawing {
1171    use taut::{Flow, Icon, Path, Ui};
1172
1173    const STAR: Icon = Icon::line("M8 1.8 9.4 6.6 14.2 8 9.4 9.4 8 14.2 6.6 9.4 1.8 8 6.6 6.6z");
1174
1175    fn describe(ui: &mut Ui) {
1176        let t = ui.theme;
1177        // A wave, as a line and as the area under it.
1178        let (wide, high) = (300.0, 90.0);
1179        let (mut line, mut area) = (Path::new(), Path::new());
1180        area.move_to(0.0, high);
1181        for step in 0..=60 {
1182            let (x, y) = (step as f32 * wide / 60.0, high / 2.0 - (step as f32 / 6.0).sin() * 28.0);
1183            area.line_to(x, y);
1184            match step {
1185                0 => line.move_to(x, y),
1186                _ => line.line_to(x, y),
1187            };
1188        }
1189        area.line_to(wide, high).close();
1190        ui.column().pad(12.0).gap(12.0).open();
1191        ui.el().flow(Flow::Stack).size(wide, high).fill(t.panel).radius(6.0).clip().open();
1192        ui.el().size(wide, high).shape(&area, t.accent.with_alpha(0.25)).show();
1193        ui.el().size(wide, high).outline(&line, 2.0, t.accent).show();
1194        ui.close();
1195        // Fills that go from colour to colour, and icons drawn from SVG path data.
1196        ui.row().gap(12.0).open();
1197        ui.el().size(90.0, 36.0).radius(8.0).gradient_across(t.accent, t.green).show();
1198        ui.el().size(90.0, 36.0).radius(8.0).gradient_along(60.0, &[(0.0, t.red), (0.5, t.amber), (1.0, t.green)]).show();
1199        ui.el().size(36.0, 36.0).radius(18.0).gradient_around(&[(0.0, t.text), (0.6, t.accent), (1.0, t.accent.with_alpha(0.0))]).show();
1200        ui.icon(STAR);
1201        ui.el().icon(STAR, 32.0, t.amber).show();
1202        ui.close();
1203        ui.close();
1204    }
1205
1206    // The picture of it:
1207    pub(super) fn shot() -> super::Shot {
1208        super::Shot::new("06-drawing", [324.0, 172.0], describe)
1209    }
1210}
1211
1212// docs/06-text-and-pictures.md
1213mod a_scene {
1214    use taut::{Camera, Mesh, Ui};
1215
1216    /// A body with four sides and a square floor: five points, and four triangles, each
1217    /// given by the numbers of its three corners.
1218    fn pyramid(ui: &mut Ui) -> Mesh {
1219        let points = vec![[-5.0, 0.0, -5.0], [5.0, 0.0, -5.0], [5.0, 0.0, 5.0], [-5.0, 0.0, 5.0], [0.0, 6.0, 0.0]];
1220        ui.add_mesh(points, vec![[0, 1, 4], [1, 2, 4], [2, 3, 4], [3, 0, 4]])
1221    }
1222
1223    fn describe(body: &mut Option<Mesh>, ui: &mut Ui) {
1224        let t = ui.theme;
1225        let pyramid = *body.get_or_insert_with(|| pyramid(ui));
1226        let view = Camera::look_at([13.0, 9.0, 17.0], [0.0, 2.0, 0.0]);
1227        ui.row().pad(12.0).open();
1228        ui.el().size(300.0, 160.0).fill(t.panel).radius(6.0).scene(&view, &[pyramid.filled(t.accent).outlined(t.text)]).show();
1229        ui.close();
1230    }
1231
1232    // The picture of it:
1233    pub(super) fn shot() -> super::Shot {
1234        let mut body = None;
1235        super::Shot::new("06-a-scene", [324.0, 184.0], move |ui| describe(&mut body, ui))
1236    }
1237}
1238
1239// docs/07-everyone-can-use-it.md
1240mod a_form {
1241    use taut::{Align, Ui};
1242
1243    struct Form {
1244        name: String,
1245        letters: bool,
1246    }
1247
1248    fn describe(form: &mut Form, ui: &mut Ui) {
1249        ui.column().pad(12.0).gap(10.0).open();
1250        ui.text_box(&mut form.name, "Your name");
1251        ui.checkbox(&mut form.letters, "Send me letters");
1252        ui.row().gap(8.0).align(Align::End, Align::Center).open();
1253        ui.button("Cancel");
1254        ui.primary_button("Save");
1255        ui.close();
1256        ui.close();
1257    }
1258
1259    // The picture of it:
1260    use super::Step::{Press, Type};
1261    use taut::{Key, Mods, Theme};
1262    pub(super) fn shots() -> Vec<super::Shot> {
1263        let mut first = Form { name: String::new(), letters: false };
1264        let mut second = Form { name: String::new(), letters: true };
1265        let tab = Press(Key::Tab, Mods::NONE);
1266        vec![
1267            super::Shot::new("07-by-the-keyboard", [360.0, 130.0], move |ui| describe(&mut first, ui)).steps(&[tab, Type("Ada"), tab, Press(Key::Space, Mods::NONE), tab]),
1268            super::Shot::new("07-light-and-larger", [360.0, 130.0], move |ui| (ui.theme = Theme::light(), describe(&mut second, ui)).1).scale(1.5),
1269        ]
1270    }
1271}
1272
1273// docs/09-inside-another-program.md
1274mod an_overlay {
1275    use std::time::{Duration, Instant};
1276    use taut::geom::{Size, pt};
1277    use taut::text::BuiltInFont;
1278    use taut::{Button, Color, Event, Length, LocalClipboard, Mods, Surface, Ui};
1279
1280    /// What the overlay's own parts are set to.
1281    struct Settings {
1282        names: bool,
1283        range: f32,
1284    }
1285
1286    fn describe(settings: &mut Settings, ui: &mut Ui) {
1287        let t = ui.theme;
1288        ui.column().w(Length::Px(220.0)).offset(16.0, 16.0).pad(14.0).gap(10.0).fill(t.panel.with_alpha(0.92)).border(t.line_strong, 1.0).radius(10.0).shadow(12.0).open();
1289        ui.text("Overlay", t.font.bold(), t.text);
1290        ui.switch(&mut settings.names, "Show names");
1291        ui.slider(&mut settings.range, 0.0..=100.0);
1292        ui.note(&format!("Seen as far as {:.0} steps", settings.range));
1293        ui.close();
1294    }
1295
1296    /// The interface over a game: what it keeps, and its pixels.
1297    struct Overlay {
1298        ui: Ui,
1299        pixels: Surface,
1300        settings: Settings,
1301        /// Something happened that the pixels do not show yet.
1302        waiting: bool,
1303        started: Instant,
1304    }
1305
1306    impl Overlay {
1307        /// An overlay as large as the game's window, `width` by `height` pixels, on a screen
1308        /// that shows `scale` pixels to a unit.
1309        fn new(width: u32, height: u32, scale: f32) -> Overlay {
1310            let mut ui = Ui::new(Box::new(BuiltInFont), Box::new(LocalClipboard::default()));
1311            ui.theme.bg = Color::NONE;
1312            ui.resize(Size { w: width as f32 / scale, h: height as f32 / scale }, scale);
1313            let pixels = Surface::default(); // (drawn whole by the first `frame`)
1314            Overlay { ui, pixels, settings: Settings { names: true, range: 60.0 }, waiting: true, started: Instant::now() }
1315        }
1316
1317        /// The game's window says the pointer moved here, in its pixels.
1318        fn pointer(&mut self, x: f32, y: f32) {
1319            let scale = self.ui.scale();
1320            self.waiting |= self.ui.event(Event::Move(pt(x / scale, y / scale)));
1321        }
1322
1323        /// The game's window says the left button went down, or came up.
1324        fn button(&mut self, down: bool) {
1325            let event = if down { Event::Press(Button::Left, Mods::NONE) } else { Event::Release(Button::Left) };
1326            self.waiting |= self.ui.event(event);
1327        }
1328
1329        /// Once a frame. The places of `self.pixels` that changed, in pixels (left, top, right,
1330        /// bottom), to copy into the texture; none, when nothing did, which is most frames.
1331        fn frame(&mut self) -> Vec<[usize; 4]> {
1332            self.ui.set_time(self.started.elapsed());
1333            let due = self.ui.wake_in() == Some(Duration::ZERO);
1334            if !std::mem::take(&mut self.waiting) && !due {
1335                return Vec::new();
1336            }
1337            let settings = &mut self.settings;
1338            self.ui.run(&mut |ui| describe(settings, ui));
1339            self.pixels.update(&mut self.ui)
1340        }
1341
1342        /// Whether what the mouse does now is the overlay's, or the game's own.
1343        fn wants_pointer(&self) -> bool {
1344            self.ui.wants_pointer()
1345        }
1346    }
1347
1348    // The picture of it:
1349    pub(super) fn shot() -> super::Shot {
1350        let mut settings = Settings { names: true, range: 60.0 };
1351        super::Shot::new("09-an-overlay", [480.0, 240.0], move |ui| (ui.theme.bg = Color::NONE, describe(&mut settings, ui)).1).over_a_game()
1352    }
1353}
1354
1355// docs/09-inside-another-program.md
1356mod a_whole_screen {
1357    use taut::{Align, Length, Panel, Ui};
1358
1359    struct Desk {
1360        notes: Panel,
1361        text: String,
1362    }
1363
1364    fn describe(desk: &mut Desk, ui: &mut Ui) {
1365        let t = ui.theme;
1366        // The wall behind everything.
1367        ui.el().grow().gradient_along(150.0, &[(0.0, t.bg), (1.0, t.selected)]).show();
1368        // A window of a program, which the person moves, sizes and closes.
1369        if ui.panel(&mut desk.notes, "Notes") {
1370            ui.text_area(&mut desk.text, "Write something", (3, 8));
1371            ui.close();
1372        }
1373        // A bar along the bottom of the screen, over everything.
1374        ui.pin(Align::Start, Align::End);
1375        let wide = ui.size().w;
1376        ui.row().w(Length::Px(wide)).h(Length::Px(40.0)).pad((8.0, 0.0)).gap(8.0).fill(t.panel).border(t.line, 1.0).open();
1377        ui.toggle(&mut desk.notes.open, "Notes");
1378        ui.spacer();
1379        ui.note("12:00");
1380        ui.close();
1381        // Nothing else on this screen draws a pointer: the interface does, last of all.
1382        ui.show_pointer();
1383    }
1384
1385    // The picture of it:
1386    use super::Step::Hover;
1387    pub(super) fn shot() -> super::Shot {
1388        let mut desk = Desk { notes: Panel::new(40.0, 30.0, 260.0, 150.0), text: "Bread, cheese, tea".into() };
1389        super::Shot::new("09-a-whole-screen", [480.0, 260.0], move |ui| describe(&mut desk, ui)).steps(&[Hover("Notes")])
1390    }
1391}