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 {...@@ -431,6 +431,9 @@ pub struct Comp {
431 pub shakes: HashMap<String, ShakeModifier>,431 pub shakes: HashMap<String, ShakeModifier>,
432 /// Standalone `Expression` modifiers keyed by modifier name (e.g. `"Expression1"`).432 /// Standalone `Expression` modifiers keyed by modifier name (e.g. `"Expression1"`).
433 pub expression_modifiers: HashMap<String, ExpressionModifier>,433 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)>,
434 /// Preserved raw root `Composition { ... }` Lua AST for lossless `.comp` roundtrip.437 /// Preserved raw root `Composition { ... }` Lua AST for lossless `.comp` roundtrip.
435 pub raw_root: Option<LuaTable>,438 pub raw_root: Option<LuaTable>,
436 /// Generation counter incremented whenever any node, wire, or spline mutates.439 /// Generation counter incremented whenever any node, wire, or spline mutates.
crates/model/src/comp/eval.rs+66-26
...@@ -1,6 +1,6 @@...@@ -1,6 +1,6 @@
1use super::math::eval_fusion_math_expr;1use super::math::eval_fusion_math_expr;
2use super::{ClsEntry, Comp, ExpressionModifier, MAX_EXPR_DEPTH, Node, ParamValue, ShakeModifier};2use super::{ClsEntry, Comp, ExpressionModifier, MAX_EXPR_DEPTH, Node, ParamValue, ShakeModifier};
3use crate::expr::ExprEngine;3use crate::expr::{ExprEngine, ExprValue};
4use crate::spline::Gradient;4use crate::spline::Gradient;
5use std::cell::RefCell;5use std::cell::RefCell;
6use std::collections::{HashMap, HashSet};6use std::collections::{HashMap, HashSet};
...@@ -12,11 +12,11 @@ thread_local! {...@@ -12,11 +12,11 @@ thread_local! {
12 static EXPR_MOD_MEMO: RefCell<Option<HashMap<ModMemoKey, Option<[f64; 2]>>>> = const { RefCell::new(None) };12 static EXPR_MOD_MEMO: RefCell<Option<HashMap<ModMemoKey, Option<[f64; 2]>>>> = const { RefCell::new(None) };
13}13}
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.
16fn referenced_names(expr: &str) -> Option<HashSet<&str>> {16fn referenced_names(expr: &str) -> Option<HashSet<&str>> {
17 let names: HashSet<&str> =17 let names: HashSet<&str> =
18 expr.split(|c: char| !c.is_ascii_alphanumeric() && c != '_').filter(|t| !t.is_empty()).collect();18 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)
20}20}
2121
22struct ModMemoScope(bool);22struct ModMemoScope(bool);
...@@ -123,10 +123,19 @@ impl Comp {...@@ -123,10 +123,19 @@ impl Comp {
123 return default;123 return default;
124 };124 };
125 if let Some(expr) = &binding.expression {125 if let Some(expr) = &binding.expression {
126 if let Some(v) = self.eval_expr_number(node, expr, time, expr_engine) {126 // A bare `Node.Param` follows that input's own expression/animation instead of its baked value.
127 if v.is_finite() {127 let referenced = expr.trim().split_once('.').and_then(|(n, p)| {
128 return v;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))
129 }134 }
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;
130 }139 }
131 }140 }
132 if let Some(src) = &binding.source_op {141 if let Some(src) = &binding.source_op {
...@@ -431,29 +440,35 @@ impl Comp {...@@ -431,29 +440,35 @@ impl Comp {
431 expr_engine.eval_number(trimmed, time, &HashMap::new(), &HashMap::new(), &en)440 expr_engine.eval_number(trimmed, time, &HashMap::new(), &HashMap::new(), &en)
432 }441 }
433442
434 /// `node name -> numeric inputs` for the nodes `expr` can reach; every other node is skipped.443 /// `node name -> numeric/text 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>> {444 fn collect_node_env(&self, expr: &str, time: f64) -> HashMap<String, HashMap<String, ExprValue>> {
436 let names = referenced_names(expr);445 let names = referenced_names(expr);
437 let mut env_nodes = HashMap::new();446 self.nodes
438 for n in &self.nodes {447 .iter()
439 if !names.as_ref().is_none_or(|s| s.contains(n.name.as_str())) {448 .filter(|n| names.as_ref().is_none_or(|s| s.contains(n.name.as_str())))
440 continue;449 .map(|n| (n.name.clone(), self.node_expr_vars(n, time)))
441 }450 .collect()
442 let mut m = HashMap::new();451 }
443 for (k, b) in &n.inputs {452
444 if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) {453 fn node_expr_vars(&self, node: &Node, time: f64) -> HashMap<String, ExprValue> {
445 m.insert(k.clone(), v);454 let mut vars = HashMap::new();
446 } else if let Some(src) = &b.source_op {455 for (k, b) in &node.inputs {
447 if let Some(sp) = self.splines.get(src) {456 match b.value.as_ref() {
448 m.insert(k.clone(), sp.eval(time));457 Some(ParamValue::Number(v)) => {
449 }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;
450 }464 }
465 _ => {}
451 }466 }
452 if !m.is_empty() {467 if let Some(sp) = b.source_op.as_ref().and_then(|src| self.splines.get(src)) {
453 env_nodes.insert(n.name.clone(), m);468 vars.insert(k.clone(), ExprValue::Number(sp.eval(time)));
454 }469 }
455 }470 }
456 env_nodes471 vars
457 }472 }
458473
459 fn build_expr_mod_vars(474 fn build_expr_mod_vars(
...@@ -699,7 +714,7 @@ impl Comp {...@@ -699,7 +714,7 @@ impl Comp {
699 ) -> (714 ) -> (
700 HashMap<String, f64>,715 HashMap<String, f64>,
701 HashMap<String, [f64; 2]>,716 HashMap<String, [f64; 2]>,
702 HashMap<String, HashMap<String, f64>>,717 HashMap<String, HashMap<String, ExprValue>>,
703 ) {718 ) {
704 let names = referenced_names(expr);719 let names = referenced_names(expr);
705 let mut self_params = HashMap::new();720 let mut self_params = HashMap::new();
...@@ -726,7 +741,11 @@ impl Comp {...@@ -726,7 +741,11 @@ impl Comp {
726 }741 }
727 }742 }
728 }743 }
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)
730 }749 }
731750
732 fn eval_expr_number(751 fn eval_expr_number(
...@@ -785,4 +804,25 @@ mod tests {...@@ -785,4 +804,25 @@ mod tests {
785 assert_eq!(comp.eval_number(probe, "Height", 3.0, 0.0, &engine), 42.0);804 assert_eq!(comp.eval_number(probe, "Height", 3.0, 0.0, &engine), 42.0);
786 assert!(start.elapsed() < std::time::Duration::from_millis(500), "{:?}", start.elapsed());805 assert!(start.elapsed() < std::time::Duration::from_millis(500), "{:?}", start.elapsed());
787 }806 }
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 }
788}828}
crates/model/src/comp/load.rs+50
...@@ -113,6 +113,8 @@ impl Comp {...@@ -113,6 +113,8 @@ impl Comp {
113 }113 }
114 }114 }
115115
116 let cross_macro_wires = clear_cross_macro_wires(&mut nodes, &node_by_name);
117
116 // Apply InstanceInput defaults from MacroOperator/GroupOperator onto their inner target tools.118 // Apply InstanceInput defaults from MacroOperator/GroupOperator onto their inner target tools.
117 for (target_op, target_param, val) in macro_defaults {119 for (target_op, target_param, val) in macro_defaults {
118 if let Some(&nid) = node_by_name.get(&target_op) {120 if let Some(&nid) = node_by_name.get(&target_op) {
...@@ -284,6 +286,7 @@ impl Comp {...@@ -284,6 +286,7 @@ impl Comp {
284 text_cls,286 text_cls,
285 shakes,287 shakes,
286 expression_modifiers,288 expression_modifiers,
289 cross_macro_wires,
287 raw_root: Some(root.clone()),290 raw_root: Some(root.clone()),
288 revision: NEXT_COMP_REVISION.fetch_add(REVISION_STRIDE, Ordering::Relaxed),291 revision: NEXT_COMP_REVISION.fetch_add(REVISION_STRIDE, Ordering::Relaxed),
289 })292 })
...@@ -291,6 +294,53 @@ impl Comp {...@@ -291,6 +294,53 @@ impl Comp {
291294
292}295}
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
294fn is_non_inheritable_instance_port(344fn is_non_inheritable_instance_port(
295 name: &str,345 name: &str,
296 binding: &InputBinding,346 binding: &InputBinding,
crates/model/src/comp/save.rs+124-12
...@@ -3,7 +3,7 @@ use super::math::find_raw_tool_mut;...@@ -3,7 +3,7 @@ use super::math::find_raw_tool_mut;
3use super::{BitDepth, Comp, InputBinding, Node, ParamValue, is_modifier_type};3use super::{BitDepth, Comp, InputBinding, Node, ParamValue, is_modifier_type};
4use crate::lua_value::{LuaKey, LuaTable, LuaValue};4use crate::lua_value::{LuaKey, LuaTable, LuaValue};
5use crate::spline::{BezierSpline, read_vec2};5use crate::spline::{BezierSpline, read_vec2};
6use std::collections::{HashMap, VecDeque};6use std::collections::{HashMap, HashSet, VecDeque};
7use std::io::Write;7use std::io::Write;
8use std::path::{Path, PathBuf};8use std::path::{Path, PathBuf};
9use std::sync::atomic::{AtomicU64, Ordering};9use std::sync::atomic::{AtomicU64, Ordering};
...@@ -201,6 +201,31 @@ impl Comp {...@@ -201,6 +201,31 @@ impl Comp {
201 tool_tbl.remove(&LuaKey::Str("PassThrough".to_owned()));201 tool_tbl.remove(&LuaKey::Str("PassThrough".to_owned()));
202 }202 }
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
204 // Group/Macro inputs hold InstanceInput wiring (synced by `sync_group_wiring`).229 // Group/Macro inputs hold InstanceInput wiring (synced by `sync_group_wiring`).
205 if !is_group_kind(&node.kind) {230 if !is_group_kind(&node.kind) {
206 let master_inputs = node231 let master_inputs = node
...@@ -208,7 +233,7 @@ impl Comp {...@@ -208,7 +233,7 @@ impl Comp {
208 .get_str("SourceOp")233 .get_str("SourceOp")
209 .and_then(|m| self.find_node(m))234 .and_then(|m| self.find_node(m))
210 .map(|mid| &self.nodes[mid.0].inputs);235 .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);
212 }237 }
213 }238 }
214239
...@@ -230,7 +255,11 @@ impl Comp {...@@ -230,7 +255,11 @@ impl Comp {
230255
231 let path = path.as_ref();256 let path = path.as_ref();
232 let target = if std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {257 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 })?
234 } else {263 } else {
235 path.to_path_buf()264 path.to_path_buf()
236 };265 };
...@@ -240,6 +269,7 @@ impl Comp {...@@ -240,6 +269,7 @@ impl Comp {
240 .and_then(|s| s.to_str())269 .and_then(|s| s.to_str())
241 .filter(|s| !s.is_empty())270 .filter(|s| !s.is_empty())
242 .unwrap_or("comp");271 .unwrap_or("comp");
272 let seq = BACKUP_SEQ.fetch_add(1, Ordering::Relaxed);
243273
244 let backup_path = if path.exists() {274 let backup_path = if path.exists() {
245 let backup_dir = std::env::temp_dir().join("fission-backups");275 let backup_dir = std::env::temp_dir().join("fission-backups");
...@@ -248,7 +278,6 @@ impl Comp {...@@ -248,7 +278,6 @@ impl Comp {
248 .duration_since(std::time::UNIX_EPOCH)278 .duration_since(std::time::UNIX_EPOCH)
249 .map(|d| d.as_millis())279 .map(|d| d.as_millis())
250 .unwrap_or(0);280 .unwrap_or(0);
251 let seq = BACKUP_SEQ.fetch_add(1, Ordering::Relaxed);
252 let backup_file = backup_dir.join(format!("{stem}_{unix_millis}_{}_{seq}.comp.bak", std::process::id()));281 let backup_file = backup_dir.join(format!("{stem}_{unix_millis}_{}_{seq}.comp.bak", std::process::id()));
253 std::fs::copy(path, &backup_file)?;282 std::fs::copy(path, &backup_file)?;
254 Some(backup_file)283 Some(backup_file)
...@@ -266,22 +295,30 @@ impl Comp {...@@ -266,22 +295,30 @@ impl Comp {
266 .duration_since(std::time::UNIX_EPOCH)295 .duration_since(std::time::UNIX_EPOCH)
267 .map(|d| d.as_nanos())296 .map(|d| d.as_nanos())
268 .unwrap_or(0);297 .unwrap_or(0);
269 let pid = std::process::id();298 let tmp_path = parent.join(format!(".{stem}.{}.{seq}.{nanos}.tmp", std::process::id()));
270 let tmp_path = parent.join(format!(".{stem}.{pid}.{nanos}.tmp"));
271299
272 let serialized = self.to_fusion_string();300 let serialized = self.to_fusion_string();
273 let written = std::fs::File::create(&tmp_path).and_then(|mut f| {301 let written = std::fs::OpenOptions::new()
274 f.write_all(serialized.as_bytes())?;302 .write(true)
275 f.sync_all()303 .create_new(true)
276 });304 .open(&tmp_path)
305 .and_then(|mut f| {
306 f.write_all(serialized.as_bytes())?;
307 f.sync_all()
308 });
277 if let Err(e) = written {309 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 }
279 return Err(e);314 return Err(e);
280 }315 }
281 if let Err(e) = std::fs::rename(&tmp_path, path) {316 if let Err(e) = std::fs::rename(&tmp_path, path) {
282 let _ = std::fs::remove_file(&tmp_path);317 let _ = std::fs::remove_file(&tmp_path);
283 return Err(e);318 return Err(e);
284 }319 }
320 // Best effort: persist the rename itself.
321 let _ = std::fs::File::open(parent).and_then(|dir| dir.sync_all());
285322
286 Ok(backup_path)323 Ok(backup_path)
287 }324 }
...@@ -433,6 +470,7 @@ fn sync_node_inputs(...@@ -433,6 +470,7 @@ fn sync_node_inputs(
433 node: &Node,470 node: &Node,
434 master_inputs: Option<&HashMap<String, InputBinding>>,471 master_inputs: Option<&HashMap<String, InputBinding>>,
435 instance_defaults: &HashMap<(&str, &str), ParamValue>,472 instance_defaults: &HashMap<(&str, &str), ParamValue>,
473 cross_macro_wires: &HashSet<(String, String)>,
436 tool_tbl: &mut LuaTable,474 tool_tbl: &mut LuaTable,
437) {475) {
438 // First remove any input present in raw `Inputs` that was explicitly removed from `node.inputs`.476 // First remove any input present in raw `Inputs` that was explicitly removed from `node.inputs`.
...@@ -467,7 +505,13 @@ fn sync_node_inputs(...@@ -467,7 +505,13 @@ fn sync_node_inputs(
467 let existing_binding = tool_tbl505 let existing_binding = tool_tbl
468 .get_table("Inputs")506 .get_table("Inputs")
469 .and_then(|i| i.get_table(port))507 .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
472 if let Some(orig) = existing_binding {516 if let Some(orig) = existing_binding {
473 if orig == *binding {517 if orig == *binding {
...@@ -688,4 +732,72 @@ mod tests {...@@ -688,4 +732,72 @@ mod tests {
688 assert_eq!(std::fs::read_to_string(&backup).unwrap(), "old");732 assert_eq!(std::fs::read_to_string(&backup).unwrap(), "old");
689 let _ = std::fs::remove_file(backup);733 let _ = std::fs::remove_file(backup);
690 }734 }
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 }
691}803}
crates/model/src/edit/history.rs+44
...@@ -118,6 +118,14 @@ impl CompHistory {...@@ -118,6 +118,14 @@ impl CompHistory {
118 self.saved_revision != Some(comp_revision)118 self.saved_revision != Some(comp_revision)
119 }119 }
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
121 /// Undo/redo bump `comp.revision` even when they land back on the saved state.129 /// Undo/redo bump `comp.revision` even when they land back on the saved state.
122 fn rebase_saved_revision(&mut self, comp_revision: u64) {130 fn rebase_saved_revision(&mut self, comp_revision: u64) {
123 if self.saved_undo_depth == Some(self.undo_stack.len()) {131 if self.saved_undo_depth == Some(self.undo_stack.len()) {
...@@ -255,6 +263,7 @@ impl CompHistory {...@@ -255,6 +263,7 @@ impl CompHistory {
255 return false;263 return false;
256 };264 };
257 let prev_rev = comp.revision;265 let prev_rev = comp.revision;
266 self.forget_diverged_saved_depth(self.undo_stack.len() + 1, prev_rev);
258 let redo_entry = HistoryEntry {267 let redo_entry = HistoryEntry {
259 label: entry.label,268 label: entry.label,
260 snapshot: comp.clone(),269 snapshot: comp.clone(),
...@@ -274,6 +283,7 @@ impl CompHistory {...@@ -274,6 +283,7 @@ impl CompHistory {
274 return false;283 return false;
275 };284 };
276 let prev_rev = comp.revision;285 let prev_rev = comp.revision;
286 self.forget_diverged_saved_depth(self.undo_stack.len(), prev_rev);
277 let undo_entry = HistoryEntry {287 let undo_entry = HistoryEntry {
278 label: entry.label,288 label: entry.label,
279 snapshot: comp.clone(),289 snapshot: comp.clone(),
...@@ -287,6 +297,7 @@ impl CompHistory {...@@ -287,6 +297,7 @@ impl CompHistory {
287 }297 }
288298
289 fn push_entry(&mut self, entry: HistoryEntry) {299 fn push_entry(&mut self, entry: HistoryEntry) {
300 self.forget_diverged_saved_depth(self.undo_stack.len(), entry.snapshot.revision);
290 // Any saved state that lived in the redo branch is now unreachable.301 // Any saved state that lived in the redo branch is now unreachable.
291 if let Some(saved_depth) = self.saved_undo_depth {302 if let Some(saved_depth) = self.saved_undo_depth {
292 if saved_depth > self.undo_stack.len() {303 if saved_depth > self.undo_stack.len() {
...@@ -448,6 +459,39 @@ mod tests {...@@ -448,6 +459,39 @@ mod tests {
448 assert!(!history.is_dirty(&comp));459 assert!(!history.is_dirty(&comp));
449 }460 }
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
451 #[test]495 #[test]
452 fn undo_and_redo_keep_the_live_file_identity() {496 fn undo_and_redo_keep_the_live_file_identity() {
453 let mut comp = sample_comp();497 let mut comp = sample_comp();
crates/model/src/expr.rs+26-7
...@@ -14,6 +14,14 @@ const INSTRUCTION_BUDGET: u64 = 50_000;...@@ -14,6 +14,14 @@ const INSTRUCTION_BUDGET: u64 = 50_000;
14const HOOK_STEP: u32 = 1000;14const HOOK_STEP: u32 = 1000;
15const MEMORY_LIMIT: usize = 16 * 1024 * 1024;15const 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
17/// Expressions come from `.comp` files, so the VM is sandboxed: no `os`/`io`/`debug`/`package`,25/// Expressions come from `.comp` files, so the VM is sandboxed: no `os`/`io`/`debug`/`package`,
18/// no code loading, and bounded instructions and memory per evaluation.26/// no code loading, and bounded instructions and memory per evaluation.
19pub struct ExprEngine {27pub struct ExprEngine {
...@@ -118,7 +126,7 @@ impl ExprEngine {...@@ -118,7 +126,7 @@ impl ExprEngine {
118 time: f64,126 time: f64,
119 self_params: &HashMap<String, f64>,127 self_params: &HashMap<String, f64>,
120 self_points: &HashMap<String, [f64; 2]>,128 self_points: &HashMap<String, [f64; 2]>,
121 env_nodes: &HashMap<String, HashMap<String, f64>>,129 env_nodes: &HashMap<String, HashMap<String, ExprValue>>,
122 ) -> Option<Value> {130 ) -> Option<Value> {
123 let env = self.build_env(time, self_params, self_points, env_nodes).ok()?;131 let env = self.build_env(time, self_params, self_points, env_nodes).ok()?;
124 self.instructions_used.store(0, Ordering::Relaxed);132 self.instructions_used.store(0, Ordering::Relaxed);
...@@ -136,7 +144,7 @@ impl ExprEngine {...@@ -136,7 +144,7 @@ impl ExprEngine {
136 }144 }
137145
138 /// Evaluates a Fusion SimpleExpression returning a number.146 /// Evaluates a Fusion SimpleExpression returning a number.
139 /// `env_nodes` provides `node_name -> (param_name -> f64)` and `self_params` provides147 /// `env_nodes` provides `node_name -> (param_name -> value)` and `self_params` provides
140 /// unqualified parameter names on the current node.148 /// unqualified parameter names on the current node.
141 pub fn eval_number(149 pub fn eval_number(
142 &self,150 &self,
...@@ -144,7 +152,7 @@ impl ExprEngine {...@@ -144,7 +152,7 @@ impl ExprEngine {
144 time: f64,152 time: f64,
145 self_params: &HashMap<String, f64>,153 self_params: &HashMap<String, f64>,
146 self_points: &HashMap<String, [f64; 2]>,154 self_points: &HashMap<String, [f64; 2]>,
147 env_nodes: &HashMap<String, HashMap<String, f64>>,155 env_nodes: &HashMap<String, HashMap<String, ExprValue>>,
148 ) -> Option<f64> {156 ) -> Option<f64> {
149 let val = self.run(expr, time, self_params, self_points, env_nodes)?;157 let val = self.run(expr, time, self_params, self_points, env_nodes)?;
150 match val {158 match val {
...@@ -163,7 +171,7 @@ impl ExprEngine {...@@ -163,7 +171,7 @@ impl ExprEngine {
163 time: f64,171 time: f64,
164 self_params: &HashMap<String, f64>,172 self_params: &HashMap<String, f64>,
165 self_points: &HashMap<String, [f64; 2]>,173 self_points: &HashMap<String, [f64; 2]>,
166 env_nodes: &HashMap<String, HashMap<String, f64>>,174 env_nodes: &HashMap<String, HashMap<String, ExprValue>>,
167 ) -> Option<[f64; 2]> {175 ) -> Option<[f64; 2]> {
168 let val = self.run(expr, time, self_params, self_points, env_nodes)?;176 let val = self.run(expr, time, self_params, self_points, env_nodes)?;
169 if let Value::Table(t) = val {177 if let Value::Table(t) = val {
...@@ -181,13 +189,14 @@ impl ExprEngine {...@@ -181,13 +189,14 @@ impl ExprEngine {
181 time: f64,189 time: f64,
182 self_params: &HashMap<String, f64>,190 self_params: &HashMap<String, f64>,
183 self_points: &HashMap<String, [f64; 2]>,191 self_points: &HashMap<String, [f64; 2]>,
184 env_nodes: &HashMap<String, HashMap<String, f64>>,192 env_nodes: &HashMap<String, HashMap<String, ExprValue>>,
185 ) -> Option<String> {193 ) -> Option<String> {
186 let val = self.run(expr, time, self_params, self_points, env_nodes)?;194 let val = self.run(expr, time, self_params, self_points, env_nodes)?;
187 match val {195 match val {
188 Value::String(s) => Some(s.to_str().ok()?.to_owned()),196 Value::String(s) => Some(s.to_str().ok()?.to_owned()),
189 Value::Number(n) => Some(format!("{n}")),197 Value::Number(n) => Some(format!("{n}")),
190 Value::Integer(i) => Some(format!("{i}")),198 Value::Integer(i) => Some(format!("{i}")),
199 Value::Table(t) => t.get::<String>("Value").ok(),
191 _ => None,200 _ => None,
192 }201 }
193 }202 }
...@@ -197,7 +206,7 @@ impl ExprEngine {...@@ -197,7 +206,7 @@ impl ExprEngine {
197 time: f64,206 time: f64,
198 self_params: &HashMap<String, f64>,207 self_params: &HashMap<String, f64>,
199 self_points: &HashMap<String, [f64; 2]>,208 self_points: &HashMap<String, [f64; 2]>,
200 env_nodes: &HashMap<String, HashMap<String, f64>>,209 env_nodes: &HashMap<String, HashMap<String, ExprValue>>,
201 ) -> mlua::Result<mlua::Table> {210 ) -> mlua::Result<mlua::Table> {
202 let env = self.lua.create_table()?;211 let env = self.lua.create_table()?;
203 let mt = self.lua.create_table()?;212 let mt = self.lua.create_table()?;
...@@ -219,10 +228,20 @@ impl ExprEngine {...@@ -219,10 +228,20 @@ impl ExprEngine {
219 // Missing node fields default to 0 so expressions don't nil-crash.228 // Missing node fields default to 0 so expressions don't nil-crash.
220 let zero_mt = self.lua.create_table()?;229 let zero_mt = self.lua.create_table()?;
221 zero_mt.set("__index", self.lua.create_function(|_, _args: MultiValue| Ok(0.0_f64))?)?;230 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"))?)?;
222 for (node_name, params) in env_nodes {233 for (node_name, params) in env_nodes {
223 let nt = self.lua.create_table()?;234 let nt = self.lua.create_table()?;
224 for (pk, pv) in params {235 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 }
226 }245 }
227 nt.set_metatable(Some(zero_mt.clone()));246 nt.set_metatable(Some(zero_mt.clone()));
228 env.set(node_name.as_str(), nt)?;247 env.set(node_name.as_str(), nt)?;