authoravatarclover caruso<git@paperclover.net>2026-12-01 18:56:54-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 19:13:51-08:00
log65e3eb9d114bdc05ad20b13c6c593763fe03ed0d
treea305e7277acee57c7f06fd02edfa652004568fcc
parenta2ed1ffbd69daa39be5cd41986d4dff547094b8f
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

fix(model): harden parser recursion, non-finite boundaries, and serializer parity


9 files changed, 637 insertions(+), 106 deletions(-)

crates/model/src/comp.rs+3-6
......@@ -232,7 +232,7 @@ impl SaverSpec {
232232 /// - `render.png` -> `render{frame:04}.png` (4-digit default when no trailing digits exist)
233233 pub fn frame_path(&self, frame: i64) -> PathBuf {
234234 let effective_frame = if let Some(start) = self.sequence_start {
235 start + (frame - self.range[0])
235 start.saturating_add(frame.saturating_sub(self.range[0]))
236236 } else {
237237 frame
238238 };
......@@ -246,11 +246,8 @@ impl SaverSpec {
246246 None => (fname, ""),
247247 };
248248
249 let digit_start = stem
250 .rfind(|c: char| !c.is_ascii_digit())
251 .map_or(0, |idx| idx + 1);
252 let prefix = &stem[..digit_start];
253 let digits = &stem[digit_start..];
249 let prefix = stem.trim_end_matches(|c: char| c.is_ascii_digit());
250 let digits = &stem[prefix.len()..];
254251 let width = if digits.is_empty() { 4 } else { digits.len() };
255252
256253 let formatted_num = if effective_frame < 0 {
crates/model/src/comp/eval.rs+17-7
......@@ -88,7 +88,7 @@ impl Comp {
8888 if kfs.is_empty() {
8989 return None;
9090 }
91 if kfs.len() == 1 || time <= kfs[0].0 {
91 if kfs.len() == 1 || time.is_nan() || time <= kfs[0].0 {
9292 return Some(kfs[0].1.clone());
9393 }
9494 if time >= kfs[kfs.len() - 1].0 {
......@@ -261,7 +261,9 @@ impl Comp {
261261 }
262262 if let Some(expr) = &binding.expression {
263263 if let Some(p) = self.eval_expr_point(node, expr, time, expr_engine) {
264 return p;
264 if p[0].is_finite() && p[1].is_finite() {
265 return p;
266 }
265267 }
266268 }
267269 if let Some(src) = &binding.source_op {
......@@ -329,7 +331,12 @@ impl Comp {
329331 }
330332
331333 fn eval_shake_axis(&self, sh: &ShakeModifier, axis: u32, time: f64, expr_engine: &ExprEngine) -> f64 {
332 let smoothness = self.eval_shake_input(sh, "Smoothness", time, 1.0, expr_engine).max(0.01);
334 let smoothness_raw = self.eval_shake_input(sh, "Smoothness", time, 1.0, expr_engine);
335 let smoothness = if smoothness_raw.is_finite() {
336 smoothness_raw.max(0.01)
337 } else {
338 1.0
339 };
333340 let seed = self.eval_shake_input(sh, "RandomSeed", time, 0.0, expr_engine).round() as i64;
334341 let lock_xy = self.eval_shake_input(sh, "LockXY", time, 1.0, expr_engine) > 0.5;
335342 let (min_v, max_v) = if axis == 0 || lock_xy {
......@@ -345,6 +352,9 @@ impl Comp {
345352 };
346353 // Smooth Catmull-Rom interpolation over seeded lattice points spaced by `smoothness` frames
347354 let u = time / smoothness;
355 if !u.is_finite() || u.abs() >= 4.5e15 {
356 return min_v;
357 }
348358 let k = u.floor() as i64;
349359 let f = u - k as f64;
350360 let hash01 = |i: i64| -> f64 {
......@@ -356,10 +366,10 @@ impl Comp {
356366 x ^= x >> 31;
357367 (x >> 11) as f64 / (1u64 << 53) as f64
358368 };
359 let p0 = hash01(k - 1);
369 let p0 = hash01(k.wrapping_sub(1));
360370 let p1 = hash01(k);
361 let p2 = hash01(k + 1);
362 let p3 = hash01(k + 2);
371 let p2 = hash01(k.wrapping_add(1));
372 let p3 = hash01(k.wrapping_add(2));
363373 let f2 = f * f;
364374 let f3 = f2 * f;
365375 let cr = 0.5 * ((2.0 * p1)
......@@ -788,7 +798,7 @@ impl Comp {
788798 if kfs.is_empty() {
789799 return None;
790800 }
791 if kfs.len() == 1 || time <= kfs[0].0 {
801 if kfs.len() == 1 || time.is_nan() || time <= kfs[0].0 {
792802 return Some(kfs[0].1.clone());
793803 }
794804 let last = &kfs[kfs.len() - 1];
crates/model/src/comp/load.rs+31-16
......@@ -30,19 +30,19 @@ impl Comp {
3030 });
3131 };
3232
33 let current_time = root.get_f64("CurrentTime").unwrap_or(0.0);
33 let current_time = root.get_f64("CurrentTime").filter(|t| t.is_finite()).unwrap_or(0.0);
3434 let global_range = root
3535 .get_table("GlobalRange")
3636 .and_then(read_vec2)
37 .map(|[a, b]| [a as i64, b as i64])
37 .and_then(normalize_frame_range)
3838 .unwrap_or([0, 1000]);
3939 let render_range = root
4040 .get_table("RenderRange")
4141 .and_then(read_vec2)
42 .map(|[a, b]| [a as i64, b as i64])
42 .and_then(normalize_frame_range)
4343 .unwrap_or(global_range);
4444 let audio_filename = root.get_str("AudioFilename").map(str::to_owned);
45 let audio_offset = root.get_f64("AudioOffset").unwrap_or(0.0);
45 let audio_offset = root.get_f64("AudioOffset").filter(|t| t.is_finite()).unwrap_or(0.0);
4646
4747 // Extract FrameFormat from Prefs.Comp.FrameFormat (default 1920x1080 @ 30fps, Int8)
4848 let mut width = 1920u32;
......@@ -55,20 +55,22 @@ impl Comp {
5555 .and_then(|p| p.get_table("Comp"))
5656 .and_then(|c| c.get_table("FrameFormat"))
5757 {
58 if let Some(w) = ff.get_f64("Width") {
59 width = w.round().max(1.0) as u32;
58 if let Some(w) = ff.get_f64("Width").and_then(normalize_frame_dim) {
59 width = w;
6060 explicit_size = true;
6161 }
62 if let Some(h) = ff.get_f64("Height") {
63 height = h.round().max(1.0) as u32;
62 if let Some(h) = ff.get_f64("Height").and_then(normalize_frame_dim) {
63 height = h;
6464 explicit_size = true;
6565 }
66 if let Some(r) = ff.get_f64("Rate") {
67 if r > 0.0 {
68 fps = r;
69 }
66 if let Some(r) = ff.get_f64("Rate").filter(|r| r.is_finite() && *r > 0.0) {
67 fps = r;
7068 }
71 if let Some(d) = ff.get_f64("DepthFull").and_then(|v| BitDepth::from_fusion_depth(v.round() as i32)) {
69 if let Some(d) = ff
70 .get_f64("DepthFull")
71 .filter(|v| v.is_finite())
72 .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32))
73 {
7274 depth_full = d;
7375 }
7476 }
......@@ -263,9 +265,9 @@ impl Comp {
263265 for n in &nodes {
264266 if matches!(n.kind.as_str(), "Background" | "TextPlus" | "FastNoise") {
265267 if let (Some(w), Some(h)) = (n.static_number("Width"), n.static_number("Height")) {
266 if w >= 64.0 && h >= 64.0 {
267 width = w as u32;
268 height = h as u32;
268 if w.is_finite() && h.is_finite() && w >= 64.0 && h >= 64.0 {
269 width = normalize_frame_dim(w).unwrap_or(width);
270 height = normalize_frame_dim(h).unwrap_or(height);
269271 break;
270272 }
271273 }
......@@ -304,6 +306,19 @@ impl Comp {
304306
305307}
306308
309pub(super) fn normalize_frame_dim(v: f64) -> Option<u32> {
310 v.is_finite()
311 .then(|| v.round().clamp(1.0, 65536.0) as u32)
312}
313
314fn normalize_frame_range([a, b]: [f64; 2]) -> Option<[i64; 2]> {
315 (a.is_finite() && b.is_finite()).then(|| {
316 let lo = i32::MIN as f64;
317 let hi = i32::MAX as f64;
318 [a.round().clamp(lo, hi) as i64, b.round().clamp(lo, hi) as i64]
319 })
320}
321
307322/// Fusion resolves a macro-internal `SourceOp` only within the macro's own scope (itself, its
308323/// enclosing macros, its nested macros) or at top level; a name that only exists inside an
309324/// unrelated macro stays unconnected. Returns the `(node, port)` wires whose `source_op` was
crates/model/src/comp/math.rs+36-17
......@@ -30,7 +30,11 @@ impl GridMesh {
3030 if tbl.tag.as_deref() != Some("Mesh") {
3131 return None;
3232 }
33 let cols = tbl.get_f64("Col")?.round().max(2.0) as usize;
33 let cols_f = tbl.get_f64("Col")?;
34 if !cols_f.is_finite() {
35 return None;
36 }
37 let cols = cols_f.round().clamp(2.0, 65536.0) as usize;
3438 let pts_tbl = tbl.get_table("Points")?;
3539 let mut points = Vec::new();
3640 for pval in pts_tbl.positional_values() {
......@@ -48,7 +52,7 @@ impl GridMesh {
4852 b_cy: pt.get_f64("B_CY"),
4953 });
5054 }
51 if points.len() < cols * 2 {
55 if points.len() < cols.checked_mul(2)? {
5256 return None;
5357 }
5458 let rows = points.len() / cols;
......@@ -148,7 +152,7 @@ impl Comp {
148152 }
149153 if !kfs.is_empty() {
150154 kfs.sort_by(|a, b| a.0.total_cmp(&b.0));
151 if kfs.len() == 1 || time <= kfs[0].0 {
155 if kfs.len() == 1 || time.is_nan() || time <= kfs[0].0 {
152156 return Some(kfs[0].1.clone());
153157 }
154158 if time >= kfs[kfs.len() - 1].0 {
......@@ -182,13 +186,25 @@ impl Comp {
182186/// Evaluates a Fusion `Expression` modifier math formula (C-like Fusion math DSL) to an `f64`.
183187/// Returns `None` if syntax is not recognized so callers can fall back to Lua `ExprEngine`.
184188pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap<String, f64>) -> Option<f64> {
189 const MAX_EXPR_DEPTH: usize = 64;
190
185191 struct Parser<'a> {
186192 bytes: &'a [u8],
187193 pos: usize,
188194 vars: &'a HashMap<String, f64>,
195 depth: usize,
189196 }
190197
191198 impl<'a> Parser<'a> {
199 fn with_depth(&mut self, f: impl FnOnce(&mut Self) -> Option<f64>) -> Option<f64> {
200 if self.depth >= MAX_EXPR_DEPTH {
201 return None;
202 }
203 self.depth += 1;
204 let res = f(self);
205 self.depth -= 1;
206 res
207 }
192208 fn skip_ws(&mut self) {
193209 while self.pos < self.bytes.len() {
194210 let b = self.bytes[self.pos];
......@@ -220,17 +236,19 @@ pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap<String, f64>) -> O
220236 }
221237
222238 fn parse_or(&mut self) -> Option<f64> {
223 let mut v = self.parse_and()?;
224 loop {
225 self.skip_ws();
226 if self.eat_str("||") || self.eat_str("|") {
227 let r = self.parse_and()?;
228 v = if v != 0.0 || r != 0.0 { 1.0 } else { 0.0 };
229 } else {
230 break;
239 self.with_depth(|p| {
240 let mut v = p.parse_and()?;
241 loop {
242 p.skip_ws();
243 if p.eat_str("||") || p.eat_str("|") {
244 let r = p.parse_and()?;
245 v = if v != 0.0 || r != 0.0 { 1.0 } else { 0.0 };
246 } else {
247 break;
248 }
231249 }
232 }
233 Some(v)
250 Some(v)
251 })
234252 }
235253
236254 fn parse_and(&mut self) -> Option<f64> {
......@@ -322,7 +340,7 @@ pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap<String, f64>) -> O
322340 let base = self.parse_unary()?;
323341 if self.peek() == Some(b'^') {
324342 self.pos += 1;
325 let exp = self.parse_pow()?;
343 let exp = self.with_depth(Self::parse_pow)?;
326344 Some(if base > 0.0 {
327345 base.powf(exp)
328346 } else if base == 0.0 {
......@@ -342,15 +360,15 @@ pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap<String, f64>) -> O
342360 match self.peek() {
343361 Some(b'-') => {
344362 self.pos += 1;
345 Some(-self.parse_unary()?)
363 Some(-self.with_depth(Self::parse_unary)?)
346364 }
347365 Some(b'+') => {
348366 self.pos += 1;
349 self.parse_unary()
367 self.with_depth(Self::parse_unary)
350368 }
351369 Some(b'!') => {
352370 self.pos += 1;
353 let v = self.parse_unary()?;
371 let v = self.with_depth(Self::parse_unary)?;
354372 Some(if v == 0.0 { 1.0 } else { 0.0 })
355373 }
356374 _ => self.parse_primary(),
......@@ -509,6 +527,7 @@ pub(super) fn eval_fusion_math_expr(src: &str, vars: &HashMap<String, f64>) -> O
509527 bytes: src.as_bytes(),
510528 pos: 0,
511529 vars,
530 depth: 0,
512531 };
513532 let val = p.parse_or()?;
514533 p.skip_ws();
crates/model/src/comp/save.rs+35-34
......@@ -1,4 +1,4 @@
1use super::load::{parse_input_binding, parse_param_value};
1use super::load::{normalize_frame_dim, parse_input_binding, parse_param_value};
22use super::math::find_raw_tool_mut;
33use super::{BitDepth, Comp, InputBinding, Node, ParamValue, is_modifier_type};
44use crate::lua_value::{
......@@ -92,30 +92,8 @@ impl Comp {
9292 }
9393
9494 // Update Prefs.Comp.FrameFormat (Width, Height, Rate, DepthFull)
95 {
96 let prefs = ensure_table_mut(&mut root, "Prefs", None);
97 let comp_prefs = ensure_table_mut(prefs, "Comp", None);
98 let ff = ensure_table_mut(comp_prefs, "FrameFormat", None);
99 if ff.get_f64("Width").map(|w| w.round().max(1.0) as u32) != Some(self.width) {
100 ff.set(LuaKey::Str("Width".to_owned()), LuaValue::Number(self.width as f64));
101 }
102 if ff.get_f64("Height").map(|h| h.round().max(1.0) as u32) != Some(self.height) {
103 ff.set(LuaKey::Str("Height".to_owned()), LuaValue::Number(self.height as f64));
104 }
105 if ff.get_f64("Rate").is_none_or(|r| (r - self.fps).abs() > 1e-9) {
106 ff.set(LuaKey::Str("Rate".to_owned()), LuaValue::Number(self.fps));
107 }
108 let existing_depth = ff
109 .get_f64("DepthFull")
110 .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32))
111 .unwrap_or(BitDepth::Int8);
112 if existing_depth != self.depth_full {
113 ff.set(
114 LuaKey::Str("DepthFull".to_owned()),
115 LuaValue::Number((self.depth_full as i32) as f64),
116 );
117 }
118 }
95 let prefs = ensure_table_mut(&mut root, "Prefs", None);
96 self.patch_prefs_table(prefs);
11997
12098 // Sync Tools
12199 let tools = ensure_table_mut(&mut root, "Tools", Some("ordered"));
......@@ -533,17 +511,21 @@ impl Comp {
533511 else {
534512 return true;
535513 };
536 if ff.get_f64("Width").map(|w| w.round().max(1.0) as u32) != Some(self.width) {
514 if ff.get_f64("Width").and_then(normalize_frame_dim) != Some(self.width) {
537515 return true;
538516 }
539 if ff.get_f64("Height").map(|h| h.round().max(1.0) as u32) != Some(self.height) {
517 if ff.get_f64("Height").and_then(normalize_frame_dim) != Some(self.height) {
540518 return true;
541519 }
542 if ff.get_f64("Rate").is_none_or(|r| (r - self.fps).abs() > 1e-9) {
520 if ff
521 .get_f64("Rate")
522 .is_none_or(|r| !r.is_finite() || (r - self.fps).abs() > 1e-9)
523 {
543524 return true;
544525 }
545526 let existing_depth = ff
546527 .get_f64("DepthFull")
528 .filter(|v| v.is_finite())
547529 .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32))
548530 .unwrap_or(BitDepth::Int8);
549531 existing_depth != self.depth_full
......@@ -552,17 +534,21 @@ impl Comp {
552534 fn patch_prefs_table(&self, prefs: &mut LuaTable) {
553535 let comp_prefs = ensure_table_mut(prefs, "Comp", None);
554536 let ff = ensure_table_mut(comp_prefs, "FrameFormat", None);
555 if ff.get_f64("Width").map(|w| w.round().max(1.0) as u32) != Some(self.width) {
537 if ff.get_f64("Width").and_then(normalize_frame_dim) != Some(self.width) {
556538 ff.set(LuaKey::Str("Width".to_owned()), LuaValue::Number(self.width as f64));
557539 }
558 if ff.get_f64("Height").map(|h| h.round().max(1.0) as u32) != Some(self.height) {
540 if ff.get_f64("Height").and_then(normalize_frame_dim) != Some(self.height) {
559541 ff.set(LuaKey::Str("Height".to_owned()), LuaValue::Number(self.height as f64));
560542 }
561 if ff.get_f64("Rate").is_none_or(|r| (r - self.fps).abs() > 1e-9) {
543 if ff
544 .get_f64("Rate")
545 .is_none_or(|r| !r.is_finite() || (r - self.fps).abs() > 1e-9)
546 {
562547 ff.set(LuaKey::Str("Rate".to_owned()), LuaValue::Number(self.fps));
563548 }
564549 let existing_depth = ff
565550 .get_f64("DepthFull")
551 .filter(|v| v.is_finite())
566552 .and_then(|v| BitDepth::from_fusion_depth(v.round() as i32))
567553 .unwrap_or(BitDepth::Int8);
568554 if existing_depth != self.depth_full {
......@@ -933,6 +919,9 @@ impl Comp {
933919 if !remaining_splines.is_empty() {
934920 for (k, v) in &inner_tools.entries {
935921 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 }
936925 if !top_level_spline_names.contains(name.as_str())
937926 && !claimed_splines.contains(name.as_str())
938927 {
......@@ -1116,7 +1105,10 @@ fn commit_inner_tools_verbatim<'a>(
11161105 // (matching `sync_existing_splines_in_tools` top-down order).
11171106 if !remaining_splines.is_empty() {
11181107 for (k, v) in &inner_tools.entries {
1119 let (LuaKey::Str(name), Some(_)) = (k, v.as_table()) else { continue };
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 }
11201112 if !top_level_spline_names.contains(name.as_str()) {
11211113 remaining_splines.remove(name.as_str());
11221114 if remaining_splines.is_empty() {
......@@ -1157,6 +1149,9 @@ fn nested_splines_verbatim<'a, 'b>(
11571149 }
11581150 for (k, v) in &tools.entries {
11591151 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 }
11601155 if !top_level_spline_names.contains(name.as_str())
11611156 && !claimed_splines.contains(name.as_str())
11621157 {
......@@ -1192,7 +1187,10 @@ fn consume_nested_splines(
11921187 return;
11931188 }
11941189 for (k, v) in &tools.entries {
1195 let (LuaKey::Str(name), Some(_)) = (k, v.as_table()) else { continue };
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 }
11961194 if !top_level_spline_names.contains(name.as_str()) {
11971195 remaining_splines.remove(name.as_str());
11981196 if remaining_splines.is_empty() {
......@@ -1220,7 +1218,7 @@ fn sync_existing_splines_in_tools_excluding(
12201218 }
12211219 for (k, v) in &mut tools.entries {
12221220 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table_mut()) else { continue };
1223 if excluded.contains(name.as_str()) {
1221 if !is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown")) || excluded.contains(name.as_str()) {
12241222 continue;
12251223 }
12261224 if let Some(spline) = remaining.remove(name.as_str()) {
......@@ -1799,6 +1797,9 @@ fn sync_existing_splines_in_tools(tools: &mut LuaTable, remaining: &mut HashMap<
17991797 }
18001798 for (k, v) in &mut tools.entries {
18011799 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 }
18021803 if let Some(spline) = remaining.remove(name.as_str()) {
18031804 sync_spline_table(name, spline, tbl);
18041805 if remaining.is_empty() {
crates/model/src/expr.rs+3
......@@ -715,6 +715,9 @@ mod pure {
715715 let mut toks = Vec::new();
716716 let mut i = 0;
717717 while i < chars.len() {
718 if toks.len() >= MAX_TOKENS {
719 return None;
720 }
718721 let c = chars[i];
719722 if c.is_whitespace() {
720723 i += 1;
crates/model/src/lua_value.rs+35-15
......@@ -182,9 +182,12 @@ pub fn parse_lua(input: &str) -> Result<LuaValue, ParseError> {
182182 Ok(val)
183183}
184184
185const MAX_PARSE_DEPTH: usize = 128;
186
185187struct Parser<'a> {
186188 src: &'a [u8],
187189 pos: usize,
190 depth: usize,
188191}
189192
190193impl<'a> Parser<'a> {
......@@ -194,7 +197,17 @@ impl<'a> Parser<'a> {
194197 if input.as_bytes().starts_with(&[0xEF, 0xBB, 0xBF]) {
195198 pos = 3;
196199 }
197 Self { src: input.as_bytes(), pos }
200 Self { src: input.as_bytes(), pos, depth: 0 }
201 }
202
203 fn with_depth<T>(&mut self, f: impl FnOnce(&mut Self) -> Result<T, ParseError>) -> Result<T, ParseError> {
204 if self.depth >= MAX_PARSE_DEPTH {
205 return Err(self.err(format!("maximum nesting depth ({MAX_PARSE_DEPTH}) exceeded")));
206 }
207 self.depth += 1;
208 let res = f(self);
209 self.depth -= 1;
210 res
198211 }
199212
200213 fn err(&self, msg: impl Into<String>) -> ParseError {
......@@ -387,22 +400,25 @@ impl<'a> Parser<'a> {
387400 // Handle calls like `ordered() { ... }` or `FuID("...")` or `Clip(...)`
388401 if self.peek() == Some(b'(') {
389402 self.pos += 1;
390 let mut args = Vec::new();
391 self.skip_ws_and_comments()?;
392 if self.peek() != Some(b')') {
393 loop {
394 args.push(self.parse_value()?);
395 self.skip_ws_and_comments()?;
396 if self.peek() == Some(b',') {
397 self.pos += 1;
398 } else {
399 break;
403 let args = self.with_depth(|p| {
404 let mut args = Vec::new();
405 p.skip_ws_and_comments()?;
406 if p.peek() != Some(b')') {
407 loop {
408 args.push(p.parse_value()?);
409 p.skip_ws_and_comments()?;
410 if p.peek() == Some(b',') {
411 p.pos += 1;
412 } else {
413 break;
414 }
400415 }
401416 }
402 }
403 if self.bump() != Some(b')') {
404 return Err(self.err(format!("expected ')' after {ident}(...")));
405 }
417 if p.bump() != Some(b')') {
418 return Err(p.err(format!("expected ')' after {ident}(...")));
419 }
420 Ok(args)
421 })?;
406422 self.skip_ws_and_comments()?;
407423 if self.peek() == Some(b'{') {
408424 let mut table = self.parse_table(Some(ident))?;
......@@ -438,6 +454,10 @@ impl<'a> Parser<'a> {
438454 }
439455
440456 fn parse_table(&mut self, tag: Option<String>) -> Result<LuaTable, ParseError> {
457 self.with_depth(|p| p.parse_table_inner(tag))
458 }
459
460 fn parse_table_inner(&mut self, tag: Option<String>) -> Result<LuaTable, ParseError> {
441461 if self.bump() != Some(b'{') {
442462 return Err(self.err("expected '{'"));
443463 }
crates/model/src/spline.rs+30-11
......@@ -83,10 +83,19 @@ impl BezierSpline {
8383 LuaKey::Number(n) => *n,
8484 _ => continue,
8585 };
86 if !time.is_finite() {
87 continue;
88 }
8689 let Some(kt) = v.as_table() else { continue };
8790 let value = kt.get_index(1).and_then(LuaValue::as_f64).unwrap_or(0.0);
88 let lh = kt.get_table("LH").and_then(read_vec2);
89 let rh = kt.get_table("RH").and_then(read_vec2);
91 if !value.is_finite() {
92 continue;
93 }
94 let finite_vec2 = |t: &LuaTable| {
95 read_vec2(t).filter(|[x, y]| x.is_finite() && y.is_finite())
96 };
97 let lh = kt.get_table("LH").and_then(finite_vec2);
98 let rh = kt.get_table("RH").and_then(finite_vec2);
9099 let mut flags = KeyFlags::default();
91100 if let Some(ft) = kt.get_table("Flags") {
92101 flags.linear = ft.get_bool("Linear").unwrap_or(false);
......@@ -133,17 +142,19 @@ impl BezierSpline {
133142 let last = &kfs[kfs.len() - 1];
134143
135144 // Fusion never loops backwards before the first keyframe (`Loop` / `LoopRel` / `PingPong` all clamp).
136 if t <= first.time {
145 if t.is_nan() || t <= first.time {
137146 return first.value;
138147 }
139148
140149 // In Fusion, `Loop` / `LoopRel` requires at least two loop-flagged keyframes (`loop_start < loop_end`).
141150 // The loop repeats `[loop_start, loop_end]` for `t >= loop_end.time` up to the next keyframe (if any).
142151 let is_loop_key = |k: &Keyframe| k.flags.loop_after || k.flags.loop_rel;
143 let loop_pair = kfs.iter().position(is_loop_key).and_then(|s| {
144 let e = kfs.iter().rposition(is_loop_key)?;
145 (s < e).then_some((s, e))
146 });
152 let loop_pair = t.is_finite().then(|| {
153 kfs.iter().position(is_loop_key).and_then(|s| {
154 let e = kfs.iter().rposition(is_loop_key)?;
155 (s < e).then_some((s, e))
156 })
157 }).flatten();
147158
148159 let mut t = t;
149160 let mut value_offset = 0.0_f64;
......@@ -230,13 +241,14 @@ pub fn segment_control_points(k0: &Keyframe, k1: &Keyframe) -> [[f64; 2]; 4] {
230241 let p3 = [k1.time, k1.value];
231242 let dt = k1.time - k0.time;
232243 let dv = k1.value - k0.value;
233 // Keys can be transiently unsorted mid-drag; `f64::clamp` would panic on `lo > hi`.
244 // Keys can be transiently unsorted mid-drag; `f64::clamp` would panic on `lo > hi` or `NaN`.
234245 let (t_lo, t_hi) = (k0.time.min(k1.time), k0.time.max(k1.time));
246 let clamp_t = |x: f64| if t_lo <= t_hi { x.clamp(t_lo, t_hi) } else { x };
235247
236248 let p1 = if k1.flags.linear && k0.rh.is_none() {
237249 [k0.time + dt / 3.0, k0.value + dv / 3.0]
238250 } else if let Some(rh) = k0.rh {
239 [rh[0].clamp(t_lo, t_hi), rh[1]]
251 [clamp_t(rh[0]), rh[1]]
240252 } else {
241253 [k0.time + dt / 3.0, k0.value + dv / 3.0]
242254 };
......@@ -244,7 +256,7 @@ pub fn segment_control_points(k0: &Keyframe, k1: &Keyframe) -> [[f64; 2]; 4] {
244256 let p2 = if k1.flags.linear && k1.lh.is_none() {
245257 [k1.time - dt / 3.0, k1.value - dv / 3.0]
246258 } else if let Some(lh) = k1.lh {
247 [lh[0].clamp(t_lo, t_hi), lh[1]]
259 [clamp_t(lh[0]), lh[1]]
248260 } else {
249261 [k1.time - dt / 3.0, k1.value - dv / 3.0]
250262 };
......@@ -428,9 +440,16 @@ impl PolyPath {
428440 }
429441 }
430442
431 if cum_len <= 1e-12 {
443 if cum_len <= 1e-12 || displacement.is_nan() {
432444 return samples[0].1;
433445 }
446 if !displacement.is_finite() {
447 return if displacement.is_sign_positive() {
448 samples[samples.len() - 1].1
449 } else {
450 samples[0].1
451 };
452 }
434453 // Extrapolate smoothly along end/start tangent when displacement is outside [0, 1]
435454 if displacement > 1.0 && samples.len() >= 2 {
436455 let (l0, v0) = samples[samples.len() - 2];
crates/model/tests/hardening_model.rs created+447
......@@ -0,0 +1,447 @@
1use model::comp::{BitDepth, Comp, NodeId, ParamValue, SaverSpec};
2use model::edit::CompHistory;
3use model::expr::ExprEngine;
4use model::lua_value::{LuaTable, parse_lua};
5use model::spline::{BezierSpline, HandleMode, KeyFlags, Keyframe, PolyPath, PolyPoint, segment_control_points};
6use std::collections::HashMap;
7
8fn ast_fusion_string(comp: &Comp) -> String {
9 let mut s = comp.sync_to_raw_ast().to_fusion_string();
10 if !s.ends_with('\n') {
11 s.push('\n');
12 }
13 s
14}
15
16fn assert_save_equivalence_and_reparse(comp: &Comp) {
17 let streamed = comp.to_fusion_string();
18 let ast = ast_fusion_string(comp);
19 assert_eq!(streamed, ast, "streaming vs AST save divergence");
20 Comp::from_fusion_str(&streamed).expect("saved comp must re-parse cleanly");
21}
22
23#[test]
24fn lua_parser_bounds_deep_nesting_without_stack_overflow() {
25 for depth in [200, 500, 5000] {
26 let open_tables = "{".repeat(depth);
27 assert!(parse_lua(&open_tables).is_err(), "unclosed tables depth {depth}");
28
29 let closed_tables = format!("{}1{}", "{".repeat(depth), "}".repeat(depth));
30 assert!(parse_lua(&closed_tables).is_err(), "closed tables depth {depth}");
31
32 let nested_calls = format!("{}1{}", "Foo(".repeat(depth), ")".repeat(depth));
33 assert!(parse_lua(&nested_calls).is_err(), "nested calls depth {depth}");
34
35 let nested_keys = format!("{}1{}", "{[".repeat(depth), "]=1}".repeat(depth));
36 assert!(parse_lua(&nested_keys).is_err(), "nested keys depth {depth}");
37
38 let nested_groups = format!(
39 "Composition {{ Tools = ordered() {{ {} }} }}",
40 "G = GroupOperator { Tools = ordered() { ".repeat(depth / 2)
41 + &"} } ".repeat(depth / 2)
42 );
43 assert!(Comp::from_fusion_str(&nested_groups).is_err(), "nested groups depth {depth}");
44 }
45
46 // Legitimate Fusion-like nesting well under the cap still parses cleanly.
47 let ok = format!("{}42{}", "{".repeat(32), "}".repeat(32));
48 assert!(parse_lua(&ok).is_ok());
49}
50
51#[test]
52fn malformed_comp_prefixes_escapes_nul_brackets_and_huge_numbers_never_panic() {
53 let sample = r#"Composition {
54 CurrentTime = 10,
55 GlobalRange = { 0, 100 },
56 RenderRange = { 0, 100 },
57 Prefs = { Comp = { FrameFormat = { Width = 1920, Height = 1080, Rate = 24 } } },
58 Tools = ordered() {
59 BG1 = Background { Inputs = { Width = Input { Value = 1920 } } },
60 Blur1 = Blur { Inputs = { Input = Input { SourceOp = "BG1", Source = "Output" } } },
61 },
62 }"#;
63
64 // Every UTF-8 prefix truncation must return Ok or Err without panicking or hanging.
65 for (idx, _) in sample.char_indices() {
66 let _ = Comp::from_fusion_str(&sample[..idx]);
67 }
68
69 // Deterministic byte/char mutations over a representative comp never panic or hang.
70 let mut seed = 0x9E37_79B9_7F4A_7C15u64;
71 let mut next_u32 = || -> u32 {
72 seed ^= seed << 13;
73 seed ^= seed >> 7;
74 seed ^= seed << 17;
75 (seed >> 16) as u32
76 };
77 let sample_bytes = sample.as_bytes();
78 for _ in 0..256 {
79 let mut buf = sample_bytes.to_vec();
80 let edits = 1 + (next_u32() as usize % 6);
81 for _ in 0..edits {
82 let pos = next_u32() as usize % buf.len();
83 match next_u32() % 3 {
84 0 => buf[pos] = next_u32() as u8,
85 1 if buf.len() > 1 => {
86 buf.remove(pos);
87 }
88 _ => buf.insert(pos, next_u32() as u8),
89 }
90 }
91 let mutated = String::from_utf8_lossy(&buf);
92 if let Ok(comp) = Comp::from_fusion_str(&mutated) {
93 let _ = comp.to_fusion_string();
94 }
95 }
96
97 // Bad escapes, unterminated strings/long brackets/comments, bare NUL bytes.
98 for bad in [
99 "",
100 " -- just a comment",
101 "\0",
102 "Composition { \0 }",
103 r#"Composition { Name = "unterminated"#,
104 r#"Composition { Name = "bad\x" }"#,
105 r#"Composition { Name = "bad\xZZ" }"#,
106 r#"Composition { Name = [===[unterminated ]==] }"#,
107 r#"--[===[unterminated comment ]==] Composition {}"#,
108 "12345",
109 "nil",
110 "\"not a table\"",
111 ] {
112 assert!(Comp::from_fusion_str(bad).is_err(), "expected Err for {bad:?}");
113 }
114
115 // NUL inside quoted strings/long brackets/comments and huge numbers survive roundtrip.
116 let weird = concat!(
117 "-- comment with \0 nul\n",
118 "Composition {\n",
119 "\tTools = ordered() {\n",
120 "\t\tN1 = Note { Inputs = { Comments = Input { Value = \"a\0b\\255\" } } },\n",
121 "\t\tN2 = Note { Inputs = { Comments = Input { Value = [=[x\0y]=] } } },\n",
122 "\t\tB1 = Blur { Inputs = { XBlurSize = Input { Value = 1e9999 } } },\n",
123 "\t\tB2 = Blur { Inputs = { XBlurSize = Input { Value = -1e9999 } } },\n",
124 "\t\tB3 = Blur {},\n",
125 "\t},\n",
126 "}\n"
127 );
128 let comp = Comp::from_fusion_str(weird).expect("weird valid comp parses");
129 assert_save_equivalence_and_reparse(&comp);
130}
131
132#[test]
133fn non_finite_and_degenerate_metadata_normalizes_and_saves_equivalently() {
134 let weird_meta = r#"Composition {
135 CurrentTime = nan,
136 AudioOffset = 1e9999,
137 GlobalRange = { nan, 1e9999 },
138 RenderRange = { -1e9999, nan },
139 Prefs = { Comp = { FrameFormat = { Width = 1e9999, Height = nan, Rate = 1e9999, DepthFull = nan } } },
140 Tools = ordered() {
141 A = Blur {},
142 B = Blur {},
143 C = Blur {},
144 D = Blur {},
145 E = Blur {},
146 },
147 }"#;
148 let comp = Comp::from_fusion_str(weird_meta).expect("parses comp with non-finite metadata");
149 assert_eq!(comp.width, 1920);
150 assert_eq!(comp.height, 1080);
151 assert_eq!(comp.fps, 30.0);
152 assert_eq!(comp.depth_full, BitDepth::Int8);
153 assert_eq!(comp.current_time, 0.0);
154 assert_eq!(comp.audio_offset, 0.0);
155 assert_eq!(comp.global_range, [0, 1000]);
156 assert_eq!(comp.render_range, [0, 1000]);
157 assert_save_equivalence_and_reparse(&comp);
158
159 // Non-table Prefs / Tools, empty Tools, and inferred huge Background sizes.
160 for src in [
161 "Composition { Prefs = 123, Tools = 123 }",
162 "Composition { Prefs = { Comp = 123 }, Tools = {} }",
163 "Composition { Tools = ordered() {} }",
164 "Composition { Prefs = { Comp = { FrameFormat = { Width = 1e20, Height = 1e20, Rate = nan } } }, Tools = ordered() { A = Blur {}, B = Blur {}, C = Blur {}, D = Blur {}, E = Blur {} } }",
165 "Composition { Tools = ordered() { BG = Background { Inputs = { Width = Input { Value = 1e9999 }, Height = Input { Value = 1e9999 } } } } }",
166 ] {
167 let c = Comp::from_fusion_str(src).expect(src);
168 assert!(c.width <= 65536 && c.height <= 65536);
169 assert!(c.fps.is_finite() && c.fps > 0.0);
170 assert_save_equivalence_and_reparse(&c);
171 }
172
173 // Duplicate flow + modifier name in Tools must not diverge between streaming and AST save.
174 let dup_name = r#"Composition {
175 Tools = ordered() {
176 Foo = Blur {},
177 Foo = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } } },
178 B = Blur {},
179 C = Blur {},
180 D = Blur {},
181 },
182 }"#;
183 let mut comp = Comp::from_fusion_str(dup_name).expect("dup name parses");
184 comp.splines.get_mut("Foo").unwrap().keyframes[0].value = 2.5;
185 assert_save_equivalence_and_reparse(&comp);
186}
187
188#[test]
189fn cyclic_source_op_and_grid_mesh_overflow_and_utf8_saver_path_do_not_panic() {
190 let cyclic = r#"Composition {
191 Tools = ordered() {
192 A = ColorCorrector { SourceOp = "B", Inputs = { MasterRGBGain = Input { Value = 2 } } },
193 B = ColorCorrector { SourceOp = "A" },
194 SelfInst = ColorCorrector { SourceOp = "SelfInst" },
195 GW = GridWarp {
196 Inputs = {
197 SrcMesh = Input {
198 Value = Mesh {
199 Col = 1e9999,
200 Points = {
201 { X = 0, Y = 0 }, { X = 1, Y = 0 },
202 { X = 0, Y = 1 }, { X = 1, Y = 1 },
203 },
204 },
205 },
206 },
207 },
208 },
209 }"#;
210 let comp = Comp::from_fusion_str(cyclic).expect("cyclic SourceOp parses");
211 let gw = comp.node(comp.find_node("GW").unwrap());
212 assert!(comp.eval_grid_mesh(gw, "SrcMesh", 0.0).is_none());
213 assert!(comp.eval_grid_mesh(gw, "SrcMesh", f64::NAN).is_none());
214
215 // Multi-byte UTF-8 Saver stem + extreme range must never slice mid-char or overflow i64.
216 for filename in ["render_é.png", "出力.exr", "frame_é001.exr", "plain.png"] {
217 let spec = SaverSpec {
218 node_id: NodeId(0),
219 name: "S".to_owned(),
220 upstream: None,
221 filename: filename.to_owned(),
222 range: [i64::MIN, i64::MAX],
223 sequence_start: Some(10),
224 };
225 let p = spec.frame_path(100);
226 assert!(!p.as_os_str().is_empty());
227 }
228}
229
230#[test]
231fn expression_engine_math_dsl_and_shake_handle_cycles_depth_and_non_finite_time() {
232 let expr = ExprEngine::new();
233
234 // Non-finite times & expressions never panic in Lua or format_number.
235 let empty_nums = HashMap::new();
236 let empty_pts = HashMap::new();
237 let empty_nodes = HashMap::new();
238 for t in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 0.0] {
239 let _ = expr.eval_number("time + 1", t, &empty_nums, &empty_pts, &empty_nodes);
240 let _ = expr.eval_string("tostring(time)", t, &empty_nums, &empty_pts, &empty_nodes);
241 let _ = expr.eval_point("Point(time, 0/0)", t, &empty_nums, &empty_pts, &empty_nodes);
242 }
243 assert_eq!(
244 expr.eval_string("0/0", 0.0, &empty_nums, &empty_pts, &empty_nodes).as_deref(),
245 Some("nan")
246 );
247 assert_eq!(
248 expr.eval_string("1/0", 0.0, &empty_nums, &empty_pts, &empty_nodes).as_deref(),
249 Some("inf")
250 );
251 assert_eq!(
252 expr.eval_string("-1/0", 0.0, &empty_nums, &empty_pts, &empty_nodes).as_deref(),
253 Some("-inf")
254 );
255
256 // Deeply nested expressions in ExpressionModifier math DSL & Lua must not overflow stack.
257 let deep_parens = format!("{}1{}", "(".repeat(4000), ")".repeat(4000));
258 let deep_unary = format!("{}1", "-".repeat(4000));
259 let deep_pow = format!("{}2", "2^".repeat(4000));
260 let src = format!(
261 r#"Composition {{
262 Tools = ordered() {{
263 A = Transform {{
264 Inputs = {{
265 Size = Input {{ Expression = "B.Size", }},
266 Angle = Input {{ SourceOp = "Shk", Source = "X", }},
267 Width = Input {{ SourceOp = "EM1", Source = "NumberResult", }},
268 Height = Input {{ SourceOp = "EM2", Source = "NumberResult", }},
269 Edges = Input {{ SourceOp = "EM3", Source = "NumberResult", }},
270 }},
271 }},
272 B = Transform {{
273 Inputs = {{
274 Size = Input {{ Expression = "A.Size", }},
275 }},
276 }},
277 Shk = Shake {{
278 Inputs = {{
279 Smoothness = Input {{ Value = 0.01 }},
280 XMinimum = Input {{ Value = 0 }},
281 XMaximum = Input {{ Value = 10 }},
282 }},
283 }},
284 EM1 = Expression {{ Inputs = {{ NumberExpression = Input {{ Value = "{deep_parens}" }} }} }},
285 EM2 = Expression {{ Inputs = {{ NumberExpression = Input {{ Value = "{deep_unary}" }} }} }},
286 EM3 = Expression {{ Inputs = {{ NumberExpression = Input {{ Value = "{deep_pow}" }} }} }},
287 }},
288 }}"#
289 );
290 let comp = Comp::from_fusion_str(&src).expect("comp parses");
291 let a = comp.node(comp.find_node("A").unwrap());
292
293 for t in [0.0, f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 1e20, -1e20] {
294 // Cyclic NodeA.P <-> NodeB.P terminates cleanly.
295 assert_eq!(comp.eval_number(a, "Size", t, 42.0, &expr), 42.0);
296 // Shake at huge / non-finite times never panics with i64 overflow.
297 let shk = comp.eval_number(a, "Angle", t, -1.0, &expr);
298 assert!(shk.is_finite());
299 // Deep ExpressionModifier formulas don't overflow stack.
300 assert_eq!(comp.eval_number(a, "Width", t, 7.0, &expr), 7.0);
301 assert_eq!(comp.eval_number(a, "Height", t, 7.0, &expr), 7.0);
302 assert_eq!(comp.eval_number(a, "Edges", t, 7.0, &expr), 7.0);
303 }
304}
305
306#[test]
307fn splines_and_polypaths_survive_degenerate_keys_nan_and_inf() {
308 // Empty & 1-key splines
309 let empty_sp = BezierSpline {
310 name: "e".to_owned(),
311 color: [0, 0, 0],
312 keyframes: vec![],
313 };
314 assert_eq!(empty_sp.eval(f64::NAN), 0.0);
315 assert_eq!(empty_sp.eval(f64::INFINITY), 0.0);
316
317 // Manually constructed NaN-timed keyframes with handles must not panic in segment_control_points.
318 let mut k0 = Keyframe::new(f64::NAN, 1.0);
319 k0.rh = Some([1.0, 2.0]);
320 let mut k1 = Keyframe::new(f64::NAN, 3.0);
321 k1.lh = Some([2.0, 4.0]);
322 let _ = segment_control_points(&k0, &k1);
323
324 // Loop spline evaluated at NaN / Inf / -Inf must stay finite (no inf - inf = NaN).
325 let lp = KeyFlags {
326 linear: true,
327 loop_after: true,
328 ..Default::default()
329 };
330 let mut sp = BezierSpline {
331 name: "loop".to_owned(),
332 color: [255, 255, 255],
333 keyframes: vec![
334 Keyframe { time: 20.0, value: 2.0, lh: None, rh: None, flags: lp, handle_mode: HandleMode::Vector },
335 Keyframe { time: 10.0, value: 1.0, lh: None, rh: None, flags: lp, handle_mode: HandleMode::Vector },
336 Keyframe { time: 10.0, value: 1.5, lh: None, rh: None, flags: lp, handle_mode: HandleMode::Vector },
337 ],
338 };
339 sp.sort();
340 for t in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY, 10.0, 15.0, 25.0] {
341 assert!(sp.eval(t).is_finite(), "non-finite eval at t={t}");
342 }
343
344 // Malformed KeyFrames table with nan/inf keys & handles filters non-finite entries cleanly.
345 let sp_tbl = parse_lua(
346 r#"BezierSpline {
347 KeyFrames = {
348 [nan] = { 1, LH = { nan, 0 }, RH = { inf, 0 } },
349 [inf] = { 2 },
350 [0] = { nan },
351 [5] = { 0.5, LH = { nan, 1 } },
352 [10] = { 1.5 },
353 },
354 }"#,
355 )
356 .unwrap();
357 let parsed_sp = BezierSpline::from_lua("s".to_owned(), sp_tbl.as_table().unwrap());
358 assert_eq!(parsed_sp.keyframes.len(), 2);
359 assert!(parsed_sp.keyframes[0].lh.is_none());
360 assert!(parsed_sp.eval(f64::NAN).is_finite());
361
362 // PolyPath at NaN / Inf / -Inf stays finite.
363 let pp = PolyPath {
364 name: "p".to_owned(),
365 displacement_op: None,
366 displacement_value: 0.0,
367 closed: false,
368 points: vec![
369 PolyPoint { x: 0.0, y: 0.0, lx: 0.0, ly: 0.0, rx: 0.0, ry: 0.0, linear: true },
370 PolyPoint { x: 0.5, y: 0.0, lx: 0.0, ly: 0.0, rx: 0.0, ry: 0.0, linear: true },
371 ],
372 };
373 for d in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
374 let p = pp.eval_center(d);
375 assert!(p[0].is_finite() && p[1].is_finite(), "non-finite PolyPath at d={d}");
376 }
377}
378
379#[test]
380fn comp_history_and_edits_handle_stale_ids_and_rapid_roundtrips() {
381 let mut comp = Comp::from_fusion_str("Composition { Tools = ordered() {} }").unwrap();
382 let mut history = CompHistory::with_max_depth(8);
383 history.mark_saved(&comp);
384
385 let stale = NodeId(999);
386 assert!(comp.set_keyframe(stale, "Gain", 0.0, 1.0).is_err());
387 assert!(!comp.delete_keyframe("MissingSpline", 0.0));
388 assert!(comp.rename_node(stale, "ValidName").is_err());
389 assert!(comp.connect_output(stale, "Output", stale, "Input").is_err());
390 assert!(!comp.disconnect(stale, "Input"));
391 assert!(comp.splice_node_into_pipe(stale, stale, stale, "Input").is_err());
392 assert!(!comp.set_input_value(stale, "Gain", ParamValue::Number(1.0)));
393 assert!(!comp.set_input_expression(stale, "Gain", Some("1".to_owned())));
394 assert!(!comp.toggle_passthrough(stale));
395 comp.set_node_pos(stale, [1.0, 2.0]);
396 assert!(comp.delete_nodes(&[stale]).is_empty());
397 assert!(comp.node_splines(stale).is_empty());
398 assert!(history.paste_fusion_clipboard(&mut comp, "{{{{{", (0.0, 0.0)).is_err());
399 assert!(!history.undo(&mut comp));
400 assert!(!history.redo(&mut comp));
401
402 // Rapid add -> wire -> keyframe -> rename -> splice -> delete -> undo -> redo sequence.
403 history.push_snapshot(&comp, "Add BG");
404 let bg = comp.add_node("Background", None, [0.0, 0.0]);
405 assert!(comp.rename_node(bg, "123bad").is_err());
406 assert!(comp.rename_node(bg, "end").is_err());
407 assert!(comp.rename_node(bg, "").is_err());
408
409 history.push_snapshot(&comp, "Add Merge");
410 let merge = comp.add_node("Merge", None, [200.0, 0.0]);
411 comp.connect_output(bg, "Output", merge, "Background").unwrap();
412
413 history.push_snapshot(&comp, "Keyframe & Splice");
414 let sp = comp.set_keyframe(merge, "Blend", 10.0, 0.5).unwrap();
415 assert!(comp.set_keyframe(merge, "Blend", f64::NAN, 1.0).is_err());
416 let blur = comp.add_node("Blur", None, [100.0, 0.0]);
417 comp.splice_node_into_pipe(blur, bg, merge, "Background").unwrap();
418 assert_save_equivalence_and_reparse(&comp);
419
420 history.push_snapshot(&comp, "Rename & Delete key");
421 comp.rename_node(blur, "SoftBlur").unwrap();
422 assert!(comp.delete_keyframe(&sp, 10.0));
423 assert!(!comp.delete_keyframe(&sp, f64::NAN));
424 assert_save_equivalence_and_reparse(&comp);
425
426 history.push_snapshot(&comp, "Delete Blur");
427 comp.delete_nodes(&[blur]);
428 assert_save_equivalence_and_reparse(&comp);
429
430 // Undo everything back to empty and redo everything forward.
431 while history.undo(&mut comp) {
432 assert_save_equivalence_and_reparse(&comp);
433 }
434 assert!(comp.nodes.is_empty());
435 while history.redo(&mut comp) {
436 assert_save_equivalence_and_reparse(&comp);
437 }
438
439 // Cancel and commit group edge cases.
440 assert!(!history.commit_group(&comp));
441 assert!(!history.cancel_group(&mut comp));
442 history.begin_group(&comp, "Canceled");
443 let _tmp = comp.add_node("Note", None, [0.0, 0.0]);
444 assert!(history.cancel_group(&mut comp));
445 assert_save_equivalence_and_reparse(&comp);
446 let _ = LuaTable::default();
447}