taut 0.3.0

A Rust GUI library for Windows, Linux, macOS, iOS and the web that aims to be small, fast and accessible, with zero dependencies and nothing compiled in that your program doesn't use.
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
//! A small node editor: numbers and words, sums of them, and a display, each a node on a
//! canvas with a grid; wired together, they compute. Right-clicking the canvas adds a node there
//! (on a node, removes it); so does Shift+A, by name; the buttons above the canvas add one in
//! the middle, and undo and redo. A wire let go on nothing offers a node to take it. Wire an
//! output to an input by dragging between them, or by keyboard: Enter on a port, arrows to the
//! target port, Enter.
//!   cargo run -p taut --example node_editor
#![windows_subsystem = "windows"]
use taut::geom::{Point, pt, rect};
use taut::{Font, Frame, Graph, GraphAction, Key, Mods, Node, Role, Ui, Window};

/// What a node does.
#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Does {
    /// Holds a number the person sets.
    Number,
    /// Holds words the person types.
    Words,
    /// Adds two numbers, takes one from another, multiplies them, divides one by the other.
    Add,
    Subtract,
    Multiply,
    Divide,
    /// Adds every number wired into it.
    Total,
    /// Shows a number large, under the words wired into it.
    Show,
}

/// Every kind of node, by the name it is added by.
const KINDS: [(Does, &str); 8] = [
    (Does::Number, "Number"),
    (Does::Words, "Words"),
    (Does::Add, "Add"),
    (Does::Subtract, "Subtract"),
    (Does::Multiply, "Multiply"),
    (Does::Divide, "Divide"),
    (Does::Total, "Total"),
    (Does::Show, "Show"),
];
/// What goes through the ports: numbers, and words. (Words do not go into a number.)
const NUMBER: &str = "number";
const WORDS: &str = "words";

/// What comes out of a node.
#[derive(Clone, Debug, PartialEq)]
pub enum Value {
    /// A number.
    Number(f64),
    /// Words.
    Words(String),
}

/// What a node of this editor holds: what it does, the number or the words the person gave
/// it (for the nodes that hold one), and what came out of it when the graph was last worked
/// out (nothing, where something it needs is not wired in, or it lies on a loop).
#[derive(Clone, Debug)]
pub struct Step {
    does: Does,
    number: f64,
    words: String,
    out: Option<Value>,
}

/// The editor: its graph; where its menu was asked for (the node, and the point of the
/// canvas); the port a wire let go on nothing came from (node, port, and whether an output), for
/// the node added next; and whether the search for a node to add is open.
pub struct Sums {
    graph: Graph<Step>,
    menu: (Option<usize>, Point),
    dropped: Option<(usize, usize, bool)>,
    finding: bool,
}

/// A node that does `does`, its corner at `at` on the canvas.
fn node(does: Does, at: Point) -> Node<Step> {
    let name = KINDS.iter().find(|(kind, _)| *kind == does).map_or("", |(_, name)| name);
    let node = Node::new(name, at.x, at.y, Step { does, number: 0.0, words: String::new(), out: None });
    match does {
        Does::Number => node.output("Value", NUMBER),
        Does::Words => node.output("Words", WORDS),
        Does::Show => node.input("Value", NUMBER).input("Caption", WORDS).width(180.0),
        Does::Total => node.multi_input("Values", NUMBER).output("Total", NUMBER),
        _ => node.input("A", NUMBER).input("B", NUMBER).output("Result", NUMBER).width(180.0),
    }
}

/// Two numbers in a frame, added and shown under a caption, and a node to multiply that is not
/// wired yet.
impl Default for Sums {
    fn default() -> Self {
        let mut graph = Graph::new();
        (graph.kinds, graph.grid) = (vec![NUMBER, WORDS], 20.0);
        graph.frames.push(Frame::new("Inputs", rect(20.0, -20.0, 200.0, 320.0)));
        let mut first = node(Does::Number, pt(40.0, 40.0));
        first.data.number = 3.0;
        let mut second = node(Does::Number, pt(40.0, 190.0));
        second.data.number = 4.0;
        let mut caption = node(Does::Words, pt(300.0, 300.0));
        caption.data.words = "Total".into();
        for each in [first, second, node(Does::Add, pt(300.0, 90.0)), caption, node(Does::Show, pt(560.0, 140.0)), node(Does::Multiply, pt(560.0, 330.0))] {
            graph.add(each);
        }
        for (from, to) in [((0, 0), (2, 0)), ((1, 0), (2, 1)), ((2, 0), (4, 0)), ((3, 0), (4, 1))] {
            graph.wire(from, to);
        }
        work_out(&mut graph);
        Sums { graph, menu: (None, pt(0.0, 0.0)), dropped: None, finding: false }
    }
}

