1//! Node Flow canvas built on `draw` + `ui`:
2//! - Sleek thin Fusion-style node bars with colored bottom stripe
3//! - Fusion handles: output square on the right edge, role-coloured input triangles that rotate toward their upstream node
4//! - Drag output -> input triangle (or node body) to wire, drag a connected triangle off to rewire or disconnect
5//! - Crisp straight lines by default (clean in any build orientation: L->R, T->B, B->T, diagonal)
6//! - Day-1 Blender `G`/`R`/`S` modal transforms + `X`/`Y` axis locks
7//! - `1`/`2` multi-viewer routing, `Cmd+F` / Numpad `.` fit-to-view, `P` bypass, drag-onto-wire insert.
8//! - `Cmd+C` / `Cmd+V` node clipboard requests, double-click into Macro/Group subgraphs, `Esc` back out.
9
10mod hit;
11mod paint;
12mod ports;
13mod scope;
14
15use draw::{Glyphs, PathStyle, Primitive};
16use model::{Comp, CompHistory, NodeId, PortRole, default_main_input_port, is_supported_tool};
17use scope::Scope;
18pub use scope::group_children;
19use std::collections::{HashMap, HashSet};
20use std::sync::Arc;
21use std::time::{Duration, Instant};
22use winit::event::{ElementState, MouseButton};
23use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey};
24
25// Exact 1:1 match to Fusion's 110×33 flow grid cells (leaving crisp 26px X / 12px Y gaps for □──▶ wires).
26const NODE_W: f32 = 84.0;
27const NODE_H: f32 = 21.0;
28const DOUBLE_CLICK: Duration = Duration::from_millis(400);
29/// Stale label layouts (renamed nodes) tolerated before the cache is rebuilt.
30const LABEL_CACHE_SLACK: usize = 512;
31
32const HUD_ROOT: &str = "Shift+Space: Add Tool G/R/S: Transform Shift+Drag: Splice Del: Delete Cmd+C/V: Copy/Paste Cmd+D: Dup F2: Rename P: Bypass 1/2: Viewer Dbl-click group: Enter";
33const HUD_GROUP: &str = "Group contents are read-only Dbl-click nested group: Enter Cmd+C: Copy 1/2: Viewer F: Fit Esc: Back";
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq)]
36pub enum TransformMode {
37 Grab,
38 Rotate,
39 Scale,
40}
41
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub enum AxisLock {
44 None,
45 X,
46 Y,
47}
48
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50enum Edge {
51 Left,
52 Right,
53 Top,
54 Bottom,
55}
56
57impl Edge {
58 fn normal(self) -> [f32; 2] {
59 match self {
60 Edge::Left => [-1.0, 0.0],
61 Edge::Right => [1.0, 0.0],
62 Edge::Top => [0.0, -1.0],
63 Edge::Bottom => [0.0, 1.0],
64 }
65 }
66}
67
68#[derive(Clone, Debug)]
69struct ModalTransform {
70 mode: TransformMode,
71 axis: AxisLock,
72 pivot_world: [f32; 2],
73 start_pointer_world: [f32; 2],
74 saved_positions: Vec<(NodeId, [f32; 2])>,
75}
76
77#[derive(Clone, Debug)]
78struct WireDrag {
79 src: NodeId,
80 /// The output the wire leaves: the detached binding's own, else the source tool's default.
81 src_output: String,
82 cursor_local: [f32; 2],
83 target: Option<DropTarget>,
84 /// Set when dragging an existing connected input off to disconnect/rewire.
85 detached_from: Option<(NodeId, String)>,
86 /// Press point of a rewire drag that has not yet moved [`DETACH_DRAG`]; the wire stays
87 /// connected until it does, so a plain click changes nothing.
88 pending: Option<[f32; 2]>,
89}
90
91impl WireDrag {
92 /// Whether this drag has detached its wire inside an open history group.
93 fn owns_group(&self) -> bool {
94 self.detached_from.is_some() && self.pending.is_none()
95 }
96}
97
98/// Screen pixels a pressed input triangle must travel before its wire detaches.
99const DETACH_DRAG: f32 = 4.0;
100
101/// Output a wire from a `kind` tool leaves by: masks and materials have their own.
102fn default_output(kind: &str) -> &'static str {
103 if kind.ends_with("Mask") {
104 "Mask"
105 } else if kind.starts_with("Mtl") {
106 "MaterialOutput"
107 } else {
108 "Output"
109 }
110}
111
112#[derive(Clone, Debug)]
113struct DropTarget {
114 node: NodeId,
115 port: String,
116 cycle: bool,
117}
118
119/// Handle under the pointer: a node's output square (`port: None`) or one of its input triangles.
120#[derive(Clone, Debug, PartialEq, Eq)]
121struct HandleId {
122 node: NodeId,
123 port: Option<String>,
124}
125
126#[derive(Clone, Debug)]
127struct BoxSelect {
128 start_local: [f32; 2],
129 cur_local: [f32; 2],
130}
131
132#[derive(Clone, Debug)]
133pub enum FlowAction {
134 SelectionChanged(Option<NodeId>),
135 /// Slot 0 = Viewer 1 (`1` key), Slot 1 = Viewer 2 (`2` key).
136 ViewNode(usize, NodeId),
137 /// Clear a single viewer slot (pressing `1` or `2` a second time when active).
138 ClearViewer(usize),
139 /// `` ` `` key: clear both Viewer 1 and Viewer 2.
140 ClearViewers,
141 /// Graph topology or node state mutated (optional affected node for subtree bust).
142 GraphMutated(Option<NodeId>),
143 /// `Shift+Space`: open Add Tool launcher.
144 OpenAddTool,
145 /// `F2`: begin inline rename on the primary selected node.
146 RequestRename(NodeId),
147 /// Transient feedback message (e.g., cycle rejected).
148 StatusNotice(String),
149 /// `Cmd+C`: serialize these nodes to the system clipboard.
150 CopyNodes(Vec<NodeId>),
151 /// `Cmd+V`: paste the system clipboard at the root graph.
152 PasteNodes,
153 /// A Macro/Group was entered or left; selection was reset to the new level.
154 ScopeChanged,
155}
156
157#[derive(Clone, Debug)]
158struct WireRef {
159 src: NodeId,
160 dst: NodeId,
161 port: String,
162}
163
164#[derive(Clone, Copy, Debug)]
165pub struct FlowPalette {
166 pub bg: [f32; 4],
167 pub grid_minor: [f32; 4],
168 pub grid_major: [f32; 4],
169 pub node_fill: [f32; 4],
170 pub node_hover: [f32; 4],
171 pub node_selected: [f32; 4],
172 pub node_border: [f32; 4],
173 pub text: [f32; 4],
174 pub text_dim: [f32; 4],
175 pub accent: [f32; 4],
176}
177
178impl FlowPalette {
179 pub fn from_ui(theme: &ui::Theme) -> Self {
180 let b = theme.base;
181 let lift = |c: [f32; 4], d: f32| {
182 [(c[0] + d).clamp(0.0, 1.0), (c[1] + d).clamp(0.0, 1.0), (c[2] + d).clamp(0.0, 1.0), 1.0]
183 };
184 Self {
185 bg: b,
186 grid_minor: lift(b, 0.012),
187 grid_major: lift(b, 0.028),
188 node_fill: lift(b, 0.036),
189 node_hover: lift(b, 0.056),
190 node_selected: lift(b, 0.078),
191 node_border: theme.chip,
192 text: theme.text,
193 text_dim: theme.text_dim,
194 accent: theme.accent,
195 }
196 }
197}
198
199pub struct FlowView {
200 pub pan: [f32; 2],
201 pub zoom: f32,
202 pub size: [f32; 2],
203 pub selected: HashSet<NodeId>,
204 pub primary: Option<NodeId>,
205 /// `[viewer_1_node, viewer_2_node]`.
206 pub viewed_nodes: [Option<NodeId>; 2],
207 pub palette: FlowPalette,
208 hovered_node: Option<NodeId>,
209 hovered_handle: Option<HandleId>,
210 hovered_wire: Option<WireRef>,
211 modal: Option<ModalTransform>,
212 wire_drag: Option<WireDrag>,
213 /// A gesture that owned a history group was dropped without its history; the next input closes it.
214 orphaned_group: bool,
215 box_select: Option<BoxSelect>,
216 panning: Option<([f32; 2], [f32; 2])>,
217 lmb_drag_node: Option<(NodeId, [f32; 2], bool)>,
218 pointer_local: [f32; 2],
219 scope: Scope,
220 last_click: Option<(Instant, NodeId)>,
221 label_cache: HashMap<String, text::Layout>,
222 badge_cache: HashMap<String, text::Layout>,
223 fitted_once: bool,
224}
225
226impl FlowView {
227 pub fn new(theme: &ui::Theme) -> Self {
228 Self {
229 pan: [0.0, 0.0],
230 zoom: 1.0,
231 size: [800.0, 500.0],
232 selected: HashSet::new(),
233 primary: None,
234 viewed_nodes: [None, None],
235 palette: FlowPalette::from_ui(theme),
236 hovered_node: None,
237 hovered_handle: None,
238 hovered_wire: None,
239 modal: None,
240 wire_drag: None,
241 orphaned_group: false,
242 box_select: None,
243 panning: None,
244 lmb_drag_node: None,
245 pointer_local: [0.0, 0.0],
246 scope: Scope::default(),
247 last_click: None,
248 label_cache: HashMap::new(),
249 badge_cache: HashMap::new(),
250 fitted_once: false,
251 }
252 }
253
254 pub fn is_modal_active(&self) -> bool {
255 self.modal.is_some()
256 }
257
258 pub fn resize(&mut self, size: [f32; 2]) {
259 self.size = [
260 if size[0].is_finite() { size[0].max(1.0) } else { 1.0 },
261 if size[1].is_finite() { size[1].max(1.0) } else { 1.0 },
262 ];
263 }
264
265 pub fn background(&self) -> [f32; 4] {
266 self.palette.bg
267 }
268
269 /// Resets transient interaction state and re-fits when a new composition is loaded.
270 pub fn reset_for_comp(&mut self, comp: &Comp) {
271 self.selected.clear();
272 self.primary = None;
273 self.hovered_node = None;
274 self.hovered_handle = None;
275 self.hovered_wire = None;
276 self.modal = None;
277 self.wire_drag = None;
278 self.box_select = None;
279 self.panning = None;
280 self.lmb_drag_node = None;
281 self.last_click = None;
282 self.scope = Scope::default();
283 self.label_cache.clear();
284 self.fitted_once = false;
285 self.fit_comp(comp);
286 }
287
288 /// Groups entered from the root, outermost first; empty at the root graph.
289 pub fn scope_path(&self) -> &[NodeId] {
290 self.scope.path()
291 }
292
293 /// Shows the inside of Macro/Group `id`, which must be visible at the current level.
294 pub fn enter_group(&mut self, comp: &Comp, id: NodeId) -> bool {
295 if !self.scope.enter(comp, id) {
296 return false;
297 }
298 self.scope_switched(comp, None);
299 true
300 }
301
302 /// Keeps the outermost `depth` groups (`0` = root) and selects the group just left.
303 pub fn exit_to_depth(&mut self, comp: &Comp, depth: usize) -> bool {
304 let Some(left) = self.scope.truncate(comp, depth) else {
305 return false;
306 };
307 self.scope_switched(comp, Some(left));
308 true
309 }
310
311 /// Leaves the innermost group.
312 pub fn exit_group(&mut self, comp: &Comp) -> bool {
313 self.scope.path().len().checked_sub(1).is_some_and(|d| self.exit_to_depth(comp, d))
314 }
315
316 fn scope_switched(&mut self, comp: &Comp, select: Option<NodeId>) {
317 self.selected.clear();
318 self.selected.extend(select);
319 self.primary = select;
320 self.hovered_node = None;
321 self.hovered_handle = None;
322 self.hovered_wire = None;
323 self.abandon_gestures();
324 self.box_select = None;
325 self.lmb_drag_node = None;
326 self.last_click = None;
327 self.fit_comp(comp);
328 }
329
330 /// Sanitizes camera/viewport scalars so `zoom` and `pan` are always finite and positive.
331 fn sanitize_view(&mut self) {
332 if !self.zoom.is_finite() || self.zoom <= 0.0 {
333 self.zoom = 1.0;
334 } else {
335 self.zoom = self.zoom.clamp(0.12, 3.5);
336 }
337 if !self.pan[0].is_finite() {
338 self.pan[0] = 0.0;
339 }
340 if !self.pan[1].is_finite() {
341 self.pan[1] = 0.0;
342 }
343 self.resize(self.size);
344 }
345
346 /// Drops only `NodeId` references and gestures that are no longer valid in `comp`,
347 /// keeping active valid gestures intact.
348 fn sanitize_stale(&mut self, comp: &Comp) {
349 self.sanitize_view();
350 let len = comp.nodes.len();
351 if self.scope.refresh(comp) {
352 self.fitted_once = false;
353 self.hovered_handle = None;
354 self.hovered_wire = None;
355 }
356 let scope = &self.scope;
357 let valid_visible = |id: NodeId| id.0 < len && scope.shows(comp.node(id));
358 self.selected.retain(|id| valid_visible(*id));
359 if self.primary.is_some_and(|id| !valid_visible(id)) {
360 self.primary = self.selected.iter().copied().next();
361 }
362 for slot in &mut self.viewed_nodes {
363 if slot.is_some_and(|id| id.0 >= len) {
364 *slot = None;
365 }
366 }
367 if self.hovered_node.is_some_and(|id| !valid_visible(id)) {
368 self.hovered_node = None;
369 }
370 if self.hovered_handle.as_ref().is_some_and(|h| !valid_visible(h.node)) {
371 self.hovered_handle = None;
372 }
373 if self.hovered_wire.as_ref().is_some_and(|w| !valid_visible(w.src) || !valid_visible(w.dst)) {
374 self.hovered_wire = None;
375 }
376 if self.lmb_drag_node.is_some_and(|(id, _, _)| !valid_visible(id)) {
377 self.lmb_drag_node = None;
378 }
379 if self.last_click.is_some_and(|(_, id)| !valid_visible(id)) {
380 self.last_click = None;
381 }
382 if self.modal.as_ref().is_some_and(|m| m.saved_positions.iter().any(|(id, _)| !valid_visible(*id))) {
383 self.modal = None;
384 self.orphaned_group = true;
385 }
386 if let Some(wd) = &mut self.wire_drag {
387 let stale_src = !valid_visible(wd.src);
388 let stale_det = wd.detached_from.as_ref().is_some_and(|(dst, _)| !valid_visible(*dst));
389 if stale_src || stale_det {
390 let owns = wd.owns_group();
391 self.wire_drag = None;
392 self.orphaned_group |= owns;
393 } else if wd.target.as_ref().is_some_and(|t| !valid_visible(t.node)) {
394 wd.target = None;
395 }
396 }
397 }
398
399 /// Removes any stale `NodeId`s from selection/viewed_nodes after undo/redo or deletion.
400 pub fn sanitize_ids(&mut self, comp: &Comp) {
401 self.sanitize_view();
402 let len = comp.nodes.len();
403 if self.scope.refresh(comp) {
404 self.fitted_once = false;
405 }
406 self.selected.retain(|id| id.0 < len && self.scope.shows(comp.node(*id)));
407 if self.primary.is_some_and(|id| id.0 >= len || !self.scope.shows(comp.node(id))) {
408 self.primary = self.selected.iter().copied().next();
409 }
410 for slot in &mut self.viewed_nodes {
411 if slot.is_some_and(|id| id.0 >= len) {
412 *slot = None;
413 }
414 }
415 if self.hovered_node.is_some_and(|id| id.0 >= len || !self.scope.shows(comp.node(id))) {
416 self.hovered_node = None;
417 }
418 self.hovered_handle = None;
419 self.hovered_wire = None;
420 self.abandon_gestures();
421 self.lmb_drag_node = None;
422 self.last_click = None;
423 }
424
425 /// Drops in-flight gestures that have no history to cancel through.
426 fn abandon_gestures(&mut self) {
427 let wire = self.wire_drag.take().is_some_and(|wd| wd.owns_group());
428 self.orphaned_group |= self.modal.take().is_some() || wire;
429 }
430
431 /// Computes a clean world-space spawn position for a newly added node.
432 pub fn spawn_position(&self, comp: &Comp, is_generator: bool) -> [f32; 2] {
433 if let Some(sel_id) = self.primary.filter(|id| id.0 < comp.nodes.len()) {
434 let p = comp.node(sel_id).pos;
435 if is_generator {
436 [p[0], p[1] - 55.0]
437 } else {
438 [p[0] + 110.0, p[1]]
439 }
440 } else {
441 self.pan
442 }
443 }
444
445 pub fn fit_all(&mut self, comp: &Comp) {
446 self.sanitize_stale(comp);
447 let ids: Vec<NodeId> = if !self.selected.is_empty() {
448 self.selected.iter().copied().collect()
449 } else {
450 self.scope.visible(comp)
451 };
452 self.fit_ids(comp, ids);
453 }
454
455 pub fn fit_comp(&mut self, comp: &Comp) {
456 self.sanitize_stale(comp);
457 let ids = self.scope.visible(comp);
458 self.fit_ids(comp, ids);
459 }
460
461 fn fit_ids(&mut self, comp: &Comp, target_ids: Vec<NodeId>) {
462 self.sanitize_view();
463 if target_ids.is_empty() {
464 return;
465 }
466 let mut min_x = f32::INFINITY;
467 let mut min_y = f32::INFINITY;
468 let mut max_x = f32::NEG_INFINITY;
469 let mut max_y = f32::NEG_INFINITY;
470 for id in target_ids {
471 let Some(node) = comp.nodes.get(id.0) else { continue };
472 let p = node.pos;
473 if !p[0].is_finite() || !p[1].is_finite() {
474 continue;
475 }
476 min_x = min_x.min(p[0] - NODE_W * 0.5);
477 max_x = max_x.max(p[0] + NODE_W * 0.5);
478 min_y = min_y.min(p[1] - NODE_H * 0.5);
479 max_y = max_y.max(p[1] + NODE_H * 0.5);
480 }
481 if !min_x.is_finite() || !max_x.is_finite() || !min_y.is_finite() || !max_y.is_finite() {
482 return;
483 }
484 let span_x = (max_x - min_x).max(200.0);
485 let span_y = (max_y - min_y).max(120.0);
486 let pad = 64.0;
487 let zx = ((self.size[0] - pad) / span_x).clamp(0.15, 1.5);
488 let zy = ((self.size[1] - pad) / span_y).clamp(0.15, 1.5);
489 self.zoom = zx.min(zy);
490 self.pan = [(min_x + max_x) * 0.5, (min_y + max_y) * 0.5];
491 self.fitted_once = true;
492 }
493
494 pub fn ensure_fitted(&mut self, comp: &Comp) {
495 if !self.fitted_once && self.size[0] > 40.0 && self.size[1] > 40.0 {
496 self.fit_comp(comp);
497 }
498 }
499
500 fn begin_modal(&mut self, comp: &Comp, history: &mut CompHistory, mode: TransformMode) {
501 if self.selected.is_empty() {
502 return;
503 }
504 let mut cx = 0.0_f32;
505 let mut cy = 0.0_f32;
506 let mut saved = Vec::with_capacity(self.selected.len());
507 for &id in &self.selected {
508 if id.0 >= comp.nodes.len() { continue; }
509 let p = comp.node(id).pos;
510 cx += p[0];
511 cy += p[1];
512 saved.push((id, p));
513 }
514 if saved.is_empty() {
515 return;
516 }
517 let label = match mode {
518 TransformMode::Grab => "Move Nodes",
519 TransformMode::Rotate => "Rotate Nodes",
520 TransformMode::Scale => "Scale Nodes",
521 };
522 history.begin_group(comp, label);
523 let n = saved.len() as f32;
524 self.modal = Some(ModalTransform {
525 mode,
526 axis: AxisLock::None,
527 pivot_world: [cx / n, cy / n],
528 start_pointer_world: self.local_to_world(self.pointer_local),
529 saved_positions: saved,
530 });
531 }
532
533 fn apply_modal(&mut self, comp: &mut Comp, shift_held: bool) {
534 let Some(m) = &self.modal else { return };
535 let cur = self.local_to_world(self.pointer_local);
536 let dx = cur[0] - m.start_pointer_world[0];
537 let dy = cur[1] - m.start_pointer_world[1];
538 let piv = m.pivot_world;
539
540 match m.mode {
541 TransformMode::Grab => {
542 let (mx, my) = match m.axis {
543 AxisLock::None => (dx, dy),
544 AxisLock::X => (dx, 0.0),
545 AxisLock::Y => (0.0, dy),
546 };
547 for &(id, orig) in &m.saved_positions {
548 comp.set_node_pos(id, [orig[0] + mx, orig[1] + my]);
549 }
550 }
551 TransformMode::Rotate => {
552 let a0 = (m.start_pointer_world[1] - piv[1]).atan2(m.start_pointer_world[0] - piv[0]);
553 let a1 = (cur[1] - piv[1]).atan2(cur[0] - piv[0]);
554 let da = a1 - a0;
555 let (c, s) = (da.cos(), da.sin());
556 for &(id, orig) in &m.saved_positions {
557 let rx = orig[0] - piv[0];
558 let ry = orig[1] - piv[1];
559 comp.set_node_pos(id, [piv[0] + rx * c - ry * s, piv[1] + rx * s + ry * c]);
560 }
561 }
562 TransformMode::Scale => {
563 let d0 = ((m.start_pointer_world[0] - piv[0]).powi(2) + (m.start_pointer_world[1] - piv[1]).powi(2)).sqrt().max(12.0);
564 let d1 = ((cur[0] - piv[0]).powi(2) + (cur[1] - piv[1]).powi(2)).sqrt();
565 let factor = (d1 / d0).clamp(0.1, 10.0);
566 let (sx, sy) = match m.axis {
567 AxisLock::None => (factor, factor),
568 AxisLock::X => (factor, 1.0),
569 AxisLock::Y => (1.0, factor),
570 };
571 for &(id, orig) in &m.saved_positions {
572 comp.set_node_pos(id, [
573 piv[0] + (orig[0] - piv[0]) * sx,
574 piv[1] + (orig[1] - piv[1]) * sy,
575 ]);
576 }
577 }
578 }
579 // Shift-dragging a single node over an existing pipe highlights it for splicing on release.
580 if m.mode == TransformMode::Grab && m.saved_positions.len() == 1 && shift_held {
581 let id = m.saved_positions[0].0;
582 let c_local = self.world_to_local(comp.node(id).pos);
583 self.hovered_wire = self.hit_wire(comp, c_local, Some(id)).filter(|w| {
584 !comp.would_create_cycle(w.src, id) && !comp.would_create_cycle(id, w.dst)
585 });
586 } else {
587 self.hovered_wire = None;
588 }
589 }
590
591 fn cancel_modal(&mut self, comp: &mut Comp, history: &mut CompHistory) {
592 if self.modal.take().is_some() {
593 history.cancel_group(comp);
594 }
595 self.hovered_wire = None;
596 }
597
598 fn confirm_modal(&mut self, comp: &mut Comp, history: &mut CompHistory, actions: &mut Vec<FlowAction>) {
599 if let Some(m) = self.modal.take() {
600 if m.mode == TransformMode::Grab && m.saved_positions.len() == 1 {
601 let id = m.saved_positions[0].0;
602 if let Some(w) = self.hovered_wire.take() {
603 match comp.splice_node_into_pipe(id, w.src, w.dst, &w.port) {
604 Ok(()) => {
605 actions.push(FlowAction::GraphMutated(Some(w.dst)));
606 actions.push(FlowAction::StatusNotice(format!(
607 "Spliced {} into pipe",
608 comp.node(id).name
609 )));
610 }
611 Err(e) => {
612 actions.push(FlowAction::StatusNotice(e));
613 }
614 }
615 }
616 }
617 history.commit_group(comp);
618 }
619 self.hovered_wire = None;
620 }
621
622 /// Drops an in-flight wire drag; a detached input is wired back.
623 fn cancel_wire_drag(&mut self, comp: &mut Comp, history: &mut CompHistory, actions: &mut Vec<FlowAction>) {
624 if self.wire_drag.take().is_some_and(|wd| wd.owns_group()) && history.cancel_group(comp) {
625 actions.push(FlowAction::GraphMutated(None));
626 }
627 }
628
629 /// Ends every held gesture, as the window losing focus must.
630 fn cancel_gestures(&mut self, comp: &mut Comp, history: &mut CompHistory, actions: &mut Vec<FlowAction>) {
631 self.cancel_modal(comp, history);
632 self.cancel_wire_drag(comp, history, actions);
633 self.panning = None;
634 self.box_select = None;
635 self.lmb_drag_node = None;
636 }
637
638 fn handle_key(
639 &mut self,
640 comp: &mut Comp,
641 history: &mut CompHistory,
642 physical: Option<PhysicalKey>,
643 key: &Key,
644 kmod: ModifiersState,
645 actions: &mut Vec<FlowAction>,
646 ) {
647 // An open modal or wire drag owns a history group; only keys that end or steer it may act.
648 let steering = matches!(key, Key::Named(NamedKey::Escape | NamedKey::Enter))
649 || (self.modal.is_some()
650 && matches!(key, Key::Character(c) if matches!(c.to_ascii_lowercase().as_str(), "x" | "y")));
651 if (self.modal.is_some() || self.wire_drag.is_some()) && !steering {
652 return;
653 }
654 let cmd = kmod.super_key() || kmod.control_key();
655 let plain = !cmd && !kmod.alt_key();
656 // Shift+Space: open Add Tool launcher
657 if kmod.shift_key()
658 && plain
659 && matches!(key, Key::Named(NamedKey::Space))
660 {
661 actions.push(FlowAction::OpenAddTool);
662 return;
663 }
664 // Numpad '.' (Blender Frame Selected) or Cmd+F or plain F
665 if physical == Some(PhysicalKey::Code(KeyCode::NumpadDecimal)) {
666 self.fit_all(comp);
667 return;
668 }
669 if physical == Some(PhysicalKey::Code(KeyCode::Backquote)) {
670 if plain {
671 self.viewed_nodes = [None, None];
672 actions.push(FlowAction::ClearViewers);
673 }
674 return;
675 }
676 match key {
677 Key::Named(NamedKey::Escape) => {
678 if self.modal.is_some() || self.wire_drag.is_some() {
679 if self.modal.is_some() {
680 self.cancel_modal(comp, history);
681 }
682 self.cancel_wire_drag(comp, history, actions);
683 } else if self.exit_group(comp) {
684 actions.push(FlowAction::SelectionChanged(self.primary));
685 actions.push(FlowAction::ScopeChanged);
686 }
687 }
688 Key::Named(NamedKey::Enter) => {
689 if self.modal.is_some() {
690 self.confirm_modal(comp, history, actions);
691 }
692 }
693 Key::Named(NamedKey::Delete) | Key::Named(NamedKey::Backspace) => {
694 if !self.scope.is_root() {
695 read_only_notice(actions);
696 } else if !self.selected.is_empty() {
697 let ids: Vec<NodeId> = self.selected.iter().copied().collect();
698 history.push_snapshot(comp, "Delete Nodes");
699 let deleted = comp.delete_nodes(&ids);
700 if !deleted.is_empty() {
701 self.sanitize_ids(comp);
702 self.selected.clear();
703 self.primary = None;
704 actions.push(FlowAction::SelectionChanged(None));
705 actions.push(FlowAction::GraphMutated(None));
706 actions.push(FlowAction::StatusNotice(format!(
707 "Deleted {} node{}",
708 deleted.len(),
709 if deleted.len() == 1 { "" } else { "s" }
710 )));
711 }
712 }
713 }
714 Key::Named(NamedKey::F2) => {
715 if !self.scope.is_root() {
716 read_only_notice(actions);
717 } else if let Some(id) = self.primary {
718 actions.push(FlowAction::RequestRename(id));
719 }
720 }
721 Key::Character(c) => match c.to_ascii_lowercase().as_str() {
722 "`" | "~" if plain => {
723 self.viewed_nodes = [None, None];
724 actions.push(FlowAction::ClearViewers);
725 }
726 "c" if cmd && !kmod.shift_key() => {
727 if !self.selected.is_empty() {
728 let mut ids: Vec<NodeId> = self.selected.iter().copied().collect();
729 ids.sort_unstable_by_key(|id| id.0);
730 actions.push(FlowAction::CopyNodes(ids));
731 }
732 }
733 "v" if cmd && !kmod.shift_key() => actions.push(FlowAction::PasteNodes),
734 "d" if cmd && !kmod.shift_key() && !self.scope.is_root() => read_only_notice(actions),
735 "d" if cmd && !kmod.shift_key() => {
736 if !self.selected.is_empty() {
737 let ids: Vec<NodeId> = self.selected.iter().copied().collect();
738 history.push_snapshot(comp, "Duplicate Nodes");
739 let created = comp.duplicate_nodes(&ids, [44.0, 28.0]);
740 if !created.is_empty() {
741 self.selected.clear();
742 for &nid in &created {
743 self.selected.insert(nid);
744 }
745 self.primary = created.first().copied();
746 actions.push(FlowAction::SelectionChanged(self.primary));
747 actions.push(FlowAction::GraphMutated(self.primary));
748 actions.push(FlowAction::StatusNotice(format!(
749 "Duplicated {} node{}",
750 created.len(),
751 if created.len() == 1 { "" } else { "s" }
752 )));
753 }
754 }
755 }
756 "f" if !kmod.control_key() && !kmod.alt_key() => self.fit_all(comp),
757 "." if plain => self.fit_all(comp),
758 "g" if plain && self.modal.is_none() && !self.scope.is_root() => read_only_notice(actions),
759 "g" if plain && self.modal.is_none() => {
760 self.begin_modal(comp, history, TransformMode::Grab);
761 }
762 "r" if plain && self.modal.is_none() && !self.scope.is_root() => read_only_notice(actions),
763 "r" if plain && self.modal.is_none() => {
764 self.begin_modal(comp, history, TransformMode::Rotate);
765 }
766 "s" if plain && self.modal.is_none() && !self.scope.is_root() => read_only_notice(actions),
767 "s" if plain && self.modal.is_none() => {
768 self.begin_modal(comp, history, TransformMode::Scale);
769 }
770 "x" if plain && self.modal.is_some() => {
771 if let Some(m) = &mut self.modal {
772 m.axis = if m.axis == AxisLock::X { AxisLock::None } else { AxisLock::X };
773 }
774 self.apply_modal(comp, kmod.shift_key());
775 }
776 "y" if plain && self.modal.is_some() => {
777 if let Some(m) = &mut self.modal {
778 m.axis = if m.axis == AxisLock::Y { AxisLock::None } else { AxisLock::Y };
779 }
780 self.apply_modal(comp, kmod.shift_key());
781 }
782 "a" if plain => {
783 let visible = self.scope.visible(comp);
784 if self.selected.len() == visible.len() {
785 self.selected.clear();
786 self.primary = None;
787 } else {
788 self.selected = visible.iter().copied().collect();
789 self.primary = visible.first().copied();
790 }
791 actions.push(FlowAction::SelectionChanged(self.primary));
792 }
793 "1" if plain => {
794 if let Some(id) = self.primary {
795 if self.viewed_nodes[0] == Some(id) {
796 self.viewed_nodes[0] = None;
797 actions.push(FlowAction::ClearViewer(0));
798 } else {
799 self.viewed_nodes[0] = Some(id);
800 actions.push(FlowAction::ViewNode(0, id));
801 }
802 } else if self.viewed_nodes[0].is_some() {
803 self.viewed_nodes[0] = None;
804 actions.push(FlowAction::ClearViewer(0));
805 }
806 }
807 "2" if plain => {
808 if let Some(id) = self.primary {
809 if self.viewed_nodes[1] == Some(id) {
810 self.viewed_nodes[1] = None;
811 actions.push(FlowAction::ClearViewer(1));
812 } else {
813 self.viewed_nodes[1] = Some(id);
814 actions.push(FlowAction::ViewNode(1, id));
815 }
816 } else if self.viewed_nodes[1].is_some() {
817 self.viewed_nodes[1] = None;
818 actions.push(FlowAction::ClearViewer(1));
819 }
820 }
821 "p" if plain && !self.scope.is_root() => read_only_notice(actions),
822 "p" if plain => {
823 if !self.selected.is_empty() {
824 let ids: Vec<NodeId> = self.selected.iter().copied().collect();
825 history.push_snapshot(comp, "Toggle Passthrough");
826 for id in ids {
827 comp.toggle_passthrough(id);
828 }
829 actions.push(FlowAction::GraphMutated(self.primary));
830 }
831 }
832 _ => {}
833 },
834 _ => {}
835 }
836 }
837
838 pub fn input(
839 &mut self,
840 comp: &mut Comp,
841 history: &mut CompHistory,
842 event: ui::Event,
843 rect: [f32; 4],
844 pointer_window: [f32; 2],
845 modifiers: ModifiersState,
846 ) -> Vec<FlowAction> {
847 let mut actions = Vec::new();
848 self.sanitize_stale(comp);
849 self.pointer_local = [pointer_window[0] - rect[0], pointer_window[1] - rect[1]];
850 if std::mem::take(&mut self.orphaned_group) {
851 history.commit_group(comp);
852 }
853
854 match event {
855 ui::Event::PointerCancelled => self.cancel_gestures(comp, history, &mut actions),
856 ui::Event::PointerMoved(p) => {
857 self.pointer_local = [p[0] - rect[0], p[1] - rect[1]];
858 if let Some((start_p, start_pan)) = self.panning {
859 self.pan = [
860 start_pan[0] - (self.pointer_local[0] - start_p[0]) / self.zoom,
861 start_pan[1] - (self.pointer_local[1] - start_p[1]) / self.zoom,
862 ];
863 } else if self.modal.is_some() {
864 self.apply_modal(comp, modifiers.shift_key());
865 } else if self.wire_drag.is_some() {
866 if let Some(wd) = &mut self.wire_drag {
867 if let Some((press, (dst, port))) = wd.pending.zip(wd.detached_from.as_ref()) {
868 if (press[0] - self.pointer_local[0]).hypot(press[1] - self.pointer_local[1]) <= DETACH_DRAG {
869 return actions;
870 }
871 history.begin_group(comp, "Rewire");
872 comp.disconnect(*dst, port);
873 actions.push(FlowAction::GraphMutated(Some(*dst)));
874 wd.pending = None;
875 }
876 }
877 let hit = self.hit_drop_target(comp, self.pointer_local);
878 if let Some(wd) = &mut self.wire_drag {
879 wd.cursor_local = self.pointer_local;
880 if wd.target.as_ref().map(|t| (t.node, t.port.as_str())) != hit {
881 wd.target = hit.map(|(node, port)| DropTarget {
882 node,
883 port: port.to_owned(),
884 cycle: comp.would_create_cycle(wd.src, node),
885 });
886 }
887 }
888 } else if let Some(bs) = &mut self.box_select {
889 bs.cur_local = self.pointer_local;
890 } else if let Some((nid, start_l, ref mut moved)) = self.lmb_drag_node {
891 let dx = self.pointer_local[0] - start_l[0];
892 let dy = self.pointer_local[1] - start_l[1];
893 if !*moved && dx * dx + dy * dy > 16.0 {
894 *moved = true;
895 if !self.selected.contains(&nid) {
896 self.selected.clear();
897 self.selected.insert(nid);
898 self.primary = Some(nid);
899 actions.push(FlowAction::SelectionChanged(self.primary));
900 }
901 self.begin_modal(comp, history, TransformMode::Grab);
902 }
903 } else {
904 self.hovered_node = self.hit_node(comp, self.pointer_local);
905 let handle = self.hit_handle(comp, self.pointer_local);
906 if self.hovered_handle.as_ref().map(|h| (h.node, h.port.as_deref())) != handle {
907 self.hovered_handle = handle.map(|(node, port)| HandleId { node, port: port.map(str::to_owned) });
908 }
909 self.hovered_wire = if self.hovered_node.is_none() && handle.is_none() {
910 self.hit_wire(comp, self.pointer_local, None)
911 } else {
912 None
913 };
914 }
915 }
916 ui::Event::Button { button, pressed, at } => {
917 if button == MouseButton::Middle || (button == MouseButton::Left && modifiers.alt_key()) {
918 if pressed {
919 self.panning = Some((self.pointer_local, self.pan));
920 } else {
921 self.panning = None;
922 }
923 } else if button == MouseButton::Right {
924 if pressed && self.modal.is_some() {
925 self.cancel_modal(comp, history);
926 } else if pressed && self.wire_drag.is_some() {
927 self.cancel_wire_drag(comp, history, &mut actions);
928 } else if pressed {
929 // Right-click a hovered wire or connected input port to disconnect it!
930 if !self.scope.is_root() {
931 read_only_notice(&mut actions);
932 } else if let Some(w) = self.hit_wire(comp, self.pointer_local, None) {
933 history.begin_group(comp, "Disconnect");
934 if comp.disconnect(w.dst, &w.port) {
935 self.hovered_wire = None;
936 actions.push(FlowAction::GraphMutated(Some(w.dst)));
937 actions.push(FlowAction::StatusNotice(format!(
938 "Disconnected {}.{}",
939 comp.node(w.dst).name,
940 w.port
941 )));
942 }
943 history.commit_group(comp);
944 }
945 }
946 } else if button == MouseButton::Left {
947 if pressed {
948 let handle = self.hit_handle(comp, self.pointer_local).filter(|_| self.scope.is_root());
949 if self.modal.is_some() {
950 self.confirm_modal(comp, history, &mut actions);
951 } else if let Some((src, None)) = handle {
952 self.wire_drag = Some(WireDrag {
953 src,
954 src_output: default_output(&comp.node(src).kind).to_owned(),
955 cursor_local: self.pointer_local,
956 target: None,
957 detached_from: None,
958 pending: None,
959 });
960 } else if let Some((dst, port, src)) = handle.and_then(|(dst, port)| {
961 let port = port?;
962 let src = self.upstream_of(comp, comp.node(dst), port)?;
963 Some((dst, port.to_owned(), src))
964 }) {
965 // Dragging a connected triangle detaches it: drop on another triangle to move
966 // the wire, or on empty canvas to disconnect.
967 let src_output = comp.node(dst).inputs[&port].source_output.clone();
968 self.wire_drag = Some(WireDrag {
969 src,
970 src_output: src_output.unwrap_or_else(|| default_output(&comp.node(src).kind).to_owned()),
971 cursor_local: self.pointer_local,
972 target: None,
973 detached_from: Some((dst, port)),
974 pending: Some(self.pointer_local),
975 });
976 } else if let Some(nid) = self.hit_node(comp, self.pointer_local) {
977 let double = self.last_click.is_some_and(|(t, prev)| prev == nid && at.duration_since(t) <= DOUBLE_CLICK);
978 self.last_click = Some((at, nid));
979 if double && !modifiers.shift_key() && self.enter_group(comp, nid) {
980 actions.push(FlowAction::SelectionChanged(None));
981 actions.push(FlowAction::ScopeChanged);
982 return actions;
983 }
984 if modifiers.shift_key() {
985 if !self.selected.remove(&nid) {
986 self.selected.insert(nid);
987 self.primary = Some(nid);
988 } else if self.primary == Some(nid) {
989 self.primary = self.selected.iter().copied().next();
990 }
991 } else if !self.selected.contains(&nid) {
992 self.selected.clear();
993 self.selected.insert(nid);
994 self.primary = Some(nid);
995 } else {
996 self.primary = Some(nid);
997 }
998 actions.push(FlowAction::SelectionChanged(self.primary));
999 if self.scope.is_root() {
1000 self.lmb_drag_node = Some((nid, self.pointer_local, false));
1001 }
1002 } else {
1003 if !modifiers.shift_key() {
1004 self.selected.clear();
1005 self.primary = None;
1006 actions.push(FlowAction::SelectionChanged(None));
1007 }
1008 self.box_select = Some(BoxSelect {
1009 start_local: self.pointer_local,
1010 cur_local: self.pointer_local,
1011 });
1012 }
1013 } else {
1014 if let Some((_nid, _start, moved)) = self.lmb_drag_node.take() {
1015 if moved && self.modal.is_some() {
1016 self.confirm_modal(comp, history, &mut actions);
1017 }
1018 }
1019 if let Some(wd) = self.wire_drag.take().filter(|wd| wd.pending.is_none()) {
1020 let detached = wd.detached_from.is_some();
1021 let target = self.hit_drop_target(comp, self.pointer_local).map(|(node, port)| (node, port.to_owned()));
1022 if let Some((dst, port)) = target {
1023 if wd.detached_from.as_ref() == Some(&(dst, port.clone())) {
1024 // Dropped back where it started: nothing changed, leave no undo entry.
1025 if history.cancel_group(comp) {
1026 actions.push(FlowAction::GraphMutated(Some(dst)));
1027 }
1028 } else {
1029 if !detached {
1030 history.begin_group(comp, "Connect");
1031 }
1032 match comp.connect_output(wd.src, &wd.src_output, dst, &port) {
1033 Ok(()) => {
1034 history.commit_group(comp);
1035 actions.push(FlowAction::GraphMutated(Some(dst)));
1036 }
1037 Err(e) => {
1038 if history.cancel_group(comp) && detached {
1039 actions.push(FlowAction::GraphMutated(None));
1040 }
1041 actions.push(FlowAction::StatusNotice(e));
1042 }
1043 }
1044 }
1045 } else if let Some((dst, port)) = wd.detached_from {
1046 history.commit_group(comp);
1047 actions.push(FlowAction::StatusNotice(format!(
1048 "Disconnected {}.{}",
1049 comp.node(dst).name,
1050 port
1051 )));
1052 }
1053 }
1054 if let Some(bs) = self.box_select.take() {
1055 let x0 = bs.start_local[0].min(bs.cur_local[0]);
1056 let x1 = bs.start_local[0].max(bs.cur_local[0]);
1057 let y0 = bs.start_local[1].min(bs.cur_local[1]);
1058 let y1 = bs.start_local[1].max(bs.cur_local[1]);
1059 if (x1 - x0) > 4.0 || (y1 - y0) > 4.0 {
1060 for n in comp.nodes.iter().filter(|n| self.scope.shows(n)) {
1061 let c = self.world_to_local(n.pos);
1062 if c[0] >= x0 && c[0] <= x1 && c[1] >= y0 && c[1] <= y1 {
1063 self.selected.insert(n.id);
1064 self.primary = Some(n.id);
1065 }
1066 }
1067 actions.push(FlowAction::SelectionChanged(self.primary));
1068 }
1069 }
1070 }
1071 }
1072 }
1073 ui::Event::Wheel(delta) => {
1074 // Blender & Fusion convention: plain scroll zooms toward mouse cursor; Shift+scroll pans.
1075 if modifiers.shift_key() {
1076 self.pan[0] -= delta[0] / self.zoom;
1077 self.pan[1] -= delta[1] / self.zoom;
1078 } else {
1079 let factor = (1.0 + delta[1] * 0.0045).clamp(0.7, 1.4);
1080 self.zoom_at(factor, self.pointer_local);
1081 }
1082 }
1083 ui::Event::Pinch(delta) => {
1084 let factor = (1.0 + delta).clamp(0.7, 1.4);
1085 self.zoom_at(factor, self.pointer_local);
1086 }
1087 ui::Event::KeyInput { physical, key, state: ElementState::Pressed, repeat: false, modifiers: kmod, .. } => {
1088 self.handle_key(comp, history, Some(physical), &key, kmod, &mut actions);
1089 }
1090 ui::Event::Key { key, modifiers: kmod, .. } => {
1091 self.handle_key(comp, history, None, &key, kmod, &mut actions);
1092 }
1093 _ => {}
1094 }
1095
1096 actions
1097 }
1098
1099 fn zoom_at(&mut self, factor: f32, pivot_local: [f32; 2]) {
1100 self.sanitize_view();
1101 if !factor.is_finite() || !pivot_local[0].is_finite() || !pivot_local[1].is_finite() {
1102 return;
1103 }
1104 let before = self.local_to_world(pivot_local);
1105 self.zoom = (self.zoom * factor).clamp(0.12, 3.5);
1106 let after = self.local_to_world(pivot_local);
1107 self.pan[0] += before[0] - after[0];
1108 self.pan[1] += before[1] - after[1];
1109 }
1110}
1111
1112fn read_only_notice(actions: &mut Vec<FlowAction>) {
1113 actions.push(FlowAction::StatusNotice("Group contents are read-only; press Esc to leave the group".to_owned()));
1114}
1115
1116/// Samples a cubic Bezier wire leaving `a` along `a_normal` and arriving at `b` from the side `b_normal` faces.
1117pub fn sample_wire_bezier(a: [f32; 2], a_normal: [f32; 2], b: [f32; 2], b_normal: [f32; 2], steps: usize) -> Vec<[f32; 2]> {
1118 let steps = steps.max(2);
1119 let dist = ((b[0] - a[0]).powi(2) + (b[1] - a[1]).powi(2)).sqrt();
1120 let handle = (dist * 0.42).clamp(24.0, 140.0);
1121 let c1 = [a[0] + a_normal[0] * handle, a[1] + a_normal[1] * handle];
1122 let c2 = [b[0] + b_normal[0] * handle * 0.65, b[1] + b_normal[1] * handle * 0.65];
1123 let mut pts = Vec::with_capacity(steps + 1);
1124 for i in 0..=steps {
1125 let t = i as f32 / steps as f32;
1126 let u = 1.0 - t;
1127 let u2 = u * u;
1128 let t2 = t * t;
1129 let x = u2 * u * a[0] + 3.0 * u2 * t * c1[0] + 3.0 * u * t2 * c2[0] + t2 * t * b[0];
1130 let y = u2 * u * a[1] + 3.0 * u2 * t * c1[1] + 3.0 * u * t2 * c2[1] + t2 * t * b[1];
1131 pts.push([x, y]);
1132 }
1133 pts
1134}
1135
1136#[cfg(test)]
1137mod tests {
1138 use super::*;
1139 use crate::hit::dist_to_seg;
1140
1141 fn test_comp() -> Comp {
1142 let src = r#"Composition {
1143 Tools = ordered() {
1144 BG1 = Background {
1145 ViewInfo = OperatorInfo { Pos = { 0, 0 } },
1146 },
1147 Merge1 = Merge {
1148 Inputs = {
1149 Background = Input { SourceOp = "BG1", Source = "Output" },
1150 },
1151 ViewInfo = OperatorInfo { Pos = { 160, 0 } },
1152 },
1153 },
1154 }"#;
1155 Comp::from_fusion_str(src).expect("parse comp")
1156 }
1157
1158 #[test]
1159 fn bezier_preview_endpoints_match() {
1160 let pts = sample_wire_bezier([10.0, 20.0], [1.0, 0.0], [210.0, 80.0], [-1.0, 0.0], 16);
1161 assert_eq!(pts.len(), 17);
1162 assert!((pts[0][0] - 10.0).abs() < 1e-4);
1163 assert!((pts[0][1] - 20.0).abs() < 1e-4);
1164 assert!((pts[16][0] - 210.0).abs() < 1e-4);
1165 assert!((pts[16][1] - 80.0).abs() < 1e-4);
1166 }
1167
1168 #[test]
1169 fn dist_to_seg_basic() {
1170 assert!((dist_to_seg([5.0, 3.0], [0.0, 0.0], [10.0, 0.0]) - 3.0).abs() < 1e-5);
1171 assert!((dist_to_seg([12.0, 0.0], [0.0, 0.0], [10.0, 0.0]) - 2.0).abs() < 1e-5);
1172 }
1173
1174 #[test]
1175 fn flow_hit_node_and_input_ports() {
1176 let theme = ui::Theme::new(&theme::KNIFE, true);
1177 let mut flow = FlowView::new(&theme);
1178 flow.size = [800.0, 600.0];
1179 flow.pan = [80.0, 0.0];
1180 flow.zoom = 1.0;
1181
1182 let comp = test_comp();
1183 let bg = comp.find_node("BG1").unwrap();
1184 let merge = comp.find_node("Merge1").unwrap();
1185
1186 let bg_local = flow.world_to_local(comp.node(bg).pos);
1187 assert_eq!(flow.hit_node(&comp, bg_local), Some(bg));
1188
1189 let merge_local = flow.world_to_local(comp.node(merge).pos);
1190 assert_eq!(flow.hit_node(&comp, merge_local), Some(merge));
1191
1192 // Each triangle drops on its own port; the body picks the first open main port.
1193 let m = ports::Metrics::at(flow.zoom);
1194 for port in ["Background", "Foreground", "EffectMask"] {
1195 let slot = flow.input_slot(&comp, comp.node(merge), port).unwrap();
1196 assert_eq!(flow.hit_drop_target(&comp, slot.center(m)), Some((merge, port)));
1197 }
1198 assert_eq!(flow.hit_drop_target(&comp, merge_local), Some((merge, "Foreground")));
1199 assert_eq!(flow.hit_drop_target(&comp, [0.0, 0.0]), None);
1200 }
1201
1202 #[test]
1203 fn flow_spawn_position_generator_vs_effect() {
1204 let theme = ui::Theme::new(&theme::KNIFE, true);
1205 let mut flow = FlowView::new(&theme);
1206 let comp = test_comp();
1207 let bg = comp.find_node("BG1").unwrap();
1208 flow.primary = Some(bg);
1209 let p_eff = flow.spawn_position(&comp, false);
1210 let p_gen = flow.spawn_position(&comp, true);
1211 assert!(p_eff[0] > comp.node(bg).pos[0]);
1212 assert!(p_gen[1] < comp.node(bg).pos[1]);
1213 }
1214
1215 const GROUP_COMP: &str = r#"Composition {
1216 Tools = ordered() {
1217 BG1 = Background { ViewInfo = OperatorInfo { Pos = { 0, 0 } }, },
1218 Outer = GroupOperator {
1219 Outputs = { Output1 = InstanceOutput { SourceOp = "Mid", Source = "Output" }, },
1220 ViewInfo = GroupInfo { Pos = { 200, 0 } },
1221 Tools = ordered() {
1222 A = Blur { ViewInfo = OperatorInfo { Pos = { 0, 100 } }, },
1223 ASpline = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, },
1224 Mid = Merge {
1225 Inputs = { Background = Input { SourceOp = "A", Source = "Output" }, },
1226 ViewInfo = OperatorInfo { Pos = { 110, 100 } },
1227 },
1228 Inner = GroupOperator {
1229 ViewInfo = GroupInfo { Pos = { 220, 100 } },
1230 Tools = ordered() {
1231 Deep = Blur { ViewInfo = OperatorInfo { Pos = { 0, 50 } }, },
1232 },
1233 },
1234 },
1235 },
1236 A = Background { ViewInfo = OperatorInfo { Pos = { 400, 0 } }, },
1237 },
1238 }"#;
1239
1240 fn group_flow() -> (Comp, FlowView) {
1241 let comp = Comp::from_fusion_str(GROUP_COMP).expect("parse group comp");
1242 let theme = ui::Theme::new(&theme::KNIFE, true);
1243 let mut flow = FlowView::new(&theme);
1244 flow.size = [800.0, 600.0];
1245 flow.reset_for_comp(&comp);
1246 flow.pan = [0.0, 0.0];
1247 flow.zoom = 1.0;
1248 (comp, flow)
1249 }
1250
1251 fn id(comp: &Comp, name: &str) -> NodeId {
1252 comp.find_node(name).unwrap()
1253 }
1254
1255 fn press(flow: &mut FlowView, comp: &mut Comp, history: &mut CompHistory, at: Instant, node: NodeId) -> Vec<FlowAction> {
1256 let local = flow.world_to_local(comp.node(node).pos);
1257 flow.input(
1258 comp,
1259 history,
1260 ui::Event::Button { button: MouseButton::Left, pressed: true, at },
1261 [0.0, 0.0, 800.0, 600.0],
1262 local,
1263 ModifiersState::empty(),
1264 )
1265 }
1266
1267 fn key(flow: &mut FlowView, comp: &mut Comp, history: &mut CompHistory, key: Key, modifiers: ModifiersState) -> Vec<FlowAction> {
1268 flow.input(
1269 comp,
1270 history,
1271 ui::Event::Key { key, text: None, modifiers },
1272 [0.0, 0.0, 800.0, 600.0],
1273 [0.0, 0.0],
1274 modifiers,
1275 )
1276 }
1277
1278 #[test]
1279 fn group_children_are_direct_tools_only() {
1280 let (comp, _) = group_flow();
1281 let names = |g: &str| -> Vec<&str> {
1282 group_children(&comp, id(&comp, g)).into_iter().map(|c| comp.node(c).name.as_str()).collect()
1283 };
1284 assert_eq!(names("Outer"), ["A", "Mid", "Inner"]);
1285 assert_eq!(names("Inner"), ["Deep"]);
1286 assert!(group_children(&comp, id(&comp, "BG1")).is_empty());
1287 }
1288
1289 #[test]
1290 fn enter_and_exit_group_filter_visible_nodes() {
1291 let (comp, mut flow) = group_flow();
1292 let (bg, outer, inner) = (id(&comp, "BG1"), id(&comp, "Outer"), id(&comp, "Inner"));
1293 let (mid, deep) = (id(&comp, "Mid"), id(&comp, "Deep"));
1294 flow.selected.insert(bg);
1295 flow.primary = Some(bg);
1296
1297 // Root shows only top-level tools; internal tools are not enterable from the root.
1298 assert_eq!(flow.hit_node(&comp, flow.world_to_local(comp.node(bg).pos)), Some(bg));
1299 assert_eq!(flow.hit_node(&comp, flow.world_to_local(comp.node(mid).pos)), None);
1300 assert!(!flow.enter_group(&comp, mid));
1301 assert!(!flow.enter_group(&comp, bg));
1302 assert!(flow.scope_path().is_empty());
1303
1304 assert!(flow.enter_group(&comp, outer));
1305 assert_eq!(flow.scope_path(), [outer]);
1306 assert!(flow.selected.is_empty() && flow.primary.is_none());
1307 assert_eq!(flow.hit_node(&comp, flow.world_to_local(comp.node(mid).pos)), Some(mid));
1308 assert_eq!(flow.hit_node(&comp, flow.world_to_local(comp.node(bg).pos)), None);
1309 assert_eq!(flow.hit_node(&comp, flow.world_to_local(comp.node(deep).pos)), None);
1310
1311 // Nested group, then back out one level at a time; leaving selects the group left.
1312 assert!(flow.enter_group(&comp, inner));
1313 assert_eq!(flow.scope_path(), [outer, inner]);
1314 assert_eq!(flow.hit_node(&comp, flow.world_to_local(comp.node(deep).pos)), Some(deep));
1315 assert!(flow.exit_group(&comp));
1316 assert_eq!(flow.scope_path(), [outer]);
1317 assert_eq!(flow.primary, Some(inner));
1318 assert!(flow.exit_to_depth(&comp, 0));
1319 assert!(flow.scope_path().is_empty());
1320 assert_eq!(flow.primary, Some(outer));
1321 assert_eq!(flow.selected, HashSet::from([outer]));
1322 assert!(!flow.exit_group(&comp));
1323 }
1324
1325 #[test]
1326 fn wires_resolve_within_the_shown_level() {
1327 let (comp, mut flow) = group_flow();
1328 let outer = id(&comp, "Outer");
1329 let (inner_a, root_a) = (comp.nodes.iter().find(|n| n.internal && n.name == "A").unwrap().id, id(&comp, "A"));
1330 assert_ne!(inner_a, root_a);
1331 assert_eq!(flow.scope.resolve(&comp, "A"), Some(root_a));
1332 flow.enter_group(&comp, outer);
1333 assert_eq!(flow.scope.resolve(&comp, "A"), Some(inner_a));
1334 assert_eq!(flow.scope.resolve(&comp, "BG1"), None);
1335
1336 // Mid's wire from A is hittable between the two inner nodes.
1337 let mid = id(&comp, "Mid");
1338 let mid_pos = comp.node(mid).pos;
1339 let a_pos = comp.node(inner_a).pos;
1340 let midpoint = [(mid_pos[0] + a_pos[0]) * 0.5, (mid_pos[1] + a_pos[1]) * 0.5];
1341 let wire = flow.hit_wire(&comp, flow.world_to_local(midpoint), None).expect("wire");
1342 assert_eq!((wire.src, wire.dst), (inner_a, mid));
1343 }
1344
1345 #[test]
1346 fn double_click_enters_group_and_escape_leaves() {
1347 let (mut comp, mut flow) = group_flow();
1348 let mut history = CompHistory::new();
1349 let (bg, outer) = (id(&comp, "BG1"), id(&comp, "Outer"));
1350 let t0 = Instant::now();
1351
1352 // Double-clicking a plain tool, or two slow clicks on a group, never enters.
1353 press(&mut flow, &mut comp, &mut history, t0, bg);
1354 press(&mut flow, &mut comp, &mut history, t0 + Duration::from_millis(100), bg);
1355 assert!(flow.scope_path().is_empty());
1356 press(&mut flow, &mut comp, &mut history, t0, outer);
1357 press(&mut flow, &mut comp, &mut history, t0 + Duration::from_millis(900), outer);
1358 assert!(flow.scope_path().is_empty());
1359
1360 let acts = press(&mut flow, &mut comp, &mut history, t0 + Duration::from_millis(1000), outer);
1361 assert_eq!(flow.scope_path(), [outer]);
1362 assert!(acts.iter().any(|a| matches!(a, FlowAction::ScopeChanged)));
1363
1364 let acts = key(&mut flow, &mut comp, &mut history, Key::Named(NamedKey::Escape), ModifiersState::empty());
1365 assert!(flow.scope_path().is_empty());
1366 assert!(acts.iter().any(|a| matches!(a, FlowAction::ScopeChanged)));
1367 assert_eq!(flow.primary, Some(outer));
1368
1369 // Escape at the root does nothing.
1370 let acts = key(&mut flow, &mut comp, &mut history, Key::Named(NamedKey::Escape), ModifiersState::empty());
1371 assert!(acts.is_empty());
1372 }
1373
1374 #[test]
1375 fn group_view_is_read_only_but_copyable() {
1376 let (mut comp, mut flow) = group_flow();
1377 let mut history = CompHistory::new();
1378 let (outer, mid) = (id(&comp, "Outer"), id(&comp, "Mid"));
1379 flow.enter_group(&comp, outer);
1380 flow.selected.insert(mid);
1381 flow.primary = Some(mid);
1382 let nodes = comp.nodes.len();
1383
1384 for k in ["g", "p"] {
1385 let acts = key(&mut flow, &mut comp, &mut history, Key::Character(k.into()), ModifiersState::empty());
1386 assert!(matches!(acts.as_slice(), [FlowAction::StatusNotice(_)]), "{k}");
1387 }
1388 let acts = key(&mut flow, &mut comp, &mut history, Key::Named(NamedKey::Delete), ModifiersState::empty());
1389 assert!(matches!(acts.as_slice(), [FlowAction::StatusNotice(_)]));
1390 let acts = key(&mut flow, &mut comp, &mut history, Key::Character("d".into()), ModifiersState::SUPER);
1391 assert!(matches!(acts.as_slice(), [FlowAction::StatusNotice(_)]));
1392 assert_eq!(comp.nodes.len(), nodes);
1393 assert!(!comp.node(mid).bypassed);
1394 assert!(!history.can_undo());
1395
1396 let acts = key(&mut flow, &mut comp, &mut history, Key::Character("c".into()), ModifiersState::SUPER);
1397 assert!(matches!(acts.as_slice(), [FlowAction::CopyNodes(ids)] if ids == &[mid]));
1398 }
1399
1400 #[test]
1401 fn copy_and_paste_shortcuts_emit_requests() {
1402 let (mut comp, mut flow) = group_flow();
1403 let mut history = CompHistory::new();
1404 let bg = id(&comp, "BG1");
1405
1406 let none = key(&mut flow, &mut comp, &mut history, Key::Character("c".into()), ModifiersState::SUPER);
1407 assert!(none.is_empty(), "nothing selected, nothing to copy");
1408
1409 flow.selected.insert(bg);
1410 flow.primary = Some(bg);
1411 let acts = key(&mut flow, &mut comp, &mut history, Key::Character("c".into()), ModifiersState::SUPER);
1412 assert!(matches!(acts.as_slice(), [FlowAction::CopyNodes(ids)] if ids == &[bg]));
1413 let acts = key(&mut flow, &mut comp, &mut history, Key::Character("v".into()), ModifiersState::SUPER);
1414 assert!(matches!(acts.as_slice(), [FlowAction::PasteNodes]));
1415 // Plain `c` / `v` are not shortcuts.
1416 let acts = key(&mut flow, &mut comp, &mut history, Key::Character("v".into()), ModifiersState::empty());
1417 assert!(acts.is_empty());
1418 }
1419
1420 #[test]
1421 fn sanitize_drops_scope_levels_that_no_longer_exist() {
1422 let (comp, mut flow) = group_flow();
1423 let (outer, inner) = (id(&comp, "Outer"), id(&comp, "Inner"));
1424 flow.enter_group(&comp, outer);
1425 flow.enter_group(&comp, inner);
1426 flow.sanitize_ids(&comp);
1427 assert_eq!(flow.scope_path(), [outer, inner]);
1428
1429 let flat = test_comp();
1430 flow.sanitize_ids(&flat);
1431 assert!(flow.scope_path().is_empty());
1432 assert!(flow.selected.is_empty());
1433 }
1434
1435 #[test]
1436 fn escape_during_wire_detach_restores_the_wire_without_an_undo_entry() {
1437 let mut comp = test_comp();
1438 let mut history = CompHistory::new();
1439 let theme = ui::Theme::new(&theme::KNIFE, true);
1440 let mut flow = FlowView::new(&theme);
1441 flow.size = [800.0, 600.0];
1442 flow.pan = [80.0, 0.0];
1443 flow.zoom = 1.0;
1444 let merge = id(&comp, "Merge1");
1445 let m = ports::Metrics::at(flow.zoom);
1446 let port = flow.input_slot(&comp, comp.node(merge), "Background").unwrap().center(m);
1447 let rect = [0.0, 0.0, 800.0, 600.0];
1448
1449 flow.input(
1450 &mut comp,
1451 &mut history,
1452 ui::Event::Button { button: MouseButton::Left, pressed: true, at: Instant::now() },
1453 rect,
1454 port,
1455 ModifiersState::empty(),
1456 );
1457 assert!(flow.wire_drag.is_some());
1458 assert_eq!(source(&comp, merge, "Background").as_deref(), Some("BG1"), "a bare press detaches nothing");
1459 flow.input(&mut comp, &mut history, ui::Event::PointerMoved([port[0] + 30.0, port[1] + 30.0]), rect, [port[0] + 30.0, port[1] + 30.0], ModifiersState::empty());
1460 assert!(comp.node(merge).inputs["Background"].source_op.is_none());
1461 assert!(history.in_group());
1462
1463 let acts = key(&mut flow, &mut comp, &mut history, Key::Named(NamedKey::Escape), ModifiersState::empty());
1464 assert!(flow.wire_drag.is_none());
1465 assert_eq!(comp.node(merge).inputs["Background"].source_op.as_deref(), Some("BG1"));
1466 assert!(acts.iter().any(|a| matches!(a, FlowAction::GraphMutated(_))));
1467 assert!(!history.can_undo() && !history.in_group());
1468 }
1469
1470 const WIRE_COMP: &str = r#"Composition {
1471 Tools = ordered() {
1472 BG1 = Background { ViewInfo = OperatorInfo { Pos = { 0, 0 } }, },
1473 BG2 = Background { ViewInfo = OperatorInfo { Pos = { 0, 80 } }, },
1474 Merge1 = Merge {
1475 Inputs = { Background = Input { SourceOp = "BG1", Source = "Output" }, },
1476 ViewInfo = OperatorInfo { Pos = { 160, 0 } },
1477 },
1478 Blur1 = Blur { ViewInfo = OperatorInfo { Pos = { 160, 120 } }, },
1479 },
1480 }"#;
1481
1482 fn wire_flow() -> (Comp, FlowView, CompHistory) {
1483 let comp = Comp::from_fusion_str(WIRE_COMP).expect("parse comp");
1484 let mut flow = FlowView::new(&ui::Theme::new(&theme::KNIFE, true));
1485 flow.size = [800.0, 600.0];
1486 flow.pan = [80.0, 60.0];
1487 flow.zoom = 1.0;
1488 (comp, flow, CompHistory::new())
1489 }
1490
1491 fn send(flow: &mut FlowView, comp: &mut Comp, history: &mut CompHistory, event: ui::Event, at: [f32; 2]) -> Vec<FlowAction> {
1492 flow.input(comp, history, event, [0.0, 0.0, 800.0, 600.0], at, ModifiersState::empty())
1493 }
1494
1495 fn drag(flow: &mut FlowView, comp: &mut Comp, history: &mut CompHistory, from: [f32; 2], to: [f32; 2]) -> Vec<FlowAction> {
1496 let button = |pressed| ui::Event::Button { button: MouseButton::Left, pressed, at: Instant::now() };
1497 send(flow, comp, history, ui::Event::PointerMoved(from), from);
1498 send(flow, comp, history, button(true), from);
1499 send(flow, comp, history, ui::Event::PointerMoved(to), to);
1500 send(flow, comp, history, button(false), to)
1501 }
1502
1503 fn output_center(flow: &FlowView, comp: &Comp, node: NodeId) -> [f32; 2] {
1504 ports::Metrics::at(flow.zoom).output_center(flow.node_rect_local(comp.node(node).pos))
1505 }
1506
1507 fn input_center(flow: &FlowView, comp: &Comp, node: NodeId, port: &str) -> [f32; 2] {
1508 flow.input_slot(comp, comp.node(node), port).unwrap().center(ports::Metrics::at(flow.zoom))
1509 }
1510
1511 fn source(comp: &Comp, node: NodeId, port: &str) -> Option<String> {
1512 comp.node(node).inputs.get(port).and_then(|b| b.source_op.clone())
1513 }
1514
1515 #[test]
1516 fn dragging_an_output_onto_an_input_triangle_wires_that_exact_port() {
1517 let (mut comp, mut flow, mut history) = wire_flow();
1518 let (bg2, merge) = (id(&comp, "BG2"), id(&comp, "Merge1"));
1519 let (from, to) = (output_center(&flow, &comp, bg2), input_center(&flow, &comp, merge, "EffectMask"));
1520
1521 let acts = drag(&mut flow, &mut comp, &mut history, from, to);
1522 assert_eq!(source(&comp, merge, "EffectMask").as_deref(), Some("BG2"));
1523 assert_eq!(source(&comp, merge, "Background").as_deref(), Some("BG1"));
1524 assert!(acts.iter().any(|a| matches!(a, FlowAction::GraphMutated(Some(n)) if *n == merge)));
1525 assert!(flow.wire_drag.is_none());
1526 assert!(history.undo(&mut comp));
1527 assert_eq!(source(&comp, merge, "EffectMask"), None);
1528 }
1529
1530 #[test]
1531 fn dropping_on_a_body_auto_picks_and_highlights_the_open_port() {
1532 let (mut comp, mut flow, mut history) = wire_flow();
1533 let (bg2, merge, blur) = (id(&comp, "BG2"), id(&comp, "Merge1"), id(&comp, "Blur1"));
1534 let from = output_center(&flow, &comp, bg2);
1535 let body = flow.world_to_local(comp.node(merge).pos);
1536
1537 let button = |pressed| ui::Event::Button { button: MouseButton::Left, pressed, at: Instant::now() };
1538 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(from), from);
1539 send(&mut flow, &mut comp, &mut history, button(true), from);
1540 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(body), body);
1541 let target = flow.wire_drag.as_ref().and_then(|wd| wd.target.as_ref()).expect("hover target");
1542 assert_eq!((target.node, target.port.as_str(), target.cycle), (merge, "Foreground", false));
1543 send(&mut flow, &mut comp, &mut history, button(false), body);
1544 assert_eq!(source(&comp, merge, "Foreground").as_deref(), Some("BG2"));
1545
1546 // Single-input tools take their main input.
1547 let (from, body) = (output_center(&flow, &comp, bg2), flow.world_to_local(comp.node(blur).pos));
1548 drag(&mut flow, &mut comp, &mut history, from, body);
1549 assert_eq!(source(&comp, blur, "Input").as_deref(), Some("BG2"));
1550 }
1551
1552 #[test]
1553 fn dropping_a_downstream_wire_upstream_is_flagged_as_a_cycle() {
1554 let (mut comp, mut flow, mut history) = wire_flow();
1555 let (bg1, merge) = (id(&comp, "BG1"), id(&comp, "Merge1"));
1556 let from = output_center(&flow, &comp, merge);
1557 let to = input_center(&flow, &comp, bg1, "EffectMask");
1558 let acts = drag(&mut flow, &mut comp, &mut history, from, to);
1559 assert!(acts.iter().any(|a| matches!(a, FlowAction::StatusNotice(_))));
1560 assert_eq!(source(&comp, bg1, "EffectMask"), None);
1561 assert!(!history.can_undo() && !history.in_group());
1562 }
1563
1564 #[test]
1565 fn dragging_a_connected_triangle_off_rewires_or_disconnects() {
1566 let (mut comp, mut flow, mut history) = wire_flow();
1567 let merge = id(&comp, "Merge1");
1568 let bg_tri = input_center(&flow, &comp, merge, "Background");
1569
1570 // Onto another triangle: the wire moves.
1571 let fg_tri = input_center(&flow, &comp, merge, "Foreground");
1572 drag(&mut flow, &mut comp, &mut history, bg_tri, fg_tri);
1573 assert_eq!(source(&comp, merge, "Background"), None);
1574 assert_eq!(source(&comp, merge, "Foreground").as_deref(), Some("BG1"));
1575 assert_eq!(history.undo_len(), 1);
1576
1577 // Dragging the moved triangle off onto empty canvas disconnects it.
1578 let fg_tri = input_center(&flow, &comp, merge, "Foreground");
1579 let acts = drag(&mut flow, &mut comp, &mut history, fg_tri, [700.0, 500.0]);
1580 assert_eq!(source(&comp, merge, "Foreground"), None);
1581 assert!(acts.iter().any(|a| matches!(a, FlowAction::StatusNotice(m) if m.starts_with("Disconnected"))));
1582 assert_eq!(history.undo_len(), 2);
1583 assert!(history.undo(&mut comp));
1584 assert_eq!(source(&comp, merge, "Foreground").as_deref(), Some("BG1"));
1585 }
1586
1587 #[test]
1588 fn dropping_a_detached_wire_back_where_it_started_leaves_no_undo_entry() {
1589 let (mut comp, mut flow, mut history) = wire_flow();
1590 let merge = id(&comp, "Merge1");
1591 let tri = input_center(&flow, &comp, merge, "Background");
1592 drag(&mut flow, &mut comp, &mut history, tri, tri);
1593 assert_eq!(source(&comp, merge, "Background").as_deref(), Some("BG1"));
1594 assert!(!history.can_undo() && !history.in_group());
1595 }
1596
1597 #[test]
1598 fn handle_hover_tracks_the_pointer_and_body_clicks_still_select() {
1599 let (mut comp, mut flow, mut history) = wire_flow();
1600 let (bg1, merge) = (id(&comp, "BG1"), id(&comp, "Merge1"));
1601 let out = output_center(&flow, &comp, bg1);
1602 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(out), out);
1603 assert_eq!(flow.hovered_handle, Some(HandleId { node: bg1, port: None }));
1604 let tri = input_center(&flow, &comp, merge, "EffectMask");
1605 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(tri), tri);
1606 assert_eq!(flow.hovered_handle, Some(HandleId { node: merge, port: Some("EffectMask".to_owned()) }));
1607 let body = flow.world_to_local(comp.node(merge).pos);
1608 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(body), body);
1609 assert_eq!(flow.hovered_handle, None);
1610
1611 press(&mut flow, &mut comp, &mut history, Instant::now(), merge);
1612 assert_eq!(flow.primary, Some(merge));
1613 assert!(flow.wire_drag.is_none());
1614 }
1615
1616 #[test]
1617 fn letter_shortcuts_ignore_ctrl_and_alt() {
1618 let (mut comp, mut flow) = group_flow();
1619 let mut history = CompHistory::new();
1620 let bg = id(&comp, "BG1");
1621 flow.selected.insert(bg);
1622 flow.primary = Some(bg);
1623
1624 for mods in [ModifiersState::CONTROL, ModifiersState::ALT] {
1625 for k in ["g", "r", "s", "p", "1"] {
1626 let acts = key(&mut flow, &mut comp, &mut history, Key::Character(k.into()), mods);
1627 assert!(flow.modal.is_none() && acts.is_empty(), "{k} with {mods:?}");
1628 }
1629 }
1630 assert!(!comp.node(bg).bypassed);
1631 key(&mut flow, &mut comp, &mut history, Key::Character("g".into()), ModifiersState::empty());
1632 assert!(flow.modal.is_some());
1633 assert!(history.in_group());
1634 }
1635
1636 #[test]
1637 fn viewer_hotkeys_1_and_2_toggle_off_when_already_active() {
1638 let (mut comp, mut flow) = group_flow();
1639 let mut history = CompHistory::new();
1640 let bg = id(&comp, "BG1");
1641 flow.selected.insert(bg);
1642 flow.primary = Some(bg);
1643
1644 let a1 = key(&mut flow, &mut comp, &mut history, Key::Character("1".into()), ModifiersState::empty());
1645 assert!(matches!(a1.as_slice(), [FlowAction::ViewNode(0, id)] if *id == bg));
1646 assert_eq!(flow.viewed_nodes[0], Some(bg));
1647
1648 let a2 = key(&mut flow, &mut comp, &mut history, Key::Character("1".into()), ModifiersState::empty());
1649 assert!(matches!(a2.as_slice(), [FlowAction::ClearViewer(0)]));
1650 assert_eq!(flow.viewed_nodes[0], None);
1651
1652 let a3 = key(&mut flow, &mut comp, &mut history, Key::Character("2".into()), ModifiersState::empty());
1653 assert!(matches!(a3.as_slice(), [FlowAction::ViewNode(1, id)] if *id == bg));
1654 assert_eq!(flow.viewed_nodes[1], Some(bg));
1655
1656 let a4 = key(&mut flow, &mut comp, &mut history, Key::Character("2".into()), ModifiersState::empty());
1657 assert!(matches!(a4.as_slice(), [FlowAction::ClearViewer(1)]));
1658 assert_eq!(flow.viewed_nodes[1], None);
1659 }
1660
1661 fn button(pressed: bool) -> ui::Event {
1662 ui::Event::Button { button: MouseButton::Left, pressed, at: Instant::now() }
1663 }
1664
1665 #[test]
1666 fn clicking_a_connected_triangle_without_dragging_changes_nothing() {
1667 let (mut comp, mut flow, mut history) = wire_flow();
1668 let merge = id(&comp, "Merge1");
1669 let tri = input_center(&flow, &comp, merge, "Background");
1670 let revision = comp.revision;
1671 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(tri), tri);
1672 send(&mut flow, &mut comp, &mut history, button(true), tri);
1673 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved([tri[0] + 2.0, tri[1]]), tri);
1674 assert!(!history.in_group());
1675 send(&mut flow, &mut comp, &mut history, button(false), [tri[0] + 2.0, tri[1]]);
1676 assert!(flow.wire_drag.is_none());
1677 assert_eq!(source(&comp, merge, "Background").as_deref(), Some("BG1"));
1678 assert_eq!(comp.revision, revision);
1679 assert!(!history.can_undo() && !history.in_group());
1680 }
1681
1682 #[test]
1683 fn rewiring_keeps_the_wires_own_output() {
1684 let mut comp = Comp::from_fusion_str(
1685 r#"Composition {
1686 Tools = ordered() {
1687 Ellipse1 = EllipseMask { ViewInfo = OperatorInfo { Pos = { 0, 0 } }, },
1688 Checker = Fuse.CheckerPieceGenerator { ViewInfo = OperatorInfo { Pos = { 0, 80 } }, },
1689 Mtl1 = MtlBlinn { ViewInfo = OperatorInfo { Pos = { 0, 160 } }, },
1690 Merge1 = Merge {
1691 Inputs = {
1692 Foreground = Input { SourceOp = "Checker", Source = "ExtraScale" },
1693 EffectMask = Input { SourceOp = "Ellipse1", Source = "Mask" },
1694 },
1695 ViewInfo = OperatorInfo { Pos = { 160, 0 } },
1696 },
1697 Blur1 = Blur { ViewInfo = OperatorInfo { Pos = { 160, 120 } }, },
1698 Blur2 = Blur { ViewInfo = OperatorInfo { Pos = { 160, 240 } }, },
1699 },
1700 }"#,
1701 )
1702 .expect("parse comp");
1703 let mut flow = FlowView::new(&ui::Theme::new(&theme::KNIFE, true));
1704 (flow.size, flow.pan, flow.zoom) = ([800.0, 600.0], [80.0, 60.0], 1.0);
1705 let mut history = CompHistory::new();
1706 let (merge, blur, blur2) = (id(&comp, "Merge1"), id(&comp, "Blur1"), id(&comp, "Blur2"));
1707 let output = |comp: &Comp, node: NodeId, port: &str| comp.node(node).inputs[port].source_output.clone();
1708
1709 let body = flow.world_to_local(comp.node(blur).pos);
1710 let from = input_center(&flow, &comp, merge, "Foreground");
1711 drag(&mut flow, &mut comp, &mut history, from, body);
1712 assert_eq!(output(&comp, blur, "Input").as_deref(), Some("ExtraScale"));
1713
1714 let from = input_center(&flow, &comp, merge, "EffectMask");
1715 let to = input_center(&flow, &comp, blur, "EffectMask");
1716 drag(&mut flow, &mut comp, &mut history, from, to);
1717 assert_eq!(output(&comp, blur, "EffectMask").as_deref(), Some("Mask"));
1718
1719 // A fresh wire picks the output its source tool has.
1720 let body = flow.world_to_local(comp.node(blur2).pos);
1721 for (name, expected) in [("Ellipse1", "Mask"), ("Mtl1", "MaterialOutput"), ("Checker", "Output")] {
1722 let from = output_center(&flow, &comp, id(&comp, name));
1723 drag(&mut flow, &mut comp, &mut history, from, body);
1724 assert_eq!(output(&comp, blur2, "Input").as_deref(), Some(expected), "{name}");
1725 }
1726 }
1727
1728 #[test]
1729 fn losing_pointer_focus_cancels_an_open_rewire_or_modal() {
1730 let (mut comp, mut flow, mut history) = wire_flow();
1731 let merge = id(&comp, "Merge1");
1732 let tri = input_center(&flow, &comp, merge, "Background");
1733 let far = [tri[0] + 40.0, tri[1] + 40.0];
1734 send(&mut flow, &mut comp, &mut history, button(true), tri);
1735 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved(far), far);
1736 assert!(history.in_group() && source(&comp, merge, "Background").is_none());
1737
1738 send(&mut flow, &mut comp, &mut history, ui::Event::PointerCancelled, far);
1739 assert!(flow.wire_drag.is_none() && !history.in_group() && !history.can_undo());
1740 assert_eq!(source(&comp, merge, "Background").as_deref(), Some("BG1"));
1741
1742 flow.selected.insert(merge);
1743 flow.primary = Some(merge);
1744 key(&mut flow, &mut comp, &mut history, Key::Character("g".into()), ModifiersState::empty());
1745 assert!(flow.modal.is_some() && history.in_group());
1746 send(&mut flow, &mut comp, &mut history, ui::Event::PointerCancelled, far);
1747 assert!(flow.modal.is_none() && !history.in_group());
1748 }
1749
1750 #[test]
1751 fn sanitizing_mid_gesture_does_not_leave_the_history_group_open() {
1752 let (mut comp, mut flow, mut history) = wire_flow();
1753 let merge = id(&comp, "Merge1");
1754 flow.selected.insert(merge);
1755 flow.primary = Some(merge);
1756 key(&mut flow, &mut comp, &mut history, Key::Character("g".into()), ModifiersState::empty());
1757 assert!(history.in_group());
1758 flow.sanitize_ids(&comp);
1759 send(&mut flow, &mut comp, &mut history, ui::Event::PointerMoved([5.0, 5.0]), [5.0, 5.0]);
1760 assert!(!history.in_group());
1761 }
1762
1763 #[test]
1764 fn port_tables_follow_fusion() {
1765 let comp = Comp::from_fusion_str(
1766 "Composition { Tools = ordered() { Else = Fuse.SwitchElse {}, Key = DeltaKeyer {}, Checker = Fuse.CheckerPieceGenerator {}, }, }",
1767 )
1768 .expect("parse comp");
1769 let mut flow = FlowView::new(&ui::Theme::new(&theme::KNIFE, true));
1770 flow.zoom = 1.0;
1771 let ports = |name: &str| {
1772 let mut found = Vec::new();
1773 flow.for_each_input(&comp, comp.node(id(&comp, name)), |s| found.push((s.port, s.color)));
1774 found
1775 };
1776 let names = |name: &str| ports(name).into_iter().map(|(p, _)| p).collect::<Vec<_>>();
1777 assert_eq!(names("Else"), ["Input1", "Input2", "EffectMask"]);
1778 assert_eq!(names("Key"), ["Input", "EffectMask", "Garbage.Matte", "Solid.Matte"]);
1779 assert_eq!(names("Checker"), ["EffectMask"]);
1780 assert!(ports("Key").iter().filter(|(p, _)| p.ends_with(".Matte")).all(|(_, c)| *c == ports::GRAY));
1781 }
1782
1783 #[test]
1784 fn stale_ids_mid_modal_wire_drag_and_group_scope_do_not_panic_on_comp_replace() {
1785 let (mut comp, mut flow, mut history) = wire_flow();
1786 let merge = id(&comp, "Merge1");
1787 flow.selected.insert(merge);
1788 flow.primary = Some(merge);
1789 flow.viewed_nodes = [Some(merge), Some(id(&comp, "BG1"))];
1790
1791 // Start modal grab, then replace comp with an empty comp without calling sanitize_ids first.
1792 key(&mut flow, &mut comp, &mut history, Key::Character("g".into()), ModifiersState::empty());
1793 assert!(flow.modal.is_some());
1794 let mut empty = Comp::from_fusion_str("Composition {}").expect("empty comp");
1795 flow.fit_all(&empty);
1796 flow.prepare_labels(&empty);
1797 let _ = flow.paint(&empty);
1798 send(&mut flow, &mut empty, &mut history, ui::Event::PointerMoved([20.0, 20.0]), [20.0, 20.0]);
1799 key(&mut flow, &mut empty, &mut history, Key::Named(NamedKey::Enter), ModifiersState::empty());
1800
1801 // Start detached wire drag, then replace comp mid-drag before release.
1802 let (mut comp2, mut flow2, mut history2) = wire_flow();
1803 let m2 = id(&comp2, "Merge1");
1804 let tri = input_center(&flow2, &comp2, m2, "Background");
1805 send(&mut flow2, &mut comp2, &mut history2, button(true), tri);
1806 send(&mut flow2, &mut comp2, &mut history2, ui::Event::PointerMoved([tri[0] + 40.0, tri[1]]), [tri[0] + 40.0, tri[1]]);
1807 assert!(flow2.wire_drag.is_some());
1808 send(&mut flow2, &mut empty, &mut history2, button(false), [300.0, 300.0]);
1809 let _ = flow2.paint(&empty);
1810
1811 // Enter a GroupOperator, then replace comp with one that has no group at that index.
1812 let grouped = Comp::from_fusion_str(
1813 r#"Composition { Tools = ordered() {
1814 G = GroupOperator { Tools = ordered() { Inner = Blur {} } },
1815 } }"#,
1816 )
1817 .expect("grouped comp");
1818 let mut flow3 = FlowView::new(&ui::Theme::new(&theme::KNIFE, true));
1819 assert!(flow3.enter_group(&grouped, grouped.find_node("G").unwrap()));
1820 assert!(!flow3.scope_path().is_empty());
1821 flow3.prepare_labels(&empty);
1822 let _ = flow3.paint(&empty);
1823 assert!(flow3.scope_path().is_empty());
1824 }
1825
1826 #[test]
1827 fn degenerate_zoom_pan_and_zero_viewport_do_not_hang_or_panic() {
1828 let mut comp = test_comp();
1829 let bg = id(&comp, "BG1");
1830 comp.set_node_pos(bg, [f32::NAN, 10.0]);
1831 let mut history = CompHistory::new();
1832 let mut flow = FlowView::new(&ui::Theme::new(&theme::KNIFE, true));
1833
1834 flow.resize([0.0, 0.0]);
1835 flow.zoom = 0.0;
1836 flow.pan = [f32::NAN, f32::INFINITY];
1837 let _ = flow.paint(&comp);
1838
1839 flow.zoom = 1e-12;
1840 flow.pan = [1e12, -1e12];
1841 let _ = flow.paint(&comp);
1842
1843 flow.zoom = f32::NAN;
1844 flow.fit_all(&comp);
1845 flow.prepare_labels(&comp);
1846 let _ = flow.paint(&comp);
1847 send(&mut flow, &mut comp, &mut history, ui::Event::Wheel([0.0, 12.0]), [10.0, 10.0]);
1848 assert!(flow.zoom.is_finite() && flow.zoom > 0.0);
1849 assert!(flow.pan.iter().all(|v| v.is_finite()));
1850 }
1851
1852}