| ... | ... | @@ -2,20 +2,25 @@ |
| 2 | 2 | |
| 3 | 3 | use crate::comp::{ |
| 4 | 4 | Comp, InputBinding, Node, NodeId, ParamValue, default_main_input_port, ensure_table_mut, |
| 5 | | param_value_to_lua, vec2_lua, |
| 5 | find_raw_tool, find_raw_tool_mut, is_group_kind, is_modifier_type, param_value_to_lua, vec2_lua, |
| 6 | 6 | }; |
| 7 | 7 | use crate::lua_value::{LuaKey, LuaTable, LuaValue, is_valid_lua_ident, parse_lua}; |
| 8 | | use crate::spline::{BezierSpline, Keyframe, PolyPath}; |
| 8 | use crate::spline::{BezierSpline, Keyframe}; |
| 9 | 9 | use std::collections::{HashMap, HashSet, VecDeque}; |
| 10 | 10 | |
| 11 | 11 | /// Default maximum number of undo steps retained by [`CompHistory`]. |
| 12 | 12 | pub const DEFAULT_MAX_HISTORY: usize = 128; |
| 13 | 13 | |
| 14 | /// Keyframe times closer than this are the same keyframe (matches the Inspector's `keyframe_state`). |
| 15 | const KEYFRAME_EPS: f64 = 1e-4; |
| 16 | |
| 17 | /// Expression-modifier inputs whose `Value` is a formula string. |
| 18 | const EXPRESSION_FORMULA_INPUTS: &[&str] = |
| 19 | &["NumberExpression", "PointExpressionX", "PointExpressionY", "PointExpression"]; |
| 20 | |
| 14 | 21 | impl Comp { |
| 15 | | /// Checks whether a tool or modifier name is already in use anywhere in this composition. |
| 16 | | fn name_exists(&self, name: &str) -> bool { |
| 17 | | if self.node_by_name.contains_key(name) |
| 18 | | || self.splines.contains_key(name) |
| 22 | fn modifier_exists(&self, name: &str) -> bool { |
| 23 | self.splines.contains_key(name) |
| 19 | 24 | || self.poly_paths.contains_key(name) |
| 20 | 25 | || self.gradient_modifiers.contains_key(name) |
| 21 | 26 | || self.text_modifiers.contains_key(name) |
| ... | ... | @@ -24,7 +29,29 @@ impl Comp { |
| 24 | 29 | || self.text_cls.contains_key(name) |
| 25 | 30 | || self.shakes.contains_key(name) |
| 26 | 31 | || self.expression_modifiers.contains_key(name) |
| 27 | | { |
| 32 | } |
| 33 | |
| 34 | /// Whether pasted tools may link to `name`: a top-level flow node, or a modifier not private |
| 35 | /// to a group. |
| 36 | fn is_linkable_external(&self, name: &str) -> bool { |
| 37 | if self.nodes.iter().any(|n| !n.internal && n.name == name) { |
| 38 | return true; |
| 39 | } |
| 40 | let Some(tools) = self.raw_root.as_ref().and_then(|r| r.get_table("Tools")) else { |
| 41 | return self.modifier_exists(name); |
| 42 | }; |
| 43 | self.modifier_exists(name) |
| 44 | && (tools.get(name).is_some() |
| 45 | || !tools |
| 46 | .entries |
| 47 | .iter() |
| 48 | .filter_map(|(_, v)| v.as_table()?.get_table("Tools")) |
| 49 | .any(|inner| find_raw_tool(inner, name).is_some())) |
| 50 | } |
| 51 | |
| 52 | /// Checks whether a tool or modifier name is already in use anywhere in this composition. |
| 53 | fn name_exists(&self, name: &str) -> bool { |
| 54 | if self.node_by_name.contains_key(name) || self.modifier_exists(name) { |
| 28 | 55 | return true; |
| 29 | 56 | } |
| 30 | 57 | if let Some(tools) = self.raw_root.as_ref().and_then(|r| r.get_table("Tools")) { |
| ... | ... | @@ -135,22 +162,96 @@ impl Comp { |
| 135 | 162 | id |
| 136 | 163 | } |
| 137 | 164 | |
| 138 | | /// Deletes the specified nodes, unwires downstream references, compacts `NodeId` indexing, |
| 139 | | /// and prunes modifiers that were owned solely by the deleted nodes. |
| 140 | | /// Returns the names of the deleted nodes. |
| 165 | /// Indices of the internal nodes owned by the Group/Macro at `idx`, including nested groups' |
| 166 | /// contents. Nodes load in post-order, so they are the contiguous internal block before `idx`. |
| 167 | fn group_children(&self, idx: usize) -> Vec<usize> { |
| 168 | let node = &self.nodes[idx]; |
| 169 | let mut remaining: HashMap<&str, usize> = HashMap::new(); |
| 170 | if is_group_kind(&node.kind) { |
| 171 | if let Some(inner) = self |
| 172 | .raw_root |
| 173 | .as_ref() |
| 174 | .and_then(|r| r.get_table("Tools")) |
| 175 | .and_then(|t| find_raw_tool(t, &node.name)) |
| 176 | .and_then(|g| g.get_table("Tools")) |
| 177 | { |
| 178 | count_flow_tools(inner, &mut remaining); |
| 179 | } |
| 180 | } |
| 181 | let mut out = Vec::new(); |
| 182 | for i in (0..idx).rev() { |
| 183 | let n = &self.nodes[i]; |
| 184 | if remaining.is_empty() || !n.internal { |
| 185 | break; |
| 186 | } |
| 187 | if let Some(left) = remaining.get_mut(n.name.as_str()) { |
| 188 | *left -= 1; |
| 189 | if *left == 0 { |
| 190 | remaining.remove(n.name.as_str()); |
| 191 | } |
| 192 | out.push(i); |
| 193 | } |
| 194 | } |
| 195 | out |
| 196 | } |
| 197 | |
| 198 | /// Modifiers directly referenced by modifier `name`. |
| 199 | fn modifier_refs(&self, name: &str) -> Vec<String> { |
| 200 | let mut out = Vec::new(); |
| 201 | if let Some(pp) = self.poly_paths.get(name) { |
| 202 | out.extend(pp.displacement_op.clone()); |
| 203 | } |
| 204 | let bindings = self |
| 205 | .shakes |
| 206 | .get(name) |
| 207 | .map(|s| &s.inputs) |
| 208 | .or_else(|| self.expression_modifiers.get(name).map(|e| &e.inputs)); |
| 209 | out.extend(bindings.into_iter().flat_map(|m| m.values()).filter_map(|b| b.source_op.clone())); |
| 210 | out |
| 211 | } |
| 212 | |
| 213 | fn close_over_modifier_refs(&self, set: &mut HashSet<String>) { |
| 214 | let mut queue: VecDeque<String> = set.iter().cloned().collect(); |
| 215 | while let Some(name) = queue.pop_front() { |
| 216 | for next in self.modifier_refs(&name) { |
| 217 | if set.insert(next.clone()) { |
| 218 | queue.push_back(next); |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | /// Deletes the specified nodes (and the private contents of any deleted Group/Macro), unwires |
| 225 | /// downstream references, compacts `NodeId` indexing, and prunes modifiers that were owned |
| 226 | /// solely by the deleted nodes. Returns the names of the deleted nodes. |
| 141 | 227 | pub fn delete_nodes(&mut self, ids: &[NodeId]) -> Vec<String> { |
| 142 | | let mut to_delete: HashSet<usize> = HashSet::new(); |
| 143 | | let mut deleted_names: Vec<String> = Vec::new(); |
| 228 | let mut doomed: Vec<usize> = Vec::new(); |
| 144 | 229 | for &id in ids { |
| 145 | | if id.0 < self.nodes.len() && to_delete.insert(id.0) { |
| 146 | | deleted_names.push(self.nodes[id.0].name.clone()); |
| 230 | if id.0 < self.nodes.len() && !doomed.contains(&id.0) { |
| 231 | doomed.push(id.0); |
| 232 | } |
| 233 | } |
| 234 | let mut next = 0; |
| 235 | while next < doomed.len() { |
| 236 | for child in self.group_children(doomed[next]) { |
| 237 | if !doomed.contains(&child) { |
| 238 | doomed.push(child); |
| 239 | } |
| 147 | 240 | } |
| 241 | next += 1; |
| 148 | 242 | } |
| 149 | | if to_delete.is_empty() { |
| 150 | | return deleted_names; |
| 243 | if doomed.is_empty() { |
| 244 | return Vec::new(); |
| 151 | 245 | } |
| 152 | 246 | |
| 247 | let deleted_names: Vec<String> = doomed.iter().map(|&i| self.nodes[i].name.clone()).collect(); |
| 153 | 248 | let deleted_name_set: HashSet<String> = deleted_names.iter().cloned().collect(); |
| 249 | let deleted_internal: HashSet<String> = doomed |
| 250 | .iter() |
| 251 | .filter(|&&i| self.nodes[i].internal) |
| 252 | .map(|&i| self.nodes[i].name.clone()) |
| 253 | .collect(); |
| 254 | let to_delete: HashSet<usize> = doomed.into_iter().collect(); |
| 154 | 255 | |
| 155 | 256 | // Collect modifier names referenced by the nodes being deleted (candidates for pruning). |
| 156 | 257 | let mut candidate_modifiers: HashSet<String> = HashSet::new(); |
| ... | ... | @@ -211,53 +312,22 @@ impl Comp { |
| 211 | 312 | } |
| 212 | 313 | self.nodes = new_nodes; |
| 213 | 314 | |
| 214 | | // Collect all modifier references still live on surviving nodes (transitively through PolyPaths/Shakes). |
| 315 | // A modifier survives if a surviving node reaches it, or a modifier that is not itself being |
| 316 | // pruned references it (transitively, through paths, shakes and expression modifiers). |
| 317 | self.close_over_modifier_refs(&mut candidate_modifiers); |
| 215 | 318 | let mut live_refs: HashSet<String> = HashSet::new(); |
| 216 | 319 | for node in &self.nodes { |
| 217 | 320 | collect_node_source_ops(node, &mut live_refs); |
| 218 | 321 | } |
| 219 | | // Propagate transitive references (e.g. surviving node -> PolyPath -> Displacement spline, |
| 220 | | // or surviving node -> Shake -> BezierSpline). |
| 221 | | let mut queue: VecDeque<String> = live_refs.iter().cloned().collect(); |
| 222 | | while let Some(mod_name) = queue.pop_front() { |
| 223 | | if let Some(pp) = self.poly_paths.get(&mod_name) { |
| 224 | | if let Some(disp) = &pp.displacement_op { |
| 225 | | if live_refs.insert(disp.clone()) { |
| 226 | | queue.push_back(disp.clone()); |
| 227 | | } |
| 228 | | } |
| 229 | | } |
| 230 | | if let Some(sh) = self.shakes.get(&mod_name) { |
| 231 | | for binding in sh.inputs.values() { |
| 232 | | if let Some(src) = &binding.source_op { |
| 233 | | if live_refs.insert(src.clone()) { |
| 234 | | queue.push_back(src.clone()); |
| 235 | | } |
| 236 | | } |
| 237 | | } |
| 238 | | } |
| 239 | | } |
| 240 | | |
| 241 | | // Expand candidate_modifiers transitively (e.g. deleted node -> PolyPath -> Displacement spline). |
| 242 | | let mut cand_queue: VecDeque<String> = candidate_modifiers.iter().cloned().collect(); |
| 243 | | while let Some(mod_name) = cand_queue.pop_front() { |
| 244 | | if let Some(pp) = self.poly_paths.get(&mod_name) { |
| 245 | | if let Some(disp) = &pp.displacement_op { |
| 246 | | if candidate_modifiers.insert(disp.clone()) { |
| 247 | | cand_queue.push_back(disp.clone()); |
| 248 | | } |
| 249 | | } |
| 250 | | } |
| 251 | | if let Some(sh) = self.shakes.get(&mod_name) { |
| 252 | | for binding in sh.inputs.values() { |
| 253 | | if let Some(src) = &binding.source_op { |
| 254 | | if candidate_modifiers.insert(src.clone()) { |
| 255 | | cand_queue.push_back(src.clone()); |
| 256 | | } |
| 257 | | } |
| 258 | | } |
| 259 | | } |
| 260 | | } |
| 322 | let surviving_modifiers = self |
| 323 | .poly_paths |
| 324 | .keys() |
| 325 | .chain(self.shakes.keys()) |
| 326 | .chain(self.expression_modifiers.keys()) |
| 327 | .filter(|name| !candidate_modifiers.contains(*name)); |
| 328 | let survivor_refs: Vec<String> = surviving_modifiers.flat_map(|n| self.modifier_refs(n)).collect(); |
| 329 | live_refs.extend(survivor_refs); |
| 330 | self.close_over_modifier_refs(&mut live_refs); |
| 261 | 331 | |
| 262 | 332 | // Prune orphaned modifiers that belonged to deleted nodes and are no longer referenced. |
| 263 | 333 | let mut pruned_modifiers: HashSet<String> = HashSet::new(); |
| ... | ... | @@ -274,21 +344,21 @@ impl Comp { |
| 274 | 344 | removed |= self.polyline_splines.remove(&cand).is_some(); |
| 275 | 345 | removed |= self.text_cls.remove(&cand).is_some(); |
| 276 | 346 | removed |= self.shakes.remove(&cand).is_some(); |
| 347 | removed |= self.expression_modifiers.remove(&cand).is_some(); |
| 277 | 348 | if removed { |
| 278 | 349 | pruned_modifiers.insert(cand); |
| 279 | 350 | } |
| 280 | 351 | } |
| 281 | 352 | |
| 282 | | // Update `raw_root.Tools`: remove deleted nodes & pruned modifiers, and clear stale SourceOp. |
| 283 | | if let Some(root) = self.raw_root.as_mut() { |
| 284 | | if let Some(tools) = root.get_table_mut("Tools") { |
| 285 | | tools.entries.retain(|(k, _)| match k { |
| 286 | | LuaKey::Str(name) => { |
| 287 | | !deleted_name_set.contains(name) && !pruned_modifiers.contains(name) |
| 288 | | } |
| 289 | | _ => true, |
| 290 | | }); |
| 291 | | } |
| 353 | // Update `raw_root.Tools`: remove deleted top-level nodes, and pruned modifiers / deleted |
| 354 | // group-private nodes wherever they are nested. |
| 355 | if let Some(tools) = self.raw_root.as_mut().and_then(|r| r.get_table_mut("Tools")) { |
| 356 | tools.entries.retain(|(k, _)| match k { |
| 357 | LuaKey::Str(name) => !deleted_name_set.contains(name), |
| 358 | _ => true, |
| 359 | }); |
| 360 | let nested: HashSet<String> = pruned_modifiers.union(&deleted_internal).cloned().collect(); |
| 361 | remove_tools_recursive(tools, &nested); |
| 292 | 362 | } |
| 293 | 363 | |
| 294 | 364 | self.revision += 1; |
| ... | ... | @@ -317,11 +387,7 @@ impl Comp { |
| 317 | 387 | }; |
| 318 | 388 | let mut refs: VecDeque<String> = VecDeque::new(); |
| 319 | 389 | 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 | | }; |
| 390 | let raw = root_tools.and_then(|t| find_raw_tool(t, &n.name)).unwrap_or(&n.raw); |
| 325 | 391 | let mut found = HashSet::new(); |
| 326 | 392 | collect_source_ops_in_table(raw, &mut found); |
| 327 | 393 | let mut found: Vec<String> = found.into_iter().collect(); |
| ... | ... | @@ -333,7 +399,14 @@ impl Comp { |
| 333 | 399 | if tools.get(&name).is_some() || node_names.contains(name.as_str()) { |
| 334 | 400 | continue; |
| 335 | 401 | } |
| 336 | | let Some(modifier) = root_tools.and_then(|t| t.get_table(&name)) else { |
| 402 | // Modifiers already nested inside a copied group travel with it. |
| 403 | let nested_in_copy = tools |
| 404 | .entries |
| 405 | .iter() |
| 406 | .filter_map(|(_, v)| v.as_table()?.get_table("Tools")) |
| 407 | .any(|inner| find_raw_tool(inner, &name).is_some()); |
| 408 | let Some(modifier) = root_tools.and_then(|t| find_raw_tool(t, &name)).filter(|_| !nested_in_copy) |
| 409 | else { |
| 337 | 410 | continue; |
| 338 | 411 | }; |
| 339 | 412 | let mut found = HashSet::new(); |
| ... | ... | @@ -378,9 +451,7 @@ impl Comp { |
| 378 | 451 | let pasted_set: HashSet<&str> = pasted_names.iter().map(String::as_str).collect(); |
| 379 | 452 | |
| 380 | 453 | 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) |
| 454 | pasted_set.contains(name) || self.is_linkable_external(name) |
| 384 | 455 | }); |
| 385 | 456 | |
| 386 | 457 | let mut reserved: HashSet<String> = self.nodes.iter().map(|n| n.name.clone()).collect(); |
| ... | ... | @@ -447,165 +518,12 @@ impl Comp { |
| 447 | 518 | Ok(created) |
| 448 | 519 | } |
| 449 | 520 | |
| 450 | | /// Duplicates the selected nodes at `pos + offset` with unique names. |
| 451 | | /// Preserves internal wires between duplicated nodes, keeps external wires intact, |
| 452 | | /// and clones owned `BezierSpline` / `PolyPath` modifiers with fresh unique names. |
| 521 | /// Duplicates the selected nodes at `pos + offset` with unique names, as a copy + paste: |
| 522 | /// wires between duplicated nodes are preserved, wires to other nodes stay intact, and owned |
| 523 | /// modifiers and group contents are cloned. Returns the new top-level nodes. |
| 453 | 524 | pub fn duplicate_nodes(&mut self, ids: &[NodeId], offset: [f32; 2]) -> Vec<NodeId> { |
| 454 | | let mut unique_ids = Vec::new(); |
| 455 | | let mut seen = HashSet::new(); |
| 456 | | for &id in ids { |
| 457 | | if id.0 < self.nodes.len() && seen.insert(id.0) { |
| 458 | | unique_ids.push(id); |
| 459 | | } |
| 460 | | } |
| 461 | | if unique_ids.is_empty() { |
| 462 | | return Vec::new(); |
| 463 | | } |
| 464 | | |
| 465 | | // Reserve names for all duplicated nodes first so internal wires can be remapped cleanly. |
| 466 | | let mut reserved: HashSet<String> = HashSet::new(); |
| 467 | | let mut node_name_map: HashMap<String, String> = HashMap::new(); |
| 468 | | let mut dup_specs: Vec<(NodeId, String)> = Vec::with_capacity(unique_ids.len()); |
| 469 | | |
| 470 | | for &id in &unique_ids { |
| 471 | | let orig_name = self.nodes[id.0].name.clone(); |
| 472 | | let new_name = self.generate_unique_name_excluding(&orig_name, &reserved); |
| 473 | | reserved.insert(new_name.clone()); |
| 474 | | node_name_map.insert(orig_name, new_name.clone()); |
| 475 | | dup_specs.push((id, new_name)); |
| 476 | | } |
| 477 | | |
| 478 | | // Clone `BezierSpline` and `PolyPath` modifiers referenced by the duplicated nodes. |
| 479 | | let mut mod_name_map: HashMap<String, String> = HashMap::new(); |
| 480 | | let mut cloned_splines: Vec<(String, BezierSpline, Option<LuaTable>)> = Vec::new(); |
| 481 | | let mut cloned_paths: Vec<(String, PolyPath, Option<LuaTable>)> = Vec::new(); |
| 482 | | |
| 483 | | for &(id, _) in &dup_specs { |
| 484 | | let mut input_ports: Vec<String> = self.nodes[id.0].inputs.keys().cloned().collect(); |
| 485 | | input_ports.sort(); |
| 486 | | for port in input_ports { |
| 487 | | let Some(src_op) = self.nodes[id.0] |
| 488 | | .inputs |
| 489 | | .get(&port) |
| 490 | | .and_then(|b| b.source_op.clone()) |
| 491 | | else { |
| 492 | | continue; |
| 493 | | }; |
| 494 | | if mod_name_map.contains_key(&src_op) || node_name_map.contains_key(&src_op) { |
| 495 | | continue; |
| 496 | | } |
| 497 | | if let Some(orig_spline) = self.splines.get(&src_op).cloned() { |
| 498 | | let new_mod = self.generate_unique_name_excluding(&src_op, &reserved); |
| 499 | | reserved.insert(new_mod.clone()); |
| 500 | | let mut sp = orig_spline; |
| 501 | | sp.name = new_mod.clone(); |
| 502 | | let raw_tbl = self |
| 503 | | .raw_root |
| 504 | | .as_ref() |
| 505 | | .and_then(|r| r.get_table("Tools")) |
| 506 | | .and_then(|t| t.get_table(&src_op)) |
| 507 | | .cloned(); |
| 508 | | mod_name_map.insert(src_op, new_mod.clone()); |
| 509 | | cloned_splines.push((new_mod, sp, raw_tbl)); |
| 510 | | } else if let Some(orig_path) = self.poly_paths.get(&src_op).cloned() { |
| 511 | | let new_mod = self.generate_unique_name_excluding(&src_op, &reserved); |
| 512 | | reserved.insert(new_mod.clone()); |
| 513 | | let mut pp = orig_path; |
| 514 | | pp.name = new_mod.clone(); |
| 515 | | |
| 516 | | let mut raw_tbl = self |
| 517 | | .raw_root |
| 518 | | .as_ref() |
| 519 | | .and_then(|r| r.get_table("Tools")) |
| 520 | | .and_then(|t| t.get_table(&src_op)) |
| 521 | | .cloned(); |
| 522 | | |
| 523 | | // Also clone PolyPath's displacement spline if present. |
| 524 | | if let Some(orig_disp) = pp.displacement_op.clone() { |
| 525 | | let new_disp = if let Some(existing) = mod_name_map.get(&orig_disp) { |
| 526 | | existing.clone() |
| 527 | | } else if let Some(disp_sp) = self.splines.get(&orig_disp).cloned() { |
| 528 | | let fresh = self.generate_unique_name_excluding(&orig_disp, &reserved); |
| 529 | | reserved.insert(fresh.clone()); |
| 530 | | let mut sp = disp_sp; |
| 531 | | sp.name = fresh.clone(); |
| 532 | | let disp_raw = self |
| 533 | | .raw_root |
| 534 | | .as_ref() |
| 535 | | .and_then(|r| r.get_table("Tools")) |
| 536 | | .and_then(|t| t.get_table(&orig_disp)) |
| 537 | | .cloned(); |
| 538 | | mod_name_map.insert(orig_disp.clone(), fresh.clone()); |
| 539 | | cloned_splines.push((fresh.clone(), sp, disp_raw)); |
| 540 | | fresh |
| 541 | | } else { |
| 542 | | orig_disp.clone() |
| 543 | | }; |
| 544 | | if new_disp != orig_disp { |
| 545 | | pp.displacement_op = Some(new_disp.clone()); |
| 546 | | if let Some(ref mut tbl) = raw_tbl { |
| 547 | | rewrite_source_op_in_table(tbl, &orig_disp, &new_disp); |
| 548 | | } |
| 549 | | } |
| 550 | | } |
| 551 | | |
| 552 | | mod_name_map.insert(src_op, new_mod.clone()); |
| 553 | | cloned_paths.push((new_mod, pp, raw_tbl)); |
| 554 | | } |
| 555 | | } |
| 556 | | } |
| 557 | | |
| 558 | | // Insert cloned modifiers into `Comp` and `raw_root.Tools`. |
| 559 | | for (name, sp, raw_tbl) in cloned_splines { |
| 560 | | self.splines.insert(name.clone(), sp); |
| 561 | | if let (Some(root), Some(tbl)) = (self.raw_root.as_mut(), raw_tbl) { |
| 562 | | let tools = ensure_table_mut(root, "Tools", Some("ordered")); |
| 563 | | tools.set(LuaKey::Str(name), LuaValue::Table(tbl)); |
| 564 | | } |
| 565 | | } |
| 566 | | for (name, pp, raw_tbl) in cloned_paths { |
| 567 | | self.poly_paths.insert(name.clone(), pp); |
| 568 | | if let (Some(root), Some(tbl)) = (self.raw_root.as_mut(), raw_tbl) { |
| 569 | | let tools = ensure_table_mut(root, "Tools", Some("ordered")); |
| 570 | | tools.set(LuaKey::Str(name), LuaValue::Table(tbl)); |
| 571 | | } |
| 572 | | } |
| 573 | | |
| 574 | | // Build and insert the duplicated nodes. |
| 575 | | let mut created_ids = Vec::with_capacity(dup_specs.len()); |
| 576 | | for (orig_id, new_name) in dup_specs { |
| 577 | | let mut cloned = self.nodes[orig_id.0].clone(); |
| 578 | | let new_id = NodeId(self.nodes.len()); |
| 579 | | cloned.id = new_id; |
| 580 | | cloned.name = new_name.clone(); |
| 581 | | cloned.pos = [cloned.pos[0] + offset[0], cloned.pos[1] + offset[1]]; |
| 582 | | |
| 583 | | for binding in cloned.inputs.values_mut() { |
| 584 | | if let Some(src) = binding.source_op.as_mut() { |
| 585 | | if let Some(mapped) = node_name_map.get(src).or_else(|| mod_name_map.get(src)) { |
| 586 | | *src = mapped.clone(); |
| 587 | | } |
| 588 | | } |
| 589 | | } |
| 590 | | |
| 591 | | // Update `cloned.raw` ViewInfo.Pos and SourceOp references. |
| 592 | | set_view_info_pos(&mut cloned.raw, cloned.pos); |
| 593 | | for (old_s, new_s) in node_name_map.iter().chain(mod_name_map.iter()) { |
| 594 | | rewrite_source_op_in_table(&mut cloned.raw, old_s, new_s); |
| 595 | | } |
| 596 | | |
| 597 | | let raw_copy = cloned.raw.clone(); |
| 598 | | self.nodes.push(cloned); |
| 599 | | self.node_by_name.insert(new_name.clone(), new_id); |
| 600 | | if let Some(root) = self.raw_root.as_mut() { |
| 601 | | let tools = ensure_table_mut(root, "Tools", Some("ordered")); |
| 602 | | tools.set(LuaKey::Str(new_name), LuaValue::Table(raw_copy)); |
| 603 | | } |
| 604 | | created_ids.push(new_id); |
| 605 | | } |
| 606 | | |
| 607 | | self.revision += 1; |
| 608 | | created_ids |
| 525 | let snippet = self.export_fusion_clipboard(ids); |
| 526 | self.paste_fusion_clipboard(&snippet, (offset[0], offset[1])).unwrap_or_default() |
| 609 | 527 | } |
| 610 | 528 | |
| 611 | 529 | fn generate_unique_name_excluding(&self, hint: &str, reserved: &HashSet<String>) -> String { |
| ... | ... | @@ -645,45 +563,81 @@ impl Comp { |
| 645 | 563 | return Err(format!("a node or modifier named '{trimmed}' already exists")); |
| 646 | 564 | } |
| 647 | 565 | |
| 566 | // A private (group-internal) tool is only visible inside its group; a top-level tool is |
| 567 | // visible everywhere except inside groups that define a tool of the same name. |
| 568 | let owner = if self.nodes[id.0].internal { |
| 569 | (0..self.nodes.len()).skip(id.0 + 1).find(|&g| self.group_children(g).contains(&id.0)) |
| 570 | } else { |
| 571 | None |
| 572 | }; |
| 573 | let affected: Vec<usize> = match owner { |
| 574 | Some(g) => self.group_children(g), |
| 575 | None => { |
| 576 | let mut shadowed: HashSet<usize> = HashSet::new(); |
| 577 | for g in 0..self.nodes.len() { |
| 578 | let kids = self.group_children(g); |
| 579 | if kids.iter().any(|&k| self.nodes[k].name == old_name) { |
| 580 | shadowed.extend(kids); |
| 581 | } |
| 582 | } |
| 583 | (0..self.nodes.len()).filter(|i| !shadowed.contains(i)).collect() |
| 584 | } |
| 585 | }; |
| 586 | let scope_name = owner.map(|g| self.nodes[g].name.clone()); |
| 587 | |
| 648 | 588 | self.nodes[id.0].name = trimmed.to_owned(); |
| 649 | 589 | if self.node_by_name.get(&old_name) == Some(&id) { |
| 650 | 590 | self.node_by_name.remove(&old_name); |
| 651 | 591 | } |
| 652 | 592 | self.node_by_name.insert(trimmed.to_owned(), id); |
| 653 | 593 | |
| 654 | | // Rewrite all `SourceOp` references across all nodes' typed `inputs` and `raw` tables. |
| 655 | | for node in &mut self.nodes { |
| 594 | for &i in &affected { |
| 595 | let node = &mut self.nodes[i]; |
| 656 | 596 | for binding in node.inputs.values_mut() { |
| 657 | 597 | if binding.source_op.as_deref() == Some(old_name.as_str()) { |
| 658 | 598 | binding.source_op = Some(trimmed.to_owned()); |
| 659 | 599 | } |
| 660 | 600 | } |
| 661 | | rewrite_source_op_in_table(&mut node.raw, &old_name, trimmed); |
| 601 | rewrite_source_op_in_scope(&mut node.raw, &old_name, trimmed, false); |
| 662 | 602 | } |
| 663 | 603 | |
| 664 | | // Rewrite `SourceOp` inside `shakes` modifiers. |
| 665 | | for shake in self.shakes.values_mut() { |
| 666 | | for binding in shake.inputs.values_mut() { |
| 667 | | if binding.source_op.as_deref() == Some(old_name.as_str()) { |
| 668 | | binding.source_op = Some(trimmed.to_owned()); |
| 604 | let renames = HashMap::from([(old_name.clone(), trimmed.to_owned())]); |
| 605 | if owner.is_none() { |
| 606 | for shake in self.shakes.values_mut() { |
| 607 | for binding in shake.inputs.values_mut() { |
| 608 | if binding.source_op.as_deref() == Some(old_name.as_str()) { |
| 609 | binding.source_op = Some(trimmed.to_owned()); |
| 610 | } |
| 611 | } |
| 612 | } |
| 613 | } |
| 614 | for em in self.expression_modifiers.values_mut() { |
| 615 | for key in EXPRESSION_FORMULA_INPUTS { |
| 616 | if let Some(ParamValue::Text(formula)) = em.inputs.get_mut(*key).and_then(|b| b.value.as_mut()) { |
| 617 | *formula = rename_expression_idents(formula, &renames); |
| 669 | 618 | } |
| 670 | 619 | } |
| 671 | 620 | } |
| 672 | 621 | |
| 673 | | // Rename key in `raw_root.Tools` in place (preserving order) and rewrite all SourceOp refs. |
| 622 | // Rename the key in place (preserving order) within the owning `Tools` table and rewrite refs. |
| 674 | 623 | if let Some(root) = self.raw_root.as_mut() { |
| 675 | | if let Some(tools) = root.get_table_mut("Tools") { |
| 676 | | for (k, _) in &mut tools.entries { |
| 677 | | if let LuaKey::Str(s) = k { |
| 678 | | if s == &old_name { |
| 679 | | *s = trimmed.to_owned(); |
| 624 | let scope = match &scope_name { |
| 625 | Some(group) => root.get_table_mut("Tools").and_then(|t| find_raw_tool_mut(t, group)), |
| 626 | None => Some(&mut *root), |
| 627 | }; |
| 628 | if let Some(scope) = scope { |
| 629 | rewrite_source_op_in_scope(scope, &old_name, trimmed, true); |
| 630 | if let Some(tools) = scope.get_table_mut("Tools") { |
| 631 | for (k, _) in &mut tools.entries { |
| 632 | if matches!(k, LuaKey::Str(s) if s == &old_name) { |
| 633 | *k = LuaKey::Str(trimmed.to_owned()); |
| 680 | 634 | break; |
| 681 | 635 | } |
| 682 | 636 | } |
| 683 | 637 | } |
| 638 | rewrite_formulas_deep(scope, &renames); |
| 684 | 639 | } |
| 685 | | rewrite_source_op_in_table(root, &old_name, trimmed); |
| 686 | | if root.get_str("ActiveTool") == Some(old_name.as_str()) { |
| 640 | if owner.is_none() && root.get_str("ActiveTool") == Some(old_name.as_str()) { |
| 687 | 641 | root.set( |
| 688 | 642 | LuaKey::Str("ActiveTool".to_owned()), |
| 689 | 643 | LuaValue::String(trimmed.to_owned()), |
| ... | ... | @@ -1011,6 +965,8 @@ impl Comp { |
| 1011 | 965 | } |
| 1012 | 966 | |
| 1013 | 967 | /// Removes the keyframe at `frame` from `spline_name`. Returns `true` if a keyframe was deleted. |
| 968 | /// Deleting a spline's last keyframe removes the spline and leaves every input it drove with |
| 969 | /// that keyframe's value as a static `Value`. |
| 1014 | 970 | pub fn delete_keyframe(&mut self, spline_name: &str, frame: f64) -> bool { |
| 1015 | 971 | let Some(sp) = self.splines.get_mut(spline_name) else { |
| 1016 | 972 | return false; |
| ... | ... | @@ -1018,11 +974,32 @@ impl Comp { |
| 1018 | 974 | let Some(pos) = sp |
| 1019 | 975 | .keyframes |
| 1020 | 976 | .iter() |
| 1021 | | .position(|kf| (kf.time - frame).abs() < 1e-6) |
| 977 | .position(|kf| (kf.time - frame).abs() < KEYFRAME_EPS) |
| 1022 | 978 | else { |
| 1023 | 979 | return false; |
| 1024 | 980 | }; |
| 1025 | | sp.keyframes.remove(pos); |
| 981 | let removed = sp.keyframes.remove(pos); |
| 982 | if sp.keyframes.is_empty() { |
| 983 | self.splines.remove(spline_name); |
| 984 | let value = ParamValue::Number(removed.value); |
| 985 | for node in &mut self.nodes { |
| 986 | for (port, binding) in &mut node.inputs { |
| 987 | if binding.source_op.as_deref() != Some(spline_name) { |
| 988 | continue; |
| 989 | } |
| 990 | binding.source_op = None; |
| 991 | binding.source_output = None; |
| 992 | binding.value = Some(value.clone()); |
| 993 | let port_tbl = ensure_table_mut(ensure_table_mut(&mut node.raw, "Inputs", None), port, Some("Input")); |
| 994 | port_tbl.remove(&LuaKey::Str("SourceOp".to_owned())); |
| 995 | port_tbl.remove(&LuaKey::Str("Source".to_owned())); |
| 996 | port_tbl.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(&value)); |
| 997 | } |
| 998 | } |
| 999 | if let Some(tools) = self.raw_root.as_mut().and_then(|r| r.get_table_mut("Tools")) { |
| 1000 | remove_tools_recursive(tools, &HashSet::from([spline_name.to_owned()])); |
| 1001 | } |
| 1002 | } |
| 1026 | 1003 | self.revision += 1; |
| 1027 | 1004 | true |
| 1028 | 1005 | } |
| ... | ... | @@ -1116,6 +1093,8 @@ impl CompHistory { |
| 1116 | 1093 | |
| 1117 | 1094 | /// Records the current state of `comp` as the clean saved point. |
| 1118 | 1095 | pub fn mark_saved(&mut self, comp: &Comp) { |
| 1096 | // Edits after a save must never coalesce into the saved undo entry. |
| 1097 | self.break_coalescing(); |
| 1119 | 1098 | self.saved_undo_depth = Some(self.undo_stack.len()); |
| 1120 | 1099 | self.saved_revision = Some(comp.revision); |
| 1121 | 1100 | } |
| ... | ... | @@ -1234,7 +1213,7 @@ impl CompHistory { |
| 1234 | 1213 | return false; |
| 1235 | 1214 | }; |
| 1236 | 1215 | let prev_rev = comp.revision; |
| 1237 | | *comp = snapshot; |
| 1216 | restore_snapshot(comp, snapshot); |
| 1238 | 1217 | if comp.revision != prev_rev { |
| 1239 | 1218 | comp.revision = prev_rev.max(comp.revision) + 1; |
| 1240 | 1219 | } |
| ... | ... | @@ -1272,7 +1251,7 @@ impl CompHistory { |
| 1272 | 1251 | coalesce_key: None, |
| 1273 | 1252 | }; |
| 1274 | 1253 | self.redo_stack.push(redo_entry); |
| 1275 | | *comp = entry.snapshot; |
| 1254 | restore_snapshot(comp, entry.snapshot); |
| 1276 | 1255 | comp.revision = prev_rev.max(comp.revision) + 1; |
| 1277 | 1256 | true |
| 1278 | 1257 | } |
| ... | ... | @@ -1290,7 +1269,7 @@ impl CompHistory { |
| 1290 | 1269 | coalesce_key: None, |
| 1291 | 1270 | }; |
| 1292 | 1271 | self.undo_stack.push_back(undo_entry); |
| 1293 | | *comp = entry.snapshot; |
| 1272 | restore_snapshot(comp, entry.snapshot); |
| 1294 | 1273 | comp.revision = prev_rev.max(comp.revision) + 1; |
| 1295 | 1274 | true |
| 1296 | 1275 | } |
| ... | ... | @@ -1311,6 +1290,14 @@ impl CompHistory { |
| 1311 | 1290 | } |
| 1312 | 1291 | } |
| 1313 | 1292 | |
| 1293 | /// Replaces `comp` with `snapshot`, keeping the live file identity so a Save As followed by undo |
| 1294 | /// never points Save at the file the snapshot came from. |
| 1295 | fn restore_snapshot(comp: &mut Comp, mut snapshot: Comp) { |
| 1296 | snapshot.path = comp.path.take(); |
| 1297 | snapshot.name = std::mem::take(&mut comp.name); |
| 1298 | *comp = snapshot; |
| 1299 | } |
| 1300 | |
| 1314 | 1301 | fn sanitize_lua_ident(raw: &str) -> String { |
| 1315 | 1302 | let mut out = String::with_capacity(raw.len()); |
| 1316 | 1303 | for ch in raw.chars() { |
| ... | ... | @@ -1353,19 +1340,49 @@ fn collect_source_ops_in_table(tbl: &LuaTable, out: &mut HashSet<String>) { |
| 1353 | 1340 | } |
| 1354 | 1341 | } |
| 1355 | 1342 | |
| 1356 | | fn rewrite_source_op_in_table(tbl: &mut LuaTable, old_name: &str, new_name: &str) { |
| 1343 | /// Rewrites `SourceOp = old_name` in `tbl`, skipping nested groups that define their own tool |
| 1344 | /// called `old_name` (inside them the name refers to that private tool). `is_scope_root` exempts |
| 1345 | /// `tbl` itself from that check. |
| 1346 | fn rewrite_source_op_in_scope(tbl: &mut LuaTable, old_name: &str, new_name: &str, is_scope_root: bool) { |
| 1347 | if !is_scope_root && tbl.get_table("Tools").is_some_and(|t| t.get(old_name).is_some()) { |
| 1348 | return; |
| 1349 | } |
| 1357 | 1350 | for (k, v) in &mut tbl.entries { |
| 1358 | | if let LuaKey::Str(key) = k { |
| 1359 | | if key == "SourceOp" { |
| 1360 | | if let LuaValue::String(s) = v { |
| 1361 | | if s == old_name { |
| 1362 | | *s = new_name.to_owned(); |
| 1363 | | } |
| 1351 | if matches!(k, LuaKey::Str(key) if key == "SourceOp") { |
| 1352 | if let LuaValue::String(s) = v { |
| 1353 | if s == old_name { |
| 1354 | *s = new_name.to_owned(); |
| 1364 | 1355 | } |
| 1365 | 1356 | } |
| 1366 | 1357 | } |
| 1367 | 1358 | if let Some(sub) = v.as_table_mut() { |
| 1368 | | rewrite_source_op_in_table(sub, old_name, new_name); |
| 1359 | rewrite_source_op_in_scope(sub, old_name, new_name, false); |
| 1360 | } |
| 1361 | } |
| 1362 | } |
| 1363 | |
| 1364 | /// Counts the flow-node (non-modifier) tools in `tools`, including inside nested groups. |
| 1365 | fn count_flow_tools<'a>(tools: &'a LuaTable, out: &mut HashMap<&'a str, usize>) { |
| 1366 | for (key, value) in &tools.entries { |
| 1367 | let (LuaKey::Str(name), Some(tool)) = (key, value.as_table()) else { continue }; |
| 1368 | if is_modifier_type(tool.tag.as_deref().unwrap_or("Unknown")) { |
| 1369 | continue; |
| 1370 | } |
| 1371 | *out.entry(name.as_str()).or_default() += 1; |
| 1372 | if let Some(inner) = tool.get_table("Tools") { |
| 1373 | count_flow_tools(inner, out); |
| 1374 | } |
| 1375 | } |
| 1376 | } |
| 1377 | |
| 1378 | /// Removes tools named in `names` from `tools` and every nested `Tools` table. |
| 1379 | fn remove_tools_recursive(tools: &mut LuaTable, names: &HashSet<String>) { |
| 1380 | tools |
| 1381 | .entries |
| 1382 | .retain(|(k, _)| !matches!(k, LuaKey::Str(name) if names.contains(name))); |
| 1383 | for (_, v) in &mut tools.entries { |
| 1384 | if let Some(inner) = v.as_table_mut().and_then(|t| t.get_table_mut("Tools")) { |
| 1385 | remove_tools_recursive(inner, names); |
| 1369 | 1386 | } |
| 1370 | 1387 | } |
| 1371 | 1388 | } |
| ... | ... | @@ -1401,6 +1418,7 @@ fn rename_tools(tools: &mut LuaTable, renames: &HashMap<String, String>) { |
| 1401 | 1418 | } |
| 1402 | 1419 | |
| 1403 | 1420 | fn rewrite_references(tbl: &mut LuaTable, renames: &HashMap<String, String>) { |
| 1421 | rewrite_formula_values(tbl, renames); |
| 1404 | 1422 | for (key, value) in &mut tbl.entries { |
| 1405 | 1423 | match (key, value) { |
| 1406 | 1424 | (LuaKey::Str(k), LuaValue::String(s)) if k == "SourceOp" => { |
| ... | ... | @@ -1417,22 +1435,48 @@ fn rewrite_references(tbl: &mut LuaTable, renames: &HashMap<String, String>) { |
| 1417 | 1435 | } |
| 1418 | 1436 | } |
| 1419 | 1437 | |
| 1438 | /// Rewrites the formula strings of an `Expression` modifier table (not recursive). |
| 1439 | fn rewrite_formula_values(tbl: &mut LuaTable, renames: &HashMap<String, String>) { |
| 1440 | if tbl.tag.as_deref() != Some("Expression") { |
| 1441 | return; |
| 1442 | } |
| 1443 | let Some(inputs) = tbl.get_table_mut("Inputs") else { return }; |
| 1444 | for key in EXPRESSION_FORMULA_INPUTS { |
| 1445 | if let Some(LuaValue::String(formula)) = inputs.get_table_mut(key).and_then(|i| i.get_mut("Value")) { |
| 1446 | *formula = rename_expression_idents(formula, renames); |
| 1447 | } |
| 1448 | } |
| 1449 | } |
| 1450 | |
| 1451 | fn rewrite_formulas_deep(tbl: &mut LuaTable, renames: &HashMap<String, String>) { |
| 1452 | rewrite_formula_values(tbl, renames); |
| 1453 | for (_, value) in &mut tbl.entries { |
| 1454 | if let Some(sub) = value.as_table_mut() { |
| 1455 | rewrite_formulas_deep(sub, renames); |
| 1456 | } |
| 1457 | } |
| 1458 | } |
| 1459 | |
| 1460 | /// Renames whole-word identifiers in `expr`, leaving property names (`Other.Size`) alone. |
| 1420 | 1461 | fn rename_expression_idents(expr: &str, renames: &HashMap<String, String>) -> String { |
| 1421 | 1462 | let mut out = String::with_capacity(expr.len()); |
| 1422 | 1463 | 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)); |
| 1464 | let mut prev = None; |
| 1465 | let flush = |word: &mut String, out: &mut String, prev: Option<char>| { |
| 1466 | let renamed = renames.get(word.as_str()).filter(|_| prev != Some('.')); |
| 1467 | out.push_str(renamed.map_or(word.as_str(), String::as_str)); |
| 1425 | 1468 | word.clear(); |
| 1426 | 1469 | }; |
| 1427 | 1470 | for ch in expr.chars() { |
| 1428 | 1471 | if ch.is_ascii_alphanumeric() || ch == '_' { |
| 1429 | 1472 | word.push(ch); |
| 1430 | 1473 | } else { |
| 1431 | | flush(&mut word, &mut out); |
| 1474 | flush(&mut word, &mut out, prev); |
| 1432 | 1475 | out.push(ch); |
| 1476 | prev = Some(ch); |
| 1433 | 1477 | } |
| 1434 | 1478 | } |
| 1435 | | flush(&mut word, &mut out); |
| 1479 | flush(&mut word, &mut out, prev); |
| 1436 | 1480 | out |
| 1437 | 1481 | } |
| 1438 | 1482 | |
| ... | ... | @@ -1465,9 +1509,16 @@ fn upsert_keyframe(spline: &mut BezierSpline, frame: f64, value: f64) { |
| 1465 | 1509 | if let Some(existing) = spline |
| 1466 | 1510 | .keyframes |
| 1467 | 1511 | .iter_mut() |
| 1468 | | .find(|kf| (kf.time - frame).abs() < 1e-6) |
| 1512 | .find(|kf| (kf.time - frame).abs() < KEYFRAME_EPS) |
| 1469 | 1513 | { |
| 1514 | // Handles are absolute coordinates, so they travel with the key. |
| 1515 | let (dt, dv) = (frame - existing.time, value - existing.value); |
| 1516 | existing.time = frame; |
| 1470 | 1517 | existing.value = value; |
| 1518 | for handle in [&mut existing.lh, &mut existing.rh].into_iter().flatten() { |
| 1519 | handle[0] += dt; |
| 1520 | handle[1] += dv; |
| 1521 | } |
| 1471 | 1522 | } else { |
| 1472 | 1523 | spline.keyframes.push(Keyframe::new(frame, value)); |
| 1473 | 1524 | spline.sort(); |
| ... | ... | @@ -2278,4 +2329,284 @@ mod tests { |
| 2278 | 2329 | assert!(!history.can_undo()); |
| 2279 | 2330 | assert!(!history.in_group()); |
| 2280 | 2331 | } |
| 2332 | |
| 2333 | const TWO_GROUPS: &str = r#"Composition { |
| 2334 | 	Tools = ordered() { |
| 2335 | 		BG = Background { }, |
| 2336 | 		GA = GroupOperator { |
| 2337 | 			Outputs = { Out = InstanceOutput { SourceOp = "Same", Source = "Output", }, }, |
| 2338 | 			Tools = ordered() { |
| 2339 | 				Same = Blur { Inputs = { XBlurSize = Input { SourceOp = "SameSize", Source = "Value", }, }, }, |
| 2340 | 				SameSize = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, }, |
| 2341 | 			}, |
| 2342 | 		}, |
| 2343 | 		GB = GroupOperator { |
| 2344 | 			Outputs = { Out = InstanceOutput { SourceOp = "Same", Source = "Output", }, }, |
| 2345 | 			Tools = ordered() { |
| 2346 | 				Same = Blur { }, |
| 2347 | 			}, |
| 2348 | 		}, |
| 2349 | 	}, |
| 2350 | }"#; |
| 2351 | |
| 2352 | fn tool_names(tools: &LuaTable) -> Vec<&str> { |
| 2353 | tools |
| 2354 | .entries |
| 2355 | .iter() |
| 2356 | .filter_map(|(k, _)| if let LuaKey::Str(s) = k { Some(s.as_str()) } else { None }) |
| 2357 | .collect() |
| 2358 | } |
| 2359 | |
| 2360 | #[test] |
| 2361 | fn mark_saved_stops_later_edits_coalescing_into_the_saved_step() { |
| 2362 | let mut comp = sample_comp(); |
| 2363 | let mut history = CompHistory::new(); |
| 2364 | let bg = comp.find_node("BG1").unwrap(); |
| 2365 | |
| 2366 | history.push_coalesced(&comp, "Drag", "drag"); |
| 2367 | comp.set_node_pos(bg, [1.0, 1.0]); |
| 2368 | history.mark_saved(&comp); |
| 2369 | assert!(!history.is_dirty(&comp)); |
| 2370 | |
| 2371 | history.push_coalesced(&comp, "Drag", "drag"); |
| 2372 | comp.set_node_pos(bg, [2.0, 2.0]); |
| 2373 | assert_eq!(history.undo_len(), 2); |
| 2374 | assert!(history.is_dirty(&comp)); |
| 2375 | } |
| 2376 | |
| 2377 | #[test] |
| 2378 | fn undo_and_redo_keep_the_live_file_identity() { |
| 2379 | let mut comp = sample_comp(); |
| 2380 | comp.path = Some("/tmp/original.comp".into()); |
| 2381 | comp.name = "original".to_owned(); |
| 2382 | let mut history = CompHistory::new(); |
| 2383 | let bg = comp.find_node("BG1").unwrap(); |
| 2384 | |
| 2385 | history.push_snapshot(&comp, "Move"); |
| 2386 | comp.set_node_pos(bg, [9.0, 9.0]); |
| 2387 | comp.path = Some("/tmp/save_as.comp".into()); |
| 2388 | comp.name = "save_as".to_owned(); |
| 2389 | |
| 2390 | assert!(history.undo(&mut comp)); |
| 2391 | assert_eq!((comp.path.as_deref(), comp.name.as_str()), (Some(Path::new("/tmp/save_as.comp")), "save_as")); |
| 2392 | assert!(history.redo(&mut comp)); |
| 2393 | assert_eq!((comp.path.as_deref(), comp.name.as_str()), (Some(Path::new("/tmp/save_as.comp")), "save_as")); |
| 2394 | } |
| 2395 | |
| 2396 | #[test] |
| 2397 | fn deleting_a_group_removes_its_private_tools_and_modifiers() { |
| 2398 | let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap(); |
| 2399 | let g = comp.find_node("Group1").unwrap(); |
| 2400 | let deleted = comp.delete_nodes(&[g]); |
| 2401 | assert_eq!(deleted, ["Group1", "Inner1"]); |
| 2402 | assert!(comp.nodes.is_empty()); |
| 2403 | assert!(comp.splines.is_empty()); |
| 2404 | assert!(tool_names(comp.raw_root.as_ref().unwrap().get_table("Tools").unwrap()).is_empty()); |
| 2405 | } |
| 2406 | |
| 2407 | #[test] |
| 2408 | fn deleting_a_node_keeps_splines_still_used_by_expression_modifiers() { |
| 2409 | let src = r#"Composition { |
| 2410 | 	Tools = ordered() { |
| 2411 | 		N = Transform { Inputs = { Angle = Input { SourceOp = "Shared", Source = "Value", }, Size = Input { SourceOp = "E", Source = "NumberResult", }, }, }, |
| 2412 | 		M = Transform { Inputs = { Angle = Input { SourceOp = "Own", Source = "Value", }, Size = Input { SourceOp = "E2", Source = "NumberResult", }, }, }, |
| 2413 | 		E = Expression { Inputs = { n1 = Input { SourceOp = "Shared", Source = "Value", }, NumberExpression = Input { Value = "n1", }, }, }, |
| 2414 | 		E2 = Expression { Inputs = { n1 = Input { SourceOp = "Own", Source = "Value", }, NumberExpression = Input { Value = "n1", }, }, }, |
| 2415 | 		Shared = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, }, |
| 2416 | 		Own = BezierSpline { KeyFrames = { [0] = { 2, Flags = { Linear = true } } }, }, |
| 2417 | 	}, |
| 2418 | }"#; |
| 2419 | let mut comp = Comp::from_fusion_str(src).unwrap(); |
| 2420 | comp.delete_nodes(&[comp.find_node("M").unwrap()]); |
| 2421 | assert!(!comp.expression_modifiers.contains_key("E2")); |
| 2422 | assert!(!comp.splines.contains_key("Own")); |
| 2423 | assert!(comp.expression_modifiers.contains_key("E")); |
| 2424 | assert!(comp.splines.contains_key("Shared")); |
| 2425 | |
| 2426 | // Deleting the other owner prunes the expression modifier and its spline. |
| 2427 | let mut comp = Comp::from_fusion_str(src).unwrap(); |
| 2428 | comp.delete_nodes(&[comp.find_node("N").unwrap()]); |
| 2429 | assert!(!comp.expression_modifiers.contains_key("E")); |
| 2430 | assert!(!comp.splines.contains_key("Shared")); |
| 2431 | |
| 2432 | // A spline referenced by a surviving (unpruned) expression modifier outlives its owner. |
| 2433 | let with_orphan = src.replace("\t},\n}", "\t\tEO = Expression { Inputs = { n1 = Input { SourceOp = \"Shared\", Source = \"Value\", }, }, },\n\t},\n}"); |
| 2434 | let mut comp = Comp::from_fusion_str(&with_orphan).unwrap(); |
| 2435 | comp.delete_nodes(&[comp.find_node("N").unwrap()]); |
| 2436 | assert!(comp.expression_modifiers.contains_key("EO")); |
| 2437 | assert!(comp.splines.contains_key("Shared")); |
| 2438 | } |
| 2439 | |
| 2440 | #[test] |
| 2441 | fn export_includes_modifiers_nested_in_a_copied_internal_node_once() { |
| 2442 | let comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap(); |
| 2443 | let inner = comp.find_node("Inner1").unwrap(); |
| 2444 | let clip = comp.export_fusion_clipboard(&[inner]); |
| 2445 | let parsed = parse_lua(&clip).unwrap(); |
| 2446 | let tools = parsed.as_table().unwrap().get_table("Tools").unwrap(); |
| 2447 | assert_eq!(tool_names(tools), ["Inner1", "Inner1Size"]); |
| 2448 | |
| 2449 | let whole = comp.export_fusion_clipboard(&[comp.find_node("Group1").unwrap()]); |
| 2450 | assert_eq!(whole.matches("Inner1Size = BezierSpline").count(), 1, "{whole}"); |
| 2451 | } |
| 2452 | |
| 2453 | #[test] |
| 2454 | fn paste_never_links_to_group_private_tools() { |
| 2455 | let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap(); |
| 2456 | let snippet = r#"{ Tools = ordered() { T = Transform { Inputs = { |
| 2457 | Input = Input { SourceOp = "Inner1", Source = "Output", }, |
| 2458 | Mask = Input { SourceOp = "Group1", Source = "Output", }, |
| 2459 | Angle = Input { SourceOp = "Inner1Size", Source = "Value", }, |
| 2460 | }, }, }, }"#; |
| 2461 | let ids = comp.paste_fusion_clipboard(snippet, (0.0, 0.0)).unwrap(); |
| 2462 | let t = comp.node(ids[0]); |
| 2463 | assert_eq!(t.connected_node("Input"), None); |
| 2464 | assert_eq!(t.connected_node("Angle"), None); |
| 2465 | assert_eq!(t.connected_node("Mask"), Some("Group1")); |
| 2466 | } |
| 2467 | |
| 2468 | #[test] |
| 2469 | fn expression_renames_skip_property_names() { |
| 2470 | let renames = HashMap::from([("Size".to_owned(), "Big".to_owned())]); |
| 2471 | assert_eq!( |
| 2472 | rename_expression_idents("Other.Size + Size.Width * Size", &renames), |
| 2473 | "Other.Size + Big.Width * Big" |
| 2474 | ); |
| 2475 | } |
| 2476 | |
| 2477 | #[test] |
| 2478 | fn rename_and_paste_rewrite_expression_modifier_formulas() { |
| 2479 | let src = r#"Composition { |
| 2480 | 	Tools = ordered() { |
| 2481 | 		BG = Background { }, |
| 2482 | 		E = Expression { Inputs = { NumberExpression = Input { Value = "BG.Width + Other.BG", }, }, }, |
| 2483 | 	}, |
| 2484 | }"#; |
| 2485 | let mut comp = Comp::from_fusion_str(src).unwrap(); |
| 2486 | let bg = comp.find_node("BG").unwrap(); |
| 2487 | comp.rename_node(bg, "Plate").unwrap(); |
| 2488 | let formula = |c: &Comp| c.expression_modifiers["E"].inputs["NumberExpression"].value.clone(); |
| 2489 | assert_eq!(formula(&comp), Some(ParamValue::Text("Plate.Width + Other.BG".to_owned()))); |
| 2490 | assert!(comp.to_fusion_string().contains("Plate.Width + Other.BG")); |
| 2491 | |
| 2492 | let paste = r#"{ Tools = ordered() { BG = Background { }, E = Expression { Inputs = { NumberExpression = Input { Value = "BG.Width", }, }, }, }, }"#; |
| 2493 | comp.paste_fusion_clipboard(paste, (0.0, 0.0)).unwrap(); |
| 2494 | assert_eq!( |
| 2495 | comp.expression_modifiers["E_1"].inputs["NumberExpression"].value, |
| 2496 | Some(ParamValue::Text("BG.Width".to_owned())) |
| 2497 | ); |
| 2498 | let mut again = Comp::from_fusion_str(paste).unwrap(); |
| 2499 | again.paste_fusion_clipboard(paste, (0.0, 0.0)).unwrap(); |
| 2500 | assert_eq!( |
| 2501 | again.expression_modifiers["E_1"].inputs["NumberExpression"].value, |
| 2502 | Some(ParamValue::Text("BG_1.Width".to_owned())) |
| 2503 | ); |
| 2504 | } |
| 2505 | |
| 2506 | #[test] |
| 2507 | fn renaming_one_groups_private_tool_leaves_same_named_tools_elsewhere() { |
| 2508 | let mut comp = Comp::from_fusion_str(TWO_GROUPS).unwrap(); |
| 2509 | let (ga, gb) = (comp.find_node("GA").unwrap(), comp.find_node("GB").unwrap()); |
| 2510 | let a_same = comp.nodes.iter().position(|n| n.name == "Same" && n.id.0 < ga.0).unwrap(); |
| 2511 | assert_eq!(comp.rename_node(NodeId(a_same), "Renamed").unwrap(), "Renamed"); |
| 2512 | |
| 2513 | let text = comp.to_fusion_string(); |
| 2514 | let saved = Comp::from_fusion_str(&text).unwrap(); |
| 2515 | let group_tools = |name: &str| { |
| 2516 | let g = saved.node(saved.find_node(name).unwrap()); |
| 2517 | ( |
| 2518 | g.raw.get_table("Outputs").unwrap().get_table("Out").unwrap().get_str("SourceOp").unwrap().to_owned(), |
| 2519 | tool_names(find_raw_tool_in(&saved, name)).into_iter().map(str::to_owned).collect::<Vec<_>>(), |
| 2520 | ) |
| 2521 | }; |
| 2522 | assert_eq!(group_tools("GA"), ("Renamed".to_owned(), vec!["Renamed".to_owned(), "SameSize".to_owned()])); |
| 2523 | assert_eq!(group_tools("GB"), ("Same".to_owned(), vec!["Same".to_owned()])); |
| 2524 | assert_eq!(comp.node(gb).name, "GB"); |
| 2525 | } |
| 2526 | |
| 2527 | fn find_raw_tool_in<'a>(comp: &'a Comp, group: &str) -> &'a LuaTable { |
| 2528 | let tools = comp.raw_root.as_ref().unwrap().get_table("Tools").unwrap(); |
| 2529 | find_raw_tool(tools, group).unwrap().get_table("Tools").unwrap() |
| 2530 | } |
| 2531 | |
| 2532 | #[test] |
| 2533 | fn renaming_a_top_level_tool_ignores_groups_with_a_private_tool_of_that_name() { |
| 2534 | let src = TWO_GROUPS.replace("BG = Background { },", "BG = Background { },\n\t\tSame = Blur { },"); |
| 2535 | let mut comp = Comp::from_fusion_str(&src).unwrap(); |
| 2536 | let top = comp.find_node("Same").unwrap(); |
| 2537 | assert!(!comp.node(top).internal); |
| 2538 | comp.rename_node(top, "Top").unwrap(); |
| 2539 | let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap(); |
| 2540 | let ga = saved.node(saved.find_node("GA").unwrap()); |
| 2541 | assert_eq!( |
| 2542 | ga.raw.get_table("Outputs").unwrap().get_table("Out").unwrap().get_str("SourceOp"), |
| 2543 | Some("Same") |
| 2544 | ); |
| 2545 | assert!(saved.find_node("Top").is_some_and(|id| !saved.node(id).internal)); |
| 2546 | } |
| 2547 | |
| 2548 | #[test] |
| 2549 | fn duplicate_nodes_clones_groups_and_curve_modifiers() { |
| 2550 | let src = r#"Composition { |
| 2551 | 	Tools = ordered() { |
| 2552 | 		BG = Background { }, |
| 2553 | 		HC = HueCurves { |
| 2554 | 			Inputs = { |
| 2555 | 				Input = Input { SourceOp = "BG", Source = "Output", }, |
| 2556 | 				RedSuppress = Input { SourceOp = "HC_RSup", Source = "Value", }, |
| 2557 | 			}, |
| 2558 | 			Tools = ordered() { |
| 2559 | 				HC_RSup = LUTBezier { KeyColorSplines = { [0] = { [0] = { 0.5 }, [6] = { 0.5 } } }, }, |
| 2560 | 			}, |
| 2561 | 		}, |
| 2562 | 	}, |
| 2563 | }"#; |
| 2564 | let mut comp = Comp::from_fusion_str(src).unwrap(); |
| 2565 | let hc = comp.find_node("HC").unwrap(); |
| 2566 | let dup = comp.duplicate_nodes(&[hc], [10.0, 0.0]); |
| 2567 | assert_eq!(dup.len(), 1); |
| 2568 | let d = comp.node(dup[0]); |
| 2569 | assert_eq!(d.name, "HC_1"); |
| 2570 | assert_eq!(d.connected_node("Input"), Some("BG")); |
| 2571 | assert_eq!(d.connected_node("RedSuppress"), Some("HC_RSup_1")); |
| 2572 | assert!(comp.splines.contains_key("HC_RSup_1") && comp.splines.contains_key("HC_RSup")); |
| 2573 | let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap(); |
| 2574 | assert!(saved.splines.contains_key("HC_RSup_1")); |
| 2575 | |
| 2576 | let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap(); |
| 2577 | let g = comp.find_node("Group1").unwrap(); |
| 2578 | let dup = comp.duplicate_nodes(&[g], [0.0, 80.0]); |
| 2579 | let copy = comp.node(dup[0]); |
| 2580 | assert_eq!(copy.name, "Group1_1"); |
| 2581 | assert_eq!(comp.node(copy.macro_output.unwrap()).name, "Inner1_1"); |
| 2582 | assert!(comp.splines.contains_key("Inner1Size_1")); |
| 2583 | } |
| 2584 | |
| 2585 | #[test] |
| 2586 | fn updating_a_keyframe_moves_its_handles_with_it() { |
| 2587 | let mut comp = sample_comp(); |
| 2588 | let bc = comp.find_node("BC1").unwrap(); |
| 2589 | comp.splines.get_mut("BC1Gain").unwrap().keyframes[1].lh = Some([20.0, 1.5]); |
| 2590 | comp.splines.get_mut("BC1Gain").unwrap().keyframes[1].rh = Some([40.0, 2.5]); |
| 2591 | comp.set_keyframe(bc, "Gain", 30.0, 3.0).unwrap(); |
| 2592 | let kf = &comp.splines["BC1Gain"].keyframes[1]; |
| 2593 | assert_eq!((kf.value, kf.lh, kf.rh), (3.0, Some([20.0, 2.5]), Some([40.0, 3.5]))); |
| 2594 | } |
| 2595 | |
| 2596 | #[test] |
| 2597 | fn deleting_the_last_keyframe_keeps_its_value_as_a_static_input() { |
| 2598 | let mut comp = sample_comp(); |
| 2599 | let bc = comp.find_node("BC1").unwrap(); |
| 2600 | // Within the shared 1e-4 tolerance. |
| 2601 | assert!(comp.delete_keyframe("BC1Gain", 0.00005)); |
| 2602 | assert!(comp.delete_keyframe("BC1Gain", 30.0)); |
| 2603 | assert!(!comp.splines.contains_key("BC1Gain")); |
| 2604 | assert_eq!(comp.node(bc).connected_node("Gain"), None); |
| 2605 | assert_eq!(comp.node(bc).static_number("Gain"), Some(2.0)); |
| 2606 | |
| 2607 | let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap(); |
| 2608 | let r = saved.node(saved.find_node("BC1").unwrap()); |
| 2609 | assert_eq!(r.static_number("Gain"), Some(2.0)); |
| 2610 | assert!(!saved.to_fusion_string().contains("BC1Gain")); |
| 2611 | } |
| 2281 | 2612 | } |