authoravatarclover caruso<git@paperclover.net>2026-11-30 16:12:04-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 16:42:08-08:00
log832721ad5a4e4737907b6522427adc6aaf542d6c
treedd23e0611df9cd749c1b714bde90fb92e49eb967
parentc95015b08daff562f3711310b3b5a673d72c2fd9
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Add Fusion clipboard copy/paste and Macro/Group subgraph navigation (#26)

Model: Comp::export_fusion_clipboard serializes selected tools plus the modifiers they reference as a Fusion { Tools = ordered() {...} } snippet; CompHistory::paste_fusion_clipboard parses it, dedups tool and modifier names (Blur1 -> Blur1_1), remaps SourceOp and Expression references among pasted tools, drops references to missing tools, offsets ViewInfo.Pos, and records the whole paste as one undo step. Flow/App: Cmd+C / Cmd+V on the focused Flow canvas use the Knife system clipboard. Double-clicking a Macro/Group enters its read-only subgraph; the toolbar breadcrumb (Root > Group) or Esc leaves it. Assisted-by: claude-sonnet-5.5

4 files changed, 1026 insertions(+), 33 deletions(-)

crates/app/src/main.rs+80
...@@ -653,6 +653,34 @@ impl Studio {...@@ -653,6 +653,34 @@ impl Studio {
653 self.set_notice(format!("Added {}", self.comp.node(new_id).name));653 self.set_notice(format!("Added {}", self.comp.node(new_id).name));
654 }654 }
655655
656 fn copy_nodes(&mut self, ids: &[NodeId]) {
657 self.ui.clipboard.set_text(self.comp.export_fusion_clipboard(ids));
658 let n = ids.len();
659 self.set_notice(format!("Copied {n} node{}", if n == 1 { "" } else { "s" }));
660 }
661
662 fn paste_nodes(&mut self) {
663 if !self.flow.scope_path().is_empty() {
664 self.set_notice("Group contents are read-only; press Esc to leave the group before pasting");
665 return;
666 }
667 let Some(text) = self.ui.clipboard.text() else {
668 self.set_notice("Clipboard is empty");
669 return;
670 };
671 match self.history.paste_fusion_clipboard(&mut self.comp, &text, (60.0, 40.0)) {
672 Ok(ids) => {
673 self.flow.selected = ids.iter().copied().collect();
674 self.flow.primary = ids.first().copied();
675 self.spline.set_target_node(&self.comp, self.flow.primary);
676 self.invalidate_node(None);
677 let n = ids.len();
678 self.set_notice(format!("Pasted {n} node{}", if n == 1 { "" } else { "s" }));
679 }
680 Err(e) => self.set_notice(format!("Nothing pasted: {e}")),
681 }
682 }
683
656 fn begin_inline_rename(&mut self, id: NodeId) {684 fn begin_inline_rename(&mut self, id: NodeId) {
657 if id.0 >= self.comp.nodes.len() {685 if id.0 >= self.comp.nodes.len() {
658 return;686 return;
...@@ -939,6 +967,7 @@ impl Studio {...@@ -939,6 +967,7 @@ impl Studio {
939 let mut req_open = false;967 let mut req_open = false;
940 let mut req_save = false;968 let mut req_save = false;
941 let mut req_save_as = false;969 let mut req_save_as = false;
970 let mut req_exit_to_depth: Option<usize> = None;
942 let mut commit_rename: Option<(NodeId, String)> = None;971 let mut commit_rename: Option<(NodeId, String)> = None;
943 let mut cancel_rename = false;972 let mut cancel_rename = false;
944973
...@@ -1022,6 +1051,47 @@ impl Studio {...@@ -1022,6 +1051,47 @@ impl Studio {
1022 if studio_btn(ui, "flow-saveas-btn", "Save As", false).clicked {1051 if studio_btn(ui, "flow-saveas-btn", "Save As", false).clicked {
1023 req_save_as = true;1052 req_save_as = true;
1024 }1053 }
1054 let scope_path = flow.scope_path();
1055 if !scope_path.is_empty() {
1056 let crumb_sep = |ui: &mut ui::Ui, part: usize| {
1057 let ink = ui.theme.text_dim;
1058 ui.leaf(
1059 ("flow-crumb-sep", part),
1060 ui::Spec {
1061 size: [ui::fit(), ui::px(22.0)],
1062 text: Some(">"),
1063 font_size: Some(11.0),
1064 color: Some(ink),
1065 pad: [2.0, 0.0],
1066 center: true,
1067 ..ui::Spec::default()
1068 },
1069 );
1070 };
1071 if studio_btn(ui, "flow-crumb-root", "Root", false).clicked {
1072 req_exit_to_depth = Some(0);
1073 }
1074 for (depth, &group) in scope_path.iter().enumerate() {
1075 crumb_sep(ui, depth);
1076 let current = depth + 1 == scope_path.len();
1077 let crumb = studio_btn(ui, ("flow-crumb", depth), &comp.node(group).name, current);
1078 if crumb.clicked && !current {
1079 req_exit_to_depth = Some(depth + 1);
1080 }
1081 }
1082 crumb_sep(ui, scope_path.len());
1083 ui.leaf(
1084 "flow-crumb-hint",
1085 ui::Spec {
1086 size: [ui::fit(), ui::px(22.0)],
1087 text: Some("Esc: back"),
1088 font_size: Some(10.5),
1089 color: Some(ui.theme.text_dim),
1090 center: true,
1091 ..ui::Spec::default()
1092 },
1093 );
1094 }
1025 if let Some(rn_id) = *renaming_node {1095 if let Some(rn_id) = *renaming_node {
1026 let rn_field_id = flow_pane_id().child(("rename-field", rn_id.0));1096 let rn_field_id = flow_pane_id().child(("rename-field", rn_id.0));
1027 let rn_sig = ui::text_field(1097 let rn_sig = ui::text_field(
...@@ -1119,6 +1189,11 @@ impl Studio {...@@ -1119,6 +1189,11 @@ impl Studio {
1119 if req_open_add_tool {1189 if req_open_add_tool {
1120 self.add_tool.open();1190 self.add_tool.open();
1121 }1191 }
1192 if let Some(depth) = req_exit_to_depth
1193 && self.flow.exit_to_depth(&self.comp, depth)
1194 {
1195 self.spline.set_target_node(&self.comp, self.flow.primary);
1196 }
1122 if req_undo {1197 if req_undo {
1123 self.undo();1198 self.undo();
1124 }1199 }
...@@ -1250,6 +1325,11 @@ impl Studio {...@@ -1250,6 +1325,11 @@ impl Studio {
1250 FlowAction::StatusNotice(msg) => {1325 FlowAction::StatusNotice(msg) => {
1251 self.set_notice(msg);1326 self.set_notice(msg);
1252 }1327 }
1328 FlowAction::CopyNodes(ids) => self.copy_nodes(&ids),
1329 FlowAction::PasteNodes => self.paste_nodes(),
1330 FlowAction::ScopeChanged => {
1331 self.spline.set_target_node(&self.comp, self.flow.primary);
1332 }
1253 }1333 }
1254 }1334 }
1255 }1335 }
crates/flow/src/lib.rs+356-32
...@@ -4,17 +4,27 @@...@@ -4,17 +4,27 @@
4//! - Crisp straight lines by default (clean in any build orientation: L->R, T->B, B->T, diagonal)4//! - Crisp straight lines by default (clean in any build orientation: L->R, T->B, B->T, diagonal)
5//! - Day-1 Blender `G`/`R`/`S` modal transforms + `X`/`Y` axis locks5//! - Day-1 Blender `G`/`R`/`S` modal transforms + `X`/`Y` axis locks
6//! - `1`/`2` multi-viewer routing, `Cmd+F` / Numpad `.` fit-to-view, `P` bypass, drag-onto-wire insert.6//! - `1`/`2` multi-viewer routing, `Cmd+F` / Numpad `.` fit-to-view, `P` bypass, drag-onto-wire insert.
7//! - `Cmd+C` / `Cmd+V` node clipboard requests, double-click into Macro/Group subgraphs, `Esc` back out.
8
9mod scope;
710
8use draw::{Glyphs, PathStyle, Primitive};11use draw::{Glyphs, PathStyle, Primitive};
9use model::{Comp, CompHistory, NodeId, PortRole, default_main_input_port, is_supported_tool};12use model::{Comp, CompHistory, NodeId, PortRole, default_main_input_port, is_supported_tool};
13use scope::Scope;
14pub use scope::group_children;
10use std::collections::{HashMap, HashSet};15use std::collections::{HashMap, HashSet};
11use std::sync::Arc;16use std::sync::Arc;
17use std::time::{Duration, Instant};
12use winit::event::{ElementState, MouseButton};18use winit::event::{ElementState, MouseButton};
13use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey};19use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey};
1420
15// Exact 1:1 match to Fusion's 110×33 flow grid cells (leaving crisp 26px X / 12px Y gaps for □──▶ wires).21// Exact 1:1 match to Fusion's 110×33 flow grid cells (leaving crisp 26px X / 12px Y gaps for □──▶ wires).
16const NODE_W: f32 = 84.0;22const NODE_W: f32 = 84.0;
17const NODE_H: f32 = 21.0;23const NODE_H: f32 = 21.0;
24const DOUBLE_CLICK: Duration = Duration::from_millis(400);
25
26const 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 Ctrl+P: Bypass 1/2: Viewer Dbl-click group: Enter";
27const HUD_GROUP: &str = "Group contents are read-only Dbl-click nested group: Enter Cmd+C: Copy 1/2: Viewer F: Fit Esc: Back";
1828
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]29#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub enum TransformMode {30pub enum TransformMode {
...@@ -98,6 +108,12 @@ pub enum FlowAction {...@@ -98,6 +108,12 @@ pub enum FlowAction {
98 RequestRename(NodeId),108 RequestRename(NodeId),
99 /// Transient feedback message (e.g., cycle rejected).109 /// Transient feedback message (e.g., cycle rejected).
100 StatusNotice(String),110 StatusNotice(String),
111 /// `Cmd+C`: serialize these nodes to the system clipboard.
112 CopyNodes(Vec<NodeId>),
113 /// `Cmd+V`: paste the system clipboard at the root graph.
114 PasteNodes,
115 /// A Macro/Group was entered or left; selection was reset to the new level.
116 ScopeChanged,
101}117}
102118
103#[derive(Clone, Debug)]119#[derive(Clone, Debug)]
...@@ -159,6 +175,8 @@ pub struct FlowView {...@@ -159,6 +175,8 @@ pub struct FlowView {
159 panning: Option<([f32; 2], [f32; 2])>,175 panning: Option<([f32; 2], [f32; 2])>,
160 lmb_drag_node: Option<(NodeId, [f32; 2], bool)>,176 lmb_drag_node: Option<(NodeId, [f32; 2], bool)>,
161 pointer_local: [f32; 2],177 pointer_local: [f32; 2],
178 scope: Scope,
179 last_click: Option<(Instant, NodeId)>,
162 label_cache: HashMap<String, text::Layout>,180 label_cache: HashMap<String, text::Layout>,
163 badge_cache: HashMap<String, text::Layout>,181 badge_cache: HashMap<String, text::Layout>,
164 fitted_once: bool,182 fitted_once: bool,
...@@ -182,6 +200,8 @@ impl FlowView {...@@ -182,6 +200,8 @@ impl FlowView {
182 panning: None,200 panning: None,
183 lmb_drag_node: None,201 lmb_drag_node: None,
184 pointer_local: [0.0, 0.0],202 pointer_local: [0.0, 0.0],
203 scope: Scope::default(),
204 last_click: None,
185 label_cache: HashMap::new(),205 label_cache: HashMap::new(),
186 badge_cache: HashMap::new(),206 badge_cache: HashMap::new(),
187 fitted_once: false,207 fitted_once: false,
...@@ -207,16 +227,63 @@ impl FlowView {...@@ -207,16 +227,63 @@ impl FlowView {
207 self.box_select = None;227 self.box_select = None;
208 self.panning = None;228 self.panning = None;
209 self.lmb_drag_node = None;229 self.lmb_drag_node = None;
230 self.last_click = None;
231 self.scope = Scope::default();
210 self.label_cache.clear();232 self.label_cache.clear();
211 self.fitted_once = false;233 self.fitted_once = false;
212 self.fit_comp(comp);234 self.fit_comp(comp);
213 }235 }
214236
237 /// Groups entered from the root, outermost first; empty at the root graph.
238 pub fn scope_path(&self) -> &[NodeId] {
239 self.scope.path()
240 }
241
242 /// Shows the inside of Macro/Group `id`, which must be visible at the current level.
243 pub fn enter_group(&mut self, comp: &Comp, id: NodeId) -> bool {
244 if !self.scope.enter(comp, id) {
245 return false;
246 }
247 self.scope_switched(comp, None);
248 true
249 }
250
251 /// Keeps the outermost `depth` groups (`0` = root) and selects the group just left.
252 pub fn exit_to_depth(&mut self, comp: &Comp, depth: usize) -> bool {
253 let Some(left) = self.scope.truncate(comp, depth) else {
254 return false;
255 };
256 self.scope_switched(comp, Some(left));
257 true
258 }
259
260 /// Leaves the innermost group.
261 pub fn exit_group(&mut self, comp: &Comp) -> bool {
262 self.scope.path().len().checked_sub(1).is_some_and(|d| self.exit_to_depth(comp, d))
263 }
264
265 fn scope_switched(&mut self, comp: &Comp, select: Option<NodeId>) {
266 self.selected.clear();
267 self.selected.extend(select);
268 self.primary = select;
269 self.hovered_node = None;
270 self.hovered_wire = None;
271 self.modal = None;
272 self.wire_drag = None;
273 self.box_select = None;
274 self.lmb_drag_node = None;
275 self.last_click = None;
276 self.fit_comp(comp);
277 }
278
215 /// Removes any stale `NodeId`s from selection/viewed_nodes after undo/redo or deletion.279 /// Removes any stale `NodeId`s from selection/viewed_nodes after undo/redo or deletion.
216 pub fn sanitize_ids(&mut self, comp: &Comp) {280 pub fn sanitize_ids(&mut self, comp: &Comp) {
217 let len = comp.nodes.len();281 let len = comp.nodes.len();
218 self.selected.retain(|id| id.0 < len && !comp.nodes[id.0].internal);282 if self.scope.refresh(comp) {
219 if self.primary.is_some_and(|id| id.0 >= len || comp.nodes[id.0].internal) {283 self.fitted_once = false;
284 }
285 self.selected.retain(|id| id.0 < len && self.scope.shows(comp.node(*id)));
286 if self.primary.is_some_and(|id| id.0 >= len || !self.scope.shows(comp.node(id))) {
220 self.primary = self.selected.iter().copied().next();287 self.primary = self.selected.iter().copied().next();
221 }288 }
222 for slot in &mut self.viewed_nodes {289 for slot in &mut self.viewed_nodes {
...@@ -231,6 +298,7 @@ impl FlowView {...@@ -231,6 +298,7 @@ impl FlowView {
231 self.modal = None;298 self.modal = None;
232 self.wire_drag = None;299 self.wire_drag = None;
233 self.lmb_drag_node = None;300 self.lmb_drag_node = None;
301 self.last_click = None;
234 }302 }
235303
236 /// Computes a clean world-space spawn position for a newly added node.304 /// Computes a clean world-space spawn position for a newly added node.
...@@ -251,13 +319,13 @@ impl FlowView {...@@ -251,13 +319,13 @@ impl FlowView {
251 let ids: Vec<NodeId> = if !self.selected.is_empty() {319 let ids: Vec<NodeId> = if !self.selected.is_empty() {
252 self.selected.iter().copied().collect()320 self.selected.iter().copied().collect()
253 } else {321 } else {
254 comp.nodes.iter().filter(|n| !n.internal).map(|n| n.id).collect()322 self.scope.visible(comp)
255 };323 };
256 self.fit_ids(comp, ids);324 self.fit_ids(comp, ids);
257 }325 }
258326
259 pub fn fit_comp(&mut self, comp: &Comp) {327 pub fn fit_comp(&mut self, comp: &Comp) {
260 let ids: Vec<NodeId> = comp.nodes.iter().filter(|n| !n.internal).map(|n| n.id).collect();328 let ids = self.scope.visible(comp);
261 self.fit_ids(comp, ids);329 self.fit_ids(comp, ids);
262 }330 }
263331
...@@ -339,7 +407,7 @@ impl FlowView {...@@ -339,7 +407,7 @@ impl FlowView {
339 let mut sx = 0.0_f32;407 let mut sx = 0.0_f32;
340 let mut sy = 0.0_f32;408 let mut sy = 0.0_f32;
341 let mut count = 0;409 let mut count = 0;
342 for other in &comp.nodes {410 for other in comp.nodes.iter().filter(|n| self.scope.shows(n)) {
343 for binding in other.inputs.values() {411 for binding in other.inputs.values() {
344 if binding.source_op.as_deref() == Some(name.as_str()) {412 if binding.source_op.as_deref() == Some(name.as_str()) {
345 let dx = other.pos[0] - sp[0];413 let dx = other.pos[0] - sp[0];
...@@ -360,7 +428,7 @@ impl FlowView {...@@ -360,7 +428,7 @@ impl FlowView {
360428
361 fn hit_node(&self, comp: &Comp, local: [f32; 2]) -> Option<NodeId> {429 fn hit_node(&self, comp: &Comp, local: [f32; 2]) -> Option<NodeId> {
362 for n in comp.nodes.iter().rev() {430 for n in comp.nodes.iter().rev() {
363 if n.internal { continue; }431 if !self.scope.shows(n) { continue; }
364 let r = self.node_rect_local(n.pos);432 let r = self.node_rect_local(n.pos);
365 if local[0] >= r[0] && local[0] <= r[2] && local[1] >= r[1] && local[1] <= r[3] {433 if local[0] >= r[0] && local[0] <= r[2] && local[1] >= r[1] && local[1] <= r[3] {
366 return Some(n.id);434 return Some(n.id);
...@@ -371,7 +439,7 @@ impl FlowView {...@@ -371,7 +439,7 @@ impl FlowView {
371439
372 fn hit_output_port(&self, comp: &Comp, local: [f32; 2]) -> Option<NodeId> {440 fn hit_output_port(&self, comp: &Comp, local: [f32; 2]) -> Option<NodeId> {
373 for n in comp.nodes.iter().rev() {441 for n in comp.nodes.iter().rev() {
374 if n.internal { continue; }442 if !self.scope.shows(n) { continue; }
375 let r = self.node_rect_local(n.pos);443 let r = self.node_rect_local(n.pos);
376 let edge = self.node_output_edge(comp, n.id);444 let edge = self.node_output_edge(comp, n.id);
377 let nrm = edge.normal();445 let nrm = edge.normal();
...@@ -388,7 +456,7 @@ impl FlowView {...@@ -388,7 +456,7 @@ impl FlowView {
388456
389 fn hit_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, &'static str)> {457 fn hit_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, &'static str)> {
390 for n in comp.nodes.iter().rev() {458 for n in comp.nodes.iter().rev() {
391 if n.internal { continue; }459 if !self.scope.shows(n) { continue; }
392 let r = self.node_rect_local(n.pos);460 let r = self.node_rect_local(n.pos);
393 if local[0] >= r[0] - 10.0 && local[0] <= r[2] + 10.0 && local[1] >= r[1] - 10.0 && local[1] <= r[3] + 10.0 {461 if local[0] >= r[0] - 10.0 && local[0] <= r[2] + 10.0 && local[1] >= r[1] - 10.0 && local[1] <= r[3] + 10.0 {
394 // Pick Background/Foreground/Mask cleanly based on approach edge for Merge/Displace!462 // Pick Background/Foreground/Mask cleanly based on approach edge for Merge/Displace!
...@@ -417,10 +485,10 @@ impl FlowView {...@@ -417,10 +485,10 @@ impl FlowView {
417 fn hit_connected_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, String, NodeId)> {485 fn hit_connected_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, String, NodeId)> {
418 let hit_r2 = 10.5_f32 * 10.5_f32;486 let hit_r2 = 10.5_f32 * 10.5_f32;
419 for dst in comp.nodes.iter().rev() {487 for dst in comp.nodes.iter().rev() {
420 if dst.internal { continue; }488 if !self.scope.shows(dst) { continue; }
421 for (port, binding) in &dst.inputs {489 for (port, binding) in &dst.inputs {
422 let Some(src_name) = &binding.source_op else { continue };490 let Some(src_name) = &binding.source_op else { continue };
423 let Some(src_id) = comp.find_node(src_name) else { continue };491 let Some(src_id) = self.scope.resolve(comp, src_name) else { continue };
424 let role = PortRole::from_input_name(port);492 let role = PortRole::from_input_name(port);
425 let (_a, _ae, b, be) = self.wire_endpoints(comp, src_id, dst.id, role);493 let (_a, _ae, b, be) = self.wire_endpoints(comp, src_id, dst.id, role);
426 let bn = be.normal();494 let bn = be.normal();
...@@ -437,13 +505,13 @@ impl FlowView {...@@ -437,13 +505,13 @@ impl FlowView {
437505
438 fn hit_wire(&self, comp: &Comp, local: [f32; 2], ignore_node: Option<NodeId>) -> Option<WireRef> {506 fn hit_wire(&self, comp: &Comp, local: [f32; 2], ignore_node: Option<NodeId>) -> Option<WireRef> {
439 let mut best: Option<(f32, WireRef)> = None;507 let mut best: Option<(f32, WireRef)> = None;
440 for dst in &comp.nodes {508 for dst in comp.nodes.iter().filter(|n| self.scope.shows(n)) {
441 if Some(dst.id) == ignore_node {509 if Some(dst.id) == ignore_node {
442 continue;510 continue;
443 }511 }
444 for (port, binding) in &dst.inputs {512 for (port, binding) in &dst.inputs {
445 let Some(src_name) = &binding.source_op else { continue };513 let Some(src_name) = &binding.source_op else { continue };
446 let Some(src_id) = comp.find_node(src_name) else { continue };514 let Some(src_id) = self.scope.resolve(comp, src_name) else { continue };
447 if Some(src_id) == ignore_node {515 if Some(src_id) == ignore_node {
448 continue;516 continue;
449 }517 }
...@@ -618,10 +686,15 @@ impl FlowView {...@@ -618,10 +686,15 @@ impl FlowView {
618 let cmd = kmod.super_key() || kmod.control_key();686 let cmd = kmod.super_key() || kmod.control_key();
619 match key {687 match key {
620 Key::Named(NamedKey::Escape) => {688 Key::Named(NamedKey::Escape) => {
621 if self.modal.is_some() {689 if self.modal.is_some() || self.wire_drag.is_some() {
622 self.cancel_modal(comp, history);690 if self.modal.is_some() {
691 self.cancel_modal(comp, history);
692 }
693 self.wire_drag = None;
694 } else if self.exit_group(comp) {
695 actions.push(FlowAction::SelectionChanged(self.primary));
696 actions.push(FlowAction::ScopeChanged);
623 }697 }
624 self.wire_drag = None;
625 }698 }
626 Key::Named(NamedKey::Enter) => {699 Key::Named(NamedKey::Enter) => {
627 if self.modal.is_some() {700 if self.modal.is_some() {
...@@ -629,7 +702,9 @@ impl FlowView {...@@ -629,7 +702,9 @@ impl FlowView {
629 }702 }
630 }703 }
631 Key::Named(NamedKey::Delete) | Key::Named(NamedKey::Backspace) => {704 Key::Named(NamedKey::Delete) | Key::Named(NamedKey::Backspace) => {
632 if !self.selected.is_empty() {705 if !self.scope.is_root() {
706 read_only_notice(actions);
707 } else if !self.selected.is_empty() {
633 let ids: Vec<NodeId> = self.selected.iter().copied().collect();708 let ids: Vec<NodeId> = self.selected.iter().copied().collect();
634 history.push_snapshot(comp, "Delete Nodes");709 history.push_snapshot(comp, "Delete Nodes");
635 let deleted = comp.delete_nodes(&ids);710 let deleted = comp.delete_nodes(&ids);
...@@ -648,7 +723,9 @@ impl FlowView {...@@ -648,7 +723,9 @@ impl FlowView {
648 }723 }
649 }724 }
650 Key::Named(NamedKey::F2) => {725 Key::Named(NamedKey::F2) => {
651 if let Some(id) = self.primary {726 if !self.scope.is_root() {
727 read_only_notice(actions);
728 } else if let Some(id) = self.primary {
652 actions.push(FlowAction::RequestRename(id));729 actions.push(FlowAction::RequestRename(id));
653 }730 }
654 }731 }
...@@ -657,6 +734,15 @@ impl FlowView {...@@ -657,6 +734,15 @@ impl FlowView {
657 self.viewed_nodes = [None, None];734 self.viewed_nodes = [None, None];
658 actions.push(FlowAction::ClearViewers);735 actions.push(FlowAction::ClearViewers);
659 }736 }
737 "c" if cmd && !kmod.shift_key() => {
738 if !self.selected.is_empty() {
739 let mut ids: Vec<NodeId> = self.selected.iter().copied().collect();
740 ids.sort_unstable_by_key(|id| id.0);
741 actions.push(FlowAction::CopyNodes(ids));
742 }
743 }
744 "v" if cmd && !kmod.shift_key() => actions.push(FlowAction::PasteNodes),
745 "d" if cmd && !kmod.shift_key() && !self.scope.is_root() => read_only_notice(actions),
660 "d" if cmd && !kmod.shift_key() => {746 "d" if cmd && !kmod.shift_key() => {
661 if !self.selected.is_empty() {747 if !self.selected.is_empty() {
662 let ids: Vec<NodeId> = self.selected.iter().copied().collect();748 let ids: Vec<NodeId> = self.selected.iter().copied().collect();
...@@ -681,12 +767,15 @@ impl FlowView {...@@ -681,12 +767,15 @@ impl FlowView {
681 "f" if kmod.super_key() => self.fit_all(comp),767 "f" if kmod.super_key() => self.fit_all(comp),
682 "f" if !kmod.super_key() => self.fit_all(comp),768 "f" if !kmod.super_key() => self.fit_all(comp),
683 "." if !kmod.super_key() => self.fit_all(comp),769 "." if !kmod.super_key() => self.fit_all(comp),
770 "g" if !cmd && self.modal.is_none() && !self.scope.is_root() => read_only_notice(actions),
684 "g" if !cmd && self.modal.is_none() => {771 "g" if !cmd && self.modal.is_none() => {
685 self.begin_modal(comp, history, TransformMode::Grab);772 self.begin_modal(comp, history, TransformMode::Grab);
686 }773 }
774 "r" if !cmd && self.modal.is_none() && !self.scope.is_root() => read_only_notice(actions),
687 "r" if !cmd && self.modal.is_none() => {775 "r" if !cmd && self.modal.is_none() => {
688 self.begin_modal(comp, history, TransformMode::Rotate);776 self.begin_modal(comp, history, TransformMode::Rotate);
689 }777 }
778 "s" if !cmd && self.modal.is_none() && !self.scope.is_root() => read_only_notice(actions),
690 "s" if !cmd && self.modal.is_none() => {779 "s" if !cmd && self.modal.is_none() => {
691 self.begin_modal(comp, history, TransformMode::Scale);780 self.begin_modal(comp, history, TransformMode::Scale);
692 }781 }
...@@ -703,7 +792,7 @@ impl FlowView {...@@ -703,7 +792,7 @@ impl FlowView {
703 self.apply_modal(comp, kmod.shift_key());792 self.apply_modal(comp, kmod.shift_key());
704 }793 }
705 "a" if !kmod.super_key() => {794 "a" if !kmod.super_key() => {
706 let visible: Vec<NodeId> = comp.nodes.iter().filter(|n| !n.internal).map(|n| n.id).collect();795 let visible = self.scope.visible(comp);
707 if self.selected.len() == visible.len() {796 if self.selected.len() == visible.len() {
708 self.selected.clear();797 self.selected.clear();
709 self.primary = None;798 self.primary = None;
...@@ -725,6 +814,7 @@ impl FlowView {...@@ -725,6 +814,7 @@ impl FlowView {
725 actions.push(FlowAction::ViewNode(1, id));814 actions.push(FlowAction::ViewNode(1, id));
726 }815 }
727 }816 }
817 "p" if !kmod.super_key() && !self.scope.is_root() => read_only_notice(actions),
728 "p" if !kmod.super_key() => {818 "p" if !kmod.super_key() => {
729 if !self.selected.is_empty() {819 if !self.selected.is_empty() {
730 let ids: Vec<NodeId> = self.selected.iter().copied().collect();820 let ids: Vec<NodeId> = self.selected.iter().copied().collect();
...@@ -797,7 +887,7 @@ impl FlowView {...@@ -797,7 +887,7 @@ impl FlowView {
797 };887 };
798 }888 }
799 }889 }
800 ui::Event::Button { button, pressed, .. } => {890 ui::Event::Button { button, pressed, at } => {
801 if button == MouseButton::Middle || (button == MouseButton::Left && modifiers.alt_key()) {891 if button == MouseButton::Middle || (button == MouseButton::Left && modifiers.alt_key()) {
802 if pressed {892 if pressed {
803 self.panning = Some((self.pointer_local, self.pan));893 self.panning = Some((self.pointer_local, self.pan));
...@@ -811,7 +901,9 @@ impl FlowView {...@@ -811,7 +901,9 @@ impl FlowView {
811 self.wire_drag = None;901 self.wire_drag = None;
812 } else if pressed {902 } else if pressed {
813 // Right-click a hovered wire or connected input port to disconnect it!903 // Right-click a hovered wire or connected input port to disconnect it!
814 if let Some(w) = self.hit_wire(comp, self.pointer_local, None) {904 if !self.scope.is_root() {
905 read_only_notice(&mut actions);
906 } else if let Some(w) = self.hit_wire(comp, self.pointer_local, None) {
815 history.push_snapshot(comp, "Disconnect");907 history.push_snapshot(comp, "Disconnect");
816 if comp.disconnect(w.dst, &w.port) {908 if comp.disconnect(w.dst, &w.port) {
817 self.hovered_wire = None;909 self.hovered_wire = None;
...@@ -828,14 +920,14 @@ impl FlowView {...@@ -828,14 +920,14 @@ impl FlowView {
828 if pressed {920 if pressed {
829 if self.modal.is_some() {921 if self.modal.is_some() {
830 self.confirm_modal(comp, history, &mut actions);922 self.confirm_modal(comp, history, &mut actions);
831 } else if let Some(src) = self.hit_output_port(comp, self.pointer_local) {923 } else if let Some(src) = self.hit_output_port(comp, self.pointer_local).filter(|_| self.scope.is_root()) {
832 self.wire_drag = Some(WireDrag {924 self.wire_drag = Some(WireDrag {
833 src,925 src,
834 cursor_local: self.pointer_local,926 cursor_local: self.pointer_local,
835 target: None,927 target: None,
836 detached_from: None,928 detached_from: None,
837 });929 });
838 } else if let Some((dst, port, src)) = self.hit_connected_input_port(comp, self.pointer_local) {930 } else if let Some((dst, port, src)) = self.hit_connected_input_port(comp, self.pointer_local).filter(|_| self.scope.is_root()) {
839 // Dragging an existing input port detaches it so user can drop to disconnect or rewire!931 // Dragging an existing input port detaches it so user can drop to disconnect or rewire!
840 history.push_snapshot(comp, "Disconnect");932 history.push_snapshot(comp, "Disconnect");
841 comp.disconnect(dst, &port);933 comp.disconnect(dst, &port);
...@@ -847,6 +939,13 @@ impl FlowView {...@@ -847,6 +939,13 @@ impl FlowView {
847 detached_from: Some((dst, port)),939 detached_from: Some((dst, port)),
848 });940 });
849 } else if let Some(nid) = self.hit_node(comp, self.pointer_local) {941 } else if let Some(nid) = self.hit_node(comp, self.pointer_local) {
942 let double = self.last_click.is_some_and(|(t, prev)| prev == nid && at.duration_since(t) <= DOUBLE_CLICK);
943 self.last_click = Some((at, nid));
944 if double && !modifiers.shift_key() && self.enter_group(comp, nid) {
945 actions.push(FlowAction::SelectionChanged(None));
946 actions.push(FlowAction::ScopeChanged);
947 return actions;
948 }
850 if modifiers.shift_key() {949 if modifiers.shift_key() {
851 if !self.selected.remove(&nid) {950 if !self.selected.remove(&nid) {
852 self.selected.insert(nid);951 self.selected.insert(nid);
...@@ -862,7 +961,9 @@ impl FlowView {...@@ -862,7 +961,9 @@ impl FlowView {
862 self.primary = Some(nid);961 self.primary = Some(nid);
863 }962 }
864 actions.push(FlowAction::SelectionChanged(self.primary));963 actions.push(FlowAction::SelectionChanged(self.primary));
865 self.lmb_drag_node = Some((nid, self.pointer_local, false));964 if self.scope.is_root() {
965 self.lmb_drag_node = Some((nid, self.pointer_local, false));
966 }
866 } else {967 } else {
867 if !modifiers.shift_key() {968 if !modifiers.shift_key() {
868 self.selected.clear();969 self.selected.clear();
...@@ -913,8 +1014,7 @@ impl FlowView {...@@ -913,8 +1014,7 @@ impl FlowView {
913 let y0 = bs.start_local[1].min(bs.cur_local[1]);1014 let y0 = bs.start_local[1].min(bs.cur_local[1]);
914 let y1 = bs.start_local[1].max(bs.cur_local[1]);1015 let y1 = bs.start_local[1].max(bs.cur_local[1]);
915 if (x1 - x0) > 4.0 || (y1 - y0) > 4.0 {1016 if (x1 - x0) > 4.0 || (y1 - y0) > 4.0 {
916 for n in &comp.nodes {1017 for n in comp.nodes.iter().filter(|n| self.scope.shows(n)) {
917 if n.internal { continue; }
918 let c = self.world_to_local(n.pos);1018 let c = self.world_to_local(n.pos);
919 if c[0] >= x0 && c[0] <= x1 && c[1] >= y0 && c[1] <= y1 {1019 if c[0] >= x0 && c[0] <= x1 && c[1] >= y0 && c[1] <= y1 {
920 self.selected.insert(n.id);1020 self.selected.insert(n.id);
...@@ -1005,7 +1105,8 @@ impl FlowView {...@@ -1005,7 +1105,8 @@ impl FlowView {
1005 .entry("cycle!".to_owned())1105 .entry("cycle!".to_owned())
1006 .or_insert_with(|| make_layout("cycle!", &tiny_font));1106 .or_insert_with(|| make_layout("cycle!", &tiny_font));
1007 for key in [1107 for key in [
1008 "Shift+Space: Add Tool G/R/S: Transform Shift+Drag: Splice Del: Delete Cmd+D: Dup F2: Rename Ctrl+P: Bypass 1/2: Viewer",1108 HUD_ROOT,
1109 HUD_GROUP,
1009 "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis, Shift: Splice]",1110 "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis, Shift: Splice]",
1010 "ROTATE [LMB/Enter confirm, RMB/Esc cancel]",1111 "ROTATE [LMB/Enter confirm, RMB/Esc cancel]",
1011 "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]",1112 "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]",
...@@ -1066,8 +1167,7 @@ impl FlowView {...@@ -1066,8 +1167,7 @@ impl FlowView {
1066 let out_gap = if large_ports { 2.2 } else { 1.5 };1167 let out_gap = if large_ports { 2.2 } else { 1.5 };
1067 let port_outline = [0.04, 0.04, 0.06, 0.92];1168 let port_outline = [0.04, 0.04, 0.06, 0.92];
10681169
1069 for dst in &comp.nodes {1170 for dst in comp.nodes.iter().filter(|n| self.scope.shows(n)) {
1070 if dst.internal { continue; }
1071 // Track used edges on `dst` so multiple inputs on the same edge spread cleanly instead of overlapping1171 // Track used edges on `dst` so multiple inputs on the same edge spread cleanly instead of overlapping
1072 let mut used_edges: HashMap<u8, usize> = HashMap::new();1172 let mut used_edges: HashMap<u8, usize> = HashMap::new();
1073 let mut sorted_ports: Vec<(&String, &model::InputBinding)> = dst.inputs.iter().collect();1173 let mut sorted_ports: Vec<(&String, &model::InputBinding)> = dst.inputs.iter().collect();
...@@ -1080,7 +1180,7 @@ impl FlowView {...@@ -1080,7 +1180,7 @@ impl FlowView {
1080 });1180 });
1081 for (port, binding) in sorted_ports {1181 for (port, binding) in sorted_ports {
1082 let Some(src_name) = &binding.source_op else { continue };1182 let Some(src_name) = &binding.source_op else { continue };
1083 let Some(src_id) = comp.find_node(src_name) else { continue };1183 let Some(src_id) = self.scope.resolve(comp, src_name) else { continue };
1084 let role = PortRole::from_input_name(port);1184 let role = PortRole::from_input_name(port);
1085 let (a, ae, mut b, mut be) = self.wire_endpoints(comp, src_id, dst.id, role);1185 let (a, ae, mut b, mut be) = self.wire_endpoints(comp, src_id, dst.id, role);
1086 let ekey = |e: Edge| match e { Edge::Left => 0u8, Edge::Right => 1, Edge::Top => 2, Edge::Bottom => 3 };1186 let ekey = |e: Edge| match e { Edge::Left => 0u8, Edge::Right => 1, Edge::Top => 2, Edge::Bottom => 3 };
...@@ -1212,8 +1312,7 @@ impl FlowView {...@@ -1212,8 +1312,7 @@ impl FlowView {
1212 }1312 }
12131313
1214 // 4. Sleek Thin Fusion-Style Node Bars (color line along BOTTOM!)1314 // 4. Sleek Thin Fusion-Style Node Bars (color line along BOTTOM!)
1215 for n in &comp.nodes {1315 for n in comp.nodes.iter().filter(|n| self.scope.shows(n)) {
1216 if n.internal { continue; }
1217 let r = self.node_rect_local(n.pos);1316 let r = self.node_rect_local(n.pos);
1218 if r[2] < -20.0 || r[0] > w + 20.0 || r[3] < -20.0 || r[1] > h + 20.0 {1317 if r[2] < -20.0 || r[0] > w + 20.0 || r[3] < -20.0 || r[1] > h + 20.0 {
1219 continue;1318 continue;
...@@ -1394,7 +1493,8 @@ impl FlowView {...@@ -1394,7 +1493,8 @@ impl FlowView {
1394 Some(TransformMode::Grab) => "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis, Shift: Splice]",1493 Some(TransformMode::Grab) => "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis, Shift: Splice]",
1395 Some(TransformMode::Rotate) => "ROTATE [LMB/Enter confirm, RMB/Esc cancel]",1494 Some(TransformMode::Rotate) => "ROTATE [LMB/Enter confirm, RMB/Esc cancel]",
1396 Some(TransformMode::Scale) => "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]",1495 Some(TransformMode::Scale) => "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]",
1397 None => "Shift+Space: Add Tool G/R/S: Transform Shift+Drag: Splice Del: Delete Cmd+D: Dup F2: Rename Ctrl+P: Bypass 1/2: Viewer",1496 None if !self.scope.is_root() => HUD_GROUP,
1497 None => HUD_ROOT,
1398 };1498 };
1399 if let Some(l) = self.badge_cache.get(hud_key) {1499 if let Some(l) = self.badge_cache.get(hud_key) {
1400 let pill_h = 20.0;1500 let pill_h = 20.0;
...@@ -1416,6 +1516,10 @@ impl FlowView {...@@ -1416,6 +1516,10 @@ impl FlowView {
1416 }1516 }
1417}1517}
14181518
1519fn read_only_notice(actions: &mut Vec<FlowAction>) {
1520 actions.push(FlowAction::StatusNotice("Group contents are read-only; press Esc to leave the group".to_owned()));
1521}
1522
1419/// Static SVG triangles pointing INTO the node edge (`origin` sits flush on the node border).1523/// Static SVG triangles pointing INTO the node edge (`origin` sits flush on the node border).
1420fn input_arrow_svg(edge: Edge, large: bool) -> &'static str {1524fn input_arrow_svg(edge: Edge, large: bool) -> &'static str {
1421 match (edge, large) {1525 match (edge, large) {
...@@ -1605,4 +1709,224 @@ mod tests {...@@ -1605,4 +1709,224 @@ mod tests {
1605 assert!(p_eff[0] > comp.node(bg).pos[0]);1709 assert!(p_eff[0] > comp.node(bg).pos[0]);
1606 assert!(p_gen[1] < comp.node(bg).pos[1]);1710 assert!(p_gen[1] < comp.node(bg).pos[1]);
1607 }1711 }
1712
1713 const GROUP_COMP: &str = r#"Composition {
1714 Tools = ordered() {
1715 BG1 = Background { ViewInfo = OperatorInfo { Pos = { 0, 0 } }, },
1716 Outer = GroupOperator {
1717 Outputs = { Output1 = InstanceOutput { SourceOp = "Mid", Source = "Output" }, },
1718 ViewInfo = GroupInfo { Pos = { 200, 0 } },
1719 Tools = ordered() {
1720 A = Blur { ViewInfo = OperatorInfo { Pos = { 0, 100 } }, },
1721 ASpline = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, },
1722 Mid = Merge {
1723 Inputs = { Background = Input { SourceOp = "A", Source = "Output" }, },
1724 ViewInfo = OperatorInfo { Pos = { 110, 100 } },
1725 },
1726 Inner = GroupOperator {
1727 ViewInfo = GroupInfo { Pos = { 220, 100 } },
1728 Tools = ordered() {
1729 Deep = Blur { ViewInfo = OperatorInfo { Pos = { 0, 50 } }, },
1730 },
1731 },
1732 },
1733 },
1734 A = Background { ViewInfo = OperatorInfo { Pos = { 400, 0 } }, },
1735 },
1736 }"#;
1737
1738 fn group_flow() -> (Comp, FlowView) {
1739 let comp = Comp::from_fusion_str(GROUP_COMP).expect("parse group comp");
1740 let theme = ui::Theme::new(&theme::KNIFE, true);
1741 let mut flow = FlowView::new(&theme);
1742 flow.size = [800.0, 600.0];
1743 flow.reset_for_comp(&comp);
1744 flow.pan = [0.0, 0.0];
1745 flow.zoom = 1.0;
1746 (comp, flow)
1747 }
1748
1749 fn id(comp: &Comp, name: &str) -> NodeId {
1750 comp.find_node(name).unwrap()
1751 }
1752
1753 fn press(flow: &mut FlowView, comp: &mut Comp, history: &mut CompHistory, at: Instant, node: NodeId) -> Vec<FlowAction> {
1754 let local = flow.world_to_local(comp.node(node).pos);
1755 flow.input(
1756 comp,
1757 history,
1758 ui::Event::Button { button: MouseButton::Left, pressed: true, at },
1759 [0.0, 0.0, 800.0, 600.0],
1760 local,
1761 ModifiersState::empty(),
1762 )
1763 }
1764
1765 fn key(flow: &mut FlowView, comp: &mut Comp, history: &mut CompHistory, key: Key, modifiers: ModifiersState) -> Vec<FlowAction> {
1766 flow.input(
1767 comp,
1768 history,
1769 ui::Event::Key { key, text: None, modifiers },
1770 [0.0, 0.0, 800.0, 600.0],
1771 [0.0, 0.0],
1772 modifiers,
1773 )
1774 }
1775
1776 #[test]
1777 fn group_children_are_direct_tools_only() {
1778 let (comp, _) = group_flow();
1779 let names = |g: &str| -> Vec<&str> {
1780 group_children(&comp, id(&comp, g)).into_iter().map(|c| comp.node(c).name.as_str()).collect()
1781 };
1782 assert_eq!(names("Outer"), ["A", "Mid", "Inner"]);
1783 assert_eq!(names("Inner"), ["Deep"]);
1784 assert!(group_children(&comp, id(&comp, "BG1")).is_empty());
1785 }
1786
1787 #[test]
1788 fn enter_and_exit_group_filter_visible_nodes() {
1789 let (comp, mut flow) = group_flow();
1790 let (bg, outer, inner) = (id(&comp, "BG1"), id(&comp, "Outer"), id(&comp, "Inner"));
1791 let (mid, deep) = (id(&comp, "Mid"), id(&comp, "Deep"));
1792 flow.selected.insert(bg);
1793 flow.primary = Some(bg);
1794
1795 // Root shows only top-level tools; internal tools are not enterable from the root.
1796 assert_eq!(flow.hit_node(&comp, flow.world_to_local(comp.node(bg).pos)), Some(bg));
1797 assert_eq!(flow.hit_node(&comp, flow.world_to_local(comp.node(mid).pos)), None);
1798 assert!(!flow.enter_group(&comp, mid));
1799 assert!(!flow.enter_group(&comp, bg));
1800 assert!(flow.scope_path().is_empty());
1801
1802 assert!(flow.enter_group(&comp, outer));
1803 assert_eq!(flow.scope_path(), [outer]);
1804 assert!(flow.selected.is_empty() && flow.primary.is_none());
1805 assert_eq!(flow.hit_node(&comp, flow.world_to_local(comp.node(mid).pos)), Some(mid));
1806 assert_eq!(flow.hit_node(&comp, flow.world_to_local(comp.node(bg).pos)), None);
1807 assert_eq!(flow.hit_node(&comp, flow.world_to_local(comp.node(deep).pos)), None);
1808
1809 // Nested group, then back out one level at a time; leaving selects the group left.
1810 assert!(flow.enter_group(&comp, inner));
1811 assert_eq!(flow.scope_path(), [outer, inner]);
1812 assert_eq!(flow.hit_node(&comp, flow.world_to_local(comp.node(deep).pos)), Some(deep));
1813 assert!(flow.exit_group(&comp));
1814 assert_eq!(flow.scope_path(), [outer]);
1815 assert_eq!(flow.primary, Some(inner));
1816 assert!(flow.exit_to_depth(&comp, 0));
1817 assert!(flow.scope_path().is_empty());
1818 assert_eq!(flow.primary, Some(outer));
1819 assert_eq!(flow.selected, HashSet::from([outer]));
1820 assert!(!flow.exit_group(&comp));
1821 }
1822
1823 #[test]
1824 fn wires_resolve_within_the_shown_level() {
1825 let (comp, mut flow) = group_flow();
1826 let outer = id(&comp, "Outer");
1827 let (inner_a, root_a) = (comp.nodes.iter().find(|n| n.internal && n.name == "A").unwrap().id, id(&comp, "A"));
1828 assert_ne!(inner_a, root_a);
1829 assert_eq!(flow.scope.resolve(&comp, "A"), Some(root_a));
1830 flow.enter_group(&comp, outer);
1831 assert_eq!(flow.scope.resolve(&comp, "A"), Some(inner_a));
1832 assert_eq!(flow.scope.resolve(&comp, "BG1"), None);
1833
1834 // Mid's wire from A is hittable between the two inner nodes.
1835 let mid = id(&comp, "Mid");
1836 let mid_pos = comp.node(mid).pos;
1837 let a_pos = comp.node(inner_a).pos;
1838 let midpoint = [(mid_pos[0] + a_pos[0]) * 0.5, (mid_pos[1] + a_pos[1]) * 0.5];
1839 let wire = flow.hit_wire(&comp, flow.world_to_local(midpoint), None).expect("wire");
1840 assert_eq!((wire.src, wire.dst), (inner_a, mid));
1841 }
1842
1843 #[test]
1844 fn double_click_enters_group_and_escape_leaves() {
1845 let (mut comp, mut flow) = group_flow();
1846 let mut history = CompHistory::new();
1847 let (bg, outer) = (id(&comp, "BG1"), id(&comp, "Outer"));
1848 let t0 = Instant::now();
1849
1850 // Double-clicking a plain tool, or two slow clicks on a group, never enters.
1851 press(&mut flow, &mut comp, &mut history, t0, bg);
1852 press(&mut flow, &mut comp, &mut history, t0 + Duration::from_millis(100), bg);
1853 assert!(flow.scope_path().is_empty());
1854 press(&mut flow, &mut comp, &mut history, t0, outer);
1855 press(&mut flow, &mut comp, &mut history, t0 + Duration::from_millis(900), outer);
1856 assert!(flow.scope_path().is_empty());
1857
1858 let acts = press(&mut flow, &mut comp, &mut history, t0 + Duration::from_millis(1000), outer);
1859 assert_eq!(flow.scope_path(), [outer]);
1860 assert!(acts.iter().any(|a| matches!(a, FlowAction::ScopeChanged)));
1861
1862 let acts = key(&mut flow, &mut comp, &mut history, Key::Named(NamedKey::Escape), ModifiersState::empty());
1863 assert!(flow.scope_path().is_empty());
1864 assert!(acts.iter().any(|a| matches!(a, FlowAction::ScopeChanged)));
1865 assert_eq!(flow.primary, Some(outer));
1866
1867 // Escape at the root does nothing.
1868 let acts = key(&mut flow, &mut comp, &mut history, Key::Named(NamedKey::Escape), ModifiersState::empty());
1869 assert!(acts.is_empty());
1870 }
1871
1872 #[test]
1873 fn group_view_is_read_only_but_copyable() {
1874 let (mut comp, mut flow) = group_flow();
1875 let mut history = CompHistory::new();
1876 let (outer, mid) = (id(&comp, "Outer"), id(&comp, "Mid"));
1877 flow.enter_group(&comp, outer);
1878 flow.selected.insert(mid);
1879 flow.primary = Some(mid);
1880 let nodes = comp.nodes.len();
1881
1882 for k in ["g", "p"] {
1883 let acts = key(&mut flow, &mut comp, &mut history, Key::Character(k.into()), ModifiersState::empty());
1884 assert!(matches!(acts.as_slice(), [FlowAction::StatusNotice(_)]), "{k}");
1885 }
1886 let acts = key(&mut flow, &mut comp, &mut history, Key::Named(NamedKey::Delete), ModifiersState::empty());
1887 assert!(matches!(acts.as_slice(), [FlowAction::StatusNotice(_)]));
1888 let acts = key(&mut flow, &mut comp, &mut history, Key::Character("d".into()), ModifiersState::SUPER);
1889 assert!(matches!(acts.as_slice(), [FlowAction::StatusNotice(_)]));
1890 assert_eq!(comp.nodes.len(), nodes);
1891 assert!(!comp.node(mid).bypassed);
1892 assert!(!history.can_undo());
1893
1894 let acts = key(&mut flow, &mut comp, &mut history, Key::Character("c".into()), ModifiersState::SUPER);
1895 assert!(matches!(acts.as_slice(), [FlowAction::CopyNodes(ids)] if ids == &[mid]));
1896 }
1897
1898 #[test]
1899 fn copy_and_paste_shortcuts_emit_requests() {
1900 let (mut comp, mut flow) = group_flow();
1901 let mut history = CompHistory::new();
1902 let bg = id(&comp, "BG1");
1903
1904 let none = key(&mut flow, &mut comp, &mut history, Key::Character("c".into()), ModifiersState::SUPER);
1905 assert!(none.is_empty(), "nothing selected, nothing to copy");
1906
1907 flow.selected.insert(bg);
1908 flow.primary = Some(bg);
1909 let acts = key(&mut flow, &mut comp, &mut history, Key::Character("c".into()), ModifiersState::SUPER);
1910 assert!(matches!(acts.as_slice(), [FlowAction::CopyNodes(ids)] if ids == &[bg]));
1911 let acts = key(&mut flow, &mut comp, &mut history, Key::Character("v".into()), ModifiersState::SUPER);
1912 assert!(matches!(acts.as_slice(), [FlowAction::PasteNodes]));
1913 // Plain `c` / `v` are not shortcuts.
1914 let acts = key(&mut flow, &mut comp, &mut history, Key::Character("v".into()), ModifiersState::empty());
1915 assert!(acts.is_empty());
1916 }
1917
1918 #[test]
1919 fn sanitize_drops_scope_levels_that_no_longer_exist() {
1920 let (comp, mut flow) = group_flow();
1921 let (outer, inner) = (id(&comp, "Outer"), id(&comp, "Inner"));
1922 flow.enter_group(&comp, outer);
1923 flow.enter_group(&comp, inner);
1924 flow.sanitize_ids(&comp);
1925 assert_eq!(flow.scope_path(), [outer, inner]);
1926
1927 let flat = test_comp();
1928 flow.sanitize_ids(&flat);
1929 assert!(flow.scope_path().is_empty());
1930 assert!(flow.selected.is_empty());
1931 }
1608}1932}
crates/flow/src/scope.rs created+134
...@@ -0,0 +1,134 @@
1//! Which graph level the Flow canvas shows: the root, or the inside of a nested
2//! `MacroOperator` / `GroupOperator`.
3//!
4//! `Comp` stores every unpacked tool in one flat `nodes` list; a group's children are the
5//! internal tools parsed immediately before it, named by the group's raw `Tools` table.
6
7use model::{Comp, LuaKey, Node, NodeId};
8use std::collections::HashSet;
9
10/// Direct children of `owner` and the first `NodeId` of its whole (nested) block.
11fn scan(comp: &Comp, owner: NodeId) -> (Vec<NodeId>, usize) {
12 let mut children = Vec::new();
13 let mut cursor = owner.0;
14 if let Some(tools) = comp.nodes[owner.0].raw.get_table("Tools") {
15 for (key, value) in tools.entries.iter().rev() {
16 let (LuaKey::Str(name), Some(tool)) = (key, value.as_table()) else {
17 continue;
18 };
19 let kind = tool.tag.as_deref().unwrap_or("Unknown");
20 let child = (0..cursor).rev().find(|&i| {
21 let n = &comp.nodes[i];
22 n.internal && n.name == *name && n.kind == kind
23 });
24 // Modifiers (splines, paths) own no node.
25 let Some(child) = child else { continue };
26 children.push(NodeId(child));
27 cursor = scan(comp, NodeId(child)).1;
28 }
29 }
30 children.reverse();
31 (children, cursor)
32}
33
34/// Tools shown inside `group`, in `comp.nodes` order.
35pub fn group_children(comp: &Comp, group: NodeId) -> Vec<NodeId> {
36 if group.0 >= comp.nodes.len() {
37 return Vec::new();
38 }
39 scan(comp, group).0
40}
41
42pub fn is_group(node: &Node) -> bool {
43 matches!(node.kind.as_str(), "MacroOperator" | "GroupOperator")
44}
45
46#[derive(Default)]
47pub struct Scope {
48 path: Vec<NodeId>,
49 members: HashSet<NodeId>,
50}
51
52impl Scope {
53 /// Groups entered from the root, outermost first.
54 pub fn path(&self) -> &[NodeId] {
55 &self.path
56 }
57
58 pub fn is_root(&self) -> bool {
59 self.path.is_empty()
60 }
61
62 pub fn shows(&self, node: &Node) -> bool {
63 if self.is_root() {
64 !node.internal
65 } else {
66 self.members.contains(&node.id)
67 }
68 }
69
70 /// The shown node called `name`; `Comp::find_node` can pick a same-named tool of another level.
71 pub fn resolve(&self, comp: &Comp, name: &str) -> Option<NodeId> {
72 if self.is_root() {
73 comp.find_node(name).filter(|&id| !comp.node(id).internal)
74 } else {
75 self.members.iter().copied().find(|&id| comp.node(id).name == name)
76 }
77 }
78
79 /// Every shown node, in `comp.nodes` order.
80 pub fn visible(&self, comp: &Comp) -> Vec<NodeId> {
81 comp.nodes.iter().filter(|n| self.shows(n)).map(|n| n.id).collect()
82 }
83
84 /// Descends into `group` when it is a shown macro/group node.
85 pub fn enter(&mut self, comp: &Comp, group: NodeId) -> bool {
86 if !comp.nodes.get(group.0).is_some_and(|n| is_group(n) && self.shows(n)) {
87 return false;
88 }
89 self.path.push(group);
90 self.members = group_children(comp, group).into_iter().collect();
91 true
92 }
93
94 /// Keeps the outermost `depth` levels; returns the first group left.
95 pub fn truncate(&mut self, comp: &Comp, depth: usize) -> Option<NodeId> {
96 let left = self.path.get(depth).copied()?;
97 self.path.truncate(depth);
98 self.reload_members(comp);
99 Some(left)
100 }
101
102 /// Drops levels that no longer exist after an undo, redo or delete, and refreshes membership.
103 /// Returns whether the path changed.
104 pub fn refresh(&mut self, comp: &Comp) -> bool {
105 let mut valid = 0;
106 let mut parent_children: Option<HashSet<NodeId>> = None;
107 for &group in &self.path {
108 let ok = comp.nodes.get(group.0).is_some_and(|n| {
109 is_group(n)
110 && match &parent_children {
111 Some(siblings) => siblings.contains(&group),
112 None => !n.internal,
113 }
114 });
115 if !ok {
116 break;
117 }
118 parent_children = Some(group_children(comp, group).into_iter().collect());
119 valid += 1;
120 }
121 let changed = valid != self.path.len();
122 self.path.truncate(valid);
123 self.reload_members(comp);
124 changed
125 }
126
127 fn reload_members(&mut self, comp: &Comp) {
128 self.members = self
129 .path
130 .last()
131 .map(|&g| group_children(comp, g).into_iter().collect())
132 .unwrap_or_default();
133 }
134}
crates/model/src/edit.rs+456-1
...@@ -4,7 +4,7 @@ use crate::comp::{...@@ -4,7 +4,7 @@ use crate::comp::{
4 Comp, InputBinding, Node, NodeId, ParamValue, default_main_input_port, ensure_table_mut,4 Comp, InputBinding, Node, NodeId, ParamValue, default_main_input_port, ensure_table_mut,
5 param_value_to_lua, vec2_lua,5 param_value_to_lua, vec2_lua,
6};6};
7use crate::lua_value::{LuaKey, LuaTable, LuaValue, is_valid_lua_ident};7use crate::lua_value::{LuaKey, LuaTable, LuaValue, is_valid_lua_ident, parse_lua};
8use crate::spline::{BezierSpline, Keyframe, PolyPath};8use crate::spline::{BezierSpline, Keyframe, PolyPath};
9use std::collections::{HashMap, HashSet, VecDeque};9use std::collections::{HashMap, HashSet, VecDeque};
1010
...@@ -23,6 +23,7 @@ impl Comp {...@@ -23,6 +23,7 @@ impl Comp {
23 || self.polyline_splines.contains_key(name)23 || self.polyline_splines.contains_key(name)
24 || self.text_cls.contains_key(name)24 || self.text_cls.contains_key(name)
25 || self.shakes.contains_key(name)25 || self.shakes.contains_key(name)
26 || self.expression_modifiers.contains_key(name)
26 {27 {
27 return true;28 return true;
28 }29 }
...@@ -294,6 +295,158 @@ impl Comp {...@@ -294,6 +295,158 @@ impl Comp {
294 deleted_names295 deleted_names
295 }296 }
296297
298 /// Serializes `ids` plus every modifier (spline, path, shake, ...) they reference into
299 /// Fusion's clipboard format: `{ Tools = ordered() { ... }, ActiveTool = "<first>" }`.
300 /// References to unselected nodes are kept verbatim and dropped again on paste if missing.
301 pub fn export_fusion_clipboard(&self, ids: &[NodeId]) -> String {
302 let synced = self.sync_to_raw_ast();
303 let root_tools = synced.get_table("Tools");
304 let node_names: HashSet<&str> = self.nodes.iter().map(|n| n.name.as_str()).collect();
305
306 let mut picked: Vec<&Node> = Vec::new();
307 for &id in ids {
308 if let Some(n) = self.nodes.get(id.0) {
309 if !picked.iter().any(|p| p.id == n.id) {
310 picked.push(n);
311 }
312 }
313 }
314 let mut tools = LuaTable {
315 tag: Some("ordered".to_owned()),
316 entries: Vec::new(),
317 };
318 let mut refs: VecDeque<String> = VecDeque::new();
319 for n in &picked {
320 let raw = if n.internal {
321 &n.raw
322 } else {
323 root_tools.and_then(|t| t.get_table(&n.name)).unwrap_or(&n.raw)
324 };
325 let mut found = HashSet::new();
326 collect_source_ops_in_table(raw, &mut found);
327 let mut found: Vec<String> = found.into_iter().collect();
328 found.sort();
329 refs.extend(found);
330 tools.set(LuaKey::Str(n.name.clone()), LuaValue::Table(raw.clone()));
331 }
332 while let Some(name) = refs.pop_front() {
333 if tools.get(&name).is_some() || node_names.contains(name.as_str()) {
334 continue;
335 }
336 let Some(modifier) = root_tools.and_then(|t| t.get_table(&name)) else {
337 continue;
338 };
339 let mut found = HashSet::new();
340 collect_source_ops_in_table(modifier, &mut found);
341 let mut found: Vec<String> = found.into_iter().collect();
342 found.sort();
343 refs.extend(found);
344 tools.set(LuaKey::Str(name), LuaValue::Table(modifier.clone()));
345 }
346
347 let mut doc = LuaTable::default();
348 doc.set(LuaKey::Str("Tools".to_owned()), LuaValue::Table(tools));
349 if let Some(first) = picked.first() {
350 doc.set(
351 LuaKey::Str("ActiveTool".to_owned()),
352 LuaValue::String(first.name.clone()),
353 );
354 }
355 doc.to_fusion_string()
356 }
357
358 /// Pastes Fusion clipboard Lua (`{ Tools = ordered() { ... } }` or a full `Composition`),
359 /// renaming colliding tools/modifiers (`Blur1` -> `Blur1_1`), rewiring references among the
360 /// pasted tools, dropping references to tools that exist nowhere, and shifting each top-level
361 /// tool's `ViewInfo.Pos` by `offset`. Returns the new top-level flow nodes; on `Err` the comp
362 /// is untouched. Prefer [`CompHistory::paste_fusion_clipboard`] for an undoable paste.
363 pub fn paste_fusion_clipboard(
364 &mut self,
365 lua_snippet: &str,
366 offset: (f32, f32),
367 ) -> Result<Vec<NodeId>, String> {
368 let parsed = parse_lua(lua_snippet).map_err(|e| format!("clipboard is not Fusion Lua: {e}"))?;
369 let mut tools = parsed
370 .as_table()
371 .and_then(|t| t.get_table("Tools"))
372 .filter(|t| !t.entries.is_empty())
373 .cloned()
374 .ok_or_else(|| "clipboard has no Fusion tools".to_owned())?;
375
376 let mut pasted_names = Vec::new();
377 collect_tool_names(&tools, &mut pasted_names);
378 let pasted_set: HashSet<&str> = pasted_names.iter().map(String::as_str).collect();
379
380 drop_unknown_source_ops(&mut tools, &mut |name| {
381 pasted_set.contains(name)
382 || self.name_exists(name)
383 || self.nodes.iter().any(|n| n.name == name)
384 });
385
386 let mut reserved: HashSet<String> = self.nodes.iter().map(|n| n.name.clone()).collect();
387 let mut renames: HashMap<String, String> = HashMap::new();
388 for name in &pasted_names {
389 if renames.contains_key(name) {
390 continue;
391 }
392 let fresh = self.generate_unique_name_excluding(name, &reserved);
393 reserved.insert(fresh.clone());
394 renames.insert(name.clone(), fresh);
395 }
396 rename_tools(&mut tools, &renames);
397
398 let mut doc = LuaTable {
399 tag: Some("Composition".to_owned()),
400 entries: Vec::new(),
401 };
402 doc.set(LuaKey::Str("Tools".to_owned()), LuaValue::Table(tools));
403 let staged = Comp::from_fusion_str(&doc.to_fusion_string())
404 .map_err(|e| format!("clipboard tools failed to parse: {e}"))?;
405 let Some(staged_tools) = doc.get_table("Tools") else {
406 return Err("clipboard has no Fusion tools".to_owned());
407 };
408
409 let base = self.nodes.len();
410 let shift = |id: NodeId| NodeId(base + id.0);
411 let mut created = Vec::new();
412 let mut top_level: HashMap<String, LuaTable> = HashMap::new();
413 for mut node in staged.nodes {
414 node.id = shift(node.id);
415 node.macro_output = node.macro_output.map(shift);
416 if !node.internal {
417 node.pos = [node.pos[0] + offset.0, node.pos[1] + offset.1];
418 set_view_info_pos(&mut node.raw, node.pos);
419 top_level.insert(node.name.clone(), node.raw.clone());
420 created.push(node.id);
421 }
422 self.nodes.push(node);
423 }
424 for (name, id) in staged.node_by_name {
425 self.node_by_name.entry(name).or_insert(shift(id));
426 }
427 self.splines.extend(staged.splines);
428 self.poly_paths.extend(staged.poly_paths);
429 self.gradient_modifiers.extend(staged.gradient_modifiers);
430 self.text_modifiers.extend(staged.text_modifiers);
431 self.text_splines.extend(staged.text_splines);
432 self.polyline_splines.extend(staged.polyline_splines);
433 self.text_cls.extend(staged.text_cls);
434 self.shakes.extend(staged.shakes);
435 self.expression_modifiers.extend(staged.expression_modifiers);
436
437 if let Some(root) = self.raw_root.as_mut() {
438 let dest = ensure_table_mut(root, "Tools", Some("ordered"));
439 for (key, value) in &staged_tools.entries {
440 let LuaKey::Str(name) = key else { continue };
441 let table = top_level.remove(name).map_or_else(|| value.clone(), LuaValue::Table);
442 dest.set(key.clone(), table);
443 }
444 }
445
446 self.revision += 1;
447 Ok(created)
448 }
449
297 /// Duplicates the selected nodes at `pos + offset` with unique names.450 /// Duplicates the selected nodes at `pos + offset` with unique names.
298 /// Preserves internal wires between duplicated nodes, keeps external wires intact,451 /// Preserves internal wires between duplicated nodes, keeps external wires intact,
299 /// and clones owned `BezierSpline` / `PolyPath` modifiers with fresh unique names.452 /// and clones owned `BezierSpline` / `PolyPath` modifiers with fresh unique names.
...@@ -1088,6 +1241,20 @@ impl CompHistory {...@@ -1088,6 +1241,20 @@ impl CompHistory {
1088 true1241 true
1089 }1242 }
10901243
1244 /// Undoable [`Comp::paste_fusion_clipboard`]: the whole paste is one undo step, and a failed
1245 /// paste leaves both `comp` and the history untouched.
1246 pub fn paste_fusion_clipboard(
1247 &mut self,
1248 comp: &mut Comp,
1249 lua_snippet: &str,
1250 offset: (f32, f32),
1251 ) -> Result<Vec<NodeId>, String> {
1252 self.begin_group(comp, "Paste");
1253 let pasted = comp.paste_fusion_clipboard(lua_snippet, offset);
1254 self.commit_group(comp);
1255 pasted
1256 }
1257
1091 /// Undoes the most recent edit, restoring `comp` to the saved snapshot.1258 /// Undoes the most recent edit, restoring `comp` to the saved snapshot.
1092 /// Always advances `comp.revision` monotonically so downstream caches invalidate cleanly.1259 /// Always advances `comp.revision` monotonically so downstream caches invalidate cleanly.
1093 pub fn undo(&mut self, comp: &mut Comp) -> bool {1260 pub fn undo(&mut self, comp: &mut Comp) -> bool {
...@@ -1203,6 +1370,89 @@ fn rewrite_source_op_in_table(tbl: &mut LuaTable, old_name: &str, new_name: &str...@@ -1203,6 +1370,89 @@ fn rewrite_source_op_in_table(tbl: &mut LuaTable, old_name: &str, new_name: &str
1203 }1370 }
1204}1371}
12051372
1373/// Names of every tool in `tools`, including tools nested in `Tools` tables (macros/groups).
1374fn collect_tool_names(tools: &LuaTable, out: &mut Vec<String>) {
1375 for (key, value) in &tools.entries {
1376 let (LuaKey::Str(name), Some(tool)) = (key, value.as_table()) else {
1377 continue;
1378 };
1379 out.push(name.clone());
1380 if let Some(inner) = tool.get_table("Tools") {
1381 collect_tool_names(inner, out);
1382 }
1383 }
1384}
1385
1386/// Renames tool keys (recursively) and rewrites every reference to them: `SourceOp` values and
1387/// whole-word identifiers inside `Expression` strings.
1388fn rename_tools(tools: &mut LuaTable, renames: &HashMap<String, String>) {
1389 for (key, value) in &mut tools.entries {
1390 let LuaKey::Str(name) = key else { continue };
1391 if let Some(new) = renames.get(name.as_str()) {
1392 *name = new.clone();
1393 }
1394 if let Some(tool) = value.as_table_mut() {
1395 rewrite_references(tool, renames);
1396 if let Some(inner) = tool.get_table_mut("Tools") {
1397 rename_tools(inner, renames);
1398 }
1399 }
1400 }
1401}
1402
1403fn rewrite_references(tbl: &mut LuaTable, renames: &HashMap<String, String>) {
1404 for (key, value) in &mut tbl.entries {
1405 match (key, value) {
1406 (LuaKey::Str(k), LuaValue::String(s)) if k == "SourceOp" => {
1407 if let Some(new) = renames.get(s.as_str()) {
1408 *s = new.clone();
1409 }
1410 }
1411 (LuaKey::Str(k), LuaValue::String(s)) if k == "Expression" => {
1412 *s = rename_expression_idents(s, renames);
1413 }
1414 (_, LuaValue::Table(sub)) => rewrite_references(sub, renames),
1415 _ => {}
1416 }
1417 }
1418}
1419
1420fn rename_expression_idents(expr: &str, renames: &HashMap<String, String>) -> String {
1421 let mut out = String::with_capacity(expr.len());
1422 let mut word = String::new();
1423 let flush = |word: &mut String, out: &mut String| {
1424 out.push_str(renames.get(word.as_str()).map_or(word.as_str(), String::as_str));
1425 word.clear();
1426 };
1427 for ch in expr.chars() {
1428 if ch.is_ascii_alphanumeric() || ch == '_' {
1429 word.push(ch);
1430 } else {
1431 flush(&mut word, &mut out);
1432 out.push(ch);
1433 }
1434 }
1435 flush(&mut word, &mut out);
1436 out
1437}
1438
1439/// Removes `SourceOp`/`Source` pairs whose target fails `exists`, so pasted tools never point at
1440/// missing operators.
1441fn drop_unknown_source_ops(tbl: &mut LuaTable, exists: &mut dyn FnMut(&str) -> bool) {
1442 let dangling = tbl
1443 .get_str("SourceOp")
1444 .is_some_and(|name| !exists(name));
1445 if dangling {
1446 tbl.remove(&LuaKey::Str("SourceOp".to_owned()));
1447 tbl.remove(&LuaKey::Str("Source".to_owned()));
1448 }
1449 for (_, value) in &mut tbl.entries {
1450 if let Some(sub) = value.as_table_mut() {
1451 drop_unknown_source_ops(sub, exists);
1452 }
1453 }
1454}
1455
1206fn set_view_info_pos(raw: &mut LuaTable, pos: [f32; 2]) {1456fn set_view_info_pos(raw: &mut LuaTable, pos: [f32; 2]) {
1207 let vi = ensure_table_mut(raw, "ViewInfo", Some("OperatorInfo"));1457 let vi = ensure_table_mut(raw, "ViewInfo", Some("OperatorInfo"));
1208 vi.set(1458 vi.set(
...@@ -1823,4 +2073,209 @@ mod tests {...@@ -1823,4 +2073,209 @@ mod tests {
1823 assert!(!history.can_undo());2073 assert!(!history.can_undo());
1824 assert!(!history.can_redo());2074 assert!(!history.can_redo());
1825 }2075 }
2076
2077 const GROUP_SNIPPET: &str = r#"{
2078 Tools = ordered() {
2079 Group1 = GroupOperator {
2080 Inputs = {
2081 Input1 = InstanceInput { SourceOp = "Inner1", Source = "Input", },
2082 },
2083 Outputs = {
2084 Output1 = InstanceOutput { SourceOp = "Inner1", Source = "Output", },
2085 },
2086 ViewInfo = GroupInfo { Pos = { 10, 20 } },
2087 Tools = ordered() {
2088 Inner1 = Blur {
2089 Inputs = {
2090 XBlurSize = Input { SourceOp = "Inner1Size", Source = "Value", },
2091 },
2092 ViewInfo = OperatorInfo { Pos = { 0, 0 } },
2093 },
2094 Inner1Size = BezierSpline {
2095 KeyFrames = { [0] = { 1, Flags = { Linear = true } } },
2096 },
2097 },
2098 },
2099 },
2100}"#;
2101
2102 #[test]
2103 fn export_fusion_clipboard_includes_owned_modifiers_and_internal_wires() {
2104 let comp = sample_comp();
2105 let bg = comp.find_node("BG1").unwrap();
2106 let bc = comp.find_node("BC1").unwrap();
2107
2108 let both = comp.export_fusion_clipboard(&[bg, bc]);
2109 assert!(both.contains("Tools = ordered()"), "{both}");
2110 assert!(both.contains("ActiveTool = \"BG1\""), "{both}");
2111 let parsed = parse_lua(&both).expect("clipboard parses as Lua");
2112 let tools = parsed.as_table().unwrap().get_table("Tools").unwrap();
2113 let names: Vec<_> = tools
2114 .entries
2115 .iter()
2116 .filter_map(|(k, _)| if let LuaKey::Str(s) = k { Some(s.as_str()) } else { None })
2117 .collect();
2118 assert_eq!(names, ["BG1", "BC1", "BC1Gain"]);
2119 assert_eq!(
2120 tools
2121 .get_table("BC1")
2122 .and_then(|t| t.get_table("Inputs"))
2123 .and_then(|i| i.get_table("Input"))
2124 .and_then(|i| i.get_str("SourceOp")),
2125 Some("BG1")
2126 );
2127
2128 // Selecting only BC1 keeps its owned spline and leaves the external BG1 reference.
2129 let only_bc = comp.export_fusion_clipboard(&[bc, bc]);
2130 assert!(only_bc.contains("BC1Gain = BezierSpline"));
2131 assert!(!only_bc.contains("BG1 = Background"));
2132 assert!(only_bc.contains("SourceOp = \"BG1\""));
2133
2134 // Splines created after load (not yet in `raw_root`) are exported too.
2135 let mut comp = comp;
2136 let sp = comp.set_keyframe(bg, "Width", 0.0, 1.0).unwrap();
2137 assert!(comp.export_fusion_clipboard(&[bg]).contains(&format!("{sp} = BezierSpline")));
2138 }
2139
2140 #[test]
2141 fn paste_dedups_names_and_remaps_internal_wires_and_splines() {
2142 let mut comp = sample_comp();
2143 let bg = comp.find_node("BG1").unwrap();
2144 let bc = comp.find_node("BC1").unwrap();
2145 let snippet = comp.export_fusion_clipboard(&[bg, bc]);
2146 let nodes_before = comp.nodes.len();
2147
2148 let ids = comp.paste_fusion_clipboard(&snippet, (60.0, 40.0)).expect("paste");
2149 assert_eq!(ids.len(), 2);
2150 assert_eq!(comp.nodes.len(), nodes_before + 2);
2151 let (pbg, pbc) = (comp.node(ids[0]), comp.node(ids[1]));
2152 assert_eq!((pbg.name.as_str(), pbc.name.as_str()), ("BG1_1", "BC1_1"));
2153 assert_eq!(pbg.pos, [160.0, 90.0]);
2154 assert_eq!(pbc.pos, [360.0, 90.0]);
2155 assert_eq!(pbc.connected_node("Input"), Some("BG1_1"));
2156 assert_eq!(pbc.connected_node("Gain"), Some("BC1Gain_1"));
2157 assert_eq!(comp.splines["BC1Gain_1"].keyframes.len(), 2);
2158 assert_eq!(comp.splines["BC1Gain"].keyframes.len(), 2);
2159 assert_eq!(comp.find_node("BC1_1"), Some(ids[1]));
2160 assert_eq!(comp.node(bc).connected_node("Input"), Some("BG1"));
2161
2162 // Pasting again keeps advancing the suffix instead of clobbering earlier pastes.
2163 let again = comp.paste_fusion_clipboard(&snippet, (0.0, 0.0)).unwrap();
2164 assert_eq!(comp.node(again[0]).name, "BG1_2");
2165 assert_eq!(comp.node(again[1]).connected_node("Input"), Some("BG1_2"));
2166
2167 // Everything survives a save/load roundtrip, including the cloned spline and offset.
2168 let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("reload");
2169 let r_bc = reloaded.node(reloaded.find_node("BC1_1").unwrap());
2170 assert_eq!(r_bc.pos, [360.0, 90.0]);
2171 assert_eq!(r_bc.connected_node("Input"), Some("BG1_1"));
2172 assert!(reloaded.splines.contains_key("BC1Gain_1"));
2173 }
2174
2175 #[test]
2176 fn paste_external_references_are_kept_when_present_and_dropped_when_missing() {
2177 let mut comp = sample_comp();
2178 let bc = comp.find_node("BC1").unwrap();
2179 let snippet = comp.export_fusion_clipboard(&[bc]);
2180
2181 let ids = comp.paste_fusion_clipboard(&snippet, (0.0, 0.0)).unwrap();
2182 assert_eq!(comp.node(ids[0]).connected_node("Input"), Some("BG1"));
2183
2184 let mut empty = Comp::from_fusion_str("Composition { Tools = ordered() { } }").unwrap();
2185 let ids = empty.paste_fusion_clipboard(&snippet, (5.0, 5.0)).unwrap();
2186 let pasted = empty.node(ids[0]);
2187 assert_eq!(pasted.name, "BC1");
2188 assert_eq!(pasted.connected_node("Input"), None);
2189 assert_eq!(pasted.connected_node("Gain"), Some("BC1Gain"));
2190 assert!(!empty.to_fusion_string().contains("BG1"));
2191 }
2192
2193 #[test]
2194 fn paste_accepts_full_composition_and_rewrites_expressions() {
2195 let mut comp = sample_comp();
2196 let snippet = r#"Composition {
2197 Tools = ordered() {
2198 BG1 = Background { Inputs = { Width = Input { Value = 64, } }, },
2199 T1 = Transform {
2200 Inputs = {
2201 Size = Input { Expression = "BG1.Width / 2 + BG10.Width", },
2202 Input = Input { SourceOp = "BG1", Source = "Output", },
2203 },
2204 },
2205 },
2206}"#;
2207 let ids = comp.paste_fusion_clipboard(snippet, (1.0, 2.0)).unwrap();
2208 let t1 = comp.node(ids[1]);
2209 assert_eq!(comp.node(ids[0]).name, "BG1_1");
2210 assert_eq!(comp.node(ids[0]).pos, [1.0, 2.0]);
2211 assert_eq!(t1.connected_node("Input"), Some("BG1_1"));
2212 assert_eq!(
2213 t1.inputs["Size"].expression.as_deref(),
2214 Some("BG1_1.Width / 2 + BG10.Width")
2215 );
2216 }
2217
2218 #[test]
2219 fn paste_group_renames_nested_tools_and_remaps_macro_output() {
2220 let mut comp = sample_comp();
2221 let first = comp.paste_fusion_clipboard(GROUP_SNIPPET, (0.0, 0.0)).unwrap();
2222 let second = comp.paste_fusion_clipboard(GROUP_SNIPPET, (50.0, 0.0)).unwrap();
2223 let (g1, g2) = (comp.node(first[0]), comp.node(second[0]));
2224 assert_eq!((g1.name.as_str(), g2.name.as_str()), ("Group1", "Group1_1"));
2225 assert_eq!(g2.pos, [60.0, 20.0]);
2226
2227 let inner = comp.node(g2.macro_output.expect("macro output"));
2228 assert_eq!(inner.name, "Inner1_1");
2229 assert!(inner.internal);
2230 assert_eq!(inner.connected_node("XBlurSize"), Some("Inner1Size_1"));
2231 assert!(comp.splines.contains_key("Inner1Size_1"));
2232 assert_eq!(comp.node(g1.macro_output.unwrap()).name, "Inner1");
2233 assert_eq!(comp.find_node("Group1_1"), Some(second[0]));
2234 assert_eq!(comp.find_node("Inner1_1"), g2.macro_output);
2235 }
2236
2237 #[test]
2238 fn paste_is_one_undo_step_and_redoable() {
2239 let mut comp = sample_comp();
2240 let mut history = CompHistory::new();
2241 let bg = comp.find_node("BG1").unwrap();
2242 let bc = comp.find_node("BC1").unwrap();
2243 let snippet = comp.export_fusion_clipboard(&[bg, bc]);
2244 let (nodes, splines) = (comp.nodes.len(), comp.splines.len());
2245 history.mark_saved(&comp);
2246
2247 let ids = history
2248 .paste_fusion_clipboard(&mut comp, &snippet, (60.0, 40.0))
2249 .unwrap();
2250 assert_eq!(ids.len(), 2);
2251 assert_eq!(history.undo_len(), 1);
2252 assert_eq!(history.undo_label(), Some("Paste"));
2253 assert!(history.is_dirty(&comp));
2254
2255 assert!(history.undo(&mut comp));
2256 assert_eq!((comp.nodes.len(), comp.splines.len()), (nodes, splines));
2257 assert!(comp.find_node("BG1_1").is_none());
2258 assert!(!comp.to_fusion_string().contains("BG1_1"));
2259 assert!(!history.can_undo());
2260 assert!(!history.is_dirty(&comp));
2261
2262 assert!(history.redo(&mut comp));
2263 assert_eq!((comp.nodes.len(), comp.splines.len()), (nodes + 2, splines + 1));
2264 let pasted = comp.find_node("BC1_1").unwrap();
2265 assert_eq!(comp.node(pasted).connected_node("Input"), Some("BG1_1"));
2266 assert!(!history.can_redo());
2267 }
2268
2269 #[test]
2270 fn paste_rejects_garbage_without_touching_comp_or_history() {
2271 let mut comp = sample_comp();
2272 let mut history = CompHistory::new();
2273 let (rev, nodes) = (comp.revision, comp.nodes.len());
2274 for bad in ["", "hello world", "{ Foo = 1 }", "{ Tools = ordered() { } }", "{ Tools = "] {
2275 assert!(history.paste_fusion_clipboard(&mut comp, bad, (0.0, 0.0)).is_err(), "{bad:?}");
2276 }
2277 assert_eq!((comp.revision, comp.nodes.len()), (rev, nodes));
2278 assert!(!history.can_undo());
2279 assert!(!history.in_group());
2280 }
1826}2281}