1use super::load::{normalize_frame_dim, parse_input_binding, parse_param_value};
2use super::math::find_raw_tool_mut;
3use super::{BitDepth, Comp, InputBinding, Node, ParamValue, is_modifier_type};
4use crate::lua_value::{
5 LuaKey, LuaTable, LuaValue, can_use_positional, has_call_args, write_entry_key, write_indent,
6 write_table, write_table_prefix, write_value,
7};
8use crate::spline::{BezierSpline, Gradient, HandleMode, KeyFlags, read_vec2};
9use std::collections::{HashMap, HashSet};
10use std::io::Write;
11use std::path::{Path, PathBuf};
12use std::sync::atomic::{AtomicU64, Ordering};
13
14enum NodePool<'a> {
15 One(&'a Node),
16 Many(Vec<&'a Node>, usize),
17}
18
19impl<'a> NodePool<'a> {
20 fn push(&mut self, node: &'a Node) {
21 match self {
22 NodePool::One(first) => {
23 *self = NodePool::Many(vec![*first, node], 0);
24 }
25 NodePool::Many(v, _) => v.push(node),
26 }
27 }
28
29 fn is_non_empty(&self) -> bool {
30 match self {
31 NodePool::One(_) => true,
32 NodePool::Many(v, idx) => *idx < v.len(),
33 }
34 }
35
36 fn peek_at(&self, offset: usize) -> Option<&'a Node> {
37 match self {
38 NodePool::One(n) => (offset == 0).then_some(*n),
39 NodePool::Many(v, idx) => v.get(*idx + offset).copied(),
40 }
41 }
42}
43
44fn pop_pool<'a>(pool: &mut HashMap<&'a str, NodePool<'a>>, name: &str) -> Option<&'a Node> {
45 match pool.get_mut(name)? {
46 NodePool::One(n) => {
47 let n = *n;
48 pool.remove(name);
49 Some(n)
50 }
51 NodePool::Many(v, idx) => {
52 let n = v.get(*idx).copied()?;
53 *idx += 1;
54 Some(n)
55 }
56 }
57}
58
59impl Comp {
60 /// Synchronizes current comp state (metadata, node positions/bypass/inputs, spline edits,
61 /// added/removed flow nodes) back onto a cloned raw Fusion `Composition { ... }` AST,
62 /// preserving all unknown nodes, modifiers, macros, UserControls, Clips, and metadata verbatim.
63 pub fn sync_to_raw_ast(&self) -> LuaTable {
64 let mut root = self.raw_root.clone().unwrap_or_else(|| LuaTable {
65 tag: Some("Composition".to_owned()),
66 entries: Vec::new(),
67 });
68
69 root.set(
70 LuaKey::Str("CurrentTime".to_owned()),
71 LuaValue::Number(self.current_time),
72 );
73 root.set(
74 LuaKey::Str("GlobalRange".to_owned()),
75 vec2_lua(self.global_range[0] as f64, self.global_range[1] as f64),
76 );
77 root.set(
78 LuaKey::Str("RenderRange".to_owned()),
79 vec2_lua(self.render_range[0] as f64, self.render_range[1] as f64),
80 );
81 if let Some(ref af) = self.audio_filename {
82 root.set(
83 LuaKey::Str("AudioFilename".to_owned()),
84 LuaValue::String(af.clone()),
85 );
86 }
87 if self.audio_offset != 0.0 || root.get("AudioOffset").is_some() {
88 root.set(
89 LuaKey::Str("AudioOffset".to_owned()),
90 LuaValue::Number(self.audio_offset),
91 );
92 }
93
94 // Update Prefs.Comp.FrameFormat (Width, Height, Rate, DepthFull)
95 let prefs = ensure_table_mut(&mut root, "Prefs", None);
96 self.patch_prefs_table(prefs);
97
98 // Sync Tools
99 let tools = ensure_table_mut(&mut root, "Tools", Some("ordered"));
100
101 for node in self.nodes.iter().filter(|n| !n.internal) {
102 if tools.get_table(&node.name).is_some() {
103 continue;
104 }
105 let mut new_tbl = if node.raw.tag.is_some() {
106 node.raw.clone()
107 } else {
108 LuaTable { tag: None, entries: Vec::new() }
109 };
110 if new_tbl.tag.is_none() {
111 new_tbl.tag = Some(node.kind.clone());
112 }
113 tools.set(LuaKey::Str(node.name.clone()), LuaValue::Table(new_tbl));
114 }
115
116 let mut top_pool: HashMap<&str, NodePool<'_>> = HashMap::with_capacity(self.nodes.len());
117 let mut inner_pool: HashMap<&str, NodePool<'_>> = HashMap::new();
118 let mut instance_defaults: HashMap<(&str, &str), ParamValue> = HashMap::new();
119 for node in &self.nodes {
120 let pool = if node.internal { &mut inner_pool } else { &mut top_pool };
121 let key = node.name.as_str();
122 if let Some(entry) = pool.get_mut(key) {
123 entry.push(node);
124 } else {
125 pool.insert(key, NodePool::One(node));
126 }
127 if !is_group_kind(&node.kind) {
128 continue;
129 }
130 for (inner_op, inner_port, default) in instance_inputs(&node.raw) {
131 if let Some(d) = default {
132 instance_defaults.insert((inner_op, inner_port), d);
133 }
134 }
135 }
136 self.sync_tools_level(tools, false, &mut top_pool, &mut inner_pool, &instance_defaults);
137
138 // Sync BezierSpline edits (walk `Tools` once in top-level-then-nested order -> O(T), not O(S * T))
139 if !self.splines.is_empty() {
140 let mut remaining: HashMap<&str, &BezierSpline> =
141 self.splines.iter().map(|(k, v)| (k.as_str(), v)).collect();
142 sync_existing_splines_in_tools(tools, &mut remaining);
143 if !remaining.is_empty() {
144 let mut new_names: Vec<&str> = remaining.keys().copied().collect();
145 new_names.sort_unstable();
146 for spline_name in new_names {
147 let spline = remaining[spline_name];
148 let mut sp_tbl = LuaTable {
149 tag: Some("BezierSpline".to_owned()),
150 entries: Vec::with_capacity(2),
151 };
152 sp_tbl.set(
153 LuaKey::Str("SplineColor".to_owned()),
154 spline_color_lua(spline.color),
155 );
156 sp_tbl.set(
157 LuaKey::Str("KeyFrames".to_owned()),
158 LuaValue::Table(build_keyframes_table(spline)),
159 );
160 tools.set(LuaKey::Str(spline_name.to_owned()), LuaValue::Table(sp_tbl));
161 }
162 }
163 }
164
165 root
166 }
167
168 /// Syncs one `Tools` table level: drops deleted flow nodes (never modifiers), then syncs each
169 /// surviving node and recurses into Group/Macro operators' private `Tools`.
170 fn sync_tools_level<'a>(
171 &'a self,
172 tools: &mut LuaTable,
173 internal: bool,
174 top_pool: &mut HashMap<&'a str, NodePool<'a>>,
175 inner_pool: &mut HashMap<&'a str, NodePool<'a>>,
176 instance_defaults: &HashMap<(&str, &str), ParamValue>,
177 ) {
178 {
179 let pool = if internal { &*inner_pool } else { &*top_pool };
180 tools.entries.retain(|(k, v)| {
181 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { return true };
182 is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown"))
183 || pool.get(name.as_str()).is_some_and(NodePool::is_non_empty)
184 });
185 }
186
187 for (k, v) in &mut tools.entries {
188 let (LuaKey::Str(name), Some(tool_tbl)) = (&*k, v.as_table_mut()) else { continue };
189 if is_modifier_type(tool_tbl.tag.as_deref().unwrap_or("Unknown")) {
190 continue;
191 }
192 let node = {
193 let pool = if internal { &mut *inner_pool } else { &mut *top_pool };
194 pop_pool(pool, name.as_str())
195 };
196 let Some(node) = node else {
197 continue;
198 };
199 self.sync_node_tool(node, tool_tbl, instance_defaults);
200 if is_group_kind(&node.kind) {
201 if let Some(inner) = tool_tbl.get_table_mut("Tools") {
202 self.sync_tools_level(inner, true, top_pool, inner_pool, instance_defaults);
203 }
204 sync_group_wiring(node, tool_tbl);
205 }
206 }
207 }
208
209 fn sync_node_tool(
210 &self,
211 node: &Node,
212 tool_tbl: &mut LuaTable,
213 instance_defaults: &HashMap<(&str, &str), ParamValue>,
214 ) {
215 // ViewInfo.Pos
216 if let Some(vi) = tool_tbl.get_table_mut("ViewInfo") {
217 let pos_changed = vi
218 .get_table("Pos")
219 .and_then(read_vec2)
220 .is_none_or(|[x, y]| {
221 (x as f32 - node.pos[0]).abs() > 1e-4 || (y as f32 - node.pos[1]).abs() > 1e-4
222 });
223 if pos_changed {
224 vi.set(
225 LuaKey::Str("Pos".to_owned()),
226 vec2_lua(node.pos[0] as f64, node.pos[1] as f64),
227 );
228 }
229 } else if node.pos[0] != 0.0 || node.pos[1] != 0.0 {
230 let mut vi = LuaTable {
231 tag: Some("OperatorInfo".to_owned()),
232 entries: Vec::new(),
233 };
234 vi.set(
235 LuaKey::Str("Pos".to_owned()),
236 vec2_lua(node.pos[0] as f64, node.pos[1] as f64),
237 );
238 tool_tbl.set(LuaKey::Str("ViewInfo".to_owned()), LuaValue::Table(vi));
239 }
240
241 // PassThrough
242 if node.bypassed {
243 tool_tbl.set(LuaKey::Str("PassThrough".to_owned()), LuaValue::Bool(true));
244 } else if tool_tbl.get("PassThrough").is_some() {
245 tool_tbl.remove(&LuaKey::Str("PassThrough".to_owned()));
246 }
247
248 // Loader timing edits made through `Inputs` land in the clip too (`Loop` is a count: 0 = loop).
249 if node.kind == "Loader" {
250 let edited = |port: &str| {
251 let now = node.static_number(port)?;
252 let before = tool_tbl
253 .get_table("Inputs")
254 .and_then(|i| i.get_table(port))
255 .and_then(|t| t.get("Value"))
256 .and_then(lua_value_as_number);
257 (before != Some(now)).then_some(now)
258 };
259 let updates = [
260 ("GlobalStart", edited("GlobalIn").map(LuaValue::Number)),
261 ("GlobalEnd", edited("GlobalOut").map(LuaValue::Number)),
262 ("Loop", edited("Loop").map(|v| LuaValue::Number(if v > 0.5 { 0.0 } else { 1.0 }))),
263 ("Reverse", edited("Reverse").map(|v| LuaValue::Bool(v > 0.5))),
264 ];
265 // The first clip proper, as `node.clips.first()` (what the engine plays) is.
266 let clip = tool_tbl.get_table_mut("Clips").and_then(|c| {
267 c.entries.iter_mut().find_map(|(_, v)| v.as_table_mut().filter(|t| t.get_str("Filename").is_some()))
268 });
269 if let Some(clip) = clip {
270 for (key, value) in updates {
271 if let Some(value) = value {
272 clip.set(LuaKey::Str(key.to_owned()), value);
273 }
274 }
275 }
276 }
277
278 // Group/Macro inputs hold InstanceInput wiring (synced by `sync_group_wiring`).
279 if !is_group_kind(&node.kind) {
280 let master_inputs = node
281 .raw
282 .get_str("SourceOp")
283 .and_then(|m| self.find_node(m))
284 .map(|mid| &self.nodes[mid.0].inputs);
285 sync_node_inputs(node, master_inputs, instance_defaults, &self.cross_macro_wires, tool_tbl);
286 }
287 }
288
289 /// Serializes this composition back to a Blackmagic Fusion `.comp` string.
290 pub fn to_fusion_string(&self) -> String {
291 if let Some(s) = self.try_to_fusion_string_streaming() {
292 return s;
293 }
294 let mut s = self.sync_to_raw_ast().to_fusion_string();
295 if !s.ends_with('\n') {
296 s.push('\n');
297 }
298 s
299 }
300
301 fn try_to_fusion_string_streaming(&self) -> Option<String> {
302 let root = self.raw_root.as_ref()?;
303 if has_call_args(root) {
304 return None;
305 }
306 let mut seen_special_root_keys = 0u8;
307 for (k, _) in &root.entries {
308 if let LuaKey::Str(name) = k {
309 let bit = match name.as_str() {
310 "CurrentTime" => 1 << 0,
311 "GlobalRange" => 1 << 1,
312 "RenderRange" => 1 << 2,
313 "AudioFilename" => 1 << 3,
314 "AudioOffset" => 1 << 4,
315 "Prefs" => 1 << 5,
316 "Tools" => 1 << 6,
317 "FrameFormat" => 1 << 7,
318 _ => 0,
319 };
320 if bit != 0 {
321 if (seen_special_root_keys & bit) != 0 {
322 return None;
323 }
324 seen_special_root_keys |= bit;
325 }
326 }
327 }
328 let tools = root.get_table("Tools")?;
329 if (tools.tag.as_deref() != Some("ordered") && tools.entries.len() <= 4)
330 || has_call_args(tools)
331 || !tools
332 .entries
333 .iter()
334 .all(|(k, v)| matches!(k, LuaKey::Str(_)) && v.as_table().is_some())
335 {
336 return None;
337 }
338
339 let cap = tools
340 .entries
341 .len()
342 .saturating_mul(1024)
343 .saturating_add(4096);
344 let mut out = String::with_capacity(cap);
345
346 let mut top_pool: HashMap<&str, NodePool<'_>> = HashMap::with_capacity(self.nodes.len());
347 let mut inner_pool: HashMap<&str, NodePool<'_>> = HashMap::new();
348 let mut instance_defaults: HashMap<(&str, &str), ParamValue> = HashMap::new();
349 for node in &self.nodes {
350 let pool = if node.internal { &mut inner_pool } else { &mut top_pool };
351 let key = node.name.as_str();
352 if let Some(entry) = pool.get_mut(key) {
353 entry.push(node);
354 } else {
355 pool.insert(key, NodePool::One(node));
356 }
357 if !is_group_kind(&node.kind) {
358 continue;
359 }
360 for (inner_op, inner_port, default) in instance_inputs(&node.raw) {
361 if let Some(d) = default {
362 instance_defaults.insert((inner_op, inner_port), d);
363 }
364 }
365 }
366
367 let positional = can_use_positional(root.entries.iter());
368 write_table_prefix(root.tag.as_deref(), &[], 0, &mut out);
369 out.push_str("{\n");
370
371 let mut seen_current_time = false;
372 let mut seen_global_range = false;
373 let mut seen_render_range = false;
374 let mut seen_audio_filename = false;
375 let mut seen_audio_offset = false;
376 let mut seen_prefs = false;
377 let mut seen_tools = false;
378
379 for (k, v) in &root.entries {
380 if let LuaKey::Str(name) = k {
381 match name.as_str() {
382 "CurrentTime" => {
383 seen_current_time = true;
384 write_indent(&mut out, 1);
385 write_entry_key(k, positional, &mut out);
386 write_value(&LuaValue::Number(self.current_time), 1, &mut out);
387 out.push_str(",\n");
388 continue;
389 }
390 "GlobalRange" => {
391 seen_global_range = true;
392 write_indent(&mut out, 1);
393 write_entry_key(k, positional, &mut out);
394 let gr = vec2_lua(self.global_range[0] as f64, self.global_range[1] as f64);
395 write_value(&gr, 1, &mut out);
396 out.push_str(",\n");
397 continue;
398 }
399 "RenderRange" => {
400 seen_render_range = true;
401 write_indent(&mut out, 1);
402 write_entry_key(k, positional, &mut out);
403 let rr = vec2_lua(self.render_range[0] as f64, self.render_range[1] as f64);
404 write_value(&rr, 1, &mut out);
405 out.push_str(",\n");
406 continue;
407 }
408 "AudioFilename" => {
409 seen_audio_filename = true;
410 write_indent(&mut out, 1);
411 write_entry_key(k, positional, &mut out);
412 if let Some(ref af) = self.audio_filename {
413 write_value(&LuaValue::String(af.clone()), 1, &mut out);
414 } else {
415 write_value(v, 1, &mut out);
416 }
417 out.push_str(",\n");
418 continue;
419 }
420 "AudioOffset" => {
421 seen_audio_offset = true;
422 write_indent(&mut out, 1);
423 write_entry_key(k, positional, &mut out);
424 write_value(&LuaValue::Number(self.audio_offset), 1, &mut out);
425 out.push_str(",\n");
426 continue;
427 }
428 "Prefs" => {
429 seen_prefs = true;
430 write_indent(&mut out, 1);
431 write_entry_key(k, positional, &mut out);
432 if self.prefs_needs_sync(v) {
433 let mut prefs_val = v.clone();
434 let prefs_tbl = match prefs_val.as_table_mut() {
435 Some(t) => t,
436 None => {
437 prefs_val = LuaValue::Table(LuaTable::default());
438 prefs_val.as_table_mut().unwrap()
439 }
440 };
441 self.patch_prefs_table(prefs_tbl);
442 write_value(&prefs_val, 1, &mut out);
443 } else {
444 write_value(v, 1, &mut out);
445 }
446 out.push_str(",\n");
447 continue;
448 }
449 "Tools" => {
450 seen_tools = true;
451 write_indent(&mut out, 1);
452 write_entry_key(k, positional, &mut out);
453 if !self.write_tools_streaming(
454 tools,
455 &mut top_pool,
456 &mut inner_pool,
457 &instance_defaults,
458 &mut out,
459 ) {
460 return None;
461 }
462 out.push_str(",\n");
463 continue;
464 }
465 _ => {}
466 }
467 }
468 write_indent(&mut out, 1);
469 write_entry_key(k, positional, &mut out);
470 write_value(v, 1, &mut out);
471 out.push_str(",\n");
472 }
473
474 if !seen_current_time {
475 write_root_kv("CurrentTime", &LuaValue::Number(self.current_time), &mut out);
476 }
477 if !seen_global_range {
478 let gr = vec2_lua(self.global_range[0] as f64, self.global_range[1] as f64);
479 write_root_kv("GlobalRange", &gr, &mut out);
480 }
481 if !seen_render_range {
482 let rr = vec2_lua(self.render_range[0] as f64, self.render_range[1] as f64);
483 write_root_kv("RenderRange", &rr, &mut out);
484 }
485 if !seen_audio_filename {
486 if let Some(ref af) = self.audio_filename {
487 write_root_kv("AudioFilename", &LuaValue::String(af.clone()), &mut out);
488 }
489 }
490 if !seen_audio_offset && self.audio_offset != 0.0 {
491 write_root_kv("AudioOffset", &LuaValue::Number(self.audio_offset), &mut out);
492 }
493 if !seen_prefs {
494 let mut prefs_tbl = LuaTable::default();
495 self.patch_prefs_table(&mut prefs_tbl);
496 write_root_kv("Prefs", &LuaValue::Table(prefs_tbl), &mut out);
497 }
498 if !seen_tools {
499 unreachable!("checked root.get_table(\"Tools\")");
500 }
501
502 out.push_str("}\n");
503 Some(out)
504 }
505
506 fn prefs_needs_sync(&self, prefs_val: &LuaValue) -> bool {
507 let Some(ff) = prefs_val
508 .as_table()
509 .and_then(|p| p.get_table("Comp"))
510 .and_then(|c| c.get_table("FrameFormat"))
511 else {
512 return true;
513 };
514 if ff.get_f64("Width").and_then(normalize_frame_dim) != Some(self.width) {
515 return true;
516 }
517 if ff.get_f64("Height").and_then(normalize_frame_dim) != Some(self.height) {
518 return true;
519 }
520 if ff
521 .get_f64("Rate")
522 .is_none_or(|r| !r.is_finite() || (r - self.fps).abs() > 1e-9)
523 {
524 return true;
525 }
526 let existing_depth = ff
527 .get_f64("DepthFull")
528 .filter(|v| v.is_finite())
529 .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32))
530 .unwrap_or(BitDepth::Int8);
531 existing_depth != self.depth_full
532 }
533
534 fn patch_prefs_table(&self, prefs: &mut LuaTable) {
535 let comp_prefs = ensure_table_mut(prefs, "Comp", None);
536 let ff = ensure_table_mut(comp_prefs, "FrameFormat", None);
537 if ff.get_f64("Width").and_then(normalize_frame_dim) != Some(self.width) {
538 ff.set(LuaKey::Str("Width".to_owned()), LuaValue::Number(self.width as f64));
539 }
540 if ff.get_f64("Height").and_then(normalize_frame_dim) != Some(self.height) {
541 ff.set(LuaKey::Str("Height".to_owned()), LuaValue::Number(self.height as f64));
542 }
543 if ff
544 .get_f64("Rate")
545 .is_none_or(|r| !r.is_finite() || (r - self.fps).abs() > 1e-9)
546 {
547 ff.set(LuaKey::Str("Rate".to_owned()), LuaValue::Number(self.fps));
548 }
549 let existing_depth = ff
550 .get_f64("DepthFull")
551 .filter(|v| v.is_finite())
552 .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32))
553 .unwrap_or(BitDepth::Int8);
554 if existing_depth != self.depth_full {
555 ff.set(
556 LuaKey::Str("DepthFull".to_owned()),
557 LuaValue::Number((self.depth_full as i32) as f64),
558 );
559 }
560 }
561
562 fn write_tools_streaming<'a>(
563 &'a self,
564 tools: &LuaTable,
565 top_pool: &mut HashMap<&'a str, NodePool<'a>>,
566 inner_pool: &mut HashMap<&'a str, NodePool<'a>>,
567 instance_defaults: &HashMap<(&str, &str), ParamValue>,
568 out: &mut String,
569 ) -> bool {
570 let mut remaining_splines: HashMap<&str, &BezierSpline> =
571 self.splines.iter().map(|(k, v)| (k.as_str(), v)).collect();
572
573 // Record top-level spline names first so nested `Tools` matches `sync_existing_splines_in_tools`
574 // priority order even if a duplicate modifier name appears at both levels.
575 let mut top_level_spline_names: HashSet<&str> = HashSet::new();
576 if !remaining_splines.is_empty() {
577 for (k, v) in &tools.entries {
578 if let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) {
579 let tag = tbl.tag.as_deref().unwrap_or("Unknown");
580 if is_modifier_type(tag) && remaining_splines.contains_key(name.as_str()) {
581 top_level_spline_names.insert(name.as_str());
582 }
583 }
584 }
585 }
586
587 let mut seen_in_tools: HashSet<&str> = HashSet::with_capacity(tools.entries.len());
588 let mut emitted_entries: usize = 0;
589
590 write_table_prefix(tools.tag.as_deref(), &[], 1, out);
591 out.push_str("{\n");
592
593 for (k, v) in &tools.entries {
594 let LuaKey::Str(name) = k else {
595 write_indent(out, 2);
596 write_entry_key(k, true, out);
597 write_value(v, 2, out);
598 out.push_str(",\n");
599 emitted_entries += 1;
600 continue;
601 };
602 let Some(tbl) = v.as_table() else {
603 seen_in_tools.insert(name.as_str());
604 write_indent(out, 2);
605 write_entry_key(k, true, out);
606 write_value(v, 2, out);
607 out.push_str(",\n");
608 emitted_entries += 1;
609 continue;
610 };
611
612 let tag = tbl.tag.as_deref().unwrap_or("Unknown");
613 if is_modifier_type(tag) {
614 seen_in_tools.insert(name.as_str());
615 write_indent(out, 2);
616 write_entry_key(k, true, out);
617 if let Some(spline) = remaining_splines.remove(name.as_str()) {
618 if !spline_needs_sync(name, spline, tbl) {
619 write_table(tbl, 2, out);
620 } else {
621 let mut cloned = tbl.clone();
622 sync_spline_table(name, spline, &mut cloned);
623 write_table(&cloned, 2, out);
624 }
625 } else {
626 write_table(tbl, 2, out);
627 }
628 out.push_str(",\n");
629 emitted_entries += 1;
630 continue;
631 }
632
633 let Some(node) = pop_pool(top_pool, name.as_str()) else {
634 // Deleted flow node.
635 continue;
636 };
637 seen_in_tools.insert(name.as_str());
638
639 write_indent(out, 2);
640 write_entry_key(k, true, out);
641
642 if is_group_kind(&node.kind) {
643 if self.group_can_stream_verbatim(
644 node,
645 tbl,
646 inner_pool,
647 instance_defaults,
648 &mut remaining_splines,
649 &top_level_spline_names,
650 ) {
651 write_table(tbl, 2, out);
652 } else {
653 let mut cloned = tbl.clone();
654 self.sync_node_tool(node, &mut cloned, instance_defaults);
655 if let Some(inner) = cloned.get_table_mut("Tools") {
656 self.sync_tools_level(inner, true, top_pool, inner_pool, instance_defaults);
657 }
658 sync_group_wiring(node, &mut cloned);
659 if !remaining_splines.is_empty() {
660 if let Some(inner) = cloned.get_table_mut("Tools") {
661 sync_existing_splines_in_tools_excluding(
662 inner,
663 &mut remaining_splines,
664 &top_level_spline_names,
665 );
666 }
667 }
668 write_table(&cloned, 2, out);
669 }
670 } else if self.node_can_stream_verbatim(
671 node,
672 tbl,
673 instance_defaults,
674 &mut remaining_splines,
675 &top_level_spline_names,
676 ) {
677 write_table(tbl, 2, out);
678 } else {
679 let mut cloned = tbl.clone();
680 self.sync_node_tool(node, &mut cloned, instance_defaults);
681 if !remaining_splines.is_empty() {
682 if let Some(inner) = cloned.get_table_mut("Tools") {
683 sync_existing_splines_in_tools_excluding(
684 inner,
685 &mut remaining_splines,
686 &top_level_spline_names,
687 );
688 }
689 }
690 write_table(&cloned, 2, out);
691 }
692 out.push_str(",\n");
693 emitted_entries += 1;
694 }
695
696 // Newly added top-level nodes not yet present in `tools`
697 for node in self.nodes.iter().filter(|n| !n.internal) {
698 if seen_in_tools.contains(node.name.as_str()) {
699 continue;
700 }
701 seen_in_tools.insert(node.name.as_str());
702 let Some(node) = pop_pool(top_pool, node.name.as_str()) else {
703 continue;
704 };
705 let mut new_tbl = if node.raw.tag.is_some() {
706 node.raw.clone()
707 } else {
708 LuaTable { tag: None, entries: Vec::new() }
709 };
710 if new_tbl.tag.is_none() {
711 new_tbl.tag = Some(node.kind.clone());
712 }
713 self.sync_node_tool(node, &mut new_tbl, instance_defaults);
714 if is_group_kind(&node.kind) {
715 if let Some(inner) = new_tbl.get_table_mut("Tools") {
716 self.sync_tools_level(inner, true, top_pool, inner_pool, instance_defaults);
717 }
718 sync_group_wiring(node, &mut new_tbl);
719 }
720 if !remaining_splines.is_empty() {
721 if let Some(inner) = new_tbl.get_table_mut("Tools") {
722 sync_existing_splines_in_tools_excluding(
723 inner,
724 &mut remaining_splines,
725 &top_level_spline_names,
726 );
727 }
728 }
729 write_indent(out, 2);
730 write_entry_key(&LuaKey::Str(node.name.clone()), true, out);
731 write_table(&new_tbl, 2, out);
732 out.push_str(",\n");
733 emitted_entries += 1;
734 }
735
736 // Newly added splines not yet present in `tools`
737 if !remaining_splines.is_empty() {
738 let mut new_names: Vec<&str> = remaining_splines.keys().copied().collect();
739 new_names.sort_unstable();
740 for spline_name in new_names {
741 let spline = remaining_splines[spline_name];
742 let mut sp_tbl = LuaTable {
743 tag: Some("BezierSpline".to_owned()),
744 entries: Vec::with_capacity(2),
745 };
746 sp_tbl.set(
747 LuaKey::Str("SplineColor".to_owned()),
748 spline_color_lua(spline.color),
749 );
750 sp_tbl.set(
751 LuaKey::Str("KeyFrames".to_owned()),
752 LuaValue::Table(build_keyframes_table(spline)),
753 );
754 write_indent(out, 2);
755 write_entry_key(&LuaKey::Str(spline_name.to_owned()), true, out);
756 write_table(&sp_tbl, 2, out);
757 out.push_str(",\n");
758 emitted_entries += 1;
759 }
760 }
761
762 if emitted_entries == 0 || (tools.tag.as_deref() != Some("ordered") && emitted_entries <= 4) {
763 return false;
764 }
765
766 write_indent(out, 1);
767 out.push('}');
768 true
769 }
770
771 fn node_header_needs_sync(&self, node: &Node, tool_tbl: &LuaTable) -> bool {
772 // ViewInfo.Pos
773 if let Some(vi) = tool_tbl.get_table("ViewInfo") {
774 let pos_changed = vi
775 .get_table("Pos")
776 .and_then(read_vec2)
777 .is_none_or(|[x, y]| {
778 (x as f32 - node.pos[0]).abs() > 1e-4 || (y as f32 - node.pos[1]).abs() > 1e-4
779 });
780 if pos_changed {
781 return true;
782 }
783 } else if node.pos[0] != 0.0 || node.pos[1] != 0.0 {
784 return true;
785 }
786
787 // PassThrough
788 if node.bypassed {
789 if tool_tbl.get_bool("PassThrough") != Some(true) {
790 return true;
791 }
792 } else if tool_tbl.get("PassThrough").is_some() {
793 return true;
794 }
795
796 // Loader clip timing
797 if node.kind == "Loader" {
798 let clip_exists = tool_tbl.get_table("Clips").is_some_and(|c| {
799 c.entries
800 .iter()
801 .any(|(_, v)| v.as_table().is_some_and(|t| t.get_str("Filename").is_some()))
802 });
803 if clip_exists {
804 let edited = |port: &str| {
805 let now = node.static_number(port)?;
806 let before = tool_tbl
807 .get_table("Inputs")
808 .and_then(|i| i.get_table(port))
809 .and_then(|t| t.get("Value"))
810 .and_then(lua_value_as_number);
811 (before != Some(now)).then_some(now)
812 };
813 if edited("GlobalIn").is_some()
814 || edited("GlobalOut").is_some()
815 || edited("Loop").is_some()
816 || edited("Reverse").is_some()
817 {
818 return true;
819 }
820 }
821 }
822
823 false
824 }
825
826 fn node_can_stream_verbatim<'a>(
827 &'a self,
828 node: &Node,
829 tool_tbl: &LuaTable,
830 instance_defaults: &HashMap<(&str, &str), ParamValue>,
831 remaining_splines: &mut HashMap<&'a str, &'a BezierSpline>,
832 top_level_spline_names: &HashSet<&str>,
833 ) -> bool {
834 if self.node_header_needs_sync(node, tool_tbl) {
835 return false;
836 }
837 let master_inputs = node
838 .raw
839 .get_str("SourceOp")
840 .and_then(|m| self.find_node(m))
841 .map(|mid| &self.nodes[mid.0].inputs);
842 if node_inputs_need_sync(
843 node,
844 master_inputs,
845 instance_defaults,
846 &self.cross_macro_wires,
847 tool_tbl,
848 ) {
849 return false;
850 }
851 if let Some(inner) = tool_tbl.get_table("Tools") {
852 let mut claimed_splines: HashSet<&str> = HashSet::new();
853 if !nested_splines_verbatim(
854 inner,
855 remaining_splines,
856 top_level_spline_names,
857 &mut claimed_splines,
858 ) {
859 return false;
860 }
861 consume_nested_splines(inner, remaining_splines, top_level_spline_names);
862 }
863 true
864 }
865
866 fn group_can_stream_verbatim<'a>(
867 &'a self,
868 node: &Node,
869 tool_tbl: &LuaTable,
870 inner_pool: &mut HashMap<&'a str, NodePool<'a>>,
871 instance_defaults: &HashMap<(&str, &str), ParamValue>,
872 remaining_splines: &mut HashMap<&'a str, &'a BezierSpline>,
873 top_level_spline_names: &HashSet<&str>,
874 ) -> bool {
875 if self.node_header_needs_sync(node, tool_tbl) {
876 return false;
877 }
878 if group_wiring_needs_sync(node, tool_tbl) {
879 return false;
880 }
881 let Some(inner_tools) = tool_tbl.get_table("Tools") else {
882 return true;
883 };
884 let mut peek_offsets: HashMap<&str, usize> = HashMap::new();
885 let mut claimed_splines: HashSet<&str> = HashSet::new();
886 if !self.check_inner_tools_verbatim(
887 inner_tools,
888 inner_pool,
889 &mut peek_offsets,
890 instance_defaults,
891 remaining_splines,
892 top_level_spline_names,
893 &mut claimed_splines,
894 ) {
895 return false;
896 }
897 // All checks passed: commit pops from `inner_pool` and removals from `remaining_splines`.
898 commit_inner_tools_verbatim(
899 inner_tools,
900 inner_pool,
901 remaining_splines,
902 top_level_spline_names,
903 );
904 true
905 }
906
907 fn check_inner_tools_verbatim<'a, 'b>(
908 &'a self,
909 inner_tools: &'b LuaTable,
910 inner_pool: &HashMap<&'a str, NodePool<'a>>,
911 peek_offsets: &mut HashMap<&'b str, usize>,
912 instance_defaults: &HashMap<(&str, &str), ParamValue>,
913 remaining_splines: &HashMap<&'a str, &'a BezierSpline>,
914 top_level_spline_names: &HashSet<&str>,
915 claimed_splines: &mut HashSet<&'b str>,
916 ) -> bool {
917 // Pass 1: check direct entries at this `inner_tools` level BEFORE recursing into
918 // nested `.Tools` tables (matching `sync_existing_splines_in_tools` top-down order).
919 if !remaining_splines.is_empty() {
920 for (k, v) in &inner_tools.entries {
921 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
922 if !is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) {
923 continue;
924 }
925 if !top_level_spline_names.contains(name.as_str())
926 && !claimed_splines.contains(name.as_str())
927 {
928 if let Some(&spline) = remaining_splines.get(name.as_str()) {
929 if spline_needs_sync(name, spline, tbl) {
930 return false;
931 }
932 claimed_splines.insert(name.as_str());
933 }
934 }
935 }
936 }
937
938 // Pass 2: validate flow nodes and recurse into nested `.Tools` tables.
939 for (k, v) in &inner_tools.entries {
940 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
941 let tag = tbl.tag.as_deref().unwrap_or("Unknown");
942 if is_modifier_type(tag) {
943 if let Some(sub_tools) = tbl.get_table("Tools") {
944 if !nested_splines_verbatim(
945 sub_tools,
946 remaining_splines,
947 top_level_spline_names,
948 claimed_splines,
949 ) {
950 return false;
951 }
952 }
953 continue;
954 }
955 // Flow node: check if it survived `retain` and matches `node`
956 let offset = peek_offsets.entry(name.as_str()).or_insert(0);
957 let Some(inner_node) = inner_pool.get(name.as_str()).and_then(|p| p.peek_at(*offset)) else {
958 // Deleted inner node!
959 return false;
960 };
961 *offset += 1;
962
963 if is_group_kind(&inner_node.kind) {
964 if self.node_header_needs_sync(inner_node, tbl) || group_wiring_needs_sync(inner_node, tbl) {
965 return false;
966 }
967 if let Some(sub_tools) = tbl.get_table("Tools") {
968 if !self.check_inner_tools_verbatim(
969 sub_tools,
970 inner_pool,
971 peek_offsets,
972 instance_defaults,
973 remaining_splines,
974 top_level_spline_names,
975 claimed_splines,
976 ) {
977 return false;
978 }
979 }
980 } else {
981 if self.node_header_needs_sync(inner_node, tbl) {
982 return false;
983 }
984 let master_inputs = inner_node
985 .raw
986 .get_str("SourceOp")
987 .and_then(|m| self.find_node(m))
988 .map(|mid| &self.nodes[mid.0].inputs);
989 if node_inputs_need_sync(
990 inner_node,
991 master_inputs,
992 instance_defaults,
993 &self.cross_macro_wires,
994 tbl,
995 ) {
996 return false;
997 }
998 if let Some(sub_tools) = tbl.get_table("Tools") {
999 if !nested_splines_verbatim(
1000 sub_tools,
1001 remaining_splines,
1002 top_level_spline_names,
1003 claimed_splines,
1004 ) {
1005 return false;
1006 }
1007 }
1008 }
1009 }
1010 true
1011 }
1012 /// Atomically saves this composition to `path`.
1013 /// If `path` already exists, backs up the original bytes to
1014 /// `<temp_dir>/fission-backups/<stem>_<unix_millis>_<pid>_<seq>.comp.bak` and returns `Ok(Some(backup_path))`.
1015 /// A symlink at `path` is followed, so the link itself survives the save.
1016 pub fn save_to_file(&self, path: impl AsRef<Path>) -> Result<Option<PathBuf>, std::io::Error> {
1017 static BACKUP_SEQ: AtomicU64 = AtomicU64::new(0);
1018
1019 let path = path.as_ref();
1020 let target = if std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
1021 // A dangling link is followed one hop so saving creates its target.
1022 std::fs::canonicalize(path).or_else(|_| {
1023 let hop = std::fs::read_link(path)?;
1024 Ok::<_, std::io::Error>(path.parent().unwrap_or_else(|| Path::new(".")).join(hop))
1025 })?
1026 } else {
1027 path.to_path_buf()
1028 };
1029 let path = target.as_path();
1030 let stem = path
1031 .file_stem()
1032 .and_then(|s| s.to_str())
1033 .filter(|s| !s.is_empty())
1034 .unwrap_or("comp");
1035 let seq = BACKUP_SEQ.fetch_add(1, Ordering::Relaxed);
1036
1037 let backup_path = if path.exists() {
1038 let backup_dir = std::env::temp_dir().join("fission-backups");
1039 std::fs::create_dir_all(&backup_dir)?;
1040 let unix_millis = std::time::SystemTime::now()
1041 .duration_since(std::time::UNIX_EPOCH)
1042 .map(|d| d.as_millis())
1043 .unwrap_or(0);
1044 let backup_file = backup_dir.join(format!("{stem}_{unix_millis}_{}_{seq}.comp.bak", std::process::id()));
1045 std::fs::copy(path, &backup_file)?;
1046 Some(backup_file)
1047 } else {
1048 None
1049 };
1050
1051 let parent = path
1052 .parent()
1053 .filter(|p| !p.as_os_str().is_empty())
1054 .unwrap_or_else(|| Path::new("."));
1055 std::fs::create_dir_all(parent)?;
1056
1057 let nanos = std::time::SystemTime::now()
1058 .duration_since(std::time::UNIX_EPOCH)
1059 .map(|d| d.as_nanos())
1060 .unwrap_or(0);
1061 let tmp_path = parent.join(format!(".{stem}.{}.{seq}.{nanos}.tmp", std::process::id()));
1062
1063 let serialized = self.to_fusion_string();
1064 let written = std::fs::OpenOptions::new()
1065 .write(true)
1066 .create_new(true)
1067 .open(&tmp_path)
1068 .and_then(|mut f| {
1069 f.write_all(serialized.as_bytes())?;
1070 f.sync_all()
1071 });
1072 if let Err(e) = written {
1073 // `create_new` failing means the name is someone else's file; never delete that.
1074 if e.kind() != std::io::ErrorKind::AlreadyExists {
1075 let _ = std::fs::remove_file(&tmp_path);
1076 }
1077 return Err(e);
1078 }
1079 if let Err(e) = std::fs::rename(&tmp_path, path) {
1080 let _ = std::fs::remove_file(&tmp_path);
1081 return Err(e);
1082 }
1083 // Best effort: persist the rename itself.
1084 let _ = std::fs::File::open(parent).and_then(|dir| dir.sync_all());
1085
1086 Ok(backup_path)
1087 }
1088}
1089
1090fn write_root_kv(key: &str, val: &LuaValue, out: &mut String) {
1091 write_indent(out, 1);
1092 out.push_str(key);
1093 out.push_str(" = ");
1094 write_value(val, 1, out);
1095 out.push_str(",\n");
1096}
1097
1098fn commit_inner_tools_verbatim<'a>(
1099 inner_tools: &LuaTable,
1100 inner_pool: &mut HashMap<&'a str, NodePool<'a>>,
1101 remaining_splines: &mut HashMap<&'a str, &'a BezierSpline>,
1102 top_level_spline_names: &HashSet<&str>,
1103) {
1104 // Pass 1: consume direct entries at this level BEFORE recursing into nested `.Tools`
1105 // (matching `sync_existing_splines_in_tools` top-down order).
1106 if !remaining_splines.is_empty() {
1107 for (k, v) in &inner_tools.entries {
1108 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
1109 if !is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) {
1110 continue;
1111 }
1112 if !top_level_spline_names.contains(name.as_str()) {
1113 remaining_splines.remove(name.as_str());
1114 if remaining_splines.is_empty() {
1115 break;
1116 }
1117 }
1118 }
1119 }
1120 // Pass 2: pop inner flow nodes and recurse into nested `.Tools`.
1121 for (k, v) in &inner_tools.entries {
1122 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
1123 let tag = tbl.tag.as_deref().unwrap_or("Unknown");
1124 if is_modifier_type(tag) {
1125 if let Some(sub_tools) = tbl.get_table("Tools") {
1126 consume_nested_splines(sub_tools, remaining_splines, top_level_spline_names);
1127 }
1128 continue;
1129 }
1130 let Some(inner_node) = pop_pool(inner_pool, name.as_str()) else { continue };
1131 if let Some(sub_tools) = tbl.get_table("Tools") {
1132 if is_group_kind(&inner_node.kind) {
1133 commit_inner_tools_verbatim(sub_tools, inner_pool, remaining_splines, top_level_spline_names);
1134 } else {
1135 consume_nested_splines(sub_tools, remaining_splines, top_level_spline_names);
1136 }
1137 }
1138 }
1139}
1140
1141fn nested_splines_verbatim<'a, 'b>(
1142 tools: &'b LuaTable,
1143 remaining_splines: &HashMap<&'a str, &'a BezierSpline>,
1144 top_level_spline_names: &HashSet<&str>,
1145 claimed_splines: &mut HashSet<&'b str>,
1146) -> bool {
1147 if remaining_splines.is_empty() {
1148 return true;
1149 }
1150 for (k, v) in &tools.entries {
1151 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
1152 if !is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) {
1153 continue;
1154 }
1155 if !top_level_spline_names.contains(name.as_str())
1156 && !claimed_splines.contains(name.as_str())
1157 {
1158 if let Some(&spline) = remaining_splines.get(name.as_str()) {
1159 if spline_needs_sync(name, spline, tbl) {
1160 return false;
1161 }
1162 claimed_splines.insert(name.as_str());
1163 }
1164 }
1165 }
1166 for (_, v) in &tools.entries {
1167 if let Some(sub) = v.as_table().and_then(|t| t.get_table("Tools")) {
1168 if !nested_splines_verbatim(
1169 sub,
1170 remaining_splines,
1171 top_level_spline_names,
1172 claimed_splines,
1173 ) {
1174 return false;
1175 }
1176 }
1177 }
1178 true
1179}
1180
1181fn consume_nested_splines(
1182 tools: &LuaTable,
1183 remaining_splines: &mut HashMap<&str, &BezierSpline>,
1184 top_level_spline_names: &HashSet<&str>,
1185) {
1186 if remaining_splines.is_empty() {
1187 return;
1188 }
1189 for (k, v) in &tools.entries {
1190 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { continue };
1191 if !is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) {
1192 continue;
1193 }
1194 if !top_level_spline_names.contains(name.as_str()) {
1195 remaining_splines.remove(name.as_str());
1196 if remaining_splines.is_empty() {
1197 return;
1198 }
1199 }
1200 }
1201 for (_, v) in &tools.entries {
1202 if let Some(sub) = v.as_table().and_then(|t| t.get_table("Tools")) {
1203 consume_nested_splines(sub, remaining_splines, top_level_spline_names);
1204 if remaining_splines.is_empty() {
1205 return;
1206 }
1207 }
1208 }
1209}
1210
1211fn sync_existing_splines_in_tools_excluding(
1212 tools: &mut LuaTable,
1213 remaining: &mut HashMap<&str, &BezierSpline>,
1214 excluded: &HashSet<&str>,
1215) {
1216 if remaining.is_empty() {
1217 return;
1218 }
1219 for (k, v) in &mut tools.entries {
1220 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table_mut()) else { continue };
1221 if !is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) || excluded.contains(name.as_str()) {
1222 continue;
1223 }
1224 if let Some(spline) = remaining.remove(name.as_str()) {
1225 sync_spline_table(name, spline, tbl);
1226 if remaining.is_empty() {
1227 return;
1228 }
1229 }
1230 }
1231 for (_, v) in &mut tools.entries {
1232 if let Some(inner) = v.as_table_mut().and_then(|t| t.get_table_mut("Tools")) {
1233 sync_existing_splines_in_tools_excluding(inner, remaining, excluded);
1234 if remaining.is_empty() {
1235 return;
1236 }
1237 }
1238 }
1239}
1240
1241fn spline_needs_sync(spline_name: &str, spline: &BezierSpline, tbl: &LuaTable) -> bool {
1242 if spline_color_from_lua(tbl) != spline.color {
1243 return true;
1244 }
1245 if keyframes_match_lua(spline, tbl) {
1246 return false;
1247 }
1248 let existing = BezierSpline::from_lua(spline_name.to_owned(), tbl);
1249 let unchanged_cyclic = tbl.tag.as_deref() == Some("LUTBezier") && {
1250 let mut normalized = existing.clone();
1251 normalized.apply_hue_curves_cyclic_ends();
1252 normalized.keyframes == spline.keyframes
1253 };
1254 existing.keyframes != spline.keyframes && !unchanged_cyclic
1255}
1256
1257fn group_wiring_needs_sync(node: &Node, group_tbl: &LuaTable) -> bool {
1258 let Some(inputs) = group_tbl.get_table("Inputs") else {
1259 return false;
1260 };
1261 let Some(inner_tools) = group_tbl.get_table("Tools") else {
1262 return false;
1263 };
1264 for (k, v) in &inputs.entries {
1265 let LuaKey::Str(port) = k else { continue };
1266 let Some(t) = v.as_table() else { continue };
1267 let Some(inner_op) = t.get_str("SourceOp") else { continue };
1268 let Some(inner_port) = t.get_str("Source") else { continue };
1269 let desired = node.inputs.get(port);
1270 if desired.is_some_and(|b| b.source_op.as_deref() == Some(inner_op)) {
1271 continue;
1272 }
1273 let Some(inner_tbl) = super::math::find_raw_tool(inner_tools, inner_op) else {
1274 continue;
1275 };
1276 let existing_it = inner_tbl
1277 .get_table("Inputs")
1278 .and_then(|i| i.get_table(inner_port));
1279 let cur_src_op = existing_it.and_then(|it| it.get_str("SourceOp"));
1280 let cur_src_out = existing_it.and_then(|it| it.get_str("Source"));
1281 match desired {
1282 Some(b) => {
1283 if existing_it.is_none()
1284 || (cur_src_op, cur_src_out) != (b.source_op.as_deref(), b.source_output.as_deref())
1285 {
1286 return true;
1287 }
1288 }
1289 None if cur_src_op.is_some() => {
1290 return true;
1291 }
1292 _ => {}
1293 }
1294 }
1295 false
1296}
1297
1298fn node_inputs_need_sync(
1299 node: &Node,
1300 master_inputs: Option<&HashMap<String, InputBinding>>,
1301 instance_defaults: &HashMap<(&str, &str), ParamValue>,
1302 cross_macro_wires: &HashSet<(String, String)>,
1303 tool_tbl: &LuaTable,
1304) -> bool {
1305 let in_tbl = tool_tbl.get_table("Inputs");
1306 if let Some(in_tbl) = in_tbl {
1307 for (k, v) in &in_tbl.entries {
1308 let LuaKey::Str(port) = k else { continue };
1309 if v.as_table().is_some() && !node.inputs.contains_key(port) {
1310 return true;
1311 }
1312 }
1313 }
1314
1315 for (port, binding) in &node.inputs {
1316 if !instance_defaults.is_empty()
1317 && binding.source_op.is_none()
1318 && binding.expression.is_none()
1319 && binding.value.is_some()
1320 && binding.value.as_ref() == instance_defaults.get(&(node.name.as_str(), port.as_str()))
1321 && in_tbl
1322 .and_then(|i| i.get_table(port))
1323 .is_none_or(|t| t.get("Value").is_none())
1324 {
1325 continue;
1326 }
1327
1328 if let Some(it) = in_tbl.and_then(|i| i.get_table(port)) {
1329 let clear_src = !cross_macro_wires.is_empty()
1330 && binding.source_op.is_none()
1331 && cross_macro_wires.contains(&(node.name.clone(), port.clone()));
1332 if binding_matches_lua(it, binding, clear_src) {
1333 continue;
1334 }
1335 // Check empty-stub master inheritance skip
1336 let is_empty_stub = it.get("Value").is_none()
1337 && (clear_src || it.get_str("SourceOp").is_none())
1338 && it.get_str("Expression").is_none();
1339 if is_empty_stub && master_inputs.is_some_and(|m| m.get(port) == Some(binding)) {
1340 continue;
1341 }
1342 return true;
1343 } else {
1344 if binding.value.is_none() && binding.source_op.is_none() && binding.expression.is_none() {
1345 continue;
1346 }
1347 if binding.source_op.is_none()
1348 && binding.expression.is_none()
1349 && binding.value.is_some()
1350 && binding.value == user_control_default(&node.raw, port)
1351 {
1352 continue;
1353 }
1354 if let Some(master) = master_inputs {
1355 if master.get(port) == Some(binding) {
1356 continue;
1357 }
1358 }
1359 return true;
1360 }
1361 }
1362 false
1363}
1364
1365pub(crate) fn vec2_lua(x: f64, y: f64) -> LuaValue {
1366 LuaValue::Table(LuaTable {
1367 tag: None,
1368 entries: vec![
1369 (LuaKey::Index(1), LuaValue::Number(x)),
1370 (LuaKey::Index(2), LuaValue::Number(y)),
1371 ],
1372 })
1373}
1374
1375pub(crate) fn ensure_table_mut<'a>(parent: &'a mut LuaTable, key: &str, tag: Option<&str>) -> &'a mut LuaTable {
1376 if parent.get_table(key).is_none() {
1377 parent.set(
1378 LuaKey::Str(key.to_owned()),
1379 LuaValue::Table(LuaTable {
1380 tag: tag.map(str::to_owned),
1381 entries: Vec::new(),
1382 }),
1383 );
1384 }
1385 parent.get_table_mut(key).expect("table just inserted")
1386}
1387
1388pub(crate) fn param_value_to_lua(v: &ParamValue) -> LuaValue {
1389 match v {
1390 ParamValue::Number(n) => LuaValue::Number(*n),
1391 ParamValue::Point([x, y]) => vec2_lua(*x, *y),
1392 ParamValue::Text(s) => LuaValue::String(s.clone()),
1393 ParamValue::FuId(s) => LuaValue::Table(LuaTable {
1394 tag: Some("FuID".to_owned()),
1395 entries: vec![(LuaKey::Index(1), LuaValue::String(s.clone()))],
1396 }),
1397 ParamValue::Gradient(g) => {
1398 let mut colors = LuaTable::default();
1399 for stop in &g.stops {
1400 let key = if stop.pos.fract() == 0.0 && stop.pos.abs() < 9_007_199_254_740_992.0 {
1401 LuaKey::Index(stop.pos as i64)
1402 } else {
1403 LuaKey::Number(stop.pos)
1404 };
1405 colors.entries.push((
1406 key,
1407 LuaValue::Table(LuaTable {
1408 tag: None,
1409 entries: vec![
1410 (LuaKey::Index(1), LuaValue::Number(stop.rgba[0] as f64)),
1411 (LuaKey::Index(2), LuaValue::Number(stop.rgba[1] as f64)),
1412 (LuaKey::Index(3), LuaValue::Number(stop.rgba[2] as f64)),
1413 (LuaKey::Index(4), LuaValue::Number(stop.rgba[3] as f64)),
1414 ],
1415 }),
1416 ));
1417 }
1418 LuaValue::Table(LuaTable {
1419 tag: Some("Gradient".to_owned()),
1420 entries: vec![(LuaKey::Str("Colors".to_owned()), LuaValue::Table(colors))],
1421 })
1422 }
1423 ParamValue::Raw(raw) => raw.clone(),
1424 }
1425}
1426
1427fn user_control_default(raw: &LuaTable, name: &str) -> Option<ParamValue> {
1428 let ut = raw.get_table("UserControls")?.get_table(name)?;
1429 let is_point = ut.get_str("LINKID_DataType") == Some("Point")
1430 || ut.get_str("INPID_InputControl") == Some("OffsetControl");
1431 if is_point {
1432 let dx = ut.get_f64("INP_DefaultX").unwrap_or(0.5);
1433 let dy = ut.get_f64("INP_DefaultY").unwrap_or(0.5);
1434 Some(ParamValue::Point([dx, dy]))
1435 } else {
1436 ut.get("INP_Default").map(parse_param_value)
1437 }
1438}
1439
1440pub(crate) fn is_group_kind(kind: &str) -> bool {
1441 matches!(kind, "MacroOperator" | "GroupOperator")
1442}
1443
1444/// `(inner_op, inner_port, default)` for each `InstanceInput` exposed by a Group/Macro tool table.
1445fn instance_inputs(group: &LuaTable) -> impl Iterator<Item = (&str, &str, Option<ParamValue>)> {
1446 group.get_table("Inputs").into_iter().flat_map(|inputs| {
1447 inputs.entries.iter().filter_map(|(_, v)| {
1448 let t = v.as_table()?;
1449 Some((t.get_str("SourceOp")?, t.get_str("Source")?, t.get("Default").map(parse_param_value)))
1450 })
1451 })
1452}
1453
1454/// Writes external wires connected to a Group/Macro node back onto the inner tool inputs that its
1455/// `InstanceInput`s expose (load surfaces them as `node.inputs`).
1456fn sync_group_wiring(node: &Node, group_tbl: &mut LuaTable) {
1457 let exposed: Vec<(String, String, String)> = group_tbl
1458 .get_table("Inputs")
1459 .map(|inputs| {
1460 inputs
1461 .entries
1462 .iter()
1463 .filter_map(|(k, v)| {
1464 let LuaKey::Str(in_name) = k else { return None };
1465 let t = v.as_table()?;
1466 Some((in_name.clone(), t.get_str("SourceOp")?.to_owned(), t.get_str("Source")?.to_owned()))
1467 })
1468 .collect()
1469 })
1470 .unwrap_or_default();
1471 let Some(inner_tools) = group_tbl.get_table_mut("Tools") else { return };
1472 for (port, inner_op, inner_port) in exposed {
1473 let desired = node.inputs.get(&port);
1474 // Still the raw InstanceInput binding: nothing was rewired.
1475 if desired.is_some_and(|b| b.source_op.as_deref() == Some(inner_op.as_str())) {
1476 continue;
1477 }
1478 let Some(inner_tbl) = find_raw_tool_mut(inner_tools, &inner_op) else { continue };
1479 let current = inner_tbl
1480 .get_table("Inputs")
1481 .and_then(|i| i.get_table(&inner_port))
1482 .map(parse_input_binding);
1483 let wired = |b: &InputBinding| (b.source_op.clone(), b.source_output.clone());
1484 match desired {
1485 Some(b) if current.as_ref().map(wired) != Some(wired(b)) => {
1486 let input = ensure_table_mut(ensure_table_mut(inner_tbl, "Inputs", None), &inner_port, Some("Input"));
1487 for (key, val) in [("SourceOp", &b.source_op), ("Source", &b.source_output)] {
1488 match val {
1489 Some(v) => input.set(LuaKey::Str(key.to_owned()), LuaValue::String(v.clone())),
1490 None => {
1491 input.remove(&LuaKey::Str(key.to_owned()));
1492 }
1493 }
1494 }
1495 }
1496 None if current.as_ref().is_some_and(|c| c.source_op.is_some()) => {
1497 if let Some(input) = inner_tbl.get_table_mut("Inputs").and_then(|i| i.get_table_mut(&inner_port)) {
1498 input.remove(&LuaKey::Str("SourceOp".to_owned()));
1499 input.remove(&LuaKey::Str("Source".to_owned()));
1500 }
1501 }
1502 _ => {}
1503 }
1504 }
1505}
1506
1507fn lua_value_as_number(v: &LuaValue) -> Option<f64> {
1508 match v {
1509 LuaValue::Number(n) => Some(*n),
1510 LuaValue::Bool(b) => Some(if *b { 1.0 } else { 0.0 }),
1511 LuaValue::Table(t) if t.tag.as_deref() == Some("Number") => Some(t.get_f64("Value").unwrap_or(0.0)),
1512 _ => None,
1513 }
1514}
1515
1516fn param_matches_lua(v: &LuaValue, p: &ParamValue) -> bool {
1517 match (v, p) {
1518 (LuaValue::Number(n), ParamValue::Number(pn)) => n == pn,
1519 (LuaValue::Bool(b), ParamValue::Number(pn)) => (if *b { 1.0 } else { 0.0 }) == *pn,
1520 (LuaValue::String(s), ParamValue::Text(ps)) => s == ps,
1521 (LuaValue::Table(t), _) => match t.tag.as_deref() {
1522 Some("FuID") => {
1523 matches!(p, ParamValue::FuId(pf) if t.get_index(1).and_then(LuaValue::as_str).unwrap_or("") == pf)
1524 }
1525 Some("Number") => {
1526 matches!(p, ParamValue::Number(pn) if t.get_f64("Value").unwrap_or(0.0) == *pn)
1527 }
1528 Some("Gradient") => {
1529 matches!(p, ParamValue::Gradient(pg) if Gradient::from_lua(t) == *pg)
1530 }
1531 _ => {
1532 if let Some(pt) = read_vec2(t) {
1533 matches!(p, ParamValue::Point(pp) if pt == *pp)
1534 } else {
1535 matches!(p, ParamValue::Raw(LuaValue::Table(rt)) if rt == t)
1536 }
1537 }
1538 },
1539 (LuaValue::Nil, ParamValue::Raw(LuaValue::Nil)) => true,
1540 _ => false,
1541 }
1542}
1543
1544fn binding_matches_lua(it: &LuaTable, binding: &InputBinding, clear_source_op: bool) -> bool {
1545 let mut source_op: Option<&str> = None;
1546 let mut source_output: Option<&str> = None;
1547 let mut expression: Option<&str> = None;
1548 let mut value: Option<&LuaValue> = None;
1549 for (k, v) in &it.entries {
1550 let LuaKey::Str(s) = k else { continue };
1551 match s.as_str() {
1552 "SourceOp" => {
1553 if let Some(sv) = v.as_str() {
1554 source_op = Some(sv);
1555 }
1556 }
1557 "Source" => {
1558 if let Some(sv) = v.as_str() {
1559 source_output = Some(sv);
1560 }
1561 }
1562 "Expression" => {
1563 if let Some(sv) = v.as_str() {
1564 expression = Some(sv);
1565 }
1566 }
1567 "Value" => {
1568 value = Some(v);
1569 }
1570 _ => {}
1571 }
1572 }
1573 if clear_source_op {
1574 source_op = None;
1575 }
1576 if source_op != binding.source_op.as_deref()
1577 || source_output != binding.source_output.as_deref()
1578 || expression != binding.expression.as_deref()
1579 {
1580 return false;
1581 }
1582 match (value, &binding.value) {
1583 (None, None) => true,
1584 (Some(lv), Some(pv)) => param_matches_lua(lv, pv),
1585 _ => false,
1586 }
1587}
1588
1589fn sync_node_inputs(
1590 node: &Node,
1591 master_inputs: Option<&HashMap<String, InputBinding>>,
1592 instance_defaults: &HashMap<(&str, &str), ParamValue>,
1593 cross_macro_wires: &HashSet<(String, String)>,
1594 tool_tbl: &mut LuaTable,
1595) {
1596 // First remove any input present in raw `Inputs` that was explicitly removed from `node.inputs`.
1597 if let Some(in_tbl) = tool_tbl.get_table_mut("Inputs") {
1598 in_tbl.entries.retain(|(k, v)| {
1599 let LuaKey::Str(port) = k else { return true };
1600 if v.as_table().is_none() {
1601 return true;
1602 }
1603 node.inputs.contains_key(port)
1604 });
1605 }
1606
1607 // Collect sorted port names for deterministic output when appending new inputs.
1608 let mut ports: Vec<&String> = node.inputs.keys().collect();
1609 if ports.len() > 1 {
1610 ports.sort();
1611 }
1612
1613 for port in ports {
1614 let binding = &node.inputs[port];
1615 // Load fills unset inner-tool inputs from the enclosing group's `InstanceInput` default.
1616 if !instance_defaults.is_empty()
1617 && binding.source_op.is_none()
1618 && binding.expression.is_none()
1619 && binding.value.is_some()
1620 && binding.value.as_ref() == instance_defaults.get(&(node.name.as_str(), port.as_str()))
1621 && tool_tbl
1622 .get_table("Inputs")
1623 .and_then(|i| i.get_table(port))
1624 .is_none_or(|t| t.get("Value").is_none())
1625 {
1626 continue;
1627 }
1628
1629 let existing_tbl = tool_tbl.get_table("Inputs").and_then(|i| i.get_table(port));
1630 if let Some(it) = existing_tbl {
1631 let clear_src = !cross_macro_wires.is_empty()
1632 && binding.source_op.is_none()
1633 && cross_macro_wires.contains(&(node.name.clone(), port.clone()));
1634 if binding_matches_lua(it, binding, clear_src) {
1635 continue;
1636 }
1637 let mut orig = parse_input_binding(it);
1638 if clear_src {
1639 orig.source_op = None;
1640 }
1641 // Don't materialize inherited master inputs into an empty stub `Input {}` on instanced tools.
1642 if orig.value.is_none()
1643 && orig.source_op.is_none()
1644 && orig.expression.is_none()
1645 && master_inputs.is_some_and(|m| m.get(port) == Some(binding))
1646 {
1647 continue;
1648 }
1649 let in_tbl = ensure_table_mut(tool_tbl, "Inputs", None);
1650 if let Some(it) = in_tbl.get_table_mut(port) {
1651 if orig.source_op != binding.source_op {
1652 match &binding.source_op {
1653 Some(op) => it.set(LuaKey::Str("SourceOp".to_owned()), LuaValue::String(op.clone())),
1654 None => {
1655 it.remove(&LuaKey::Str("SourceOp".to_owned()));
1656 }
1657 }
1658 }
1659 if orig.source_output != binding.source_output {
1660 match &binding.source_output {
1661 Some(src) => it.set(LuaKey::Str("Source".to_owned()), LuaValue::String(src.clone())),
1662 None => {
1663 it.remove(&LuaKey::Str("Source".to_owned()));
1664 }
1665 }
1666 }
1667 if orig.expression != binding.expression {
1668 match &binding.expression {
1669 Some(expr) => it.set(LuaKey::Str("Expression".to_owned()), LuaValue::String(expr.clone())),
1670 None => {
1671 it.remove(&LuaKey::Str("Expression".to_owned()));
1672 }
1673 }
1674 }
1675 if orig.value != binding.value {
1676 match &binding.value {
1677 Some(val) => it.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(val)),
1678 None => {
1679 it.remove(&LuaKey::Str("Value".to_owned()));
1680 }
1681 }
1682 }
1683 if it.entries.is_empty()
1684 && binding.value.is_none()
1685 && binding.source_op.is_none()
1686 && binding.source_output.is_none()
1687 && binding.expression.is_none()
1688 {
1689 in_tbl.remove(&LuaKey::Str(port.clone()));
1690 }
1691 }
1692 } else {
1693 // Port did not exist in raw `Inputs`.
1694 if binding.value.is_none() && binding.source_op.is_none() && binding.expression.is_none() {
1695 continue;
1696 }
1697 // Don't pollute `Inputs` with unedited `UserControls` defaults synthesized during load.
1698 if binding.source_op.is_none()
1699 && binding.expression.is_none()
1700 && binding.value.is_some()
1701 && binding.value == user_control_default(&node.raw, port)
1702 {
1703 continue;
1704 }
1705 // Don't duplicate inherited master inputs onto instanced tools.
1706 if let Some(master) = master_inputs {
1707 if master.get(port) == Some(binding) {
1708 continue;
1709 }
1710 }
1711
1712 let mut it = LuaTable {
1713 tag: Some("Input".to_owned()),
1714 entries: Vec::with_capacity(4),
1715 };
1716 if let Some(op) = &binding.source_op {
1717 it.set(LuaKey::Str("SourceOp".to_owned()), LuaValue::String(op.clone()));
1718 }
1719 if let Some(src) = &binding.source_output {
1720 it.set(LuaKey::Str("Source".to_owned()), LuaValue::String(src.clone()));
1721 }
1722 if let Some(val) = &binding.value {
1723 it.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(val));
1724 }
1725 if let Some(expr) = &binding.expression {
1726 it.set(LuaKey::Str("Expression".to_owned()), LuaValue::String(expr.clone()));
1727 }
1728 let in_tbl = ensure_table_mut(tool_tbl, "Inputs", None);
1729 in_tbl.set(LuaKey::Str(port.clone()), LuaValue::Table(it));
1730 }
1731 }
1732}
1733
1734fn spline_color_lua(color: [u8; 3]) -> LuaValue {
1735 LuaValue::Table(LuaTable {
1736 tag: None,
1737 entries: vec![
1738 (LuaKey::Str("Red".to_owned()), LuaValue::Number(color[0] as f64)),
1739 (LuaKey::Str("Green".to_owned()), LuaValue::Number(color[1] as f64)),
1740 (LuaKey::Str("Blue".to_owned()), LuaValue::Number(color[2] as f64)),
1741 ],
1742 })
1743}
1744
1745fn build_keyframes_table(spline: &BezierSpline) -> LuaTable {
1746 let mut kfs = spline.keyframes.clone();
1747 kfs.sort_by(|a, b| a.time.total_cmp(&b.time));
1748 let mut tbl = LuaTable::default();
1749 for kf in kfs {
1750 let key = if kf.time.fract() == 0.0 && kf.time.abs() < 9_007_199_254_740_992.0 {
1751 LuaKey::Index(kf.time as i64)
1752 } else {
1753 LuaKey::Number(kf.time)
1754 };
1755 let mut entry = LuaTable::default();
1756 entry.entries.push((LuaKey::Index(1), LuaValue::Number(kf.value)));
1757 if let Some([lx, ly]) = kf.lh {
1758 entry.entries.push((LuaKey::Str("LH".to_owned()), vec2_lua(lx, ly)));
1759 }
1760 if let Some([rx, ry]) = kf.rh {
1761 entry.entries.push((LuaKey::Str("RH".to_owned()), vec2_lua(rx, ry)));
1762 }
1763 let mut flags = LuaTable::default();
1764 if kf.flags.linear {
1765 flags.entries.push((LuaKey::Str("Linear".to_owned()), LuaValue::Bool(true)));
1766 }
1767 if kf.flags.step_in {
1768 flags.entries.push((LuaKey::Str("StepIn".to_owned()), LuaValue::Bool(true)));
1769 }
1770 if kf.flags.step_out {
1771 flags.entries.push((LuaKey::Str("StepOut".to_owned()), LuaValue::Bool(true)));
1772 }
1773 if kf.flags.loop_after {
1774 flags.entries.push((LuaKey::Str("Loop".to_owned()), LuaValue::Bool(true)));
1775 }
1776 if kf.flags.loop_rel {
1777 flags.entries.push((LuaKey::Str("LoopRel".to_owned()), LuaValue::Bool(true)));
1778 }
1779 if kf.flags.ping_pong {
1780 flags.entries.push((LuaKey::Str("PingPong".to_owned()), LuaValue::Bool(true)));
1781 }
1782 if kf.flags.locked_y {
1783 flags.entries.push((LuaKey::Str("LockedY".to_owned()), LuaValue::Bool(true)));
1784 }
1785 if !flags.entries.is_empty() {
1786 entry.entries.push((LuaKey::Str("Flags".to_owned()), LuaValue::Table(flags)));
1787 }
1788 tbl.entries.push((key, LuaValue::Table(entry)));
1789 }
1790 tbl
1791}
1792
1793/// Walks `tools` in top-level-before-nested order to sync all existing splines in one O(T) pass.
1794fn sync_existing_splines_in_tools(tools: &mut LuaTable, remaining: &mut HashMap<&str, &BezierSpline>) {
1795 if remaining.is_empty() {
1796 return;
1797 }
1798 for (k, v) in &mut tools.entries {
1799 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table_mut()) else { continue };
1800 if !is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) {
1801 continue;
1802 }
1803 if let Some(spline) = remaining.remove(name.as_str()) {
1804 sync_spline_table(name, spline, tbl);
1805 if remaining.is_empty() {
1806 return;
1807 }
1808 }
1809 }
1810 for (_, v) in &mut tools.entries {
1811 if let Some(inner) = v.as_table_mut().and_then(|t| t.get_table_mut("Tools")) {
1812 sync_existing_splines_in_tools(inner, remaining);
1813 if remaining.is_empty() {
1814 return;
1815 }
1816 }
1817 }
1818}
1819
1820fn spline_color_from_lua(table: &LuaTable) -> [u8; 3] {
1821 table
1822 .get_table("SplineColor")
1823 .map(|c| {
1824 [
1825 c.get_f64("Red").unwrap_or(200.0) as u8,
1826 c.get_f64("Green").unwrap_or(140.0) as u8,
1827 c.get_f64("Blue").unwrap_or(255.0) as u8,
1828 ]
1829 })
1830 .unwrap_or([210, 140, 255])
1831}
1832
1833fn keyframes_match_lua(spline: &BezierSpline, table: &LuaTable) -> bool {
1834 let kf_table = table.get_table("KeyFrames").or_else(|| {
1835 table
1836 .get_table("KeyColorSplines")
1837 .and_then(|kc| kc.get_index(0))
1838 .and_then(LuaValue::as_table)
1839 });
1840 let Some(kfs) = kf_table else {
1841 return spline.keyframes.is_empty();
1842 };
1843 let mut idx = 0usize;
1844 let mut prev_time = f64::NEG_INFINITY;
1845 for (k, v) in &kfs.entries {
1846 let time = match k {
1847 LuaKey::Index(i) => *i as f64,
1848 LuaKey::Number(n) => *n,
1849 _ => continue,
1850 };
1851 let Some(kt) = v.as_table() else { continue };
1852 // Fall back to full parse + sort if raw keyframes are not strictly ascending.
1853 if !(time > prev_time) && idx > 0 {
1854 return false;
1855 }
1856 prev_time = time;
1857 let Some(target) = spline.keyframes.get(idx) else {
1858 return false;
1859 };
1860 let value = kt.get_index(1).and_then(LuaValue::as_f64).unwrap_or(0.0);
1861 let lh = kt.get_table("LH").and_then(read_vec2);
1862 let rh = kt.get_table("RH").and_then(read_vec2);
1863 let mut flags = KeyFlags::default();
1864 if let Some(ft) = kt.get_table("Flags") {
1865 flags.linear = ft.get_bool("Linear").unwrap_or(false);
1866 flags.step_in = ft.get_bool("StepIn").unwrap_or(false);
1867 flags.step_out = ft.get_bool("StepOut").unwrap_or(false);
1868 flags.loop_after = ft.get_bool("Loop").unwrap_or(false);
1869 flags.loop_rel = ft.get_bool("LoopRel").unwrap_or(false);
1870 flags.ping_pong = ft.get_bool("PingPong").unwrap_or(false);
1871 flags.locked_y = ft.get_bool("LockedY").unwrap_or(false);
1872 }
1873 let handle_mode = if flags.linear {
1874 HandleMode::Vector
1875 } else {
1876 HandleMode::Free
1877 };
1878 if target.time != time
1879 || target.value != value
1880 || target.lh != lh
1881 || target.rh != rh
1882 || target.flags != flags
1883 || target.handle_mode != handle_mode
1884 {
1885 return false;
1886 }
1887 idx += 1;
1888 }
1889 idx == spline.keyframes.len()
1890}
1891
1892fn sync_spline_table(spline_name: &str, spline: &BezierSpline, tbl: &mut LuaTable) {
1893 if spline_color_from_lua(tbl) != spline.color {
1894 tbl.set(LuaKey::Str("SplineColor".to_owned()), spline_color_lua(spline.color));
1895 }
1896 if keyframes_match_lua(spline, tbl) {
1897 return;
1898 }
1899 let existing = BezierSpline::from_lua(spline_name.to_owned(), tbl);
1900 let unchanged_cyclic = tbl.tag.as_deref() == Some("LUTBezier") && {
1901 let mut normalized = existing.clone();
1902 normalized.apply_hue_curves_cyclic_ends();
1903 normalized.keyframes == spline.keyframes
1904 };
1905 if existing.keyframes != spline.keyframes && !unchanged_cyclic {
1906 let new_kfs = LuaValue::Table(build_keyframes_table(spline));
1907 if tbl.tag.as_deref() == Some("LUTBezier") && tbl.get_table("KeyColorSplines").is_some() {
1908 if let Some(kcs) = tbl.get_table_mut("KeyColorSplines") {
1909 kcs.set(LuaKey::Index(0), new_kfs);
1910 }
1911 } else {
1912 tbl.set(LuaKey::Str("KeyFrames".to_owned()), new_kfs);
1913 }
1914 }
1915}
1916
1917#[cfg(test)]
1918mod tests {
1919 use super::*;
1920
1921 fn scratch(name: &str) -> PathBuf {
1922 let dir = std::env::temp_dir().join(format!("fission_save_{name}_{}", std::process::id()));
1923 let _ = std::fs::remove_dir_all(&dir);
1924 std::fs::create_dir_all(&dir).unwrap();
1925 dir
1926 }
1927
1928 #[test]
1929 fn rapid_saves_keep_distinct_backups() {
1930 let dir = scratch("backups");
1931 let path = dir.join("rapid_backup_test.comp");
1932 let comp = Comp::from_fusion_str("Composition { Tools = ordered() { }, }").unwrap();
1933 comp.save_to_file(&path).unwrap();
1934 let backups: std::collections::HashSet<_> =
1935 (0..20).map(|_| comp.save_to_file(&path).unwrap().expect("existing file is backed up")).collect();
1936 assert_eq!(backups.len(), 20);
1937 assert!(backups.iter().all(|b| b.exists()));
1938 for b in backups {
1939 let _ = std::fs::remove_file(b);
1940 }
1941 }
1942
1943 #[cfg(unix)]
1944 #[test]
1945 fn saving_through_a_symlink_keeps_the_link() {
1946 let dir = scratch("symlink");
1947 let real = dir.join("real.comp");
1948 let link = dir.join("link.comp");
1949 std::fs::write(&real, "old").unwrap();
1950 std::os::unix::fs::symlink(&real, &link).unwrap();
1951 let comp = Comp::from_fusion_str("Composition { Tools = ordered() { }, }").unwrap();
1952 let backup = comp.save_to_file(&link).unwrap().unwrap();
1953 assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
1954 assert_eq!(std::fs::read_to_string(&real).unwrap(), comp.to_fusion_string());
1955 assert_eq!(std::fs::read_to_string(&backup).unwrap(), "old");
1956 let _ = std::fs::remove_file(backup);
1957 }
1958
1959 #[cfg(unix)]
1960 #[test]
1961 fn saving_through_a_dangling_symlink_creates_its_target() {
1962 let dir = scratch("dangling");
1963 let real = dir.join("real.comp");
1964 let link = dir.join("link.comp");
1965 std::os::unix::fs::symlink("real.comp", &link).unwrap();
1966 let comp = Comp::from_fusion_str("Composition { Tools = ordered() { }, }").unwrap();
1967 assert!(comp.save_to_file(&link).unwrap().is_none());
1968 assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
1969 assert_eq!(std::fs::read_to_string(&real).unwrap(), comp.to_fusion_string());
1970 }
1971
1972 const LOADER: &str = r#"Composition {
1973 Tools = ordered() {
1974 L = Loader {
1975 Clips = {
1976 Clip {
1977 Filename = "a.0000.exr",
1978 GlobalStart = 0,
1979 GlobalEnd = 10,
1980 Loop = 1,
1981 },
1982 },
1983 Inputs = {
1984 Loop = Input { Value = 0, },
1985 },
1986 },
1987 },
1988 }"#;
1989
1990 #[test]
1991 fn edited_loader_timing_inputs_land_in_the_clip() {
1992 let mut comp = Comp::from_fusion_str(LOADER).unwrap();
1993 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
1994 assert!(!saved.node(saved.find_node("L").unwrap()).clips[0].loop_clip);
1995
1996 let l = comp.find_node("L").unwrap();
1997 comp.set_input_value(l, "Loop", ParamValue::Number(1.0));
1998 comp.set_input_value(l, "GlobalOut", ParamValue::Number(25.0));
1999 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
2000 let clip = &saved.node(saved.find_node("L").unwrap()).clips[0];
2001 assert!(clip.loop_clip);
2002 assert_eq!(clip.global_end, 25);
2003 }
2004
2005 #[test]
2006 fn loader_timing_edits_land_in_the_first_clip_of_a_multi_clip_loader() {
2007 let src = r#"Composition {
2008 Tools = ordered() {
2009 L = Loader {
2010 Clips = {
2011 Note = { Comment = "not a clip", },
2012 Clip {
2013 Filename = "a.0000.exr",
2014 GlobalStart = 0,
2015 GlobalEnd = 10,
2016 },
2017 Clip {
2018 Filename = "b.0000.exr",
2019 GlobalStart = 11,
2020 GlobalEnd = 30,
2021 },
2022 },
2023 },
2024 },
2025 }"#;
2026 let mut comp = Comp::from_fusion_str(src).unwrap();
2027 let l = comp.find_node("L").unwrap();
2028 comp.set_input_value(l, "GlobalOut", ParamValue::Number(25.0));
2029 comp.set_input_value(l, "Reverse", ParamValue::Number(1.0));
2030 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
2031 let clips = &saved.node(saved.find_node("L").unwrap()).clips;
2032 assert_eq!(clips.len(), 2);
2033 assert_eq!((clips[0].global_end, clips[0].reverse), (25, true));
2034 assert_eq!((clips[1].global_start, clips[1].global_end, clips[1].reverse), (11, 30, false));
2035 assert!(comp.to_fusion_string().contains("Comment = \"not a clip\""));
2036 }
2037
2038 #[test]
2039 fn cleared_cross_macro_wire_keeps_its_source_op_on_save() {
2040 let src = r#"Composition {
2041 Tools = ordered() {
2042 A = MacroOperator {
2043 Tools = ordered() {
2044 InA = Blur {},
2045 },
2046 },
2047 B = MacroOperator {
2048 Tools = ordered() {
2049 InB = Blur { Inputs = { Input = Input { SourceOp = "InA", Source = "Output", }, }, },
2050 },
2051 },
2052 },
2053 }"#;
2054 let comp = Comp::from_fusion_str(src).unwrap();
2055 let in_b = comp.node(comp.find_node("InB").unwrap());
2056 assert_eq!(in_b.connected_node("Input"), None);
2057 assert!(comp.to_fusion_string().contains(r#"SourceOp = "InA""#));
2058 }
2059
2060 fn ast_fusion_string(comp: &Comp) -> String {
2061 let mut s = comp.sync_to_raw_ast().to_fusion_string();
2062 if !s.ends_with('\n') {
2063 s.push('\n');
2064 }
2065 s
2066 }
2067
2068 #[test]
2069 fn streaming_matches_ast_for_same_named_nested_splines() {
2070 let src = r#"Composition {
2071 Tools = ordered() {
2072 Outer = GroupOperator {
2073 Tools = ordered() {
2074 Inner = GroupOperator {
2075 Tools = ordered() {
2076 SharedSpline = BezierSpline {
2077 SplineColor = { Red = 255, Green = 0, Blue = 0 },
2078 KeyFrames = {
2079 [0] = { 0.1 },
2080 [10] = { 0.2 },
2081 },
2082 },
2083 InnerBG = Background {},
2084 },
2085 },
2086 SharedSpline = BezierSpline {
2087 SplineColor = { Red = 0, Green = 255, Blue = 0 },
2088 KeyFrames = {
2089 [0] = { 0.5 },
2090 [10] = { 1.0 },
2091 },
2092 },
2093 },
2094 },
2095 },
2096 }"#;
2097 let mut comp = Comp::from_fusion_str(src).unwrap();
2098
2099 // Case 1: active spline matches Outer.Tools.SharedSpline while Inner.Tools.SharedSpline differs.
2100 {
2101 let sp = comp.splines.get_mut("SharedSpline").expect("SharedSpline loaded");
2102 sp.color = [0, 255, 0];
2103 sp.keyframes[0].time = 0.0;
2104 sp.keyframes[0].value = 0.5;
2105 sp.keyframes[1].time = 10.0;
2106 sp.keyframes[1].value = 1.0;
2107 }
2108 assert!(comp.try_to_fusion_string_streaming().is_some());
2109 assert_eq!(comp.to_fusion_string(), ast_fusion_string(&comp));
2110
2111 // Case 2: active spline matches Inner.Tools.SharedSpline (differs from Outer.Tools.SharedSpline).
2112 // `sync_existing_splines_in_tools` updates Outer.Tools.SharedSpline first and leaves Inner untouched.
2113 {
2114 let sp = comp.splines.get_mut("SharedSpline").unwrap();
2115 sp.color = [255, 0, 0];
2116 sp.keyframes[0].value = 0.1;
2117 sp.keyframes[1].value = 0.2;
2118 }
2119 assert!(comp.try_to_fusion_string_streaming().is_some());
2120 assert_eq!(comp.to_fusion_string(), ast_fusion_string(&comp));
2121
2122 // Case 3: active spline edited to a brand-new value.
2123 {
2124 let sp = comp.splines.get_mut("SharedSpline").unwrap();
2125 sp.keyframes[0].value = 0.75;
2126 }
2127 assert!(comp.try_to_fusion_string_streaming().is_some());
2128 assert_eq!(comp.to_fusion_string(), ast_fusion_string(&comp));
2129 }
2130
2131 #[test]
2132 fn streaming_bails_and_matches_ast_when_all_nodes_deleted() {
2133 let src = r#"Composition {
2134 Tools = ordered() {
2135 A = Blur {},
2136 B = Blur {},
2137 },
2138 }"#;
2139 // Path 1: deleted via `delete_nodes`
2140 let mut comp = Comp::from_fusion_str(src).unwrap();
2141 let a = comp.find_node("A").unwrap();
2142 let b = comp.find_node("B").unwrap();
2143 comp.delete_nodes(&[a, b]);
2144 assert!(comp.try_to_fusion_string_streaming().is_none());
2145 let saved = comp.to_fusion_string();
2146 assert_eq!(saved, ast_fusion_string(&comp));
2147 assert!(saved.contains("Tools = ordered() {},"));
2148
2149 // Path 2: `raw_root.Tools` still has entries, but all flow nodes removed from `comp.nodes`
2150 let mut comp2 = Comp::from_fusion_str(src).unwrap();
2151 comp2.nodes.clear();
2152 comp2.node_by_name.clear();
2153 assert!(comp2.try_to_fusion_string_streaming().is_none());
2154 let saved2 = comp2.to_fusion_string();
2155 assert_eq!(saved2, ast_fusion_string(&comp2));
2156 assert!(saved2.contains("Tools = ordered() {},"));
2157 }
2158
2159 #[test]
2160 fn streaming_bails_and_matches_ast_for_non_table_entry_in_tools() {
2161 let src = r#"Composition {
2162 Tools = ordered() {
2163 Foo = "not_a_table",
2164 BG = Background {},
2165 },
2166 }"#;
2167 let mut comp = Comp::from_fusion_str(src).unwrap();
2168 // Add a flow node named "Foo" without mutating `raw_root.Tools`, so `raw_root.Tools`
2169 // retains the colliding non-table `Foo = "not_a_table"` entry.
2170 let id = super::super::NodeId(comp.nodes.len());
2171 comp.nodes.push(Node {
2172 id,
2173 name: "Foo".to_owned(),
2174 kind: "Blur".to_owned(),
2175 pos: [10.0, 20.0],
2176 bypassed: false,
2177 internal: false,
2178 macro_output: None,
2179 inputs: HashMap::new(),
2180 clips: Vec::new(),
2181 raw: LuaTable::default(),
2182 });
2183 comp.node_by_name.insert("Foo".to_owned(), id);
2184
2185 assert!(comp.try_to_fusion_string_streaming().is_none());
2186 let saved = comp.to_fusion_string();
2187 assert_eq!(saved, ast_fusion_string(&comp));
2188 assert!(saved.contains("Foo = Blur {"));
2189 assert!(!saved.contains("not_a_table"));
2190 }
2191
2192 #[test]
2193 fn streaming_bails_and_matches_ast_for_duplicate_root_and_tools_keys() {
2194 let dup_root_src = r#"Composition {
2195 CurrentTime = 5,
2196 CurrentTime = 99,
2197 RenderRange = { 0, 10 },
2198 RenderRange = { 5, 25 },
2199 Tools = ordered() {
2200 BG = Background {},
2201 },
2202 }"#;
2203 let mut comp = Comp::from_fusion_str(dup_root_src).unwrap();
2204 comp.current_time = 12.0;
2205 assert!(comp.try_to_fusion_string_streaming().is_none());
2206 assert_eq!(comp.to_fusion_string(), ast_fusion_string(&comp));
2207
2208 let dup_tools_src = r#"Composition {
2209 CurrentTime = 0,
2210 Tools = ordered() {
2211 BG = Background {},
2212 },
2213 Tools = ordered() {
2214 Shadowed = Blur {},
2215 },
2216 }"#;
2217 let comp2 = Comp::from_fusion_str(dup_tools_src).unwrap();
2218 assert!(comp2.try_to_fusion_string_streaming().is_none());
2219 assert_eq!(comp2.to_fusion_string(), ast_fusion_string(&comp2));
2220 }
2221
2222 #[test]
2223 fn streaming_bails_and_matches_ast_when_untagged_tools_shrinks_to_four_or_fewer() {
2224 let src = r#"Composition {
2225 Tools = {
2226 A = Blur {},
2227 B = Blur {},
2228 C = Blur {},
2229 D = Blur {},
2230 E = Blur {},
2231 },
2232 }"#;
2233 let mut comp = Comp::from_fusion_str(src).unwrap();
2234 // With 5 entries, streaming can run.
2235 assert!(comp.try_to_fusion_string_streaming().is_some());
2236 assert_eq!(comp.to_fusion_string(), ast_fusion_string(&comp));
2237
2238 // Remove 3 nodes from `comp.nodes` while `raw_root.Tools` still holds 5 entries, so
2239 // post-edit untagged `Tools` shrinks from 5 -> 2 (<= 4, eligible for inline formatting).
2240 comp.nodes.retain(|n| n.name == "A" || n.name == "B");
2241 comp.node_by_name.retain(|name, _| name == "A" || name == "B");
2242 assert!(comp.try_to_fusion_string_streaming().is_none());
2243 let saved = comp.to_fusion_string();
2244 assert_eq!(saved, ast_fusion_string(&comp));
2245 assert!(saved.contains("Tools = { A = Blur {}, B = Blur {} },"));
2246
2247 // Also verify via `delete_nodes`.
2248 let mut comp2 = Comp::from_fusion_str(src).unwrap();
2249 let ids: Vec<_> = ["C", "D", "E"].iter().map(|n| comp2.find_node(n).unwrap()).collect();
2250 comp2.delete_nodes(&ids);
2251 assert!(comp2.try_to_fusion_string_streaming().is_none());
2252 let saved2 = comp2.to_fusion_string();
2253 assert_eq!(saved2, ast_fusion_string(&comp2));
2254 assert!(saved2.contains("Tools = { A = Blur {}, B = Blur {} },"));
2255 }
2256}