Skip to main content

node_editor/
node_editor.rs

1//! A small node editor: numbers and words, sums of them, and a display, each a node on a
2//! canvas with a grid; wired together, they compute. Right-clicking the canvas adds a node there
3//! (on a node, removes it); so does Shift+A, by name; the buttons above the canvas add one in
4//! the middle, and undo and redo. A wire let go on nothing offers a node to take it. Wire an
5//! output to an input by dragging between them, or by keyboard: Enter on a port, arrows to the
6//! target port, Enter.
7//!   cargo run -p taut --example node_editor
8#![windows_subsystem = "windows"]
9use taut::geom::{Point, pt, rect};
10use taut::{Font, Frame, Graph, GraphAction, Key, Mods, Node, Role, Ui, Window};
11
12/// What a node does.
13#[derive(Clone, Copy, Debug, PartialEq)]
14pub enum Does {
15    /// Holds a number the person sets.
16    Number,
17    /// Holds words the person types.
18    Words,
19    /// Adds two numbers, takes one from another, multiplies them, divides one by the other.
20    Add,
21    Subtract,
22    Multiply,
23    Divide,
24    /// Adds every number wired into it.
25    Total,
26    /// Shows a number large, under the words wired into it.
27    Show,
28}
29
30/// Every kind of node, by the name it is added by.
31const KINDS: [(Does, &str); 8] = [
32    (Does::Number, "Number"),
33    (Does::Words, "Words"),
34    (Does::Add, "Add"),
35    (Does::Subtract, "Subtract"),
36    (Does::Multiply, "Multiply"),
37    (Does::Divide, "Divide"),
38    (Does::Total, "Total"),
39    (Does::Show, "Show"),
40];
41/// What goes through the ports: numbers, and words. (Words do not go into a number.)
42const NUMBER: &str = "number";
43const WORDS: &str = "words";
44
45/// What comes out of a node.
46#[derive(Clone, Debug, PartialEq)]
47pub enum Value {
48    /// A number.
49    Number(f64),
50    /// Words.
51    Words(String),
52}
53
54/// What a node of this editor holds: what it does, the number or the words the person gave
55/// it (for the nodes that hold one), and what came out of it when the graph was last worked
56/// out (nothing, where something it needs is not wired in, or it lies on a loop).
57#[derive(Clone, Debug)]
58pub struct Step {
59    does: Does,
60    number: f64,
61    words: String,
62    out: Option<Value>,
63}
64
65/// The editor: its graph; where its menu was asked for (the node, and the point of the
66/// canvas); the port a wire let go on nothing came from (node, port, and whether an output), for
67/// the node added next; and whether the search for a node to add is open.
68pub struct Sums {
69    graph: Graph<Step>,
70    menu: (Option<usize>, Point),
71    dropped: Option<(usize, usize, bool)>,
72    finding: bool,
73}
74
75/// A node that does `does`, its corner at `at` on the canvas.
76fn node(does: Does, at: Point) -> Node<Step> {
77    let name = KINDS.iter().find(|(kind, _)| *kind == does).map_or("", |(_, name)| name);
78    let node = Node::new(name, at.x, at.y, Step { does, number: 0.0, words: String::new(), out: None });
79    match does {
80        Does::Number => node.output("Value", NUMBER),
81        Does::Words => node.output("Words", WORDS),
82        Does::Show => node.input("Value", NUMBER).input("Caption", WORDS).width(180.0),
83        Does::Total => node.multi_input("Values", NUMBER).output("Total", NUMBER),
84        _ => node.input("A", NUMBER).input("B", NUMBER).output("Result", NUMBER).width(180.0),
85    }
86}
87
88/// Two numbers in a frame, added and shown under a caption, and a node to multiply that is not
89/// wired yet.
90impl Default for Sums {
91    fn default() -> Self {
92        let mut graph = Graph::new();
93        (graph.kinds, graph.grid) = (vec![NUMBER, WORDS], 20.0);
94        graph.frames.push(Frame::new("Inputs", rect(20.0, -20.0, 200.0, 320.0)));
95        let mut first = node(Does::Number, pt(40.0, 40.0));
96        first.data.number = 3.0;
97        let mut second = node(Does::Number, pt(40.0, 190.0));
98        second.data.number = 4.0;
99        let mut caption = node(Does::Words, pt(300.0, 300.0));
100        caption.data.words = "Total".into();
101        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))] {
102            graph.add(each);
103        }
104        for (from, to) in [((0, 0), (2, 0)), ((1, 0), (2, 1)), ((2, 0), (4, 0)), ((3, 0), (4, 1))] {
105            graph.wire(from, to);
106        }
107        work_out(&mut graph);
108        Sums { graph, menu: (None, pt(0.0, 0.0)), dropped: None, finding: false }
109    }
110}
111
112/// Works out what comes out of every node: each once what is wired into it is known, in
113/// the order that makes so (a node on a loop never is).
114fn work_out(graph: &mut Graph<Step>) {
115    let mut waiting = vec![0; graph.nodes.len()];
116    for wire in &graph.wires {
117        waiting[wire.to.0] += 1;
118    }
119    let mut ready: Vec<usize> = (0..graph.nodes.len()).filter(|node| waiting[*node] == 0).collect();
120    graph.nodes.iter_mut().for_each(|node| node.data.out = None);
121    while let Some(node) = ready.pop() {
122        graph.nodes[node].data.out = output(graph, node);
123        for wire in graph.wires.iter().filter(|wire| wire.from.0 == node) {
124            waiting[wire.to.0] -= 1;
125            if waiting[wire.to.0] == 0 {
126                ready.push(wire.to.0);
127            }
128        }
129    }
130}
131
132/// What is wired into an input of a node, as it came out of the node it comes from.
133fn input(graph: &Graph<Step>, node: usize, port: usize) -> Option<&Value> {
134    graph.wire_into((node, port)).and_then(|wire| graph.nodes[wire.from.0].data.out.as_ref())
135}
136
137/// Every number wired into an input, added.
138fn total(graph: &Graph<Step>, node: usize, port: usize) -> f64 {
139    let numbers = graph.wires_into((node, port)).filter_map(|wire| match graph.nodes[wire.from.0].data.out {
140        Some(Value::Number(number)) => Some(number),
141        _ => None,
142    });
143    numbers.sum()
144}
145
146/// What comes out of a node, from what is wired into it.
147fn output(graph: &Graph<Step>, node: usize) -> Option<Value> {
148    let step = &graph.nodes[node].data;
149    let number = |port: usize| match input(graph, node, port) {
150        Some(Value::Number(number)) => Some(*number),
151        _ => None,
152    };
153    let (a, b) = (number(0), number(1));
154    let both = |work: fn(f64, f64) -> f64| a.zip(b).map(|(a, b)| Value::Number(work(a, b)));
155    match step.does {
156        Does::Number => Some(Value::Number(step.number)),
157        Does::Words => Some(Value::Words(step.words.clone())),
158        Does::Add => both(|a, b| a + b),
159        Does::Subtract => both(|a, b| a - b),
160        Does::Multiply => both(|a, b| a * b),
161        Does::Divide => both(|a, b| a / b),
162        Does::Total => Some(Value::Number(total(graph, node, 0))),
163        Does::Show => a.map(Value::Number),
164    }
165}
166
167/// A number as it is written: with no more figures after the point than it needs (six at
168/// the most).
169fn written(number: f64) -> String {
170    if !number.is_finite() {
171        return "Not a number".into();
172    }
173    let fixed = format!("{number:.6}");
174    fixed.trim_end_matches('0').trim_end_matches('.').to_string()
175}
176
177/// What a node shows of what came out of it.
178fn shown(out: &Option<Value>) -> String {
179    match out {
180        Some(Value::Number(number)) => format!("= {}", written(*number)),
181        Some(Value::Words(words)) => words.clone(),
182        None => "Needs A and B".into(),
183    }
184}
185
186/// The editor's window: the buttons that add nodes, undo and redo, and the canvas with the
187/// graph on it.
188pub fn describe(app: &mut Sums, ui: &mut Ui) {
189    let room = ui.size();
190    ui.row().pad(8.0).gap(6.0).open();
191    for (does, name) in KINDS {
192        // (A node added by a button goes in the middle of what is in sight.)
193        if ui.button(name).clicked {
194            let sight = app.graph.view.visible_rect(room);
195            add(app, does, pt(sight.x + sight.w / 2.0 - 80.0, sight.y + sight.h / 2.0 - 60.0));
196        }
197    }
198    ui.spacer();
199    ui.set_enabled(app.graph.can_undo());
200    let undone = ui.button("Undo").clicked && app.graph.undo();
201    ui.set_enabled(app.graph.can_redo());
202    let redone = ui.button("Redo").clicked && app.graph.redo();
203    ui.set_enabled(true);
204    ui.close();
205    if undone || redone {
206        work_out(&mut app.graph);
207    }
208    let mut changed = false;
209    while let Some(n) = ui.graph(&mut app.graph, "Sums") {
210        changed |= body(ui, &mut app.graph, n);
211        ui.close();
212    }
213    // (A wire let go on nothing opens the same menu, and the node added takes it.)
214    match app.graph.action {
215        GraphAction::Menu { node, at } => (app.menu, app.dropped) = ((node, at), None),
216        GraphAction::WireDropped { port, output, at } => (app.menu, app.dropped) = ((None, at), Some((port.0, port.1, output))),
217        GraphAction::None | GraphAction::Selected | GraphAction::Moved => {}
218        _ => changed = true,
219    }
220    if matches!(app.graph.action, GraphAction::Menu { .. } | GraphAction::WireDropped { .. }) {
221        let pointer = ui.pointer().unwrap_or_default();
222        ui.open_popup(MENU, rect(pointer.x, pointer.y, 0.0, 0.0));
223    }
224    menu(app, ui);
225    find(app, ui);
226    if changed {
227        work_out(&mut app.graph);
228        ui.rerun();
229    }
230}
231
232/// What the menu of the right button is known by.
233const MENU: taut::Id = 0x5e7_0001;
234
235/// The menu of the right button: on the canvas, the kinds of node to add where it was
236/// pressed; on a node, taking it away.
237fn menu(app: &mut Sums, ui: &mut Ui) {
238    if !ui.menu(MENU) {
239        return;
240    }
241    match app.menu {
242        (Some(node), _) => {
243            if ui.menu_item("Delete\tDelete").clicked && node < app.graph.nodes.len() {
244                app.graph.save_undo_step();
245                app.graph.remove(node);
246                work_out(&mut app.graph);
247            }
248        }
249        (None, at) => {
250            for (does, name) in KINDS {
251                if ui.menu_item(name).clicked {
252                    add(app, does, at);
253                }
254            }
255        }
256    }
257    ui.close();
258}
259
260/// Shift+A: a search for a kind of node to add, in the middle of what is in sight.
261fn find(app: &mut Sums, ui: &mut Ui) {
262    if ui.key(Key::Char('a'), Mods::SHIFT) {
263        let sight = app.graph.view.visible_rect(ui.size());
264        let middle = pt(sight.x + sight.w / 2.0 - 80.0, sight.y + sight.h / 2.0 - 60.0);
265        (app.finding, app.menu, app.dropped) = (true, (None, middle), None);
266    }
267    let names = KINDS.map(|(_, name)| name);
268    if let Some(picked) = ui.command_palette(&mut app.finding, &names) {
269        add(app, KINDS[picked].0, app.menu.1);
270    }
271}
272
273/// Adds a node that does `does` at `at` on the canvas (on the grid), selected by itself: an
274/// edit undo takes back. It takes the wire let go on nothing, if it can.
275fn add(app: &mut Sums, does: Does, at: Point) {
276    app.graph.save_undo_step();
277    app.graph.nodes.iter_mut().for_each(|node| node.selected = false);
278    let added = app.graph.add(node(does, app.graph.snapped(at)));
279    app.graph.nodes[added].selected = true;
280    if let Some((from, port, output)) = app.dropped.take() {
281        let ports = if output { app.graph.nodes[added].inputs.len() } else { app.graph.nodes[added].outputs.len() };
282        // (Into its first port that takes it.)
283        let _ = (0..ports).any(|other| if output { app.graph.wire((from, port), (added, other)) } else { app.graph.wire((added, other), (from, port)) });
284    }
285    work_out(&mut app.graph);
286}
287
288/// What goes in a node under its ports: the number or the words it holds, or what came out
289/// of it. Says whether the person changed what it holds.
290fn body(ui: &mut Ui, graph: &mut Graph<Step>, n: usize) -> bool {
291    let t = ui.theme;
292    let caption = match input(graph, n, 1) {
293        Some(Value::Words(words)) => words.clone(),
294        _ => String::new(),
295    };
296    let step = &mut graph.nodes[n].data;
297    match step.does {
298        Does::Number => {
299            let number = ui.number(&mut step.number, 1.0);
300            ui.tell(&number, Role::SpinButton, None, "Value");
301            number.changed
302        }
303        Does::Words => ui.text_box(&mut step.words, "Words").changed,
304        Does::Show => {
305            ui.note(&caption);
306            let number = match &step.out {
307                Some(Value::Number(number)) => written(*number),
308                _ => "Nothing wired in".into(),
309            };
310            ui.text(&number, Font { size: t.font.size * 1.6, ..t.font }, t.text);
311            false
312        }
313        _ => {
314            ui.label(&shown(&step.out));
315            false
316        }
317    }
318}
319
320fn main() {
321    let mut app = Sums::default();
322    let window = Window { title: "Nodes", width: 900.0, height: 600.0, min_width: 480.0, min_height: 320.0, ..Default::default() };
323    taut::run(window, move |ui| describe(&mut app, ui));
324}
325
326#[cfg(test)]
327mod tests {
328    use super::*;
329    use taut::testing::Trial;
330
331    #[test]
332    fn nodes_work_themselves_out_as_they_are_wired_by_the_pointer_and_the_keys() {
333        let mut trial = Trial::new(Sums::default(), describe);
334        trial.resize(900.0, 600.0, 1.0);
335        // 3 and 4 added, under their caption; the node to multiply needs its inputs.
336        assert!(trial.has(Role::Text, "7") && trial.has(Role::Text, "Total") && trial.has(Role::Text, "Needs A and B"), "{}", trial.dump());
337        // The sum dragged into the first input of the node to multiply (the only input not
338        // wired), and the second number into its other one from the keyboard.
339        let (from, to) = (trial.center_of(Role::Button, "Result, number out, to Show: Value"), trial.center_of(Role::Button, "A, number in, not wired"));
340        trial.drag(from, to);
341        trial.press(Role::Button, "B, number in, not wired");
342        trial.key("Enter");
343        trial.key("Down");
344        trial.key("Down");
345        assert!(trial.find(Role::Button, "Value, number out, to Add: B").focused, "{}", trial.dump());
346        trial.key("Enter");
347        assert!(trial.has(Role::Text, "= 28"), "7 times 4: {}", trial.dump());
348        // A number stepped up: everything that comes of it follows.
349        trial.press(Role::SpinButton, "Value");
350        trial.key("Up");
351        assert!(trial.has(Role::Text, "8") && trial.has(Role::Text, "= 32"), "{}", trial.dump());
352    }
353
354    #[test]
355    fn the_right_button_adds_a_node_where_it_was_pressed_and_words_do_not_go_into_a_number() {
356        let mut trial = Trial::new(Sums::default(), describe);
357        trial.resize(900.0, 600.0, 1.0);
358        trial.right_click(pt(300.0, 520.0));
359        trial.press(Role::MenuItem, "Divide");
360        let divide = trial.app.graph.nodes.last().expect("a node").clone();
361        assert_eq!((divide.title.as_str(), divide.selected), ("Divide", true));
362        let wires = trial.app.graph.wires.len();
363        let (from, to) = (trial.center_of(Role::Button, "Words, words out, to Show: Caption"), trial.center_of(Role::Button, "A, number in, not wired"));
364        trial.drag(from, to);
365        assert_eq!(trial.app.graph.wires.len(), wires, "words are refused by a number");
366        // On a node, the right button takes it away.
367        let title = trial.center_of(Role::Row, "Divide");
368        trial.right_click(title);
369        trial.press(Role::MenuItem, "Delete");
370        assert!(!trial.app.graph.nodes.iter().any(|node| node.title == "Divide"));
371    }
372
373    #[test]
374    fn a_wire_let_go_on_nothing_and_a_search_add_nodes_and_undo_takes_them_back() {
375        let mut trial = Trial::new(Sums::default(), describe);
376        trial.resize(900.0, 600.0, 1.0);
377        let nodes = trial.app.graph.nodes.len();
378        // From the sum's output onto bare canvas: the menu, and the node picked takes the wire.
379        let from = trial.center_of(Role::Button, "Result, number out, to Show: Value");
380        trial.drag(from, pt(from.x + 40.0, 520.0));
381        trial.press(Role::MenuItem, "Total");
382        let total = trial.app.graph.nodes.len() - 1;
383        assert_eq!((trial.app.graph.nodes.len(), trial.app.graph.nodes[total].title.as_str()), (nodes + 1, "Total"));
384        assert!(trial.app.graph.wires_into((total, 0)).any(|wire| wire.from.0 == 2), "{:?}", trial.app.graph.wires);
385        // A second number into the same input: the total is of both.
386        let four = trial.center_of(Role::Button, "Value, number out, to Add: B");
387        let values = trial.center_of(Role::Button, "Values, number in, several, from Add: Result");
388        trial.drag(four, values);
389        assert!(trial.has(Role::Text, "= 11"), "7 and 4: {}", trial.dump());
390        // Shift and A: a search; Enter adds the first that matches.
391        trial.key("Shift+A");
392        trial.type_text("mul");
393        trial.key("Enter");
394        assert_eq!(trial.app.graph.nodes.last().map(|node| node.title.as_str()), Some("Multiply"));
395        // Undo takes back the node, the wire, then the other node.
396        trial.press(Role::Button, "Undo");
397        trial.press(Role::Button, "Undo");
398        assert!(trial.has(Role::Text, "= 7") && !trial.has(Role::Text, "= 11"), "{}", trial.dump());
399        trial.press(Role::Button, "Undo");
400        assert_eq!(trial.app.graph.nodes.len(), nodes);
401        trial.press(Role::Button, "Redo");
402        assert_eq!(trial.app.graph.nodes.len(), nodes + 1);
403    }
404}