| 1 | use super::{ |
| 2 | EXPRESSION_FORMULA_INPUTS, collect_source_ops_in_table, sanitize_lua_ident, set_view_info_pos, |
| 3 | }; |
| 4 | use crate::comp::{Comp, Node, NodeId, ensure_table_mut, find_raw_tool}; |
| 5 | use crate::lua_value::{LuaKey, LuaTable, LuaValue, parse_lua}; |
| 6 | use std::collections::{HashMap, HashSet, VecDeque}; |
| 7 | |
| 8 | impl Comp { |
| 9 | pub fn export_fusion_clipboard(&self, ids: &[NodeId]) -> String { |
| 10 | let synced = self.sync_to_raw_ast(); |
| 11 | let root_tools = synced.get_table("Tools"); |
| 12 | let node_names: HashSet<&str> = self.nodes.iter().map(|n| n.name.as_str()).collect(); |
| 13 | |
| 14 | let mut picked: Vec<&Node> = Vec::new(); |
| 15 | for &id in ids { |
| 16 | if let Some(n) = self.nodes.get(id.0) { |
| 17 | if !picked.iter().any(|p| p.id == n.id) { |
| 18 | picked.push(n); |
| 19 | } |
| 20 | } |
| 21 | } |
| 22 | let mut tools = LuaTable { |
| 23 | tag: Some("ordered".to_owned()), |
| 24 | entries: Vec::new(), |
| 25 | }; |
| 26 | let mut refs: VecDeque<String> = VecDeque::new(); |
| 27 | for n in &picked { |
| 28 | let raw = root_tools.and_then(|t| find_raw_tool(t, &n.name)).unwrap_or(&n.raw); |
| 29 | let mut found = HashSet::new(); |
| 30 | collect_source_ops_in_table(raw, &mut found); |
| 31 | let mut found: Vec<String> = found.into_iter().collect(); |
| 32 | found.sort(); |
| 33 | refs.extend(found); |
| 34 | tools.set(LuaKey::Str(n.name.clone()), LuaValue::Table(raw.clone())); |
| 35 | } |
| 36 | while let Some(name) = refs.pop_front() { |
| 37 | if tools.get(&name).is_some() || node_names.contains(name.as_str()) { |
| 38 | continue; |
| 39 | } |
| 40 | // Modifiers already nested inside a copied group travel with it. |
| 41 | let nested_in_copy = tools |
| 42 | .entries |
| 43 | .iter() |
| 44 | .filter_map(|(_, v)| v.as_table()?.get_table("Tools")) |
| 45 | .any(|inner| find_raw_tool(inner, &name).is_some()); |
| 46 | let Some(modifier) = root_tools.and_then(|t| find_raw_tool(t, &name)).filter(|_| !nested_in_copy) |
| 47 | else { |
| 48 | continue; |
| 49 | }; |
| 50 | let mut found = HashSet::new(); |
| 51 | collect_source_ops_in_table(modifier, &mut found); |
| 52 | let mut found: Vec<String> = found.into_iter().collect(); |
| 53 | found.sort(); |
| 54 | refs.extend(found); |
| 55 | tools.set(LuaKey::Str(name), LuaValue::Table(modifier.clone())); |
| 56 | } |
| 57 | |
| 58 | let mut doc = LuaTable::default(); |
| 59 | doc.set(LuaKey::Str("Tools".to_owned()), LuaValue::Table(tools)); |
| 60 | if let Some(first) = picked.first() { |
| 61 | doc.set( |
| 62 | LuaKey::Str("ActiveTool".to_owned()), |
| 63 | LuaValue::String(first.name.clone()), |
| 64 | ); |
| 65 | } |
| 66 | doc.to_fusion_string() |
| 67 | } |
| 68 | |
| 69 | /// Pastes Fusion clipboard Lua (`{ Tools = ordered() { ... } }` or a full `Composition`), |
| 70 | /// renaming colliding tools/modifiers (`Blur1` -> `Blur1_1`), rewiring references among the |
| 71 | /// pasted tools, dropping references to tools that exist nowhere, and shifting each top-level |
| 72 | /// tool's `ViewInfo.Pos` by `offset`. Returns the new top-level flow nodes; on `Err` the comp |
| 73 | /// is untouched. Prefer [`CompHistory::paste_fusion_clipboard`] for an undoable paste. |
| 74 | pub fn paste_fusion_clipboard( |
| 75 | &mut self, |
| 76 | lua_snippet: &str, |
| 77 | offset: (f32, f32), |
| 78 | ) -> Result<Vec<NodeId>, String> { |
| 79 | let parsed = parse_lua(lua_snippet).map_err(|e| format!("clipboard is not Fusion Lua: {e}"))?; |
| 80 | let mut tools = parsed |
| 81 | .as_table() |
| 82 | .and_then(|t| t.get_table("Tools")) |
| 83 | .filter(|t| !t.entries.is_empty()) |
| 84 | .cloned() |
| 85 | .ok_or_else(|| "clipboard has no Fusion tools".to_owned())?; |
| 86 | |
| 87 | let mut pasted_names = Vec::new(); |
| 88 | collect_tool_names(&tools, &mut pasted_names); |
| 89 | let pasted_set: HashSet<&str> = pasted_names.iter().map(String::as_str).collect(); |
| 90 | |
| 91 | drop_unknown_source_ops(&mut tools, &mut |name| { |
| 92 | pasted_set.contains(name) || self.is_linkable_external(name) |
| 93 | }); |
| 94 | |
| 95 | let mut reserved: HashSet<String> = self.nodes.iter().map(|n| n.name.clone()).collect(); |
| 96 | let mut renames: HashMap<String, String> = HashMap::new(); |
| 97 | for name in &pasted_names { |
| 98 | if renames.contains_key(name) { |
| 99 | continue; |
| 100 | } |
| 101 | let fresh = self.generate_unique_name_excluding(name, &reserved); |
| 102 | reserved.insert(fresh.clone()); |
| 103 | renames.insert(name.clone(), fresh); |
| 104 | } |
| 105 | rename_tools(&mut tools, &renames); |
| 106 | |
| 107 | let mut doc = LuaTable { |
| 108 | tag: Some("Composition".to_owned()), |
| 109 | entries: Vec::new(), |
| 110 | }; |
| 111 | doc.set(LuaKey::Str("Tools".to_owned()), LuaValue::Table(tools)); |
| 112 | let staged = Comp::from_fusion_str(&doc.to_fusion_string()) |
| 113 | .map_err(|e| format!("clipboard tools failed to parse: {e}"))?; |
| 114 | let Some(staged_tools) = doc.get_table("Tools") else { |
| 115 | return Err("clipboard has no Fusion tools".to_owned()); |
| 116 | }; |
| 117 | |
| 118 | let base = self.nodes.len(); |
| 119 | let shift = |id: NodeId| NodeId(base + id.0); |
| 120 | let mut created = Vec::new(); |
| 121 | let mut top_level: HashMap<String, LuaTable> = HashMap::new(); |
| 122 | for mut node in staged.nodes { |
| 123 | node.id = shift(node.id); |
| 124 | node.macro_output = node.macro_output.map(shift); |
| 125 | if !node.internal { |
| 126 | node.pos = [node.pos[0] + offset.0, node.pos[1] + offset.1]; |
| 127 | set_view_info_pos(&mut node.raw, node.pos); |
| 128 | top_level.insert(node.name.clone(), node.raw.clone()); |
| 129 | created.push(node.id); |
| 130 | } |
| 131 | self.nodes.push(node); |
| 132 | } |
| 133 | for (name, id) in staged.node_by_name { |
| 134 | self.node_by_name.entry(name).or_insert(shift(id)); |
| 135 | } |
| 136 | self.splines.extend(staged.splines); |
| 137 | self.poly_paths.extend(staged.poly_paths); |
| 138 | self.gradient_modifiers.extend(staged.gradient_modifiers); |
| 139 | self.text_modifiers.extend(staged.text_modifiers); |
| 140 | self.text_splines.extend(staged.text_splines); |
| 141 | self.polyline_splines.extend(staged.polyline_splines); |
| 142 | self.text_cls.extend(staged.text_cls); |
| 143 | self.shakes.extend(staged.shakes); |
| 144 | self.expression_modifiers.extend(staged.expression_modifiers); |
| 145 | |
| 146 | if let Some(root) = self.raw_root.as_mut() { |
| 147 | let dest = ensure_table_mut(root, "Tools", Some("ordered")); |
| 148 | for (key, value) in &staged_tools.entries { |
| 149 | let LuaKey::Str(name) = key else { continue }; |
| 150 | let table = top_level.remove(name).map_or_else(|| value.clone(), LuaValue::Table); |
| 151 | dest.set(key.clone(), table); |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | self.revision += 1; |
| 156 | Ok(created) |
| 157 | } |
| 158 | |
| 159 | /// Duplicates the selected nodes at `pos + offset` with unique names, as a copy + paste: |
| 160 | /// wires between duplicated nodes are preserved, wires to other nodes stay intact, and owned |
| 161 | /// modifiers and group contents are cloned. Returns the new top-level nodes. |
| 162 | pub fn duplicate_nodes(&mut self, ids: &[NodeId], offset: [f32; 2]) -> Vec<NodeId> { |
| 163 | let snippet = self.export_fusion_clipboard(ids); |
| 164 | self.paste_fusion_clipboard(&snippet, (offset[0], offset[1])).unwrap_or_default() |
| 165 | } |
| 166 | |
| 167 | fn generate_unique_name_excluding(&self, hint: &str, reserved: &HashSet<String>) -> String { |
| 168 | let base = sanitize_lua_ident(hint); |
| 169 | if !self.name_exists(&base) && !reserved.contains(&base) { |
| 170 | return base; |
| 171 | } |
| 172 | let mut idx = 1usize; |
| 173 | loop { |
| 174 | let candidate = format!("{base}_{idx}"); |
| 175 | if !self.name_exists(&candidate) && !reserved.contains(&candidate) { |
| 176 | return candidate; |
| 177 | } |
| 178 | idx += 1; |
| 179 | } |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | pub(super) fn collect_tool_names(tools: &LuaTable, out: &mut Vec<String>) { |
| 184 | for (key, value) in &tools.entries { |
| 185 | let (LuaKey::Str(name), Some(tool)) = (key, value.as_table()) else { |
| 186 | continue; |
| 187 | }; |
| 188 | out.push(name.clone()); |
| 189 | if let Some(inner) = tool.get_table("Tools") { |
| 190 | collect_tool_names(inner, out); |
| 191 | } |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | /// Renames tool keys (recursively) and rewrites every reference to them: `SourceOp` values and |
| 196 | /// whole-word identifiers inside `Expression` strings. |
| 197 | pub(super) fn rename_tools(tools: &mut LuaTable, renames: &HashMap<String, String>) { |
| 198 | for (key, value) in &mut tools.entries { |
| 199 | let LuaKey::Str(name) = key else { continue }; |
| 200 | if let Some(new) = renames.get(name.as_str()) { |
| 201 | *name = new.clone(); |
| 202 | } |
| 203 | if let Some(tool) = value.as_table_mut() { |
| 204 | rewrite_references(tool, renames); |
| 205 | if let Some(inner) = tool.get_table_mut("Tools") { |
| 206 | rename_tools(inner, renames); |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | |
| 212 | pub(super) fn rewrite_references(tbl: &mut LuaTable, renames: &HashMap<String, String>) { |
| 213 | rewrite_formula_values(tbl, renames); |
| 214 | for (key, value) in &mut tbl.entries { |
| 215 | match (key, value) { |
| 216 | (LuaKey::Str(k), LuaValue::String(s)) if k == "SourceOp" => { |
| 217 | if let Some(new) = renames.get(s.as_str()) { |
| 218 | *s = new.clone(); |
| 219 | } |
| 220 | } |
| 221 | (LuaKey::Str(k), LuaValue::String(s)) if k == "Expression" => { |
| 222 | *s = rename_expression_idents(s, renames); |
| 223 | } |
| 224 | (_, LuaValue::Table(sub)) => rewrite_references(sub, renames), |
| 225 | _ => {} |
| 226 | } |
| 227 | } |
| 228 | } |
| 229 | |
| 230 | /// Rewrites the formula strings of an `Expression` modifier table (not recursive). |
| 231 | pub(super) fn rewrite_formula_values(tbl: &mut LuaTable, renames: &HashMap<String, String>) { |
| 232 | if tbl.tag.as_deref() != Some("Expression") { |
| 233 | return; |
| 234 | } |
| 235 | let Some(inputs) = tbl.get_table_mut("Inputs") else { return }; |
| 236 | for key in EXPRESSION_FORMULA_INPUTS { |
| 237 | if let Some(LuaValue::String(formula)) = inputs.get_table_mut(key).and_then(|i| i.get_mut("Value")) { |
| 238 | *formula = rename_expression_idents(formula, renames); |
| 239 | } |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | pub(super) fn rewrite_formulas_deep(tbl: &mut LuaTable, renames: &HashMap<String, String>) { |
| 244 | rewrite_formula_values(tbl, renames); |
| 245 | for (_, value) in &mut tbl.entries { |
| 246 | if let Some(sub) = value.as_table_mut() { |
| 247 | rewrite_formulas_deep(sub, renames); |
| 248 | } |
| 249 | } |
| 250 | } |
| 251 | |
| 252 | /// Renames whole-word identifiers in `expr`, leaving property names (`Other.Size`) alone. |
| 253 | pub(super) fn rename_expression_idents(expr: &str, renames: &HashMap<String, String>) -> String { |
| 254 | let mut out = String::with_capacity(expr.len()); |
| 255 | let mut word = String::new(); |
| 256 | let mut prev = None; |
| 257 | let flush = |word: &mut String, out: &mut String, prev: Option<char>| { |
| 258 | let renamed = renames.get(word.as_str()).filter(|_| prev != Some('.')); |
| 259 | out.push_str(renamed.map_or(word.as_str(), String::as_str)); |
| 260 | word.clear(); |
| 261 | }; |
| 262 | for ch in expr.chars() { |
| 263 | if ch.is_ascii_alphanumeric() || ch == '_' { |
| 264 | word.push(ch); |
| 265 | } else { |
| 266 | flush(&mut word, &mut out, prev); |
| 267 | out.push(ch); |
| 268 | prev = Some(ch); |
| 269 | } |
| 270 | } |
| 271 | flush(&mut word, &mut out, prev); |
| 272 | out |
| 273 | } |
| 274 | |
| 275 | /// Removes `SourceOp`/`Source` pairs whose target fails `exists`, so pasted tools never point at |
| 276 | /// missing operators. |
| 277 | fn drop_unknown_source_ops(tbl: &mut LuaTable, exists: &mut dyn FnMut(&str) -> bool) { |
| 278 | let dangling = tbl |
| 279 | .get_str("SourceOp") |
| 280 | .is_some_and(|name| !exists(name)); |
| 281 | if dangling { |
| 282 | tbl.remove(&LuaKey::Str("SourceOp".to_owned())); |
| 283 | tbl.remove(&LuaKey::Str("Source".to_owned())); |
| 284 | } |
| 285 | for (_, value) in &mut tbl.entries { |
| 286 | if let Some(sub) = value.as_table_mut() { |
| 287 | drop_unknown_source_ops(sub, exists); |
| 288 | } |
| 289 | } |
| 290 | } |
| 291 | |
| 292 | |
| 293 | #[cfg(test)] |
| 294 | mod tests { |
| 295 | use super::*; |
| 296 | use crate::comp::ParamValue; |
| 297 | use crate::edit::CompHistory; |
| 298 | use crate::edit::tests::{GROUP_SNIPPET, sample_comp}; |
| 299 | |
| 300 | #[test] |
| 301 | fn export_fusion_clipboard_includes_owned_modifiers_and_internal_wires() { |
| 302 | let comp = sample_comp(); |
| 303 | let bg = comp.find_node("BG1").unwrap(); |
| 304 | let bc = comp.find_node("BC1").unwrap(); |
| 305 | |
| 306 | let both = comp.export_fusion_clipboard(&[bg, bc]); |
| 307 | assert!(both.contains("Tools = ordered()"), "{both}"); |
| 308 | assert!(both.contains("ActiveTool = \"BG1\""), "{both}"); |
| 309 | let parsed = parse_lua(&both).expect("clipboard parses as Lua"); |
| 310 | let tools = parsed.as_table().unwrap().get_table("Tools").unwrap(); |
| 311 | let names: Vec<_> = tools |
| 312 | .entries |
| 313 | .iter() |
| 314 | .filter_map(|(k, _)| if let LuaKey::Str(s) = k { Some(s.as_str()) } else { None }) |
| 315 | .collect(); |
| 316 | assert_eq!(names, ["BG1", "BC1", "BC1Gain"]); |
| 317 | assert_eq!( |
| 318 | tools |
| 319 | .get_table("BC1") |
| 320 | .and_then(|t| t.get_table("Inputs")) |
| 321 | .and_then(|i| i.get_table("Input")) |
| 322 | .and_then(|i| i.get_str("SourceOp")), |
| 323 | Some("BG1") |
| 324 | ); |
| 325 | |
| 326 | // Selecting only BC1 keeps its owned spline and leaves the external BG1 reference. |
| 327 | let only_bc = comp.export_fusion_clipboard(&[bc, bc]); |
| 328 | assert!(only_bc.contains("BC1Gain = BezierSpline")); |
| 329 | assert!(!only_bc.contains("BG1 = Background")); |
| 330 | assert!(only_bc.contains("SourceOp = \"BG1\"")); |
| 331 | |
| 332 | // Splines created after load (not yet in `raw_root`) are exported too. |
| 333 | let mut comp = comp; |
| 334 | let sp = comp.set_keyframe(bg, "Width", 0.0, 1.0).unwrap(); |
| 335 | assert!(comp.export_fusion_clipboard(&[bg]).contains(&format!("{sp} = BezierSpline"))); |
| 336 | } |
| 337 | |
| 338 | #[test] |
| 339 | fn paste_dedups_names_and_remaps_internal_wires_and_splines() { |
| 340 | let mut comp = sample_comp(); |
| 341 | let bg = comp.find_node("BG1").unwrap(); |
| 342 | let bc = comp.find_node("BC1").unwrap(); |
| 343 | let snippet = comp.export_fusion_clipboard(&[bg, bc]); |
| 344 | let nodes_before = comp.nodes.len(); |
| 345 | |
| 346 | let ids = comp.paste_fusion_clipboard(&snippet, (60.0, 40.0)).expect("paste"); |
| 347 | assert_eq!(ids.len(), 2); |
| 348 | assert_eq!(comp.nodes.len(), nodes_before + 2); |
| 349 | let (pbg, pbc) = (comp.node(ids[0]), comp.node(ids[1])); |
| 350 | assert_eq!((pbg.name.as_str(), pbc.name.as_str()), ("BG1_1", "BC1_1")); |
| 351 | assert_eq!(pbg.pos, [160.0, 90.0]); |
| 352 | assert_eq!(pbc.pos, [360.0, 90.0]); |
| 353 | assert_eq!(pbc.connected_node("Input"), Some("BG1_1")); |
| 354 | assert_eq!(pbc.connected_node("Gain"), Some("BC1Gain_1")); |
| 355 | assert_eq!(comp.splines["BC1Gain_1"].keyframes.len(), 2); |
| 356 | assert_eq!(comp.splines["BC1Gain"].keyframes.len(), 2); |
| 357 | assert_eq!(comp.find_node("BC1_1"), Some(ids[1])); |
| 358 | assert_eq!(comp.node(bc).connected_node("Input"), Some("BG1")); |
| 359 | |
| 360 | // Pasting again keeps advancing the suffix instead of clobbering earlier pastes. |
| 361 | let again = comp.paste_fusion_clipboard(&snippet, (0.0, 0.0)).unwrap(); |
| 362 | assert_eq!(comp.node(again[0]).name, "BG1_2"); |
| 363 | assert_eq!(comp.node(again[1]).connected_node("Input"), Some("BG1_2")); |
| 364 | |
| 365 | // Everything survives a save/load roundtrip, including the cloned spline and offset. |
| 366 | let reloaded = Comp::from_fusion_str(&comp.to_fusion_string()).expect("reload"); |
| 367 | let r_bc = reloaded.node(reloaded.find_node("BC1_1").unwrap()); |
| 368 | assert_eq!(r_bc.pos, [360.0, 90.0]); |
| 369 | assert_eq!(r_bc.connected_node("Input"), Some("BG1_1")); |
| 370 | assert!(reloaded.splines.contains_key("BC1Gain_1")); |
| 371 | } |
| 372 | |
| 373 | #[test] |
| 374 | fn paste_external_references_are_kept_when_present_and_dropped_when_missing() { |
| 375 | let mut comp = sample_comp(); |
| 376 | let bc = comp.find_node("BC1").unwrap(); |
| 377 | let snippet = comp.export_fusion_clipboard(&[bc]); |
| 378 | |
| 379 | let ids = comp.paste_fusion_clipboard(&snippet, (0.0, 0.0)).unwrap(); |
| 380 | assert_eq!(comp.node(ids[0]).connected_node("Input"), Some("BG1")); |
| 381 | |
| 382 | let mut empty = Comp::from_fusion_str("Composition { Tools = ordered() { } }").unwrap(); |
| 383 | let ids = empty.paste_fusion_clipboard(&snippet, (5.0, 5.0)).unwrap(); |
| 384 | let pasted = empty.node(ids[0]); |
| 385 | assert_eq!(pasted.name, "BC1"); |
| 386 | assert_eq!(pasted.connected_node("Input"), None); |
| 387 | assert_eq!(pasted.connected_node("Gain"), Some("BC1Gain")); |
| 388 | assert!(!empty.to_fusion_string().contains("BG1")); |
| 389 | } |
| 390 | |
| 391 | #[test] |
| 392 | fn paste_accepts_full_composition_and_rewrites_expressions() { |
| 393 | let mut comp = sample_comp(); |
| 394 | let snippet = r#"Composition { |
| 395 | 	Tools = ordered() { |
| 396 | 		BG1 = Background { Inputs = { Width = Input { Value = 64, } }, }, |
| 397 | 		T1 = Transform { |
| 398 | 			Inputs = { |
| 399 | 				Size = Input { Expression = "BG1.Width / 2 + BG10.Width", }, |
| 400 | 				Input = Input { SourceOp = "BG1", Source = "Output", }, |
| 401 | 			}, |
| 402 | 		}, |
| 403 | 	}, |
| 404 | }"#; |
| 405 | let ids = comp.paste_fusion_clipboard(snippet, (1.0, 2.0)).unwrap(); |
| 406 | let t1 = comp.node(ids[1]); |
| 407 | assert_eq!(comp.node(ids[0]).name, "BG1_1"); |
| 408 | assert_eq!(comp.node(ids[0]).pos, [1.0, 2.0]); |
| 409 | assert_eq!(t1.connected_node("Input"), Some("BG1_1")); |
| 410 | assert_eq!( |
| 411 | t1.inputs["Size"].expression.as_deref(), |
| 412 | Some("BG1_1.Width / 2 + BG10.Width") |
| 413 | ); |
| 414 | } |
| 415 | |
| 416 | #[test] |
| 417 | fn paste_group_renames_nested_tools_and_remaps_macro_output() { |
| 418 | let mut comp = sample_comp(); |
| 419 | let first = comp.paste_fusion_clipboard(GROUP_SNIPPET, (0.0, 0.0)).unwrap(); |
| 420 | let second = comp.paste_fusion_clipboard(GROUP_SNIPPET, (50.0, 0.0)).unwrap(); |
| 421 | let (g1, g2) = (comp.node(first[0]), comp.node(second[0])); |
| 422 | assert_eq!((g1.name.as_str(), g2.name.as_str()), ("Group1", "Group1_1")); |
| 423 | assert_eq!(g2.pos, [60.0, 20.0]); |
| 424 | |
| 425 | let inner = comp.node(g2.macro_output.expect("macro output")); |
| 426 | assert_eq!(inner.name, "Inner1_1"); |
| 427 | assert!(inner.internal); |
| 428 | assert_eq!(inner.connected_node("XBlurSize"), Some("Inner1Size_1")); |
| 429 | assert!(comp.splines.contains_key("Inner1Size_1")); |
| 430 | assert_eq!(comp.node(g1.macro_output.unwrap()).name, "Inner1"); |
| 431 | assert_eq!(comp.find_node("Group1_1"), Some(second[0])); |
| 432 | assert_eq!(comp.find_node("Inner1_1"), g2.macro_output); |
| 433 | } |
| 434 | |
| 435 | #[test] |
| 436 | fn paste_is_one_undo_step_and_redoable() { |
| 437 | let mut comp = sample_comp(); |
| 438 | let mut history = CompHistory::new(); |
| 439 | let bg = comp.find_node("BG1").unwrap(); |
| 440 | let bc = comp.find_node("BC1").unwrap(); |
| 441 | let snippet = comp.export_fusion_clipboard(&[bg, bc]); |
| 442 | let (nodes, splines) = (comp.nodes.len(), comp.splines.len()); |
| 443 | history.mark_saved(&comp); |
| 444 | |
| 445 | let ids = history |
| 446 | .paste_fusion_clipboard(&mut comp, &snippet, (60.0, 40.0)) |
| 447 | .unwrap(); |
| 448 | assert_eq!(ids.len(), 2); |
| 449 | assert_eq!(history.undo_len(), 1); |
| 450 | assert_eq!(history.undo_label(), Some("Paste")); |
| 451 | assert!(history.is_dirty(&comp)); |
| 452 | |
| 453 | assert!(history.undo(&mut comp)); |
| 454 | assert_eq!((comp.nodes.len(), comp.splines.len()), (nodes, splines)); |
| 455 | assert!(comp.find_node("BG1_1").is_none()); |
| 456 | assert!(!comp.to_fusion_string().contains("BG1_1")); |
| 457 | assert!(!history.can_undo()); |
| 458 | assert!(!history.is_dirty(&comp)); |
| 459 | |
| 460 | assert!(history.redo(&mut comp)); |
| 461 | assert_eq!((comp.nodes.len(), comp.splines.len()), (nodes + 2, splines + 1)); |
| 462 | let pasted = comp.find_node("BC1_1").unwrap(); |
| 463 | assert_eq!(comp.node(pasted).connected_node("Input"), Some("BG1_1")); |
| 464 | assert!(!history.can_redo()); |
| 465 | } |
| 466 | |
| 467 | #[test] |
| 468 | fn paste_rejects_garbage_without_touching_comp_or_history() { |
| 469 | let mut comp = sample_comp(); |
| 470 | let mut history = CompHistory::new(); |
| 471 | let (rev, nodes) = (comp.revision, comp.nodes.len()); |
| 472 | for bad in ["", "hello world", "{ Foo = 1 }", "{ Tools = ordered() { } }", "{ Tools = "] { |
| 473 | assert!(history.paste_fusion_clipboard(&mut comp, bad, (0.0, 0.0)).is_err(), "{bad:?}"); |
| 474 | } |
| 475 | assert_eq!((comp.revision, comp.nodes.len()), (rev, nodes)); |
| 476 | assert!(!history.can_undo()); |
| 477 | assert!(!history.in_group()); |
| 478 | } |
| 479 | |
| 480 | const TWO_GROUPS: &str = r#"Composition { |
| 481 | 	Tools = ordered() { |
| 482 | 		BG = Background { }, |
| 483 | 		GA = GroupOperator { |
| 484 | 			Outputs = { Out = InstanceOutput { SourceOp = "Same", Source = "Output", }, }, |
| 485 | 			Tools = ordered() { |
| 486 | 				Same = Blur { Inputs = { XBlurSize = Input { SourceOp = "SameSize", Source = "Value", }, }, }, |
| 487 | 				SameSize = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, }, |
| 488 | 			}, |
| 489 | 		}, |
| 490 | 		GB = GroupOperator { |
| 491 | 			Outputs = { Out = InstanceOutput { SourceOp = "Same", Source = "Output", }, }, |
| 492 | 			Tools = ordered() { |
| 493 | 				Same = Blur { }, |
| 494 | 			}, |
| 495 | 		}, |
| 496 | 	}, |
| 497 | }"#; |
| 498 | |
| 499 | fn tool_names(tools: &LuaTable) -> Vec<&str> { |
| 500 | tools |
| 501 | .entries |
| 502 | .iter() |
| 503 | .filter_map(|(k, _)| if let LuaKey::Str(s) = k { Some(s.as_str()) } else { None }) |
| 504 | .collect() |
| 505 | } |
| 506 | |
| 507 | #[test] |
| 508 | |
| 509 | fn deleting_a_group_removes_its_private_tools_and_modifiers() { |
| 510 | let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap(); |
| 511 | let g = comp.find_node("Group1").unwrap(); |
| 512 | let deleted = comp.delete_nodes(&[g]); |
| 513 | assert_eq!(deleted, ["Group1", "Inner1"]); |
| 514 | assert!(comp.nodes.is_empty()); |
| 515 | assert!(comp.splines.is_empty()); |
| 516 | assert!(tool_names(comp.raw_root.as_ref().unwrap().get_table("Tools").unwrap()).is_empty()); |
| 517 | } |
| 518 | |
| 519 | #[test] |
| 520 | fn deleting_a_node_keeps_splines_still_used_by_expression_modifiers() { |
| 521 | let src = r#"Composition { |
| 522 | 	Tools = ordered() { |
| 523 | 		N = Transform { Inputs = { Angle = Input { SourceOp = "Shared", Source = "Value", }, Size = Input { SourceOp = "E", Source = "NumberResult", }, }, }, |
| 524 | 		M = Transform { Inputs = { Angle = Input { SourceOp = "Own", Source = "Value", }, Size = Input { SourceOp = "E2", Source = "NumberResult", }, }, }, |
| 525 | 		E = Expression { Inputs = { n1 = Input { SourceOp = "Shared", Source = "Value", }, NumberExpression = Input { Value = "n1", }, }, }, |
| 526 | 		E2 = Expression { Inputs = { n1 = Input { SourceOp = "Own", Source = "Value", }, NumberExpression = Input { Value = "n1", }, }, }, |
| 527 | 		Shared = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, }, |
| 528 | 		Own = BezierSpline { KeyFrames = { [0] = { 2, Flags = { Linear = true } } }, }, |
| 529 | 	}, |
| 530 | }"#; |
| 531 | let mut comp = Comp::from_fusion_str(src).unwrap(); |
| 532 | comp.delete_nodes(&[comp.find_node("M").unwrap()]); |
| 533 | assert!(!comp.expression_modifiers.contains_key("E2")); |
| 534 | assert!(!comp.splines.contains_key("Own")); |
| 535 | assert!(comp.expression_modifiers.contains_key("E")); |
| 536 | assert!(comp.splines.contains_key("Shared")); |
| 537 | |
| 538 | // Deleting the other owner prunes the expression modifier and its spline. |
| 539 | let mut comp = Comp::from_fusion_str(src).unwrap(); |
| 540 | comp.delete_nodes(&[comp.find_node("N").unwrap()]); |
| 541 | assert!(!comp.expression_modifiers.contains_key("E")); |
| 542 | assert!(!comp.splines.contains_key("Shared")); |
| 543 | |
| 544 | // A spline referenced by a surviving (unpruned) expression modifier outlives its owner. |
| 545 | let with_orphan = src.replace("\t},\n}", "\t\tEO = Expression { Inputs = { n1 = Input { SourceOp = \"Shared\", Source = \"Value\", }, }, },\n\t},\n}"); |
| 546 | let mut comp = Comp::from_fusion_str(&with_orphan).unwrap(); |
| 547 | comp.delete_nodes(&[comp.find_node("N").unwrap()]); |
| 548 | assert!(comp.expression_modifiers.contains_key("EO")); |
| 549 | assert!(comp.splines.contains_key("Shared")); |
| 550 | } |
| 551 | |
| 552 | #[test] |
| 553 | fn export_includes_modifiers_nested_in_a_copied_internal_node_once() { |
| 554 | let comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap(); |
| 555 | let inner = comp.find_node("Inner1").unwrap(); |
| 556 | let clip = comp.export_fusion_clipboard(&[inner]); |
| 557 | let parsed = parse_lua(&clip).unwrap(); |
| 558 | let tools = parsed.as_table().unwrap().get_table("Tools").unwrap(); |
| 559 | assert_eq!(tool_names(tools), ["Inner1", "Inner1Size"]); |
| 560 | |
| 561 | let whole = comp.export_fusion_clipboard(&[comp.find_node("Group1").unwrap()]); |
| 562 | assert_eq!(whole.matches("Inner1Size = BezierSpline").count(), 1, "{whole}"); |
| 563 | } |
| 564 | |
| 565 | #[test] |
| 566 | fn paste_never_links_to_group_private_tools() { |
| 567 | let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap(); |
| 568 | let snippet = r#"{ Tools = ordered() { T = Transform { Inputs = { |
| 569 | Input = Input { SourceOp = "Inner1", Source = "Output", }, |
| 570 | Mask = Input { SourceOp = "Group1", Source = "Output", }, |
| 571 | Angle = Input { SourceOp = "Inner1Size", Source = "Value", }, |
| 572 | }, }, }, }"#; |
| 573 | let ids = comp.paste_fusion_clipboard(snippet, (0.0, 0.0)).unwrap(); |
| 574 | let t = comp.node(ids[0]); |
| 575 | assert_eq!(t.connected_node("Input"), None); |
| 576 | assert_eq!(t.connected_node("Angle"), None); |
| 577 | assert_eq!(t.connected_node("Mask"), Some("Group1")); |
| 578 | } |
| 579 | |
| 580 | #[test] |
| 581 | fn expression_renames_skip_property_names() { |
| 582 | let renames = HashMap::from([("Size".to_owned(), "Big".to_owned())]); |
| 583 | assert_eq!( |
| 584 | rename_expression_idents("Other.Size + Size.Width * Size", &renames), |
| 585 | "Other.Size + Big.Width * Big" |
| 586 | ); |
| 587 | } |
| 588 | |
| 589 | #[test] |
| 590 | fn rename_and_paste_rewrite_expression_modifier_formulas() { |
| 591 | let src = r#"Composition { |
| 592 | 	Tools = ordered() { |
| 593 | 		BG = Background { }, |
| 594 | 		E = Expression { Inputs = { NumberExpression = Input { Value = "BG.Width + Other.BG", }, }, }, |
| 595 | 	}, |
| 596 | }"#; |
| 597 | let mut comp = Comp::from_fusion_str(src).unwrap(); |
| 598 | let bg = comp.find_node("BG").unwrap(); |
| 599 | comp.rename_node(bg, "Plate").unwrap(); |
| 600 | let formula = |c: &Comp| c.expression_modifiers["E"].inputs["NumberExpression"].value.clone(); |
| 601 | assert_eq!(formula(&comp), Some(ParamValue::Text("Plate.Width + Other.BG".to_owned()))); |
| 602 | assert!(comp.to_fusion_string().contains("Plate.Width + Other.BG")); |
| 603 | |
| 604 | let paste = r#"{ Tools = ordered() { BG = Background { }, E = Expression { Inputs = { NumberExpression = Input { Value = "BG.Width", }, }, }, }, }"#; |
| 605 | comp.paste_fusion_clipboard(paste, (0.0, 0.0)).unwrap(); |
| 606 | assert_eq!( |
| 607 | comp.expression_modifiers["E_1"].inputs["NumberExpression"].value, |
| 608 | Some(ParamValue::Text("BG.Width".to_owned())) |
| 609 | ); |
| 610 | let mut again = Comp::from_fusion_str(paste).unwrap(); |
| 611 | again.paste_fusion_clipboard(paste, (0.0, 0.0)).unwrap(); |
| 612 | assert_eq!( |
| 613 | again.expression_modifiers["E_1"].inputs["NumberExpression"].value, |
| 614 | Some(ParamValue::Text("BG_1.Width".to_owned())) |
| 615 | ); |
| 616 | } |
| 617 | |
| 618 | #[test] |
| 619 | fn renaming_one_groups_private_tool_leaves_same_named_tools_elsewhere() { |
| 620 | let mut comp = Comp::from_fusion_str(TWO_GROUPS).unwrap(); |
| 621 | let (ga, gb) = (comp.find_node("GA").unwrap(), comp.find_node("GB").unwrap()); |
| 622 | let a_same = comp.nodes.iter().position(|n| n.name == "Same" && n.id.0 < ga.0).unwrap(); |
| 623 | assert_eq!(comp.rename_node(NodeId(a_same), "Renamed").unwrap(), "Renamed"); |
| 624 | |
| 625 | let text = comp.to_fusion_string(); |
| 626 | let saved = Comp::from_fusion_str(&text).unwrap(); |
| 627 | let group_tools = |name: &str| { |
| 628 | let g = saved.node(saved.find_node(name).unwrap()); |
| 629 | ( |
| 630 | g.raw.get_table("Outputs").unwrap().get_table("Out").unwrap().get_str("SourceOp").unwrap().to_owned(), |
| 631 | tool_names(find_raw_tool_in(&saved, name)).into_iter().map(str::to_owned).collect::<Vec<_>>(), |
| 632 | ) |
| 633 | }; |
| 634 | assert_eq!(group_tools("GA"), ("Renamed".to_owned(), vec!["Renamed".to_owned(), "SameSize".to_owned()])); |
| 635 | assert_eq!(group_tools("GB"), ("Same".to_owned(), vec!["Same".to_owned()])); |
| 636 | assert_eq!(comp.node(gb).name, "GB"); |
| 637 | } |
| 638 | |
| 639 | fn find_raw_tool_in<'a>(comp: &'a Comp, group: &str) -> &'a LuaTable { |
| 640 | let tools = comp.raw_root.as_ref().unwrap().get_table("Tools").unwrap(); |
| 641 | find_raw_tool(tools, group).unwrap().get_table("Tools").unwrap() |
| 642 | } |
| 643 | |
| 644 | #[test] |
| 645 | fn renaming_a_top_level_tool_ignores_groups_with_a_private_tool_of_that_name() { |
| 646 | let src = TWO_GROUPS.replace("BG = Background { },", "BG = Background { },\n\t\tSame = Blur { },"); |
| 647 | let mut comp = Comp::from_fusion_str(&src).unwrap(); |
| 648 | let top = comp.find_node("Same").unwrap(); |
| 649 | assert!(!comp.node(top).internal); |
| 650 | comp.rename_node(top, "Top").unwrap(); |
| 651 | let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap(); |
| 652 | let ga = saved.node(saved.find_node("GA").unwrap()); |
| 653 | assert_eq!( |
| 654 | ga.raw.get_table("Outputs").unwrap().get_table("Out").unwrap().get_str("SourceOp"), |
| 655 | Some("Same") |
| 656 | ); |
| 657 | assert!(saved.find_node("Top").is_some_and(|id| !saved.node(id).internal)); |
| 658 | } |
| 659 | |
| 660 | #[test] |
| 661 | fn duplicate_nodes_clones_groups_and_curve_modifiers() { |
| 662 | let src = r#"Composition { |
| 663 | 	Tools = ordered() { |
| 664 | 		BG = Background { }, |
| 665 | 		HC = HueCurves { |
| 666 | 			Inputs = { |
| 667 | 				Input = Input { SourceOp = "BG", Source = "Output", }, |
| 668 | 				RedSuppress = Input { SourceOp = "HC_RSup", Source = "Value", }, |
| 669 | 			}, |
| 670 | 			Tools = ordered() { |
| 671 | 				HC_RSup = LUTBezier { KeyColorSplines = { [0] = { [0] = { 0.5 }, [6] = { 0.5 } } }, }, |
| 672 | 			}, |
| 673 | 		}, |
| 674 | 	}, |
| 675 | }"#; |
| 676 | let mut comp = Comp::from_fusion_str(src).unwrap(); |
| 677 | let hc = comp.find_node("HC").unwrap(); |
| 678 | let dup = comp.duplicate_nodes(&[hc], [10.0, 0.0]); |
| 679 | assert_eq!(dup.len(), 1); |
| 680 | let d = comp.node(dup[0]); |
| 681 | assert_eq!(d.name, "HC_1"); |
| 682 | assert_eq!(d.connected_node("Input"), Some("BG")); |
| 683 | assert_eq!(d.connected_node("RedSuppress"), Some("HC_RSup_1")); |
| 684 | assert!(comp.splines.contains_key("HC_RSup_1") && comp.splines.contains_key("HC_RSup")); |
| 685 | let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap(); |
| 686 | assert!(saved.splines.contains_key("HC_RSup_1")); |
| 687 | |
| 688 | let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap(); |
| 689 | let g = comp.find_node("Group1").unwrap(); |
| 690 | let dup = comp.duplicate_nodes(&[g], [0.0, 80.0]); |
| 691 | let copy = comp.node(dup[0]); |
| 692 | assert_eq!(copy.name, "Group1_1"); |
| 693 | assert_eq!(comp.node(copy.macro_output.unwrap()).name, "Inner1_1"); |
| 694 | assert!(comp.splines.contains_key("Inner1Size_1")); |
| 695 | } |
| 696 | } |