| 1 | //! Lossless graph & parameter mutation API for `Comp`, plus `CompHistory` undo/redo stack. |
| 2 | |
| 3 | mod clipboard; |
| 4 | mod defaults; |
| 5 | mod history; |
| 6 | mod keyframes; |
| 7 | #[cfg(test)] |
| 8 | mod tests; |
| 9 | |
| 10 | pub use history::{CompHistory, DEFAULT_MAX_HISTORY}; |
| 11 | |
| 12 | use clipboard::{rename_expression_idents, rewrite_formulas_deep}; |
| 13 | use defaults::{default_inputs_for_kind, default_view_info_for_kind}; |
| 14 | use crate::comp::{ |
| 15 | Comp, InputBinding, Node, NodeId, ParamValue, default_main_input_port, ensure_table_mut, |
| 16 | find_raw_tool, find_raw_tool_mut, is_group_kind, is_modifier_type, param_value_to_lua, vec2_lua, |
| 17 | }; |
| 18 | use crate::lua_value::{LuaKey, LuaTable, LuaValue, is_valid_lua_ident}; |
| 19 | use std::collections::{HashMap, HashSet, VecDeque}; |
| 20 | |
| 21 | /// Expression-modifier inputs whose `Value` is a formula string. |
| 22 | pub(super) const EXPRESSION_FORMULA_INPUTS: &[&str] = |
| 23 | &["NumberExpression", "PointExpressionX", "PointExpressionY", "PointExpression"]; |
| 24 | |
| 25 | |
| 26 | impl Comp { |
| 27 | fn modifier_exists(&self, name: &str) -> bool { |
| 28 | self.splines.contains_key(name) |
| 29 | || self.poly_paths.contains_key(name) |
| 30 | || self.gradient_modifiers.contains_key(name) |
| 31 | || self.text_modifiers.contains_key(name) |
| 32 | || self.text_splines.contains_key(name) |
| 33 | || self.polyline_splines.contains_key(name) |
| 34 | || self.text_cls.contains_key(name) |
| 35 | || self.shakes.contains_key(name) |
| 36 | || self.expression_modifiers.contains_key(name) |
| 37 | } |
| 38 | |
| 39 | /// Whether pasted tools may link to `name`: a top-level flow node, or a modifier not private |
| 40 | /// to a group. |
| 41 | fn is_linkable_external(&self, name: &str) -> bool { |
| 42 | if self.nodes.iter().any(|n| !n.internal && n.name == name) { |
| 43 | return true; |
| 44 | } |
| 45 | let Some(tools) = self.raw_root.as_ref().and_then(|r| r.get_table("Tools")) else { |
| 46 | return self.modifier_exists(name); |
| 47 | }; |
| 48 | self.modifier_exists(name) |
| 49 | && (tools.get(name).is_some() |
| 50 | || !tools |
| 51 | .entries |
| 52 | .iter() |
| 53 | .filter_map(|(_, v)| v.as_table()?.get_table("Tools")) |
| 54 | .any(|inner| find_raw_tool(inner, name).is_some())) |
| 55 | } |
| 56 | |
| 57 | /// Checks whether a tool or modifier name is already in use anywhere in this composition. |
| 58 | fn name_exists(&self, name: &str) -> bool { |
| 59 | if self.node_by_name.contains_key(name) || self.modifier_exists(name) { |
| 60 | return true; |
| 61 | } |
| 62 | if let Some(tools) = self.raw_root.as_ref().and_then(|r| r.get_table("Tools")) { |
| 63 | if tools.get(name).is_some() { |
| 64 | return true; |
| 65 | } |
| 66 | } |
| 67 | false |
| 68 | } |
| 69 | |
| 70 | /// Generates a unique Fusion-style name for a node or modifier. |
| 71 | /// - With `Some(hint)`: sanitizes `hint`; uses `hint` if free, else `hint_1`, `hint_2`, ... |
| 72 | /// - With `None`: derives a clean base from `kind` and tries `Base1`, `Base2`, ... |
| 73 | fn generate_unique_name(&self, kind: &str, name_hint: Option<&str>) -> String { |
| 74 | if let Some(hint) = name_hint.map(str::trim).filter(|s| !s.is_empty()) { |
| 75 | let base = sanitize_lua_ident(hint); |
| 76 | if !self.name_exists(&base) { |
| 77 | return base; |
| 78 | } |
| 79 | let mut idx = 1usize; |
| 80 | loop { |
| 81 | let candidate = format!("{base}_{idx}"); |
| 82 | if !self.name_exists(&candidate) { |
| 83 | return candidate; |
| 84 | } |
| 85 | idx += 1; |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | let raw_base = kind.rsplit('.').next().unwrap_or(kind); |
| 90 | let base = sanitize_lua_ident(raw_base); |
| 91 | let mut idx = 1usize; |
| 92 | loop { |
| 93 | let candidate = format!("{base}{idx}"); |
| 94 | if !self.name_exists(&candidate) { |
| 95 | return candidate; |
| 96 | } |
| 97 | idx += 1; |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | /// Adds a new node of Fusion class `kind` at flow position `pos` with sensible Fusion 21.1 defaults. |
| 102 | pub fn add_node(&mut self, kind: &str, name_hint: Option<&str>, pos: [f32; 2]) -> NodeId { |
| 103 | let name = self.generate_unique_name(kind, name_hint); |
| 104 | let id = NodeId(self.nodes.len()); |
| 105 | |
| 106 | let defaults = default_inputs_for_kind(kind, self.width, self.height); |
| 107 | let mut inputs = HashMap::new(); |
| 108 | let mut raw_inputs = LuaTable::default(); |
| 109 | for (port, val) in defaults { |
| 110 | let mut it = LuaTable { |
| 111 | tag: Some("Input".to_owned()), |
| 112 | entries: Vec::new(), |
| 113 | }; |
| 114 | it.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(&val)); |
| 115 | raw_inputs.set(LuaKey::Str(port.clone()), LuaValue::Table(it)); |
| 116 | inputs.insert( |
| 117 | port, |
| 118 | InputBinding { |
| 119 | value: Some(val), |
| 120 | source_op: None, |
| 121 | source_output: None, |
| 122 | expression: None, |
| 123 | }, |
| 124 | ); |
| 125 | } |
| 126 | |
| 127 | let mut raw = LuaTable { |
| 128 | tag: Some(kind.to_owned()), |
| 129 | entries: Vec::new(), |
| 130 | }; |
| 131 | if kind == "Loader" { |
| 132 | raw.set( |
| 133 | LuaKey::Str("Clips".to_owned()), |
| 134 | LuaValue::Table(LuaTable::default()), |
| 135 | ); |
| 136 | } |
| 137 | if !raw_inputs.entries.is_empty() { |
| 138 | raw.set(LuaKey::Str("Inputs".to_owned()), LuaValue::Table(raw_inputs)); |
| 139 | } |
| 140 | raw.set( |
| 141 | LuaKey::Str("ViewInfo".to_owned()), |
| 142 | LuaValue::Table(default_view_info_for_kind(kind, pos)), |
| 143 | ); |
| 144 | |
| 145 | let node = Node { |
| 146 | id, |
| 147 | name: name.clone(), |
| 148 | kind: kind.to_owned(), |
| 149 | pos, |
| 150 | bypassed: false, |
| 151 | internal: false, |
| 152 | macro_output: None, |
| 153 | inputs, |
| 154 | clips: Vec::new(), |
| 155 | raw: raw.clone(), |
| 156 | }; |
| 157 | |
| 158 | self.nodes.push(node); |
| 159 | self.node_by_name.insert(name.clone(), id); |
| 160 | |
| 161 | if let Some(root) = self.raw_root.as_mut() { |
| 162 | let tools = ensure_table_mut(root, "Tools", Some("ordered")); |
| 163 | tools.set(LuaKey::Str(name), LuaValue::Table(raw)); |
| 164 | } |
| 165 | |
| 166 | self.revision += 1; |
| 167 | id |
| 168 | } |
| 169 | |
| 170 | /// Maps each group-private node to the innermost group that owns it. |
| 171 | fn group_owners(&self) -> HashMap<usize, usize> { |
| 172 | let mut owners = HashMap::new(); |
| 173 | for g in (0..self.nodes.len()).filter(|&g| is_group_kind(&self.nodes[g].kind)) { |
| 174 | for kid in self.group_children(g) { |
| 175 | owners.entry(kid).or_insert(g); |
| 176 | } |
| 177 | } |
| 178 | owners |
| 179 | } |
| 180 | |
| 181 | /// Indices of the internal nodes owned by the Group/Macro at `idx`, including nested groups' |
| 182 | /// contents. Nodes load in post-order, so they are the contiguous internal block before `idx`. |
| 183 | fn group_children(&self, idx: usize) -> Vec<usize> { |
| 184 | let node = &self.nodes[idx]; |
| 185 | let mut remaining: HashMap<&str, usize> = HashMap::new(); |
| 186 | if is_group_kind(&node.kind) { |
| 187 | if let Some(inner) = self |
| 188 | .raw_root |
| 189 | .as_ref() |
| 190 | .and_then(|r| r.get_table("Tools")) |
| 191 | .and_then(|t| find_raw_tool(t, &node.name)) |
| 192 | .and_then(|g| g.get_table("Tools")) |
| 193 | { |
| 194 | count_flow_tools(inner, &mut remaining); |
| 195 | } |
| 196 | } |
| 197 | let mut out = Vec::new(); |
| 198 | for i in (0..idx).rev() { |
| 199 | let n = &self.nodes[i]; |
| 200 | if remaining.is_empty() || !n.internal { |
| 201 | break; |
| 202 | } |
| 203 | if let Some(left) = remaining.get_mut(n.name.as_str()) { |
| 204 | *left -= 1; |
| 205 | if *left == 0 { |
| 206 | remaining.remove(n.name.as_str()); |
| 207 | } |
| 208 | out.push(i); |
| 209 | } |
| 210 | } |
| 211 | out |
| 212 | } |
| 213 | |
| 214 | /// Modifiers directly referenced by modifier `name`. |
| 215 | fn modifier_refs(&self, name: &str) -> Vec<String> { |
| 216 | let mut out = Vec::new(); |
| 217 | if let Some(pp) = self.poly_paths.get(name) { |
| 218 | out.extend(pp.displacement_op.clone()); |
| 219 | } |
| 220 | let bindings = self |
| 221 | .shakes |
| 222 | .get(name) |
| 223 | .map(|s| &s.inputs) |
| 224 | .or_else(|| self.expression_modifiers.get(name).map(|e| &e.inputs)); |
| 225 | out.extend(bindings.into_iter().flat_map(|m| m.values()).filter_map(|b| b.source_op.clone())); |
| 226 | out |
| 227 | } |
| 228 | |
| 229 | fn close_over_modifier_refs(&self, set: &mut HashSet<String>) { |
| 230 | let mut queue: VecDeque<String> = set.iter().cloned().collect(); |
| 231 | while let Some(name) = queue.pop_front() { |
| 232 | for next in self.modifier_refs(&name) { |
| 233 | if set.insert(next.clone()) { |
| 234 | queue.push_back(next); |
| 235 | } |
| 236 | } |
| 237 | } |
| 238 | } |
| 239 | |
| 240 | /// Deletes the specified nodes (and the private contents of any deleted Group/Macro), unwires |
| 241 | /// downstream references, compacts `NodeId` indexing, and prunes modifiers that were owned |
| 242 | /// solely by the deleted nodes. Returns the names of the deleted nodes. |
| 243 | pub fn delete_nodes(&mut self, ids: &[NodeId]) -> Vec<String> { |
| 244 | let mut doomed: Vec<usize> = Vec::new(); |
| 245 | for &id in ids { |
| 246 | if id.0 < self.nodes.len() && !doomed.contains(&id.0) { |
| 247 | doomed.push(id.0); |
| 248 | } |
| 249 | } |
| 250 | let mut next = 0; |
| 251 | while next < doomed.len() { |
| 252 | for child in self.group_children(doomed[next]) { |
| 253 | if !doomed.contains(&child) { |
| 254 | doomed.push(child); |
| 255 | } |
| 256 | } |
| 257 | next += 1; |
| 258 | } |
| 259 | if doomed.is_empty() { |
| 260 | return Vec::new(); |
| 261 | } |
| 262 | |
| 263 | let deleted_names: Vec<String> = doomed.iter().map(|&i| self.nodes[i].name.clone()).collect(); |
| 264 | let to_delete: HashSet<usize> = doomed.into_iter().collect(); |
| 265 | |
| 266 | // Names are scoped: a group-private tool shadows a same-named top-level tool inside its group. |
| 267 | let owner_of = self.group_owners(); |
| 268 | let mut by_scope: HashMap<(Option<usize>, &str), usize> = HashMap::new(); |
| 269 | for (i, node) in self.nodes.iter().enumerate() { |
| 270 | by_scope.insert((owner_of.get(&i).copied(), node.name.as_str()), i); |
| 271 | } |
| 272 | let mut dead_sources: Vec<HashSet<String>> = self |
| 273 | .nodes |
| 274 | .iter() |
| 275 | .enumerate() |
| 276 | .map(|(i, node)| { |
| 277 | let scope = owner_of.get(&i).copied(); |
| 278 | node.inputs |
| 279 | .values() |
| 280 | .filter_map(|b| b.source_op.as_deref()) |
| 281 | .filter(|src| { |
| 282 | let target = by_scope.get(&(scope, *src)).or_else(|| by_scope.get(&(None, *src))); |
| 283 | target.is_some_and(|t| to_delete.contains(t)) |
| 284 | }) |
| 285 | .map(str::to_owned) |
| 286 | .collect() |
| 287 | }) |
| 288 | .collect(); |
| 289 | let deleted_top_level: HashSet<String> = to_delete |
| 290 | .iter() |
| 291 | .filter(|&&i| !self.nodes[i].internal) |
| 292 | .map(|&i| self.nodes[i].name.clone()) |
| 293 | .collect(); |
| 294 | // Private tools deleted on their own live in a surviving group's raw `Tools`. |
| 295 | let deleted_private: Vec<(String, String)> = to_delete |
| 296 | .iter() |
| 297 | .filter_map(|i| Some((self.nodes[*owner_of.get(i)?].name.clone(), self.nodes[*i].name.clone()))) |
| 298 | .collect(); |
| 299 | |
| 300 | // Collect modifier names referenced by the nodes being deleted (candidates for pruning). |
| 301 | let mut candidate_modifiers: HashSet<String> = HashSet::new(); |
| 302 | for &idx in &to_delete { |
| 303 | collect_node_source_ops(&self.nodes[idx], &mut candidate_modifiers); |
| 304 | } |
| 305 | |
| 306 | // Compact `self.nodes` while building an old_idx -> Option<new_id> remap. |
| 307 | let old_len = self.nodes.len(); |
| 308 | let mut remap: Vec<Option<NodeId>> = vec![None; old_len]; |
| 309 | let mut kept_dead_sources = Vec::new(); |
| 310 | let old_nodes = std::mem::take(&mut self.nodes); |
| 311 | let mut new_nodes = Vec::with_capacity(old_len - to_delete.len()); |
| 312 | for (old_idx, mut node) in old_nodes.into_iter().enumerate() { |
| 313 | if to_delete.contains(&old_idx) { |
| 314 | continue; |
| 315 | } |
| 316 | let new_id = NodeId(new_nodes.len()); |
| 317 | remap[old_idx] = Some(new_id); |
| 318 | node.id = new_id; |
| 319 | new_nodes.push(node); |
| 320 | kept_dead_sources.push(std::mem::take(&mut dead_sources[old_idx])); |
| 321 | } |
| 322 | |
| 323 | // Fix `macro_output` and unwire any inputs pointing to deleted nodes. |
| 324 | for (node, dead) in new_nodes.iter_mut().zip(&kept_dead_sources) { |
| 325 | if let Some(old_mo) = node.macro_output { |
| 326 | node.macro_output = remap.get(old_mo.0).copied().flatten(); |
| 327 | } |
| 328 | let mut unwired_ports = Vec::new(); |
| 329 | for (port, binding) in &mut node.inputs { |
| 330 | if binding.source_op.as_ref().is_some_and(|s| dead.contains(s)) { |
| 331 | binding.source_op = None; |
| 332 | binding.source_output = None; |
| 333 | unwired_ports.push(port.clone()); |
| 334 | } |
| 335 | } |
| 336 | if !unwired_ports.is_empty() { |
| 337 | if let Some(in_tbl) = node.raw.get_table_mut("Inputs") { |
| 338 | for port in &unwired_ports { |
| 339 | if let Some(it) = in_tbl.get_table_mut(port) { |
| 340 | it.remove(&LuaKey::Str("SourceOp".to_owned())); |
| 341 | it.remove(&LuaKey::Str("Source".to_owned())); |
| 342 | } |
| 343 | } |
| 344 | } |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | // Rebuild `node_by_name`. |
| 349 | self.node_by_name.clear(); |
| 350 | for node in &new_nodes { |
| 351 | if !node.internal || !self.node_by_name.contains_key(&node.name) { |
| 352 | self.node_by_name.insert(node.name.clone(), node.id); |
| 353 | } |
| 354 | } |
| 355 | self.nodes = new_nodes; |
| 356 | |
| 357 | // A modifier survives if a surviving node reaches it, or a modifier that is not itself being |
| 358 | // pruned references it (transitively, through paths, shakes and expression modifiers). |
| 359 | self.close_over_modifier_refs(&mut candidate_modifiers); |
| 360 | let mut live_refs: HashSet<String> = HashSet::new(); |
| 361 | for node in &self.nodes { |
| 362 | collect_node_source_ops(node, &mut live_refs); |
| 363 | } |
| 364 | let surviving_modifiers = self |
| 365 | .poly_paths |
| 366 | .keys() |
| 367 | .chain(self.shakes.keys()) |
| 368 | .chain(self.expression_modifiers.keys()) |
| 369 | .filter(|name| !candidate_modifiers.contains(*name)); |
| 370 | let survivor_refs: Vec<String> = surviving_modifiers.flat_map(|n| self.modifier_refs(n)).collect(); |
| 371 | live_refs.extend(survivor_refs); |
| 372 | self.close_over_modifier_refs(&mut live_refs); |
| 373 | |
| 374 | // Prune orphaned modifiers that belonged to deleted nodes and are no longer referenced. |
| 375 | let mut pruned_modifiers: HashSet<String> = HashSet::new(); |
| 376 | for cand in candidate_modifiers { |
| 377 | if live_refs.contains(&cand) || self.node_by_name.contains_key(&cand) { |
| 378 | continue; |
| 379 | } |
| 380 | let mut removed = false; |
| 381 | removed |= self.splines.remove(&cand).is_some(); |
| 382 | removed |= self.poly_paths.remove(&cand).is_some(); |
| 383 | removed |= self.gradient_modifiers.remove(&cand).is_some(); |
| 384 | removed |= self.text_modifiers.remove(&cand).is_some(); |
| 385 | removed |= self.text_splines.remove(&cand).is_some(); |
| 386 | removed |= self.polyline_splines.remove(&cand).is_some(); |
| 387 | removed |= self.text_cls.remove(&cand).is_some(); |
| 388 | removed |= self.shakes.remove(&cand).is_some(); |
| 389 | removed |= self.expression_modifiers.remove(&cand).is_some(); |
| 390 | if removed { |
| 391 | pruned_modifiers.insert(cand); |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | // Update `raw_root.Tools`: remove deleted top-level nodes, and pruned modifiers / deleted |
| 396 | // group-private nodes wherever they are nested. |
| 397 | if let Some(tools) = self.raw_root.as_mut().and_then(|r| r.get_table_mut("Tools")) { |
| 398 | tools.entries.retain(|(k, _)| match k { |
| 399 | LuaKey::Str(name) => !deleted_top_level.contains(name), |
| 400 | _ => true, |
| 401 | }); |
| 402 | for (group, child) in &deleted_private { |
| 403 | if let Some(inner) = find_raw_tool_mut(tools, group).and_then(|g| g.get_table_mut("Tools")) { |
| 404 | inner.entries.retain(|(k, _)| !matches!(k, LuaKey::Str(name) if name == child)); |
| 405 | } |
| 406 | } |
| 407 | remove_tools_recursive(tools, &pruned_modifiers); |
| 408 | } |
| 409 | |
| 410 | self.revision += 1; |
| 411 | deleted_names |
| 412 | } |
| 413 | |
| 414 | /// Serializes `ids` plus every modifier (spline, path, shake, ...) they reference into |
| 415 | /// Fusion's clipboard format: `{ Tools = ordered() { ... }, ActiveTool = "<first>" }`. |
| 416 | |
| 417 | pub fn rename_node(&mut self, id: NodeId, new_name: &str) -> Result<String, String> { |
| 418 | if id.0 >= self.nodes.len() { |
| 419 | return Err(format!("invalid node id {}", id.0)); |
| 420 | } |
| 421 | let trimmed = new_name.trim(); |
| 422 | if trimmed.is_empty() { |
| 423 | return Err("node name cannot be empty".to_owned()); |
| 424 | } |
| 425 | if !is_valid_lua_ident(trimmed) { |
| 426 | return Err(format!("'{trimmed}' is not a valid Fusion/Lua identifier")); |
| 427 | } |
| 428 | |
| 429 | let old_name = self.nodes[id.0].name.clone(); |
| 430 | if trimmed == old_name { |
| 431 | return Ok(old_name); |
| 432 | } |
| 433 | if self.name_exists(trimmed) { |
| 434 | return Err(format!("a node or modifier named '{trimmed}' already exists")); |
| 435 | } |
| 436 | |
| 437 | // A private (group-internal) tool is only visible inside its group; a top-level tool is |
| 438 | // visible everywhere except inside groups that define a tool of the same name. |
| 439 | let owner = self.group_owners().get(&id.0).copied(); |
| 440 | let affected: Vec<usize> = match owner { |
| 441 | Some(g) => self.group_children(g), |
| 442 | None => { |
| 443 | let mut shadowed: HashSet<usize> = HashSet::new(); |
| 444 | for g in 0..self.nodes.len() { |
| 445 | let kids = self.group_children(g); |
| 446 | if kids.iter().any(|&k| self.nodes[k].name == old_name) { |
| 447 | shadowed.extend(kids); |
| 448 | } |
| 449 | } |
| 450 | (0..self.nodes.len()).filter(|i| !shadowed.contains(i)).collect() |
| 451 | } |
| 452 | }; |
| 453 | let scope_name = owner.map(|g| self.nodes[g].name.clone()); |
| 454 | |
| 455 | let renames = HashMap::from([(old_name.clone(), trimmed.to_owned())]); |
| 456 | self.nodes[id.0].name = trimmed.to_owned(); |
| 457 | if self.node_by_name.get(&old_name) == Some(&id) { |
| 458 | self.node_by_name.remove(&old_name); |
| 459 | } |
| 460 | self.node_by_name.insert(trimmed.to_owned(), id); |
| 461 | |
| 462 | for &i in &affected { |
| 463 | let node = &mut self.nodes[i]; |
| 464 | for binding in node.inputs.values_mut() { |
| 465 | if binding.source_op.as_deref() == Some(old_name.as_str()) { |
| 466 | binding.source_op = Some(trimmed.to_owned()); |
| 467 | } |
| 468 | if let Some(expr) = &mut binding.expression { |
| 469 | *expr = rename_expression_idents(expr, &renames); |
| 470 | } |
| 471 | } |
| 472 | rewrite_source_op_in_scope(&mut node.raw, &old_name, trimmed, false); |
| 473 | } |
| 474 | if owner.is_none() { |
| 475 | for shake in self.shakes.values_mut() { |
| 476 | for binding in shake.inputs.values_mut() { |
| 477 | if binding.source_op.as_deref() == Some(old_name.as_str()) { |
| 478 | binding.source_op = Some(trimmed.to_owned()); |
| 479 | } |
| 480 | if let Some(expr) = &mut binding.expression { |
| 481 | *expr = rename_expression_idents(expr, &renames); |
| 482 | } |
| 483 | } |
| 484 | } |
| 485 | } |
| 486 | for em in self.expression_modifiers.values_mut() { |
| 487 | for binding in em.inputs.values_mut() { |
| 488 | if let Some(expr) = &mut binding.expression { |
| 489 | *expr = rename_expression_idents(expr, &renames); |
| 490 | } |
| 491 | } |
| 492 | for key in EXPRESSION_FORMULA_INPUTS { |
| 493 | if let Some(ParamValue::Text(formula)) = em.inputs.get_mut(*key).and_then(|b| b.value.as_mut()) { |
| 494 | *formula = rename_expression_idents(formula, &renames); |
| 495 | } |
| 496 | } |
| 497 | } |
| 498 | |
| 499 | // Rename the key in place (preserving order) within the owning `Tools` table and rewrite refs. |
| 500 | if let Some(root) = self.raw_root.as_mut() { |
| 501 | let scope = match &scope_name { |
| 502 | Some(group) => root.get_table_mut("Tools").and_then(|t| find_raw_tool_mut(t, group)), |
| 503 | None => Some(&mut *root), |
| 504 | }; |
| 505 | if let Some(scope) = scope { |
| 506 | rewrite_source_op_in_scope(scope, &old_name, trimmed, true); |
| 507 | if let Some(tools) = scope.get_table_mut("Tools") { |
| 508 | for (k, _) in &mut tools.entries { |
| 509 | if matches!(k, LuaKey::Str(s) if s == &old_name) { |
| 510 | *k = LuaKey::Str(trimmed.to_owned()); |
| 511 | break; |
| 512 | } |
| 513 | } |
| 514 | } |
| 515 | rewrite_formulas_deep(scope, &renames); |
| 516 | } |
| 517 | if owner.is_none() && root.get_str("ActiveTool") == Some(old_name.as_str()) { |
| 518 | root.set( |
| 519 | LuaKey::Str("ActiveTool".to_owned()), |
| 520 | LuaValue::String(trimmed.to_owned()), |
| 521 | ); |
| 522 | } |
| 523 | } |
| 524 | |
| 525 | self.revision += 1; |
| 526 | Ok(trimmed.to_owned()) |
| 527 | } |
| 528 | |
| 529 | /// Returns `true` if wiring `from_node -> to_node` would create a cycle (including self-loops). |
| 530 | pub fn would_create_cycle(&self, from_node: NodeId, to_node: NodeId) -> bool { |
| 531 | if from_node.0 >= self.nodes.len() || to_node.0 >= self.nodes.len() { |
| 532 | return false; |
| 533 | } |
| 534 | if from_node == to_node { |
| 535 | return true; |
| 536 | } |
| 537 | let mut visited: HashSet<NodeId> = HashSet::new(); |
| 538 | let mut stack: Vec<NodeId> = vec![from_node]; |
| 539 | while let Some(curr) = stack.pop() { |
| 540 | if !visited.insert(curr) { |
| 541 | continue; |
| 542 | } |
| 543 | for binding in self.nodes[curr.0].inputs.values() { |
| 544 | if let Some(src_name) = &binding.source_op { |
| 545 | if let Some(src_id) = self.find_node(src_name) { |
| 546 | if src_id == to_node { |
| 547 | return true; |
| 548 | } |
| 549 | if !visited.contains(&src_id) { |
| 550 | stack.push(src_id); |
| 551 | } |
| 552 | } |
| 553 | } |
| 554 | } |
| 555 | } |
| 556 | false |
| 557 | } |
| 558 | |
| 559 | /// Connects `from_node`'s `from_output` (typically `"Output"` or `"Mask"`) to `to_node`'s |
| 560 | /// `to_input` port, rejecting self-loops and cycles. |
| 561 | pub fn connect_output( |
| 562 | &mut self, |
| 563 | from_node: NodeId, |
| 564 | from_output: &str, |
| 565 | to_node: NodeId, |
| 566 | to_input: &str, |
| 567 | ) -> Result<(), String> { |
| 568 | if from_node.0 >= self.nodes.len() { |
| 569 | return Err(format!("invalid source node id {}", from_node.0)); |
| 570 | } |
| 571 | if to_node.0 >= self.nodes.len() { |
| 572 | return Err(format!("invalid target node id {}", to_node.0)); |
| 573 | } |
| 574 | if from_node == to_node { |
| 575 | return Err("cannot connect a node to itself".to_owned()); |
| 576 | } |
| 577 | if self.would_create_cycle(from_node, to_node) { |
| 578 | return Err(format!( |
| 579 | "connecting '{}' -> '{}' would create a cycle", |
| 580 | self.nodes[from_node.0].name, self.nodes[to_node.0].name |
| 581 | )); |
| 582 | } |
| 583 | |
| 584 | let src_name = self.nodes[from_node.0].name.clone(); |
| 585 | let out_name = if from_output.is_empty() { |
| 586 | "Output" |
| 587 | } else { |
| 588 | from_output |
| 589 | }; |
| 590 | |
| 591 | let dst = &mut self.nodes[to_node.0]; |
| 592 | let entry = dst |
| 593 | .inputs |
| 594 | .entry(to_input.to_owned()) |
| 595 | .or_insert(InputBinding { |
| 596 | value: None, |
| 597 | source_op: None, |
| 598 | source_output: None, |
| 599 | expression: None, |
| 600 | }); |
| 601 | entry.source_op = Some(src_name.clone()); |
| 602 | entry.source_output = Some(out_name.to_owned()); |
| 603 | |
| 604 | let in_tbl = ensure_table_mut(&mut dst.raw, "Inputs", None); |
| 605 | let port_tbl = ensure_table_mut(in_tbl, to_input, Some("Input")); |
| 606 | port_tbl.set(LuaKey::Str("SourceOp".to_owned()), LuaValue::String(src_name)); |
| 607 | port_tbl.set( |
| 608 | LuaKey::Str("Source".to_owned()), |
| 609 | LuaValue::String(out_name.to_owned()), |
| 610 | ); |
| 611 | |
| 612 | self.revision += 1; |
| 613 | Ok(()) |
| 614 | } |
| 615 | |
| 616 | /// Disconnects `to_node`'s `to_input` port. Returns `true` if a connection was removed. |
| 617 | pub fn disconnect(&mut self, to_node: NodeId, to_input: &str) -> bool { |
| 618 | if to_node.0 >= self.nodes.len() { |
| 619 | return false; |
| 620 | } |
| 621 | let dst = &mut self.nodes[to_node.0]; |
| 622 | let Some(entry) = dst.inputs.get_mut(to_input) else { |
| 623 | return false; |
| 624 | }; |
| 625 | if entry.source_op.is_none() && entry.source_output.is_none() { |
| 626 | return false; |
| 627 | } |
| 628 | entry.source_op = None; |
| 629 | entry.source_output = None; |
| 630 | |
| 631 | if let Some(in_tbl) = dst.raw.get_table_mut("Inputs") { |
| 632 | if let Some(port_tbl) = in_tbl.get_table_mut(to_input) { |
| 633 | port_tbl.remove(&LuaKey::Str("SourceOp".to_owned())); |
| 634 | port_tbl.remove(&LuaKey::Str("Source".to_owned())); |
| 635 | } |
| 636 | } |
| 637 | |
| 638 | self.revision += 1; |
| 639 | true |
| 640 | } |
| 641 | |
| 642 | /// Splices `new_node` into the pipe `upstream -> downstream.downstream_input`: |
| 643 | /// connects `upstream -> new_node.(default_main_input_port)` and |
| 644 | /// `new_node -> downstream.downstream_input`. |
| 645 | pub fn splice_node_into_pipe( |
| 646 | &mut self, |
| 647 | new_node: NodeId, |
| 648 | upstream: NodeId, |
| 649 | downstream: NodeId, |
| 650 | downstream_input: &str, |
| 651 | ) -> Result<(), String> { |
| 652 | if new_node.0 >= self.nodes.len() |
| 653 | || upstream.0 >= self.nodes.len() |
| 654 | || downstream.0 >= self.nodes.len() |
| 655 | { |
| 656 | return Err("invalid node id for splice_node_into_pipe".to_owned()); |
| 657 | } |
| 658 | if new_node == upstream || new_node == downstream || upstream == downstream { |
| 659 | return Err("splice_node_into_pipe requires three distinct nodes".to_owned()); |
| 660 | } |
| 661 | if self.would_create_cycle(upstream, new_node) |
| 662 | || self.would_create_cycle(new_node, downstream) |
| 663 | { |
| 664 | return Err("splicing node into pipe would create a cycle".to_owned()); |
| 665 | } |
| 666 | |
| 667 | let upstream_name = self.nodes[upstream.0].name.as_str(); |
| 668 | let upstream_output = self.nodes[downstream.0] |
| 669 | .inputs |
| 670 | .get(downstream_input) |
| 671 | .filter(|b| b.source_op.as_deref() == Some(upstream_name)) |
| 672 | .and_then(|b| b.source_output.clone()) |
| 673 | .unwrap_or_else(|| "Output".to_owned()); |
| 674 | |
| 675 | let mid_port = default_main_input_port(&self.nodes[new_node.0].kind); |
| 676 | self.connect_output(upstream, &upstream_output, new_node, mid_port)?; |
| 677 | self.connect_output(new_node, "Output", downstream, downstream_input)?; |
| 678 | Ok(()) |
| 679 | } |
| 680 | |
| 681 | /// Sets a static parameter value on `node`'s `input` port. |
| 682 | pub fn set_input_value(&mut self, node: NodeId, input: &str, value: ParamValue) -> bool { |
| 683 | if node.0 >= self.nodes.len() { |
| 684 | return false; |
| 685 | } |
| 686 | let n = &mut self.nodes[node.0]; |
| 687 | let entry = n.inputs.entry(input.to_owned()).or_insert(InputBinding { |
| 688 | value: None, |
| 689 | source_op: None, |
| 690 | source_output: None, |
| 691 | expression: None, |
| 692 | }); |
| 693 | entry.value = Some(value.clone()); |
| 694 | |
| 695 | let in_tbl = ensure_table_mut(&mut n.raw, "Inputs", None); |
| 696 | let port_tbl = ensure_table_mut(in_tbl, input, Some("Input")); |
| 697 | port_tbl.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(&value)); |
| 698 | |
| 699 | self.revision += 1; |
| 700 | true |
| 701 | } |
| 702 | |
| 703 | /// Sets or clears a Fusion Lua expression on `node`'s `input` port. |
| 704 | pub fn set_input_expression( |
| 705 | &mut self, |
| 706 | node: NodeId, |
| 707 | input: &str, |
| 708 | expr: Option<String>, |
| 709 | ) -> bool { |
| 710 | if node.0 >= self.nodes.len() { |
| 711 | return false; |
| 712 | } |
| 713 | let normalized = expr.and_then(|s| { |
| 714 | let trimmed = s.trim(); |
| 715 | if trimmed.is_empty() { |
| 716 | None |
| 717 | } else { |
| 718 | Some(s) |
| 719 | } |
| 720 | }); |
| 721 | |
| 722 | let n = &mut self.nodes[node.0]; |
| 723 | let entry = n.inputs.entry(input.to_owned()).or_insert(InputBinding { |
| 724 | value: None, |
| 725 | source_op: None, |
| 726 | source_output: None, |
| 727 | expression: None, |
| 728 | }); |
| 729 | entry.expression = normalized.clone(); |
| 730 | |
| 731 | if let Some(expr_str) = normalized { |
| 732 | let in_tbl = ensure_table_mut(&mut n.raw, "Inputs", None); |
| 733 | let port_tbl = ensure_table_mut(in_tbl, input, Some("Input")); |
| 734 | port_tbl.set( |
| 735 | LuaKey::Str("Expression".to_owned()), |
| 736 | LuaValue::String(expr_str), |
| 737 | ); |
| 738 | } else if let Some(in_tbl) = n.raw.get_table_mut("Inputs") { |
| 739 | if let Some(port_tbl) = in_tbl.get_table_mut(input) { |
| 740 | port_tbl.remove(&LuaKey::Str("Expression".to_owned())); |
| 741 | } |
| 742 | } |
| 743 | |
| 744 | self.revision += 1; |
| 745 | true |
| 746 | } |
| 747 | |
| 748 | /// Toggles `PassThrough` (bypass) on `node` and returns the new passthrough state. |
| 749 | pub fn toggle_passthrough(&mut self, node: NodeId) -> bool { |
| 750 | if node.0 >= self.nodes.len() { |
| 751 | return false; |
| 752 | } |
| 753 | let n = &mut self.nodes[node.0]; |
| 754 | n.bypassed = !n.bypassed; |
| 755 | if n.bypassed { |
| 756 | n.raw |
| 757 | .set(LuaKey::Str("PassThrough".to_owned()), LuaValue::Bool(true)); |
| 758 | } else { |
| 759 | n.raw.remove(&LuaKey::Str("PassThrough".to_owned())); |
| 760 | } |
| 761 | self.revision += 1; |
| 762 | n.bypassed |
| 763 | } |
| 764 | |
| 765 | /// Moves `node` to flow position `pos` and updates `ViewInfo.Pos` in `node.raw`. |
| 766 | pub fn set_node_pos(&mut self, node: NodeId, pos: [f32; 2]) { |
| 767 | if node.0 >= self.nodes.len() { |
| 768 | return; |
| 769 | } |
| 770 | let n = &mut self.nodes[node.0]; |
| 771 | n.pos = pos; |
| 772 | set_view_info_pos(&mut n.raw, pos); |
| 773 | self.revision += 1; |
| 774 | } |
| 775 | } |
| 776 | |
| 777 | pub(super) fn sanitize_lua_ident(raw: &str) -> String { |
| 778 | let mut out = String::with_capacity(raw.len()); |
| 779 | for ch in raw.chars() { |
| 780 | if ch.is_ascii_alphanumeric() || ch == '_' { |
| 781 | out.push(ch); |
| 782 | } else { |
| 783 | out.push('_'); |
| 784 | } |
| 785 | } |
| 786 | if out.is_empty() || out.as_bytes()[0].is_ascii_digit() { |
| 787 | out.insert(0, '_'); |
| 788 | } |
| 789 | if !is_valid_lua_ident(&out) { |
| 790 | out.push('_'); |
| 791 | } |
| 792 | out |
| 793 | } |
| 794 | |
| 795 | pub(super) fn collect_node_source_ops(node: &Node, out: &mut HashSet<String>) { |
| 796 | for binding in node.inputs.values() { |
| 797 | if let Some(src) = &binding.source_op { |
| 798 | out.insert(src.clone()); |
| 799 | } |
| 800 | } |
| 801 | collect_source_ops_in_table(&node.raw, out); |
| 802 | } |
| 803 | |
| 804 | pub(super) fn collect_source_ops_in_table(tbl: &LuaTable, out: &mut HashSet<String>) { |
| 805 | for (k, v) in &tbl.entries { |
| 806 | if let LuaKey::Str(key) = k { |
| 807 | if key == "SourceOp" { |
| 808 | if let Some(s) = v.as_str() { |
| 809 | out.insert(s.to_owned()); |
| 810 | } |
| 811 | } |
| 812 | } |
| 813 | if let Some(sub) = v.as_table() { |
| 814 | collect_source_ops_in_table(sub, out); |
| 815 | } |
| 816 | } |
| 817 | } |
| 818 | |
| 819 | /// Rewrites `SourceOp = old_name` and inline `Expression` identifiers in `tbl`, skipping nested groups that define their own tool |
| 820 | /// called `old_name` (inside them the name refers to that private tool). `is_scope_root` exempts |
| 821 | /// `tbl` itself from that check. |
| 822 | fn rewrite_source_op_in_scope(tbl: &mut LuaTable, old_name: &str, new_name: &str, is_scope_root: bool) { |
| 823 | if !is_scope_root && tbl.get_table("Tools").is_some_and(|t| t.get(old_name).is_some()) { |
| 824 | return; |
| 825 | } |
| 826 | for (k, v) in &mut tbl.entries { |
| 827 | match (k, &mut *v) { |
| 828 | (LuaKey::Str(key), LuaValue::String(s)) if key == "SourceOp" && s == old_name => { |
| 829 | *s = new_name.to_owned(); |
| 830 | } |
| 831 | (LuaKey::Str(key), LuaValue::String(s)) if key == "Expression" => { |
| 832 | let renames = HashMap::from([(old_name.to_owned(), new_name.to_owned())]); |
| 833 | *s = rename_expression_idents(s, &renames); |
| 834 | } |
| 835 | (_, LuaValue::Table(sub)) => rewrite_source_op_in_scope(sub, old_name, new_name, false), |
| 836 | _ => {} |
| 837 | } |
| 838 | } |
| 839 | } |
| 840 | |
| 841 | /// Counts the flow-node (non-modifier) tools in `tools`, including inside nested groups. |
| 842 | fn count_flow_tools<'a>(tools: &'a LuaTable, out: &mut HashMap<&'a str, usize>) { |
| 843 | for (key, value) in &tools.entries { |
| 844 | let (LuaKey::Str(name), Some(tool)) = (key, value.as_table()) else { continue }; |
| 845 | if is_modifier_type(tool.tag.as_deref().unwrap_or("Unknown")) { |
| 846 | continue; |
| 847 | } |
| 848 | *out.entry(name.as_str()).or_default() += 1; |
| 849 | if let Some(inner) = tool.get_table("Tools") { |
| 850 | count_flow_tools(inner, out); |
| 851 | } |
| 852 | } |
| 853 | } |
| 854 | |
| 855 | /// Removes tools named in `names` from `tools` and every nested `Tools` table. |
| 856 | pub(super) fn remove_tools_recursive(tools: &mut LuaTable, names: &HashSet<String>) { |
| 857 | tools |
| 858 | .entries |
| 859 | .retain(|(k, _)| !matches!(k, LuaKey::Str(name) if names.contains(name))); |
| 860 | for (_, v) in &mut tools.entries { |
| 861 | if let Some(inner) = v.as_table_mut().and_then(|t| t.get_table_mut("Tools")) { |
| 862 | remove_tools_recursive(inner, names); |
| 863 | } |
| 864 | } |
| 865 | } |
| 866 | |
| 867 | /// Names of every tool in `tools`, including tools nested in `Tools` tables (macros/groups). |
| 868 | |
| 869 | pub(super) fn set_view_info_pos(raw: &mut LuaTable, pos: [f32; 2]) { |
| 870 | let vi = ensure_table_mut(raw, "ViewInfo", Some("OperatorInfo")); |
| 871 | vi.set( |
| 872 | LuaKey::Str("Pos".to_owned()), |
| 873 | vec2_lua(pos[0] as f64, pos[1] as f64), |
| 874 | ); |
| 875 | } |
| 876 | |