/// Works out what comes out of every node: each once what is wired into it is known, in
/// the order that makes so (a node on a loop never is).
fn work_out(graph: &mut Graph<Step>) {
    let mut waiting = vec![0; graph.nodes.len()];
    for wire in &graph.wires {
        waiting[wire.to.0] += 1;
    }
    let mut ready: Vec<usize> = (0..graph.nodes.len()).filter(|node| waiting[*node] == 0).collect();
    graph.nodes.iter_mut().for_each(|node| node.data.out = None);
    while let Some(node) = ready.pop() {
        graph.nodes[node].data.out = output(graph, node);
        for wire in graph.wires.iter().filter(|wire| wire.from.0 == node) {
            waiting[wire.to.0] -= 1;
            if waiting[wire.to.0] == 0 {
                ready.push(wire.to.0);
            }
        }
    }
}

/// What is wired into an input of a node, as it came out of the node it comes from.
fn input(graph: &Graph<Step>, node: usize, port: usize) -> Option<&Value> {
    graph.wire_into((node, port)).and_then(|wire| graph.nodes[wire.from.0].data.out.as_ref())
}

/// Every number wired into an input, added.
fn total(graph: &Graph<Step>, node: usize, port: usize) -> f64 {
    let numbers = graph.wires_into((node, port)).filter_map(|wire| match graph.nodes[wire.from.0].data.out {
        Some(Value::Number(number)) => Some(number),
        _ => None,
    });
    numbers.sum()
}

/// What comes out of a node, from what is wired into it.
fn output(graph: &Graph<Step>, node: usize) -> Option<Value> {
    let step = &graph.nodes[node].data;
    let number = |port: usize| match input(graph, node, port) {
        Some(Value::Number(number)) => Some(*number),
        _ => None,
    };
    let (a, b) = (number(0), number(1));
    let both = |work: fn(f64, f64) -> f64| a.zip(b).map(|(a, b)| Value::Number(work(a, b)));
    match step.does {
        Does::Number => Some(Value::Number(step.number)),
        Does::Words => Some(Value::Words(step.words.clone())),
        Does::Add => both(|a, b| a + b),
        Does::Subtract => both(|a, b| a - b),
        Does::Multiply => both(|a, b| a * b),
        Does::Divide => both(|a, b| a / b),
        Does::Total => Some(Value::Number(total(graph, node, 0))),
        Does::Show => a.map(Value::Number),
    }
}

/// A number as it is written: with no more figures after the point than it needs (six at
/// the most).
fn written(number: f64) -> String {
    if !number.is_finite() {
        return "Not a number".into();
    }
    let fixed = format!("{number:.6}");
    fixed.trim_end_matches('0').trim_end_matches('.').to_string()
}

/// What a node shows of what came out of it.
fn shown(out: &Option<Value>) -> String {
    match out {
        Some(Value::Number(number)) => format!("= {}", written(*number)),
        Some(Value::Words(words)) => words.clone(),
        None => "Needs A and B".into(),
    }
}

/// The editor's window: the buttons that add nodes, undo and redo, and the canvas with the
/// graph on it.
pub fn describe(app: &mut Sums, ui: &mut Ui) {
    let room = ui.size();
    ui.row().pad(8.0).gap(6.0).open();
    for (does, name) in KINDS {
        // (A node added by a button goes in the middle of what is in sight.)
        if ui.button(name).clicked {
            let sight = app.graph.view.visible_rect(room);
            add(app, does, pt(sight.x + sight.w / 2.0 - 80.0, sight.y + sight.h / 2.0 - 60.0));
        }
    }
    ui.spacer();
    ui.set_enabled(app.graph.can_undo());
    let undone = ui.button("Undo").clicked && app.graph.undo();
    ui.set_enabled(app.graph.can_redo());
    let redone = ui.button("Redo").clicked && app.graph.redo();
    ui.set_enabled(true);
    ui.close();
    if undone || redone {
        work_out(&mut app.graph);
    }
    let mut changed = false;
    while let Some(n) = ui.graph(&mut app.graph, "Sums") {
        changed |= body(ui, &mut app.graph, n);
        ui.close();
    }
    // (A wire let go on nothing opens the same menu, and the node added takes it.)
    match app.graph.action {
        GraphAction::Menu { node, at } => (app.menu, app.dropped) = ((node, at), None),
        GraphAction::WireDropped { port, output, at } => (app.menu, app.dropped) = ((None, at), Some((port.0, port.1, output))),
        GraphAction::None | GraphAction::Selected | GraphAction::Moved => {}
        _ => changed = true,
    }
    if matches!(app.graph.action, GraphAction::Menu { .. } | GraphAction::WireDropped { .. }) {
        let pointer = ui.pointer().unwrap_or_default();
        ui.open_popup(MENU, rect(pointer.x, pointer.y, 0.0, 0.0));
    }
    menu(app, ui);
    find(app, ui);
    if changed {
        work_out(&mut app.graph);
        ui.rerun();
    }
}

