diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index a39d1083528256b6b82409ba2a5d8896d7811d1b..6e083cb34f87e2b64fb3b7fbfca21d3636acb440 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -653,6 +653,34 @@ impl Studio { self.set_notice(format!("Added {}", self.comp.node(new_id).name)); } + fn copy_nodes(&mut self, ids: &[NodeId]) { + self.ui.clipboard.set_text(self.comp.export_fusion_clipboard(ids)); + let n = ids.len(); + self.set_notice(format!("Copied {n} node{}", if n == 1 { "" } else { "s" })); + } + + fn paste_nodes(&mut self) { + if !self.flow.scope_path().is_empty() { + self.set_notice("Group contents are read-only; press Esc to leave the group before pasting"); + return; + } + let Some(text) = self.ui.clipboard.text() else { + self.set_notice("Clipboard is empty"); + return; + }; + match self.history.paste_fusion_clipboard(&mut self.comp, &text, (60.0, 40.0)) { + Ok(ids) => { + self.flow.selected = ids.iter().copied().collect(); + self.flow.primary = ids.first().copied(); + self.spline.set_target_node(&self.comp, self.flow.primary); + self.invalidate_node(None); + let n = ids.len(); + self.set_notice(format!("Pasted {n} node{}", if n == 1 { "" } else { "s" })); + } + Err(e) => self.set_notice(format!("Nothing pasted: {e}")), + } + } + fn begin_inline_rename(&mut self, id: NodeId) { if id.0 >= self.comp.nodes.len() { return; @@ -939,6 +967,7 @@ impl Studio { let mut req_open = false; let mut req_save = false; let mut req_save_as = false; + let mut req_exit_to_depth: Option = None; let mut commit_rename: Option<(NodeId, String)> = None; let mut cancel_rename = false; @@ -1022,6 +1051,47 @@ impl Studio { if studio_btn(ui, "flow-saveas-btn", "Save As", false).clicked { req_save_as = true; } + let scope_path = flow.scope_path(); + if !scope_path.is_empty() { + let crumb_sep = |ui: &mut ui::Ui, part: usize| { + let ink = ui.theme.text_dim; + ui.leaf( + ("flow-crumb-sep", part), + ui::Spec { + size: [ui::fit(), ui::px(22.0)], + text: Some(">"), + font_size: Some(11.0), + color: Some(ink), + pad: [2.0, 0.0], + center: true, + ..ui::Spec::default() + }, + ); + }; + if studio_btn(ui, "flow-crumb-root", "Root", false).clicked { + req_exit_to_depth = Some(0); + } + for (depth, &group) in scope_path.iter().enumerate() { + crumb_sep(ui, depth); + let current = depth + 1 == scope_path.len(); + let crumb = studio_btn(ui, ("flow-crumb", depth), &comp.node(group).name, current); + if crumb.clicked && !current { + req_exit_to_depth = Some(depth + 1); + } + } + crumb_sep(ui, scope_path.len()); + ui.leaf( + "flow-crumb-hint", + ui::Spec { + size: [ui::fit(), ui::px(22.0)], + text: Some("Esc: back"), + font_size: Some(10.5), + color: Some(ui.theme.text_dim), + center: true, + ..ui::Spec::default() + }, + ); + } if let Some(rn_id) = *renaming_node { let rn_field_id = flow_pane_id().child(("rename-field", rn_id.0)); let rn_sig = ui::text_field( @@ -1119,6 +1189,11 @@ impl Studio { if req_open_add_tool { self.add_tool.open(); } + if let Some(depth) = req_exit_to_depth + && self.flow.exit_to_depth(&self.comp, depth) + { + self.spline.set_target_node(&self.comp, self.flow.primary); + } if req_undo { self.undo(); } @@ -1250,6 +1325,11 @@ impl Studio { FlowAction::StatusNotice(msg) => { self.set_notice(msg); } + FlowAction::CopyNodes(ids) => self.copy_nodes(&ids), + FlowAction::PasteNodes => self.paste_nodes(), + FlowAction::ScopeChanged => { + self.spline.set_target_node(&self.comp, self.flow.primary); + } } } } diff --git a/crates/flow/src/lib.rs b/crates/flow/src/lib.rs index 9b51f1d4fd586e771fdb1b27e6874b3284ad8147..cca1d33894c144a27e2739f861f025839fce202a 100644 --- a/crates/flow/src/lib.rs +++ b/crates/flow/src/lib.rs @@ -4,17 +4,27 @@ //! - Crisp straight lines by default (clean in any build orientation: L->R, T->B, B->T, diagonal) //! - Day-1 Blender `G`/`R`/`S` modal transforms + `X`/`Y` axis locks //! - `1`/`2` multi-viewer routing, `Cmd+F` / Numpad `.` fit-to-view, `P` bypass, drag-onto-wire insert. +//! - `Cmd+C` / `Cmd+V` node clipboard requests, double-click into Macro/Group subgraphs, `Esc` back out. + +mod scope; use draw::{Glyphs, PathStyle, Primitive}; use model::{Comp, CompHistory, NodeId, PortRole, default_main_input_port, is_supported_tool}; +use scope::Scope; +pub use scope::group_children; use std::collections::{HashMap, HashSet}; use std::sync::Arc; +use std::time::{Duration, Instant}; use winit::event::{ElementState, MouseButton}; use winit::keyboard::{Key, KeyCode, ModifiersState, NamedKey, PhysicalKey}; // Exact 1:1 match to Fusion's 110×33 flow grid cells (leaving crisp 26px X / 12px Y gaps for □──▶ wires). const NODE_W: f32 = 84.0; const NODE_H: f32 = 21.0; +const DOUBLE_CLICK: Duration = Duration::from_millis(400); + +const 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"; +const HUD_GROUP: &str = "Group contents are read-only Dbl-click nested group: Enter Cmd+C: Copy 1/2: Viewer F: Fit Esc: Back"; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum TransformMode { @@ -98,6 +108,12 @@ pub enum FlowAction { RequestRename(NodeId), /// Transient feedback message (e.g., cycle rejected). StatusNotice(String), + /// `Cmd+C`: serialize these nodes to the system clipboard. + CopyNodes(Vec), + /// `Cmd+V`: paste the system clipboard at the root graph. + PasteNodes, + /// A Macro/Group was entered or left; selection was reset to the new level. + ScopeChanged, } #[derive(Clone, Debug)] @@ -159,6 +175,8 @@ pub struct FlowView { panning: Option<([f32; 2], [f32; 2])>, lmb_drag_node: Option<(NodeId, [f32; 2], bool)>, pointer_local: [f32; 2], + scope: Scope, + last_click: Option<(Instant, NodeId)>, label_cache: HashMap, badge_cache: HashMap, fitted_once: bool, @@ -182,6 +200,8 @@ impl FlowView { panning: None, lmb_drag_node: None, pointer_local: [0.0, 0.0], + scope: Scope::default(), + last_click: None, label_cache: HashMap::new(), badge_cache: HashMap::new(), fitted_once: false, @@ -207,16 +227,63 @@ impl FlowView { self.box_select = None; self.panning = None; self.lmb_drag_node = None; + self.last_click = None; + self.scope = Scope::default(); self.label_cache.clear(); self.fitted_once = false; self.fit_comp(comp); } + /// Groups entered from the root, outermost first; empty at the root graph. + pub fn scope_path(&self) -> &[NodeId] { + self.scope.path() + } + + /// Shows the inside of Macro/Group `id`, which must be visible at the current level. + pub fn enter_group(&mut self, comp: &Comp, id: NodeId) -> bool { + if !self.scope.enter(comp, id) { + return false; + } + self.scope_switched(comp, None); + true + } + + /// Keeps the outermost `depth` groups (`0` = root) and selects the group just left. + pub fn exit_to_depth(&mut self, comp: &Comp, depth: usize) -> bool { + let Some(left) = self.scope.truncate(comp, depth) else { + return false; + }; + self.scope_switched(comp, Some(left)); + true + } + + /// Leaves the innermost group. + pub fn exit_group(&mut self, comp: &Comp) -> bool { + self.scope.path().len().checked_sub(1).is_some_and(|d| self.exit_to_depth(comp, d)) + } + + fn scope_switched(&mut self, comp: &Comp, select: Option) { + self.selected.clear(); + self.selected.extend(select); + self.primary = select; + self.hovered_node = None; + self.hovered_wire = None; + self.modal = None; + self.wire_drag = None; + self.box_select = None; + self.lmb_drag_node = None; + self.last_click = None; + self.fit_comp(comp); + } + /// Removes any stale `NodeId`s from selection/viewed_nodes after undo/redo or deletion. pub fn sanitize_ids(&mut self, comp: &Comp) { let len = comp.nodes.len(); - self.selected.retain(|id| id.0 < len && !comp.nodes[id.0].internal); - if self.primary.is_some_and(|id| id.0 >= len || comp.nodes[id.0].internal) { + if self.scope.refresh(comp) { + self.fitted_once = false; + } + self.selected.retain(|id| id.0 < len && self.scope.shows(comp.node(*id))); + if self.primary.is_some_and(|id| id.0 >= len || !self.scope.shows(comp.node(id))) { self.primary = self.selected.iter().copied().next(); } for slot in &mut self.viewed_nodes { @@ -231,6 +298,7 @@ impl FlowView { self.modal = None; self.wire_drag = None; self.lmb_drag_node = None; + self.last_click = None; } /// Computes a clean world-space spawn position for a newly added node. @@ -251,13 +319,13 @@ impl FlowView { let ids: Vec = if !self.selected.is_empty() { self.selected.iter().copied().collect() } else { - comp.nodes.iter().filter(|n| !n.internal).map(|n| n.id).collect() + self.scope.visible(comp) }; self.fit_ids(comp, ids); } pub fn fit_comp(&mut self, comp: &Comp) { - let ids: Vec = comp.nodes.iter().filter(|n| !n.internal).map(|n| n.id).collect(); + let ids = self.scope.visible(comp); self.fit_ids(comp, ids); } @@ -339,7 +407,7 @@ impl FlowView { let mut sx = 0.0_f32; let mut sy = 0.0_f32; let mut count = 0; - for other in &comp.nodes { + for other in comp.nodes.iter().filter(|n| self.scope.shows(n)) { for binding in other.inputs.values() { if binding.source_op.as_deref() == Some(name.as_str()) { let dx = other.pos[0] - sp[0]; @@ -360,7 +428,7 @@ impl FlowView { fn hit_node(&self, comp: &Comp, local: [f32; 2]) -> Option { for n in comp.nodes.iter().rev() { - if n.internal { continue; } + if !self.scope.shows(n) { continue; } let r = self.node_rect_local(n.pos); if local[0] >= r[0] && local[0] <= r[2] && local[1] >= r[1] && local[1] <= r[3] { return Some(n.id); @@ -371,7 +439,7 @@ impl FlowView { fn hit_output_port(&self, comp: &Comp, local: [f32; 2]) -> Option { for n in comp.nodes.iter().rev() { - if n.internal { continue; } + if !self.scope.shows(n) { continue; } let r = self.node_rect_local(n.pos); let edge = self.node_output_edge(comp, n.id); let nrm = edge.normal(); @@ -388,7 +456,7 @@ impl FlowView { fn hit_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, &'static str)> { for n in comp.nodes.iter().rev() { - if n.internal { continue; } + if !self.scope.shows(n) { continue; } let r = self.node_rect_local(n.pos); 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 { // Pick Background/Foreground/Mask cleanly based on approach edge for Merge/Displace! @@ -417,10 +485,10 @@ impl FlowView { fn hit_connected_input_port(&self, comp: &Comp, local: [f32; 2]) -> Option<(NodeId, String, NodeId)> { let hit_r2 = 10.5_f32 * 10.5_f32; for dst in comp.nodes.iter().rev() { - if dst.internal { continue; } + if !self.scope.shows(dst) { continue; } for (port, binding) in &dst.inputs { let Some(src_name) = &binding.source_op else { continue }; - let Some(src_id) = comp.find_node(src_name) else { continue }; + let Some(src_id) = self.scope.resolve(comp, src_name) else { continue }; let role = PortRole::from_input_name(port); let (_a, _ae, b, be) = self.wire_endpoints(comp, src_id, dst.id, role); let bn = be.normal(); @@ -437,13 +505,13 @@ impl FlowView { fn hit_wire(&self, comp: &Comp, local: [f32; 2], ignore_node: Option) -> Option { let mut best: Option<(f32, WireRef)> = None; - for dst in &comp.nodes { + for dst in comp.nodes.iter().filter(|n| self.scope.shows(n)) { if Some(dst.id) == ignore_node { continue; } for (port, binding) in &dst.inputs { let Some(src_name) = &binding.source_op else { continue }; - let Some(src_id) = comp.find_node(src_name) else { continue }; + let Some(src_id) = self.scope.resolve(comp, src_name) else { continue }; if Some(src_id) == ignore_node { continue; } @@ -618,10 +686,15 @@ impl FlowView { let cmd = kmod.super_key() || kmod.control_key(); match key { Key::Named(NamedKey::Escape) => { - if self.modal.is_some() { - self.cancel_modal(comp, history); + if self.modal.is_some() || self.wire_drag.is_some() { + if self.modal.is_some() { + self.cancel_modal(comp, history); + } + self.wire_drag = None; + } else if self.exit_group(comp) { + actions.push(FlowAction::SelectionChanged(self.primary)); + actions.push(FlowAction::ScopeChanged); } - self.wire_drag = None; } Key::Named(NamedKey::Enter) => { if self.modal.is_some() { @@ -629,7 +702,9 @@ impl FlowView { } } Key::Named(NamedKey::Delete) | Key::Named(NamedKey::Backspace) => { - if !self.selected.is_empty() { + if !self.scope.is_root() { + read_only_notice(actions); + } else if !self.selected.is_empty() { let ids: Vec = self.selected.iter().copied().collect(); history.push_snapshot(comp, "Delete Nodes"); let deleted = comp.delete_nodes(&ids); @@ -648,7 +723,9 @@ impl FlowView { } } Key::Named(NamedKey::F2) => { - if let Some(id) = self.primary { + if !self.scope.is_root() { + read_only_notice(actions); + } else if let Some(id) = self.primary { actions.push(FlowAction::RequestRename(id)); } } @@ -657,6 +734,15 @@ impl FlowView { self.viewed_nodes = [None, None]; actions.push(FlowAction::ClearViewers); } + "c" if cmd && !kmod.shift_key() => { + if !self.selected.is_empty() { + let mut ids: Vec = self.selected.iter().copied().collect(); + ids.sort_unstable_by_key(|id| id.0); + actions.push(FlowAction::CopyNodes(ids)); + } + } + "v" if cmd && !kmod.shift_key() => actions.push(FlowAction::PasteNodes), + "d" if cmd && !kmod.shift_key() && !self.scope.is_root() => read_only_notice(actions), "d" if cmd && !kmod.shift_key() => { if !self.selected.is_empty() { let ids: Vec = self.selected.iter().copied().collect(); @@ -681,12 +767,15 @@ impl FlowView { "f" if kmod.super_key() => self.fit_all(comp), "f" if !kmod.super_key() => self.fit_all(comp), "." if !kmod.super_key() => self.fit_all(comp), + "g" if !cmd && self.modal.is_none() && !self.scope.is_root() => read_only_notice(actions), "g" if !cmd && self.modal.is_none() => { self.begin_modal(comp, history, TransformMode::Grab); } + "r" if !cmd && self.modal.is_none() && !self.scope.is_root() => read_only_notice(actions), "r" if !cmd && self.modal.is_none() => { self.begin_modal(comp, history, TransformMode::Rotate); } + "s" if !cmd && self.modal.is_none() && !self.scope.is_root() => read_only_notice(actions), "s" if !cmd && self.modal.is_none() => { self.begin_modal(comp, history, TransformMode::Scale); } @@ -703,7 +792,7 @@ impl FlowView { self.apply_modal(comp, kmod.shift_key()); } "a" if !kmod.super_key() => { - let visible: Vec = comp.nodes.iter().filter(|n| !n.internal).map(|n| n.id).collect(); + let visible = self.scope.visible(comp); if self.selected.len() == visible.len() { self.selected.clear(); self.primary = None; @@ -725,6 +814,7 @@ impl FlowView { actions.push(FlowAction::ViewNode(1, id)); } } + "p" if !kmod.super_key() && !self.scope.is_root() => read_only_notice(actions), "p" if !kmod.super_key() => { if !self.selected.is_empty() { let ids: Vec = self.selected.iter().copied().collect(); @@ -797,7 +887,7 @@ impl FlowView { }; } } - ui::Event::Button { button, pressed, .. } => { + ui::Event::Button { button, pressed, at } => { if button == MouseButton::Middle || (button == MouseButton::Left && modifiers.alt_key()) { if pressed { self.panning = Some((self.pointer_local, self.pan)); @@ -811,7 +901,9 @@ impl FlowView { self.wire_drag = None; } else if pressed { // Right-click a hovered wire or connected input port to disconnect it! - if let Some(w) = self.hit_wire(comp, self.pointer_local, None) { + if !self.scope.is_root() { + read_only_notice(&mut actions); + } else if let Some(w) = self.hit_wire(comp, self.pointer_local, None) { history.push_snapshot(comp, "Disconnect"); if comp.disconnect(w.dst, &w.port) { self.hovered_wire = None; @@ -828,14 +920,14 @@ impl FlowView { if pressed { if self.modal.is_some() { self.confirm_modal(comp, history, &mut actions); - } else if let Some(src) = self.hit_output_port(comp, self.pointer_local) { + } else if let Some(src) = self.hit_output_port(comp, self.pointer_local).filter(|_| self.scope.is_root()) { self.wire_drag = Some(WireDrag { src, cursor_local: self.pointer_local, target: None, detached_from: None, }); - } else if let Some((dst, port, src)) = self.hit_connected_input_port(comp, self.pointer_local) { + } else if let Some((dst, port, src)) = self.hit_connected_input_port(comp, self.pointer_local).filter(|_| self.scope.is_root()) { // Dragging an existing input port detaches it so user can drop to disconnect or rewire! history.push_snapshot(comp, "Disconnect"); comp.disconnect(dst, &port); @@ -847,6 +939,13 @@ impl FlowView { detached_from: Some((dst, port)), }); } else if let Some(nid) = self.hit_node(comp, self.pointer_local) { + let double = self.last_click.is_some_and(|(t, prev)| prev == nid && at.duration_since(t) <= DOUBLE_CLICK); + self.last_click = Some((at, nid)); + if double && !modifiers.shift_key() && self.enter_group(comp, nid) { + actions.push(FlowAction::SelectionChanged(None)); + actions.push(FlowAction::ScopeChanged); + return actions; + } if modifiers.shift_key() { if !self.selected.remove(&nid) { self.selected.insert(nid); @@ -862,7 +961,9 @@ impl FlowView { self.primary = Some(nid); } actions.push(FlowAction::SelectionChanged(self.primary)); - self.lmb_drag_node = Some((nid, self.pointer_local, false)); + if self.scope.is_root() { + self.lmb_drag_node = Some((nid, self.pointer_local, false)); + } } else { if !modifiers.shift_key() { self.selected.clear(); @@ -913,8 +1014,7 @@ impl FlowView { let y0 = bs.start_local[1].min(bs.cur_local[1]); let y1 = bs.start_local[1].max(bs.cur_local[1]); if (x1 - x0) > 4.0 || (y1 - y0) > 4.0 { - for n in &comp.nodes { - if n.internal { continue; } + for n in comp.nodes.iter().filter(|n| self.scope.shows(n)) { let c = self.world_to_local(n.pos); if c[0] >= x0 && c[0] <= x1 && c[1] >= y0 && c[1] <= y1 { self.selected.insert(n.id); @@ -1005,7 +1105,8 @@ impl FlowView { .entry("cycle!".to_owned()) .or_insert_with(|| make_layout("cycle!", &tiny_font)); for key in [ - "Shift+Space: Add Tool G/R/S: Transform Shift+Drag: Splice Del: Delete Cmd+D: Dup F2: Rename Ctrl+P: Bypass 1/2: Viewer", + HUD_ROOT, + HUD_GROUP, "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis, Shift: Splice]", "ROTATE [LMB/Enter confirm, RMB/Esc cancel]", "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]", @@ -1066,8 +1167,7 @@ impl FlowView { let out_gap = if large_ports { 2.2 } else { 1.5 }; let port_outline = [0.04, 0.04, 0.06, 0.92]; - for dst in &comp.nodes { - if dst.internal { continue; } + for dst in comp.nodes.iter().filter(|n| self.scope.shows(n)) { // Track used edges on `dst` so multiple inputs on the same edge spread cleanly instead of overlapping let mut used_edges: HashMap = HashMap::new(); let mut sorted_ports: Vec<(&String, &model::InputBinding)> = dst.inputs.iter().collect(); @@ -1080,7 +1180,7 @@ impl FlowView { }); for (port, binding) in sorted_ports { let Some(src_name) = &binding.source_op else { continue }; - let Some(src_id) = comp.find_node(src_name) else { continue }; + let Some(src_id) = self.scope.resolve(comp, src_name) else { continue }; let role = PortRole::from_input_name(port); let (a, ae, mut b, mut be) = self.wire_endpoints(comp, src_id, dst.id, role); let ekey = |e: Edge| match e { Edge::Left => 0u8, Edge::Right => 1, Edge::Top => 2, Edge::Bottom => 3 }; @@ -1212,8 +1312,7 @@ impl FlowView { } // 4. Sleek Thin Fusion-Style Node Bars (color line along BOTTOM!) - for n in &comp.nodes { - if n.internal { continue; } + for n in comp.nodes.iter().filter(|n| self.scope.shows(n)) { let r = self.node_rect_local(n.pos); if r[2] < -20.0 || r[0] > w + 20.0 || r[3] < -20.0 || r[1] > h + 20.0 { continue; @@ -1394,7 +1493,8 @@ impl FlowView { Some(TransformMode::Grab) => "GRAB [LMB/Enter confirm, RMB/Esc cancel, X/Y axis, Shift: Splice]", Some(TransformMode::Rotate) => "ROTATE [LMB/Enter confirm, RMB/Esc cancel]", Some(TransformMode::Scale) => "SCALE [LMB/Enter confirm, RMB/Esc cancel, X/Y axis]", - 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", + None if !self.scope.is_root() => HUD_GROUP, + None => HUD_ROOT, }; if let Some(l) = self.badge_cache.get(hud_key) { let pill_h = 20.0; @@ -1416,6 +1516,10 @@ impl FlowView { } } +fn read_only_notice(actions: &mut Vec) { + actions.push(FlowAction::StatusNotice("Group contents are read-only; press Esc to leave the group".to_owned())); +} + /// Static SVG triangles pointing INTO the node edge (`origin` sits flush on the node border). fn input_arrow_svg(edge: Edge, large: bool) -> &'static str { match (edge, large) { @@ -1605,4 +1709,224 @@ mod tests { assert!(p_eff[0] > comp.node(bg).pos[0]); assert!(p_gen[1] < comp.node(bg).pos[1]); } + + const GROUP_COMP: &str = r#"Composition { + Tools = ordered() { + BG1 = Background { ViewInfo = OperatorInfo { Pos = { 0, 0 } }, }, + Outer = GroupOperator { + Outputs = { Output1 = InstanceOutput { SourceOp = "Mid", Source = "Output" }, }, + ViewInfo = GroupInfo { Pos = { 200, 0 } }, + Tools = ordered() { + A = Blur { ViewInfo = OperatorInfo { Pos = { 0, 100 } }, }, + ASpline = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, }, + Mid = Merge { + Inputs = { Background = Input { SourceOp = "A", Source = "Output" }, }, + ViewInfo = OperatorInfo { Pos = { 110, 100 } }, + }, + Inner = GroupOperator { + ViewInfo = GroupInfo { Pos = { 220, 100 } }, + Tools = ordered() { + Deep = Blur { ViewInfo = OperatorInfo { Pos = { 0, 50 } }, }, + }, + }, + }, + }, + A = Background { ViewInfo = OperatorInfo { Pos = { 400, 0 } }, }, + }, + }"#; + + fn group_flow() -> (Comp, FlowView) { + let comp = Comp::from_fusion_str(GROUP_COMP).expect("parse group comp"); + let theme = ui::Theme::new(&theme::KNIFE, true); + let mut flow = FlowView::new(&theme); + flow.size = [800.0, 600.0]; + flow.reset_for_comp(&comp); + flow.pan = [0.0, 0.0]; + flow.zoom = 1.0; + (comp, flow) + } + + fn id(comp: &Comp, name: &str) -> NodeId { + comp.find_node(name).unwrap() + } + + fn press(flow: &mut FlowView, comp: &mut Comp, history: &mut CompHistory, at: Instant, node: NodeId) -> Vec { + let local = flow.world_to_local(comp.node(node).pos); + flow.input( + comp, + history, + ui::Event::Button { button: MouseButton::Left, pressed: true, at }, + [0.0, 0.0, 800.0, 600.0], + local, + ModifiersState::empty(), + ) + } + + fn key(flow: &mut FlowView, comp: &mut Comp, history: &mut CompHistory, key: Key, modifiers: ModifiersState) -> Vec { + flow.input( + comp, + history, + ui::Event::Key { key, text: None, modifiers }, + [0.0, 0.0, 800.0, 600.0], + [0.0, 0.0], + modifiers, + ) + } + + #[test] + fn group_children_are_direct_tools_only() { + let (comp, _) = group_flow(); + let names = |g: &str| -> Vec<&str> { + group_children(&comp, id(&comp, g)).into_iter().map(|c| comp.node(c).name.as_str()).collect() + }; + assert_eq!(names("Outer"), ["A", "Mid", "Inner"]); + assert_eq!(names("Inner"), ["Deep"]); + assert!(group_children(&comp, id(&comp, "BG1")).is_empty()); + } + + #[test] + fn enter_and_exit_group_filter_visible_nodes() { + let (comp, mut flow) = group_flow(); + let (bg, outer, inner) = (id(&comp, "BG1"), id(&comp, "Outer"), id(&comp, "Inner")); + let (mid, deep) = (id(&comp, "Mid"), id(&comp, "Deep")); + flow.selected.insert(bg); + flow.primary = Some(bg); + + // Root shows only top-level tools; internal tools are not enterable from the root. + assert_eq!(flow.hit_node(&comp, flow.world_to_local(comp.node(bg).pos)), Some(bg)); + assert_eq!(flow.hit_node(&comp, flow.world_to_local(comp.node(mid).pos)), None); + assert!(!flow.enter_group(&comp, mid)); + assert!(!flow.enter_group(&comp, bg)); + assert!(flow.scope_path().is_empty()); + + assert!(flow.enter_group(&comp, outer)); + assert_eq!(flow.scope_path(), [outer]); + assert!(flow.selected.is_empty() && flow.primary.is_none()); + assert_eq!(flow.hit_node(&comp, flow.world_to_local(comp.node(mid).pos)), Some(mid)); + assert_eq!(flow.hit_node(&comp, flow.world_to_local(comp.node(bg).pos)), None); + assert_eq!(flow.hit_node(&comp, flow.world_to_local(comp.node(deep).pos)), None); + + // Nested group, then back out one level at a time; leaving selects the group left. + assert!(flow.enter_group(&comp, inner)); + assert_eq!(flow.scope_path(), [outer, inner]); + assert_eq!(flow.hit_node(&comp, flow.world_to_local(comp.node(deep).pos)), Some(deep)); + assert!(flow.exit_group(&comp)); + assert_eq!(flow.scope_path(), [outer]); + assert_eq!(flow.primary, Some(inner)); + assert!(flow.exit_to_depth(&comp, 0)); + assert!(flow.scope_path().is_empty()); + assert_eq!(flow.primary, Some(outer)); + assert_eq!(flow.selected, HashSet::from([outer])); + assert!(!flow.exit_group(&comp)); + } + + #[test] + fn wires_resolve_within_the_shown_level() { + let (comp, mut flow) = group_flow(); + let outer = id(&comp, "Outer"); + let (inner_a, root_a) = (comp.nodes.iter().find(|n| n.internal && n.name == "A").unwrap().id, id(&comp, "A")); + assert_ne!(inner_a, root_a); + assert_eq!(flow.scope.resolve(&comp, "A"), Some(root_a)); + flow.enter_group(&comp, outer); + assert_eq!(flow.scope.resolve(&comp, "A"), Some(inner_a)); + assert_eq!(flow.scope.resolve(&comp, "BG1"), None); + + // Mid's wire from A is hittable between the two inner nodes. + let mid = id(&comp, "Mid"); + let mid_pos = comp.node(mid).pos; + let a_pos = comp.node(inner_a).pos; + let midpoint = [(mid_pos[0] + a_pos[0]) * 0.5, (mid_pos[1] + a_pos[1]) * 0.5]; + let wire = flow.hit_wire(&comp, flow.world_to_local(midpoint), None).expect("wire"); + assert_eq!((wire.src, wire.dst), (inner_a, mid)); + } + + #[test] + fn double_click_enters_group_and_escape_leaves() { + let (mut comp, mut flow) = group_flow(); + let mut history = CompHistory::new(); + let (bg, outer) = (id(&comp, "BG1"), id(&comp, "Outer")); + let t0 = Instant::now(); + + // Double-clicking a plain tool, or two slow clicks on a group, never enters. + press(&mut flow, &mut comp, &mut history, t0, bg); + press(&mut flow, &mut comp, &mut history, t0 + Duration::from_millis(100), bg); + assert!(flow.scope_path().is_empty()); + press(&mut flow, &mut comp, &mut history, t0, outer); + press(&mut flow, &mut comp, &mut history, t0 + Duration::from_millis(900), outer); + assert!(flow.scope_path().is_empty()); + + let acts = press(&mut flow, &mut comp, &mut history, t0 + Duration::from_millis(1000), outer); + assert_eq!(flow.scope_path(), [outer]); + assert!(acts.iter().any(|a| matches!(a, FlowAction::ScopeChanged))); + + let acts = key(&mut flow, &mut comp, &mut history, Key::Named(NamedKey::Escape), ModifiersState::empty()); + assert!(flow.scope_path().is_empty()); + assert!(acts.iter().any(|a| matches!(a, FlowAction::ScopeChanged))); + assert_eq!(flow.primary, Some(outer)); + + // Escape at the root does nothing. + let acts = key(&mut flow, &mut comp, &mut history, Key::Named(NamedKey::Escape), ModifiersState::empty()); + assert!(acts.is_empty()); + } + + #[test] + fn group_view_is_read_only_but_copyable() { + let (mut comp, mut flow) = group_flow(); + let mut history = CompHistory::new(); + let (outer, mid) = (id(&comp, "Outer"), id(&comp, "Mid")); + flow.enter_group(&comp, outer); + flow.selected.insert(mid); + flow.primary = Some(mid); + let nodes = comp.nodes.len(); + + for k in ["g", "p"] { + let acts = key(&mut flow, &mut comp, &mut history, Key::Character(k.into()), ModifiersState::empty()); + assert!(matches!(acts.as_slice(), [FlowAction::StatusNotice(_)]), "{k}"); + } + let acts = key(&mut flow, &mut comp, &mut history, Key::Named(NamedKey::Delete), ModifiersState::empty()); + assert!(matches!(acts.as_slice(), [FlowAction::StatusNotice(_)])); + let acts = key(&mut flow, &mut comp, &mut history, Key::Character("d".into()), ModifiersState::SUPER); + assert!(matches!(acts.as_slice(), [FlowAction::StatusNotice(_)])); + assert_eq!(comp.nodes.len(), nodes); + assert!(!comp.node(mid).bypassed); + assert!(!history.can_undo()); + + let acts = key(&mut flow, &mut comp, &mut history, Key::Character("c".into()), ModifiersState::SUPER); + assert!(matches!(acts.as_slice(), [FlowAction::CopyNodes(ids)] if ids == &[mid])); + } + + #[test] + fn copy_and_paste_shortcuts_emit_requests() { + let (mut comp, mut flow) = group_flow(); + let mut history = CompHistory::new(); + let bg = id(&comp, "BG1"); + + let none = key(&mut flow, &mut comp, &mut history, Key::Character("c".into()), ModifiersState::SUPER); + assert!(none.is_empty(), "nothing selected, nothing to copy"); + + flow.selected.insert(bg); + flow.primary = Some(bg); + let acts = key(&mut flow, &mut comp, &mut history, Key::Character("c".into()), ModifiersState::SUPER); + assert!(matches!(acts.as_slice(), [FlowAction::CopyNodes(ids)] if ids == &[bg])); + let acts = key(&mut flow, &mut comp, &mut history, Key::Character("v".into()), ModifiersState::SUPER); + assert!(matches!(acts.as_slice(), [FlowAction::PasteNodes])); + // Plain `c` / `v` are not shortcuts. + let acts = key(&mut flow, &mut comp, &mut history, Key::Character("v".into()), ModifiersState::empty()); + assert!(acts.is_empty()); + } + + #[test] + fn sanitize_drops_scope_levels_that_no_longer_exist() { + let (comp, mut flow) = group_flow(); + let (outer, inner) = (id(&comp, "Outer"), id(&comp, "Inner")); + flow.enter_group(&comp, outer); + flow.enter_group(&comp, inner); + flow.sanitize_ids(&comp); + assert_eq!(flow.scope_path(), [outer, inner]); + + let flat = test_comp(); + flow.sanitize_ids(&flat); + assert!(flow.scope_path().is_empty()); + assert!(flow.selected.is_empty()); + } } diff --git a/crates/flow/src/scope.rs b/crates/flow/src/scope.rs new file mode 100644 index 0000000000000000000000000000000000000000..9193c05c87acc70128e9fe6d4b20df8a956e5f5f --- /dev/null +++ b/crates/flow/src/scope.rs @@ -0,0 +1,134 @@ +//! Which graph level the Flow canvas shows: the root, or the inside of a nested +//! `MacroOperator` / `GroupOperator`. +//! +//! `Comp` stores every unpacked tool in one flat `nodes` list; a group's children are the +//! internal tools parsed immediately before it, named by the group's raw `Tools` table. + +use model::{Comp, LuaKey, Node, NodeId}; +use std::collections::HashSet; + +/// Direct children of `owner` and the first `NodeId` of its whole (nested) block. +fn scan(comp: &Comp, owner: NodeId) -> (Vec, usize) { + let mut children = Vec::new(); + let mut cursor = owner.0; + if let Some(tools) = comp.nodes[owner.0].raw.get_table("Tools") { + for (key, value) in tools.entries.iter().rev() { + let (LuaKey::Str(name), Some(tool)) = (key, value.as_table()) else { + continue; + }; + let kind = tool.tag.as_deref().unwrap_or("Unknown"); + let child = (0..cursor).rev().find(|&i| { + let n = &comp.nodes[i]; + n.internal && n.name == *name && n.kind == kind + }); + // Modifiers (splines, paths) own no node. + let Some(child) = child else { continue }; + children.push(NodeId(child)); + cursor = scan(comp, NodeId(child)).1; + } + } + children.reverse(); + (children, cursor) +} + +/// Tools shown inside `group`, in `comp.nodes` order. +pub fn group_children(comp: &Comp, group: NodeId) -> Vec { + if group.0 >= comp.nodes.len() { + return Vec::new(); + } + scan(comp, group).0 +} + +pub fn is_group(node: &Node) -> bool { + matches!(node.kind.as_str(), "MacroOperator" | "GroupOperator") +} + +#[derive(Default)] +pub struct Scope { + path: Vec, + members: HashSet, +} + +impl Scope { + /// Groups entered from the root, outermost first. + pub fn path(&self) -> &[NodeId] { + &self.path + } + + pub fn is_root(&self) -> bool { + self.path.is_empty() + } + + pub fn shows(&self, node: &Node) -> bool { + if self.is_root() { + !node.internal + } else { + self.members.contains(&node.id) + } + } + + /// The shown node called `name`; `Comp::find_node` can pick a same-named tool of another level. + pub fn resolve(&self, comp: &Comp, name: &str) -> Option { + if self.is_root() { + comp.find_node(name).filter(|&id| !comp.node(id).internal) + } else { + self.members.iter().copied().find(|&id| comp.node(id).name == name) + } + } + + /// Every shown node, in `comp.nodes` order. + pub fn visible(&self, comp: &Comp) -> Vec { + comp.nodes.iter().filter(|n| self.shows(n)).map(|n| n.id).collect() + } + + /// Descends into `group` when it is a shown macro/group node. + pub fn enter(&mut self, comp: &Comp, group: NodeId) -> bool { + if !comp.nodes.get(group.0).is_some_and(|n| is_group(n) && self.shows(n)) { + return false; + } + self.path.push(group); + self.members = group_children(comp, group).into_iter().collect(); + true + } + + /// Keeps the outermost `depth` levels; returns the first group left. + pub fn truncate(&mut self, comp: &Comp, depth: usize) -> Option { + let left = self.path.get(depth).copied()?; + self.path.truncate(depth); + self.reload_members(comp); + Some(left) + } + + /// Drops levels that no longer exist after an undo, redo or delete, and refreshes membership. + /// Returns whether the path changed. + pub fn refresh(&mut self, comp: &Comp) -> bool { + let mut valid = 0; + let mut parent_children: Option> = None; + for &group in &self.path { + let ok = comp.nodes.get(group.0).is_some_and(|n| { + is_group(n) + && match &parent_children { + Some(siblings) => siblings.contains(&group), + None => !n.internal, + } + }); + if !ok { + break; + } + parent_children = Some(group_children(comp, group).into_iter().collect()); + valid += 1; + } + let changed = valid != self.path.len(); + self.path.truncate(valid); + self.reload_members(comp); + changed + } + + fn reload_members(&mut self, comp: &Comp) { + self.members = self + .path + .last() + .map(|&g| group_children(comp, g).into_iter().collect()) + .unwrap_or_default(); + } +} diff --git a/crates/model/src/edit.rs b/crates/model/src/edit.rs index d20a0d13fc8a512f8eb8ec6fc7626e1fd81e84ff..03f52acd662a61f313dc56d7d1fd05b77ba67827 100644 --- a/crates/model/src/edit.rs +++ b/crates/model/src/edit.rs @@ -4,7 +4,7 @@ use crate::comp::{ Comp, InputBinding, Node, NodeId, ParamValue, default_main_input_port, ensure_table_mut, param_value_to_lua, vec2_lua, }; -use crate::lua_value::{LuaKey, LuaTable, LuaValue, is_valid_lua_ident}; +use crate::lua_value::{LuaKey, LuaTable, LuaValue, is_valid_lua_ident, parse_lua}; use crate::spline::{BezierSpline, Keyframe, PolyPath}; use std::collections::{HashMap, HashSet, VecDeque}; @@ -23,6 +23,7 @@ impl Comp { || self.polyline_splines.contains_key(name) || self.text_cls.contains_key(name) || self.shakes.contains_key(name) + || self.expression_modifiers.contains_key(name) { return true; } @@ -294,6 +295,158 @@ impl Comp { deleted_names } + /// Serializes `ids` plus every modifier (spline, path, shake, ...) they reference into + /// Fusion's clipboard format: `{ Tools = ordered() { ... }, ActiveTool = "" }`. + /// References to unselected nodes are kept verbatim and dropped again on paste if missing. + pub fn export_fusion_clipboard(&self, ids: &[NodeId]) -> String { + let synced = self.sync_to_raw_ast(); + let root_tools = synced.get_table("Tools"); + let node_names: HashSet<&str> = self.nodes.iter().map(|n| n.name.as_str()).collect(); + + let mut picked: Vec<&Node> = Vec::new(); + for &id in ids { + if let Some(n) = self.nodes.get(id.0) { + if !picked.iter().any(|p| p.id == n.id) { + picked.push(n); + } + } + } + let mut tools = LuaTable { + tag: Some("ordered".to_owned()), + entries: Vec::new(), + }; + let mut refs: VecDeque = VecDeque::new(); + for n in &picked { + let raw = if n.internal { + &n.raw + } else { + root_tools.and_then(|t| t.get_table(&n.name)).unwrap_or(&n.raw) + }; + let mut found = HashSet::new(); + collect_source_ops_in_table(raw, &mut found); + let mut found: Vec = found.into_iter().collect(); + found.sort(); + refs.extend(found); + tools.set(LuaKey::Str(n.name.clone()), LuaValue::Table(raw.clone())); + } + while let Some(name) = refs.pop_front() { + if tools.get(&name).is_some() || node_names.contains(name.as_str()) { + continue; + } + let Some(modifier) = root_tools.and_then(|t| t.get_table(&name)) else { + continue; + }; + let mut found = HashSet::new(); + collect_source_ops_in_table(modifier, &mut found); + let mut found: Vec = found.into_iter().collect(); + found.sort(); + refs.extend(found); + tools.set(LuaKey::Str(name), LuaValue::Table(modifier.clone())); + } + + let mut doc = LuaTable::default(); + doc.set(LuaKey::Str("Tools".to_owned()), LuaValue::Table(tools)); + if let Some(first) = picked.first() { + doc.set( + LuaKey::Str("ActiveTool".to_owned()), + LuaValue::String(first.name.clone()), + ); + } + doc.to_fusion_string() + } + + /// Pastes Fusion clipboard Lua (`{ Tools = ordered() { ... } }` or a full `Composition`), + /// renaming colliding tools/modifiers (`Blur1` -> `Blur1_1`), rewiring references among the + /// pasted tools, dropping references to tools that exist nowhere, and shifting each top-level + /// tool's `ViewInfo.Pos` by `offset`. Returns the new top-level flow nodes; on `Err` the comp + /// is untouched. Prefer [`CompHistory::paste_fusion_clipboard`] for an undoable paste. + pub fn paste_fusion_clipboard( + &mut self, + lua_snippet: &str, + offset: (f32, f32), + ) -> Result, String> { + let parsed = parse_lua(lua_snippet).map_err(|e| format!("clipboard is not Fusion Lua: {e}"))?; + let mut tools = parsed + .as_table() + .and_then(|t| t.get_table("Tools")) + .filter(|t| !t.entries.is_empty()) + .cloned() + .ok_or_else(|| "clipboard has no Fusion tools".to_owned())?; + + let mut pasted_names = Vec::new(); + collect_tool_names(&tools, &mut pasted_names); + let pasted_set: HashSet<&str> = pasted_names.iter().map(String::as_str).collect(); + + drop_unknown_source_ops(&mut tools, &mut |name| { + pasted_set.contains(name) + || self.name_exists(name) + || self.nodes.iter().any(|n| n.name == name) + }); + + let mut reserved: HashSet = self.nodes.iter().map(|n| n.name.clone()).collect(); + let mut renames: HashMap = HashMap::new(); + for name in &pasted_names { + if renames.contains_key(name) { + continue; + } + let fresh = self.generate_unique_name_excluding(name, &reserved); + reserved.insert(fresh.clone()); + renames.insert(name.clone(), fresh); + } + rename_tools(&mut tools, &renames); + + let mut doc = LuaTable { + tag: Some("Composition".to_owned()), + entries: Vec::new(), + }; + doc.set(LuaKey::Str("Tools".to_owned()), LuaValue::Table(tools)); + let staged = Comp::from_fusion_str(&doc.to_fusion_string()) + .map_err(|e| format!("clipboard tools failed to parse: {e}"))?; + let Some(staged_tools) = doc.get_table("Tools") else { + return Err("clipboard has no Fusion tools".to_owned()); + }; + + let base = self.nodes.len(); + let shift = |id: NodeId| NodeId(base + id.0); + let mut created = Vec::new(); + let mut top_level: HashMap = HashMap::new(); + for mut node in staged.nodes { + node.id = shift(node.id); + node.macro_output = node.macro_output.map(shift); + if !node.internal { + node.pos = [node.pos[0] + offset.0, node.pos[1] + offset.1]; + set_view_info_pos(&mut node.raw, node.pos); + top_level.insert(node.name.clone(), node.raw.clone()); + created.push(node.id); + } + self.nodes.push(node); + } + for (name, id) in staged.node_by_name { + self.node_by_name.entry(name).or_insert(shift(id)); + } + self.splines.extend(staged.splines); + self.poly_paths.extend(staged.poly_paths); + self.gradient_modifiers.extend(staged.gradient_modifiers); + self.text_modifiers.extend(staged.text_modifiers); + self.text_splines.extend(staged.text_splines); + self.polyline_splines.extend(staged.polyline_splines); + self.text_cls.extend(staged.text_cls); + self.shakes.extend(staged.shakes); + self.expression_modifiers.extend(staged.expression_modifiers); + + if let Some(root) = self.raw_root.as_mut() { + let dest = ensure_table_mut(root, "Tools", Some("ordered")); + for (key, value) in &staged_tools.entries { + let LuaKey::Str(name) = key else { continue }; + let table = top_level.remove(name).map_or_else(|| value.clone(), LuaValue::Table); + dest.set(key.clone(), table); + } + } + + self.revision += 1; + Ok(created) + } + /// Duplicates the selected nodes at `pos + offset` with unique names. /// Preserves internal wires between duplicated nodes, keeps external wires intact, /// and clones owned `BezierSpline` / `PolyPath` modifiers with fresh unique names. @@ -1088,6 +1241,20 @@ impl CompHistory { true } + /// Undoable [`Comp::paste_fusion_clipboard`]: the whole paste is one undo step, and a failed + /// paste leaves both `comp` and the history untouched. + pub fn paste_fusion_clipboard( + &mut self, + comp: &mut Comp, + lua_snippet: &str, + offset: (f32, f32), + ) -> Result, String> { + self.begin_group(comp, "Paste"); + let pasted = comp.paste_fusion_clipboard(lua_snippet, offset); + self.commit_group(comp); + pasted + } + /// Undoes the most recent edit, restoring `comp` to the saved snapshot. /// Always advances `comp.revision` monotonically so downstream caches invalidate cleanly. 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 } } +/// Names of every tool in `tools`, including tools nested in `Tools` tables (macros/groups). +fn collect_tool_names(tools: &LuaTable, out: &mut Vec) { + for (key, value) in &tools.entries { + let (LuaKey::Str(name), Some(tool)) = (key, value.as_table()) else { + continue; + }; + out.push(name.clone()); + if let Some(inner) = tool.get_table("Tools") { + collect_tool_names(inner, out); + } + } +} + +/// Renames tool keys (recursively) and rewrites every reference to them: `SourceOp` values and +/// whole-word identifiers inside `Expression` strings. +fn rename_tools(tools: &mut LuaTable, renames: &HashMap) { + for (key, value) in &mut tools.entries { + let LuaKey::Str(name) = key else { continue }; + if let Some(new) = renames.get(name.as_str()) { + *name = new.clone(); + } + if let Some(tool) = value.as_table_mut() { + rewrite_references(tool, renames); + if let Some(inner) = tool.get_table_mut("Tools") { + rename_tools(inner, renames); + } + } + } +} + +fn rewrite_references(tbl: &mut LuaTable, renames: &HashMap) { + for (key, value) in &mut tbl.entries { + match (key, value) { + (LuaKey::Str(k), LuaValue::String(s)) if k == "SourceOp" => { + if let Some(new) = renames.get(s.as_str()) { + *s = new.clone(); + } + } + (LuaKey::Str(k), LuaValue::String(s)) if k == "Expression" => { + *s = rename_expression_idents(s, renames); + } + (_, LuaValue::Table(sub)) => rewrite_references(sub, renames), + _ => {} + } + } +} + +fn rename_expression_idents(expr: &str, renames: &HashMap) -> String { + let mut out = String::with_capacity(expr.len()); + let mut word = String::new(); + let flush = |word: &mut String, out: &mut String| { + out.push_str(renames.get(word.as_str()).map_or(word.as_str(), String::as_str)); + word.clear(); + }; + for ch in expr.chars() { + if ch.is_ascii_alphanumeric() || ch == '_' { + word.push(ch); + } else { + flush(&mut word, &mut out); + out.push(ch); + } + } + flush(&mut word, &mut out); + out +} + +/// Removes `SourceOp`/`Source` pairs whose target fails `exists`, so pasted tools never point at +/// missing operators. +fn drop_unknown_source_ops(tbl: &mut LuaTable, exists: &mut dyn FnMut(&str) -> bool) { + let dangling = tbl + .get_str("SourceOp") + .is_some_and(|name| !exists(name)); + if dangling { + tbl.remove(&LuaKey::Str("SourceOp".to_owned())); + tbl.remove(&LuaKey::Str("Source".to_owned())); + } + for (_, value) in &mut tbl.entries { + if let Some(sub) = value.as_table_mut() { + drop_unknown_source_ops(sub, exists); + } + } +} + fn set_view_info_pos(raw: &mut LuaTable, pos: [f32; 2]) { let vi = ensure_table_mut(raw, "ViewInfo", Some("OperatorInfo")); vi.set( @@ -1823,4 +2073,209 @@ mod tests { assert!(!history.can_undo()); assert!(!history.can_redo()); } + + const GROUP_SNIPPET: &str = r#"{ + Tools = ordered() { + Group1 = GroupOperator { + Inputs = { + Input1 = InstanceInput { SourceOp = "Inner1", Source = "Input", }, + }, + Outputs = { + Output1 = InstanceOutput { SourceOp = "Inner1", Source = "Output", }, + }, + ViewInfo = GroupInfo { Pos = { 10, 20 } }, + Tools = ordered() { + Inner1 = Blur { + Inputs = { + XBlurSize = Input { SourceOp = "Inner1Size", Source = "Value", }, + }, + ViewInfo = OperatorInfo { Pos = { 0, 0 } }, + }, + Inner1Size = BezierSpline { + KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, + }, + }, + }, + }, +}"#; + + #[test] + fn export_fusion_clipboard_includes_owned_modifiers_and_internal_wires() { + let comp = sample_comp(); + let bg = comp.find_node("BG1").unwrap(); + let bc = comp.find_node("BC1").unwrap(); + + let both = comp.export_fusion_clipboard(&[bg, bc]); + assert!(both.contains("Tools = ordered()"), "{both}"); + assert!(both.contains("ActiveTool = \"BG1\""), "{both}"); + let parsed = parse_lua(&both).expect("clipboard parses as Lua"); + let tools = parsed.as_table().unwrap().get_table("Tools").unwrap(); + let names: Vec<_> = tools + .entries + .iter() + .filter_map(|(k, _)| if let LuaKey::Str(s) = k { Some(s.as_str()) } else { None }) + .collect(); + assert_eq!(names, ["BG1", "BC1", "BC1Gain"]); + assert_eq!( + tools + .get_table("BC1") + .and_then(|t| t.get_table("Inputs")) + .and_then(|i| i.get_table("Input")) + .and_then(|i| i.get_str("SourceOp")), + Some("BG1") + ); + + // Selecting only BC1 keeps its owned spline and leaves the external BG1 reference. + let only_bc = comp.export_fusion_clipboard(&[bc, bc]); + assert!(only_bc.contains("BC1Gain = BezierSpline")); + assert!(!only_bc.contains("BG1 = Background")); + assert!(only_bc.contains("SourceOp = \"BG1\"")); + + // Splines created after load (not yet in `raw_root`) are exported too. + let mut comp = comp; + let sp = comp.set_keyframe(bg, "Width", 0.0, 1.0).unwrap(); + assert!(comp.export_fusion_clipboard(&[bg]).contains(&format!("{sp} = BezierSpline"))); + } + + #[test] + fn paste_dedups_names_and_remaps_internal_wires_and_splines() { + let mut comp = sample_comp(); + let bg = comp.find_node("BG1").unwrap(); + let bc = comp.find_node("BC1").unwrap(); + let snippet = comp.export_fusion_clipboard(&[bg, bc]); + let nodes_before = comp.nodes.len(); + + let ids = comp.paste_fusion_clipboard(&snippet, (60.0, 40.0)).expect("paste"); + assert_eq!(ids.len(), 2); + assert_eq!(comp.nodes.len(), nodes_before + 2); + let (pbg, pbc) = (comp.node(ids[0]), comp.node(ids[1])); + assert_eq!((pbg.name.as_str(), pbc.name.as_str()), ("BG1_1", "BC1_1")); + assert_eq!(pbg.pos, [160.0, 90.0]); + assert_eq!(pbc.pos, [360.0, 90.0]); + assert_eq!(pbc.connected_node("Input"), Some("BG1_1")); + assert_eq!(pbc.connected_node("Gain"), Some("BC1Gain_1")); + assert_eq!(comp.splines["BC1Gain_1"].keyframes.len(), 2); + assert_eq!(comp.splines["BC1Gain"].keyframes.len(), 2); + assert_eq!(comp.find_node("BC1_1"), Some(ids[1])); + assert_eq!(comp.node(bc).connected_node("Input"), Some("BG1")); + + // Pasting again keeps advancing the suffix instead of clobbering earlier pastes. + let again = comp.paste_fusion_clipboard(&snippet, (0.0, 0.0)).unwrap(); + assert_eq!(comp.node(again[0]).name, "BG1_2"); + assert_eq!(comp.node(again[1]).connected_node("Input"), Some("BG1_2")); + + // Everything survives a save/load roundtrip, including the cloned spline and offset. + let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("reload"); + let r_bc = reloaded.node(reloaded.find_node("BC1_1").unwrap()); + assert_eq!(r_bc.pos, [360.0, 90.0]); + assert_eq!(r_bc.connected_node("Input"), Some("BG1_1")); + assert!(reloaded.splines.contains_key("BC1Gain_1")); + } + + #[test] + fn paste_external_references_are_kept_when_present_and_dropped_when_missing() { + let mut comp = sample_comp(); + let bc = comp.find_node("BC1").unwrap(); + let snippet = comp.export_fusion_clipboard(&[bc]); + + let ids = comp.paste_fusion_clipboard(&snippet, (0.0, 0.0)).unwrap(); + assert_eq!(comp.node(ids[0]).connected_node("Input"), Some("BG1")); + + let mut empty = Comp::from_fusion_str("Composition { Tools = ordered() { } }").unwrap(); + let ids = empty.paste_fusion_clipboard(&snippet, (5.0, 5.0)).unwrap(); + let pasted = empty.node(ids[0]); + assert_eq!(pasted.name, "BC1"); + assert_eq!(pasted.connected_node("Input"), None); + assert_eq!(pasted.connected_node("Gain"), Some("BC1Gain")); + assert!(!empty.to_fusion_string().contains("BG1")); + } + + #[test] + fn paste_accepts_full_composition_and_rewrites_expressions() { + let mut comp = sample_comp(); + let snippet = r#"Composition { + Tools = ordered() { + BG1 = Background { Inputs = { Width = Input { Value = 64, } }, }, + T1 = Transform { + Inputs = { + Size = Input { Expression = "BG1.Width / 2 + BG10.Width", }, + Input = Input { SourceOp = "BG1", Source = "Output", }, + }, + }, + }, +}"#; + let ids = comp.paste_fusion_clipboard(snippet, (1.0, 2.0)).unwrap(); + let t1 = comp.node(ids[1]); + assert_eq!(comp.node(ids[0]).name, "BG1_1"); + assert_eq!(comp.node(ids[0]).pos, [1.0, 2.0]); + assert_eq!(t1.connected_node("Input"), Some("BG1_1")); + assert_eq!( + t1.inputs["Size"].expression.as_deref(), + Some("BG1_1.Width / 2 + BG10.Width") + ); + } + + #[test] + fn paste_group_renames_nested_tools_and_remaps_macro_output() { + let mut comp = sample_comp(); + let first = comp.paste_fusion_clipboard(GROUP_SNIPPET, (0.0, 0.0)).unwrap(); + let second = comp.paste_fusion_clipboard(GROUP_SNIPPET, (50.0, 0.0)).unwrap(); + let (g1, g2) = (comp.node(first[0]), comp.node(second[0])); + assert_eq!((g1.name.as_str(), g2.name.as_str()), ("Group1", "Group1_1")); + assert_eq!(g2.pos, [60.0, 20.0]); + + let inner = comp.node(g2.macro_output.expect("macro output")); + assert_eq!(inner.name, "Inner1_1"); + assert!(inner.internal); + assert_eq!(inner.connected_node("XBlurSize"), Some("Inner1Size_1")); + assert!(comp.splines.contains_key("Inner1Size_1")); + assert_eq!(comp.node(g1.macro_output.unwrap()).name, "Inner1"); + assert_eq!(comp.find_node("Group1_1"), Some(second[0])); + assert_eq!(comp.find_node("Inner1_1"), g2.macro_output); + } + + #[test] + fn paste_is_one_undo_step_and_redoable() { + let mut comp = sample_comp(); + let mut history = CompHistory::new(); + let bg = comp.find_node("BG1").unwrap(); + let bc = comp.find_node("BC1").unwrap(); + let snippet = comp.export_fusion_clipboard(&[bg, bc]); + let (nodes, splines) = (comp.nodes.len(), comp.splines.len()); + history.mark_saved(&comp); + + let ids = history + .paste_fusion_clipboard(&mut comp, &snippet, (60.0, 40.0)) + .unwrap(); + assert_eq!(ids.len(), 2); + assert_eq!(history.undo_len(), 1); + assert_eq!(history.undo_label(), Some("Paste")); + assert!(history.is_dirty(&comp)); + + assert!(history.undo(&mut comp)); + assert_eq!((comp.nodes.len(), comp.splines.len()), (nodes, splines)); + assert!(comp.find_node("BG1_1").is_none()); + assert!(!comp.to_fusion_string().contains("BG1_1")); + assert!(!history.can_undo()); + assert!(!history.is_dirty(&comp)); + + assert!(history.redo(&mut comp)); + assert_eq!((comp.nodes.len(), comp.splines.len()), (nodes + 2, splines + 1)); + let pasted = comp.find_node("BC1_1").unwrap(); + assert_eq!(comp.node(pasted).connected_node("Input"), Some("BG1_1")); + assert!(!history.can_redo()); + } + + #[test] + fn paste_rejects_garbage_without_touching_comp_or_history() { + let mut comp = sample_comp(); + let mut history = CompHistory::new(); + let (rev, nodes) = (comp.revision, comp.nodes.len()); + for bad in ["", "hello world", "{ Foo = 1 }", "{ Tools = ordered() { } }", "{ Tools = "] { + assert!(history.paste_fusion_clipboard(&mut comp, bad, (0.0, 0.0)).is_err(), "{bad:?}"); + } + assert_eq!((comp.revision, comp.nodes.len()), (rev, nodes)); + assert!(!history.can_undo()); + assert!(!history.in_group()); + } }