authoravatarclover caruso<git@paperclover.net>2026-11-30 21:17:36-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 21:26:34-08:00
log0e60fad05e3b97d36ea194f3ff65775d12de6c00
tree4f2044b0eebd004051bf3978a49de86ea5ae34bc
parent10ba830bfdf5a6c68ae9b264d0d76f5ea9a1a19c
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Add PolylineMask Angle, lazy expr env lookup, durable save_to_file, and revision dirty check

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>

6 files changed, 231 insertions(+), 74 deletions(-)

crates/engine/src/eval/masks.rs+4-1
...@@ -192,6 +192,7 @@ impl Engine {...@@ -192,6 +192,7 @@ impl Engine {
192 ) -> CachedTexture {192 ) -> CachedTexture {
193 let size = self.explicit_mask_size(comp, node, time, comp_dims);193 let size = self.explicit_mask_size(comp, node, time, comp_dims);
194 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);194 let center = comp.eval_point(node, "Center", time, [0.5, 0.5], &self.expr);
195 let angle = comp.eval_number(node, "Angle", time, 0.0, &self.expr) as f32;
195 let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr).max(0.0) as f32;196 let soft = comp.eval_number(node, "SoftEdge", time, 0.0, &self.expr).max(0.0) as f32;
196 let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) > 0.5;197 let invert = comp.eval_number(node, "Invert", time, 0.0, &self.expr) > 0.5;
197 let level = comp.eval_number(node, "Level", time, 1.0, &self.expr) as f32;198 let level = comp.eval_number(node, "Level", time, 1.0, &self.expr) as f32;
...@@ -203,10 +204,11 @@ impl Engine {...@@ -203,10 +204,11 @@ impl Engine {
203204
204 let points = Self::polyline_points(comp, node, time);205 let points = Self::polyline_points(comp, node, time);
205206
206 let mut hash_floats = Vec::with_capacity(8 + points.len() * 6);207 let mut hash_floats = Vec::with_capacity(9 + points.len() * 6);
207 hash_floats.extend_from_slice(&[208 hash_floats.extend_from_slice(&[
208 center[0] as f32,209 center[0] as f32,
209 center[1] as f32,210 center[1] as f32,
211 angle,
210 soft,212 soft,
211 if invert { 1.0 } else { 0.0 },213 if invert { 1.0 } else { 0.0 },
212 level,214 level,
...@@ -231,6 +233,7 @@ impl Engine {...@@ -231,6 +233,7 @@ impl Engine {
231 size,233 size,
232 &points,234 &points,
233 [center[0] as f32, center[1] as f32],235 [center[0] as f32, center[1] as f32],
236 angle,
234 if need_post { false } else { invert },237 if need_post { false } else { invert },
235 if need_post { 1.0 } else { level },238 if need_post { 1.0 } else { level },
236 );239 );
crates/engine/src/media/raster.rs+33-4
...@@ -179,11 +179,13 @@ fn blit_max(c: &text_engine::Coverage, origin: [i32; 2], plane: [usize; 2], mut...@@ -179,11 +179,13 @@ fn blit_max(c: &text_engine::Coverage, origin: [i32; 2], plane: [usize; 2], mut
179 }179 }
180}180}
181181
182/// Rasterizes a closed Fusion `PolylineMask` into RGBA8 `[w, h]` via `zeno`.182/// Rasterizes a closed Fusion `PolylineMask` into RGBA8 `[w, h]` via `zeno`. Points and handles
183/// are offsets from `center`, rotated counter-clockwise by `angle_deg` in isotropic frame-width units.
183pub fn rasterize_polyline_mask(184pub fn rasterize_polyline_mask(
184 dims: [u32; 2],185 dims: [u32; 2],
185 points: &[PolyPoint],186 points: &[PolyPoint],
186 center: [f32; 2],187 center: [f32; 2],
188 angle_deg: f32,
187 invert: bool,189 invert: bool,
188 level: f32,190 level: f32,
189) -> Vec<u8> {191) -> Vec<u8> {
...@@ -192,10 +194,12 @@ pub fn rasterize_polyline_mask(...@@ -192,10 +194,12 @@ pub fn rasterize_polyline_mask(
192 if points.len() < 2 {194 if points.len() < 2 {
193 return out;195 return out;
194 }196 }
197 let aspect = w as f32 / (h as f32).max(1.0);
198 let (s, c) = angle_deg.to_radians().sin_cos();
195 let to_px = |x: f64, y: f64| -> [f32; 2] {199 let to_px = |x: f64, y: f64| -> [f32; 2] {
196 let fx = (center[0] + x as f32) * w as f32;200 let (x, y) = (x as f32, y as f32 / aspect);
197 let fy = (1.0 - (center[1] + y as f32)) * h as f32;201 let (rx, ry) = (x * c - y * s, (x * s + y * c) * aspect);
198 [fx, fy]202 [(center[0] + rx) * w as f32, (1.0 - (center[1] + ry)) * h as f32]
199 };203 };
200 let mut cmds = Vec::new();204 let mut cmds = Vec::new();
201 let p0 = to_px(points[0].x, points[0].y);205 let p0 = to_px(points[0].x, points[0].y);
...@@ -236,3 +240,28 @@ pub fn rasterize_polyline_mask(...@@ -236,3 +240,28 @@ pub fn rasterize_polyline_mask(
236 }240 }
237 out241 out
238}242}
243
244#[cfg(test)]
245mod tests {
246 use super::*;
247
248 fn corner(x: f64, y: f64) -> PolyPoint {
249 PolyPoint { x, y, lx: 0.0, ly: 0.0, rx: 0.0, ry: 0.0, linear: true }
250 }
251
252 #[test]
253 fn polyline_mask_angle_rotates_ccw_around_center_in_isotropic_units() {
254 // 2:1 canvas; rect is 0.4 frame-widths wide and 0.1 frame-heights tall around Center.
255 let rect = [corner(-0.2, -0.05), corner(0.2, -0.05), corner(0.2, 0.05), corner(-0.2, 0.05)];
256 let on = |px: &[u8], x: usize, y: usize| px[(y * 200 + x) * 4 + 3] > 200;
257
258 let flat = rasterize_polyline_mask([200, 100], &rect, [0.5, 0.5], 0.0, false, 1.0);
259 assert!(on(&flat, 130, 50) && on(&flat, 100, 50));
260 assert!(!on(&flat, 100, 20) && !on(&flat, 100, 80));
261
262 // 90 degrees: 0.2 width = 0.4 height, so the bar spans y 10..90 and is 0.05 width thick.
263 let tall = rasterize_polyline_mask([200, 100], &rect, [0.5, 0.5], 90.0, false, 1.0);
264 assert!(on(&tall, 100, 50) && on(&tall, 100, 20) && on(&tall, 100, 80));
265 assert!(!on(&tall, 130, 50) && !on(&tall, 70, 50) && !on(&tall, 110, 50));
266 }
267}
crates/model/src/comp/eval.rs+64-47
...@@ -3,7 +3,7 @@ use super::{ClsEntry, Comp, ExpressionModifier, MAX_EXPR_DEPTH, Node, ParamValue...@@ -3,7 +3,7 @@ use super::{ClsEntry, Comp, ExpressionModifier, MAX_EXPR_DEPTH, Node, ParamValue
3use crate::expr::ExprEngine;3use crate::expr::ExprEngine;
4use crate::spline::Gradient;4use crate::spline::Gradient;
5use std::cell::RefCell;5use std::cell::RefCell;
6use std::collections::HashMap;6use std::collections::{HashMap, HashSet};
77
8/// `(modifier address, output tag, time bits)`.8/// `(modifier address, output tag, time bits)`.
9type ModMemoKey = (usize, u8, u64);9type ModMemoKey = (usize, u8, u64);
...@@ -12,6 +12,13 @@ thread_local! {...@@ -12,6 +12,13 @@ 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.
16fn referenced_names(expr: &str) -> Option<HashSet<&str>> {
17 let names: HashSet<&str> =
18 expr.split(|c: char| !c.is_ascii_alphanumeric() && c != '_').filter(|t| !t.is_empty()).collect();
19 (!names.contains("_ENV")).then_some(names)
20}
21
15struct ModMemoScope(bool);22struct ModMemoScope(bool);
1623
17impl Drop for ModMemoScope {24impl Drop for ModMemoScope {
...@@ -363,8 +370,8 @@ impl Comp {...@@ -363,8 +370,8 @@ impl Comp {
363 }370 }
364 }371 }
365 }372 }
366 let (sp, spts, en) = self.collect_global_expr_env(time);373 let en = self.collect_node_env(trimmed, time);
367 if let Some(pt) = expr_engine.eval_point(trimmed, time, &sp, &spts, &en) {374 if let Some(pt) = expr_engine.eval_point(trimmed, time, &HashMap::new(), &HashMap::new(), &en) {
368 if pt[0].is_finite() && pt[1].is_finite() {375 if pt[0].is_finite() && pt[1].is_finite() {
369 return pt;376 return pt;
370 }377 }
...@@ -420,20 +427,18 @@ impl Comp {...@@ -420,20 +427,18 @@ impl Comp {
420 }427 }
421 }428 }
422 }429 }
423 let (sp, spts, en) = self.collect_global_expr_env(time);430 let en = self.collect_node_env(trimmed, time);
424 expr_engine.eval_number(trimmed, time, &sp, &spts, &en)431 expr_engine.eval_number(trimmed, time, &HashMap::new(), &HashMap::new(), &en)
425 }432 }
426433
427 fn collect_global_expr_env(434 /// `node name -> numeric inputs` for the nodes `expr` can reach; every other node is skipped.
428 &self,435 fn collect_node_env(&self, expr: &str, time: f64) -> HashMap<String, HashMap<String, f64>> {
429 time: f64,436 let names = referenced_names(expr);
430 ) -> (
431 HashMap<String, f64>,
432 HashMap<String, [f64; 2]>,
433 HashMap<String, HashMap<String, f64>>,
434 ) {
435 let mut env_nodes = HashMap::new();437 let mut env_nodes = HashMap::new();
436 for n in &self.nodes {438 for n in &self.nodes {
439 if !names.as_ref().is_none_or(|s| s.contains(n.name.as_str())) {
440 continue;
441 }
437 let mut m = HashMap::new();442 let mut m = HashMap::new();
438 for (k, b) in &n.inputs {443 for (k, b) in &n.inputs {
439 if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) {444 if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) {
...@@ -448,7 +453,7 @@ impl Comp {...@@ -448,7 +453,7 @@ impl Comp {
448 env_nodes.insert(n.name.clone(), m);453 env_nodes.insert(n.name.clone(), m);
449 }454 }
450 }455 }
451 (HashMap::new(), HashMap::new(), env_nodes)456 env_nodes
452 }457 }
453458
454 fn build_expr_mod_vars(459 fn build_expr_mod_vars(
...@@ -520,7 +525,7 @@ impl Comp {...@@ -520,7 +525,7 @@ impl Comp {
520 return Some(v);525 return Some(v);
521 }526 }
522 // Fallback to Lua SimpleExpression engine for Lua-specific formulas527 // Fallback to Lua SimpleExpression engine for Lua-specific formulas
523 let (_, _, en) = self.collect_global_expr_env(time);528 let en = self.collect_node_env(trimmed, time);
524 expr_engine.eval_number(trimmed, time, vars, pts, &en)529 expr_engine.eval_number(trimmed, time, vars, pts, &en)
525 }530 }
526531
...@@ -589,7 +594,7 @@ impl Comp {...@@ -589,7 +594,7 @@ impl Comp {
589 .and_then(|b| b.value.as_ref())594 .and_then(|b| b.value.as_ref())
590 .and_then(ParamValue::as_str)595 .and_then(ParamValue::as_str)
591 {596 {
592 let (_, _, en) = self.collect_global_expr_env(time);597 let en = self.collect_node_env(fp, time);
593 if let Some(pt) = expr_engine.eval_point(fp, time, &vars, &pts, &en) {598 if let Some(pt) = expr_engine.eval_point(fp, time, &vars, &pts, &en) {
594 return Some(pt);599 return Some(pt);
595 }600 }
...@@ -610,7 +615,7 @@ impl Comp {...@@ -610,7 +615,7 @@ impl Comp {
610 return default.to_owned();615 return default.to_owned();
611 };616 };
612 if let Some(expr) = &binding.expression {617 if let Some(expr) = &binding.expression {
613 let (sp, spts, en) = self.collect_expr_env(node, time);618 let (sp, spts, en) = self.collect_expr_env(node, expr, time);
614 if let Some(s) = expr_engine.eval_string(expr, time, &sp, &spts, &en) {619 if let Some(s) = expr_engine.eval_string(expr, time, &sp, &spts, &en) {
615 return s;620 return s;
616 }621 }
...@@ -689,15 +694,20 @@ impl Comp {...@@ -689,15 +694,20 @@ impl Comp {
689 fn collect_expr_env(694 fn collect_expr_env(
690 &self,695 &self,
691 node: &Node,696 node: &Node,
697 expr: &str,
692 time: f64,698 time: f64,
693 ) -> (699 ) -> (
694 HashMap<String, f64>,700 HashMap<String, f64>,
695 HashMap<String, [f64; 2]>,701 HashMap<String, [f64; 2]>,
696 HashMap<String, HashMap<String, f64>>,702 HashMap<String, HashMap<String, f64>>,
697 ) {703 ) {
704 let names = referenced_names(expr);
698 let mut self_params = HashMap::new();705 let mut self_params = HashMap::new();
699 let mut self_points = HashMap::new();706 let mut self_points = HashMap::new();
700 for (k, b) in &node.inputs {707 for (k, b) in &node.inputs {
708 if !names.as_ref().is_none_or(|s| s.contains(k.as_str())) {
709 continue;
710 }
701 if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) {711 if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) {
702 self_params.insert(k.clone(), v);712 self_params.insert(k.clone(), v);
703 } else if let Some(pt) = b.value.as_ref().and_then(ParamValue::as_point) {713 } else if let Some(pt) = b.value.as_ref().and_then(ParamValue::as_point) {
...@@ -716,23 +726,7 @@ impl Comp {...@@ -716,23 +726,7 @@ impl Comp {
716 }726 }
717 }727 }
718 }728 }
719 let mut env_nodes = HashMap::new();729 (self_params, self_points, self.collect_node_env(expr, time))
720 for n in &self.nodes {
721 let mut m = HashMap::new();
722 for (k, b) in &n.inputs {
723 if let Some(v) = b.value.as_ref().and_then(ParamValue::as_f64) {
724 m.insert(k.clone(), v);
725 } else if let Some(src) = &b.source_op {
726 if let Some(sp) = self.splines.get(src) {
727 m.insert(k.clone(), sp.eval(time));
728 }
729 }
730 }
731 if !m.is_empty() {
732 env_nodes.insert(n.name.clone(), m);
733 }
734 }
735 (self_params, self_points, env_nodes)
736 }730 }
737731
738 fn eval_expr_number(732 fn eval_expr_number(
...@@ -742,18 +736,7 @@ impl Comp {...@@ -742,18 +736,7 @@ impl Comp {
742 time: f64,736 time: f64,
743 expr_engine: &ExprEngine,737 expr_engine: &ExprEngine,
744 ) -> Option<f64> {738 ) -> Option<f64> {
745 let needs_nodes = expr.contains('.')739 let (sp, spts, en) = self.collect_expr_env(node, expr, time);
746 || expr.trim_start().starts_with(':')
747 || expr
748 .split(|c: char| !c.is_alphanumeric() && c != '_')
749 .any(|tok| !tok.is_empty() && node.inputs.contains_key(tok));
750 if !needs_nodes {
751 let empty_self = HashMap::new();
752 let empty_pts = HashMap::new();
753 let empty_env = HashMap::new();
754 return expr_engine.eval_number(expr, time, &empty_self, &empty_pts, &empty_env);
755 }
756 let (sp, spts, en) = self.collect_expr_env(node, time);
757 expr_engine.eval_number(expr, time, &sp, &spts, &en)740 expr_engine.eval_number(expr, time, &sp, &spts, &en)
758 }741 }
759742
...@@ -764,8 +747,42 @@ impl Comp {...@@ -764,8 +747,42 @@ impl Comp {
764 time: f64,747 time: f64,
765 expr_engine: &ExprEngine,748 expr_engine: &ExprEngine,
766 ) -> Option<[f64; 2]> {749 ) -> Option<[f64; 2]> {
767 let (sp, spts, en) = self.collect_expr_env(node, time);750 let (sp, spts, en) = self.collect_expr_env(node, expr, time);
768 expr_engine.eval_point(expr, time, &sp, &spts, &en)751 expr_engine.eval_point(expr, time, &sp, &spts, &en)
769 }752 }
770753
771}754}
755
756#[cfg(test)]
757mod tests {
758 use super::*;
759
760 #[test]
761 fn expressions_see_only_referenced_nodes_in_a_large_comp() {
762 let mut src = String::from("Composition { Tools = ordered() {\n");
763 for i in 0..100 {
764 src += &format!("N{i} = Transform {{ Inputs = {{ Size = Input {{ Value = {i}, }}, Angle = Input {{ Value = 1, }}, }}, }},\n");
765 }
766 src += r#"Probe = Transform { Inputs = {
767 Angle = Input { Value = 5, },
768 Size = Input { Expression = "N7.Size + N93.Size + Angle + time + N12.Missing", },
769 Width = Input { Expression = "time * 2", },
770 Height = Input { Expression = "_ENV['N' .. '42'].Size", },
771 }, }, } }"#;
772 let comp = Comp::from_fusion_str(&src).unwrap();
773 let probe = comp.node(comp.find_node("Probe").unwrap());
774 let engine = ExprEngine::new();
775
776 let names = comp.collect_node_env("N7.Size + N93.Size", 0.0);
777 assert_eq!(names.keys().map(String::as_str).collect::<HashSet<_>>(), HashSet::from(["N7", "N93"]));
778 assert_eq!(comp.collect_node_env("1", 0.0).len(), 0);
779
780 let start = std::time::Instant::now();
781 for _ in 0..200 {
782 assert_eq!(comp.eval_number(probe, "Size", 3.0, 0.0, &engine), 7.0 + 93.0 + 5.0 + 3.0);
783 }
784 assert_eq!(comp.eval_number(probe, "Width", 3.0, 0.0, &engine), 6.0);
785 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());
787 }
788}
crates/model/src/comp/save.rs+62-3
...@@ -4,7 +4,9 @@ use super::{BitDepth, Comp, InputBinding, Node, ParamValue, is_modifier_type};...@@ -4,7 +4,9 @@ use 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, VecDeque};
7use std::io::Write;
7use std::path::{Path, PathBuf};8use std::path::{Path, PathBuf};
9use std::sync::atomic::{AtomicU64, Ordering};
810
9impl Comp {11impl Comp {
10 /// Synchronizes current comp state (metadata, node positions/bypass/inputs, spline edits,12 /// Synchronizes current comp state (metadata, node positions/bypass/inputs, spline edits,
...@@ -221,9 +223,18 @@ impl Comp {...@@ -221,9 +223,18 @@ impl Comp {
221223
222 /// Atomically saves this composition to `path`.224 /// Atomically saves this composition to `path`.
223 /// If `path` already exists, backs up the original bytes to225 /// If `path` already exists, backs up the original bytes to
224 /// `<temp_dir>/fission-backups/<stem>_<unix_millis>.comp.bak` and returns `Ok(Some(backup_path))`.226 /// `<temp_dir>/fission-backups/<stem>_<unix_millis>_<pid>_<seq>.comp.bak` and returns `Ok(Some(backup_path))`.
227 /// A symlink at `path` is followed, so the link itself survives the save.
225 pub fn save_to_file(&self, path: impl AsRef<Path>) -> Result<Option<PathBuf>, std::io::Error> {228 pub fn save_to_file(&self, path: impl AsRef<Path>) -> Result<Option<PathBuf>, std::io::Error> {
229 static BACKUP_SEQ: AtomicU64 = AtomicU64::new(0);
230
226 let path = path.as_ref();231 let path = path.as_ref();
232 let target = if std::fs::symlink_metadata(path).is_ok_and(|m| m.file_type().is_symlink()) {
233 std::fs::canonicalize(path)?
234 } else {
235 path.to_path_buf()
236 };
237 let path = target.as_path();
227 let stem = path238 let stem = path
228 .file_stem()239 .file_stem()
229 .and_then(|s| s.to_str())240 .and_then(|s| s.to_str())
...@@ -237,7 +248,8 @@ impl Comp {...@@ -237,7 +248,8 @@ impl Comp {
237 .duration_since(std::time::UNIX_EPOCH)248 .duration_since(std::time::UNIX_EPOCH)
238 .map(|d| d.as_millis())249 .map(|d| d.as_millis())
239 .unwrap_or(0);250 .unwrap_or(0);
240 let backup_file = backup_dir.join(format!("{stem}_{unix_millis}.comp.bak"));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()));
241 std::fs::copy(path, &backup_file)?;253 std::fs::copy(path, &backup_file)?;
242 Some(backup_file)254 Some(backup_file)
243 } else {255 } else {
...@@ -258,7 +270,11 @@ impl Comp {...@@ -258,7 +270,11 @@ impl Comp {
258 let tmp_path = parent.join(format!(".{stem}.{pid}.{nanos}.tmp"));270 let tmp_path = parent.join(format!(".{stem}.{pid}.{nanos}.tmp"));
259271
260 let serialized = self.to_fusion_string();272 let serialized = self.to_fusion_string();
261 if let Err(e) = std::fs::write(&tmp_path, serialized.as_bytes()) {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 });
277 if let Err(e) = written {
262 let _ = std::fs::remove_file(&tmp_path);278 let _ = std::fs::remove_file(&tmp_path);
263 return Err(e);279 return Err(e);
264 }280 }
...@@ -630,3 +646,46 @@ fn sync_spline_table(spline_name: &str, spline: &BezierSpline, tbl: &mut LuaTabl...@@ -630,3 +646,46 @@ fn sync_spline_table(spline_name: &str, spline: &BezierSpline, tbl: &mut LuaTabl
630 }646 }
631 }647 }
632}648}
649
650#[cfg(test)]
651mod tests {
652 use super::*;
653
654 fn scratch(name: &str) -> PathBuf {
655 let dir = std::env::temp_dir().join(format!("fission_save_{name}_{}", std::process::id()));
656 let _ = std::fs::remove_dir_all(&dir);
657 std::fs::create_dir_all(&dir).unwrap();
658 dir
659 }
660
661 #[test]
662 fn rapid_saves_keep_distinct_backups() {
663 let dir = scratch("backups");
664 let path = dir.join("rapid_backup_test.comp");
665 let comp = Comp::from_fusion_str("Composition { Tools = ordered() { }, }").unwrap();
666 comp.save_to_file(&path).unwrap();
667 let backups: std::collections::HashSet<_> =
668 (0..20).map(|_| comp.save_to_file(&path).unwrap().expect("existing file is backed up")).collect();
669 assert_eq!(backups.len(), 20);
670 assert!(backups.iter().all(|b| b.exists()));
671 for b in backups {
672 let _ = std::fs::remove_file(b);
673 }
674 }
675
676 #[cfg(unix)]
677 #[test]
678 fn saving_through_a_symlink_keeps_the_link() {
679 let dir = scratch("symlink");
680 let real = dir.join("real.comp");
681 let link = dir.join("link.comp");
682 std::fs::write(&real, "old").unwrap();
683 std::os::unix::fs::symlink(&real, &link).unwrap();
684 let comp = Comp::from_fusion_str("Composition { Tools = ordered() { }, }").unwrap();
685 let backup = comp.save_to_file(&link).unwrap().unwrap();
686 assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
687 assert_eq!(std::fs::read_to_string(&real).unwrap(), comp.to_fusion_string());
688 assert_eq!(std::fs::read_to_string(&backup).unwrap(), "old");
689 let _ = std::fs::remove_file(backup);
690 }
691}
crates/model/src/edit/history.rs+64-12
...@@ -92,10 +92,15 @@ impl CompHistory {...@@ -92,10 +92,15 @@ impl CompHistory {
9292
93 /// Records the current state of `comp` as the clean saved point.93 /// Records the current state of `comp` as the clean saved point.
94 pub fn mark_saved(&mut self, comp: &Comp) {94 pub fn mark_saved(&mut self, comp: &Comp) {
95 self.mark_saved_at(comp.revision);
96 }
97
98 /// Records the state at `comp_revision` as the clean saved point.
99 pub fn mark_saved_at(&mut self, comp_revision: u64) {
95 // Edits after a save must never coalesce into the saved undo entry.100 // Edits after a save must never coalesce into the saved undo entry.
96 self.break_coalescing();101 self.break_coalescing();
97 self.saved_undo_depth = Some(self.undo_stack.len());102 self.saved_undo_depth = Some(self.undo_stack.len());
98 self.saved_revision = Some(comp.revision);103 self.saved_revision = Some(comp_revision);
99 }104 }
100105
101 pub fn saved_revision(&self) -> Option<u64> {106 pub fn saved_revision(&self) -> Option<u64> {
...@@ -104,17 +109,19 @@ impl CompHistory {...@@ -104,17 +109,19 @@ impl CompHistory {
104109
105 /// Returns `true` if `comp` has unsaved modifications relative to the last [`Self::mark_saved`].110 /// Returns `true` if `comp` has unsaved modifications relative to the last [`Self::mark_saved`].
106 pub fn is_dirty(&self, comp: &Comp) -> bool {111 pub fn is_dirty(&self, comp: &Comp) -> bool {
107 match self.saved_undo_depth {112 self.is_dirty_for(comp.revision)
108 Some(depth) if depth == self.undo_stack.len() => {113 }
109 // If an edit was pushed via coalescing or outside history after mark_saved,114
110 // check whether we're still at the saved depth without an active modified group.115 /// Returns `true` if a comp at `comp_revision` differs from the last [`Self::mark_saved_at`],
111 if let Some((_, ref snap)) = self.active_group {116 /// including mutations that never went through the history.
112 comp.revision != snap.revision117 pub fn is_dirty_for(&self, comp_revision: u64) -> bool {
113 } else {118 self.saved_revision != Some(comp_revision)
114 false119 }
115 }120
116 }121 /// Undo/redo bump `comp.revision` even when they land back on the saved state.
117 _ => self.saved_revision != Some(comp.revision),122 fn rebase_saved_revision(&mut self, comp_revision: u64) {
123 if self.saved_undo_depth == Some(self.undo_stack.len()) {
124 self.saved_revision = Some(comp_revision);
118 }125 }
119 }126 }
120127
...@@ -212,10 +219,14 @@ impl CompHistory {...@@ -212,10 +219,14 @@ impl CompHistory {
212 return false;219 return false;
213 };220 };
214 let prev_rev = comp.revision;221 let prev_rev = comp.revision;
222 let was_clean = self.saved_revision == Some(snapshot.revision);
215 restore_snapshot(comp, snapshot);223 restore_snapshot(comp, snapshot);
216 if comp.revision != prev_rev {224 if comp.revision != prev_rev {
217 comp.revision = prev_rev.max(comp.revision) + 1;225 comp.revision = prev_rev.max(comp.revision) + 1;
218 }226 }
227 if was_clean {
228 self.saved_revision = Some(comp.revision);
229 }
219 true230 true
220 }231 }
221232
...@@ -252,6 +263,7 @@ impl CompHistory {...@@ -252,6 +263,7 @@ impl CompHistory {
252 self.redo_stack.push(redo_entry);263 self.redo_stack.push(redo_entry);
253 restore_snapshot(comp, entry.snapshot);264 restore_snapshot(comp, entry.snapshot);
254 comp.revision = prev_rev.max(comp.revision) + 1;265 comp.revision = prev_rev.max(comp.revision) + 1;
266 self.rebase_saved_revision(comp.revision);
255 true267 true
256 }268 }
257269
...@@ -270,6 +282,7 @@ impl CompHistory {...@@ -270,6 +282,7 @@ impl CompHistory {
270 self.undo_stack.push_back(undo_entry);282 self.undo_stack.push_back(undo_entry);
271 restore_snapshot(comp, entry.snapshot);283 restore_snapshot(comp, entry.snapshot);
272 comp.revision = prev_rev.max(comp.revision) + 1;284 comp.revision = prev_rev.max(comp.revision) + 1;
285 self.rebase_saved_revision(comp.revision);
273 true286 true
274 }287 }
275288
...@@ -396,6 +409,45 @@ mod tests {...@@ -396,6 +409,45 @@ mod tests {
396 assert!(history.is_dirty(&comp));409 assert!(history.is_dirty(&comp));
397 }410 }
398411
412 #[test]
413 fn dirty_tracking_sees_edits_made_at_the_saved_depth() {
414 let mut history = CompHistory::new();
415 assert!(history.is_dirty_for(0));
416 history.mark_saved_at(7);
417 assert!(!history.is_dirty_for(7));
418 assert!(history.is_dirty_for(8));
419
420 let mut comp = sample_comp();
421 let bg = comp.find_node("BG1").unwrap();
422 history.mark_saved(&comp);
423 assert_eq!(history.saved_revision(), Some(comp.revision));
424
425 // Mutated without a history entry: undo depth still equals the saved depth.
426 comp.set_node_pos(bg, [5.0, 5.0]);
427 assert_eq!(history.undo_len(), 0);
428 assert!(history.is_dirty(&comp));
429 assert!(history.is_dirty_for(comp.revision));
430
431 // Undo/redo landing back on the saved depth is clean again.
432 history.mark_saved(&comp);
433 history.push_snapshot(&comp, "Move");
434 comp.set_node_pos(bg, [6.0, 6.0]);
435 assert!(history.is_dirty(&comp));
436 assert!(history.undo(&mut comp));
437 assert!(!history.is_dirty(&comp));
438 assert!(history.redo(&mut comp));
439 assert!(history.is_dirty(&comp));
440 assert!(history.undo(&mut comp));
441 assert!(!history.is_dirty(&comp));
442
443 // A cancelled group restores a clean comp to clean.
444 history.begin_group(&comp, "Group");
445 comp.set_node_pos(bg, [7.0, 7.0]);
446 assert!(history.is_dirty(&comp));
447 assert!(history.cancel_group(&mut comp));
448 assert!(!history.is_dirty(&comp));
449 }
450
399 #[test]451 #[test]
400 fn undo_and_redo_keep_the_live_file_identity() {452 fn undo_and_redo_keep_the_live_file_identity() {
401 let mut comp = sample_comp();453 let mut comp = sample_comp();
crates/model/src/expr.rs+4-7
...@@ -216,18 +216,15 @@ impl ExprEngine {...@@ -216,18 +216,15 @@ impl ExprEngine {
216 pt.set(2, p[1])?;216 pt.set(2, p[1])?;
217 env.set(k.as_str(), pt)?;217 env.set(k.as_str(), pt)?;
218 }218 }
219 // Missing node fields default to 0 so expressions don't nil-crash.
220 let zero_mt = self.lua.create_table()?;
221 zero_mt.set("__index", self.lua.create_function(|_, _args: MultiValue| Ok(0.0_f64))?)?;
219 for (node_name, params) in env_nodes {222 for (node_name, params) in env_nodes {
220 let nt = self.lua.create_table()?;223 let nt = self.lua.create_table()?;
221 for (pk, pv) in params {224 for (pk, pv) in params {
222 nt.set(pk.as_str(), *pv)?;225 nt.set(pk.as_str(), *pv)?;
223 }226 }
224 // Also default missing fields to 0 so expressions don't nil-crash227 nt.set_metatable(Some(zero_mt.clone()));
225 let nmt = self.lua.create_table()?;
226 nmt.set(
227 "__index",
228 self.lua.create_function(|_, _args: MultiValue| Ok(0.0_f64))?,
229 )?;
230 nt.set_metatable(Some(nmt));
231 env.set(node_name.as_str(), nt)?;228 env.set(node_name.as_str(), nt)?;
232 }229 }
233 Ok(env)230 Ok(env)