/// What the menu of the right button is known by.
const MENU: taut::Id = 0x5e7_0001;

/// The menu of the right button: on the canvas, the kinds of node to add where it was
/// pressed; on a node, taking it away.
fn menu(app: &mut Sums, ui: &mut Ui) {
    if !ui.menu(MENU) {
        return;
    }
    match app.menu {
        (Some(node), _) => {
            if ui.menu_item("Delete\tDelete").clicked && node < app.graph.nodes.len() {
                app.graph.save_undo_step();
                app.graph.remove(node);
                work_out(&mut app.graph);
            }
        }
        (None, at) => {
            for (does, name) in KINDS {
                if ui.menu_item(name).clicked {
                    add(app, does, at);
                }
            }
        }
    }
    ui.close();
}

/// Shift+A: a search for a kind of node to add, in the middle of what is in sight.
fn find(app: &mut Sums, ui: &mut Ui) {
    if ui.key(Key::Char('a'), Mods::SHIFT) {
        let sight = app.graph.view.visible_rect(ui.size());
        let middle = pt(sight.x + sight.w / 2.0 - 80.0, sight.y + sight.h / 2.0 - 60.0);
        (app.finding, app.menu, app.dropped) = (true, (None, middle), None);
    }
    let names = KINDS.map(|(_, name)| name);
    if let Some(picked) = ui.command_palette(&mut app.finding, &names) {
        add(app, KINDS[picked].0, app.menu.1);
    }
}

/// Adds a node that does `does` at `at` on the canvas (on the grid), selected by itself: an
/// edit undo takes back. It takes the wire let go on nothing, if it can.
fn add(app: &mut Sums, does: Does, at: Point) {
    app.graph.save_undo_step();
    app.graph.nodes.iter_mut().for_each(|node| node.selected = false);
    let added = app.graph.add(node(does, app.graph.snapped(at)));
    app.graph.nodes[added].selected = true;
    if let Some((from, port, output)) = app.dropped.take() {
        let ports = if output { app.graph.nodes[added].inputs.len() } else { app.graph.nodes[added].outputs.len() };
        // (Into its first port that takes it.)
        let _ = (0..ports).any(|other| if output { app.graph.wire((from, port), (added, other)) } else { app.graph.wire((added, other), (from, port)) });
    }
    work_out(&mut app.graph);
}

/// What goes in a node under its ports: the number or the words it holds, or what came out
/// of it. Says whether the person changed what it holds.
fn body(ui: &mut Ui, graph: &mut Graph<Step>, n: usize) -> bool {
    let t = ui.theme;
    let caption = match input(graph, n, 1) {
        Some(Value::Words(words)) => words.clone(),
        _ => String::new(),
    };
    let step = &mut graph.nodes[n].data;
    match step.does {
        Does::Number => {
            let number = ui.number(&mut step.number, 1.0);
            ui.tell(&number, Role::SpinButton, None, "Value");
            number.changed
        }
        Does::Words => ui.text_box(&mut step.words, "Words").changed,
        Does::Show => {
            ui.note(&caption);
            let number = match &step.out {
                Some(Value::Number(number)) => written(*number),
                _ => "Nothing wired in".into(),
            };
            ui.text(&number, Font { size: t.font.size * 1.6, ..t.font }, t.text);
            false
        }
        _ => {
            ui.label(&shown(&step.out));
            false
        }
    }
}

