authoravatarclover caruso<git@paperclover.net>2026-11-30 20:21:08-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-30 20:40:12-08:00
log0e7a2c62afd19b813b5077fad79c34ab0389ebe4
treec53d6df4978ae88f4f9111ad1c2514faf23313a4
parente32308b6b4a0302ade600bb0ee21a260aa4494ed
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Fix model Lua sandbox, expression cycles, clamp panics, and edit/history/group P0s

- expr: sandbox Lua (math/string/table only, loaders nil, instruction hook, memory limit) - comp: thread depth through eval_number/eval_point to stop expression cycles; panic-free clamp; keep explicit FrameFormat size; per-load revision range; sync_to_raw_ast recurses into Group/Macro tools and writes group wiring back - spline: panic-free handle clamp on unsorted keys - edit: mark_saved breaks coalescing; undo/redo/cancel keep live path+name; delete_nodes cascades groups and prunes expression modifiers; clipboard finds nested modifiers and never links to group-private tools; duplicate_nodes is copy+paste; scoped rename; formula/property-aware ident rename; keyframe handles shift and last-keyframe delete keeps the static value Assisted-by: claude-sonnet-5.5

4 files changed, 1135 insertions(+), 418 deletions(-)

crates/model/src/comp.rs+418-134
......@@ -3,8 +3,9 @@
33use crate::expr::ExprEngine;
44use crate::lua_value::{LuaKey, LuaTable, LuaValue, ParseError, parse_lua};
55use crate::spline::{BezierSpline, Gradient, PolyPath, read_vec2};
6use std::collections::{HashMap, HashSet};
6use std::collections::{HashMap, HashSet, VecDeque};
77use std::path::{Path, PathBuf};
8use std::sync::atomic::{AtomicU64, Ordering};
89
910/// Fusion working color bit depth (`DepthFull` / `ChangeDepth.Depth` / generator `Depth`).
1011/// Fusion enum: `0 = Default`, `1 = int8`, `2 = int16`, `3 = float16`, `4 = float32`.
......@@ -450,7 +451,14 @@ const MODIFIER_TYPES: &[&str] = &[
450451 "GradientModifier",
451452];
452453
453fn is_modifier_type(kind: &str) -> bool {
454/// Each loaded comp gets its own revision range so frame-cache keys never collide across reloads.
455static NEXT_COMP_REVISION: AtomicU64 = AtomicU64::new(1);
456const REVISION_STRIDE: u64 = 1 << 32;
457
458/// Max hops through chained expression modifiers / `Node.Param` references before evaluation gives up.
459const MAX_EXPR_DEPTH: usize = 16;
460
461pub(crate) fn is_modifier_type(kind: &str) -> bool {
454462 MODIFIER_TYPES.contains(&kind) || kind.ends_with("Spline") || kind.ends_with("Modifier")
455463}
456464
......@@ -492,6 +500,7 @@ impl Comp {
492500 let mut height = 1080u32;
493501 let mut fps = 30.0_f64;
494502 let mut depth_full = BitDepth::Int8;
503 let mut explicit_size = false;
495504 if let Some(ff) = root
496505 .get_table("Prefs")
497506 .and_then(|p| p.get_table("Comp"))
......@@ -499,9 +508,11 @@ impl Comp {
499508 {
500509 if let Some(w) = ff.get_f64("Width") {
501510 width = w.round().max(1.0) as u32;
511 explicit_size = true;
502512 }
503513 if let Some(h) = ff.get_f64("Height") {
504514 height = h.round().max(1.0) as u32;
515 explicit_size = true;
505516 }
506517 if let Some(r) = ff.get_f64("Rate") {
507518 if r > 0.0 {
......@@ -697,7 +708,7 @@ impl Comp {
697708 }
698709
699710 // Infer comp dimensions from first Background/TextPlus if Prefs omitted Width/Height
700 if width == 1920 && height == 1080 {
711 if !explicit_size {
701712 for n in &nodes {
702713 if matches!(n.kind.as_str(), "Background" | "TextPlus" | "FastNoise") {
703714 if let (Some(w), Some(h)) = (n.static_number("Width"), n.static_number("Height")) {
......@@ -735,7 +746,7 @@ impl Comp {
735746 shakes,
736747 expression_modifiers,
737748 raw_root: Some(root.clone()),
738 revision: 1,
749 revision: NEXT_COMP_REVISION.fetch_add(REVISION_STRIDE, Ordering::Relaxed),
739750 })
740751 }
741752
......@@ -884,20 +895,27 @@ impl GridMesh {
884895 }
885896}
886897
887fn find_raw_tool_in_tools<'a>(tools: &'a LuaTable, target: &str) -> Option<&'a LuaTable> {
898/// Finds a tool/modifier by name in `tools` or any nested `Tools` table (Groups, Macros, curve nodes).
899pub(crate) fn find_raw_tool<'a>(tools: &'a LuaTable, target: &str) -> Option<&'a LuaTable> {
888900 if let Some(t) = tools.get_table(target) {
889901 return Some(t);
890902 }
891 for (_, v) in &tools.entries {
892 if let Some(tbl) = v.as_table() {
893 if matches!(tbl.tag.as_deref(), Some("GroupOperator" | "MacroOperator")) {
894 if let Some(sub) = tbl.get_table("Tools").and_then(|st| find_raw_tool_in_tools(st, target)) {
895 return Some(sub);
896 }
897 }
898 }
903 tools
904 .entries
905 .iter()
906 .filter_map(|(_, v)| v.as_table()?.get_table("Tools"))
907 .find_map(|inner| find_raw_tool(inner, target))
908}
909
910pub(crate) fn find_raw_tool_mut<'a>(tools: &'a mut LuaTable, target: &str) -> Option<&'a mut LuaTable> {
911 if tools.get_table(target).is_some() {
912 return tools.get_table_mut(target);
899913 }
900 None
914 tools
915 .entries
916 .iter_mut()
917 .filter_map(|(_, v)| v.as_table_mut()?.get_table_mut("Tools"))
918 .find_map(|inner| find_raw_tool_mut(inner, target))
901919}
902920
903921impl Comp {
......@@ -905,7 +923,7 @@ impl Comp {
905923 pub fn eval_grid_mesh(&self, node: &Node, key: &str, time: f64) -> Option<GridMesh> {
906924 if let Some(spline_name) = node.inputs.get(key).and_then(|b| b.source_op.as_deref()) {
907925 let tools = self.raw_root.as_ref()?.get_table("Tools")?;
908 let stbl = find_raw_tool_in_tools(tools, spline_name)?;
926 let stbl = find_raw_tool(tools, spline_name)?;
909927 let kfs_tbl = stbl.get_table("KeyFrames")?;
910928 let mut kfs: Vec<(f64, GridMesh)> = Vec::new();
911929 for (k, v) in &kfs_tbl.entries {
......@@ -1027,6 +1045,21 @@ impl Comp {
10271045 default: f64,
10281046 expr_engine: &ExprEngine,
10291047 ) -> f64 {
1048 self.eval_number_at(node, param, time, default, expr_engine, 0)
1049 }
1050
1051 fn eval_number_at(
1052 &self,
1053 node: &Node,
1054 param: &str,
1055 time: f64,
1056 default: f64,
1057 expr_engine: &ExprEngine,
1058 depth: usize,
1059 ) -> f64 {
1060 if depth >= MAX_EXPR_DEPTH {
1061 return default;
1062 }
10301063 let Some(binding) = node.inputs.get(param) else {
10311064 return default;
10321065 };
......@@ -1054,7 +1087,7 @@ impl Comp {
10541087 binding.source_output.as_deref(),
10551088 time,
10561089 expr_engine,
1057 0,
1090 depth + 1,
10581091 ) {
10591092 if v.is_finite() {
10601093 return v;
......@@ -1078,6 +1111,21 @@ impl Comp {
10781111 default: [f64; 2],
10791112 expr_engine: &ExprEngine,
10801113 ) -> [f64; 2] {
1114 self.eval_point_at(node, param, time, default, expr_engine, 0)
1115 }
1116
1117 fn eval_point_at(
1118 &self,
1119 node: &Node,
1120 param: &str,
1121 time: f64,
1122 default: [f64; 2],
1123 expr_engine: &ExprEngine,
1124 depth: usize,
1125 ) -> [f64; 2] {
1126 if depth >= MAX_EXPR_DEPTH {
1127 return default;
1128 }
10811129 let Some(binding) = node.inputs.get(param) else {
10821130 return default;
10831131 };
......@@ -1102,7 +1150,7 @@ impl Comp {
11021150 return [x, y];
11031151 }
11041152 if let Some(em) = self.expression_modifiers.get(src) {
1105 if let Some(pt) = self.eval_expr_mod_point(em, time, expr_engine, 0) {
1153 if let Some(pt) = self.eval_expr_mod_point(em, time, expr_engine, depth + 1) {
11061154 if pt[0].is_finite() && pt[1].is_finite() {
11071155 return pt;
11081156 }
......@@ -1199,13 +1247,13 @@ impl Comp {
11991247 time: f64,
12001248 default: f64,
12011249 expr_engine: &ExprEngine,
1202 depth: u8,
1250 depth: usize,
12031251 ) -> f64 {
12041252 let Some(b) = keys.iter().find_map(|k| em.inputs.get(*k)) else {
12051253 return default;
12061254 };
12071255 if let Some(expr) = &b.expression {
1208 if let Some(v) = self.eval_modifier_inline_number(expr, time, expr_engine) {
1256 if let Some(v) = self.eval_modifier_inline_number(expr, time, expr_engine, depth) {
12091257 if v.is_finite() {
12101258 return v;
12111259 }
......@@ -1222,7 +1270,7 @@ impl Comp {
12221270 };
12231271 return self.eval_shake_axis(sh, axis, time, expr_engine);
12241272 }
1225 if depth < 8 {
1273 if depth < MAX_EXPR_DEPTH {
12261274 if let Some(sub) = self.expression_modifiers.get(src) {
12271275 if let Some(v) = self.eval_expr_mod_number(
12281276 sub,
......@@ -1248,7 +1296,7 @@ impl Comp {
12481296 time: f64,
12491297 default: [f64; 2],
12501298 expr_engine: &ExprEngine,
1251 depth: u8,
1299 depth: usize,
12521300 ) -> [f64; 2] {
12531301 let Some(b) = keys.iter().find_map(|k| em.inputs.get(*k)) else {
12541302 return default;
......@@ -1259,7 +1307,7 @@ impl Comp {
12591307 if let Some((node_name, param_name)) = trimmed.split_once('.') {
12601308 if !param_name.contains('.') && !param_name.contains(' ') {
12611309 if let Some(nid) = self.find_node(node_name.trim()) {
1262 return self.eval_point(self.node(nid), param_name.trim(), time, default, expr_engine);
1310 return self.eval_point_at(self.node(nid), param_name.trim(), time, default, expr_engine, depth + 1);
12631311 }
12641312 }
12651313 }
......@@ -1285,7 +1333,7 @@ impl Comp {
12851333 let y = self.eval_shake_axis(sh, 1, time, expr_engine);
12861334 return [x, y];
12871335 }
1288 if depth < 8 {
1336 if depth < MAX_EXPR_DEPTH {
12891337 if let Some(sub) = self.expression_modifiers.get(src) {
12901338 if let Some(pt) = self.eval_expr_mod_point(sub, time, expr_engine, depth + 1) {
12911339 if pt[0].is_finite() && pt[1].is_finite() {
......@@ -1303,12 +1351,20 @@ impl Comp {
13031351 expr: &str,
13041352 time: f64,
13051353 expr_engine: &ExprEngine,
1354 depth: usize,
13061355 ) -> Option<f64> {
13071356 let trimmed = expr.trim();
13081357 if let Some((node_name, param_name)) = trimmed.split_once('.') {
13091358 if !param_name.contains('.') && !param_name.contains(' ') && !param_name.contains('(') {
13101359 if let Some(nid) = self.find_node(node_name.trim()) {
1311 return Some(self.eval_number(self.node(nid), param_name.trim(), time, 0.0, expr_engine));
1360 return Some(self.eval_number_at(
1361 self.node(nid),
1362 param_name.trim(),
1363 time,
1364 0.0,
1365 expr_engine,
1366 depth + 1,
1367 ));
13121368 }
13131369 }
13141370 }
......@@ -1348,7 +1404,7 @@ impl Comp {
13481404 em: &ExpressionModifier,
13491405 time: f64,
13501406 expr_engine: &ExprEngine,
1351 depth: u8,
1407 depth: usize,
13521408 ) -> (HashMap<String, f64>, HashMap<String, [f64; 2]>) {
13531409 let mut vars = HashMap::with_capacity(32);
13541410 let mut pts = HashMap::with_capacity(18);
......@@ -1422,9 +1478,9 @@ impl Comp {
14221478 source_output: Option<&str>,
14231479 time: f64,
14241480 expr_engine: &ExprEngine,
1425 depth: u8,
1481 depth: usize,
14261482 ) -> Option<f64> {
1427 if depth >= 8 {
1483 if depth >= MAX_EXPR_DEPTH {
14281484 return None;
14291485 }
14301486 let (vars, pts) = self.build_expr_mod_vars(em, time, expr_engine, depth);
......@@ -1446,9 +1502,9 @@ impl Comp {
14461502 em: &ExpressionModifier,
14471503 time: f64,
14481504 expr_engine: &ExprEngine,
1449 depth: u8,
1505 depth: usize,
14501506 ) -> Option<[f64; 2]> {
1451 if depth >= 8 {
1507 if depth >= MAX_EXPR_DEPTH {
14521508 return None;
14531509 }
14541510 let (vars, pts) = self.build_expr_mod_vars(em, time, expr_engine, depth);
......@@ -1773,134 +1829,144 @@ impl Comp {
17731829 // Sync Tools
17741830 let tools = ensure_table_mut(&mut root, "Tools", Some("ordered"));
17751831
1776 // Remove top-level flow nodes that were deleted from `self.nodes`,
1777 // while NEVER removing modifiers or any node still present in `self.nodes`.
1778 let live_flow_names: HashSet<&str> = self
1779 .nodes
1780 .iter()
1781 .filter(|n| !n.internal)
1782 .map(|n| n.name.as_str())
1783 .collect();
1784 tools.entries.retain(|(k, v)| {
1785 let LuaKey::Str(name) = k else { return true };
1786 let Some(tbl) = v.as_table() else { return true };
1787 let kind = tbl.tag.as_deref().unwrap_or("Unknown");
1788 if is_modifier_type(kind) {
1789 true
1832 for node in self.nodes.iter().filter(|n| !n.internal) {
1833 if tools.get_table(&node.name).is_some() {
1834 continue;
1835 }
1836 let mut new_tbl = if node.raw.tag.is_some() {
1837 node.raw.clone()
17901838 } else {
1791 live_flow_names.contains(name.as_str())
1839 LuaTable { tag: None, entries: Vec::new() }
1840 };
1841 if new_tbl.tag.is_none() {
1842 new_tbl.tag = Some(node.kind.clone());
17921843 }
1793 });
1844 tools.set(LuaKey::Str(node.name.clone()), LuaValue::Table(new_tbl));
1845 }
17941846
1795 // Sync each visible (non-internal) flow node
1847 let mut pool: HashMap<(bool, String), VecDeque<&Node>> = HashMap::new();
1848 let mut instance_defaults: HashMap<(&str, &str), ParamValue> = HashMap::new();
17961849 for node in &self.nodes {
1797 if node.internal {
1850 pool.entry((node.internal, node.name.clone())).or_default().push_back(node);
1851 if !is_group_kind(&node.kind) {
17981852 continue;
17991853 }
1800 if tools.get_table(&node.name).is_none() {
1801 let mut new_tbl = if node.raw.tag.is_some() {
1802 node.raw.clone()
1803 } else {
1804 LuaTable {
1805 tag: Some(node.kind.clone()),
1806 entries: Vec::new(),
1807 }
1808 };
1809 if new_tbl.tag.is_none() {
1810 new_tbl.tag = Some(node.kind.clone());
1854 for (inner_op, inner_port, default) in instance_inputs(&node.raw) {
1855 if let Some(d) = default {
1856 instance_defaults.insert((inner_op, inner_port), d);
18111857 }
1812 tools.set(LuaKey::Str(node.name.clone()), LuaValue::Table(new_tbl));
1813 }
1814
1815 let Some(tool_tbl) = tools.get_table_mut(&node.name) else {
1816 continue;
1817 };
1818
1819 // ViewInfo.Pos
1820 if let Some(vi) = tool_tbl.get_table_mut("ViewInfo") {
1821 let pos_changed = vi
1822 .get_table("Pos")
1823 .and_then(read_vec2)
1824 .is_none_or(|[x, y]| {
1825 (x as f32 - node.pos[0]).abs() > 1e-4
1826 || (y as f32 - node.pos[1]).abs() > 1e-4
1827 });
1828 if pos_changed {
1829 vi.set(
1830 LuaKey::Str("Pos".to_owned()),
1831 vec2_lua(node.pos[0] as f64, node.pos[1] as f64),
1832 );
1833 }
1834 } else if node.pos[0] != 0.0 || node.pos[1] != 0.0 {
1835 let mut vi = LuaTable {
1836 tag: Some("OperatorInfo".to_owned()),
1837 entries: Vec::new(),
1838 };
1839 vi.set(
1840 LuaKey::Str("Pos".to_owned()),
1841 vec2_lua(node.pos[0] as f64, node.pos[1] as f64),
1842 );
1843 tool_tbl.set(LuaKey::Str("ViewInfo".to_owned()), LuaValue::Table(vi));
1844 }
1845
1846 // PassThrough
1847 if node.bypassed {
1848 tool_tbl.set(LuaKey::Str("PassThrough".to_owned()), LuaValue::Bool(true));
1849 } else if tool_tbl.get("PassThrough").is_some() {
1850 tool_tbl.remove(&LuaKey::Str("PassThrough".to_owned()));
1851 }
1852
1853 // Inputs (skip MacroOperator / GroupOperator so InstanceInput wiring stays intact)
1854 if !matches!(node.kind.as_str(), "MacroOperator" | "GroupOperator") {
1855 let master_inputs = node
1856 .raw
1857 .get_str("SourceOp")
1858 .and_then(|m| self.find_node(m))
1859 .map(|mid| &self.nodes[mid.0].inputs);
1860 sync_node_inputs(node, master_inputs, tool_tbl);
18611858 }
18621859 }
1860 self.sync_tools_level(tools, false, &mut pool, &instance_defaults);
18631861
18641862 // Sync BezierSpline edits (only touch splines that actually differ from the raw AST)
18651863 let mut spline_names: Vec<&String> = self.splines.keys().collect();
18661864 spline_names.sort();
18671865 for spline_name in spline_names {
18681866 let spline = &self.splines[spline_name];
1869 if let Some(tbl) = tools.get_table_mut(spline_name) {
1867 if let Some(tbl) = find_raw_tool_mut(tools, spline_name) {
18701868 sync_spline_table(spline_name, spline, tbl);
18711869 continue;
18721870 }
1873 // Check nested `Tools` (e.g. ColorCurves / HueCurves LUTBezier)
1874 let mut found_nested = false;
1875 for (_, v) in &mut tools.entries {
1876 if let Some(node_tbl) = v.as_table_mut() {
1877 if let Some(inner_tools) = node_tbl.get_table_mut("Tools") {
1878 if let Some(inner_sp) = inner_tools.get_table_mut(spline_name) {
1879 sync_spline_table(spline_name, spline, inner_sp);
1880 found_nested = true;
1881 break;
1882 }
1883 }
1871 let mut sp_tbl = LuaTable {
1872 tag: Some("BezierSpline".to_owned()),
1873 entries: Vec::new(),
1874 };
1875 sp_tbl.set(
1876 LuaKey::Str("SplineColor".to_owned()),
1877 spline_color_lua(spline.color),
1878 );
1879 sp_tbl.set(
1880 LuaKey::Str("KeyFrames".to_owned()),
1881 LuaValue::Table(build_keyframes_table(spline)),
1882 );
1883 tools.set(LuaKey::Str(spline_name.clone()), LuaValue::Table(sp_tbl));
1884 }
1885
1886 root
1887 }
1888
1889 /// Syncs one `Tools` table level: drops deleted flow nodes (never modifiers), then syncs each
1890 /// surviving node and recurses into Group/Macro operators' private `Tools`.
1891 fn sync_tools_level<'a>(
1892 &'a self,
1893 tools: &mut LuaTable,
1894 internal: bool,
1895 pool: &mut HashMap<(bool, String), VecDeque<&'a Node>>,
1896 instance_defaults: &HashMap<(&str, &str), ParamValue>,
1897 ) {
1898 tools.entries.retain(|(k, v)| {
1899 let (LuaKey::Str(name), Some(tbl)) = (k, v.as_table()) else { return true };
1900 is_modifier_type(tbl.tag.as_deref().unwrap_or("Unknown"))
1901 || pool.get(&(internal, name.clone())).is_some_and(|q| !q.is_empty())
1902 });
1903
1904 for (k, v) in &mut tools.entries {
1905 let (LuaKey::Str(name), Some(tool_tbl)) = (&*k, v.as_table_mut()) else { continue };
1906 if is_modifier_type(tool_tbl.tag.as_deref().unwrap_or("Unknown")) {
1907 continue;
1908 }
1909 let Some(node) = pool.get_mut(&(internal, name.clone())).and_then(VecDeque::pop_front) else {
1910 continue;
1911 };
1912 self.sync_node_tool(node, tool_tbl, instance_defaults);
1913 if is_group_kind(&node.kind) {
1914 if let Some(inner) = tool_tbl.get_table_mut("Tools") {
1915 self.sync_tools_level(inner, true, pool, instance_defaults);
18841916 }
1917 sync_group_wiring(node, tool_tbl);
18851918 }
1886 if !found_nested {
1887 let mut sp_tbl = LuaTable {
1888 tag: Some("BezierSpline".to_owned()),
1889 entries: Vec::new(),
1890 };
1891 sp_tbl.set(
1892 LuaKey::Str("SplineColor".to_owned()),
1893 spline_color_lua(spline.color),
1894 );
1895 sp_tbl.set(
1896 LuaKey::Str("KeyFrames".to_owned()),
1897 LuaValue::Table(build_keyframes_table(spline)),
1919 }
1920 }
1921
1922 fn sync_node_tool(
1923 &self,
1924 node: &Node,
1925 tool_tbl: &mut LuaTable,
1926 instance_defaults: &HashMap<(&str, &str), ParamValue>,
1927 ) {
1928 // ViewInfo.Pos
1929 if let Some(vi) = tool_tbl.get_table_mut("ViewInfo") {
1930 let pos_changed = vi
1931 .get_table("Pos")
1932 .and_then(read_vec2)
1933 .is_none_or(|[x, y]| {
1934 (x as f32 - node.pos[0]).abs() > 1e-4 || (y as f32 - node.pos[1]).abs() > 1e-4
1935 });
1936 if pos_changed {
1937 vi.set(
1938 LuaKey::Str("Pos".to_owned()),
1939 vec2_lua(node.pos[0] as f64, node.pos[1] as f64),
18981940 );
1899 tools.set(LuaKey::Str(spline_name.clone()), LuaValue::Table(sp_tbl));
19001941 }
1942 } else if node.pos[0] != 0.0 || node.pos[1] != 0.0 {
1943 let mut vi = LuaTable {
1944 tag: Some("OperatorInfo".to_owned()),
1945 entries: Vec::new(),
1946 };
1947 vi.set(
1948 LuaKey::Str("Pos".to_owned()),
1949 vec2_lua(node.pos[0] as f64, node.pos[1] as f64),
1950 );
1951 tool_tbl.set(LuaKey::Str("ViewInfo".to_owned()), LuaValue::Table(vi));
19011952 }
19021953
1903 root
1954 // PassThrough
1955 if node.bypassed {
1956 tool_tbl.set(LuaKey::Str("PassThrough".to_owned()), LuaValue::Bool(true));
1957 } else if tool_tbl.get("PassThrough").is_some() {
1958 tool_tbl.remove(&LuaKey::Str("PassThrough".to_owned()));
1959 }
1960
1961 // Group/Macro inputs hold InstanceInput wiring (synced by `sync_group_wiring`).
1962 if !is_group_kind(&node.kind) {
1963 let master_inputs = node
1964 .raw
1965 .get_str("SourceOp")
1966 .and_then(|m| self.find_node(m))
1967 .map(|mid| &self.nodes[mid.0].inputs);
1968 sync_node_inputs(node, master_inputs, instance_defaults, tool_tbl);
1969 }
19041970 }
19051971
19061972 /// Serializes this composition back to a Blackmagic Fusion `.comp` string.
......@@ -2039,9 +2105,82 @@ fn user_control_default(raw: &LuaTable, name: &str) -> Option<ParamValue> {
20392105 }
20402106}
20412107
2108pub(crate) fn is_group_kind(kind: &str) -> bool {
2109 matches!(kind, "MacroOperator" | "GroupOperator")
2110}
2111
2112/// `(inner_op, inner_port, default)` for each `InstanceInput` exposed by a Group/Macro tool table.
2113fn instance_inputs(group: &LuaTable) -> impl Iterator<Item = (&str, &str, Option<ParamValue>)> {
2114 group.get_table("Inputs").into_iter().flat_map(|inputs| {
2115 inputs.entries.iter().filter_map(|(_, v)| {
2116 let t = v.as_table()?;
2117 Some((t.get_str("SourceOp")?, t.get_str("Source")?, t.get("Default").map(parse_param_value)))
2118 })
2119 })
2120}
2121
2122/// Writes external wires connected to a Group/Macro node back onto the inner tool inputs that its
2123/// `InstanceInput`s expose (load surfaces them as `node.inputs`).
2124fn sync_group_wiring(node: &Node, group_tbl: &mut LuaTable) {
2125 let exposed: Vec<(String, String, String)> = group_tbl
2126 .get_table("Inputs")
2127 .map(|inputs| {
2128 inputs
2129 .entries
2130 .iter()
2131 .filter_map(|(k, v)| {
2132 let LuaKey::Str(in_name) = k else { return None };
2133 let t = v.as_table()?;
2134 let port = if in_name.starts_with("MainInput") || in_name == "Input" {
2135 "Input".to_owned()
2136 } else {
2137 in_name.clone()
2138 };
2139 Some((port, t.get_str("SourceOp")?.to_owned(), t.get_str("Source")?.to_owned()))
2140 })
2141 .collect()
2142 })
2143 .unwrap_or_default();
2144 let Some(inner_tools) = group_tbl.get_table_mut("Tools") else { return };
2145 for (port, inner_op, inner_port) in exposed {
2146 let desired = node.inputs.get(&port);
2147 // Still the raw InstanceInput binding: nothing was rewired.
2148 if desired.is_some_and(|b| b.source_op.as_deref() == Some(inner_op.as_str())) {
2149 continue;
2150 }
2151 let Some(inner_tbl) = find_raw_tool_mut(inner_tools, &inner_op) else { continue };
2152 let current = inner_tbl
2153 .get_table("Inputs")
2154 .and_then(|i| i.get_table(&inner_port))
2155 .map(parse_input_binding);
2156 let wired = |b: &InputBinding| (b.source_op.clone(), b.source_output.clone());
2157 match desired {
2158 Some(b) if current.as_ref().map(wired) != Some(wired(b)) => {
2159 let input = ensure_table_mut(ensure_table_mut(inner_tbl, "Inputs", None), &inner_port, Some("Input"));
2160 for (key, val) in [("SourceOp", &b.source_op), ("Source", &b.source_output)] {
2161 match val {
2162 Some(v) => input.set(LuaKey::Str(key.to_owned()), LuaValue::String(v.clone())),
2163 None => {
2164 input.remove(&LuaKey::Str(key.to_owned()));
2165 }
2166 }
2167 }
2168 }
2169 None if current.as_ref().is_some_and(|c| c.source_op.is_some()) => {
2170 if let Some(input) = inner_tbl.get_table_mut("Inputs").and_then(|i| i.get_table_mut(&inner_port)) {
2171 input.remove(&LuaKey::Str("SourceOp".to_owned()));
2172 input.remove(&LuaKey::Str("Source".to_owned()));
2173 }
2174 }
2175 _ => {}
2176 }
2177 }
2178}
2179
20422180fn sync_node_inputs(
20432181 node: &Node,
20442182 master_inputs: Option<&HashMap<String, InputBinding>>,
2183 instance_defaults: &HashMap<(&str, &str), ParamValue>,
20452184 tool_tbl: &mut LuaTable,
20462185) {
20472186 // First remove any input present in raw `Inputs` that was explicitly removed from `node.inputs`.
......@@ -2061,6 +2200,18 @@ fn sync_node_inputs(
20612200
20622201 for port in ports {
20632202 let binding = &node.inputs[port];
2203 // Load fills unset inner-tool inputs from the enclosing group's `InstanceInput` default.
2204 if binding.source_op.is_none()
2205 && binding.expression.is_none()
2206 && binding.value.is_some()
2207 && binding.value.as_ref() == instance_defaults.get(&(node.name.as_str(), port.as_str()))
2208 && tool_tbl
2209 .get_table("Inputs")
2210 .and_then(|i| i.get_table(port))
2211 .is_none_or(|t| parse_input_binding(t).value.is_none())
2212 {
2213 continue;
2214 }
20642215 let existing_binding = tool_tbl
20652216 .get_table("Inputs")
20662217 .and_then(|i| i.get_table(port))
......@@ -3064,7 +3215,7 @@ fn eval_fusion_math_expr(src: &str, vars: &HashMap<String, f64>) -> Option<f64>
30643215 if args.is_empty() { return None; }
30653216 args.iter().copied().fold(f64::NEG_INFINITY, f64::max)
30663217 }
3067 "clamp" => a(0)?.clamp(a(1)?, a(2)?),
3218 "clamp" => a(0)?.max(a(1)?).min(a(2)?),
30683219 "mod" => {
30693220 let (x, y) = (a(0)?, a(1)?);
30703221 if y.abs() < 1e-12 { 0.0 } else { x - y * (x / y).floor() }
......@@ -3473,4 +3624,137 @@ mod expression_modifier_tests {
34733624 assert!((comp.eval_number(cg, "HighHue", 4155.0, 0.0, &expr) - 0.0).abs() < 1e-9);
34743625 assert!((comp.eval_number(cg, "HighHue", 4168.0, 0.0, &expr) - 0.5).abs() < 1e-9);
34753626 }
3627
3628 #[test]
3629 fn cyclic_expression_references_terminate() {
3630 let src = r#"Composition {
3631 Tools = ordered() {
3632 N = Transform {
3633 Inputs = { Size = Input { SourceOp = "E", Source = "NumberResult", }, },
3634 },
3635 E = Expression {
3636 Inputs = {
3637 n1 = Input { Expression = "N.Size", },
3638 NumberExpression = Input { Value = "n1 + 1", },
3639 },
3640 },
3641 },
3642 }"#;
3643 let comp = Comp::from_fusion_str(src).unwrap();
3644 let n = comp.node(comp.find_node("N").unwrap());
3645 let v = comp.eval_number(n, "Size", 0.0, 7.0, &ExprEngine::new());
3646 assert!(v.is_finite());
3647 }
3648
3649 #[test]
3650 fn clamp_with_inverted_bounds_does_not_panic() {
3651 let src = r#"Composition {
3652 Tools = ordered() {
3653 N = Transform { Inputs = { Size = Input { SourceOp = "E", Source = "NumberResult", }, }, },
3654 E = Expression {
3655 Inputs = {
3656 n1 = Input { Value = 5, },
3657 NumberExpression = Input { Value = "clamp(n1, 1, 0)", },
3658 },
3659 },
3660 },
3661 }"#;
3662 let comp = Comp::from_fusion_str(src).unwrap();
3663 let n = comp.node(comp.find_node("N").unwrap());
3664 assert_eq!(comp.eval_number(n, "Size", 0.0, 9.0, &ExprEngine::new()), 0.0);
3665 }
3666
3667 #[test]
3668 fn explicit_frame_format_is_never_overwritten_by_inferred_size() {
3669 let tools = r#"Tools = ordered() {
3670 BG = Background { Inputs = { Width = Input { Value = 1280, }, Height = Input { Value = 720, }, }, },
3671 }"#;
3672 let explicit = Comp::from_fusion_str(&format!(
3673 "Composition {{ Prefs = {{ Comp = {{ FrameFormat = {{ Width = 1920, Height = 1080, }}, }}, }}, {tools} }}"
3674 ))
3675 .unwrap();
3676 assert_eq!((explicit.width, explicit.height), (1920, 1080));
3677
3678 let inferred = Comp::from_fusion_str(&format!("Composition {{ {tools} }}")).unwrap();
3679 assert_eq!((inferred.width, inferred.height), (1280, 720));
3680 }
3681
3682 #[test]
3683 fn each_loaded_comp_gets_a_distinct_revision_range() {
3684 let src = "Composition { Tools = ordered() { } }";
3685 let a = Comp::from_fusion_str(src).unwrap();
3686 let mut b = Comp::from_fusion_str(src).unwrap();
3687 for _ in 0..1000 {
3688 b.revision += 1;
3689 }
3690 let c = Comp::from_fusion_str(src).unwrap();
3691 assert!(a.revision != b.revision && b.revision != c.revision && a.revision != c.revision);
3692 assert!(c.revision > b.revision);
3693 }
3694
3695 const GROUP_COMP: &str = r#"Composition {
3696 Tools = ordered() {
3697 BG = Background { },
3698 BG2 = Background { },
3699 Group1 = GroupOperator {
3700 Inputs = {
3701 MainInput1 = InstanceInput { SourceOp = "Inner1", Source = "Input", },
3702 BlurSize = InstanceInput { SourceOp = "Inner1", Source = "XBlurSize", Default = 3, },
3703 },
3704 Outputs = {
3705 MainOutput1 = InstanceOutput { SourceOp = "Inner2", Source = "Output", },
3706 },
3707 Tools = ordered() {
3708 Inner1 = Blur {
3709 Inputs = {
3710 Input = Input { SourceOp = "BG", Source = "Output", },
3711 },
3712 },
3713 Inner2 = Transform {
3714 Inputs = {
3715 Input = Input { SourceOp = "Inner1", Source = "Output", },
3716 Size = Input { Value = 1, },
3717 },
3718 },
3719 Inner3 = Blur { },
3720 },
3721 },
3722 },
3723}"#;
3724
3725 #[test]
3726 fn unedited_group_roundtrips_byte_for_byte() {
3727 let comp = Comp::from_fusion_str(GROUP_COMP).unwrap();
3728 let tools = |t: &LuaTable| t.get_table("Tools").unwrap().to_fusion_string();
3729 assert_eq!(tools(&comp.sync_to_raw_ast()), tools(comp.raw_root.as_ref().unwrap()));
3730 }
3731
3732 #[test]
3733 fn nested_group_edits_and_wiring_survive_save() {
3734 let mut comp = Comp::from_fusion_str(GROUP_COMP).unwrap();
3735 let group = comp.find_node("Group1").unwrap();
3736 assert_eq!(comp.node(group).connected_node("Input"), Some("BG"));
3737
3738 comp.delete_nodes(&[comp.find_node("Inner3").unwrap()]);
3739 let inner2 = comp.find_node("Inner2").unwrap();
3740 assert!(comp.set_input_value(inner2, "Size", ParamValue::Number(2.5)));
3741 let (group, bg2) = (comp.find_node("Group1").unwrap(), comp.find_node("BG2").unwrap());
3742 comp.connect_output(bg2, "Output", group, "Input").unwrap();
3743
3744 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
3745 let inner2 = saved.node(saved.find_node("Inner2").unwrap());
3746 assert_eq!(inner2.static_number("Size"), Some(2.5));
3747 assert!(saved.find_node("Inner3").is_none());
3748 assert_eq!(saved.node(saved.find_node("Inner1").unwrap()).connected_node("Input"), Some("BG2"));
3749 assert_eq!(saved.node(saved.find_node("Group1").unwrap()).connected_node("Input"), Some("BG2"));
3750 // The exposed `Default` stays on the InstanceInput instead of leaking onto Inner1.
3751 let text = comp.to_fusion_string();
3752 assert_eq!(text.matches("Value = 3").count(), 0, "{text}");
3753
3754 let mut comp = saved;
3755 let group = comp.find_node("Group1").unwrap();
3756 assert!(comp.disconnect(group, "Input"));
3757 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
3758 assert_eq!(saved.node(saved.find_node("Inner1").unwrap()).connected_node("Input"), None);
3759 }
34763760}
crates/model/src/edit.rs+601-270
......@@ -2,20 +2,25 @@
22
33use crate::comp::{
44 Comp, InputBinding, Node, NodeId, ParamValue, default_main_input_port, ensure_table_mut,
5 param_value_to_lua, vec2_lua,
5 find_raw_tool, find_raw_tool_mut, is_group_kind, is_modifier_type, param_value_to_lua, vec2_lua,
66};
77use crate::lua_value::{LuaKey, LuaTable, LuaValue, is_valid_lua_ident, parse_lua};
8use crate::spline::{BezierSpline, Keyframe, PolyPath};
8use crate::spline::{BezierSpline, Keyframe};
99use std::collections::{HashMap, HashSet, VecDeque};
1010
1111/// Default maximum number of undo steps retained by [`CompHistory`].
1212pub const DEFAULT_MAX_HISTORY: usize = 128;
1313
14/// Keyframe times closer than this are the same keyframe (matches the Inspector's `keyframe_state`).
15const KEYFRAME_EPS: f64 = 1e-4;
16
17/// Expression-modifier inputs whose `Value` is a formula string.
18const EXPRESSION_FORMULA_INPUTS: &[&str] =
19 &["NumberExpression", "PointExpressionX", "PointExpressionY", "PointExpression"];
20
1421impl Comp {
15 /// Checks whether a tool or modifier name is already in use anywhere in this composition.
16 fn name_exists(&self, name: &str) -> bool {
17 if self.node_by_name.contains_key(name)
18 || self.splines.contains_key(name)
22 fn modifier_exists(&self, name: &str) -> bool {
23 self.splines.contains_key(name)
1924 || self.poly_paths.contains_key(name)
2025 || self.gradient_modifiers.contains_key(name)
2126 || self.text_modifiers.contains_key(name)
......@@ -24,7 +29,29 @@ impl Comp {
2429 || self.text_cls.contains_key(name)
2530 || self.shakes.contains_key(name)
2631 || self.expression_modifiers.contains_key(name)
27 {
32 }
33
34 /// Whether pasted tools may link to `name`: a top-level flow node, or a modifier not private
35 /// to a group.
36 fn is_linkable_external(&self, name: &str) -> bool {
37 if self.nodes.iter().any(|n| !n.internal && n.name == name) {
38 return true;
39 }
40 let Some(tools) = self.raw_root.as_ref().and_then(|r| r.get_table("Tools")) else {
41 return self.modifier_exists(name);
42 };
43 self.modifier_exists(name)
44 && (tools.get(name).is_some()
45 || !tools
46 .entries
47 .iter()
48 .filter_map(|(_, v)| v.as_table()?.get_table("Tools"))
49 .any(|inner| find_raw_tool(inner, name).is_some()))
50 }
51
52 /// Checks whether a tool or modifier name is already in use anywhere in this composition.
53 fn name_exists(&self, name: &str) -> bool {
54 if self.node_by_name.contains_key(name) || self.modifier_exists(name) {
2855 return true;
2956 }
3057 if let Some(tools) = self.raw_root.as_ref().and_then(|r| r.get_table("Tools")) {
......@@ -135,22 +162,96 @@ impl Comp {
135162 id
136163 }
137164
138 /// Deletes the specified nodes, unwires downstream references, compacts `NodeId` indexing,
139 /// and prunes modifiers that were owned solely by the deleted nodes.
140 /// Returns the names of the deleted nodes.
165 /// Indices of the internal nodes owned by the Group/Macro at `idx`, including nested groups'
166 /// contents. Nodes load in post-order, so they are the contiguous internal block before `idx`.
167 fn group_children(&self, idx: usize) -> Vec<usize> {
168 let node = &self.nodes[idx];
169 let mut remaining: HashMap<&str, usize> = HashMap::new();
170 if is_group_kind(&node.kind) {
171 if let Some(inner) = self
172 .raw_root
173 .as_ref()
174 .and_then(|r| r.get_table("Tools"))
175 .and_then(|t| find_raw_tool(t, &node.name))
176 .and_then(|g| g.get_table("Tools"))
177 {
178 count_flow_tools(inner, &mut remaining);
179 }
180 }
181 let mut out = Vec::new();
182 for i in (0..idx).rev() {
183 let n = &self.nodes[i];
184 if remaining.is_empty() || !n.internal {
185 break;
186 }
187 if let Some(left) = remaining.get_mut(n.name.as_str()) {
188 *left -= 1;
189 if *left == 0 {
190 remaining.remove(n.name.as_str());
191 }
192 out.push(i);
193 }
194 }
195 out
196 }
197
198 /// Modifiers directly referenced by modifier `name`.
199 fn modifier_refs(&self, name: &str) -> Vec<String> {
200 let mut out = Vec::new();
201 if let Some(pp) = self.poly_paths.get(name) {
202 out.extend(pp.displacement_op.clone());
203 }
204 let bindings = self
205 .shakes
206 .get(name)
207 .map(|s| &s.inputs)
208 .or_else(|| self.expression_modifiers.get(name).map(|e| &e.inputs));
209 out.extend(bindings.into_iter().flat_map(|m| m.values()).filter_map(|b| b.source_op.clone()));
210 out
211 }
212
213 fn close_over_modifier_refs(&self, set: &mut HashSet<String>) {
214 let mut queue: VecDeque<String> = set.iter().cloned().collect();
215 while let Some(name) = queue.pop_front() {
216 for next in self.modifier_refs(&name) {
217 if set.insert(next.clone()) {
218 queue.push_back(next);
219 }
220 }
221 }
222 }
223
224 /// Deletes the specified nodes (and the private contents of any deleted Group/Macro), unwires
225 /// downstream references, compacts `NodeId` indexing, and prunes modifiers that were owned
226 /// solely by the deleted nodes. Returns the names of the deleted nodes.
141227 pub fn delete_nodes(&mut self, ids: &[NodeId]) -> Vec<String> {
142 let mut to_delete: HashSet<usize> = HashSet::new();
143 let mut deleted_names: Vec<String> = Vec::new();
228 let mut doomed: Vec<usize> = Vec::new();
144229 for &id in ids {
145 if id.0 < self.nodes.len() && to_delete.insert(id.0) {
146 deleted_names.push(self.nodes[id.0].name.clone());
230 if id.0 < self.nodes.len() && !doomed.contains(&id.0) {
231 doomed.push(id.0);
232 }
233 }
234 let mut next = 0;
235 while next < doomed.len() {
236 for child in self.group_children(doomed[next]) {
237 if !doomed.contains(&child) {
238 doomed.push(child);
239 }
147240 }
241 next += 1;
148242 }
149 if to_delete.is_empty() {
150 return deleted_names;
243 if doomed.is_empty() {
244 return Vec::new();
151245 }
152246
247 let deleted_names: Vec<String> = doomed.iter().map(|&i| self.nodes[i].name.clone()).collect();
153248 let deleted_name_set: HashSet<String> = deleted_names.iter().cloned().collect();
249 let deleted_internal: HashSet<String> = doomed
250 .iter()
251 .filter(|&&i| self.nodes[i].internal)
252 .map(|&i| self.nodes[i].name.clone())
253 .collect();
254 let to_delete: HashSet<usize> = doomed.into_iter().collect();
154255
155256 // Collect modifier names referenced by the nodes being deleted (candidates for pruning).
156257 let mut candidate_modifiers: HashSet<String> = HashSet::new();
......@@ -211,53 +312,22 @@ impl Comp {
211312 }
212313 self.nodes = new_nodes;
213314
214 // Collect all modifier references still live on surviving nodes (transitively through PolyPaths/Shakes).
315 // A modifier survives if a surviving node reaches it, or a modifier that is not itself being
316 // pruned references it (transitively, through paths, shakes and expression modifiers).
317 self.close_over_modifier_refs(&mut candidate_modifiers);
215318 let mut live_refs: HashSet<String> = HashSet::new();
216319 for node in &self.nodes {
217320 collect_node_source_ops(node, &mut live_refs);
218321 }
219 // Propagate transitive references (e.g. surviving node -> PolyPath -> Displacement spline,
220 // or surviving node -> Shake -> BezierSpline).
221 let mut queue: VecDeque<String> = live_refs.iter().cloned().collect();
222 while let Some(mod_name) = queue.pop_front() {
223 if let Some(pp) = self.poly_paths.get(&mod_name) {
224 if let Some(disp) = &pp.displacement_op {
225 if live_refs.insert(disp.clone()) {
226 queue.push_back(disp.clone());
227 }
228 }
229 }
230 if let Some(sh) = self.shakes.get(&mod_name) {
231 for binding in sh.inputs.values() {
232 if let Some(src) = &binding.source_op {
233 if live_refs.insert(src.clone()) {
234 queue.push_back(src.clone());
235 }
236 }
237 }
238 }
239 }
240
241 // Expand candidate_modifiers transitively (e.g. deleted node -> PolyPath -> Displacement spline).
242 let mut cand_queue: VecDeque<String> = candidate_modifiers.iter().cloned().collect();
243 while let Some(mod_name) = cand_queue.pop_front() {
244 if let Some(pp) = self.poly_paths.get(&mod_name) {
245 if let Some(disp) = &pp.displacement_op {
246 if candidate_modifiers.insert(disp.clone()) {
247 cand_queue.push_back(disp.clone());
248 }
249 }
250 }
251 if let Some(sh) = self.shakes.get(&mod_name) {
252 for binding in sh.inputs.values() {
253 if let Some(src) = &binding.source_op {
254 if candidate_modifiers.insert(src.clone()) {
255 cand_queue.push_back(src.clone());
256 }
257 }
258 }
259 }
260 }
322 let surviving_modifiers = self
323 .poly_paths
324 .keys()
325 .chain(self.shakes.keys())
326 .chain(self.expression_modifiers.keys())
327 .filter(|name| !candidate_modifiers.contains(*name));
328 let survivor_refs: Vec<String> = surviving_modifiers.flat_map(|n| self.modifier_refs(n)).collect();
329 live_refs.extend(survivor_refs);
330 self.close_over_modifier_refs(&mut live_refs);
261331
262332 // Prune orphaned modifiers that belonged to deleted nodes and are no longer referenced.
263333 let mut pruned_modifiers: HashSet<String> = HashSet::new();
......@@ -274,21 +344,21 @@ impl Comp {
274344 removed |= self.polyline_splines.remove(&cand).is_some();
275345 removed |= self.text_cls.remove(&cand).is_some();
276346 removed |= self.shakes.remove(&cand).is_some();
347 removed |= self.expression_modifiers.remove(&cand).is_some();
277348 if removed {
278349 pruned_modifiers.insert(cand);
279350 }
280351 }
281352
282 // Update `raw_root.Tools`: remove deleted nodes & pruned modifiers, and clear stale SourceOp.
283 if let Some(root) = self.raw_root.as_mut() {
284 if let Some(tools) = root.get_table_mut("Tools") {
285 tools.entries.retain(|(k, _)| match k {
286 LuaKey::Str(name) => {
287 !deleted_name_set.contains(name) && !pruned_modifiers.contains(name)
288 }
289 _ => true,
290 });
291 }
353 // Update `raw_root.Tools`: remove deleted top-level nodes, and pruned modifiers / deleted
354 // group-private nodes wherever they are nested.
355 if let Some(tools) = self.raw_root.as_mut().and_then(|r| r.get_table_mut("Tools")) {
356 tools.entries.retain(|(k, _)| match k {
357 LuaKey::Str(name) => !deleted_name_set.contains(name),
358 _ => true,
359 });
360 let nested: HashSet<String> = pruned_modifiers.union(&deleted_internal).cloned().collect();
361 remove_tools_recursive(tools, &nested);
292362 }
293363
294364 self.revision += 1;
......@@ -317,11 +387,7 @@ impl Comp {
317387 };
318388 let mut refs: VecDeque<String> = VecDeque::new();
319389 for n in &picked {
320 let raw = if n.internal {
321 &n.raw
322 } else {
323 root_tools.and_then(|t| t.get_table(&n.name)).unwrap_or(&n.raw)
324 };
390 let raw = root_tools.and_then(|t| find_raw_tool(t, &n.name)).unwrap_or(&n.raw);
325391 let mut found = HashSet::new();
326392 collect_source_ops_in_table(raw, &mut found);
327393 let mut found: Vec<String> = found.into_iter().collect();
......@@ -333,7 +399,14 @@ impl Comp {
333399 if tools.get(&name).is_some() || node_names.contains(name.as_str()) {
334400 continue;
335401 }
336 let Some(modifier) = root_tools.and_then(|t| t.get_table(&name)) else {
402 // Modifiers already nested inside a copied group travel with it.
403 let nested_in_copy = tools
404 .entries
405 .iter()
406 .filter_map(|(_, v)| v.as_table()?.get_table("Tools"))
407 .any(|inner| find_raw_tool(inner, &name).is_some());
408 let Some(modifier) = root_tools.and_then(|t| find_raw_tool(t, &name)).filter(|_| !nested_in_copy)
409 else {
337410 continue;
338411 };
339412 let mut found = HashSet::new();
......@@ -378,9 +451,7 @@ impl Comp {
378451 let pasted_set: HashSet<&str> = pasted_names.iter().map(String::as_str).collect();
379452
380453 drop_unknown_source_ops(&mut tools, &mut |name| {
381 pasted_set.contains(name)
382 || self.name_exists(name)
383 || self.nodes.iter().any(|n| n.name == name)
454 pasted_set.contains(name) || self.is_linkable_external(name)
384455 });
385456
386457 let mut reserved: HashSet<String> = self.nodes.iter().map(|n| n.name.clone()).collect();
......@@ -447,165 +518,12 @@ impl Comp {
447518 Ok(created)
448519 }
449520
450 /// Duplicates the selected nodes at `pos + offset` with unique names.
451 /// Preserves internal wires between duplicated nodes, keeps external wires intact,
452 /// and clones owned `BezierSpline` / `PolyPath` modifiers with fresh unique names.
521 /// Duplicates the selected nodes at `pos + offset` with unique names, as a copy + paste:
522 /// wires between duplicated nodes are preserved, wires to other nodes stay intact, and owned
523 /// modifiers and group contents are cloned. Returns the new top-level nodes.
453524 pub fn duplicate_nodes(&mut self, ids: &[NodeId], offset: [f32; 2]) -> Vec<NodeId> {
454 let mut unique_ids = Vec::new();
455 let mut seen = HashSet::new();
456 for &id in ids {
457 if id.0 < self.nodes.len() && seen.insert(id.0) {
458 unique_ids.push(id);
459 }
460 }
461 if unique_ids.is_empty() {
462 return Vec::new();
463 }
464
465 // Reserve names for all duplicated nodes first so internal wires can be remapped cleanly.
466 let mut reserved: HashSet<String> = HashSet::new();
467 let mut node_name_map: HashMap<String, String> = HashMap::new();
468 let mut dup_specs: Vec<(NodeId, String)> = Vec::with_capacity(unique_ids.len());
469
470 for &id in &unique_ids {
471 let orig_name = self.nodes[id.0].name.clone();
472 let new_name = self.generate_unique_name_excluding(&orig_name, &reserved);
473 reserved.insert(new_name.clone());
474 node_name_map.insert(orig_name, new_name.clone());
475 dup_specs.push((id, new_name));
476 }
477
478 // Clone `BezierSpline` and `PolyPath` modifiers referenced by the duplicated nodes.
479 let mut mod_name_map: HashMap<String, String> = HashMap::new();
480 let mut cloned_splines: Vec<(String, BezierSpline, Option<LuaTable>)> = Vec::new();
481 let mut cloned_paths: Vec<(String, PolyPath, Option<LuaTable>)> = Vec::new();
482
483 for &(id, _) in &dup_specs {
484 let mut input_ports: Vec<String> = self.nodes[id.0].inputs.keys().cloned().collect();
485 input_ports.sort();
486 for port in input_ports {
487 let Some(src_op) = self.nodes[id.0]
488 .inputs
489 .get(&port)
490 .and_then(|b| b.source_op.clone())
491 else {
492 continue;
493 };
494 if mod_name_map.contains_key(&src_op) || node_name_map.contains_key(&src_op) {
495 continue;
496 }
497 if let Some(orig_spline) = self.splines.get(&src_op).cloned() {
498 let new_mod = self.generate_unique_name_excluding(&src_op, &reserved);
499 reserved.insert(new_mod.clone());
500 let mut sp = orig_spline;
501 sp.name = new_mod.clone();
502 let raw_tbl = self
503 .raw_root
504 .as_ref()
505 .and_then(|r| r.get_table("Tools"))
506 .and_then(|t| t.get_table(&src_op))
507 .cloned();
508 mod_name_map.insert(src_op, new_mod.clone());
509 cloned_splines.push((new_mod, sp, raw_tbl));
510 } else if let Some(orig_path) = self.poly_paths.get(&src_op).cloned() {
511 let new_mod = self.generate_unique_name_excluding(&src_op, &reserved);
512 reserved.insert(new_mod.clone());
513 let mut pp = orig_path;
514 pp.name = new_mod.clone();
515
516 let mut raw_tbl = self
517 .raw_root
518 .as_ref()
519 .and_then(|r| r.get_table("Tools"))
520 .and_then(|t| t.get_table(&src_op))
521 .cloned();
522
523 // Also clone PolyPath's displacement spline if present.
524 if let Some(orig_disp) = pp.displacement_op.clone() {
525 let new_disp = if let Some(existing) = mod_name_map.get(&orig_disp) {
526 existing.clone()
527 } else if let Some(disp_sp) = self.splines.get(&orig_disp).cloned() {
528 let fresh = self.generate_unique_name_excluding(&orig_disp, &reserved);
529 reserved.insert(fresh.clone());
530 let mut sp = disp_sp;
531 sp.name = fresh.clone();
532 let disp_raw = self
533 .raw_root
534 .as_ref()
535 .and_then(|r| r.get_table("Tools"))
536 .and_then(|t| t.get_table(&orig_disp))
537 .cloned();
538 mod_name_map.insert(orig_disp.clone(), fresh.clone());
539 cloned_splines.push((fresh.clone(), sp, disp_raw));
540 fresh
541 } else {
542 orig_disp.clone()
543 };
544 if new_disp != orig_disp {
545 pp.displacement_op = Some(new_disp.clone());
546 if let Some(ref mut tbl) = raw_tbl {
547 rewrite_source_op_in_table(tbl, &orig_disp, &new_disp);
548 }
549 }
550 }
551
552 mod_name_map.insert(src_op, new_mod.clone());
553 cloned_paths.push((new_mod, pp, raw_tbl));
554 }
555 }
556 }
557
558 // Insert cloned modifiers into `Comp` and `raw_root.Tools`.
559 for (name, sp, raw_tbl) in cloned_splines {
560 self.splines.insert(name.clone(), sp);
561 if let (Some(root), Some(tbl)) = (self.raw_root.as_mut(), raw_tbl) {
562 let tools = ensure_table_mut(root, "Tools", Some("ordered"));
563 tools.set(LuaKey::Str(name), LuaValue::Table(tbl));
564 }
565 }
566 for (name, pp, raw_tbl) in cloned_paths {
567 self.poly_paths.insert(name.clone(), pp);
568 if let (Some(root), Some(tbl)) = (self.raw_root.as_mut(), raw_tbl) {
569 let tools = ensure_table_mut(root, "Tools", Some("ordered"));
570 tools.set(LuaKey::Str(name), LuaValue::Table(tbl));
571 }
572 }
573
574 // Build and insert the duplicated nodes.
575 let mut created_ids = Vec::with_capacity(dup_specs.len());
576 for (orig_id, new_name) in dup_specs {
577 let mut cloned = self.nodes[orig_id.0].clone();
578 let new_id = NodeId(self.nodes.len());
579 cloned.id = new_id;
580 cloned.name = new_name.clone();
581 cloned.pos = [cloned.pos[0] + offset[0], cloned.pos[1] + offset[1]];
582
583 for binding in cloned.inputs.values_mut() {
584 if let Some(src) = binding.source_op.as_mut() {
585 if let Some(mapped) = node_name_map.get(src).or_else(|| mod_name_map.get(src)) {
586 *src = mapped.clone();
587 }
588 }
589 }
590
591 // Update `cloned.raw` ViewInfo.Pos and SourceOp references.
592 set_view_info_pos(&mut cloned.raw, cloned.pos);
593 for (old_s, new_s) in node_name_map.iter().chain(mod_name_map.iter()) {
594 rewrite_source_op_in_table(&mut cloned.raw, old_s, new_s);
595 }
596
597 let raw_copy = cloned.raw.clone();
598 self.nodes.push(cloned);
599 self.node_by_name.insert(new_name.clone(), new_id);
600 if let Some(root) = self.raw_root.as_mut() {
601 let tools = ensure_table_mut(root, "Tools", Some("ordered"));
602 tools.set(LuaKey::Str(new_name), LuaValue::Table(raw_copy));
603 }
604 created_ids.push(new_id);
605 }
606
607 self.revision += 1;
608 created_ids
525 let snippet = self.export_fusion_clipboard(ids);
526 self.paste_fusion_clipboard(&snippet, (offset[0], offset[1])).unwrap_or_default()
609527 }
610528
611529 fn generate_unique_name_excluding(&self, hint: &str, reserved: &HashSet<String>) -> String {
......@@ -645,45 +563,81 @@ impl Comp {
645563 return Err(format!("a node or modifier named '{trimmed}' already exists"));
646564 }
647565
566 // A private (group-internal) tool is only visible inside its group; a top-level tool is
567 // visible everywhere except inside groups that define a tool of the same name.
568 let owner = if self.nodes[id.0].internal {
569 (0..self.nodes.len()).skip(id.0 + 1).find(|&g| self.group_children(g).contains(&id.0))
570 } else {
571 None
572 };
573 let affected: Vec<usize> = match owner {
574 Some(g) => self.group_children(g),
575 None => {
576 let mut shadowed: HashSet<usize> = HashSet::new();
577 for g in 0..self.nodes.len() {
578 let kids = self.group_children(g);
579 if kids.iter().any(|&k| self.nodes[k].name == old_name) {
580 shadowed.extend(kids);
581 }
582 }
583 (0..self.nodes.len()).filter(|i| !shadowed.contains(i)).collect()
584 }
585 };
586 let scope_name = owner.map(|g| self.nodes[g].name.clone());
587
648588 self.nodes[id.0].name = trimmed.to_owned();
649589 if self.node_by_name.get(&old_name) == Some(&id) {
650590 self.node_by_name.remove(&old_name);
651591 }
652592 self.node_by_name.insert(trimmed.to_owned(), id);
653593
654 // Rewrite all `SourceOp` references across all nodes' typed `inputs` and `raw` tables.
655 for node in &mut self.nodes {
594 for &i in &affected {
595 let node = &mut self.nodes[i];
656596 for binding in node.inputs.values_mut() {
657597 if binding.source_op.as_deref() == Some(old_name.as_str()) {
658598 binding.source_op = Some(trimmed.to_owned());
659599 }
660600 }
661 rewrite_source_op_in_table(&mut node.raw, &old_name, trimmed);
601 rewrite_source_op_in_scope(&mut node.raw, &old_name, trimmed, false);
662602 }
663603
664 // Rewrite `SourceOp` inside `shakes` modifiers.
665 for shake in self.shakes.values_mut() {
666 for binding in shake.inputs.values_mut() {
667 if binding.source_op.as_deref() == Some(old_name.as_str()) {
668 binding.source_op = Some(trimmed.to_owned());
604 let renames = HashMap::from([(old_name.clone(), trimmed.to_owned())]);
605 if owner.is_none() {
606 for shake in self.shakes.values_mut() {
607 for binding in shake.inputs.values_mut() {
608 if binding.source_op.as_deref() == Some(old_name.as_str()) {
609 binding.source_op = Some(trimmed.to_owned());
610 }
611 }
612 }
613 }
614 for em in self.expression_modifiers.values_mut() {
615 for key in EXPRESSION_FORMULA_INPUTS {
616 if let Some(ParamValue::Text(formula)) = em.inputs.get_mut(*key).and_then(|b| b.value.as_mut()) {
617 *formula = rename_expression_idents(formula, &renames);
669618 }
670619 }
671620 }
672621
673 // Rename key in `raw_root.Tools` in place (preserving order) and rewrite all SourceOp refs.
622 // Rename the key in place (preserving order) within the owning `Tools` table and rewrite refs.
674623 if let Some(root) = self.raw_root.as_mut() {
675 if let Some(tools) = root.get_table_mut("Tools") {
676 for (k, _) in &mut tools.entries {
677 if let LuaKey::Str(s) = k {
678 if s == &old_name {
679 *s = trimmed.to_owned();
624 let scope = match &scope_name {
625 Some(group) => root.get_table_mut("Tools").and_then(|t| find_raw_tool_mut(t, group)),
626 None => Some(&mut *root),
627 };
628 if let Some(scope) = scope {
629 rewrite_source_op_in_scope(scope, &old_name, trimmed, true);
630 if let Some(tools) = scope.get_table_mut("Tools") {
631 for (k, _) in &mut tools.entries {
632 if matches!(k, LuaKey::Str(s) if s == &old_name) {
633 *k = LuaKey::Str(trimmed.to_owned());
680634 break;
681635 }
682636 }
683637 }
638 rewrite_formulas_deep(scope, &renames);
684639 }
685 rewrite_source_op_in_table(root, &old_name, trimmed);
686 if root.get_str("ActiveTool") == Some(old_name.as_str()) {
640 if owner.is_none() && root.get_str("ActiveTool") == Some(old_name.as_str()) {
687641 root.set(
688642 LuaKey::Str("ActiveTool".to_owned()),
689643 LuaValue::String(trimmed.to_owned()),
......@@ -1011,6 +965,8 @@ impl Comp {
1011965 }
1012966
1013967 /// Removes the keyframe at `frame` from `spline_name`. Returns `true` if a keyframe was deleted.
968 /// Deleting a spline's last keyframe removes the spline and leaves every input it drove with
969 /// that keyframe's value as a static `Value`.
1014970 pub fn delete_keyframe(&mut self, spline_name: &str, frame: f64) -> bool {
1015971 let Some(sp) = self.splines.get_mut(spline_name) else {
1016972 return false;
......@@ -1018,11 +974,32 @@ impl Comp {
1018974 let Some(pos) = sp
1019975 .keyframes
1020976 .iter()
1021 .position(|kf| (kf.time - frame).abs() < 1e-6)
977 .position(|kf| (kf.time - frame).abs() < KEYFRAME_EPS)
1022978 else {
1023979 return false;
1024980 };
1025 sp.keyframes.remove(pos);
981 let removed = sp.keyframes.remove(pos);
982 if sp.keyframes.is_empty() {
983 self.splines.remove(spline_name);
984 let value = ParamValue::Number(removed.value);
985 for node in &mut self.nodes {
986 for (port, binding) in &mut node.inputs {
987 if binding.source_op.as_deref() != Some(spline_name) {
988 continue;
989 }
990 binding.source_op = None;
991 binding.source_output = None;
992 binding.value = Some(value.clone());
993 let port_tbl = ensure_table_mut(ensure_table_mut(&mut node.raw, "Inputs", None), port, Some("Input"));
994 port_tbl.remove(&LuaKey::Str("SourceOp".to_owned()));
995 port_tbl.remove(&LuaKey::Str("Source".to_owned()));
996 port_tbl.set(LuaKey::Str("Value".to_owned()), param_value_to_lua(&value));
997 }
998 }
999 if let Some(tools) = self.raw_root.as_mut().and_then(|r| r.get_table_mut("Tools")) {
1000 remove_tools_recursive(tools, &HashSet::from([spline_name.to_owned()]));
1001 }
1002 }
10261003 self.revision += 1;
10271004 true
10281005 }
......@@ -1116,6 +1093,8 @@ impl CompHistory {
11161093
11171094 /// Records the current state of `comp` as the clean saved point.
11181095 pub fn mark_saved(&mut self, comp: &Comp) {
1096 // Edits after a save must never coalesce into the saved undo entry.
1097 self.break_coalescing();
11191098 self.saved_undo_depth = Some(self.undo_stack.len());
11201099 self.saved_revision = Some(comp.revision);
11211100 }
......@@ -1234,7 +1213,7 @@ impl CompHistory {
12341213 return false;
12351214 };
12361215 let prev_rev = comp.revision;
1237 *comp = snapshot;
1216 restore_snapshot(comp, snapshot);
12381217 if comp.revision != prev_rev {
12391218 comp.revision = prev_rev.max(comp.revision) + 1;
12401219 }
......@@ -1272,7 +1251,7 @@ impl CompHistory {
12721251 coalesce_key: None,
12731252 };
12741253 self.redo_stack.push(redo_entry);
1275 *comp = entry.snapshot;
1254 restore_snapshot(comp, entry.snapshot);
12761255 comp.revision = prev_rev.max(comp.revision) + 1;
12771256 true
12781257 }
......@@ -1290,7 +1269,7 @@ impl CompHistory {
12901269 coalesce_key: None,
12911270 };
12921271 self.undo_stack.push_back(undo_entry);
1293 *comp = entry.snapshot;
1272 restore_snapshot(comp, entry.snapshot);
12941273 comp.revision = prev_rev.max(comp.revision) + 1;
12951274 true
12961275 }
......@@ -1311,6 +1290,14 @@ impl CompHistory {
13111290 }
13121291}
13131292
1293/// Replaces `comp` with `snapshot`, keeping the live file identity so a Save As followed by undo
1294/// never points Save at the file the snapshot came from.
1295fn restore_snapshot(comp: &mut Comp, mut snapshot: Comp) {
1296 snapshot.path = comp.path.take();
1297 snapshot.name = std::mem::take(&mut comp.name);
1298 *comp = snapshot;
1299}
1300
13141301fn sanitize_lua_ident(raw: &str) -> String {
13151302 let mut out = String::with_capacity(raw.len());
13161303 for ch in raw.chars() {
......@@ -1353,19 +1340,49 @@ fn collect_source_ops_in_table(tbl: &LuaTable, out: &mut HashSet<String>) {
13531340 }
13541341}
13551342
1356fn rewrite_source_op_in_table(tbl: &mut LuaTable, old_name: &str, new_name: &str) {
1343/// Rewrites `SourceOp = old_name` in `tbl`, skipping nested groups that define their own tool
1344/// called `old_name` (inside them the name refers to that private tool). `is_scope_root` exempts
1345/// `tbl` itself from that check.
1346fn rewrite_source_op_in_scope(tbl: &mut LuaTable, old_name: &str, new_name: &str, is_scope_root: bool) {
1347 if !is_scope_root && tbl.get_table("Tools").is_some_and(|t| t.get(old_name).is_some()) {
1348 return;
1349 }
13571350 for (k, v) in &mut tbl.entries {
1358 if let LuaKey::Str(key) = k {
1359 if key == "SourceOp" {
1360 if let LuaValue::String(s) = v {
1361 if s == old_name {
1362 *s = new_name.to_owned();
1363 }
1351 if matches!(k, LuaKey::Str(key) if key == "SourceOp") {
1352 if let LuaValue::String(s) = v {
1353 if s == old_name {
1354 *s = new_name.to_owned();
13641355 }
13651356 }
13661357 }
13671358 if let Some(sub) = v.as_table_mut() {
1368 rewrite_source_op_in_table(sub, old_name, new_name);
1359 rewrite_source_op_in_scope(sub, old_name, new_name, false);
1360 }
1361 }
1362}
1363
1364/// Counts the flow-node (non-modifier) tools in `tools`, including inside nested groups.
1365fn count_flow_tools<'a>(tools: &'a LuaTable, out: &mut HashMap<&'a str, usize>) {
1366 for (key, value) in &tools.entries {
1367 let (LuaKey::Str(name), Some(tool)) = (key, value.as_table()) else { continue };
1368 if is_modifier_type(tool.tag.as_deref().unwrap_or("Unknown")) {
1369 continue;
1370 }
1371 *out.entry(name.as_str()).or_default() += 1;
1372 if let Some(inner) = tool.get_table("Tools") {
1373 count_flow_tools(inner, out);
1374 }
1375 }
1376}
1377
1378/// Removes tools named in `names` from `tools` and every nested `Tools` table.
1379fn remove_tools_recursive(tools: &mut LuaTable, names: &HashSet<String>) {
1380 tools
1381 .entries
1382 .retain(|(k, _)| !matches!(k, LuaKey::Str(name) if names.contains(name)));
1383 for (_, v) in &mut tools.entries {
1384 if let Some(inner) = v.as_table_mut().and_then(|t| t.get_table_mut("Tools")) {
1385 remove_tools_recursive(inner, names);
13691386 }
13701387 }
13711388}
......@@ -1401,6 +1418,7 @@ fn rename_tools(tools: &mut LuaTable, renames: &HashMap<String, String>) {
14011418}
14021419
14031420fn rewrite_references(tbl: &mut LuaTable, renames: &HashMap<String, String>) {
1421 rewrite_formula_values(tbl, renames);
14041422 for (key, value) in &mut tbl.entries {
14051423 match (key, value) {
14061424 (LuaKey::Str(k), LuaValue::String(s)) if k == "SourceOp" => {
......@@ -1417,22 +1435,48 @@ fn rewrite_references(tbl: &mut LuaTable, renames: &HashMap<String, String>) {
14171435 }
14181436}
14191437
1438/// Rewrites the formula strings of an `Expression` modifier table (not recursive).
1439fn rewrite_formula_values(tbl: &mut LuaTable, renames: &HashMap<String, String>) {
1440 if tbl.tag.as_deref() != Some("Expression") {
1441 return;
1442 }
1443 let Some(inputs) = tbl.get_table_mut("Inputs") else { return };
1444 for key in EXPRESSION_FORMULA_INPUTS {
1445 if let Some(LuaValue::String(formula)) = inputs.get_table_mut(key).and_then(|i| i.get_mut("Value")) {
1446 *formula = rename_expression_idents(formula, renames);
1447 }
1448 }
1449}
1450
1451fn rewrite_formulas_deep(tbl: &mut LuaTable, renames: &HashMap<String, String>) {
1452 rewrite_formula_values(tbl, renames);
1453 for (_, value) in &mut tbl.entries {
1454 if let Some(sub) = value.as_table_mut() {
1455 rewrite_formulas_deep(sub, renames);
1456 }
1457 }
1458}
1459
1460/// Renames whole-word identifiers in `expr`, leaving property names (`Other.Size`) alone.
14201461fn rename_expression_idents(expr: &str, renames: &HashMap<String, String>) -> String {
14211462 let mut out = String::with_capacity(expr.len());
14221463 let mut word = String::new();
1423 let flush = |word: &mut String, out: &mut String| {
1424 out.push_str(renames.get(word.as_str()).map_or(word.as_str(), String::as_str));
1464 let mut prev = None;
1465 let flush = |word: &mut String, out: &mut String, prev: Option<char>| {
1466 let renamed = renames.get(word.as_str()).filter(|_| prev != Some('.'));
1467 out.push_str(renamed.map_or(word.as_str(), String::as_str));
14251468 word.clear();
14261469 };
14271470 for ch in expr.chars() {
14281471 if ch.is_ascii_alphanumeric() || ch == '_' {
14291472 word.push(ch);
14301473 } else {
1431 flush(&mut word, &mut out);
1474 flush(&mut word, &mut out, prev);
14321475 out.push(ch);
1476 prev = Some(ch);
14331477 }
14341478 }
1435 flush(&mut word, &mut out);
1479 flush(&mut word, &mut out, prev);
14361480 out
14371481}
14381482
......@@ -1465,9 +1509,16 @@ fn upsert_keyframe(spline: &mut BezierSpline, frame: f64, value: f64) {
14651509 if let Some(existing) = spline
14661510 .keyframes
14671511 .iter_mut()
1468 .find(|kf| (kf.time - frame).abs() < 1e-6)
1512 .find(|kf| (kf.time - frame).abs() < KEYFRAME_EPS)
14691513 {
1514 // Handles are absolute coordinates, so they travel with the key.
1515 let (dt, dv) = (frame - existing.time, value - existing.value);
1516 existing.time = frame;
14701517 existing.value = value;
1518 for handle in [&mut existing.lh, &mut existing.rh].into_iter().flatten() {
1519 handle[0] += dt;
1520 handle[1] += dv;
1521 }
14711522 } else {
14721523 spline.keyframes.push(Keyframe::new(frame, value));
14731524 spline.sort();
......@@ -2278,4 +2329,284 @@ mod tests {
22782329 assert!(!history.can_undo());
22792330 assert!(!history.in_group());
22802331 }
2332
2333 const TWO_GROUPS: &str = r#"Composition {
2334 Tools = ordered() {
2335 BG = Background { },
2336 GA = GroupOperator {
2337 Outputs = { Out = InstanceOutput { SourceOp = "Same", Source = "Output", }, },
2338 Tools = ordered() {
2339 Same = Blur { Inputs = { XBlurSize = Input { SourceOp = "SameSize", Source = "Value", }, }, },
2340 SameSize = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, },
2341 },
2342 },
2343 GB = GroupOperator {
2344 Outputs = { Out = InstanceOutput { SourceOp = "Same", Source = "Output", }, },
2345 Tools = ordered() {
2346 Same = Blur { },
2347 },
2348 },
2349 },
2350}"#;
2351
2352 fn tool_names(tools: &LuaTable) -> Vec<&str> {
2353 tools
2354 .entries
2355 .iter()
2356 .filter_map(|(k, _)| if let LuaKey::Str(s) = k { Some(s.as_str()) } else { None })
2357 .collect()
2358 }
2359
2360 #[test]
2361 fn mark_saved_stops_later_edits_coalescing_into_the_saved_step() {
2362 let mut comp = sample_comp();
2363 let mut history = CompHistory::new();
2364 let bg = comp.find_node("BG1").unwrap();
2365
2366 history.push_coalesced(&comp, "Drag", "drag");
2367 comp.set_node_pos(bg, [1.0, 1.0]);
2368 history.mark_saved(&comp);
2369 assert!(!history.is_dirty(&comp));
2370
2371 history.push_coalesced(&comp, "Drag", "drag");
2372 comp.set_node_pos(bg, [2.0, 2.0]);
2373 assert_eq!(history.undo_len(), 2);
2374 assert!(history.is_dirty(&comp));
2375 }
2376
2377 #[test]
2378 fn undo_and_redo_keep_the_live_file_identity() {
2379 let mut comp = sample_comp();
2380 comp.path = Some("/tmp/original.comp".into());
2381 comp.name = "original".to_owned();
2382 let mut history = CompHistory::new();
2383 let bg = comp.find_node("BG1").unwrap();
2384
2385 history.push_snapshot(&comp, "Move");
2386 comp.set_node_pos(bg, [9.0, 9.0]);
2387 comp.path = Some("/tmp/save_as.comp".into());
2388 comp.name = "save_as".to_owned();
2389
2390 assert!(history.undo(&mut comp));
2391 assert_eq!((comp.path.as_deref(), comp.name.as_str()), (Some(Path::new("/tmp/save_as.comp")), "save_as"));
2392 assert!(history.redo(&mut comp));
2393 assert_eq!((comp.path.as_deref(), comp.name.as_str()), (Some(Path::new("/tmp/save_as.comp")), "save_as"));
2394 }
2395
2396 #[test]
2397 fn deleting_a_group_removes_its_private_tools_and_modifiers() {
2398 let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap();
2399 let g = comp.find_node("Group1").unwrap();
2400 let deleted = comp.delete_nodes(&[g]);
2401 assert_eq!(deleted, ["Group1", "Inner1"]);
2402 assert!(comp.nodes.is_empty());
2403 assert!(comp.splines.is_empty());
2404 assert!(tool_names(comp.raw_root.as_ref().unwrap().get_table("Tools").unwrap()).is_empty());
2405 }
2406
2407 #[test]
2408 fn deleting_a_node_keeps_splines_still_used_by_expression_modifiers() {
2409 let src = r#"Composition {
2410 Tools = ordered() {
2411 N = Transform { Inputs = { Angle = Input { SourceOp = "Shared", Source = "Value", }, Size = Input { SourceOp = "E", Source = "NumberResult", }, }, },
2412 M = Transform { Inputs = { Angle = Input { SourceOp = "Own", Source = "Value", }, Size = Input { SourceOp = "E2", Source = "NumberResult", }, }, },
2413 E = Expression { Inputs = { n1 = Input { SourceOp = "Shared", Source = "Value", }, NumberExpression = Input { Value = "n1", }, }, },
2414 E2 = Expression { Inputs = { n1 = Input { SourceOp = "Own", Source = "Value", }, NumberExpression = Input { Value = "n1", }, }, },
2415 Shared = BezierSpline { KeyFrames = { [0] = { 1, Flags = { Linear = true } } }, },
2416 Own = BezierSpline { KeyFrames = { [0] = { 2, Flags = { Linear = true } } }, },
2417 },
2418}"#;
2419 let mut comp = Comp::from_fusion_str(src).unwrap();
2420 comp.delete_nodes(&[comp.find_node("M").unwrap()]);
2421 assert!(!comp.expression_modifiers.contains_key("E2"));
2422 assert!(!comp.splines.contains_key("Own"));
2423 assert!(comp.expression_modifiers.contains_key("E"));
2424 assert!(comp.splines.contains_key("Shared"));
2425
2426 // Deleting the other owner prunes the expression modifier and its spline.
2427 let mut comp = Comp::from_fusion_str(src).unwrap();
2428 comp.delete_nodes(&[comp.find_node("N").unwrap()]);
2429 assert!(!comp.expression_modifiers.contains_key("E"));
2430 assert!(!comp.splines.contains_key("Shared"));
2431
2432 // A spline referenced by a surviving (unpruned) expression modifier outlives its owner.
2433 let with_orphan = src.replace("\t},\n}", "\t\tEO = Expression { Inputs = { n1 = Input { SourceOp = \"Shared\", Source = \"Value\", }, }, },\n\t},\n}");
2434 let mut comp = Comp::from_fusion_str(&with_orphan).unwrap();
2435 comp.delete_nodes(&[comp.find_node("N").unwrap()]);
2436 assert!(comp.expression_modifiers.contains_key("EO"));
2437 assert!(comp.splines.contains_key("Shared"));
2438 }
2439
2440 #[test]
2441 fn export_includes_modifiers_nested_in_a_copied_internal_node_once() {
2442 let comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap();
2443 let inner = comp.find_node("Inner1").unwrap();
2444 let clip = comp.export_fusion_clipboard(&[inner]);
2445 let parsed = parse_lua(&clip).unwrap();
2446 let tools = parsed.as_table().unwrap().get_table("Tools").unwrap();
2447 assert_eq!(tool_names(tools), ["Inner1", "Inner1Size"]);
2448
2449 let whole = comp.export_fusion_clipboard(&[comp.find_node("Group1").unwrap()]);
2450 assert_eq!(whole.matches("Inner1Size = BezierSpline").count(), 1, "{whole}");
2451 }
2452
2453 #[test]
2454 fn paste_never_links_to_group_private_tools() {
2455 let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap();
2456 let snippet = r#"{ Tools = ordered() { T = Transform { Inputs = {
2457 Input = Input { SourceOp = "Inner1", Source = "Output", },
2458 Mask = Input { SourceOp = "Group1", Source = "Output", },
2459 Angle = Input { SourceOp = "Inner1Size", Source = "Value", },
2460 }, }, }, }"#;
2461 let ids = comp.paste_fusion_clipboard(snippet, (0.0, 0.0)).unwrap();
2462 let t = comp.node(ids[0]);
2463 assert_eq!(t.connected_node("Input"), None);
2464 assert_eq!(t.connected_node("Angle"), None);
2465 assert_eq!(t.connected_node("Mask"), Some("Group1"));
2466 }
2467
2468 #[test]
2469 fn expression_renames_skip_property_names() {
2470 let renames = HashMap::from([("Size".to_owned(), "Big".to_owned())]);
2471 assert_eq!(
2472 rename_expression_idents("Other.Size + Size.Width * Size", &renames),
2473 "Other.Size + Big.Width * Big"
2474 );
2475 }
2476
2477 #[test]
2478 fn rename_and_paste_rewrite_expression_modifier_formulas() {
2479 let src = r#"Composition {
2480 Tools = ordered() {
2481 BG = Background { },
2482 E = Expression { Inputs = { NumberExpression = Input { Value = "BG.Width + Other.BG", }, }, },
2483 },
2484}"#;
2485 let mut comp = Comp::from_fusion_str(src).unwrap();
2486 let bg = comp.find_node("BG").unwrap();
2487 comp.rename_node(bg, "Plate").unwrap();
2488 let formula = |c: &Comp| c.expression_modifiers["E"].inputs["NumberExpression"].value.clone();
2489 assert_eq!(formula(&comp), Some(ParamValue::Text("Plate.Width + Other.BG".to_owned())));
2490 assert!(comp.to_fusion_string().contains("Plate.Width + Other.BG"));
2491
2492 let paste = r#"{ Tools = ordered() { BG = Background { }, E = Expression { Inputs = { NumberExpression = Input { Value = "BG.Width", }, }, }, }, }"#;
2493 comp.paste_fusion_clipboard(paste, (0.0, 0.0)).unwrap();
2494 assert_eq!(
2495 comp.expression_modifiers["E_1"].inputs["NumberExpression"].value,
2496 Some(ParamValue::Text("BG.Width".to_owned()))
2497 );
2498 let mut again = Comp::from_fusion_str(paste).unwrap();
2499 again.paste_fusion_clipboard(paste, (0.0, 0.0)).unwrap();
2500 assert_eq!(
2501 again.expression_modifiers["E_1"].inputs["NumberExpression"].value,
2502 Some(ParamValue::Text("BG_1.Width".to_owned()))
2503 );
2504 }
2505
2506 #[test]
2507 fn renaming_one_groups_private_tool_leaves_same_named_tools_elsewhere() {
2508 let mut comp = Comp::from_fusion_str(TWO_GROUPS).unwrap();
2509 let (ga, gb) = (comp.find_node("GA").unwrap(), comp.find_node("GB").unwrap());
2510 let a_same = comp.nodes.iter().position(|n| n.name == "Same" && n.id.0 < ga.0).unwrap();
2511 assert_eq!(comp.rename_node(NodeId(a_same), "Renamed").unwrap(), "Renamed");
2512
2513 let text = comp.to_fusion_string();
2514 let saved = Comp::from_fusion_str(&text).unwrap();
2515 let group_tools = |name: &str| {
2516 let g = saved.node(saved.find_node(name).unwrap());
2517 (
2518 g.raw.get_table("Outputs").unwrap().get_table("Out").unwrap().get_str("SourceOp").unwrap().to_owned(),
2519 tool_names(find_raw_tool_in(&saved, name)).into_iter().map(str::to_owned).collect::<Vec<_>>(),
2520 )
2521 };
2522 assert_eq!(group_tools("GA"), ("Renamed".to_owned(), vec!["Renamed".to_owned(), "SameSize".to_owned()]));
2523 assert_eq!(group_tools("GB"), ("Same".to_owned(), vec!["Same".to_owned()]));
2524 assert_eq!(comp.node(gb).name, "GB");
2525 }
2526
2527 fn find_raw_tool_in<'a>(comp: &'a Comp, group: &str) -> &'a LuaTable {
2528 let tools = comp.raw_root.as_ref().unwrap().get_table("Tools").unwrap();
2529 find_raw_tool(tools, group).unwrap().get_table("Tools").unwrap()
2530 }
2531
2532 #[test]
2533 fn renaming_a_top_level_tool_ignores_groups_with_a_private_tool_of_that_name() {
2534 let src = TWO_GROUPS.replace("BG = Background { },", "BG = Background { },\n\t\tSame = Blur { },");
2535 let mut comp = Comp::from_fusion_str(&src).unwrap();
2536 let top = comp.find_node("Same").unwrap();
2537 assert!(!comp.node(top).internal);
2538 comp.rename_node(top, "Top").unwrap();
2539 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
2540 let ga = saved.node(saved.find_node("GA").unwrap());
2541 assert_eq!(
2542 ga.raw.get_table("Outputs").unwrap().get_table("Out").unwrap().get_str("SourceOp"),
2543 Some("Same")
2544 );
2545 assert!(saved.find_node("Top").is_some_and(|id| !saved.node(id).internal));
2546 }
2547
2548 #[test]
2549 fn duplicate_nodes_clones_groups_and_curve_modifiers() {
2550 let src = r#"Composition {
2551 Tools = ordered() {
2552 BG = Background { },
2553 HC = HueCurves {
2554 Inputs = {
2555 Input = Input { SourceOp = "BG", Source = "Output", },
2556 RedSuppress = Input { SourceOp = "HC_RSup", Source = "Value", },
2557 },
2558 Tools = ordered() {
2559 HC_RSup = LUTBezier { KeyColorSplines = { [0] = { [0] = { 0.5 }, [6] = { 0.5 } } }, },
2560 },
2561 },
2562 },
2563}"#;
2564 let mut comp = Comp::from_fusion_str(src).unwrap();
2565 let hc = comp.find_node("HC").unwrap();
2566 let dup = comp.duplicate_nodes(&[hc], [10.0, 0.0]);
2567 assert_eq!(dup.len(), 1);
2568 let d = comp.node(dup[0]);
2569 assert_eq!(d.name, "HC_1");
2570 assert_eq!(d.connected_node("Input"), Some("BG"));
2571 assert_eq!(d.connected_node("RedSuppress"), Some("HC_RSup_1"));
2572 assert!(comp.splines.contains_key("HC_RSup_1") && comp.splines.contains_key("HC_RSup"));
2573 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
2574 assert!(saved.splines.contains_key("HC_RSup_1"));
2575
2576 let mut comp = Comp::from_fusion_str(GROUP_SNIPPET).unwrap();
2577 let g = comp.find_node("Group1").unwrap();
2578 let dup = comp.duplicate_nodes(&[g], [0.0, 80.0]);
2579 let copy = comp.node(dup[0]);
2580 assert_eq!(copy.name, "Group1_1");
2581 assert_eq!(comp.node(copy.macro_output.unwrap()).name, "Inner1_1");
2582 assert!(comp.splines.contains_key("Inner1Size_1"));
2583 }
2584
2585 #[test]
2586 fn updating_a_keyframe_moves_its_handles_with_it() {
2587 let mut comp = sample_comp();
2588 let bc = comp.find_node("BC1").unwrap();
2589 comp.splines.get_mut("BC1Gain").unwrap().keyframes[1].lh = Some([20.0, 1.5]);
2590 comp.splines.get_mut("BC1Gain").unwrap().keyframes[1].rh = Some([40.0, 2.5]);
2591 comp.set_keyframe(bc, "Gain", 30.0, 3.0).unwrap();
2592 let kf = &comp.splines["BC1Gain"].keyframes[1];
2593 assert_eq!((kf.value, kf.lh, kf.rh), (3.0, Some([20.0, 2.5]), Some([40.0, 3.5])));
2594 }
2595
2596 #[test]
2597 fn deleting_the_last_keyframe_keeps_its_value_as_a_static_input() {
2598 let mut comp = sample_comp();
2599 let bc = comp.find_node("BC1").unwrap();
2600 // Within the shared 1e-4 tolerance.
2601 assert!(comp.delete_keyframe("BC1Gain", 0.00005));
2602 assert!(comp.delete_keyframe("BC1Gain", 30.0));
2603 assert!(!comp.splines.contains_key("BC1Gain"));
2604 assert_eq!(comp.node(bc).connected_node("Gain"), None);
2605 assert_eq!(comp.node(bc).static_number("Gain"), Some(2.0));
2606
2607 let saved = Comp::from_fusion_str(&comp.to_fusion_string()).unwrap();
2608 let r = saved.node(saved.find_node("BC1").unwrap());
2609 assert_eq!(r.static_number("Gain"), Some(2.0));
2610 assert!(!saved.to_fusion_string().contains("BC1Gain"));
2611 }
22812612}
crates/model/src/expr.rs+101-12
......@@ -3,11 +3,22 @@
33//! Supports Fusion globals (`time`, `iif`, `Point`, `Text`, `sin`/`cos`/`floor`/`ceil`/etc.)
44//! and `NodeName.ParamName` lookups without requiring full Fusion runtime scripting.
55
6use mlua::{Lua, MultiValue, Value};
6use mlua::{HookTriggers, Lua, LuaOptions, MultiValue, StdLib, Value, VmState};
77use std::collections::HashMap;
8use std::sync::Arc;
9use std::sync::atomic::{AtomicU64, Ordering};
810
11/// VM instructions one expression evaluation may execute before it is aborted.
12const INSTRUCTION_BUDGET: u64 = 50_000;
13/// Hook granularity; the budget is enforced in steps of this many instructions.
14const HOOK_STEP: u32 = 1000;
15const MEMORY_LIMIT: usize = 16 * 1024 * 1024;
16
17/// 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.
919pub struct ExprEngine {
1020 lua: Lua,
21 instructions_used: Arc<AtomicU64>,
1122}
1223
1324impl Default for ExprEngine {
......@@ -18,7 +29,8 @@ impl Default for ExprEngine {
1829
1930impl ExprEngine {
2031 pub fn new() -> Self {
21 let lua = Lua::new();
32 let lua = Lua::new_with(StdLib::MATH | StdLib::STRING | StdLib::TABLE, LuaOptions::default())
33 .expect("safe Lua stdlib subset loads");
2234 // Install Fusion SimpleExpression standard library into global scope.
2335 let init = r#"
2436 abs = math.abs
......@@ -53,7 +65,40 @@ impl ExprEngine {
5365 mix = function(a, b, t) return a + (b - a) * t end
5466 "#;
5567 let _ = lua.load(init).exec();
56 Self { lua }
68
69 let globals = lua.globals();
70 for name in [
71 "dofile", "loadfile", "load", "require", "collectgarbage", "os", "io", "debug", "package",
72 ] {
73 let _ = globals.set(name, Value::Nil);
74 }
75
76 let instructions_used = Arc::new(AtomicU64::new(0));
77 let counter = Arc::clone(&instructions_used);
78 lua.set_hook(HookTriggers::new().every_nth_instruction(HOOK_STEP), move |_, _| {
79 if counter.fetch_add(u64::from(HOOK_STEP), Ordering::Relaxed) >= INSTRUCTION_BUDGET {
80 Err(mlua::Error::runtime("expression instruction budget exceeded"))
81 } else {
82 Ok(VmState::Continue)
83 }
84 });
85 lua.set_memory_limit(MEMORY_LIMIT).expect("memory limit applies");
86
87 Self { lua, instructions_used }
88 }
89
90 /// Evaluates `expr` in a fresh environment with a fresh instruction budget.
91 fn run(
92 &self,
93 expr: &str,
94 time: f64,
95 self_params: &HashMap<String, f64>,
96 self_points: &HashMap<String, [f64; 2]>,
97 env_nodes: &HashMap<String, HashMap<String, f64>>,
98 ) -> Option<Value> {
99 let env = self.build_env(time, self_params, self_points, env_nodes).ok()?;
100 self.instructions_used.store(0, Ordering::Relaxed);
101 self.lua.load(&Self::expr_chunk(expr)).set_environment(env).eval().ok()
57102 }
58103
59104 fn expr_chunk(expr: &str) -> String {
......@@ -76,9 +121,7 @@ impl ExprEngine {
76121 self_points: &HashMap<String, [f64; 2]>,
77122 env_nodes: &HashMap<String, HashMap<String, f64>>,
78123 ) -> Option<f64> {
79 let env = self.build_env(time, self_params, self_points, env_nodes).ok()?;
80 let chunk = Self::expr_chunk(expr);
81 let val: Value = self.lua.load(&chunk).set_environment(env).eval().ok()?;
124 let val = self.run(expr, time, self_params, self_points, env_nodes)?;
82125 match val {
83126 Value::Number(n) => Some(n),
84127 Value::Integer(i) => Some(i as f64),
......@@ -97,9 +140,7 @@ impl ExprEngine {
97140 self_points: &HashMap<String, [f64; 2]>,
98141 env_nodes: &HashMap<String, HashMap<String, f64>>,
99142 ) -> Option<[f64; 2]> {
100 let env = self.build_env(time, self_params, self_points, env_nodes).ok()?;
101 let chunk = Self::expr_chunk(expr);
102 let val: Value = self.lua.load(&chunk).set_environment(env).eval().ok()?;
143 let val = self.run(expr, time, self_params, self_points, env_nodes)?;
103144 if let Value::Table(t) = val {
104145 let x = t.get::<f64>("X").or_else(|_| t.get::<f64>(1)).ok()?;
105146 let y = t.get::<f64>("Y").or_else(|_| t.get::<f64>(2)).ok()?;
......@@ -117,9 +158,7 @@ impl ExprEngine {
117158 self_points: &HashMap<String, [f64; 2]>,
118159 env_nodes: &HashMap<String, HashMap<String, f64>>,
119160 ) -> Option<String> {
120 let env = self.build_env(time, self_params, self_points, env_nodes).ok()?;
121 let chunk = Self::expr_chunk(expr);
122 let val: Value = self.lua.load(&chunk).set_environment(env).eval().ok()?;
161 let val = self.run(expr, time, self_params, self_points, env_nodes)?;
123162 match val {
124163 Value::String(s) => Some(s.to_str().ok()?.to_owned()),
125164 Value::Number(n) => Some(format!("{n}")),
......@@ -169,3 +208,53 @@ impl ExprEngine {
169208 Ok(env)
170209 }
171210}
211
212#[cfg(test)]
213mod tests {
214 use super::*;
215
216 fn num(expr: &str) -> Option<f64> {
217 let e = HashMap::new();
218 ExprEngine::new().eval_number(expr, 2.0, &HashMap::new(), &HashMap::new(), &e)
219 }
220
221 #[test]
222 fn fusion_expressions_still_evaluate() {
223 let v = num("time * 2 + math.sin(0.5)").unwrap();
224 assert!((v - (4.0 + 0.5_f64.sin())).abs() < 1e-12);
225 assert_eq!(num("clamp(5, 0, 1)"), Some(1.0));
226 assert_eq!(num(":local a = 3; return a * time"), Some(6.0));
227 }
228
229 #[test]
230 fn os_io_and_loaders_are_unavailable() {
231 let marker = std::env::temp_dir().join("fission_expr_sandbox_marker");
232 let _ = std::fs::remove_file(&marker);
233 let cmd = format!("os.execute('touch {}')", marker.display());
234 assert_eq!(num(&format!(":{cmd}; return 1")), None);
235 assert!(!marker.exists());
236 for src in [
237 "io.open('/etc/passwd')",
238 "require('os')",
239 "load('return 1')()",
240 "dofile('/etc/passwd')",
241 "debug.getinfo(1)",
242 "package.loaded",
243 "collectgarbage('count')",
244 ] {
245 assert_eq!(num(src), None, "{src}");
246 }
247 }
248
249 #[test]
250 fn runaway_loops_and_allocations_error_out() {
251 let engine = ExprEngine::new();
252 let e = HashMap::new();
253 let eval = |src: &str| engine.eval_number(src, 0.0, &HashMap::new(), &HashMap::new(), &e);
254 assert_eq!(eval(":while true do end"), None);
255 assert_eq!(eval(":local s = 'x'; while true do s = s .. s end"), None);
256 assert_eq!(eval("string.rep('x', 1e9) and 1"), None);
257 // Budget resets per evaluation, so the engine stays usable.
258 assert_eq!(eval("1 + 1"), Some(2.0));
259 }
260}
crates/model/src/spline.rs+15-2
......@@ -230,11 +230,13 @@ pub fn segment_control_points(k0: &Keyframe, k1: &Keyframe) -> [[f64; 2]; 4] {
230230 let p3 = [k1.time, k1.value];
231231 let dt = k1.time - k0.time;
232232 let dv = k1.value - k0.value;
233 // Keys can be transiently unsorted mid-drag; `f64::clamp` would panic on `lo > hi`.
234 let (t_lo, t_hi) = (k0.time.min(k1.time), k0.time.max(k1.time));
233235
234236 let p1 = if k1.flags.linear && k0.rh.is_none() {
235237 [k0.time + dt / 3.0, k0.value + dv / 3.0]
236238 } else if let Some(rh) = k0.rh {
237 [rh[0].clamp(k0.time, k1.time), rh[1]]
239 [rh[0].clamp(t_lo, t_hi), rh[1]]
238240 } else {
239241 [k0.time + dt / 3.0, k0.value + dv / 3.0]
240242 };
......@@ -242,7 +244,7 @@ pub fn segment_control_points(k0: &Keyframe, k1: &Keyframe) -> [[f64; 2]; 4] {
242244 let p2 = if k1.flags.linear && k1.lh.is_none() {
243245 [k1.time - dt / 3.0, k1.value - dv / 3.0]
244246 } else if let Some(lh) = k1.lh {
245 [lh[0].clamp(k0.time, k1.time), lh[1]]
247 [lh[0].clamp(t_lo, t_hi), lh[1]]
246248 } else {
247249 [k1.time - dt / 3.0, k1.value - dv / 3.0]
248250 };
......@@ -556,6 +558,17 @@ mod tests {
556558 }
557559 }
558560
561 #[test]
562 fn segment_control_points_survive_unsorted_keys() {
563 let mut a = Keyframe::new(10.0, 0.0);
564 a.rh = Some([5.0, 1.0]);
565 let mut b = Keyframe::new(4.0, 1.0);
566 b.lh = Some([20.0, 0.5]);
567 let [_, p1, p2, _] = segment_control_points(&a, &b);
568 assert_eq!(p1, [5.0, 1.0]);
569 assert_eq!(p2, [10.0, 0.5]);
570 }
571
559572 #[test]
560573 fn loop_clamps_before_first_keyframe_and_loops_after_last() {
561574 let loop_flags = KeyFlags { linear: true, loop_after: true, ..Default::default() };