authoravatarclover caruso<git@paperclover.net>2026-12-01 01:21:31-08:00
committeravatarclover caruso<git@paperclover.net>2026-12-01 02:52:53-08:00
loga5e1d16ebe8cc3e59daf03d7bd093cb52249af67
tree4176bea8b0e38c75c4cdaeeb3ec0e59b87ba4cad
parent593ab777d3af33be8762ad53fdc0bb5ff46b29df
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Scope macro-internal SourceOps, text inputs in expressions, history dirty-flag and atomic save fixes

- Clear SourceOp wires that point into an unrelated macro on load (globe 10.0% -> 3.2% MAE); save keeps the original text. - Expose text inputs and `self` to expressions as { Value = ... } tables; follow bare Node.Param references through that input's own expression (technique001 4.0% -> 1.5%). - Always insert referenced nodes into the expression env and exempt _G like _ENV. - CompHistory forgets the saved depth once an unrecorded mutation diverges from it. - save_to_file: unique create_new temp, dangling symlinks, parent dir fsync; edited Loader timing inputs sync into Clips[1]. Assisted-by: claude-sonnet-5.5

6 files changed, 313 insertions(+), 45 deletions(-)

crates/model/src/comp.rs+3
......@@ -431,6 +431,9 @@ pub struct Comp {
431431 pub shakes: HashMap<String, ShakeModifier>,
432432 /// Standalone `Expression` modifiers keyed by modifier name (e.g. `"Expression1"`).
433433 pub expression_modifiers: HashMap<String, ExpressionModifier>,
434 /// `(internal node, port)` wires whose out-of-scope `SourceOp` into another macro was cleared
435 /// on load; the raw AST still carries the original text.
436 pub(crate) cross_macro_wires: HashSet<(String, String)>,
434437 /// Preserved raw root `Composition { ... }` Lua AST for lossless `.comp` roundtrip.
435438 pub raw_root: Option<LuaTable>,
436439 /// Generation counter incremented whenever any node, wire, or spline mutates.
crates/model/src/comp/eval.rs+66-26
......@@ -1,6 +1,6 @@
11use super::math::eval_fusion_math_expr;
22use super::{ClsEntry, Comp, ExpressionModifier, MAX_EXPR_DEPTH, Node, ParamValue, ShakeModifier};
3use crate::expr::ExprEngine;
3use crate::expr::{ExprEngine, ExprValue};
44use crate::spline::Gradient;
55use std::cell::RefCell;
66use std::collections::{HashMap, HashSet};
......@@ -12,11 +12,11 @@ thread_local! {
1212 static EXPR_MOD_MEMO: RefCell<Option<HashMap<ModMemoKey, Option<[f64; 2]>>>> = const { RefCell::new(None) };
1313}
1414
15/// Identifiers `expr` can look up, or `None` when `_ENV` allows lookups by computed name.
15/// Identifiers `expr` can look up, or `None` when `_ENV`/`_G` allow lookups by computed name.
1616fn referenced_names(expr: &str) -> Option<HashSet<&str>> {
1717 let names: HashSet<&str> =
1818 expr.split(|c: char| !c.is_ascii_alphanumeric() && c != '_').filter(|t| !t.is_empty()).collect();
19 (!names.contains("_ENV")).then_some(names)
19 (!names.contains("_ENV") && !names.contains("_G")).then_some(names)
2020}
2121
2222struct ModMemoScope(bool);
......@@ -123,10 +123,19 @@ impl Comp {
123123 return default;
124124 };
125125 if let Some(expr) = &binding.expression {
126 if let Some(v) = self.eval_expr_number(node, expr, time, expr_engine) {
127 if v.is_finite() {
128 return v;
126 // A bare `Node.Param` follows that input's own expression/animation instead of its baked value.
127 let referenced = expr.trim().split_once('.').and_then(|(n, p)| {
128 let ident = |s: &str| !s.is_empty() && s.chars().all(|c| c.is_ascii_alphanumeric() || c == '_');
129 (ident(n) && ident(p)).then_some((n, p))
130 });
131 let v = match referenced.and_then(|(n, p)| Some((self.node(self.find_node(n)?), p))) {
132 Some((other, p)) if other.inputs.contains_key(p) && other.id != node.id => {
133 Some(self.eval_number_at(other, p, time, f64::NAN, expr_engine, depth + 1))
129134 }
135 _ => self.eval_expr_number(node, expr, time, expr_engine),
136 };
137 if let Some(v) = v.filter(|v| v.is_finite()) {
138 return v;
130139 }
131140 }
132141 if let Some(src) = &binding.source_op {
......@@ -431,29 +440,35 @@ impl Comp {
431440 expr_engine.eval_number(trimmed, time, &HashMap::new(), &HashMap::new(), &en)
432441 }
433442
434 /// `node name -> numeric inputs` for the nodes `expr` can reach; every other node is skipped.
435 fn collect_node_env(&self, expr: &str, time: f64) -> HashMap<String, HashMap<String, f64>> {
443 /// `node name -> numeric/text inputs` for the nodes `expr` can reach; every other node is skipped.
444 fn collect_node_env(&self, expr: &str, time: f64) -> HashMap<String, HashMap<String, ExprValue>> {
436445 let names = referenced_names(expr);
437 let mut env_nodes = HashMap::new();
438 for n in &self.nodes {
439 if !names.as_ref().is_none_or(|s| s.contains(n.name.as_str())) {
440 continue;
441 }
442 let mut m = HashMap::new();
443 for (k, b) in &n.inputs {
444 if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) {
445 m.insert(k.clone(), v);
446 } else if let Some(src) = &b.source_op {
447 if let Some(sp) = self.splines.get(src) {
448 m.insert(k.clone(), sp.eval(time));
449 }
446 self.nodes
447 .iter()
448 .filter(|n| names.as_ref().is_none_or(|s| s.contains(n.name.as_str())))
449 .map(|n| (n.name.clone(), self.node_expr_vars(n, time)))
450 .collect()
451 }
452
453 fn node_expr_vars(&self, node: &Node, time: f64) -> HashMap<String, ExprValue> {
454 let mut vars = HashMap::new();
455 for (k, b) in &node.inputs {
456 match b.value.as_ref() {
457 Some(ParamValue::Number(v)) => {
458 vars.insert(k.clone(), ExprValue::Number(*v));
459 continue;
460 }
461 Some(ParamValue::Text(t)) => {
462 vars.insert(k.clone(), ExprValue::Text(t.clone()));
463 continue;
450464 }
465 _ => {}
451466 }
452 if !m.is_empty() {
453 env_nodes.insert(n.name.clone(), m);
467 if let Some(sp) = b.source_op.as_ref().and_then(|src| self.splines.get(src)) {
468 vars.insert(k.clone(), ExprValue::Number(sp.eval(time)));
454469 }
455470 }
456 env_nodes
471 vars
457472 }
458473
459474 fn build_expr_mod_vars(
......@@ -699,7 +714,7 @@ impl Comp {
699714 ) -> (
700715 HashMap<String, f64>,
701716 HashMap<String, [f64; 2]>,
702 HashMap<String, HashMap<String, f64>>,
717 HashMap<String, HashMap<String, ExprValue>>,
703718 ) {
704719 let names = referenced_names(expr);
705720 let mut self_params = HashMap::new();
......@@ -726,7 +741,11 @@ impl Comp {
726741 }
727742 }
728743 }
729 (self_params, self_points, self.collect_node_env(expr, time))
744 let mut env_nodes = self.collect_node_env(expr, time);
745 if names.as_ref().is_none_or(|s| s.contains("self")) {
746 env_nodes.insert("self".to_owned(), self.node_expr_vars(node, time));
747 }
748 (self_params, self_points, env_nodes)
730749 }
731750
732751 fn eval_expr_number(
......@@ -785,4 +804,25 @@ mod tests {
785804 assert_eq!(comp.eval_number(probe, "Height", 3.0, 0.0, &engine), 42.0);
786805 assert!(start.elapsed() < std::time::Duration::from_millis(500), "{:?}", start.elapsed());
787806 }
807
808 #[test]
809 fn self_and_referenced_nodes_expose_text_inputs() {
810 let src = r##"Composition { Tools = ordered() {
811 TextA = TextPlus { Inputs = {
812 StyledText = Input { Value = "one two three", },
813 SyncWord = Input { Value = 2, },
814 End = Input { Expression = "(function(a,b) return #a + b end)(self.StyledText.Value, self.SyncWord)", },
815 }, },
816 Follower = TextPlus { Inputs = { End = Input { Expression = "TextA.End", }, }, },
817 Echo = TextPlus { Inputs = {
818 Width = Input { Expression = "#tostring(TextA.StyledText)", },
819 }, },
820 } }"##;
821 let comp = Comp::from_fusion_str(src).unwrap();
822 let engine = ExprEngine::new();
823 let follower = comp.node(comp.find_node("Follower").unwrap());
824 assert_eq!(comp.eval_number(follower, "End", 0.0, -1.0, &engine), 15.0);
825 let echo = comp.node(comp.find_node("Echo").unwrap());
826 assert_eq!(comp.eval_number(echo, "Width", 0.0, -1.0, &engine), 13.0);
827 }
788828}
crates/model/src/comp/load.rs+50
......@@ -113,6 +113,8 @@ impl Comp {
113113 }
114114 }
115115
116 let cross_macro_wires = clear_cross_macro_wires(&mut nodes, &node_by_name);
117
116118 // Apply InstanceInput defaults from MacroOperator/GroupOperator onto their inner target tools.
117119 for (target_op, target_param, val) in macro_defaults {
118120 if let Some(&nid) = node_by_name.get(&target_op) {
......@@ -284,6 +286,7 @@ impl Comp {
284286 text_cls,
285287 shakes,
286288 expression_modifiers,
289 cross_macro_wires,
287290 raw_root: Some(root.clone()),
288291 revision: NEXT_COMP_REVISION.fetch_add(REVISION_STRIDE, Ordering::Relaxed),
289292 })
......@@ -291,6 +294,53 @@ impl Comp {
291294
292295}
293296
297/// Fusion resolves a macro-internal `SourceOp` only within the macro's own scope (itself, its
298/// enclosing macros, its nested macros) or at top level; a name that only exists inside an
299/// unrelated macro stays unconnected. Returns the `(node, port)` wires whose `source_op` was
300/// cleared here so saving keeps the original text.
301fn clear_cross_macro_wires(nodes: &mut [Node], node_by_name: &HashMap<String, NodeId>) -> HashSet<(String, String)> {
302 let mut owner: HashMap<NodeId, NodeId> = HashMap::new();
303 for m in nodes.iter().filter(|n| matches!(n.kind.as_str(), "MacroOperator" | "GroupOperator")) {
304 let Some(inner) = m.raw.get_table("Tools") else { continue };
305 for (key, _) in &inner.entries {
306 let LuaKey::Str(child) = key else { continue };
307 if let Some(&cid) = node_by_name.get(child).filter(|&&c| nodes[c.0].internal) {
308 owner.insert(cid, m.id);
309 }
310 }
311 }
312 let encloses = |outer: NodeId, mut inner: NodeId| {
313 loop {
314 if inner == outer {
315 return true;
316 }
317 match owner.get(&inner) {
318 Some(&up) => inner = up,
319 None => return false,
320 }
321 }
322 };
323 let mut cleared = Vec::new();
324 for n in nodes.iter().filter(|n| n.internal) {
325 let Some(&n_scope) = owner.get(&n.id) else { continue };
326 for (port, b) in &n.inputs {
327 let Some(&t) = b.source_op.as_ref().and_then(|s| node_by_name.get(s)) else { continue };
328 if let Some(&t_scope) = owner.get(&t) {
329 if !encloses(t_scope, n_scope) && !encloses(n_scope, t_scope) {
330 cleared.push((n.id, port.clone()));
331 }
332 }
333 }
334 }
335 cleared
336 .into_iter()
337 .map(|(id, port)| {
338 nodes[id.0].inputs.get_mut(&port).expect("collected from this map").source_op = None;
339 (nodes[id.0].name.clone(), port)
340 })
341 .collect()
342}
343
294344fn is_non_inheritable_instance_port(
295345 name: &str,
296346 binding: &InputBinding,
crates/model/src/comp/save.rs+124-12
......@@ -3,7 +3,7 @@ use super::math::find_raw_tool_mut;
33use super::{BitDepth, Comp, InputBinding, Node, ParamValue, is_modifier_type};
44use crate::lua_value::{LuaKey, LuaTable, LuaValue};
55use crate::spline::{BezierSpline, read_vec2};
6use std::collections::{HashMap, VecDeque};
6use std::collections::{HashMap, HashSet, VecDeque};
77use std::io::Write;
88use std::path::{Path, PathBuf};
99use std::sync::atomic::{AtomicU64, Ordering};
......@@ -201,6 +201,31 @@ impl Comp {
201201 tool_tbl.remove(&LuaKey::Str("PassThrough".to_owned()));
202202 }
203203
204 // Loader timing edits made through `Inputs` land in the clip too (`Loop` is a count: 0 = loop).
205 if node.kind == "Loader" {
206 let edited = |port: &str| {
207 let now = node.static_number(port)?;
208 let before = tool_tbl.get_table("Inputs").and_then(|i| i.get_table(port)).map(parse_input_binding);
209 (before.and_then(|b| b.value?.as_f64()) != Some(now)).then_some(now)
210 };
211 let updates = [
212 ("GlobalStart", edited("GlobalIn").map(LuaValue::Number)),
213 ("GlobalEnd", edited("GlobalOut").map(LuaValue::Number)),
214 ("Loop", edited("Loop").map(|v| LuaValue::Number(if v > 0.5 { 0.0 } else { 1.0 }))),
215 ("Reverse", edited("Reverse").map(|v| LuaValue::Bool(v > 0.5))),
216 ];
217 let clip = tool_tbl
218 .get_table_mut("Clips")
219 .and_then(|c| c.entries.iter_mut().find_map(|(_, v)| v.as_table_mut()));
220 if let Some(clip) = clip {
221 for (key, value) in updates {
222 if let Some(value) = value {
223 clip.set(LuaKey::Str(key.to_owned()), value);
224 }
225 }
226 }
227 }
228
204229 // Group/Macro inputs hold InstanceInput wiring (synced by `sync_group_wiring`).
205230 if !is_group_kind(&node.kind) {
206231 let master_inputs = node
......@@ -208,7 +233,7 @@ impl Comp {
208233 .get_str("SourceOp")
209234 .and_then(|m| self.find_node(m))
210235 .map(|mid| &self.nodes[mid.0].inputs);
211 sync_node_inputs(node, master_inputs, instance_defaults, tool_tbl);
236 sync_node_inputs(node, master_inputs, instance_defaults, &self.cross_macro_wires, tool_tbl);
212237 }
213238 }
214239
......@@ -230,7 +255,11 @@ impl Comp {
230255
231256 let path = path.as_ref();
232257 let target = if std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
233 std::fs::canonicalize(path)?
258 // A dangling link is followed one hop so saving creates its target.
259 std::fs::canonicalize(path).or_else(|_| {
260 let hop = std::fs::read_link(path)?;
261 Ok::<_, std::io::Error>(path.parent().unwrap_or_else(|| Path::new(".")).join(hop))
262 })?
234263 } else {
235264 path.to_path_buf()
236265 };
......@@ -240,6 +269,7 @@ impl Comp {
240269 .and_then(|s| s.to_str())
241270 .filter(|s| !s.is_empty())
242271 .unwrap_or("comp");
272 let seq = BACKUP_SEQ.fetch_add(1, Ordering::Relaxed);
243273
244274 let backup_path = if path.exists() {
245275 let backup_dir = std::env::temp_dir().join("fission-backups");
......@@ -248,7 +278,6 @@ impl Comp {
248278 .duration_since(std::time::UNIX_EPOCH)
249279 .map(|d| d.as_millis())
250280 .unwrap_or(0);
251 let seq = BACKUP_SEQ.fetch_add(1, Ordering::Relaxed);
252281 let backup_file = backup_dir.join(format!("{stem}_{unix_millis}_{}_{seq}.comp.bak", std::process::id()));
253282 std::fs::copy(path, &backup_file)?;
254283 Some(backup_file)
......@@ -266,22 +295,30 @@ impl Comp {
266295 .duration_since(std::time::UNIX_EPOCH)
267296 .map(|d| d.as_nanos())
268297 .unwrap_or(0);
269 let pid = std::process::id();
270 let tmp_path = parent.join(format!(".{stem}.{pid}.{nanos}.tmp"));
298 let tmp_path = parent.join(format!(".{stem}.{}.{seq}.{nanos}.tmp", std::process::id()));
271299
272300 let serialized = self.to_fusion_string();
273 let written = std::fs::File::create(&tmp_path).and_then(|mut f| {
274 f.write_all(serialized.as_bytes())?;
275 f.sync_all()
276 });
301 let written = std::fs::OpenOptions::new()
302 .write(true)
303 .create_new(true)
304 .open(&tmp_path)
305 .and_then(|mut f| {
306 f.write_all(serialized.as_bytes())?;
307 f.sync_all()
308 });
277309 if let Err(e) = written {
278 let _ = std::fs::remove_file(&tmp_path);
310 // `create_new` failing means the name is someone else's file; never delete that.
311 if e.kind() != std::io::ErrorKind::AlreadyExists {
312 let _ = std::fs::remove_file(&tmp_path);
313 }
279314 return Err(e);
280315 }
281316 if let Err(e) = std::fs::rename(&tmp_path, path) {
282317 let _ = std::fs::remove_file(&tmp_path);
283318 return Err(e);
284319 }
320 // Best effort: persist the rename itself.
321 let _ = std::fs::File::open(parent).and_then(|dir| dir.sync_all());
285322
286323 Ok(backup_path)
287324 }
......@@ -433,6 +470,7 @@ fn sync_node_inputs(
433470 node: &Node,
434471 master_inputs: Option<&HashMap<String, InputBinding>>,
435472 instance_defaults: &HashMap<(&str, &str), ParamValue>,
473 cross_macro_wires: &HashSet<(String, String)>,
436474 tool_tbl: &mut LuaTable,
437475) {
438476 // First remove any input present in raw `Inputs` that was explicitly removed from `node.inputs`.
......@@ -467,7 +505,13 @@ fn sync_node_inputs(
467505 let existing_binding = tool_tbl
468506 .get_table("Inputs")
469507 .and_then(|i| i.get_table(port))
470 .map(parse_input_binding);
508 .map(parse_input_binding)
509 .map(|mut b| {
510 if binding.source_op.is_none() && cross_macro_wires.contains(&(node.name.clone(), port.clone())) {
511 b.source_op = None;
512 }
513 b
514 });
471515
472516 if let Some(orig) = existing_binding {
473517 if orig == *binding {
......@@ -688,4 +732,72 @@ mod tests {
688732 assert_eq!(std::fs::read_to_string(&backup).unwrap(), "old");
689733 let _ = std::fs::remove_file(backup);
690734 }
735
736 #[cfg(unix)]
737 #[test]
738 fn saving_through_a_dangling_symlink_creates_its_target() {
739 let dir = scratch("dangling");
740 let real = dir.join("real.comp");
741 let link = dir.join("link.comp");
742 std::os::unix::fs::symlink("real.comp", &link).unwrap();
743 let comp = Comp::from_fusion_str("Composition { Tools = ordered() { }, }").unwrap();
744 assert!(comp.save_to_file(&link).unwrap().is_none());
745 assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
746 assert_eq!(std::fs::read_to_string(&real).unwrap(), comp.to_fusion_string());
747 }
748
749 const LOADER: &str = r#"Composition {
750 Tools = ordered() {
751 L = Loader {
752 Clips = {
753 Clip {
754 Filename = "a.0000.exr",
755 GlobalStart = 0,
756 GlobalEnd = 10,
757 Loop = 1,
758 },
759 },
760 Inputs = {
761 Loop = Input { Value = 0, },
762 },
763 },
764 },
765 }"#;
766
767 #[test]
768 fn edited_loader_timing_inputs_land_in_the_clip() {
769 let mut comp = Comp::from_fusion_str(LOADER).unwrap();
770 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
771 assert!(!saved.node(saved.find_node("L").unwrap()).clips[0].loop_clip);
772
773 let l = comp.find_node("L").unwrap();
774 comp.set_input_value(l, "Loop", ParamValue::Number(1.0));
775 comp.set_input_value(l, "GlobalOut", ParamValue::Number(25.0));
776 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
777 let clip = &saved.node(saved.find_node("L").unwrap()).clips[0];
778 assert!(clip.loop_clip);
779 assert_eq!(clip.global_end, 25);
780 }
781
782 #[test]
783 fn cleared_cross_macro_wire_keeps_its_source_op_on_save() {
784 let src = r#"Composition {
785 Tools = ordered() {
786 A = MacroOperator {
787 Tools = ordered() {
788 InA = Blur {},
789 },
790 },
791 B = MacroOperator {
792 Tools = ordered() {
793 InB = Blur { Inputs = { Input = Input { SourceOp = "InA", Source = "Output", }, }, },
794 },
795 },
796 },
797 }"#;
798 let comp = Comp::from_fusion_str(src).unwrap();
799 let in_b = comp.node(comp.find_node("InB").unwrap());
800 assert_eq!(in_b.connected_node("Input"), None);
801 assert!(comp.to_fusion_string().contains(r#"SourceOp = "InA""#));
802 }
691803}
crates/model/src/edit/history.rs+44
......@@ -118,6 +118,14 @@ impl CompHistory {
118118 self.saved_revision != Some(comp_revision)
119119 }
120120
121 /// An unrecorded mutation at the saved depth makes the saved state unreachable: any entry
122 /// recorded from here on captures the mutated state, not the saved one.
123 fn forget_diverged_saved_depth(&mut self, depth: usize, state_revision: u64) {
124 if self.saved_undo_depth == Some(depth) && self.saved_revision != Some(state_revision) {
125 self.saved_undo_depth = None;
126 }
127 }
128
121129 /// Undo/redo bump `comp.revision` even when they land back on the saved state.
122130 fn rebase_saved_revision(&mut self, comp_revision: u64) {
123131 if self.saved_undo_depth == Some(self.undo_stack.len()) {
......@@ -255,6 +263,7 @@ impl CompHistory {
255263 return false;
256264 };
257265 let prev_rev = comp.revision;
266 self.forget_diverged_saved_depth(self.undo_stack.len() + 1, prev_rev);
258267 let redo_entry = HistoryEntry {
259268 label: entry.label,
260269 snapshot: comp.clone(),
......@@ -274,6 +283,7 @@ impl CompHistory {
274283 return false;
275284 };
276285 let prev_rev = comp.revision;
286 self.forget_diverged_saved_depth(self.undo_stack.len(), prev_rev);
277287 let undo_entry = HistoryEntry {
278288 label: entry.label,
279289 snapshot: comp.clone(),
......@@ -287,6 +297,7 @@ impl CompHistory {
287297 }
288298
289299 fn push_entry(&mut self, entry: HistoryEntry) {
300 self.forget_diverged_saved_depth(self.undo_stack.len(), entry.snapshot.revision);
290301 // Any saved state that lived in the redo branch is now unreachable.
291302 if let Some(saved_depth) = self.saved_undo_depth {
292303 if saved_depth > self.undo_stack.len() {
......@@ -448,6 +459,39 @@ mod tests {
448459 assert!(!history.is_dirty(&comp));
449460 }
450461
462 #[test]
463 fn unrecorded_mutation_at_saved_depth_is_never_clean_after_undo_redo() {
464 let mut comp = sample_comp();
465 let mut history = CompHistory::new();
466 let bg = comp.find_node("BG1").unwrap();
467
468 history.push_snapshot(&comp, "Move");
469 comp.set_node_pos(bg, [1.0, 1.0]);
470 history.mark_saved(&comp);
471
472 comp.set_node_pos(bg, [2.0, 2.0]);
473 assert!(history.is_dirty(&comp));
474 assert!(history.undo(&mut comp));
475 assert!(history.redo(&mut comp));
476 assert_eq!(comp.node(bg).pos, [2.0, 2.0]);
477 assert!(history.is_dirty(&comp));
478 }
479
480 #[test]
481 fn unrecorded_mutation_at_saved_depth_is_never_clean_after_push_undo() {
482 let mut comp = sample_comp();
483 let mut history = CompHistory::new();
484 let bg = comp.find_node("BG1").unwrap();
485 history.mark_saved(&comp);
486
487 comp.set_node_pos(bg, [2.0, 2.0]);
488 history.push_snapshot(&comp, "Move");
489 comp.set_node_pos(bg, [3.0, 3.0]);
490 assert!(history.undo(&mut comp));
491 assert_eq!(comp.node(bg).pos, [2.0, 2.0]);
492 assert!(history.is_dirty(&comp));
493 }
494
451495 #[test]
452496 fn undo_and_redo_keep_the_live_file_identity() {
453497 let mut comp = sample_comp();
crates/model/src/expr.rs+26-7
......@@ -14,6 +14,14 @@ const INSTRUCTION_BUDGET: u64 = 50_000;
1414const HOOK_STEP: u32 = 1000;
1515const MEMORY_LIMIT: usize = 16 * 1024 * 1024;
1616
17/// An input readable from an expression. Text inputs surface as `{ Value = "..." }` tables that
18/// also stringify, matching Fusion's `Node.StyledText.Value`.
19#[derive(Clone, Debug, PartialEq)]
20pub enum ExprValue {
21 Number(f64),
22 Text(String),
23}
24
1725/// Expressions come from `.comp` files, so the VM is sandboxed: no `os`/`io`/`debug`/`package`,
1826/// no code loading, and bounded instructions and memory per evaluation.
1927pub struct ExprEngine {
......@@ -118,7 +126,7 @@ impl ExprEngine {
118126 time: f64,
119127 self_params: &HashMap<String, f64>,
120128 self_points: &HashMap<String, [f64; 2]>,
121 env_nodes: &HashMap<String, HashMap<String, f64>>,
129 env_nodes: &HashMap<String, HashMap<String, ExprValue>>,
122130 ) -> Option<Value> {
123131 let env = self.build_env(time, self_params, self_points, env_nodes).ok()?;
124132 self.instructions_used.store(0, Ordering::Relaxed);
......@@ -136,7 +144,7 @@ impl ExprEngine {
136144 }
137145
138146 /// Evaluates a Fusion SimpleExpression returning a number.
139 /// `env_nodes` provides `node_name -> (param_name -> f64)` and `self_params` provides
147 /// `env_nodes` provides `node_name -> (param_name -> value)` and `self_params` provides
140148 /// unqualified parameter names on the current node.
141149 pub fn eval_number(
142150 &self,
......@@ -144,7 +152,7 @@ impl ExprEngine {
144152 time: f64,
145153 self_params: &HashMap<String, f64>,
146154 self_points: &HashMap<String, [f64; 2]>,
147 env_nodes: &HashMap<String, HashMap<String, f64>>,
155 env_nodes: &HashMap<String, HashMap<String, ExprValue>>,
148156 ) -> Option<f64> {
149157 let val = self.run(expr, time, self_params, self_points, env_nodes)?;
150158 match val {
......@@ -163,7 +171,7 @@ impl ExprEngine {
163171 time: f64,
164172 self_params: &HashMap<String, f64>,
165173 self_points: &HashMap<String, [f64; 2]>,
166 env_nodes: &HashMap<String, HashMap<String, f64>>,
174 env_nodes: &HashMap<String, HashMap<String, ExprValue>>,
167175 ) -> Option<[f64; 2]> {
168176 let val = self.run(expr, time, self_params, self_points, env_nodes)?;
169177 if let Value::Table(t) = val {
......@@ -181,13 +189,14 @@ impl ExprEngine {
181189 time: f64,
182190 self_params: &HashMap<String, f64>,
183191 self_points: &HashMap<String, [f64; 2]>,
184 env_nodes: &HashMap<String, HashMap<String, f64>>,
192 env_nodes: &HashMap<String, HashMap<String, ExprValue>>,
185193 ) -> Option<String> {
186194 let val = self.run(expr, time, self_params, self_points, env_nodes)?;
187195 match val {
188196 Value::String(s) => Some(s.to_str().ok()?.to_owned()),
189197 Value::Number(n) => Some(format!("{n}")),
190198 Value::Integer(i) => Some(format!("{i}")),
199 Value::Table(t) => t.get::<String>("Value").ok(),
191200 _ => None,
192201 }
193202 }
......@@ -197,7 +206,7 @@ impl ExprEngine {
197206 time: f64,
198207 self_params: &HashMap<String, f64>,
199208 self_points: &HashMap<String, [f64; 2]>,
200 env_nodes: &HashMap<String, HashMap<String, f64>>,
209 env_nodes: &HashMap<String, HashMap<String, ExprValue>>,
201210 ) -> mlua::Result<mlua::Table> {
202211 let env = self.lua.create_table()?;
203212 let mt = self.lua.create_table()?;
......@@ -219,10 +228,20 @@ impl ExprEngine {
219228 // Missing node fields default to 0 so expressions don't nil-crash.
220229 let zero_mt = self.lua.create_table()?;
221230 zero_mt.set("__index", self.lua.create_function(|_, _args: MultiValue| Ok(0.0_f64))?)?;
231 let text_mt = self.lua.create_table()?;
232 text_mt.set("__tostring", self.lua.create_function(|_, this: mlua::Table| this.get::<String>("Value"))?)?;
222233 for (node_name, params) in env_nodes {
223234 let nt = self.lua.create_table()?;
224235 for (pk, pv) in params {
225 nt.set(pk.as_str(), *pv)?;
236 match pv {
237 ExprValue::Number(n) => nt.set(pk.as_str(), *n)?,
238 ExprValue::Text(s) => {
239 let text = self.lua.create_table()?;
240 text.set("Value", s.as_str())?;
241 text.set_metatable(Some(text_mt.clone()));
242 nt.set(pk.as_str(), text)?;
243 }
244 }
226245 }
227246 nt.set_metatable(Some(zero_mt.clone()));
228247 env.set(node_name.as_str(), nt)?;