Skip to main content

egui_pop_viewport/graph/
mod.rs

1//! A node graph editor over an application's graph, drawn in egui's
2//! [`Scene`](egui::Scene), its pan and zoom driven by the pointer
3//! profile.
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! **The application keeps the graph.** It describes its nodes, their
9//! typed ports, its wires and groups through [`GraphModel`]; the editor
10//! draws them and hands back what the user did as [`Edit`]s (connect,
11//! disconnect, move, delete, add, a parameter changed), which the
12//! application applies to its graph or not. Each edit goes through the
13//! [`on_edit`](GraphEditor::on_edit) hook first: allow, veto or redirect
14//! (`egui-pop-imaging` runs them as the `graph.*` steps).
15//!
16//! - **Pan and zoom**, as the pointer profile says (its `canvas.graph`
17//!   scope, `docs/pointer-gestures.md`): by default the wheel pans,
18//!   Ctrl (Cmd) and the wheel or a pinch zoom around the pointer, a
19//!   drag with the middle button pans, and a double click on the canvas
20//!   fits the graph; a drag with Space held always pans.
21//!   [`GraphMinimap`] is the navigator's pattern: the whole graph, the
22//!   part in view framed.
23//! - **Levels**: the zoom picks what is drawn ([`Level`]): the
24//!   overview (compact nodes, groups folded into stacks), the ports, and
25//!   the detail, where each node's parameters are egui-pop sliders
26//!   edited inline.
27//! - **Nodes**: a click selects (Ctrl or Shift adds), a drag moves the
28//!   selection (one [`Edit::Move`] at its end, snapped to the grid with
29//!   [`snap`](GraphEditor::snap); Escape puts it back), the chevron or a
30//!   double click on the title collapses, a slot in the title bar is the
31//!   application's ([`header`](GraphEditor::header)), and so is a status
32//!   drawn there ([`status`](GraphEditor::status): a short word in a tone,
33//!   a colour or a theme token's colour, its detail as a tooltip, read
34//!   aloud as part of the node's description). A drag on the canvas draws
35//!   a rubber band.
36//! - **Wires**: a drag from a port draws a wire, checked against the
37//!   ports' types while it is drawn; dropped on a port that accepts it,
38//!   it connects (replacing an input's wire); a drag off a connected
39//!   input takes its wire along, dropped nowhere it disconnects. A click
40//!   on a port, then on another, connects too.
41//! - **A wire itself** answers the pointer within 6 points (12 on a touch
42//!   screen), where no node or port is, at the ports and detail levels:
43//!   hovered, the pointer becomes a hand and the wire is drawn thicker and
44//!   lighter with its ports ringed and a tooltip naming its ends; a click
45//!   selects it (and no node), Ctrl (Cmd) or Shift adds it to the nodes
46//!   and wires selected; selected, it is drawn thicker in the selection's
47//!   colour over a soft glow, with a larger handle near each end and its
48//!   ports ringed (`graph.wire-hover.*`, `graph.wire-selected.*`). A drag on it
49//!   takes its nearer end along (one of an output's several wires too):
50//!   dropped on a port that accepts it, one [`Edit::Connect`] whose
51//!   `replaces` holds the old wire; dropped nowhere, a disconnect. Delete
52//!   removes the wires selected as one [`Edit::Disconnect`] (with nodes,
53//!   one [`Edit::Delete`]); its menu disconnects it or selects the node at
54//!   either end. A click on the canvas clears the selection, nodes and
55//!   wires.
56//! - **Groups**: a frame around the group's nodes, whose title folds
57//!   them into a stack (a click on the stack unfolds it).
58//! - **Keyboard** ([`GraphKeys`]): Tab goes through the nodes and their
59//!   ports; on a node the arrows go to the nearest node that way and
60//!   Shift with the arrows moves the selection; on a port the arrows go
61//!   to the node's other ports, Enter or Space picks it as a wire's end
62//!   (twice: connected), Delete disconnects it and Escape goes back to
63//!   the node. After a connected input, Tab reaches each of its wires:
64//!   Delete disconnects it, Enter picks its input end up and Shift+Enter
65//!   its output end (then a port, as above), the menu key opens its menu,
66//!   Escape goes back to the port. Delete removes the selection, Ctrl+D duplicates it,
67//!   Ctrl+A selects everything, Home fits. A large graph is one Tab stop
68//!   ([`TabStops`]): Tab enters and leaves it, Enter goes into a node's
69//!   parts and Escape back.
70//! - **Accessibility**: the canvas is a group named by its label, each
71//!   node a group (role description "node") with its ports as buttons,
72//!   their type and wires as the value, and each wire into an input a
73//!   button after it (role description "wire", named by its two ports,
74//!   its keys as the description, selected or not); refusals, wires made
75//!   or removed and the wires selected are announced.
76//!
77//! ```
78//! use egui_pop_viewport::graph::{Edge, Edit, GraphEditor, GraphModel, GraphState, Node};
79//!
80//! struct Pipeline {
81//!     nodes: Vec<Node>,
82//!     edges: Vec<Edge>,
83//! }
84//!
85//! impl GraphModel for Pipeline {
86//!     fn nodes(&self) -> Vec<Node> {
87//!         self.nodes.clone()
88//!     }
89//!     fn edges(&self) -> Vec<Edge> {
90//!         self.edges.clone()
91//!     }
92//! }
93//!
94//! fn ui(ui: &mut egui::Ui, graph: &mut Pipeline, state: &mut GraphState) {
95//!     let out = GraphEditor::new(&*graph, state).snap(Some(10.0)).show(ui);
96//!     for edit in out.edits {
97//!         if let Edit::Connect { from, to, replaces } = edit {
98//!             graph.edges.retain(|e| !replaces.contains(e));
99//!             graph.edges.push(Edge::new(from, to));
100//!         }
101//!     }
102//! }
103//! ```
104
105mod export;
106mod minimap;
107mod model;
108mod state;
109mod status;
110mod wires;
111#[cfg(feature = "graph-yaml")]
112pub mod yaml;
113
114use std::collections::{BTreeSet, HashMap};
115use std::fmt;
116
117use egui::accesskit::Role;
118use egui::emath::TSTransform;
119use egui::text::{LayoutJob, TextWrapping};
120use egui::{
121    Color32, CornerRadius, FontId, Id, Key, Modifiers, Pos2, Rangef, Rect, Response, Sense, Stroke,
122    StrokeKind, Ui, UiBuilder, Vec2, pos2, vec2,
123};
124use egui_pop_core::a11y::{self, Politeness};
125use egui_pop_core::icon::Icon;
126use egui_pop_core::pointer::DragKind;
127use egui_pop_core::pointer::claim::{self, Secondary};
128use egui_pop_core::slider::{self, Slider};
129use egui_pop_core::state::Slot;
130use egui_pop_core::strings::{self, Arg, tr, tr_args};
131use egui_pop_core::tab;
132use egui_pop_core::theme::Tokens;
133use serde_json::{Value as Json, json};
134
135pub use export::{ExportError, ExportOptions, ExportTheme, GraphExport};
136pub use minimap::GraphMinimap;
137pub use model::{
138    Edge, Edit, GraphEvent, GraphModel, Group, Kind, Level, Moved, NewNode, Node, Param, Port,
139    PortRef, PortType, Refusal, Request, Side, TYPE_TOKENS, check,
140};
141pub use state::GraphState;
142pub use status::{NodeStatus, StatusColor};
143pub use wires::WireStyle;
144
145use crate::change::{Cause, Verdict};
146use crate::navigation::{self, NavCommand, Overview};
147use crate::strings as s;
148use state::{Moving, Wire};
149
150/// A title bar's height, in graph units.
151const HEADER: f32 = 28.0;
152/// A row of ports.
153const ROW: f32 = 20.0;
154/// Inside a node's edges.
155const PAD: f32 = 6.0;
156/// A node's heights in the overview, the smallest that keeps its title
157/// readable at the zoom (a few steps, so the glyph cache stays small).
158const OVERVIEW_H: [f32; 3] = [48.0, 64.0, 90.0];
159/// A port's radius.
160const PORT_R: f32 = 5.0;
161/// The square a port answers the pointer in.
162const PORT_HIT: f32 = 16.0;
163/// How near a port a dragged wire is dropped on it.
164const DROP: f32 = 14.0;
165/// How near a wire (screen points) the pointer is on it.
166const WIRE_HIT: f32 = 6.0;
167/// As [`WIRE_HIT`], on a touch screen.
168const WIRE_HIT_TOUCH: f32 = 12.0;
169/// How far from each end of a wire its handles are drawn (screen points).
170const HANDLE: f32 = 18.0;
171/// Around a group's nodes.
172const GROUP_PAD: f32 = 14.0;
173/// A group's title band.
174const GROUP_LABEL: f32 = 24.0;
175/// The chevron's square in a title bar.
176const CHEVRON: f32 = 16.0;
177/// A node's width by default, in graph units.
178const NODE_WIDTH: f32 = 180.0;
179
180/// The node graph's colours, from the theme (`graph.*`).
181#[derive(Clone, Copy, Debug, PartialEq)]
182pub struct GraphTokens {
183    pub background: Color32,
184    pub grid: Color32,
185    pub node: Color32,
186    pub node_header: Color32,
187    pub node_border: Color32,
188    pub node_selected: Color32,
189    pub wire: Color32,
190    pub wire_preview: Color32,
191    pub wire_refused: Color32,
192    pub group: Color32,
193    pub group_border: Color32,
194    pub band: Color32,
195    pub text: Color32,
196    pub text_muted: Color32,
197    pub focus: Color32,
198}
199
200impl GraphTokens {
201    pub fn of(ctx: &egui::Context) -> GraphTokens {
202        let t = Tokens::of(ctx);
203        let c = |path: &str, fallback: Color32| t.color(path).unwrap_or(fallback);
204        GraphTokens {
205            background: c("graph.background", t.surface.canvas),
206            grid: c("graph.grid", t.border.default),
207            node: c("graph.node", t.surface.raised),
208            node_header: c("graph.node-header", t.surface.overlay),
209            node_border: c("graph.node-border", t.border.default),
210            node_selected: c("graph.node-selected", t.accent.default),
211            wire: c("graph.wire", t.border.strong),
212            wire_preview: c("graph.wire-preview", t.accent.default),
213            wire_refused: c("graph.wire-refused", t.status.danger),
214            group: c("graph.group", t.accent.subtle),
215            group_border: c("graph.group-border", t.border.default),
216            band: c("graph.band", t.accent.default),
217            text: t.text.default,
218            text_muted: t.text.muted,
219            focus: t.focus_ring,
220        }
221    }
222
223    /// A port type's colour: its token, else the plain wire's.
224    pub fn type_color(&self, ctx: &egui::Context, ty: &PortType) -> Color32 {
225        Tokens::of(ctx).color(&ty.color).unwrap_or(self.wire)
226    }
227}
228
229/// How a hovered and a selected wire are drawn (`graph.wire-hover.*`,
230/// `graph.wire-selected.*`); widths in screen points.
231#[derive(Clone, Copy, Debug, PartialEq)]
232struct WireLook {
233    hover: Color32,
234    hover_width: f32,
235    selected: Color32,
236    selected_width: f32,
237    glow: Color32,
238    glow_width: f32,
239}
240
241impl WireLook {
242    fn of(ctx: &egui::Context) -> WireLook {
243        let t = Tokens::of(ctx);
244        let r = t.resolved();
245        let d = |path: &str, fallback: f32| r.dimension(path).unwrap_or(fallback);
246        let accent = t.accent.default;
247        let opacity = d("graph.wire-selected.glow-opacity", 0.35).clamp(0.0, 1.0);
248        WireLook {
249            hover: t.color("graph.wire-hover.color").unwrap_or(t.text.strong),
250            hover_width: d("graph.wire-hover.width", 3.5).max(0.5),
251            selected: t.color("graph.wire-selected.color").unwrap_or(accent),
252            selected_width: d("graph.wire-selected.width", 4.0).max(0.5),
253            glow: t
254                .color("graph.wire-selected.glow")
255                .unwrap_or(accent)
256                .gamma_multiply(opacity),
257            glow_width: d("graph.wire-selected.glow-width", 12.0).max(0.0),
258        }
259    }
260}
261
262/// The node editors' keys, as data for input profiles ([`set_keys`]).
263#[derive(Clone, Copy, Debug, PartialEq)]
264pub struct GraphKeys {
265    /// Deletes the selection (on a port: disconnects it).
266    pub delete: [Key; 2],
267    /// With Ctrl (Cmd): duplicates the selection.
268    pub duplicate: Key,
269    /// With Ctrl (Cmd): selects every node.
270    pub select_all: Key,
271    /// Fits the graph in view.
272    pub fit: Key,
273    /// Held with the arrows on a node: moves the selection.
274    pub nudge: Modifiers,
275    /// Cancels a wire, a drag; on a port, back to its node.
276    pub cancel: Key,
277}
278
279impl Default for GraphKeys {
280    fn default() -> Self {
281        GraphKeys {
282            delete: [Key::Delete, Key::Backspace],
283            duplicate: Key::D,
284            select_all: Key::A,
285            fit: Key::Home,
286            nudge: Modifiers::SHIFT,
287            cancel: Key::Escape,
288        }
289    }
290}
291
292const KEYS: Slot<GraphKeys> = Slot::new("viewport.graph.keys");
293
294/// The node editors' keys in a context (the defaults until set).
295pub fn keys(ctx: &egui::Context) -> GraphKeys {
296    KEYS.get_or_default(ctx)
297}
298
299/// Remaps the node editors' keys in a context (an input profile).
300pub fn set_keys(ctx: &egui::Context, keys: GraphKeys) {
301    KEYS.set(ctx, keys);
302}
303
304type HookFn<'a> = dyn FnMut(&Edit, Cause) -> Verdict<Edit> + 'a;
305type HeaderFn<'a> = dyn FnMut(&mut Ui, &Node) + 'a;
306type StatusFn<'a> = dyn FnMut(&Node) -> Option<NodeStatus> + 'a;
307
308/// How Tab goes through a graph, set with [`GraphEditor::tab_stops`].
309#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
310pub enum TabStops {
311    /// One stop from [`ONE_STOP_FROM`] nodes, a stop per part below.
312    #[default]
313    Auto,
314    /// The graph is one Tab stop, as ARIA asks of a composite widget: Tab
315    /// enters it on the node (or the canvas) focused there last and leaves it
316    /// from anywhere in it; the arrows go between nodes; Enter goes into a
317    /// node's parts (its chevron, ports, sliders and header), Tab and
318    /// Shift+Tab go round them, Escape goes back to the node.
319    One,
320    /// Tab goes through the canvas, each node, its chevron, its ports and its
321    /// sliders.
322    Each,
323}
324
325/// From how many nodes a graph is one Tab stop with [`TabStops::Auto`].
326pub const ONE_STOP_FROM: usize = 12;
327
328/// The node graph editor.
329pub struct GraphEditor<'a> {
330    model: &'a dyn GraphModel,
331    state: &'a mut GraphState,
332    id_salt: Option<Id>,
333    label: Option<String>,
334    size: Option<Vec2>,
335    snap: Option<f32>,
336    node_width: f32,
337    wires: WireStyle,
338    overview_below: f32,
339    detail_from: f32,
340    zoom_range: Rangef,
341    header: Option<Box<HeaderFn<'a>>>,
342    status: Option<Box<StatusFn<'a>>>,
343    hook: Option<Box<HookFn<'a>>>,
344    requests: Vec<Request>,
345    describe: bool,
346    keep_export: bool,
347    tab_stops: TabStops,
348    keep_view: Option<Id>,
349    overview: Overview,
350    hint: bool,
351}
352
353impl fmt::Debug for GraphEditor<'_> {
354    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
355        f.debug_struct("GraphEditor")
356            .field("label", &self.label)
357            .field("snap", &self.snap)
358            .field("requests", &self.requests)
359            .finish_non_exhaustive()
360    }
361}
362
363/// What the editor did in a frame.
364#[derive(Debug)]
365pub struct GraphOutput {
366    /// The canvas; `changed()` when an edit was proposed.
367    pub response: Response,
368    /// The edits for the application to apply, after the hook.
369    pub edits: Vec<Edit>,
370    pub events: Vec<GraphEvent>,
371    pub level: Level,
372    /// Screen points per graph unit.
373    pub zoom: f32,
374    /// The graph as drawn, when asked ([`GraphEditor::describe`]).
375    pub snapshot: Option<Json>,
376    /// A copy to export, when asked ([`GraphEditor::keep_export`]).
377    pub export: Option<GraphExport>,
378    /// While the pointer is over it: what the pointer does with the
379    /// keys held now, as the profile says, for a status line; empty
380    /// otherwise.
381    pub hint: String,
382    /// The canvas's id for the navigation commands
383    /// (`egui_pop_core::canvas::request_to`, a
384    /// [`CanvasZoom`](crate::navigation::CanvasZoom)).
385    pub canvas: Id,
386}
387
388impl<'a> GraphEditor<'a> {
389    pub fn new(model: &'a dyn GraphModel, state: &'a mut GraphState) -> GraphEditor<'a> {
390        GraphEditor {
391            model,
392            state,
393            id_salt: None,
394            label: None,
395            size: None,
396            snap: None,
397            node_width: NODE_WIDTH,
398            wires: WireStyle::Curves,
399            overview_below: 0.55,
400            detail_from: 0.9,
401            // upstream: text blurs in a Scene zoomed past 100 % (docs/upstream.md).
402            zoom_range: Rangef::new(0.05, 1.5),
403            header: None,
404            status: None,
405            hook: None,
406            requests: Vec::new(),
407            describe: false,
408            keep_export: false,
409            tab_stops: TabStops::Auto,
410            keep_view: None,
411            overview: Overview::WhenNeeded,
412            hint: true,
413        }
414    }
415
416    /// Keeps the view across sessions under `id` (egui's persisted
417    /// memory, saved with the application's): the graph opens where it
418    /// was left instead of fitted.
419    pub fn keep_view(mut self, id: impl std::hash::Hash + fmt::Debug) -> Self {
420        self.keep_view = Some(Id::unique(id));
421        self
422    }
423
424    /// When the overview (a minimap in the bottom-right corner) shows:
425    /// when the graph is much larger than the view by default.
426    pub fn overview(mut self, policy: Overview) -> Self {
427        self.overview = policy;
428        self
429    }
430
431    /// Whether the one-time navigation hint shows on the graph's first
432    /// use (on by default; once seen, never again on this installation).
433    pub fn hint(mut self, on: bool) -> Self {
434        self.hint = on;
435        self
436    }
437
438    /// Tells two editors in one `Ui` apart.
439    pub fn id_salt(mut self, salt: impl std::hash::Hash + fmt::Debug) -> Self {
440        self.id_salt = Some(Id::unique(salt));
441        self
442    }
443
444    /// The accessible name (default "Node graph").
445    pub fn label(mut self, label: impl Into<String>) -> Self {
446        self.label = Some(label.into());
447        self
448    }
449
450    /// The size in points (default: what is available).
451    pub fn size(mut self, size: Vec2) -> Self {
452        self.size = Some(size);
453        self
454    }
455
456    /// Snaps moved and added nodes to a grid of this many graph units
457    /// (and draws it); `None` (the default) moves freely.
458    pub fn snap(mut self, grid: Option<f32>) -> Self {
459        self.snap = grid.filter(|g| *g > 0.0);
460        self
461    }
462
463    /// A node's width in graph units (default 180).
464    pub fn node_width(mut self, width: f32) -> Self {
465        self.node_width = width.max(80.0);
466        self
467    }
468
469    /// How wires are drawn (default [`WireStyle::Curves`]).
470    /// [`WireStyle::Orthogonal`] routes them around the nodes; the
471    /// routes are kept in the [`GraphState`] and computed again only
472    /// when the layout changes.
473    pub fn wires(mut self, style: WireStyle) -> Self {
474        self.wires = style;
475        self
476    }
477
478    /// The zooms where the levels change: below `overview_below` the
479    /// overview, from `detail_from` the detail (defaults 0.55 and 0.9).
480    pub fn levels(mut self, overview_below: f32, detail_from: f32) -> Self {
481        self.overview_below = overview_below;
482        self.detail_from = detail_from.max(overview_below);
483        self
484    }
485
486    /// How far the zoom goes (default 0.05 to 1.5; text blurs above 1).
487    pub fn zoom_range(mut self, range: impl Into<Rangef>) -> Self {
488        self.zoom_range = range.into();
489        self
490    }
491
492    /// The application's slot in each title bar, at its right end (a
493    /// status, a toggle), in the ports and detail views.
494    pub fn header(mut self, header: impl FnMut(&mut Ui, &Node) + 'a) -> Self {
495        self.header = Some(Box::new(header));
496        self
497    }
498
499    /// Each node's status, drawn small at its title bar's right end (left
500    /// of the [`header`](GraphEditor::header) slot), in the ports and
501    /// detail views: its text in its colour, its detail as a tooltip.
502    /// `None` draws none. The status (text and detail) is part of the
503    /// node's accessible description at every level.
504    pub fn status(mut self, status: impl FnMut(&Node) -> Option<NodeStatus> + 'a) -> Self {
505        self.status = Some(Box::new(status));
506        self
507    }
508
509    /// Sees each edit before it is handed back: allow, veto or redirect
510    /// (another edit). A slider's drag frames come too (`done: false`).
511    pub fn on_edit(mut self, hook: impl FnMut(&Edit, Cause) -> Verdict<Edit> + 'a) -> Self {
512        self.hook = Some(Box::new(hook));
513        self
514    }
515
516    /// Requests done at this frame, as if by the user (an agent's
517    /// command, a menu of the application's).
518    pub fn requests(mut self, requests: impl IntoIterator<Item = Request>) -> Self {
519        self.requests.extend(requests);
520        self
521    }
522
523    /// Puts the graph as drawn in [`GraphOutput::snapshot`] (for agents
524    /// and the debug bridge; see [`describe`]).
525    pub fn describe(mut self, on: bool) -> Self {
526        self.describe = on;
527        self
528    }
529
530    /// How Tab goes through the graph: one stop for a large graph by default,
531    /// see [`TabStops`].
532    pub fn tab_stops(mut self, stops: TabStops) -> Self {
533        self.tab_stops = stops;
534        self
535    }
536
537    /// Puts a copy of the graph as drawn in [`GraphOutput::export`], to
538    /// export later (an agent's `graph.export`); see [`GraphExport`].
539    pub fn keep_export(mut self, on: bool) -> Self {
540        self.keep_export = on;
541        self
542    }
543
544    /// The graph as this editor would draw it, ready to export (its
545    /// wire style and node width, the state's selection, collapsed nodes
546    /// and folded groups, the theme's colours).
547    pub fn export(&self, ctx: &egui::Context) -> GraphExport {
548        GraphExport::capture(ctx, self.model, self.state)
549            .wires(self.wires)
550            .node_width(self.node_width)
551    }
552
553    /// The graph as an SVG image, drawn from the model and the layout
554    /// (not from the screen): the same graph and options give the same
555    /// text. See [`GraphExport::svg`].
556    pub fn export_svg(&self, ctx: &egui::Context, options: &ExportOptions) -> String {
557        self.export(ctx).svg(options)
558    }
559
560    /// The wheel, a scroll and a pinch over the graph, as the profile
561    /// says: zoom around the pointer, or pan. Takes the wheel when the
562    /// pointer is over the graph. Whether the view moved.
563    fn wheel(&mut self, ui: &Ui, outer: Rect, g: &crate::gestures::ViewGestures) -> bool {
564        use crate::gestures::ViewAction;
565        let ctx = ui.ctx();
566        if !self.state.has_view() {
567            return false;
568        }
569        if !ui.rect_contains_pointer(outer) {
570            let touch = navigation::touch_pan(ctx, outer);
571            if touch == Vec2::ZERO {
572                return false;
573            }
574            let zoom = zoom_of(outer.size(), self.state.view, self.zoom_range);
575            self.state.pan(-touch / zoom.max(1e-6));
576            return true;
577        }
578        let inputs = egui_pop_core::pointer::wheel_inputs(ctx);
579        // The scene would scroll with egui's smoothed wheel: never.
580        ctx.input_mut(|i| i.smooth_scroll_delta = Vec2::ZERO);
581        let Some(at) = ctx.input(|i| i.pointer.latest_pos()) else {
582            return false;
583        };
584        let speed = ctx.options(|o| o.input_options.scroll_zoom_speed);
585        let mut moved = false;
586        for input in &inputs {
587            let zoom = zoom_of(outer.size(), self.state.view, self.zoom_range);
588            // The graph point under the pointer (the scene fits the view
589            // in `outer`, centred).
590            let around = self.state.view.center() + (at - outer.center()) / zoom.max(1e-6);
591            match g.wheel_action(input) {
592                ViewAction::Zoom | ViewAction::ZoomFree => {
593                    let factor = if input.zoom != 1.0 {
594                        input.zoom
595                    } else {
596                        (speed * input.along_y()).exp()
597                    };
598                    let to = self.zoom_range.clamp(zoom * factor);
599                    if to != zoom {
600                        self.state.zoom_by(to / zoom, around);
601                        moved = true;
602                    }
603                }
604                a @ (ViewAction::Pan | ViewAction::PanX | ViewAction::PanY) => {
605                    let d = match a {
606                        ViewAction::PanX => vec2(input.along_x(), 0.0),
607                        ViewAction::PanY => vec2(0.0, input.along_y()),
608                        _ => input.delta,
609                    };
610                    self.state.pan(-d / zoom.max(1e-6));
611                    moved = true;
612                }
613                _ => {}
614            }
615        }
616        // Two fingers on a touch screen: the graph follows them.
617        let touch = navigation::touch_pan(ctx, outer);
618        if touch != Vec2::ZERO {
619            let zoom = zoom_of(outer.size(), self.state.view, self.zoom_range);
620            self.state.pan(-touch / zoom.max(1e-6));
621            moved = true;
622        }
623        // What the graph used is not the nodes' (a slider stepped by
624        // the wheel's modifiers keeps its wheel when the graph has none).
625        if moved {
626            egui_pop_core::pointer::take_wheel(ctx);
627        }
628        moved
629    }
630
631    /// Does a navigation command (`docs/design/navigation.md`).
632    fn navigate(&mut self, c: NavCommand, outer: Rect, nodes: &[Node]) {
633        if !self.state.has_view() {
634            if matches!(c, NavCommand::Fit | NavCommand::FrameSelection) {
635                self.state.fit = true;
636            }
637            return;
638        }
639        let zoom = zoom_of(outer.size(), self.state.view, self.zoom_range);
640        let center = self.state.view.center();
641        let zoom_to = |state: &mut GraphState, to: f32| {
642            let to = self.zoom_range.clamp(to);
643            if to > 0.0 && zoom > 0.0 {
644                state.zoom_by(to / zoom, center);
645            }
646        };
647        match c {
648            NavCommand::Fit => self.state.fit = true,
649            NavCommand::FrameSelection => {
650                let selected: Vec<Node> = nodes
651                    .iter()
652                    .filter(|n| self.state.selection.contains(&n.id))
653                    .cloned()
654                    .collect();
655                if selected.is_empty() {
656                    self.state.fit = true;
657                } else {
658                    self.state.view = fit_rect(&selected, self.node_width);
659                }
660            }
661            NavCommand::ZoomIn => zoom_to(self.state, zoom * ZOOM_STEP),
662            NavCommand::ZoomOut => zoom_to(self.state, zoom / ZOOM_STEP),
663            NavCommand::Zoom100 => zoom_to(self.state, 1.0),
664            NavCommand::ZoomTo(p) => zoom_to(self.state, p as f32 / 100.0),
665            NavCommand::Pan(d) => {
666                let step = self.state.view.size() * PAN_STEP;
667                self.state.pan(d.vec() * step);
668            }
669            NavCommand::Hand => {}
670        }
671    }
672
673    /// The level a zoom shows.
674    fn level_at(&self, zoom: f32) -> Level {
675        if zoom < self.overview_below {
676            Level::Overview
677        } else if zoom >= self.detail_from {
678            Level::Detail
679        } else {
680            Level::Ports
681        }
682    }
683
684    /// Draws the editor; says what the user asked for.
685    pub fn show(mut self, ui: &mut Ui) -> GraphOutput {
686        let ctx = ui.ctx().clone();
687        let id = ui.make_persistent_id(self.id_salt.unwrap_or(Id::unique("egui_pop_graph")));
688        let nodes = self.model.nodes();
689        let edges = self.model.edges();
690        let groups = self.model.groups();
691        let size = self.size.unwrap_or_else(|| ui.available_size());
692        let outer = Rect::from_min_size(ui.available_rect_before_wrap().min, size);
693
694        let mut requests = std::mem::take(&mut self.state.requests);
695        requests.append(&mut self.requests);
696        let mut edits = Vec::new();
697        let mut events = Vec::new();
698        let before_selection = self.state.selection.clone();
699        // Wires gone from the graph are no longer selected.
700        self.state.selected_edges.retain(|e| edges.contains(e));
701        let before_wires = self.state.selected_edges.clone();
702
703        // Requests: selections and views first, edits once checked.
704        let base = Base {
705            model: self.model,
706            nodes: &nodes,
707            edges: &edges,
708        };
709        for r in requests {
710            match r {
711                Request::Select(list) => {
712                    self.state.selection = list
713                        .into_iter()
714                        .filter(|n| nodes.iter().any(|m| m.id == *n))
715                        .collect();
716                }
717                Request::SelectWires(list) => {
718                    self.state.selected_edges =
719                        list.into_iter().filter(|e| edges.contains(e)).collect();
720                }
721                Request::Fit => self.state.fit = true,
722                Request::Level(level) => {
723                    if self.state.has_view() {
724                        let now = zoom_of(outer.size(), self.state.view, self.zoom_range);
725                        let want = match level {
726                            Level::Overview => self.overview_below * 0.7,
727                            Level::Ports => (self.overview_below + self.detail_from) / 2.0,
728                            Level::Detail => self.detail_from.max(1.0).min(self.zoom_range.max),
729                        };
730                        let c = self.state.view.center();
731                        self.state.zoom_by(want / now.max(1e-6), c);
732                    }
733                }
734                Request::Focus(node) => {
735                    if let Some(n) = nodes.iter().find(|n| n.id == node) {
736                        ctx.memory_mut(|m| m.request_focus(node_id(id, &n.id)));
737                        let r = Rect::from_min_size(
738                            pos2(n.pos[0], n.pos[1]),
739                            vec2(self.node_width, HEADER),
740                        );
741                        self.state.center_on(r.center());
742                    }
743                }
744                Request::Edit(e) => {
745                    let e = match e {
746                        Edit::Connect { from, to, replaces } => {
747                            let a = (from.clone(), Side::Output);
748                            let b = (to.clone(), Side::Input);
749                            // The wires it names that are there: a
750                            // reconnection, as one edit.
751                            let moved: Vec<Edge> =
752                                replaces.into_iter().filter(|e| edges.contains(e)).collect();
753                            match base.connect(&a, &b, &moved) {
754                                Ok(e) => e,
755                                Err(Refusal::Exists) => continue,
756                                Err(refusal) => {
757                                    refuse(&ctx, &base, &a.0, &b.0, &refusal, &mut events);
758                                    continue;
759                                }
760                            }
761                        }
762                        e => e,
763                    };
764                    propose(&mut self.hook, e, Cause::Command, &mut edits);
765                }
766            }
767        }
768
769        if let Some(key) = self.keep_view
770            && !self.state.has_view()
771            && let Some(view) = navigation::load_view(&ctx, key)
772        {
773            self.state.view = view;
774        }
775        let had_view = self.state.has_view();
776        let start_view = self.state.view;
777        let hovered = ui.rect_contains_pointer(outer)
778            && !self
779                .state
780                .overview_rect
781                .is_some_and(|r| ui.rect_contains_pointer(r));
782        for c in navigation::commands(&ctx, id, hovered, self.state.had_focus) {
783            self.navigate(c, outer, &nodes);
784        }
785        let gestures = crate::gestures::graph_gestures(&ctx);
786        if self.wheel(ui, outer, &gestures) {
787            ctx.request_repaint();
788        }
789        if self.state.fit || !self.state.has_view() {
790            self.state.view = fit_rect(&nodes, self.node_width);
791            self.state.fit = false;
792        }
793        let zoom = zoom_of(outer.size(), self.state.view, self.zoom_range);
794        egui_pop_core::canvas::set_zoom(&ctx, id, zoom);
795        let level = self.level_at(zoom);
796        if self.state.level != Some(level) {
797            if self.state.level.is_some() {
798                events.push(GraphEvent::Level(level));
799            }
800            self.state.level = Some(level);
801        }
802
803        self.state.node_width = self.node_width;
804        if self.state.wire_style != self.wires {
805            self.state.wire_style = self.wires;
806            self.state.routes.clear();
807        }
808        let label = self.label.clone().unwrap_or_else(|| tr(&ctx, &s::GRAPH));
809        let one_stop = match self.tab_stops {
810            TabStops::One => true,
811            TabStops::Each => false,
812            TabStops::Auto => nodes.len() >= ONE_STOP_FROM,
813        };
814        let statuses: HashMap<String, NodeStatus> = match self.status.as_mut() {
815            Some(f) => nodes
816                .iter()
817                .filter_map(|n| f(n).map(|s| (n.id.clone(), s)))
818                .collect(),
819            None => HashMap::new(),
820        };
821        let shown = self.state.view;
822        let mut view = shown;
823        let overview_rect = self.state.overview_rect;
824        let mut cx = Cx {
825            ctx: ctx.clone(),
826            id,
827            t: GraphTokens::of(&ctx),
828            look: WireLook::of(&ctx),
829            keys: keys(&ctx),
830            base,
831            groups: &groups,
832            level,
833            zoom,
834            node_width: self.node_width,
835            snap: self.snap,
836            state: &mut *self.state,
837            hook: &mut self.hook,
838            header: &mut self.header,
839            statuses: &statuses,
840            edits: &mut edits,
841            events: &mut events,
842            lay: Layout::default(),
843            focused: None,
844            to_global: TSTransform::IDENTITY,
845            reveal: None,
846            gestures,
847            one_stop,
848            pan_drag: pan_drag(ui, outer, overview_rect, &gestures),
849            paths: Vec::new(),
850            hover: None,
851        };
852        // The scene draws; the profile moves it (above and in `canvas`):
853        // its zoom held where it is, its own pan off, the wheel taken.
854        let scene = egui::Scene::new()
855            .zoom_range(Rangef::point(zoom))
856            .drag_pan_buttons(egui::containers::DragPanButtons::empty())
857            .sense(Sense::click_and_drag());
858        let mut draw = |ui: &mut Ui| {
859            ui.scope_builder(UiBuilder::new().max_rect(outer), |ui| {
860                scene.show(ui, &mut view, |ui| cx.content(ui))
861            })
862        };
863        let inner = if one_stop {
864            let name = format!("graph:{id:?}");
865            tab::roving(ui, &name, tab::Axis::Own, draw)
866        } else {
867            draw(ui)
868        };
869        let mut response = inner.inner.response;
870        cx.canvas(&response, &label);
871        let wire_hovered = cx.hover.is_some() && response.hovered();
872        if wire_hovered {
873            ctx.set_cursor_icon(egui::CursorIcon::PointingHand);
874        }
875        cx.state.over_canvas = response.hovered();
876        let reveal = cx.reveal.take();
877        let visible = cx.lay.visible;
878        let node_focused = cx.focused.is_some();
879        drop(cx);
880        // The scene's rect changes only by its own (rounding); a pan by a
881        // drag (`canvas`) already moved the state's view and stays.
882        if view != shown && self.state.view == shown {
883            self.state.view = view;
884        }
885        if let Some(r) = reveal
886            && !visible.contains_rect(r)
887        {
888            self.state.center_on(r.center());
889        }
890        self.state.had_focus = response.has_focus() || node_focused;
891        // The navigation model's overlays: the overview, hand mode's
892        // indicator, the one-time hint.
893        let panned = had_view && self.state.view != start_view;
894        self.state.overview_rect = None;
895        let (bounds, visible) = (self.state.drawn.bounds, self.state.drawn.visible);
896        if self.overview.shows(bounds, visible) {
897            let w = (outer.width() * 0.25).clamp(120.0, 240.0);
898            let size = vec2(w, (w * 2.0 / 3.0).round());
899            let r = Rect::from_min_size(outer.right_bottom() - size - vec2(8.0, 8.0), size);
900            if outer.contains_rect(r) {
901                // Above the scene's own layer, where the nodes are: a
902                // click on the overview is the overview's. Under a
903                // window over the canvas.
904                navigation::canvas_overlay(ui, id.with("overview"), r.min, |ui| {
905                    GraphMinimap::new(self.state).size(size).show(ui);
906                });
907                self.state.overview_rect = Some(r);
908            }
909        }
910        navigation::indicator(ui, outer, &response);
911        if self.hint {
912            navigation::hint(ui, id, outer, "graph", &response, panned);
913        }
914        if let Some(key) = self.keep_view {
915            navigation::save_view(&ctx, key, self.state.view);
916        }
917
918        if self.state.selection != before_selection {
919            events.push(GraphEvent::Selection(
920                self.state.selection.iter().cloned().collect(),
921            ));
922        }
923        if self.state.selected_edges != before_wires {
924            let count = self.state.selected_edges.len();
925            a11y::announce(
926                &ctx,
927                strings::tr_with(&ctx, &s::GRAPH_WIRES_SELECTED, &[("count", count.into())]),
928                Politeness::Polite,
929            );
930            events.push(GraphEvent::WireSelection(
931                self.state.selected_edges.iter().cloned().collect(),
932            ));
933        }
934        if !edits.is_empty() {
935            response.mark_changed();
936        }
937        let snapshot = self
938            .describe
939            .then(|| describe(self.model, &nodes, &edges, self.state));
940        let export = self.keep_export.then(|| {
941            let theme = ExportTheme::of_nodes(&ctx, &nodes);
942            GraphExport::from_parts(self.model, nodes, edges, groups, self.state, theme).faces(
943                egui_pop_core::fonts::installed_faces(&ctx, egui_pop_core::fonts::Role::Ui)
944                    .unwrap_or_default(),
945            )
946        });
947        let hint = if response.hovered() {
948            let hint = if wire_hovered {
949                tr(&ctx, &s::GRAPH_WIRE_HINT)
950            } else {
951                crate::gestures::hint(&ctx, egui_pop_core::model::pointer::SCOPE_GRAPH)
952            };
953            egui_pop_core::pointer::show_hint(&ctx, &hint);
954            hint
955        } else {
956            String::new()
957        };
958        GraphOutput {
959            response,
960            edits,
961            events,
962            level,
963            zoom,
964            snapshot,
965            export,
966            hint,
967            canvas: id,
968        }
969    }
970}
971
972/// What a zoom in or out multiplies the zoom by.
973const ZOOM_STEP: f32 = 1.25;
974/// A pan by key moves the view by this part of its size.
975const PAN_STEP: f32 = 0.1;
976
977/// The button of a drag that pans the graph this pass: one pressed on
978/// the graph (not on its overview, nor on a window above it), moving,
979/// that the profile pans with, or a primary drag in hand mode or with
980/// Space held. Read before the graph's
981/// widgets, so a node, a port or a wire under the pointer does not take
982/// the drag for its own.
983fn pan_drag(
984    ui: &Ui,
985    outer: Rect,
986    overview: Option<Rect>,
987    g: &crate::gestures::ViewGestures,
988) -> Option<egui::PointerButton> {
989    let ctx = ui.ctx();
990    let order = ui.layer_id().order;
991    let space = navigation::primary_pans(ctx);
992    if navigation::touching(ctx) {
993        // Two fingers pan (`wheel`); the first one's drag is not a pan.
994        return None;
995    }
996    ctx.input(|i| {
997        let p = &i.pointer;
998        let origin = p.press_origin()?;
999        if !p.is_decidedly_dragging()
1000            || !outer.contains(origin)
1001            || overview.is_some_and(|r| r.contains(origin))
1002        {
1003            return None;
1004        }
1005        [
1006            egui::PointerButton::Primary,
1007            egui::PointerButton::Secondary,
1008            egui::PointerButton::Middle,
1009            egui::PointerButton::Extra1,
1010            egui::PointerButton::Extra2,
1011        ]
1012        .into_iter()
1013        .find(|&b| {
1014            p.button_down(b)
1015                && (g.drag_pans(b, i.modifiers) || (space && b == egui::PointerButton::Primary))
1016        })
1017    })
1018    .filter(|_| {
1019        ctx.layer_id_at(ctx.input(|i| i.pointer.press_origin()).unwrap_or_default())
1020            .is_none_or(|l| l.order == order)
1021    })
1022}
1023
1024/// Screen points per graph unit when `view` is fitted in `size` (as
1025/// egui's `Scene` does).
1026fn zoom_of(size: Vec2, view: Rect, range: Rangef) -> f32 {
1027    if view.width() <= 0.0 || view.height() <= 0.0 {
1028        return 1.0;
1029    }
1030    range.clamp((size / view.size()).min_elem())
1031}
1032
1033/// Around every node, with a margin.
1034fn fit_rect(nodes: &[Node], width: f32) -> Rect {
1035    let mut r = Rect::NOTHING;
1036    for n in nodes {
1037        r = r.union(Rect::from_min_size(
1038            pos2(n.pos[0], n.pos[1]),
1039            vec2(width, HEADER + ROW * 3.0),
1040        ));
1041    }
1042    if !r.is_positive() {
1043        r = Rect::from_min_size(Pos2::ZERO, vec2(width * 3.0, width * 2.0));
1044    }
1045    r.expand(40.0)
1046}
1047
1048/// The edit as the hook leaves it, kept.
1049fn propose(hook: &mut Option<Box<HookFn<'_>>>, edit: Edit, cause: Cause, edits: &mut Vec<Edit>) {
1050    match hook.as_mut().map_or(Verdict::Allow, |h| h(&edit, cause)) {
1051        Verdict::Allow => edits.push(edit),
1052        Verdict::Veto => {}
1053        Verdict::Redirect(e) => edits.push(e),
1054    }
1055}
1056
1057/// Why a wire is refused, in words.
1058fn reason(ctx: &egui::Context, r: &Refusal) -> String {
1059    match r {
1060        Refusal::Types { from, to } => {
1061            tr_args(ctx, &s::GRAPH_TYPES_DIFFER, &[("from", from), ("to", to)])
1062        }
1063        Refusal::SameNode => tr(ctx, &s::GRAPH_SAME_NODE),
1064        Refusal::SameSide => tr(ctx, &s::GRAPH_SAME_SIDE),
1065        Refusal::Exists => tr(ctx, &s::GRAPH_EXISTS),
1066        Refusal::Other(text) => text.clone(),
1067    }
1068}
1069
1070/// Reports a refused wire: an event and an announcement.
1071fn refuse(
1072    ctx: &egui::Context,
1073    base: &Base<'_>,
1074    from: &PortRef,
1075    to: &PortRef,
1076    refusal: &Refusal,
1077    events: &mut Vec<GraphEvent>,
1078) {
1079    let why = reason(ctx, refusal);
1080    a11y::announce(
1081        ctx,
1082        tr_args(
1083            ctx,
1084            &s::GRAPH_REFUSED,
1085            &[
1086                ("from", &base.port_name(ctx, from)),
1087                ("to", &base.port_name(ctx, to)),
1088                ("reason", &why),
1089            ],
1090        ),
1091        Politeness::Assertive,
1092    );
1093    events.push(GraphEvent::Refused {
1094        from: from.clone(),
1095        to: to.clone(),
1096        reason: why,
1097    });
1098}
1099
1100fn node_id(id: Id, node: &str) -> Id {
1101    id.with(("node", node))
1102}
1103
1104fn port_id(id: Id, port: &PortRef, side: Side) -> Id {
1105    id.with(("port", &port.node, &port.port, side))
1106}
1107
1108/// The graph and the application's checks.
1109#[derive(Clone, Copy)]
1110struct Base<'g> {
1111    model: &'g dyn GraphModel,
1112    nodes: &'g [Node],
1113    edges: &'g [Edge],
1114}
1115
1116impl<'g> Base<'g> {
1117    fn node(&self, id: &str) -> Option<&'g Node> {
1118        self.nodes.iter().find(|n| n.id == id)
1119    }
1120
1121    fn port(&self, p: &PortRef, side: Side) -> Option<(&'g Node, &'g Port)> {
1122        let n = self.node(&p.node)?;
1123        Some((n, n.port(side, &p.port)?))
1124    }
1125
1126    /// "Blur, input Image" (or the ids when the port is gone).
1127    fn port_name(&self, ctx: &egui::Context, p: &PortRef) -> String {
1128        for side in [Side::Output, Side::Input] {
1129            if let Some((n, port)) = self.port(p, side) {
1130                return port_label(ctx, n, port, side);
1131            }
1132        }
1133        format!("{}.{}", p.node, p.port)
1134    }
1135
1136    /// The wires at a port.
1137    fn wires_at(&self, p: &PortRef, side: Side) -> Vec<Edge> {
1138        self.edges
1139            .iter()
1140            .filter(|e| match side {
1141                Side::Input => e.to == *p,
1142                Side::Output => e.from == *p,
1143            })
1144            .cloned()
1145            .collect()
1146    }
1147
1148    /// Whether a wire from `a` may end at `b` (either way round).
1149    fn check(&self, a: &(PortRef, Side), b: &(PortRef, Side)) -> Result<(), Refusal> {
1150        if a.1 == b.1 {
1151            return Err(Refusal::SameSide);
1152        }
1153        let (out, inp) = if a.1 == Side::Output { (a, b) } else { (b, a) };
1154        let from = self
1155            .port(&out.0, Side::Output)
1156            .ok_or_else(|| Refusal::Other(format!("no output `{}`", out.0.port)))?;
1157        let to = self
1158            .port(&inp.0, Side::Input)
1159            .ok_or_else(|| Refusal::Other(format!("no input `{}`", inp.0.port)))?;
1160        if from.0.id == to.0.id {
1161            return Err(Refusal::SameNode);
1162        }
1163        self.model.can_connect(from, to)
1164    }
1165
1166    /// The edit a wire from `a` to `b` makes (`detached`: the wires whose
1167    /// end it moves).
1168    fn connect(
1169        &self,
1170        a: &(PortRef, Side),
1171        b: &(PortRef, Side),
1172        detached: &[Edge],
1173    ) -> Result<Edit, Refusal> {
1174        self.check(a, b)?;
1175        let (out, inp) = if a.1 == Side::Output { (a, b) } else { (b, a) };
1176        let mut replaces: Vec<Edge> = detached.to_vec();
1177        let multiple = self
1178            .port(&inp.0, Side::Input)
1179            .is_some_and(|(_, p)| p.multiple);
1180        if !multiple {
1181            for e in self.wires_at(&inp.0, Side::Input) {
1182                if !replaces.contains(&e) {
1183                    replaces.push(e);
1184                }
1185            }
1186        }
1187        let edge = Edge::new(out.0.clone(), inp.0.clone());
1188        replaces.retain(|e| *e != edge);
1189        if replaces.is_empty() && self.edges.contains(&edge) {
1190            return Err(Refusal::Exists);
1191        }
1192        Ok(Edit::Connect {
1193            from: edge.from,
1194            to: edge.to,
1195            replaces,
1196        })
1197    }
1198}
1199
1200/// A port's accessible name: "Blur, input Image".
1201fn port_label(ctx: &egui::Context, node: &Node, port: &Port, side: Side) -> String {
1202    let key = match side {
1203        Side::Input => &s::GRAPH_PORT_INPUT,
1204        Side::Output => &s::GRAPH_PORT_OUTPUT,
1205    };
1206    tr_args(ctx, key, &[("node", &node.title), ("port", &port.label)])
1207}
1208
1209/// A box drawn: a node, or a group folded into a stack.
1210#[derive(Clone, Debug)]
1211struct Placed {
1212    rect: Rect,
1213    /// The node's index, or `None` for a stack.
1214    node: Option<usize>,
1215    /// A stack's group index.
1216    group: Option<usize>,
1217    collapsed: bool,
1218}
1219
1220/// Where everything is this frame.
1221#[derive(Clone, Debug)]
1222struct Layout {
1223    boxes: Vec<Placed>,
1224    /// Each node's box index (`None`: not drawn; in a stack, the
1225    /// stack's).
1226    box_of: Vec<Option<usize>>,
1227    /// Ports' centres, by node index, side and port index.
1228    ports: HashMap<(usize, Side, usize), Pos2>,
1229    /// The frames of unfolded groups: group index and rect (title band
1230    /// included).
1231    frames: Vec<(usize, Rect)>,
1232    /// The part of the graph in view.
1233    visible: Rect,
1234}
1235
1236impl Default for Layout {
1237    fn default() -> Self {
1238        Layout {
1239            boxes: Vec::new(),
1240            box_of: Vec::new(),
1241            ports: HashMap::new(),
1242            frames: Vec::new(),
1243            visible: Rect::NOTHING,
1244        }
1245    }
1246}
1247
1248/// One frame of the editor.
1249struct Cx<'a, 'g, 'h> {
1250    ctx: egui::Context,
1251    id: Id,
1252    t: GraphTokens,
1253    look: WireLook,
1254    keys: GraphKeys,
1255    base: Base<'g>,
1256    groups: &'g [Group],
1257    level: Level,
1258    zoom: f32,
1259    node_width: f32,
1260    snap: Option<f32>,
1261    state: &'a mut GraphState,
1262    hook: &'a mut Option<Box<HookFn<'h>>>,
1263    header: &'a mut Option<Box<HeaderFn<'h>>>,
1264    /// Each node's status, by id ([`GraphEditor::status`]).
1265    statuses: &'g HashMap<String, NodeStatus>,
1266    edits: &'a mut Vec<Edit>,
1267    events: &'a mut Vec<GraphEvent>,
1268    lay: Layout,
1269    /// The node with the keyboard focus, by index.
1270    focused: Option<usize>,
1271    to_global: TSTransform,
1272    /// A rect to bring into view (what gained the focus).
1273    reveal: Option<Rect>,
1274    /// The pointer profile's gestures on the graph.
1275    gestures: crate::gestures::ViewGestures,
1276    /// The graph is one Tab stop ([`TabStops`]).
1277    one_stop: bool,
1278    /// The button of a drag that pans the view this pass, wherever it
1279    /// started on the graph (a node, a port, a wire, the canvas): the
1280    /// profile's panning drags, and any primary drag with Space held.
1281    pan_drag: Option<egui::PointerButton>,
1282    /// The wires that answer the pointer this frame, as drawn (graph
1283    /// units): not in the overview, nor into a stack.
1284    paths: Vec<(Edge, Vec<Pos2>)>,
1285    /// The wire under the pointer.
1286    hover: Option<Edge>,
1287}
1288
1289impl Cx<'_, '_, '_> {
1290    fn propose(&mut self, edit: Edit, cause: Cause) {
1291        propose(self.hook, edit, cause, self.edits);
1292    }
1293
1294    /// Gives an accessible node its bounds on screen: egui gives those
1295    /// of the scene's layer, before its transform.
1296    // upstream: AccessKit bounds ignore layer transforms (docs/upstream.md).
1297    fn bounds(&self, id: Id, rect: Rect) {
1298        let r = self.to_global * rect;
1299        self.ctx.accesskit_node_builder(id, |node| {
1300            node.set_bounds(egui::accesskit::Rect {
1301                x0: r.min.x.into(),
1302                y0: r.min.y.into(),
1303                x1: r.max.x.into(),
1304                y1: r.max.y.into(),
1305            });
1306        });
1307    }
1308
1309    /// The pointer, in graph units.
1310    fn pointer(&self) -> Option<Pos2> {
1311        self.ctx
1312            .input(|i| i.pointer.latest_pos())
1313            .map(|p| self.to_global.inverse() * p)
1314    }
1315
1316    /// Whether a group is folded into a stack at this level.
1317    fn folded(&self, group: &str) -> bool {
1318        if self.level == Level::Overview {
1319            !self.state.unfolded.contains(group)
1320        } else {
1321            self.state.folded.contains(group)
1322        }
1323    }
1324
1325    fn toggle_fold(&mut self, group: &str) {
1326        let set = if self.level == Level::Overview {
1327            &mut self.state.unfolded
1328        } else {
1329            &mut self.state.folded
1330        };
1331        if !set.remove(group) {
1332            set.insert(group.to_string());
1333        }
1334    }
1335
1336    /// A node's place, moved with the drag under way.
1337    fn pos_of(&self, n: &Node) -> Pos2 {
1338        let p = pos2(n.pos[0], n.pos[1]);
1339        match &self.state.moving {
1340            Some(m) if m.nodes.iter().any(|(id, _)| *id == n.id) => p + m.offset,
1341            _ => p,
1342        }
1343    }
1344
1345    /// Lays the graph out.
1346    fn layout(&mut self) {
1347        let base = self.base;
1348        let folded: Vec<bool> = self.groups.iter().map(|g| self.folded(&g.id)).collect();
1349        let params = |i: usize| base.model.params(&base.nodes[i].id).len();
1350        let pos = |n: &Node| self.pos_of(n);
1351        let mut lay = lay_out(&LayoutIn {
1352            nodes: base.nodes,
1353            groups: self.groups,
1354            folded: &folded,
1355            collapsed: &self.state.collapsed,
1356            level: self.level,
1357            node_width: self.node_width,
1358            overview_h: self.overview_h(),
1359            param_h: param_h(&self.ctx),
1360            params: &params,
1361            pos: &pos,
1362        });
1363        lay.visible = self.lay.visible;
1364        self.lay = lay;
1365    }
1366
1367    /// Where a port is drawn, by reference.
1368    fn port_pos(&self, p: &PortRef, side: Side) -> Option<Pos2> {
1369        port_at(self.base.nodes, &self.lay, p, side)
1370    }
1371
1372    /// Whether ports are drawn and answer.
1373    fn ports_shown(&self, b: &Placed) -> bool {
1374        self.level != Level::Overview && b.node.is_some() && !b.collapsed
1375    }
1376
1377    /// The scene's content.
1378    fn content(&mut self, ui: &mut Ui) {
1379        self.to_global = self
1380            .ctx
1381            .layer_transform_to_global(ui.layer_id())
1382            .unwrap_or(TSTransform::IDENTITY);
1383        self.lay.visible = ui.clip_rect();
1384        self.layout();
1385        let painter = ui.painter().clone();
1386        painter.rect_filled(self.lay.visible, 0.0, self.t.background);
1387        self.paint_grid(&painter);
1388        self.groups_ui(ui, &painter);
1389        self.paint_wires(&painter);
1390        for b in 0..self.lay.boxes.len() {
1391            let placed = self.lay.boxes[b].clone();
1392            match placed.node {
1393                Some(i) => self.node_ui(ui, &painter, &placed, i),
1394                None => self.stack_ui(ui, &painter, &placed),
1395            }
1396        }
1397        self.paint_wire_ends(&painter);
1398        self.wire_ui(ui, &painter);
1399        if let Some([a, b]) = self.state.band {
1400            let r = Rect::from_two_pos(a, b);
1401            painter.rect_filled(r, 0.0, self.t.band.gamma_multiply(0.12));
1402            painter.rect_stroke(
1403                r,
1404                0.0,
1405                Stroke::new(1.0 / self.zoom, self.t.band),
1406                StrokeKind::Inside,
1407            );
1408        }
1409        self.state.drawn = state::Drawn {
1410            boxes: self
1411                .lay
1412                .boxes
1413                .iter()
1414                .map(|b| {
1415                    let sel = b
1416                        .node
1417                        .is_some_and(|i| self.state.selection.contains(&self.base.nodes[i].id));
1418                    (b.rect, sel)
1419                })
1420                .collect(),
1421            bounds: self
1422                .lay
1423                .boxes
1424                .iter()
1425                .fold(Rect::NOTHING, |r, b| r.union(b.rect)),
1426            visible: self.lay.visible,
1427            zoom: self.zoom,
1428            routes: std::mem::take(&mut self.state.drawn.routes),
1429        };
1430    }
1431
1432    fn paint_grid(&self, painter: &egui::Painter) {
1433        let mut g = self.snap.unwrap_or(24.0);
1434        while g * self.zoom < 10.0 {
1435            g *= 4.0;
1436        }
1437        let v = self.lay.visible;
1438        let stroke = Stroke::new(1.0 / self.zoom, self.t.grid.gamma_multiply(0.5));
1439        let mut x = (v.left() / g).floor() * g;
1440        while x <= v.right() {
1441            painter.vline(x, v.y_range(), stroke);
1442            x += g;
1443        }
1444        let mut y = (v.top() / g).floor() * g;
1445        while y <= v.bottom() {
1446            painter.hline(v.x_range(), y, stroke);
1447            y += g;
1448        }
1449    }
1450
1451    /// A wire's stroke width in graph units: about two points on screen.
1452    fn wire_width(&self) -> f32 {
1453        (2.0 / self.zoom).clamp(1.5, 12.0)
1454    }
1455
1456    fn bezier(&self, painter: &egui::Painter, a: Pos2, b: Pos2, color: Color32) {
1457        painter.add(egui::epaint::CubicBezierShape::from_points_stroke(
1458            export::curve(a, b),
1459            false,
1460            Color32::TRANSPARENT,
1461            Stroke::new(self.wire_width(), color),
1462        ));
1463    }
1464
1465    /// A wire from an output at `a` to an input at `b`, in the graph's
1466    /// style; an orthogonal one is a rough elbow (the wire being drawn).
1467    fn wire_line(&self, painter: &egui::Painter, a: Pos2, b: Pos2, color: Color32) {
1468        let stroke = Stroke::new(self.wire_width(), color);
1469        match self.state.wire_style {
1470            WireStyle::Curves => self.bezier(painter, a, b, color),
1471            WireStyle::Straight => {
1472                painter.line_segment([a, b], stroke);
1473            }
1474            WireStyle::Orthogonal => {
1475                painter.add(egui::Shape::line(wires::elbow(a, b).to_vec(), stroke));
1476            }
1477        }
1478    }
1479
1480    fn paint_wires(&mut self, painter: &egui::Painter) {
1481        let detached = self.state.wire.as_ref().and_then(|w| w.detached.clone());
1482        let drawn: Vec<(Edge, Pos2, Pos2, Color32)> = wires_drawn(
1483            self.base.nodes,
1484            self.base.edges,
1485            &self.lay,
1486            detached.as_ref(),
1487        )
1488        .into_iter()
1489        .map(|(e, a, b)| {
1490            let color = self
1491                .base
1492                .port(&e.from, Side::Output)
1493                .map_or(self.t.wire, |(_, p)| self.t.type_color(&self.ctx, &p.ty));
1494            (e.clone(), a, b, color)
1495        })
1496        .collect();
1497        self.state.drawn.routes.clear();
1498        let routes = if self.state.wire_style == WireStyle::Orthogonal {
1499            // Around every box drawn (nodes and stacks), cached by layout.
1500            let boxes: Vec<Rect> = self.lay.boxes.iter().map(|b| b.rect).collect();
1501            let ends: Vec<(Pos2, Pos2)> = drawn.iter().map(|&(_, a, b, _)| (a, b)).collect();
1502            self.state.routes.routes(&boxes, &ends).to_vec()
1503        } else {
1504            Vec::new()
1505        };
1506        // Each wire as a line of points, to draw and to hit.
1507        let lines: Vec<Vec<Pos2>> = drawn
1508            .iter()
1509            .enumerate()
1510            .map(|(k, &(_, a, b, _))| match self.state.wire_style {
1511                WireStyle::Orthogonal => routes.get(k).cloned().unwrap_or_else(|| vec![a, b]),
1512                WireStyle::Straight => vec![a, b],
1513                WireStyle::Curves => flatten(export::curve(a, b)),
1514            })
1515            .collect();
1516        self.paths = drawn
1517            .iter()
1518            .zip(&lines)
1519            .filter(|((e, ..), _)| self.wire_answers(e))
1520            .map(|((e, ..), line)| (e.clone(), line.clone()))
1521            .collect();
1522        // The wire under the pointer, when nothing else is under way.
1523        let idle = self.state.wire.is_none()
1524            && self.state.moving.is_none()
1525            && self.state.band.is_none()
1526            && self.ctx.dragged_id().is_none();
1527        self.hover = None;
1528        if idle
1529            && self.state.over_canvas
1530            && let Some(p) = self.pointer()
1531            && self.lay.visible.contains(p)
1532        {
1533            self.hover = self.wire_at(p).map(|(e, _)| e);
1534        }
1535        let width = self.wire_width();
1536        let look = self.look;
1537        // Screen points to graph units, held near the plain wire's bounds.
1538        let px = |w: f32| (w / self.zoom.max(1e-3)).clamp(w * 0.75, w * 6.0);
1539        for ((edge, a, b, color), line) in drawn.into_iter().zip(lines) {
1540            let selected = self.state.selected_edges.contains(&edge);
1541            let hovered = self.hover.as_ref() == Some(&edge);
1542            if selected && look.glow_width > 0.0 {
1543                // A soft glow under the wire: seen however short it is.
1544                painter.add(egui::Shape::line(
1545                    line.clone(),
1546                    Stroke::new(px(look.glow_width), look.glow),
1547                ));
1548            }
1549            // Selected: the selection's colour and width; hovered: its own
1550            // colour lightened, thicker.
1551            let (w, color) = match (selected, hovered) {
1552                (true, false) => (px(look.selected_width), look.selected),
1553                (true, true) => (
1554                    px(look.selected_width.max(look.hover_width)),
1555                    look.selected.lerp_to_gamma(look.hover, 0.25),
1556                ),
1557                (false, true) => (px(look.hover_width), color.lerp_to_gamma(look.hover, 0.5)),
1558                (false, false) => (width, color),
1559            };
1560            if self.state.wire_style == WireStyle::Curves {
1561                painter.add(egui::epaint::CubicBezierShape::from_points_stroke(
1562                    export::curve(a, b),
1563                    false,
1564                    Color32::TRANSPARENT,
1565                    Stroke::new(w, color),
1566                ));
1567            } else {
1568                painter.add(egui::Shape::line(line.clone(), Stroke::new(w, color)));
1569            }
1570            if self.state.wire_style == WireStyle::Orthogonal {
1571                self.state.drawn.routes.push((edge, line));
1572            }
1573        }
1574    }
1575
1576    /// Whether a wire answers the pointer and the keyboard: between two
1577    /// nodes whose ports are drawn, or collapsed, not into a stack nor in
1578    /// the overview.
1579    fn wire_answers(&self, e: &Edge) -> bool {
1580        if self.level == Level::Overview {
1581            return false;
1582        }
1583        let shown = |node: &str| {
1584            self.base
1585                .nodes
1586                .iter()
1587                .position(|n| n.id == node)
1588                .and_then(|i| self.lay.box_of[i])
1589                .is_some_and(|b| self.lay.boxes[b].node.is_some())
1590        };
1591        shown(&e.from.node) && shown(&e.to.node)
1592    }
1593
1594    /// The wire near a point (graph units), and whether the point is
1595    /// nearer its output end: within 6 points on screen (12 on a touch
1596    /// screen), where no node or port is.
1597    fn wire_at(&self, p: Pos2) -> Option<(Edge, bool)> {
1598        if self.lay.boxes.iter().any(|b| b.rect.contains(p)) {
1599            return None;
1600        }
1601        let near_port = self.lay.ports.iter().any(|(&(i, _, _), &at)| {
1602            self.lay.box_of[i].is_some_and(|b| self.ports_shown(&self.lay.boxes[b]))
1603                && Rect::from_center_size(at, Vec2::splat(PORT_HIT)).contains(p)
1604        });
1605        if near_port {
1606            return None;
1607        }
1608        let touch = self.ctx.input(|i| i.has_touch_screen());
1609        let reach = if touch { WIRE_HIT_TOUCH } else { WIRE_HIT } / self.zoom.max(1e-3);
1610        let mut best: Option<(f32, usize, bool)> = None;
1611        for (k, (_, line)) in self.paths.iter().enumerate() {
1612            if let Some((d, along)) = distance_along(line, p)
1613                && d <= reach
1614                && best.is_none_or(|(bd, ..)| d < bd)
1615            {
1616                best = Some((d, k, along < 0.5));
1617            }
1618        }
1619        best.map(|(_, k, out)| (self.paths[k].0.clone(), out))
1620    }
1621
1622    /// A wire's line as drawn this frame.
1623    fn path_of(&self, e: &Edge) -> Option<&[Pos2]> {
1624        self.paths
1625            .iter()
1626            .find(|(x, _)| x == e)
1627            .map(|(_, l)| l.as_slice())
1628    }
1629
1630    /// Over the nodes: the hovered wire's ports ringed, and on the hovered
1631    /// and selected wires a handle near each end (a drag there moves that
1632    /// end).
1633    fn paint_wire_ends(&self, painter: &egui::Painter) {
1634        let r = 3.5 / self.zoom.max(0.25);
1635        let handle = HANDLE / self.zoom.max(1e-3);
1636        for (e, line) in &self.paths {
1637            let hovered = self.hover.as_ref() == Some(e);
1638            let selected = self.state.selected_edges.contains(e);
1639            if !hovered && !selected {
1640                continue;
1641            }
1642            let color = if selected {
1643                self.look.selected
1644            } else {
1645                self.base
1646                    .port(&e.from, Side::Output)
1647                    .map_or(self.t.wire, |(_, p)| self.t.type_color(&self.ctx, &p.ty))
1648            };
1649            // Its two ports ringed, wider and thicker when selected.
1650            let (ring, ring_w) = if selected {
1651                (PORT_R + 4.0, 2.5)
1652            } else {
1653                (PORT_R + 3.0, 2.0)
1654            };
1655            for (p, side) in [(&e.from, Side::Output), (&e.to, Side::Input)] {
1656                if let Some(at) = self.port_pos(p, side) {
1657                    painter.circle_stroke(
1658                        at,
1659                        ring,
1660                        Stroke::new(ring_w / self.zoom.max(0.5), color),
1661                    );
1662                }
1663            }
1664            for at in [point_along(line, handle), point_along_back(line, handle)] {
1665                if selected {
1666                    // Larger, filled with the selection's colour, a ring
1667                    // of the node's colour around it.
1668                    painter.circle(
1669                        at,
1670                        r * 1.6,
1671                        color,
1672                        Stroke::new(1.5 / self.zoom.max(0.5), self.t.node),
1673                    );
1674                } else {
1675                    painter.circle(
1676                        at,
1677                        r,
1678                        self.t.node,
1679                        Stroke::new(1.5 / self.zoom.max(0.5), color),
1680                    );
1681                }
1682            }
1683        }
1684    }
1685
1686    /// The nodes of a group.
1687    fn members(&self, g: usize) -> Vec<String> {
1688        let id = &self.groups[g].id;
1689        self.base
1690            .nodes
1691            .iter()
1692            .filter(|n| n.group.as_deref() == Some(id.as_str()))
1693            .map(|n| n.id.clone())
1694            .collect()
1695    }
1696
1697    /// Starts moving these nodes.
1698    fn start_move(&mut self, nodes: Vec<String>) {
1699        let nodes = nodes
1700            .into_iter()
1701            .filter_map(|id| {
1702                let n = self.base.node(&id)?;
1703                Some((id, n.pos))
1704            })
1705            .collect();
1706        self.state.moving = Some(Moving {
1707            nodes,
1708            offset: Vec2::ZERO,
1709        });
1710    }
1711
1712    /// A drag of a box or a frame: moves, then one edit at its end.
1713    fn drag_move(&mut self, ui: &Ui, r: &Response) {
1714        if r.dragged_by(egui::PointerButton::Primary) && self.state.moving.is_some() {
1715            egui_pop_core::pointer::hold_drag_cursor(&self.ctx, DragKind::Move);
1716        } else if !r.dragged() {
1717            egui_pop_core::pointer::drag_cursor(r, DragKind::Move);
1718        }
1719        if r.dragged_by(egui::PointerButton::Primary)
1720            && let Some(m) = &mut self.state.moving
1721        {
1722            m.offset += r.drag_delta();
1723        }
1724        if r.drag_stopped() {
1725            let cancelled = egui_pop_core::focus::cancel_pressed(ui.ctx(), self.keys.cancel);
1726            if let Some(m) = self.state.moving.take()
1727                && !cancelled
1728                && m.offset != Vec2::ZERO
1729            {
1730                let moves = m
1731                    .nodes
1732                    .into_iter()
1733                    .map(|(node, from)| Moved {
1734                        to: self.snapped(pos2(from[0], from[1]) + m.offset),
1735                        node,
1736                        from,
1737                    })
1738                    .collect();
1739                self.propose(Edit::Move { moves }, Cause::Drag);
1740            }
1741        }
1742    }
1743
1744    fn snapped(&self, p: Pos2) -> [f32; 2] {
1745        match self.snap {
1746            Some(g) => [(p.x / g).round() * g, (p.y / g).round() * g],
1747            None => [p.x, p.y],
1748        }
1749    }
1750
1751    fn groups_ui(&mut self, ui: &mut Ui, painter: &egui::Painter) {
1752        let radius = CornerRadius::same(6);
1753        for (g, r) in self.lay.frames.clone() {
1754            painter.rect_filled(r, radius, self.t.group.gamma_multiply(0.45));
1755            painter.rect_stroke(
1756                r,
1757                radius,
1758                Stroke::new(1.0 / self.zoom.max(0.5), self.t.group_border),
1759                StrokeKind::Inside,
1760            );
1761            let band = Rect::from_min_size(r.min, vec2(r.width(), GROUP_LABEL));
1762            let label = self.groups[g].label.clone();
1763            painter.text(
1764                band.left_center() + vec2(PAD + 2.0, 0.0),
1765                egui::Align2::LEFT_CENTER,
1766                &label,
1767                FontId::proportional(Tokens::of(&self.ctx).font.small),
1768                self.t.text_muted,
1769            );
1770            let gid = self.id.with(("group", &self.groups[g].id));
1771            let resp = ui.interact(band, gid, Sense::click_and_drag());
1772            let name = tr_args(&self.ctx, &s::GRAPH_FOLD, &[("group", &label)]);
1773            a11y::name(&resp, egui::Role::Button, &name);
1774            self.bounds(gid, band);
1775            if resp.has_focus() {
1776                egui_pop_core::focus::own_ring(&resp.ctx, resp.id);
1777                self.ring(painter, band);
1778            }
1779            if resp.clicked() {
1780                let id = self.groups[g].id.clone();
1781                self.toggle_fold(&id);
1782            }
1783            if resp.drag_started_by(egui::PointerButton::Primary) && self.pan_drag.is_none() {
1784                let members = self.members(g);
1785                self.start_move(members);
1786            }
1787            self.drag_move(ui, &resp);
1788        }
1789    }
1790
1791    /// The focus ring around a part, only while the focus is visible
1792    /// ([`egui_pop_core::focus::ring_shown`]).
1793    fn ring(&self, painter: &egui::Painter, r: Rect) {
1794        if !egui_pop_core::focus::ring_shown(&self.ctx) {
1795            return;
1796        }
1797        painter.rect_stroke(
1798            r.expand(3.0 / self.zoom),
1799            CornerRadius::same(7),
1800            Stroke::new(2.0 / self.zoom.max(0.25), self.t.focus),
1801            StrokeKind::Outside,
1802        );
1803    }
1804
1805    /// A title, cut to its width, at a size readable at this zoom.
1806    fn title(&self, painter: &egui::Painter, rect: Rect, text: &str, size: f32, color: Color32) {
1807        let mut job =
1808            LayoutJob::simple_singleline(text.to_string(), FontId::proportional(size), color);
1809        job.wrap = TextWrapping {
1810            max_width: rect.width().max(1.0),
1811            max_rows: 1,
1812            break_anywhere: true,
1813            overflow_character: Some('…'),
1814        };
1815        let galley = painter.layout_job(job);
1816        let pos = pos2(rect.left(), rect.center().y - galley.size().y / 2.0);
1817        painter.galley(pos, galley, color);
1818    }
1819
1820    /// A node's height in the overview.
1821    fn overview_h(&self) -> f32 {
1822        overview_height(Tokens::of(&self.ctx).font.body, self.zoom)
1823    }
1824
1825    /// The title's font size: in the overview, near half the node's
1826    /// height (readable when zoomed out), else the body's.
1827    fn title_size(&self) -> f32 {
1828        if self.level == Level::Overview {
1829            (self.overview_h() * 0.45).round()
1830        } else {
1831            Tokens::of(&self.ctx).font.body
1832        }
1833    }
1834
1835    fn stack_ui(&mut self, ui: &mut Ui, painter: &egui::Painter, b: &Placed) {
1836        let Some(g) = b.group else { return };
1837        let r = b.rect;
1838        let radius = CornerRadius::same(6);
1839        // The stack's depth: two edges behind.
1840        for k in [2.0, 1.0] {
1841            let off = vec2(6.0, 6.0) * k;
1842            painter.rect_filled(r.translate(off), radius, self.t.node_header);
1843            painter.rect_stroke(
1844                r.translate(off),
1845                radius,
1846                Stroke::new(1.0 / self.zoom.max(0.5), self.t.node_border),
1847                StrokeKind::Inside,
1848            );
1849        }
1850        painter.rect_filled(r, radius, self.t.node);
1851        let members = self.members(g);
1852        let selected = members.iter().any(|m| self.state.selection.contains(m));
1853        painter.rect_stroke(
1854            r,
1855            radius,
1856            Stroke::new(
1857                if selected { 2.0 } else { 1.0 } / self.zoom.max(0.5),
1858                if selected {
1859                    self.t.node_selected
1860                } else {
1861                    self.t.node_border
1862                },
1863            ),
1864            StrokeKind::Inside,
1865        );
1866        let label = self.groups[g].label.clone();
1867        let count = members.len().to_string();
1868        let size = self.title_size();
1869        let badge = format!("+{count}");
1870        let text_r = Rect::from_min_max(
1871            r.min + vec2(PAD * 2.0, 0.0),
1872            pos2(r.right() - PAD * 2.0 - size * 2.0, r.max.y),
1873        );
1874        self.title(painter, text_r, &label, size, self.t.text);
1875        painter.text(
1876            r.right_center() - vec2(PAD * 2.0, 0.0),
1877            egui::Align2::RIGHT_CENTER,
1878            badge,
1879            FontId::proportional(size * 0.85),
1880            self.t.text_muted,
1881        );
1882        let sid = self.id.with(("stack", &self.groups[g].id));
1883        let resp = ui.interact(r, sid, Sense::click_and_drag());
1884        let name = strings::tr_with(
1885            &self.ctx,
1886            &s::GRAPH_UNFOLD,
1887            &[("group", Arg::Str(&label)), ("count", members.len().into())],
1888        );
1889        a11y::name(&resp, egui::Role::Button, &name);
1890        let role = tr(&self.ctx, &s::GRAPH_ROLE_STACK);
1891        self.ctx.accesskit_node_builder(sid, |node| {
1892            node.set_role_description(role);
1893        });
1894        self.bounds(sid, r);
1895        if resp.has_focus() {
1896            egui_pop_core::focus::own_ring(&resp.ctx, resp.id);
1897            self.ring(painter, r);
1898        }
1899        if resp.clicked() {
1900            let id = self.groups[g].id.clone();
1901            self.toggle_fold(&id);
1902        }
1903        if resp.drag_started_by(egui::PointerButton::Primary) && self.pan_drag.is_none() {
1904            self.start_move(members);
1905        }
1906        self.drag_move(ui, &resp);
1907    }
1908
1909    fn node_ui(&mut self, ui: &mut Ui, painter: &egui::Painter, b: &Placed, i: usize) {
1910        let base = self.base;
1911        let n = &base.nodes[i];
1912        let r = b.rect;
1913        let selected = self.state.selection.contains(&n.id);
1914        let radius = CornerRadius::same(6);
1915        let header = Rect::from_min_size(
1916            r.min,
1917            vec2(
1918                r.width(),
1919                if self.level == Level::Overview {
1920                    r.height()
1921                } else {
1922                    HEADER
1923                },
1924            ),
1925        );
1926        painter.rect_filled(r, radius, self.t.node);
1927        if self.level != Level::Overview {
1928            painter.rect_filled(
1929                header,
1930                CornerRadius {
1931                    nw: 6,
1932                    ne: 6,
1933                    sw: if b.collapsed { 6 } else { 0 },
1934                    se: if b.collapsed { 6 } else { 0 },
1935                },
1936                self.t.node_header,
1937            );
1938        }
1939        // The colour of what it gives, as a band on the left.
1940        if let Some(p) = n.outputs.first().or(n.inputs.first()) {
1941            let band = Rect::from_min_size(r.min, vec2(4.0, header.height()));
1942            painter.rect_filled(
1943                band,
1944                CornerRadius {
1945                    nw: 6,
1946                    sw: if self.level == Level::Overview || b.collapsed {
1947                        6
1948                    } else {
1949                        0
1950                    },
1951                    ne: 0,
1952                    se: 0,
1953                },
1954                self.t.type_color(&self.ctx, &p.ty),
1955            );
1956        }
1957        painter.rect_stroke(
1958            r,
1959            radius,
1960            Stroke::new(
1961                if selected { 2.5 } else { 1.0 } / self.zoom.max(0.5),
1962                if selected {
1963                    self.t.node_selected
1964                } else {
1965                    self.t.node_border
1966                },
1967            ),
1968            StrokeKind::Inside,
1969        );
1970
1971        // The node: a click selects, a drag moves the selection.
1972        let nid = node_id(self.id, &n.id);
1973        let resp = ui.interact(r, nid, Sense::click_and_drag());
1974        let wires = base.edges.iter().filter(|e| e.touches(&n.id)).count();
1975        let value = strings::tr_with(
1976            &self.ctx,
1977            &s::GRAPH_NODE_VALUE,
1978            &[
1979                ("inputs", n.inputs.len().into()),
1980                ("outputs", n.outputs.len().into()),
1981                ("wires", wires.into()),
1982            ],
1983        );
1984        let enabled = ui.is_enabled();
1985        let title = n.title.clone();
1986        resp.widget_info(|| {
1987            let mut info = egui::WidgetInfo::labeled(egui::Role::Unknown, enabled, &title);
1988            info.current_text_value = Some(value.clone());
1989            info.selected = Some(selected);
1990            info
1991        });
1992        let role = tr(&self.ctx, &s::GRAPH_ROLE_NODE);
1993        let status = self.statuses.get(&n.id).map(NodeStatus::description);
1994        self.ctx.accesskit_node_builder(nid, |node| {
1995            node.set_role(Role::Group);
1996            node.set_role_description(role);
1997            node.set_selected(selected);
1998            if let Some(status) = status {
1999                node.set_description(status);
2000            }
2001        });
2002        self.bounds(nid, r);
2003        if resp.has_focus() {
2004            egui_pop_core::focus::own_ring(&resp.ctx, resp.id);
2005            self.focused = Some(i);
2006            self.ring(painter, r);
2007            lock_keys(ui, nid, false);
2008        }
2009        if resp.gained_focus() {
2010            self.reveal = Some(r);
2011        }
2012        if resp.clicked() {
2013            resp.request_focus();
2014            self.click_select(ui, &n.id);
2015            if self.state.wire.as_ref().is_some_and(|w| !w.by_pointer) {
2016                self.state.wire = None;
2017            }
2018        }
2019        if resp.double_clicked() && self.level != Level::Overview {
2020            self.toggle_collapsed(&n.id);
2021        }
2022        if resp.drag_started_by(egui::PointerButton::Primary) && self.pan_drag.is_none() {
2023            if !selected {
2024                self.state.selection = BTreeSet::from([n.id.clone()]);
2025            }
2026            let list = self.state.selection.iter().cloned().collect();
2027            self.start_move(list);
2028        }
2029        self.drag_move(ui, &resp);
2030        self.node_menu(&resp, n);
2031        if self.one_stop {
2032            // Its parts: Enter goes into them, Escape back.
2033            let name = format!("graph-node:{nid:?}");
2034            tab::parts(ui, &name, nid, |ui| {
2035                self.node_parts(ui, painter, b, i, header);
2036            });
2037        } else {
2038            self.node_parts(ui, painter, b, i, header);
2039        }
2040    }
2041
2042    /// A node's parts: its title bar's chevron and slot, its ports, its
2043    /// parameters.
2044    fn node_parts(
2045        &mut self,
2046        ui: &mut Ui,
2047        painter: &egui::Painter,
2048        b: &Placed,
2049        i: usize,
2050        header: Rect,
2051    ) {
2052        let base = self.base;
2053        let n = &base.nodes[i];
2054        let r = b.rect;
2055        let nid = node_id(self.id, &n.id);
2056        // The title bar: the chevron, the title, the application's slot.
2057        let mut text_left = r.left() + PAD * 2.0;
2058        if self.level != Level::Overview {
2059            let c = Rect::from_center_size(
2060                pos2(r.left() + PAD + CHEVRON / 2.0 + 2.0, header.center().y),
2061                Vec2::splat(CHEVRON),
2062            );
2063            let icon = if b.collapsed {
2064                Icon::ChevronRight
2065            } else {
2066                Icon::ChevronDown
2067            };
2068            let cid = nid.with("chevron");
2069            let cr = ui.interact(c, cid, Sense::click());
2070            icon.paint(
2071                painter,
2072                c,
2073                if cr.hovered() {
2074                    self.t.text
2075                } else {
2076                    self.t.text_muted
2077                },
2078            );
2079            let key = if b.collapsed {
2080                &s::GRAPH_EXPAND
2081            } else {
2082                &s::GRAPH_COLLAPSE
2083            };
2084            a11y::name(
2085                &cr,
2086                egui::Role::Button,
2087                &tr_args(&self.ctx, key, &[("node", &n.title)]),
2088            );
2089            self.bounds(cid, c);
2090            if cr.has_focus() {
2091                egui_pop_core::focus::own_ring(&cr.ctx, cr.id);
2092                self.ring(painter, c);
2093            }
2094            if cr.clicked() {
2095                self.toggle_collapsed(&n.id);
2096            }
2097            text_left = c.right() + PAD;
2098        }
2099        let slot_w = if self.header.is_some() && self.level != Level::Overview {
2100            72.0
2101        } else {
2102            0.0
2103        };
2104        let mut title_right = header.right() - PAD - slot_w;
2105        if self.level != Level::Overview
2106            && let Some(status) = self.statuses.get(&n.id)
2107        {
2108            title_right = self.status_ui(ui, painter, nid, status, text_left, title_right, header);
2109        }
2110        let title_r = Rect::from_min_max(
2111            pos2(text_left, header.top()),
2112            pos2(title_right, header.bottom()),
2113        );
2114        self.title(painter, title_r, &n.title, self.title_size(), self.t.text);
2115        if slot_w > 0.0
2116            && let Some(h) = self.header.as_mut()
2117        {
2118            let slot = Rect::from_min_max(
2119                pos2(header.right() - PAD - slot_w, header.top()),
2120                pos2(header.right() - PAD, header.bottom()),
2121            );
2122            ui.scope_builder(
2123                UiBuilder::new()
2124                    .max_rect(slot)
2125                    .id_salt(("header", &n.id))
2126                    .layout(egui::Layout::right_to_left(egui::Align::Center)),
2127                |ui| h(ui, n),
2128            );
2129        }
2130
2131        if !self.ports_shown(b) {
2132            return;
2133        }
2134        self.ports_ui(ui, painter, i, r);
2135        if self.level == Level::Detail {
2136            self.params_ui(ui, i, r);
2137        }
2138    }
2139
2140    /// A node's status at the right end of its title bar, up to
2141    /// `right`, never past half the room from `left`: its text small in
2142    /// its colour, elided, its detail (or its whole text when elided) as
2143    /// a tooltip. Gives where the title ends.
2144    #[allow(
2145        clippy::too_many_arguments,
2146        reason = "independent inputs of one drawing or step; a struct would bundle them for this call only"
2147    )]
2148    fn status_ui(
2149        &self,
2150        ui: &mut Ui,
2151        painter: &egui::Painter,
2152        nid: Id,
2153        status: &NodeStatus,
2154        left: f32,
2155        right: f32,
2156        header: Rect,
2157    ) -> f32 {
2158        let tokens = Tokens::of(&self.ctx);
2159        let color = status.color.resolve(&tokens);
2160        let room = ((right - left) / 2.0).max(0.0);
2161        let mut job = LayoutJob::simple_singleline(
2162            status.text.clone(),
2163            FontId::proportional(tokens.font.small),
2164            color,
2165        );
2166        job.wrap = TextWrapping {
2167            max_width: room.max(1.0),
2168            max_rows: 1,
2169            break_anywhere: true,
2170            overflow_character: Some('…'),
2171        };
2172        let galley = painter.layout_job(job);
2173        let w = galley.size().x;
2174        let rect = Rect::from_min_max(pos2(right - w, header.top()), pos2(right, header.bottom()));
2175        painter.galley(
2176            pos2(rect.left(), header.center().y - galley.size().y / 2.0),
2177            galley.clone(),
2178            color,
2179        );
2180        let elided = galley.rows.iter().any(|r| r.ends_with_newline) || {
2181            let full = painter.layout_no_wrap(
2182                status.text.clone(),
2183                FontId::proportional(tokens.font.small),
2184                color,
2185            );
2186            full.size().x > w + 0.5
2187        };
2188        let tip = match (&status.detail, elided) {
2189            (Some(d), true) => Some(format!("{}: {d}", status.text)),
2190            (Some(d), false) => Some(d.clone()),
2191            (None, true) => Some(status.text.clone()),
2192            (None, false) => None,
2193        };
2194        if let Some(tip) = tip {
2195            let r = ui.interact(rect, nid.with("status"), Sense::hover());
2196            r.on_hover_text(tip);
2197        }
2198        rect.left() - PAD
2199    }
2200
2201    fn click_select(&mut self, ui: &Ui, node: &str) {
2202        let m = ui.input(|i| i.modifiers);
2203        if m.command || m.shift {
2204            if !self.state.selection.remove(node) {
2205                self.state.selection.insert(node.to_string());
2206            }
2207        } else {
2208            self.state.selection = BTreeSet::from([node.to_string()]);
2209            self.state.selected_edges.clear();
2210        }
2211    }
2212
2213    /// A click on a wire: selects it alone, or with Ctrl (Cmd) or Shift
2214    /// adds it to the selection (or takes it out).
2215    fn click_wire(&mut self, e: &Edge, add: bool) {
2216        if add {
2217            if !self.state.selected_edges.remove(e) {
2218                self.state.selected_edges.insert(e.clone());
2219            }
2220        } else {
2221            self.state.selection.clear();
2222            self.state.selected_edges = BTreeSet::from([e.clone()]);
2223        }
2224    }
2225
2226    /// Picks a wire's end up, as a wire being drawn from its other end: its
2227    /// output end (`output`) or its input end.
2228    fn pick_end(&mut self, e: &Edge, output: bool, by_pointer: bool) {
2229        let (from, side) = if output {
2230            (e.to.clone(), Side::Input)
2231        } else {
2232            (e.from.clone(), Side::Output)
2233        };
2234        self.state.wire = Some(Wire {
2235            from,
2236            side,
2237            by_pointer,
2238            detached: Some(e.clone()),
2239        });
2240        let (f, t) = self.wire_ends(e);
2241        let key = if output {
2242            &s::GRAPH_WIRE_OUTPUT_PICKED
2243        } else {
2244            &s::GRAPH_WIRE_INPUT_PICKED
2245        };
2246        a11y::announce(
2247            &self.ctx,
2248            tr_args(&self.ctx, key, &[("from", &f), ("to", &t)]),
2249            Politeness::Polite,
2250        );
2251    }
2252
2253    /// A wire's tooltip: "Load · Image to Blur · Image".
2254    fn wire_tip(&self, e: &Edge) -> String {
2255        let part = |p: &PortRef, side: Side| match self.base.port(p, side) {
2256            Some((n, q)) => (n.title.clone(), q.label.clone()),
2257            None => (p.node.clone(), p.port.clone()),
2258        };
2259        let (a, b) = (part(&e.from, Side::Output), part(&e.to, Side::Input));
2260        tr_args(
2261            &self.ctx,
2262            &s::GRAPH_WIRE_TIP,
2263            &[
2264                ("from_node", &a.0),
2265                ("from_port", &a.1),
2266                ("to_node", &b.0),
2267                ("to_port", &b.1),
2268            ],
2269        )
2270    }
2271
2272    /// A connected input's wire as a part of its node, after the port: the
2273    /// keyboard reaches it, an assistive technology names it. Delete
2274    /// disconnects it, Enter picks its input end up and Shift+Enter its
2275    /// output end, Escape goes back to the port.
2276    fn wire_stop(&mut self, ui: &mut Ui, painter: &egui::Painter, e: &Edge, port: Id, at: Pos2) {
2277        let wid = self.id.with(("wire", e));
2278        // Not under the pointer: the canvas answers it on the wire.
2279        let resp = ui.interact(
2280            Rect::from_center_size(at, Vec2::splat(1.0)),
2281            wid,
2282            Sense::focusable_noninteractive(),
2283        );
2284        let (f, t) = self.wire_ends(e);
2285        let name = tr_args(&self.ctx, &s::GRAPH_WIRE_NAME, &[("from", &f), ("to", &t)]);
2286        let selected = self.state.selected_edges.contains(e);
2287        let enabled = ui.is_enabled();
2288        resp.widget_info(|| {
2289            let mut info = egui::WidgetInfo::labeled(egui::Role::Button, enabled, &name);
2290            info.selected = Some(selected);
2291            info
2292        });
2293        let role = tr(&self.ctx, &s::GRAPH_ROLE_WIRE);
2294        let keys = tr(&self.ctx, &s::GRAPH_WIRE_KEYS);
2295        self.ctx.accesskit_node_builder(wid, |node| {
2296            node.set_role_description(role);
2297            node.set_description(keys);
2298            node.set_selected(selected);
2299        });
2300        let line = self.path_of(e).map(<[Pos2]>::to_vec);
2301        let bounds = line
2302            .as_ref()
2303            .map_or(Rect::from_center_size(at, Vec2::splat(PORT_HIT)), |l| {
2304                Rect::from_points(l)
2305            });
2306        self.bounds(wid, bounds);
2307        if resp.gained_focus() {
2308            self.reveal = Some(bounds);
2309        }
2310        if !resp.has_focus() {
2311            return;
2312        }
2313        egui_pop_core::focus::own_ring(&resp.ctx, resp.id);
2314        if let Some(l) = line.filter(|_| egui_pop_core::focus::ring_shown(&resp.ctx)) {
2315            painter.add(egui::Shape::line(
2316                l,
2317                Stroke::new(self.wire_width() * 2.5, self.t.focus),
2318            ));
2319        }
2320        lock_keys(ui, wid, true);
2321        let k = self.keys;
2322        let (delete, output, input, cancel) = ui.input_mut(|i| {
2323            // Shift+Enter first: a plain Enter's pattern takes it too.
2324            let output = i.consume_key(Modifiers::SHIFT, Key::Enter);
2325            (
2326                k.delete
2327                    .iter()
2328                    .any(|key| i.consume_key(Modifiers::NONE, *key)),
2329                output,
2330                !output && i.consume_key(Modifiers::NONE, Key::Enter),
2331                i.consume_key(Modifiers::NONE, k.cancel),
2332            )
2333        });
2334        if delete {
2335            self.disconnect(vec![e.clone()], Cause::Key);
2336            ui.memory_mut(|m| m.request_focus(port));
2337        } else if input || output {
2338            self.pick_end(e, output, false);
2339        } else if cancel && self.state.wire.take().is_none() {
2340            ui.memory_mut(|m| m.request_focus(port));
2341        }
2342        let _ = claim::context_menu(&resp, |ui| self.wire_menu_items(ui, e));
2343    }
2344
2345    /// A wire's ports' names.
2346    fn wire_ends(&self, e: &Edge) -> (String, String) {
2347        let name = |p: &PortRef, side: Side| match self.base.port(p, side) {
2348            Some((n, q)) => port_label(&self.ctx, n, q, side),
2349            None => format!("{}.{}", p.node, p.port),
2350        };
2351        (name(&e.from, Side::Output), name(&e.to, Side::Input))
2352    }
2353
2354    /// Removes wires: one edit, announced.
2355    fn disconnect(&mut self, edges: Vec<Edge>, cause: Cause) {
2356        if edges.is_empty() {
2357            return;
2358        }
2359        for e in &edges {
2360            let (f, t) = self.wire_ends(e);
2361            a11y::announce(
2362                &self.ctx,
2363                tr_args(
2364                    &self.ctx,
2365                    &s::GRAPH_DISCONNECTED,
2366                    &[("from", &f), ("to", &t)],
2367                ),
2368                Politeness::Polite,
2369            );
2370        }
2371        self.propose(Edit::Disconnect { edges }, cause);
2372    }
2373
2374    /// A wire's menu: disconnect it, select the node at either end.
2375    fn wire_menu_items(&mut self, ui: &mut Ui, e: &Edge) {
2376        let ctx = self.ctx.clone();
2377        if ui.button(tr(&ctx, &s::GRAPH_DISCONNECT)).clicked() {
2378            self.disconnect(vec![e.clone()], Cause::Command);
2379            ui.close();
2380        }
2381        for (key, node) in [
2382            (&s::GRAPH_SELECT_SOURCE, &e.from.node),
2383            (&s::GRAPH_SELECT_DESTINATION, &e.to.node),
2384        ] {
2385            if ui.button(tr(&ctx, key)).clicked() {
2386                self.state.selection = BTreeSet::from([node.clone()]);
2387                self.state.selected_edges.clear();
2388                ui.close();
2389            }
2390        }
2391    }
2392
2393    fn toggle_collapsed(&mut self, node: &str) {
2394        if !self.state.collapsed.remove(node) {
2395            self.state.collapsed.insert(node.to_string());
2396        }
2397    }
2398
2399    fn node_menu(&mut self, resp: &Response, n: &Node) {
2400        let ctx = self.ctx.clone();
2401        let mut chosen = None;
2402        let _ = claim::context_menu(resp, |ui| {
2403            if ui.button(tr(&ctx, &s::GRAPH_DUPLICATE)).clicked() {
2404                chosen = Some(0);
2405                ui.close();
2406            }
2407            if ui.button(tr(&ctx, &s::GRAPH_DELETE)).clicked() {
2408                chosen = Some(1);
2409                ui.close();
2410            }
2411        });
2412        if let Some(c) = chosen {
2413            if !self.state.selection.contains(&n.id) {
2414                self.state.selection = BTreeSet::from([n.id.clone()]);
2415                self.state.selected_edges.clear();
2416            }
2417            if c == 0 {
2418                self.duplicate(Cause::Command);
2419            } else {
2420                self.delete(Cause::Command);
2421            }
2422        }
2423    }
2424
2425    fn ports_ui(&mut self, ui: &mut Ui, painter: &egui::Painter, i: usize, r: Rect) {
2426        let base = self.base;
2427        let n = &base.nodes[i];
2428        let small = FontId::proportional(Tokens::of(&self.ctx).font.small);
2429        let order: Vec<(Side, usize)> = (0..n.inputs.len())
2430            .map(|k| (Side::Input, k))
2431            .chain((0..n.outputs.len()).map(|k| (Side::Output, k)))
2432            .collect();
2433        for (o, &(side, k)) in order.iter().enumerate() {
2434            let port = match side {
2435                Side::Input => &n.inputs[k],
2436                Side::Output => &n.outputs[k],
2437            };
2438            let Some(&at) = self.lay.ports.get(&(i, side, k)) else {
2439                continue;
2440            };
2441            let pref = PortRef::new(n.id.clone(), port.id.clone());
2442            let color = self.t.type_color(&self.ctx, &port.ty);
2443            // While a wire is drawn: lit where it may end, dimmed where
2444            // it may not.
2445            let fit = self.state.wire.as_ref().map(|w| {
2446                w.from == pref && w.side == side
2447                    || base
2448                        .check(&(w.from.clone(), w.side), &(pref.clone(), side))
2449                        .is_ok()
2450            });
2451            let fill = if fit == Some(false) {
2452                color.gamma_multiply(0.3)
2453            } else {
2454                color
2455            };
2456            let wired = !base.wires_at(&pref, side).is_empty();
2457            painter.circle(
2458                at,
2459                PORT_R,
2460                if wired { fill } else { self.t.node },
2461                Stroke::new(1.5, fill),
2462            );
2463            if fit == Some(true) {
2464                painter.circle_stroke(at, PORT_R + 3.0, Stroke::new(1.5, self.t.wire_preview));
2465            }
2466            let (text_at, align) = match side {
2467                Side::Input => (at + vec2(PORT_R + 5.0, 0.0), egui::Align2::LEFT_CENTER),
2468                Side::Output => (at - vec2(PORT_R + 5.0, 0.0), egui::Align2::RIGHT_CENTER),
2469            };
2470            painter.text(
2471                text_at,
2472                align,
2473                &port.label,
2474                small.clone(),
2475                self.t.text_muted,
2476            );
2477
2478            let pid = port_id(self.id, &pref, side);
2479            let hit = Rect::from_center_size(at, Vec2::splat(PORT_HIT));
2480            let pr = ui.interact(hit, pid, Sense::click_and_drag());
2481            let name = port_label(&self.ctx, n, port, side);
2482            let value = strings::tr_with(
2483                &self.ctx,
2484                &s::GRAPH_PORT_VALUE,
2485                &[
2486                    ("type", Arg::Str(&port.ty.name)),
2487                    ("wires", base.wires_at(&pref, side).len().into()),
2488                ],
2489            );
2490            let enabled = ui.is_enabled();
2491            pr.widget_info(|| {
2492                let mut info = egui::WidgetInfo::labeled(egui::Role::Button, enabled, &name);
2493                info.current_text_value = Some(value.clone());
2494                info
2495            });
2496            let role = tr(
2497                &self.ctx,
2498                match side {
2499                    Side::Input => &s::GRAPH_ROLE_INPUT,
2500                    Side::Output => &s::GRAPH_ROLE_OUTPUT,
2501                },
2502            );
2503            self.ctx.accesskit_node_builder(pid, |node| {
2504                node.set_role_description(role);
2505            });
2506            self.bounds(pid, hit);
2507            if pr.hovered() && self.state.wire.is_none() {
2508                painter.circle_stroke(at, PORT_R + 3.0, Stroke::new(1.0, color));
2509            }
2510            if pr.has_focus() {
2511                egui_pop_core::focus::own_ring(&pr.ctx, pr.id);
2512                if egui_pop_core::focus::ring_shown(&pr.ctx) {
2513                    painter.circle_stroke(
2514                        at,
2515                        PORT_R + 4.0,
2516                        Stroke::new(2.0 / self.zoom.max(0.25), self.t.focus),
2517                    );
2518                }
2519                lock_keys(ui, pid, true);
2520                self.port_keys(ui, i, &order, o, &pref, side);
2521            }
2522            if pr.gained_focus() {
2523                self.reveal = Some(r);
2524            }
2525            if pr.drag_started_by(egui::PointerButton::Primary) && self.pan_drag.is_none() {
2526                self.start_wire(&pref, side, port.multiple, true);
2527            }
2528            egui_pop_core::pointer::drag_cursor(&pr, DragKind::Carry);
2529            if pr.clicked() {
2530                self.click_port(&pref, side, &name);
2531            }
2532            self.port_menu(&pr, &pref, side);
2533            if side == Side::Input {
2534                for e in base.wires_at(&pref, side) {
2535                    if self.wire_answers(&e) {
2536                        self.wire_stop(ui, painter, &e, pid, at);
2537                    }
2538                }
2539            }
2540        }
2541    }
2542
2543    /// A drag begins at a port: a wire from it, or the wire of a
2544    /// connected single input, taken off it.
2545    fn start_wire(&mut self, p: &PortRef, side: Side, multiple: bool, by_pointer: bool) {
2546        let mut wire = Wire {
2547            from: p.clone(),
2548            side,
2549            by_pointer,
2550            detached: None,
2551        };
2552        if side == Side::Input
2553            && !multiple
2554            && let Some(e) = self.base.wires_at(p, side).into_iter().next()
2555        {
2556            wire.from = e.from.clone();
2557            wire.side = Side::Output;
2558            wire.detached = Some(e);
2559        }
2560        self.state.wire = Some(wire);
2561    }
2562
2563    /// A click on a port (or Enter, Space, an assistive technology's
2564    /// click): begins a wire, or ends the one begun.
2565    fn click_port(&mut self, p: &PortRef, side: Side, name: &str) {
2566        match self.state.wire.take() {
2567            Some(w) if w.from == *p && w.side == side => {}
2568            Some(w) if !w.by_pointer => self.finish_wire(&w, p, side, Cause::Click),
2569            _ => {
2570                self.state.wire = Some(Wire {
2571                    from: p.clone(),
2572                    side,
2573                    by_pointer: false,
2574                    detached: None,
2575                });
2576                a11y::announce(
2577                    &self.ctx,
2578                    tr_args(&self.ctx, &s::GRAPH_WIRE_STARTED, &[("port", name)]),
2579                    Politeness::Polite,
2580                );
2581            }
2582        }
2583    }
2584
2585    /// Ends a wire at a port: an edit, or a refusal.
2586    fn finish_wire(&mut self, w: &Wire, p: &PortRef, side: Side, cause: Cause) {
2587        let a = (w.from.clone(), w.side);
2588        let b = (p.clone(), side);
2589        match self.base.connect(&a, &b, w.detached.as_slice()) {
2590            Ok(edit) => {
2591                if let Edit::Connect { from, to, .. } = &edit {
2592                    let (f, t) = self.wire_ends(&Edge::new(from.clone(), to.clone()));
2593                    a11y::announce(
2594                        &self.ctx,
2595                        tr_args(&self.ctx, &s::GRAPH_CONNECTED, &[("from", &f), ("to", &t)]),
2596                        Politeness::Polite,
2597                    );
2598                }
2599                self.propose(edit, cause);
2600            }
2601            // The same wire again: nothing to do.
2602            Err(Refusal::Exists) => {}
2603            Err(refusal) => {
2604                let (from, to) = if a.1 == Side::Output {
2605                    (a.0, b.0)
2606                } else {
2607                    (b.0, a.0)
2608                };
2609                refuse(&self.ctx, &self.base, &from, &to, &refusal, self.events);
2610            }
2611        }
2612    }
2613
2614    fn port_menu(&mut self, pr: &Response, p: &PortRef, side: Side) {
2615        let wires = self.base.wires_at(p, side);
2616        if wires.is_empty() {
2617            return;
2618        }
2619        let ctx = self.ctx.clone();
2620        let mut chosen = false;
2621        let _ = claim::context_menu(pr, |ui| {
2622            if ui.button(tr(&ctx, &s::GRAPH_DISCONNECT)).clicked() {
2623                chosen = true;
2624                ui.close();
2625            }
2626        });
2627        if chosen {
2628            self.propose(Edit::Disconnect { edges: wires }, Cause::Command);
2629        }
2630    }
2631
2632    /// Keys on a focused port: the arrows go through the node's ports,
2633    /// Escape cancels a wire or goes back to the node, Delete
2634    /// disconnects.
2635    fn port_keys(
2636        &mut self,
2637        ui: &Ui,
2638        i: usize,
2639        order: &[(Side, usize)],
2640        o: usize,
2641        p: &PortRef,
2642        side: Side,
2643    ) {
2644        let base = self.base;
2645        let n = &base.nodes[i];
2646        let (next, prev, cancel, delete) = ui.input_mut(|inp| {
2647            let next = inp.consume_key(Modifiers::NONE, Key::ArrowDown)
2648                || inp.consume_key(Modifiers::NONE, Key::ArrowRight);
2649            let prev = inp.consume_key(Modifiers::NONE, Key::ArrowUp)
2650                || inp.consume_key(Modifiers::NONE, Key::ArrowLeft);
2651            let cancel = inp.consume_key(Modifiers::NONE, self.keys.cancel);
2652            let delete = self
2653                .keys
2654                .delete
2655                .iter()
2656                .any(|k| inp.consume_key(Modifiers::NONE, *k));
2657            (next, prev, cancel, delete)
2658        });
2659        let len = order.len();
2660        let go = if next {
2661            Some((o + 1) % len)
2662        } else if prev {
2663            Some((o + len - 1) % len)
2664        } else {
2665            None
2666        };
2667        if let Some(t) = go {
2668            let (s2, k) = order[t];
2669            let port = match s2 {
2670                Side::Input => &n.inputs[k],
2671                Side::Output => &n.outputs[k],
2672            };
2673            let target = port_id(self.id, &PortRef::new(n.id.clone(), port.id.clone()), s2);
2674            ui.memory_mut(|m| m.request_focus(target));
2675        }
2676        if cancel && self.state.wire.take().is_none() {
2677            ui.memory_mut(|m| m.request_focus(node_id(self.id, &n.id)));
2678        }
2679        if delete {
2680            let wires = base.wires_at(p, side);
2681            if !wires.is_empty() {
2682                self.propose(Edit::Disconnect { edges: wires }, Cause::Key);
2683            }
2684        }
2685    }
2686
2687    fn params_ui(&mut self, ui: &mut Ui, i: usize, r: Rect) {
2688        let base = self.base;
2689        let n = &base.nodes[i];
2690        let rows = n.inputs.len().max(n.outputs.len());
2691        let h = param_h(&self.ctx);
2692        let mut y = r.top() + HEADER + rows as f32 * ROW;
2693        for p in base.model.params(&n.id) {
2694            let row = Rect::from_min_size(
2695                pos2(r.left() + PAD * 2.0, y + 2.0),
2696                vec2(r.width() - PAD * 4.0, h - 4.0),
2697            );
2698            y += h;
2699            let mut v = p.value;
2700            let hook = &mut *self.hook;
2701            let node = n.id.clone();
2702            let param = p.id.clone();
2703            let out = ui
2704                .scope_builder(
2705                    UiBuilder::new()
2706                        .max_rect(row)
2707                        .id_salt(("param", &n.id, &p.id)),
2708                    |ui| {
2709                        let mut sl = Slider::new(&mut v, &p.label, p.range.clone());
2710                        if let Some(step) = p.step {
2711                            sl = sl.step(step);
2712                        }
2713                        if let Some(u) = &p.unit {
2714                            sl = sl.unit(u);
2715                        }
2716                        if let Some(d) = p.default {
2717                            sl = sl.default(d);
2718                        }
2719                        sl.on_change(|c: &slider::Change| {
2720                            let edit = Edit::Param {
2721                                node: node.clone(),
2722                                param: param.clone(),
2723                                from: c.from,
2724                                to: c.to,
2725                                done: c.done,
2726                            };
2727                            let cause = Cause::of_slider(c.cause);
2728                            match hook.as_mut().map_or(Verdict::Allow, |h| h(&edit, cause)) {
2729                                Verdict::Allow => slider::Verdict::Go,
2730                                Verdict::Veto => slider::Verdict::Veto,
2731                                Verdict::Redirect(Edit::Param { to, .. }) => {
2732                                    slider::Verdict::Redirect(to)
2733                                }
2734                                Verdict::Redirect(_) => slider::Verdict::Veto,
2735                            }
2736                        })
2737                        .show(ui)
2738                    },
2739                )
2740                .inner;
2741            self.bounds(out.response.id, out.response.rect);
2742            for c in out.changes {
2743                // Already through the hook.
2744                self.edits.push(Edit::Param {
2745                    node: n.id.clone(),
2746                    param: p.id.clone(),
2747                    from: c.from,
2748                    to: c.to,
2749                    done: c.done,
2750                });
2751            }
2752        }
2753    }
2754
2755    /// The wire being drawn, and its end.
2756    fn wire_ui(&mut self, ui: &Ui, painter: &egui::Painter) {
2757        let Some(w) = self.state.wire.clone() else {
2758            return;
2759        };
2760        if egui_pop_core::focus::cancel_pressed(ui.ctx(), self.keys.cancel) {
2761            self.state.wire = None;
2762            return;
2763        }
2764        let Some(start) = self.port_pos(&w.from, w.side) else {
2765            self.state.wire = None;
2766            return;
2767        };
2768        let pointer = self.pointer();
2769        let target = pointer.and_then(|p| self.port_near(p));
2770        let color = match &target {
2771            Some((q, side))
2772                if self
2773                    .base
2774                    .check(&(w.from.clone(), w.side), &(q.clone(), *side))
2775                    .is_err() =>
2776            {
2777                self.t.wire_refused
2778            }
2779            _ => self.t.wire_preview,
2780        };
2781        let hovering = ui.rect_contains_pointer(self.lay.visible);
2782        if let Some(p) = pointer
2783            && (w.by_pointer || hovering)
2784        {
2785            let end = target
2786                .as_ref()
2787                .and_then(|(q, side)| self.port_pos(q, *side))
2788                .unwrap_or(p);
2789            let (a, b) = if w.side == Side::Output {
2790                (start, end)
2791            } else {
2792                (end, start)
2793            };
2794            self.wire_line(painter, a, b, color);
2795        }
2796        if w.by_pointer && ui.input(|i| i.pointer.any_released()) {
2797            self.state.wire = None;
2798            match target {
2799                Some((q, side)) if q != w.from || side != w.side => {
2800                    self.finish_wire(&w, &q, side, Cause::Drag);
2801                }
2802                Some(_) => {}
2803                None => {
2804                    if let Some(e) = w.detached {
2805                        self.propose(Edit::Disconnect { edges: vec![e] }, Cause::Drag);
2806                    }
2807                }
2808            }
2809        }
2810    }
2811
2812    /// The port under a point, if one is near enough.
2813    fn port_near(&self, p: Pos2) -> Option<(PortRef, Side)> {
2814        let mut best: Option<(f32, PortRef, Side)> = None;
2815        for (&(i, side, k), &at) in &self.lay.ports {
2816            let Some(b) = self.lay.box_of[i] else {
2817                continue;
2818            };
2819            if !self.ports_shown(&self.lay.boxes[b]) {
2820                continue;
2821            }
2822            let d = at.distance(p);
2823            if d <= DROP && best.as_ref().is_none_or(|(bd, _, _)| d < *bd) {
2824                let n = &self.base.nodes[i];
2825                let port = match side {
2826                    Side::Input => &n.inputs[k],
2827                    Side::Output => &n.outputs[k],
2828                };
2829                best = Some((d, PortRef::new(n.id.clone(), port.id.clone()), side));
2830            }
2831        }
2832        best.map(|(_, q, s)| (q, s))
2833    }
2834
2835    fn duplicate(&mut self, cause: Cause) {
2836        let off = self.snap.unwrap_or(10.0).max(10.0) * 2.0;
2837        let nodes: Vec<NewNode> = self
2838            .state
2839            .selection
2840            .iter()
2841            .filter_map(|id| self.base.node(id))
2842            .map(|n| NewNode {
2843                kind: n.kind.clone(),
2844                at: self.snapped(pos2(n.pos[0] + off, n.pos[1] + off)),
2845                copy_of: Some(n.id.clone()),
2846            })
2847            .collect();
2848        if !nodes.is_empty() {
2849            self.propose(Edit::Add { nodes }, cause);
2850        }
2851    }
2852
2853    /// Deletes the selection: the nodes with their wires and the wires
2854    /// selected, one edit (a `Disconnect` when only wires are selected).
2855    fn delete(&mut self, cause: Cause) {
2856        let nodes: Vec<String> = self
2857            .state
2858            .selection
2859            .iter()
2860            .filter(|id| self.base.node(id).is_some())
2861            .cloned()
2862            .collect();
2863        let wires: Vec<Edge> = self
2864            .base
2865            .edges
2866            .iter()
2867            .filter(|e| self.state.selected_edges.contains(e))
2868            .cloned()
2869            .collect();
2870        if nodes.is_empty() {
2871            self.disconnect(wires, cause);
2872            return;
2873        }
2874        let edges = self
2875            .base
2876            .edges
2877            .iter()
2878            .filter(|e| nodes.iter().any(|n| e.touches(n)) || wires.contains(e))
2879            .cloned()
2880            .collect();
2881        self.propose(Edit::Delete { nodes, edges }, cause);
2882    }
2883
2884    /// The canvas: its name, the rubber band, a click, a double click,
2885    /// its menu, and the keys on it or on a node.
2886    fn canvas(&mut self, response: &Response, label: &str) {
2887        let ctx = self.ctx.clone();
2888        let value = strings::tr_with(
2889            &ctx,
2890            &s::GRAPH_VALUE,
2891            &[
2892                ("nodes", self.base.nodes.len().into()),
2893                ("wires", self.base.edges.len().into()),
2894                (
2895                    "level",
2896                    Arg::Str(&tr(
2897                        &ctx,
2898                        match self.level {
2899                            Level::Overview => &s::GRAPH_LEVEL_OVERVIEW,
2900                            Level::Ports => &s::GRAPH_LEVEL_PORTS,
2901                            Level::Detail => &s::GRAPH_LEVEL_DETAIL,
2902                        },
2903                    )),
2904                ),
2905            ],
2906        );
2907        let label = label.to_string();
2908        response.widget_info(|| {
2909            let mut info = egui::WidgetInfo::labeled(egui::Role::Unknown, true, &label);
2910            info.current_text_value = Some(value.clone());
2911            info
2912        });
2913        ctx.accesskit_node_builder(response.id, |node| node.set_role(Role::Group));
2914        self.bounds(response.id, self.lay.visible);
2915        let to_scene = self.to_global.inverse();
2916        let pointer = ctx.input(|i| i.pointer.latest_pos()).map(|p| to_scene * p);
2917        let modifiers = ctx.input(|i| i.modifiers);
2918        // A drag the profile pans with, from anywhere on the graph (a
2919        // widget on the graph that claims the secondary drag keeps it).
2920        let panning = self.pan_drag.is_some_and(|b| {
2921            !(b == egui::PointerButton::Secondary
2922                && claim::claimed(&ctx, Secondary::Drag).is_some())
2923        });
2924        if panning {
2925            let delta = ctx.input(|i| i.pointer.delta());
2926            self.state.pan(-delta / self.zoom.max(1e-6));
2927        } else if response.drag_started_by(egui::PointerButton::Primary)
2928            && let Some(p) = pointer
2929        {
2930            // On a wire, its nearer end follows; elsewhere a rubber band.
2931            let origin = ctx
2932                .input(|i| i.pointer.press_origin())
2933                .map_or(p, |o| to_scene * o);
2934            match self.wire_at(origin) {
2935                Some((e, output)) => self.pick_end(&e, output, true),
2936                None => self.state.band = Some([p, p]),
2937            }
2938        }
2939        if let Some(band) = &mut self.state.band
2940            && let Some(p) = pointer
2941        {
2942            band[1] = p;
2943        }
2944        // The canvas's drags keep their cursor wherever the pointer goes.
2945        if panning {
2946            egui_pop_core::pointer::hold_drag_cursor(&ctx, DragKind::Pan);
2947        } else if response.dragged() {
2948            if self.state.band.is_some() {
2949                egui_pop_core::pointer::hold_drag_cursor(&ctx, DragKind::Select);
2950            } else if self.state.wire.as_ref().is_some_and(|w| w.by_pointer) {
2951                egui_pop_core::pointer::hold_drag_cursor(&ctx, DragKind::Carry);
2952            }
2953        }
2954        if response.drag_stopped()
2955            && let Some([a, b]) = self.state.band.take()
2956        {
2957            let r = Rect::from_two_pos(a, b);
2958            let add = ctx.input(|i| i.modifiers.shift || i.modifiers.command);
2959            if !add {
2960                self.state.selection.clear();
2961                self.state.selected_edges.clear();
2962            }
2963            for placed in &self.lay.boxes {
2964                if !placed.rect.intersects(r) {
2965                    continue;
2966                }
2967                match (placed.node, placed.group) {
2968                    (Some(i), _) => {
2969                        self.state.selection.insert(self.base.nodes[i].id.clone());
2970                    }
2971                    (None, Some(g)) => {
2972                        let members = self.members(g);
2973                        self.state.selection.extend(members);
2974                    }
2975                    _ => {}
2976                }
2977            }
2978        }
2979        if response.clicked() {
2980            response.request_focus();
2981            let add = ctx.input(|i| i.modifiers.shift || i.modifiers.command);
2982            match self.hover.clone() {
2983                Some(e) => self.click_wire(&e, add),
2984                None if !add => {
2985                    self.state.selection.clear();
2986                    self.state.selected_edges.clear();
2987                }
2988                None => {}
2989            }
2990            self.state.wire = None;
2991        }
2992        if let Some(e) = &self.hover
2993            && response.hovered()
2994        {
2995            let tip = self.wire_tip(e);
2996            egui::Tooltip::always_open(
2997                ctx.clone(),
2998                response.layer_id,
2999                response.id.with("wire-tip"),
3000                egui::PopupAnchor::Pointer,
3001            )
3002            .show(|ui| ui.label(tip));
3003        }
3004        if response.double_clicked()
3005            && self
3006                .gestures
3007                .double_click_action(egui::PointerButton::Primary, modifiers)
3008                == crate::gestures::ViewAction::Fit
3009        {
3010            self.state.fit = true;
3011        }
3012        for b in [
3013            egui::PointerButton::Middle,
3014            egui::PointerButton::Extra1,
3015            egui::PointerButton::Extra2,
3016        ] {
3017            if response.clicked_by(b)
3018                && self.gestures.click_action(b, modifiers) == crate::gestures::ViewAction::Fit
3019            {
3020                self.state.fit = true;
3021            }
3022        }
3023        if claim::opens_context_menu(response) {
3024            self.state.menu_at = pointer;
3025            // On a wire, its menu.
3026            self.state.menu_wire = if response.secondary_clicked() {
3027                self.hover.clone()
3028            } else {
3029                None
3030            };
3031        }
3032        let kinds = self.base.model.kinds();
3033        if let Some(e) = self.state.menu_wire.clone() {
3034            let _ = claim::context_menu(response, |ui| self.wire_menu_items(ui, &e));
3035        } else if !kinds.is_empty() {
3036            let mut chosen = None;
3037            let _ = claim::context_menu(response, |ui| {
3038                ui.label(tr(&ctx, &s::GRAPH_ADD_NODE));
3039                for k in &kinds {
3040                    if ui.button(&k.title).clicked() {
3041                        chosen = Some(k.id.clone());
3042                        ui.close();
3043                    }
3044                }
3045            });
3046            if let Some(kind) = chosen {
3047                let at = self
3048                    .state
3049                    .menu_at
3050                    .unwrap_or_else(|| self.lay.visible.center());
3051                self.propose(
3052                    Edit::Add {
3053                        nodes: vec![NewNode {
3054                            kind,
3055                            at: self.snapped(at),
3056                            copy_of: None,
3057                        }],
3058                    },
3059                    Cause::Command,
3060                );
3061            }
3062        }
3063        if response.has_focus() {
3064            ctx.memory_mut(|m| {
3065                m.set_focus_lock_filter(
3066                    response.id,
3067                    egui::EventFilter {
3068                        horizontal_arrows: true,
3069                        vertical_arrows: true,
3070                        ..Default::default()
3071                    },
3072                );
3073            });
3074            let arrow = ctx.input_mut(|i| {
3075                [
3076                    Key::ArrowLeft,
3077                    Key::ArrowRight,
3078                    Key::ArrowUp,
3079                    Key::ArrowDown,
3080                ]
3081                .into_iter()
3082                .any(|k| i.consume_key(Modifiers::NONE, k))
3083            });
3084            if arrow {
3085                // Into the graph: the node nearest the view's centre.
3086                let c = self.lay.visible.center();
3087                if let Some(i) = self.nearest(c, None) {
3088                    ctx.memory_mut(|m| m.request_focus(node_id(self.id, &self.base.nodes[i].id)));
3089                }
3090            }
3091        }
3092        if response.has_focus() || self.focused.is_some() {
3093            self.graph_keys();
3094        }
3095    }
3096
3097    /// The node nearest a point (that way from it, when a direction is
3098    /// given), other than the one there.
3099    fn nearest(&self, from: Pos2, dir: Option<Vec2>) -> Option<usize> {
3100        let mut best: Option<(f32, usize)> = None;
3101        for b in &self.lay.boxes {
3102            let Some(i) = b.node else { continue };
3103            let d = b.rect.center() - from;
3104            if d.length() < 1.0 && dir.is_some() {
3105                continue;
3106            }
3107            let score = match dir {
3108                Some(dir) => {
3109                    let along = d.dot(dir);
3110                    if along <= 0.0 {
3111                        continue;
3112                    }
3113                    let across = (d - dir * along).length();
3114                    along + 2.0 * across
3115                }
3116                None => d.length(),
3117            };
3118            if best.is_none_or(|(s, _)| score < s) {
3119                best = Some((score, i));
3120            }
3121        }
3122        best.map(|(_, i)| i)
3123    }
3124
3125    /// The keys on the canvas or on a node.
3126    fn graph_keys(&mut self) {
3127        let ctx = self.ctx.clone();
3128        let k = self.keys;
3129        let (delete, duplicate, all, fit) = ctx.input_mut(|i| {
3130            (
3131                k.delete
3132                    .iter()
3133                    .any(|key| i.consume_key(Modifiers::NONE, *key)),
3134                i.consume_key(Modifiers::COMMAND, k.duplicate),
3135                i.consume_key(Modifiers::COMMAND, k.select_all),
3136                i.consume_key(Modifiers::NONE, k.fit),
3137            )
3138        });
3139        let base = self.base;
3140        if let Some(i) = self.focused {
3141            let id = &base.nodes[i].id;
3142            if (delete || duplicate) && !self.state.selection.contains(id) {
3143                self.state.selection = BTreeSet::from([id.clone()]);
3144            }
3145            // The arrows: Shift moves the selection, alone they go to
3146            // the nearest node that way.
3147            let dirs = [
3148                (Key::ArrowLeft, vec2(-1.0, 0.0)),
3149                (Key::ArrowRight, vec2(1.0, 0.0)),
3150                (Key::ArrowUp, vec2(0.0, -1.0)),
3151                (Key::ArrowDown, vec2(0.0, 1.0)),
3152            ];
3153            for (key, dir) in dirs {
3154                let nudged = ctx.input_mut(|inp| inp.consume_key(k.nudge, key));
3155                if nudged {
3156                    if !self.state.selection.contains(id) {
3157                        self.state.selection = BTreeSet::from([id.clone()]);
3158                    }
3159                    let step = self.snap.unwrap_or(10.0);
3160                    let moves = self
3161                        .state
3162                        .selection
3163                        .iter()
3164                        .filter_map(|s| base.node(s))
3165                        .map(|n| Moved {
3166                            node: n.id.clone(),
3167                            from: n.pos,
3168                            to: self.snapped(pos2(n.pos[0], n.pos[1]) + dir * step),
3169                        })
3170                        .collect();
3171                    self.propose(Edit::Move { moves }, Cause::Key);
3172                    continue;
3173                }
3174                if ctx.input_mut(|inp| inp.consume_key(Modifiers::NONE, key)) {
3175                    let from = self.lay.box_of[i].map(|b| self.lay.boxes[b].rect.center());
3176                    if let Some(from) = from
3177                        && let Some(t) = self.nearest(from, Some(dir))
3178                    {
3179                        let target = node_id(self.id, &base.nodes[t].id);
3180                        ctx.memory_mut(|m| m.request_focus(target));
3181                    }
3182                }
3183            }
3184        }
3185        if delete {
3186            self.delete(Cause::Key);
3187        }
3188        if duplicate {
3189            self.duplicate(Cause::Key);
3190        }
3191        if all {
3192            self.state.selection = base.nodes.iter().map(|n| n.id.clone()).collect();
3193        }
3194        if fit {
3195            self.state.fit = true;
3196        }
3197    }
3198}
3199
3200/// What a layout is made from.
3201struct LayoutIn<'a> {
3202    nodes: &'a [Node],
3203    groups: &'a [Group],
3204    /// Whether each group is folded into a stack, by index.
3205    folded: &'a [bool],
3206    collapsed: &'a BTreeSet<String>,
3207    level: Level,
3208    node_width: f32,
3209    /// A node's height in the overview.
3210    overview_h: f32,
3211    /// A parameter row's height.
3212    param_h: f32,
3213    /// A node's number of parameters, by index (asked at the detail
3214    /// level only).
3215    params: &'a dyn Fn(usize) -> usize,
3216    /// Where a node is drawn (its top-left corner).
3217    pos: &'a dyn Fn(&Node) -> Pos2,
3218}
3219
3220/// Lays a graph out: its boxes (stacks first, then nodes), its ports and
3221/// the frames of its unfolded groups. The part in view is left empty.
3222fn lay_out(input: &LayoutIn<'_>) -> Layout {
3223    let nodes = input.nodes;
3224    let mut lay = Layout {
3225        box_of: vec![None; nodes.len()],
3226        ..Layout::default()
3227    };
3228    let group_index = |id: &str| -> Option<usize> { input.groups.iter().position(|g| g.id == id) };
3229    // Stacks: one box per folded group with members, where its
3230    // first-placed member is.
3231    let mut stack_box: HashMap<usize, usize> = HashMap::new();
3232    for (i, n) in nodes.iter().enumerate() {
3233        let Some(g) = n.group.as_deref().and_then(group_index) else {
3234            continue;
3235        };
3236        if !input.folded[g] {
3237            continue;
3238        }
3239        let p = (input.pos)(n);
3240        let b = *stack_box.entry(g).or_insert_with(|| {
3241            lay.boxes.push(Placed {
3242                rect: Rect::from_min_size(p, Vec2::ZERO),
3243                node: None,
3244                group: Some(g),
3245                collapsed: true,
3246            });
3247            lay.boxes.len() - 1
3248        });
3249        let r = &mut lay.boxes[b].rect;
3250        r.min = r.min.min(p);
3251        lay.box_of[i] = Some(b);
3252    }
3253    let stack_h = if input.level == Level::Overview {
3254        input.overview_h
3255    } else {
3256        HEADER + ROW
3257    };
3258    for b in &mut lay.boxes {
3259        b.rect = Rect::from_min_size(b.rect.min, vec2(input.node_width, stack_h));
3260    }
3261    for (i, n) in nodes.iter().enumerate() {
3262        if lay.box_of[i].is_some() {
3263            continue;
3264        }
3265        let collapsed = input.collapsed.contains(&n.id);
3266        let rows = n.inputs.len().max(n.outputs.len());
3267        let params = if input.level == Level::Detail && !collapsed {
3268            (input.params)(i)
3269        } else {
3270            0
3271        };
3272        let h = match input.level {
3273            Level::Overview => input.overview_h,
3274            _ if collapsed => HEADER,
3275            _ => HEADER + rows as f32 * ROW + params as f32 * input.param_h + PAD,
3276        };
3277        let rect = Rect::from_min_size((input.pos)(n), vec2(input.node_width, h));
3278        lay.boxes.push(Placed {
3279            rect,
3280            node: Some(i),
3281            group: None,
3282            collapsed,
3283        });
3284        lay.box_of[i] = Some(lay.boxes.len() - 1);
3285    }
3286    // Ports: on their rows, or at the box's sides when it is
3287    // compact.
3288    for (i, n) in nodes.iter().enumerate() {
3289        let Some(b) = lay.box_of[i] else { continue };
3290        let placed = &lay.boxes[b];
3291        let r = placed.rect;
3292        let compact = placed.node.is_none() || placed.collapsed || input.level == Level::Overview;
3293        for (side, list) in [(Side::Input, &n.inputs), (Side::Output, &n.outputs)] {
3294            let x = if side == Side::Input {
3295                r.left()
3296            } else {
3297                r.right()
3298            };
3299            for k in 0..list.len() {
3300                let y = if compact {
3301                    r.center().y
3302                } else {
3303                    r.top() + HEADER + (k as f32 + 0.5) * ROW
3304                };
3305                lay.ports.insert((i, side, k), pos2(x, y));
3306            }
3307        }
3308    }
3309    // Frames around unfolded groups.
3310    for (g, group) in input.groups.iter().enumerate() {
3311        if input.folded[g] {
3312            continue;
3313        }
3314        let mut r = Rect::NOTHING;
3315        for (i, n) in nodes.iter().enumerate() {
3316            if n.group.as_deref() == Some(group.id.as_str())
3317                && let Some(b) = lay.box_of[i]
3318            {
3319                r = r.union(lay.boxes[b].rect);
3320            }
3321        }
3322        if r.is_positive() {
3323            let mut r = r.expand(GROUP_PAD);
3324            r.min.y -= GROUP_LABEL;
3325            lay.frames.push((g, r));
3326        }
3327    }
3328    lay
3329}
3330
3331/// Where a port is laid out, by reference.
3332fn port_at(nodes: &[Node], lay: &Layout, p: &PortRef, side: Side) -> Option<Pos2> {
3333    let i = nodes.iter().position(|n| n.id == p.node)?;
3334    let n = &nodes[i];
3335    let k = match side {
3336        Side::Input => n.inputs.iter().position(|q| q.id == p.port)?,
3337        Side::Output => n.outputs.iter().position(|q| q.id == p.port)?,
3338    };
3339    lay.ports.get(&(i, side, k)).copied()
3340}
3341
3342/// The wires drawn in a layout, with their ends (an output, then an
3343/// input): none inside one stack, one where several join the same two
3344/// points (between stacks); `skip` is the wire being dragged off.
3345fn wires_drawn<'e>(
3346    nodes: &[Node],
3347    edges: &'e [Edge],
3348    lay: &Layout,
3349    skip: Option<&Edge>,
3350) -> Vec<(&'e Edge, Pos2, Pos2)> {
3351    let box_of = |node: &str| -> Option<usize> {
3352        let i = nodes.iter().position(|n| n.id == node)?;
3353        lay.box_of[i]
3354    };
3355    let mut drawn = Vec::new();
3356    let mut seen: BTreeSet<[i64; 4]> = BTreeSet::new();
3357    for e in edges {
3358        if skip == Some(e) {
3359            continue;
3360        }
3361        let (Some(a), Some(b)) = (
3362            port_at(nodes, lay, &e.from, Side::Output),
3363            port_at(nodes, lay, &e.to, Side::Input),
3364        ) else {
3365            continue;
3366        };
3367        // Inside one stack, or drawn twice between stacks.
3368        let from_box = box_of(&e.from.node);
3369        let same_box = from_box.is_some() && from_box == box_of(&e.to.node);
3370        let key = [a.x, a.y, b.x, b.y].map(|v| (v * 4.0).round() as i64);
3371        if same_box || !seen.insert(key) {
3372            continue;
3373        }
3374        drawn.push((e, a, b));
3375    }
3376    drawn
3377}
3378
3379/// A node's height in the overview at a zoom: the smallest that keeps
3380/// its title (`body` points) readable.
3381fn overview_height(body: f32, zoom: f32) -> f32 {
3382    let want = body * 1.8 / zoom.max(0.01);
3383    OVERVIEW_H
3384        .into_iter()
3385        .find(|h| *h >= want)
3386        .unwrap_or(OVERVIEW_H[2])
3387}
3388
3389/// A parameter row's height.
3390fn param_h(ctx: &egui::Context) -> f32 {
3391    ctx.global_style().spacing.interact_size.y + 4.0
3392}
3393
3394/// A cubic Bézier curve as a line of points.
3395fn flatten(c: [Pos2; 4]) -> Vec<Pos2> {
3396    const STEPS: usize = 24;
3397    (0..=STEPS)
3398        .map(|k| {
3399            let t = k as f32 / STEPS as f32;
3400            let u = 1.0 - t;
3401            let w = [u * u * u, 3.0 * u * u * t, 3.0 * u * t * t, t * t * t];
3402            pos2(
3403                w[0] * c[0].x + w[1] * c[1].x + w[2] * c[2].x + w[3] * c[3].x,
3404                w[0] * c[0].y + w[1] * c[1].y + w[2] * c[2].y + w[3] * c[3].y,
3405            )
3406        })
3407        .collect()
3408}
3409
3410/// How far a point is from a line of points, and where along it the
3411/// nearest point is (0 at its start, 1 at its end).
3412fn distance_along(line: &[Pos2], p: Pos2) -> Option<(f32, f32)> {
3413    let total: f32 = line.windows(2).map(|w| w[0].distance(w[1])).sum();
3414    let mut best: Option<(f32, f32)> = None;
3415    let mut walked = 0.0;
3416    for w in line.windows(2) {
3417        let (a, b) = (w[0], w[1]);
3418        let ab = b - a;
3419        let len = ab.length();
3420        let t = if len > 0.0 {
3421            ((p - a).dot(ab) / (len * len)).clamp(0.0, 1.0)
3422        } else {
3423            0.0
3424        };
3425        let d = p.distance(a + ab * t);
3426        if best.is_none_or(|(bd, _)| d < bd) {
3427            let along = if total > 0.0 {
3428                (walked + len * t) / total
3429            } else {
3430                0.0
3431            };
3432            best = Some((d, along));
3433        }
3434        walked += len;
3435    }
3436    best
3437}
3438
3439/// The point `dist` along a line from its start (its end, if shorter).
3440fn point_along(line: &[Pos2], dist: f32) -> Pos2 {
3441    let mut left = dist;
3442    for w in line.windows(2) {
3443        let len = w[0].distance(w[1]);
3444        if len >= left && len > 0.0 {
3445            return w[0] + (w[1] - w[0]) * (left / len);
3446        }
3447        left -= len;
3448    }
3449    line.last().copied().unwrap_or(Pos2::ZERO)
3450}
3451
3452/// The point `dist` along a line from its end.
3453fn point_along_back(line: &[Pos2], dist: f32) -> Pos2 {
3454    let back: Vec<Pos2> = line.iter().rev().copied().collect();
3455    point_along(&back, dist)
3456}
3457
3458/// Keeps the arrows (and Escape, on a port) on a focused part of the
3459/// graph: egui would move the focus, or drop it.
3460fn lock_keys(ui: &Ui, id: Id, escape: bool) {
3461    ui.memory_mut(|m| {
3462        m.set_focus_lock_filter(
3463            id,
3464            egui::EventFilter {
3465                horizontal_arrows: true,
3466                vertical_arrows: true,
3467                escape,
3468                ..Default::default()
3469            },
3470        );
3471    });
3472}
3473
3474/// The graph as drawn: nodes (place, ports and their wires, group,
3475/// collapsed, selected, parameters), wires, groups, the selection (nodes,
3476/// and wires as `selected_edges`), the
3477/// view and the level; the wire style, and each wire's route when it is
3478/// orthogonal. What `graph.read` answers.
3479pub fn describe(
3480    model: &dyn GraphModel,
3481    nodes: &[Node],
3482    edges: &[Edge],
3483    state: &GraphState,
3484) -> Json {
3485    let port = |p: &Port| {
3486        json!({
3487            "id": p.id,
3488            "label": p.label,
3489            "type": p.ty.name,
3490            "multiple": p.multiple,
3491        })
3492    };
3493    let v = state.drawn.visible;
3494    json!({
3495        "nodes": nodes
3496            .iter()
3497            .map(|n| json!({
3498                "id": n.id,
3499                "kind": n.kind,
3500                "title": n.title,
3501                "pos": [n.pos[0], n.pos[1]],
3502                "group": n.group,
3503                "collapsed": state.collapsed.contains(&n.id),
3504                "selected": state.selection.contains(&n.id),
3505                "inputs": n.inputs.iter().map(port).collect::<Vec<_>>(),
3506                "outputs": n.outputs.iter().map(port).collect::<Vec<_>>(),
3507                "params": model
3508                    .params(&n.id)
3509                    .iter()
3510                    .map(|p| json!({ "id": p.id, "label": p.label, "value": p.value }))
3511                    .collect::<Vec<_>>(),
3512            }))
3513            .collect::<Vec<_>>(),
3514        "edges": edges.iter().map(Edge::to_json).collect::<Vec<_>>(),
3515        "groups": model
3516            .groups()
3517            .iter()
3518            .map(|g| json!({
3519                "id": g.id,
3520                "label": g.label,
3521                "folded": state.folded.contains(&g.id),
3522                "unfolded": state.unfolded.contains(&g.id),
3523            }))
3524            .collect::<Vec<_>>(),
3525        "kinds": model
3526            .kinds()
3527            .iter()
3528            .map(|k| json!({ "id": k.id, "title": k.title }))
3529            .collect::<Vec<_>>(),
3530        "selection": state.selection.iter().collect::<Vec<_>>(),
3531        "selected_edges": state.selected_edges.iter().map(Edge::to_json).collect::<Vec<_>>(),
3532        "level": state.level.map(Level::name),
3533        "zoom": state.drawn.zoom,
3534        "visible": [v.min.x, v.min.y, v.max.x, v.max.y],
3535        "wiring": state.wire.as_ref().map(|w| json!({ "from": w.from.to_json(), "side": w.side.name() })),
3536        "wires": state.wire_style.name(),
3537        "routes": state
3538            .drawn
3539            .routes
3540            .iter()
3541            .map(|(e, points)| json!({
3542                "edge": e.to_json(),
3543                "points": points.iter().map(|p| [p.x, p.y]).collect::<Vec<_>>(),
3544            }))
3545            .collect::<Vec<_>>(),
3546    })
3547}
3548
3549/// The number of a zoom in percent, as the interface writes numbers.
3550pub(crate) fn zoom_text(ctx: &egui::Context, zoom: f32) -> String {
3551    strings::number(ctx, f64::from(zoom) * 100.0, 0)
3552}