fn main() {
    let mut app = Sums::default();
    let window = Window { title: "Nodes", width: 900.0, height: 600.0, min_width: 480.0, min_height: 320.0, ..Default::default() };
    taut::run(window, move |ui| describe(&mut app, ui));
}

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

    #[test]
    fn nodes_work_themselves_out_as_they_are_wired_by_the_pointer_and_the_keys() {
        let mut trial = Trial::new(Sums::default(), describe);
        trial.resize(900.0, 600.0, 1.0);
        // 3 and 4 added, under their caption; the node to multiply needs its inputs.
        assert!(trial.has(Role::Text, "7") && trial.has(Role::Text, "Total") && trial.has(Role::Text, "Needs A and B"), "{}", trial.dump());
        // The sum dragged into the first input of the node to multiply (the only input not
        // wired), and the second number into its other one from the keyboard.
        let (from, to) = (trial.center_of(Role::Button, "Result, number out, to Show: Value"), trial.center_of(Role::Button, "A, number in, not wired"));
        trial.drag(from, to);
        trial.press(Role::Button, "B, number in, not wired");
        trial.key("Enter");
        trial.key("Down");
        trial.key("Down");
        assert!(trial.find(Role::Button, "Value, number out, to Add: B").focused, "{}", trial.dump());
        trial.key("Enter");
        assert!(trial.has(Role::Text, "= 28"), "7 times 4: {}", trial.dump());
        // A number stepped up: everything that comes of it follows.
        trial.press(Role::SpinButton, "Value");
        trial.key("Up");
        assert!(trial.has(Role::Text, "8") && trial.has(Role::Text, "= 32"), "{}", trial.dump());
    }

    #[test]
    fn the_right_button_adds_a_node_where_it_was_pressed_and_words_do_not_go_into_a_number() {
        let mut trial = Trial::new(Sums::default(), describe);
        trial.resize(900.0, 600.0, 1.0);
        trial.right_click(pt(300.0, 520.0));
        trial.press(Role::MenuItem, "Divide");
        let divide = trial.app.graph.nodes.last().expect("a node").clone();
        assert_eq!((divide.title.as_str(), divide.selected), ("Divide", true));
        let wires = trial.app.graph.wires.len();
        let (from, to) = (trial.center_of(Role::Button, "Words, words out, to Show: Caption"), trial.center_of(Role::Button, "A, number in, not wired"));
        trial.drag(from, to);
        assert_eq!(trial.app.graph.wires.len(), wires, "words are refused by a number");
        // On a node, the right button takes it away.
        let title = trial.center_of(Role::Row, "Divide");
        trial.right_click(title);
        trial.press(Role::MenuItem, "Delete");
        assert!(!trial.app.graph.nodes.iter().any(|node| node.title == "Divide"));
    }

    #[test]
    fn a_wire_let_go_on_nothing_and_a_search_add_nodes_and_undo_takes_them_back() {
        let mut trial = Trial::new(Sums::default(), describe);
        trial.resize(900.0, 600.0, 1.0);
        let nodes = trial.app.graph.nodes.len();
        // From the sum's output onto bare canvas: the menu, and the node picked takes the wire.
        let from = trial.center_of(Role::Button, "Result, number out, to Show: Value");
        trial.drag(from, pt(from.x + 40.0, 520.0));
        trial.press(Role::MenuItem, "Total");
        let total = trial.app.graph.nodes.len() - 1;
        assert_eq!((trial.app.graph.nodes.len(), trial.app.graph.nodes[total].title.as_str()), (nodes + 1, "Total"));
        assert!(trial.app.graph.wires_into((total, 0)).any(|wire| wire.from.0 == 2), "{:?}", trial.app.graph.wires);
        // A second number into the same input: the total is of both.
        let four = trial.center_of(Role::Button, "Value, number out, to Add: B");
        let values = trial.center_of(Role::Button, "Values, number in, several, from Add: Result");
        trial.drag(four, values);
        assert!(trial.has(Role::Text, "= 11"), "7 and 4: {}", trial.dump());
        // Shift and A: a search; Enter adds the first that matches.
        trial.key("Shift+A");
        trial.type_text("mul");
        trial.key("Enter");
        assert_eq!(trial.app.graph.nodes.last().map(|node| node.title.as_str()), Some("Multiply"));
        // Undo takes back the node, the wire, then the other node.
        trial.press(Role::Button, "Undo");
        trial.press(Role::Button, "Undo");
        assert!(trial.has(Role::Text, "= 7") && !trial.has(Role::Text, "= 11"), "{}", trial.dump());
        trial.press(Role::Button, "Undo");
        assert_eq!(trial.app.graph.nodes.len(), nodes);
        trial.press(Role::Button, "Redo");
        assert_eq!(trial.app.graph.nodes.len(), nodes + 1);
    }
}