Skip to content

EffectCraft: An open-source motion graphics and compositing tool written by scratch in pure Rust

Merge main into menu-parity branch; point AE menu entries at main's real commands

Brandon Thomasc99527708f31
diff --cc crates/engine/src/commands/anim.rs
index 62ac01835,f3560ccdd..0fbef4bb0
--- a/crates/engine/src/commands/anim.rs
+++ b/crates/engine/src/commands/anim.rs
@@@ -400,29 -384,31 +384,31 @@@ fn keys_or_layers(s: &Session) -> std::
pub fn specs() -> Vec<CommandSpec> {
vec![
+ cmd!("keys.copy", "Copy Keyframes", [], None, "{}", has_keys, copy),
+ cmd!("keys.paste", "Paste Keyframes", [], None, "{layers?, prop?|path?, time?}", has_key_clip, paste),
- cmd!("keys.selectAll", "Select All Keyframes", ["Edit"], Some("Cmd+Alt+A"), "{layers?}", keys_or_layers, select_all),
++ cmd!("keys.selectAll", "Select All Keyframes", [], Some("Cmd+Alt+A"), "{layers?}", keys_or_layers, select_all),
+ cmd!("keys.nudge", "Nudge Keyframes", [], None, "{frames, merge?}", has_keys, nudge),
+ cmd!("keys.nudgeForward", "Move Keyframes 1 Frame Later", [], Some("Alt+ArrowRight"), "{}", has_keys, |s, _| nudge(s, &json!({"frames": 1}))),
+ cmd!("keys.nudgeBackward", "Move Keyframes 1 Frame Earlier", [], Some("Alt+ArrowLeft"), "{}", has_keys, |s, _| nudge(s, &json!({"frames": -1}))),
+ cmd!("keys.nudgeForward10", "Move Keyframes 10 Frames Later", [], Some("Alt+Shift+ArrowRight"), "{}", has_keys, |s, _| nudge(
+ s,
+ &json!({"frames": 10})
+ )),
+ cmd!("keys.nudgeBackward10", "Move Keyframes 10 Frames Earlier", [], Some("Alt+Shift+ArrowLeft"), "{}", has_keys, |s, _| nudge(
+ s,
+ &json!({"frames": -10})
+ )),
+ cmd!("keys.set", "Edit Keyframe", [], None, "{layer?, path|prop, time (layer s), newTime?, value?, merge?}", has_comp, set_key),
cmd!(
- "anim.savePreset",
- "Save Animation Preset...",
- ["Animation"],
- None,
- "{path (.ecpreset), name?} — saves the selected properties/effects",
- has_selected_props,
- save_preset
- ),
- cmd!("anim.applyPreset", "Apply Animation Preset...", ["Animation"], None, "{path | preset, layers?}", has_layers, apply_preset),
- cmd!("anim.addKeyframe", "Add Keyframe", ["Animation"], None, "{} — keys the selected properties at the CTI", has_selected_props, add_keyframe),
- cmd!(
- "keys.exponentialScale",
- "Exponential Scale",
- ["Animation", "Keyframe Assistant"],
+ "keys.setEase",
+ "Set Keyframe Ease",
+ [],
None,
- "{} — two selected Scale keys",
- has_keys,
- exponential_scale
+ "{layer?, path|prop, time (layer s), side: in|out, dim?, speed?, influence? %, merge?}",
+ has_comp,
+ set_ease
),
- cmd!("keys.timeReverse", "Time-Reverse Keyframes", ["Animation", "Keyframe Assistant"], None, "{}", has_keys, time_reverse_keys),
- cmd!("text.addSelector", "Add Text Selector", [], None, "{layer?, kind: range}", has_text_layer, add_selector),
- cmd!("text.removeAllAnimators", "Remove All Text Animators", ["Animation"], None, "{layers?}", has_text_layer, remove_all_animators),
- cmd!("anim.reveal", "Reveal Properties", [], None, "{kind: keyframes|animation|modified}", has_comp, reveal),
+ cmd!("keys.timeReverse", "Time-Reverse Keyframes", ["Animation", "Keyframe Assistant"], None, "{}", has_keys, time_reverse),
+ query!("keys.info", "Keyframe Info", "{keys?: [{layer, prop, time}]}", info),
]
}
diff --cc crates/engine/src/commands/animation.rs
index 000000000,000000000..69a9ec31e
new file mode 100644
--- /dev/null
+++ b/crates/engine/src/commands/animation.rs
@@@ -1,0 -1,0 +1,399 @@@
++//! Animation menu: animation presets (EffectCraft's own JSON format), Add Keyframe, Keyframe
++//! Assistant (Exponential Scale), text animators/selectors, and the
++//! Reveal Properties commands.
++
++use std::collections::BTreeMap;
++
++use effectcraft_keyframe::{Interp, Keyframe, Value as KV};
++use effectcraft_project::build::{self, Ids};
++use effectcraft_project::{GroupKind, LayerId, Node, PropGroup, Property, Uid};
++use effectcraft_time::Tick;
++use serde_json::{Value, json};
++
++use super::{CommandSpec, bad, frontend, has_comp, has_keys, has_layers, layer_mut, layer_p, layers_p, match_path_of, selected_leaf_props, str_p};
++use crate::{EngineError, KeyRef, Result, Session, cmd};
++
++/// Preset file format version tag (`*.ecpreset`, JSON).
++pub const PRESET_TAG: &str = "effectcraftAnimationPreset";
++
++fn has_selected_props(s: &Session) -> std::result::Result<(), String> {
++ has_comp(s)?;
++ if selected_leaf_props(s).is_empty() && selected_effects(s).is_empty() { Err("select properties or effects first".into()) } else { Ok(()) }
++}
++
++fn has_text_layer(s: &Session) -> std::result::Result<(), String> {
++ has_layers(s)?;
++ let c = s.active_comp().ok_or("no composition")?;
++ if s.state.selected_layers.iter().filter_map(|l| c.layer(*l)).any(|l| l.props.group("text/animators").is_some()) {
++ Ok(())
++ } else {
++ Err("select a text layer".into())
++ }
++}
++
++/// Selected effect groups (layer, effect group).
++fn selected_effects(s: &Session) -> Vec<(LayerId, PropGroup)> {
++ let Some(c) = s.active_comp() else { return vec![] };
++ s.state
++ .selected_props
++ .iter()
++ .filter_map(|(l, u)| {
++ let layer = c.layer(*l)?;
++ let fx = layer.effects()?;
++ fx.groups().find(|g| g.uid == *u).map(|g| (*l, g.clone()))
++ })
++ .collect()
++}
++
++// ---------------------------------------------------------------- presets
++
++fn save_preset(s: &mut Session, p: &Value) -> Result<Value> {
++ let path = str_p(p, "path").ok_or_else(|| bad("anim.savePreset", "missing `path`"))?.to_string();
++ let comp = s.active_comp().ok_or(EngineError::NoComp)?;
++ let t = s.time();
++ let effects: Vec<(LayerId, PropGroup)> = selected_effects(s);
++ let effect_uids: Vec<Uid> = effects.iter().map(|(_, g)| g.uid).collect();
++ let mut props = vec![];
++ for (lid, uid) in selected_leaf_props(s) {
++ let Some(l) = comp.layer(lid) else { continue };
++ // Properties inside a saved effect travel with the effect.
++ if l.effects().is_some_and(|fx| fx.groups().any(|g| effect_uids.contains(&g.uid) && g.find(uid).is_some())) {
++ continue;
++ }
++ let (Some(pr), Some(mp)) = (l.props.find(uid), match_path_of(&l.props, uid)) else { continue };
++ props.push((l.layer_time(t), mp, pr.clone()));
++ }
++ if props.is_empty() && effects.is_empty() {
++ return Err(bad("anim.savePreset", "select properties or effects to save"));
++ }
++ // Key times are stored relative to the earliest key so the preset applies at the CTI.
++ let first = props.iter().flat_map(|(_, _, pr)| pr.keys.iter().map(|k| k.time)).min().unwrap_or(Tick::ZERO);
++ let props_json: Vec<Value> = props
++ .iter()
++ .map(|(_, mp, pr)| {
++ let mut pr = pr.clone();
++ for k in &mut pr.keys {
++ k.time -= first;
++ }
++ json!({"path": mp, "value": pr.value, "keys": pr.keys, "expression": pr.expr})
++ })
++ .collect();
++ let fx_json: Vec<Value> = effects.iter().map(|(_, g)| serde_json::to_value(g).unwrap_or_default()).collect();
++ let name = str_p(p, "name")
++ .map(str::to_string)
++ .unwrap_or_else(|| std::path::Path::new(&path).file_stem().map(|s| s.to_string_lossy().to_string()).unwrap_or_default());
++ let doc = json!({PRESET_TAG: 1, "name": name, "properties": props_json, "effects": fx_json});
++ let text = serde_json::to_string_pretty(&doc).unwrap_or_default();
++ s.services.write_file(&path, text.as_bytes()).map_err(|e| EngineError::Other(format!("cannot write {path}: {e}")))?;
++ Ok(json!({"path": path, "properties": props.len(), "effects": effects.len()}))
++}
++
++fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {
++ let doc: Value = match (p.get("preset"), str_p(p, "path")) {
++ (Some(v), _) => v.clone(),
++ (None, Some(path)) => {
++ let bytes = s.services.read_file(path).map_err(|e| EngineError::Other(format!("cannot read {path}: {e}")))?;
++ serde_json::from_slice(&bytes).map_err(|e| bad("anim.applyPreset", format!("not a preset: {e}")))?
++ }
++ _ => return Err(bad("anim.applyPreset", "missing `path` (or inline `preset`)")),
++ };
++ if doc.get(PRESET_TAG).is_none() {
++ return Err(bad("anim.applyPreset", "not an EffectCraft animation preset"));
++ }
++ let (cid, ids) = layers_p(s, p)?;
++ if ids.is_empty() {
++ return Err(bad("anim.applyPreset", "select a layer"));
++ }
++ let effects: Vec<PropGroup> =
++ doc["effects"].as_array().map(|a| a.iter().filter_map(|v| serde_json::from_value(v.clone()).ok()).collect()).unwrap_or_default();
++ let props: Vec<(String, Property)> = doc["properties"]
++ .as_array()
++ .map(|a| {
++ a.iter()
++ .filter_map(|v| {
++ let path = v["path"].as_str()?.to_string();
++ let value: KV = serde_json::from_value(v["value"].clone()).ok()?;
++ let keys: Vec<Keyframe> = serde_json::from_value(v["keys"].clone()).unwrap_or_default();
++ let expr = serde_json::from_value(v["expression"].clone()).ok().flatten();
++ let mut pr = Property::new(0, "", "", value);
++ pr.keys = keys;
++ pr.expr = expr;
++ Some((path, pr))
++ })
++ .collect()
++ })
++ .unwrap_or_default();
++ let t = s.time();
++ let mut applied = 0;
++ let mut skipped = vec![];
++ s.edit("Apply Animation Preset", None, |proj, _| {
++ let mut next = proj.next_id;
++ for lid in &ids {
++ let l = layer_mut(proj, cid, *lid)?;
++ let lt = l.layer_time(t);
++ if let Some(fx) = l.props.sub_mut("effects") {
++ for g in &effects {
++ let mut g = g.clone();
++ g.reassign_uids(&mut next);
++ next += 1;
++ fx.children.push(Node::Group(g));
++ applied += 1;
++ }
++ }
++ for (path, src) in &props {
++ match l.props.prop_mut(path) {
++ Some(pr) if std::mem::discriminant(&pr.value) == std::mem::discriminant(&src.value) => {
++ pr.value = src.value.clone();
++ pr.keys = src
++ .keys
++ .iter()
++ .cloned()
++ .map(|mut k| {
++ k.time += lt;
++ k
++ })
++ .collect();
++ if src.expr.is_some() {
++ pr.expr = src.expr.clone();
++ }
++ applied += 1;
++ }
++ _ => skipped.push(path.clone()),
++ }
++ }
++ }
++ proj.next_id = next;
++ Ok(())
++ })?;
++ Ok(json!({"applied": applied, "skipped": skipped}))
++}
++
++// ---------------------------------------------------------------- keyframes
++
++fn add_keyframe(s: &mut Session, _: &Value) -> Result<Value> {
++ let targets = selected_leaf_props(s);
++ if targets.is_empty() {
++ return Err(bad("anim.addKeyframe", "select properties first"));
++ }
++ let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
++ let t = s.time();
++ let n = s.edit("Add Keyframe", None, |proj, _| {
++ let mut n = 0;
++ for (lid, uid) in &targets {
++ let l = layer_mut(proj, cid, *lid)?;
++ let lt = l.layer_time(t);
++ let Some(pr) = l.props.find_mut(*uid) else { continue };
++ if pr.static_only {
++ continue;
++ }
++ if pr.keys.is_empty() {
++ pr.set_animated(true, lt);
++ } else {
++ let v = pr.value_at(lt);
++ pr.set_value_at(lt, v);
++ }
++ n += 1;
++ }
++ Ok(n)
++ })?;
++ Ok(json!({"keys": n}))
++}
++
++/// Selected keys grouped by (layer, property).
++fn keys_by_prop(s: &Session) -> BTreeMap<(LayerId, Uid), Vec<Tick>> {
++ let mut m: BTreeMap<(LayerId, Uid), Vec<Tick>> = BTreeMap::new();
++ for k in &s.state.selected_keys {
++ m.entry((k.layer, k.prop)).or_default().push(k.time);
++ }
++ m
++}
++
++fn exponential_scale(s: &mut Session, _: &Value) -> Result<Value> {
++ let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
++ let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
++ let fd = comp.frame_duration();
++ let groups = keys_by_prop(s);
++ let mut done = 0;
++ let mut work = vec![];
++ for ((lid, uid), mut times) in groups {
++ let Some(l) = comp.layer(lid) else { continue };
++ if l.transform().and_then(|tr| tr.get("scale")).map(|p| p.uid) != Some(uid) {
++ continue;
++ }
++ times.sort();
++ if times.len() >= 2 {
++ work.push((lid, uid, times[0], *times.last().unwrap_or(&times[0])));
++ }
++ }
++ if work.is_empty() {
++ return Err(bad("keys.exponentialScale", "select two Scale keyframes"));
++ }
++ s.edit("Exponential Scale", None, |proj, st| {
++ for (lid, uid, a, b) in &work {
++ let l = layer_mut(proj, cid, *lid)?;
++ let Some(pr) = l.props.find_mut(*uid) else { continue };
++ let (va, vb) = (pr.value_at(*a).as_vec3(), pr.value_at(*b).as_vec3());
++ pr.keys.retain(|k| k.time <= *a || k.time >= *b);
++ let n = ((*b - *a).0 / fd.0.max(1)).max(1);
++ for i in 0..=n {
++ let u = i as f64 / n as f64;
++ let t = if i == n { *b } else { *a + Tick(fd.0 * i) };
++ let f = |x: f64, y: f64| if x.abs() < 1e-9 || y.abs() < 1e-9 || x.signum() != y.signum() { x + (y - x) * u } else { x * (y / x).powf(u) };
++ let v = [f(va[0], vb[0]), f(va[1], vb[1]), f(va[2], vb[2])];
++ let mut k = Keyframe::new(t, KV::Vec3(v));
++ k.in_interp = Interp::Linear;
++ k.out_interp = Interp::Linear;
++ effectcraft_keyframe::set_key(&mut pr.keys, k);
++ st.selected_keys.push(KeyRef { layer: *lid, prop: *uid, time: t });
++ }
++ done += 1;
++ }
++ st.selected_keys.sort_by_key(|k| (k.layer.0, k.prop, k.time));
++ st.selected_keys.dedup();
++ Ok(())
++ })?;
++ Ok(json!({"properties": done}))
++}
++
++// ---------------------------------------------------------------- text animators
++
++fn add_selector(s: &mut Session, p: &Value) -> Result<Value> {
++ let kind = str_p(p, "kind").unwrap_or("range");
++ if kind != "range" {
++ return Err(bad("text.addSelector", "only Range selectors are available"));
++ }
++ let (cid, lid) = layer_p(s, p, "text.addSelector")?;
++ // Target: a selected animator (or anything inside one), else the last animator.
++ let sel: Vec<Uid> = s.state.selected_props.iter().filter(|(l, _)| *l == lid).map(|(_, u)| *u).collect();
++ let uid = s.edit("Add Text Selector", None, |proj, _| {
++ let mut next = proj.next_id;
++ let l = layer_mut(proj, cid, lid)?;
++ let anims = l.props.group_mut("text/animators").ok_or_else(|| bad("text.addSelector", "not a text layer"))?;
++ if anims.children.is_empty() {
++ return Err(bad("text.addSelector", "the layer has no text animators (use Animate Text first)"));
++ }
++ let idx = anims
++ .children
++ .iter()
++ .position(|c| c.as_group().is_some_and(|g| sel.contains(&g.uid) || sel.iter().any(|u| g.find(*u).is_some() || g.find_group(*u).is_some())))
++ .unwrap_or(anims.children.len() - 1);
++ let Some(Node::Group(anim)) = anims.children.get_mut(idx) else { return Err(bad("text.addSelector", "no animator")) };
++ let sels = anim.sub_mut("selectors").ok_or_else(|| bad("text.addSelector", "animator has no selectors group"))?;
++ let mut ids = Ids(&mut next);
++ let g = build::range_selector(&mut ids, &format!("Range Selector {}", sels.children.len() + 1));
++ let uid = g.uid;
++ sels.children.push(g.into());
++ proj.next_id = next;
++ Ok(uid)
++ })?;
++ Ok(json!({"selector": uid}))
++}
++
++fn remove_all_animators(s: &mut Session, p: &Value) -> Result<Value> {
++ let (cid, ids) = layers_p(s, p)?;
++ s.edit("Remove All Text Animators", None, |proj, _| {
++ for lid in &ids {
++ if let Some(a) = layer_mut(proj, cid, *lid)?.props.group_mut("text/animators") {
++ a.children.clear();
++ }
++ }
++ Ok(())
++ })?;
++ Ok(Value::Null)
++}
++
++// ---------------------------------------------------------------- reveal
++
++/// Whether a static property differs from the value a fresh layer would have. Transform
++/// defaults depend on the source size and comp size.
++fn modified(pr: &Property, group: &str, default_anchor: [f64; 2], comp_center: [f64; 2]) -> bool {
++ if pr.is_animated() || pr.expr.is_some() {
++ return true;
++ }
++ let v = &pr.value;
++ let near = |a: &[f64], b: &[f64]| a.iter().zip(b).all(|(x, y)| (x - y).abs() < 1e-6);
++ match (group, pr.match_id.as_str()) {
++ ("transform", "anchor") => !near(&v.as_vec2(), &default_anchor),
++ ("transform", "position") => !near(&v.as_vec2(), &comp_center) || v.as_vec3()[2].abs() > 1e-6,
++ ("transform", "scale") => !near(&v.as_vec3(), &[100.0; 3]),
++ ("transform", "opacity") => (v.as_f64() - 100.0).abs() > 1e-6,
++ ("transform", "orientation") => !near(&v.as_vec3(), &[0.0; 3]),
++ ("transform", _) => v.as_f64().abs() > 1e-6,
++ _ => false,
++ }
++}
++
++fn reveal(s: &mut Session, p: &Value) -> Result<Value> {
++ let kind = str_p(p, "kind").unwrap_or("keyframes").to_string();
++ let cid = super::comp_id(s, p)?;
++ let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
++ let layers: Vec<LayerId> = if s.state.selected_layers.is_empty() { comp.layers.iter().map(|l| l.id).collect() } else { s.state.selected_layers.clone() };
++ let mut out = vec![];
++ for lid in &layers {
++ let Some(l) = comp.layer(*lid) else { continue };
++ let (w, h) = effectcraft_render::source_size(&s.project, l);
++ let anchor = [w as f64 / 2.0, h as f64 / 2.0];
++ let center = [comp.width as f64 / 2.0, comp.height as f64 / 2.0];
++ for top in l.props.groups() {
++ let hit = |pr: &Property| match kind.as_str() {
++ "keyframes" => pr.is_animated(),
++ "animation" => pr.is_animated() || pr.has_expression(),
++ _ => modified(pr, &top.match_id, anchor, center),
++ };
++ let mut found = vec![];
++ top.walk("", &mut |_, pr| {
++ if hit(pr) {
++ found.push(pr.uid);
++ }
++ });
++ // Modified: effects and masks count as modifications in full (AE reveals them).
++ if kind == "modified" && matches!(top.match_id.as_str(), "effects" | "masks") {
++ for g in top.groups() {
++ found.push(g.uid);
++ }
++ }
++ if kind == "modified" && top.match_id == "text" {
++ for g in top.group("animators").into_iter().flat_map(|a| a.groups()) {
++ found.push(g.uid);
++ }
++ }
++ out.extend(found.into_iter().map(|u| json!({"layer": lid.0, "prop": u})));
++ }
++ }
++ frontend(s, "timeline.revealProps", &json!({"props": out, "kind": kind}))?;
++ Ok(json!({"props": out}))
++}
++
++/// Is `g` an effect/mask group kind (used by tests).
++#[allow(dead_code)]
++pub(crate) fn is_indexed(g: &PropGroup) -> bool {
++ matches!(g.kind, GroupKind::Indexed | GroupKind::Mask { .. } | GroupKind::Effect { .. })
++}
++
++pub fn specs() -> Vec<CommandSpec> {
++ vec![
++ cmd!(
++ "anim.savePreset",
++ "Save Animation Preset...",
++ ["Animation"],
++ None,
++ "{path (.ecpreset), name?} — saves the selected properties/effects",
++ has_selected_props,
++ save_preset
++ ),
++ cmd!("anim.applyPreset", "Apply Animation Preset...", ["Animation"], None, "{path | preset, layers?}", has_layers, apply_preset),
++ cmd!("anim.addKeyframe", "Add Keyframe", ["Animation"], None, "{} — keys the selected properties at the CTI", has_selected_props, add_keyframe),
++ cmd!(
++ "keys.exponentialScale",
++ "Exponential Scale",
++ ["Animation", "Keyframe Assistant"],
++ None,
++ "{} — two selected Scale keys",
++ has_keys,
++ exponential_scale
++ ),
++ cmd!("text.addSelector", "Add Text Selector", [], None, "{layer?, kind: range}", has_text_layer, add_selector),
++ cmd!("text.removeAllAnimators", "Remove All Text Animators", ["Animation"], None, "{layers?}", has_text_layer, remove_all_animators),
++ cmd!("anim.reveal", "Reveal Properties", [], None, "{kind: keyframes|animation|modified}", has_comp, reveal),
++ ]
++}
diff --cc crates/engine/src/commands/comp.rs
index c066536d5,f00b9b519..996df5df7
--- a/crates/engine/src/commands/comp.rs
+++ b/crates/engine/src/commands/comp.rs
@@@ -202,19 -241,19 +241,19 @@@ pub fn specs() -> Vec<CommandSpec>
vec![
cmd!(
"comp.new",
- "New Composition…",
+ "New Composition...",
["Composition"],
Some("Cmd+N"),
- "{name?, width?, height?, frameRate?, duration? (s), background? [r,g,b]|#hex, open?}",
+ "{name?, width?, height?, frameRate?, duration? (s), startTime? (s) | startTimecode?, background? [r,g,b]|#hex, pixelAspect?, shutterAngle?, shutterPhase?, motionBlurSamples?, renderer? classic3D|advanced3D, anchor?, open?}",
always,
new_comp
),
cmd!(
"comp.settings",
- "Composition Settings…",
+ "Composition Settings...",
["Composition"],
Some("Cmd+K"),
- "{comp?, name?, width?, height?, frameRate?, duration?, background?, shutterAngle?, shutterPhase?, motionBlurSamples?}",
+ "{comp?, name?, width?, height?, anchor? 0-8 (resize anchor, 4 = center), frameRate?, duration?, startTime? (s) | startTimecode?, background?, shutterAngle?, shutterPhase?, motionBlurSamples?, pixelAspect?, renderer? classic3D|advanced3D}",
has_comp,
settings
),
diff --cc crates/engine/src/commands/edit.rs
index 4e48c8456,027c23b65..df7a9e426
--- a/crates/engine/src/commands/edit.rs
+++ b/crates/engine/src/commands/edit.rs
@@@ -1,12 -1,11 +1,12 @@@
//! Edit menu.
use effectcraft_color::Label;
-use effectcraft_project::{Layer, LayerId};
+use effectcraft_project::{Expression, ItemKind, Layer, LayerId, LayerSource};
+use effectcraft_time::Tick;
use serde_json::{Value, json};
-use super::{CommandSpec, has_comp, has_layers, layers_p, str_p};
-use crate::{Result, Session, cmd};
+use super::{CommandSpec, has_comp, has_layers, layers_p, match_path_of, selected_leaf_props, str_p};
- use crate::{EngineError, KeyClip, LinkClip, Result, Session, cmd};
++use crate::{EngineError, LinkClip, Result, Session, cmd};
fn can_undo(s: &Session) -> std::result::Result<(), String> {
if s.history.undo.is_empty() { Err("nothing to undo".into()) } else { Ok(()) }
@@@ -115,214 -100,30 +119,202 @@@ fn delete(s: &mut Session, p: &Value) -
Ok(json!(ids.len()))
}
+fn clear_clipboards(s: &mut Session) {
+ s.state.clipboard.clear();
+ s.state.key_clipboard.clear();
+ s.state.link_clipboard = None;
++ s.state.clip_is_keys = false;
+}
+
+/// Edit ▸ Copy: selected keyframes (when any) go to the keyframe clipboard, else layers.
fn copy(s: &mut Session, p: &Value) -> Result<Value> {
- if !s.state.selected_keys.is_empty() && p.get("layers").is_none() && p.get("layer").is_none() {
- let comp = s.active_comp().ok_or(EngineError::NoComp)?;
- let mut clips: Vec<KeyClip> = vec![];
- let earliest = s.state.selected_keys.iter().map(|k| k.time).min().unwrap_or(Tick::ZERO);
- for k in &s.state.selected_keys {
- let Some(l) = comp.layer(k.layer) else { continue };
- let (Some(pr), Some(path)) = (l.props.find(k.prop), match_path_of(&l.props, k.prop)) else { continue };
- let Some(key) = pr.keys.iter().find(|x| x.time == k.time) else { continue };
- let mut key = key.clone();
- key.time -= earliest;
- match clips.iter_mut().find(|c| c.path == path) {
- Some(c) => c.keys.push(key),
- None => clips.push(KeyClip { path, keys: vec![key] }),
- }
- }
- for c in &mut clips {
- c.keys.sort_by_key(|k| k.time);
- }
- let n: usize = clips.iter().map(|c| c.keys.len()).sum();
- clear_clipboards(s);
- s.state.key_clipboard = clips;
- return Ok(json!({"keys": n}));
+ // Keyframes selected → copy keys (pasted at the CTI).
+ if !s.state.selected_keys.is_empty() && p.get("layers").is_none() {
++ s.state.link_clipboard = None;
+ return s.execute("keys.copy", json!({}));
}
let (cid, ids) = layers_p(s, p)?;
+ s.state.clip_is_keys = false;
let comp = s.project.comp(cid).ok_or(crate::EngineError::NoComp)?;
- s.state.clipboard = comp.layers.iter().filter(|l| ids.contains(&l.id)).cloned().collect();
+ let layers: Vec<Layer> = comp.layers.iter().filter(|l| ids.contains(&l.id)).cloned().collect();
+ clear_clipboards(s);
+ s.state.clipboard = layers;
Ok(json!(s.state.clipboard.len()))
}
+/// The expression accessor for a property, e.g. `comp("Main").layer("Solid").transform("Position")`.
+pub(crate) fn link_expression(s: &Session, lid: LayerId, uid: effectcraft_project::Uid, relative: bool) -> Option<String> {
+ let cid = s.active_comp_id()?;
+ let comp = s.project.comp(cid)?;
+ let l = comp.layer(lid)?;
+ let names = l.props.name_path_of(uid)?;
+ let matches = match_path_of(&l.props, uid)?;
+ let names: Vec<&str> = names.split('/').collect();
+ let first = matches.split('/').next()?.to_string();
+ let q = |x: &str| serde_json::to_string(x).unwrap_or_default();
+ let base = if relative { format!("thisComp.layer({})", q(&l.name)) } else { format!("comp({}).layer({})", q(&s.project.item(cid)?.name), q(&l.name)) };
+ let mut out = match first.as_str() {
+ "transform" => format!("{base}.transform"),
+ "effects" => format!("{base}.effect({})", q(names.get(1)?)),
+ "masks" => format!("{base}.mask({})", q(names.get(1)?)),
+ "text" => format!("{base}.text"),
+ "contents" => format!("{base}.content({})", q(names.get(1)?)),
+ _ => return None,
+ };
+ let skip = if matches!(first.as_str(), "effects" | "masks" | "contents") { 2 } else { 1 };
+ for n in names.iter().skip(skip) {
+ out.push_str(&format!("({})", q(n)));
+ }
+ Some(out)
+}
+
+fn copy_links(s: &mut Session, p: &Value, relative: bool) -> Result<Value> {
+ let props = selected_leaf_props(s);
+ if props.is_empty() {
+ // Layers: copy them with every animatable transform/effect property linked to the source.
+ let (cid, ids) = layers_p(s, p)?;
+ let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
+ let mut layers = vec![];
+ for l in comp.layers.iter().filter(|l| ids.contains(&l.id)) {
+ let mut copy = l.clone();
+ let mut uids = vec![];
+ for g in ["transform", "effects"] {
+ if let Some(grp) = l.props.sub(g) {
+ grp.walk("", &mut |_, pr| {
+ if !pr.static_only && !pr.hold_only {
+ uids.push(pr.uid);
+ }
+ });
+ }
+ }
+ for uid in uids {
+ if let (Some(e), Some(pr)) = (link_expression(s, l.id, uid, relative), copy.props.find_mut(uid)) {
+ pr.expr = Some(Expression { text: e, enabled: true });
+ }
+ }
+ layers.push(copy);
+ }
+ let n = layers.len();
+ clear_clipboards(s);
+ s.state.clipboard = layers;
+ return Ok(json!({"layers": n}));
+ }
+ let comp = s.active_comp().ok_or(EngineError::NoComp)?;
+ let mut links = vec![];
+ for (lid, uid) in &props {
+ let Some(path) = comp.layer(*lid).and_then(|l| match_path_of(&l.props, *uid)) else { continue };
+ if let Some(e) = link_expression(s, *lid, *uid, relative) {
+ links.push((path, e));
+ }
+ }
+ let n = links.len();
+ clear_clipboards(s);
+ s.state.link_clipboard = Some(LinkClip::Links { relative, links });
+ Ok(json!({"links": n}))
+}
+
+fn copy_expression_only(s: &mut Session, _: &Value) -> Result<Value> {
+ let comp = s.active_comp().ok_or(EngineError::NoComp)?;
+ let mut out = vec![];
+ for (lid, uid) in selected_leaf_props(s) {
+ let Some(l) = comp.layer(lid) else { continue };
+ if let (Some(pr), Some(path)) = (l.props.find(uid), match_path_of(&l.props, uid))
+ && let Some(e) = &pr.expr
+ {
+ out.push((path, e.clone()));
+ }
+ }
+ if out.is_empty() {
+ return Err(EngineError::Other("the selected properties have no expressions".into()));
+ }
+ let n = out.len();
+ clear_clipboards(s);
+ s.state.link_clipboard = Some(LinkClip::Expressions(out));
+ Ok(json!({"expressions": n}))
+}
+
+/// Paste the keyframe clipboard at the CTI onto the selected layers (same property paths).
+fn paste_keys(s: &mut Session, reversed: bool) -> Result<Value> {
+ let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
+ let ids = s.state.selected_layers.clone();
+ if ids.is_empty() {
+ return Err(EngineError::Other("select a layer to paste keyframes into".into()));
+ }
+ let clip = s.state.key_clipboard.clone();
+ let t = s.time();
+ let n = s.edit(if reversed { "Paste Reversed Keyframes" } else { "Paste Keyframes" }, None, |proj, st| {
+ let mut n = 0;
+ st.selected_keys.clear();
+ for lid in &ids {
+ let l = super::layer_mut(proj, cid, *lid)?;
+ let lt = l.layer_time(t);
+ for c in &clip {
+ let Some(pr) = l.props.prop_mut(&c.path) else { continue };
+ let span = c.keys.last().map(|k| k.time).unwrap_or(Tick::ZERO);
+ for k in &c.keys {
+ let mut k = k.clone();
+ if std::mem::discriminant(&k.value) != std::mem::discriminant(&pr.value) {
+ continue;
+ }
+ if reversed {
+ k.time = span - k.time;
+ std::mem::swap(&mut k.in_interp, &mut k.out_interp);
+ std::mem::swap(&mut k.in_ease, &mut k.out_ease);
+ std::mem::swap(&mut k.spatial_in, &mut k.spatial_out);
+ }
+ k.time += lt;
+ st.selected_keys.push(crate::KeyRef { layer: *lid, prop: pr.uid, time: k.time });
+ effectcraft_keyframe::set_key(&mut pr.keys, k);
+ n += 1;
+ }
+ }
+ }
+ Ok(n)
+ })?;
+ Ok(json!({"keys": n}))
+}
+
+fn paste_links(s: &mut Session, clip: LinkClip) -> Result<Value> {
+ let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
+ let ids = s.state.selected_layers.clone();
+ if ids.is_empty() {
+ return Err(EngineError::Other("select a layer to paste into".into()));
+ }
+ let pairs: Vec<(String, Expression)> = match clip {
+ LinkClip::Links { links, .. } => links.into_iter().map(|(p, e)| (p, Expression { text: e, enabled: true })).collect(),
+ LinkClip::Expressions(v) => v,
+ };
+ let n = s.edit("Paste", None, |proj, _| {
+ let mut n = 0;
+ for lid in &ids {
+ let l = super::layer_mut(proj, cid, *lid)?;
+ for (path, e) in &pairs {
+ if let Some(pr) = l.props.prop_mut(path) {
+ pr.expr = Some(e.clone());
+ n += 1;
+ }
+ }
+ }
+ Ok(n)
+ })?;
+ Ok(json!({"expressions": n}))
+}
+
fn cut(s: &mut Session, p: &Value) -> Result<Value> {
+ if !s.state.selected_keys.is_empty() && p.get("layers").is_none() {
+ s.execute("keys.copy", json!({}))?;
+ return s.execute("keys.delete", json!({}));
+ }
copy(s, p)?;
delete(s, p)
}
fn paste(s: &mut Session, p: &Value) -> Result<Value> {
+ if let Some(clip) = s.state.link_clipboard.clone() {
+ return paste_links(s, clip);
+ }
- if !s.state.key_clipboard.is_empty() {
- return paste_keys(s, false);
+ if s.state.clip_is_keys && !s.state.key_clipboard.is_empty() {
+ return s.execute("keys.paste", p.clone());
}
let cid = super::comp_id(s, p)?;
let clip = s.state.clipboard.clone();
@@@ -523,34 -207,12 +515,34 @@@ pub fn specs() -> Vec<CommandSpec>
vec![
cmd!("edit.undo", "Undo", ["Edit"], Some("Cmd+Z"), "{}", can_undo, undo),
cmd!("edit.redo", "Redo", ["Edit"], Some("Cmd+Shift+Z"), "{}", can_redo, redo),
- cmd!("edit.cut", "Cut", ["Edit"], Some("Cmd+X"), "{layers?}", has_layers, cut),
- cmd!("edit.copy", "Copy", ["Edit"], Some("Cmd+C"), "{layers?} (copies the selected keyframes when any, else layers)", has_props_or_layers, copy),
+ cmd!("edit.cut", "Cut", ["Edit"], Some("Cmd+X"), "{layers?} (keyframes when keys are selected)", layers_or_keys, cut),
+ cmd!("edit.copy", "Copy", ["Edit"], Some("Cmd+C"), "{layers?} (keyframes when keys are selected)", layers_or_keys, copy),
- cmd!("edit.paste", "Paste", ["Edit"], Some("Cmd+V"), "{}", has_clip, paste),
+ cmd!(
+ "edit.copyWithPropertyLinks",
+ "Copy with Property Links",
+ ["Edit"],
+ Some("Cmd+Alt+C"),
+ "{layers?} (selected properties, or layers, as expressions linking to the originals)",
+ has_props_or_layers,
+ |s, p| copy_links(s, p, false)
+ ),
+ cmd!(
+ "edit.copyWithRelativePropertyLinks",
+ "Copy with Relative Property Links",
+ ["Edit"],
+ None,
+ "{layers?} (like Copy with Property Links, using thisComp)",
+ has_props_or_layers,
+ |s, p| copy_links(s, p, true)
+ ),
+ cmd!("edit.copyExpressionOnly", "Copy Expression Only", ["Edit"], None, "{}", has_props_or_layers, copy_expression_only),
+ cmd!("edit.paste", "Paste", ["Edit"], Some("Cmd+V"), "{} (layers, keyframes at the CTI, or property links / expressions)", has_clip, paste),
+ cmd!("edit.pasteReversedKeyframes", "Paste Reversed Keyframes", ["Edit"], None, "{}", has_key_clip, paste_reversed),
- cmd!("edit.clear", "Clear", ["Edit"], Some("Delete"), "{layers?}", has_layers, delete),
+ cmd!("edit.clear", "Clear", ["Edit"], Some("Delete"), "{layers?}", layers_or_keys, delete),
cmd!("edit.duplicate", "Duplicate", ["Edit"], Some("Cmd+D"), "{layers?}", has_layers, duplicate),
cmd!("edit.splitLayer", "Split Layer", ["Edit"], Some("Cmd+Shift+D"), "{layers?}", has_layers, split),
+ cmd!("edit.liftWorkArea", "Lift Work Area", ["Edit"], None, "{layers?}", has_comp, lift),
+ cmd!("edit.extractWorkArea", "Extract Work Area", ["Edit"], None, "{layers?}", has_comp, extract),
cmd!("edit.selectAll", "Select All", ["Edit"], Some("Cmd+A"), "{}", has_comp, select_all),
cmd!("edit.deselectAll", "Deselect All", ["Edit"], Some("Cmd+Shift+A"), "{}", always_ok, deselect_all),
cmd!("edit.label", "Label", ["Edit", "Label"], None, "{label: Red|Yellow|Aqua|…, layers?}", always_ok, label),
diff --cc crates/engine/src/commands/layer.rs
index b20b9c824,94559f83c..5d9e6a38b
--- a/crates/engine/src/commands/layer.rs
+++ b/crates/engine/src/commands/layer.rs
@@@ -865,9 -942,7 +942,7 @@@ fn with_layer(p: &Value, lid: LayerId)
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("layer.newText", "Text", ["Layer", "New"], Some("Cmd+Alt+Shift+T"), "{text?, size?, font?, fill?, position? [x,y], justify?}", has_comp, new_text),
- cmd!("layer.newSolid", "Solid…", ["Layer", "New"], Some("Cmd+Y"), "{name?, color? #hex|[r,g,b], width?, height?}", has_comp, new_solid),
+ cmd!("layer.newSolid", "Solid...", ["Layer", "New"], Some("Cmd+Y"), "{name?, color? #hex|[r,g,b], width?, height?}", has_comp, new_solid),
- cmd!("layer.newLight", "Light...", ["Layer", "New"], Some("Cmd+Alt+Shift+L"), "{kind?: Parallel|Spot|Point|Ambient}", has_comp, new_light),
- cmd!("layer.newCamera", "Camera...", ["Layer", "New"], Some("Cmd+Alt+Shift+C"), "{name?}", has_comp, new_camera),
cmd!("layer.newNull", "Null Object", ["Layer", "New"], Some("Cmd+Alt+Shift+Y"), "{name?}", has_comp, new_null),
cmd!(
"layer.newShape",
diff --cc crates/engine/src/commands/layer_menu.rs
index 117240b1e,000000000..f183e7a05
mode 100644,000000..100644
--- a/crates/engine/src/commands/layer_menu.rs
+++ b/crates/engine/src/commands/layer_menu.rs
@@@ -1,834 -1,0 +1,805 @@@
+//! Layer menu: quality / sampling / frame blending, switches, transform dialogs, masks on existing
+//! layers, markers, track matte shortcuts, open/reveal, and Keyframe Assistant ▸ Sequence Layers.
+
+use effectcraft_keyframe::{Keyframe, ShapePath, Value as KV};
- use effectcraft_project::{
- AutoOrient, FrameBlend, GroupKind, ItemId, LayerId, LayerSource, Marker, MaskMode, MatteKind, Node, Quality, Sampling, TrackMatte, Uid,
- };
++use effectcraft_project::{FrameBlend, GroupKind, ItemId, LayerId, LayerSource, Marker, MaskMode, MatteKind, Node, Quality, Sampling, TrackMatte, Uid};
+use effectcraft_time::Tick;
+use serde_json::{Value, json};
+
+use super::{CommandSpec, b_p, bad, comp_id, f_p, frontend, has_comp, has_layers, layer_mut, layer_p, layers_p, merge_p, str_p};
+use crate::{EngineError, Result, Session, cmd};
+
+// ---------------------------------------------------------------- enablement
+
+fn has_masks(s: &Session) -> std::result::Result<(), String> {
+ has_layers(s)?;
+ let c = s.active_comp().ok_or("no composition")?;
+ let any = s.state.selected_layers.iter().filter_map(|l| c.layer(*l)).any(|l| l.masks().is_some_and(|m| !m.children.is_empty()));
+ if any { Ok(()) } else { Err("the selected layers have no masks".into()) }
+}
+
+fn has_markers(s: &Session) -> std::result::Result<(), String> {
+ has_layers(s)?;
+ let c = s.active_comp().ok_or("no composition")?;
+ if s.state.selected_layers.iter().filter_map(|l| c.layer(*l)).any(|l| !l.markers.is_empty()) {
+ Ok(())
+ } else {
+ Err("the selected layers have no markers".into())
+ }
+}
+
+fn has_source_item(s: &Session) -> std::result::Result<(), String> {
+ has_layers(s)?;
+ let c = s.active_comp().ok_or("no composition")?;
+ if s.state.selected_layers.iter().filter_map(|l| c.layer(*l)).any(|l| l.source.item().is_some()) {
+ Ok(())
+ } else {
+ Err("the selected layer has no source item".into())
+ }
+}
+
+fn has_footage_layer(s: &Session) -> std::result::Result<(), String> {
+ has_layers(s)?;
+ let c = s.active_comp().ok_or("no composition")?;
+ let any = s.state.selected_layers.iter().filter_map(|l| c.layer(*l)).any(|l| matches!(l.source, LayerSource::Footage { .. }));
+ if any { Ok(()) } else { Err("select a footage layer".into()) }
+}
+
+fn has_multiple_layers(s: &Session) -> std::result::Result<(), String> {
+ has_comp(s)?;
+ if s.state.selected_layers.len() >= 2 { Ok(()) } else { Err("select two or more layers".into()) }
+}
+
+// ---------------------------------------------------------------- quality / sampling / blending
+
+fn quality(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, ids) = layers_p(s, p)?;
+ let q = match str_p(p, "quality").unwrap_or("best").to_ascii_lowercase().as_str() {
+ "best" => Quality::Best,
+ "draft" => Quality::Draft,
+ "wireframe" => Quality::Wireframe,
+ q => return Err(bad("layer.quality", format!("quality must be best|draft|wireframe, not `{q}`"))),
+ };
+ s.edit("Layer Quality", None, |proj, _| {
+ for l in proj.comp_mut(cid).ok_or(EngineError::NoComp)?.layers.iter_mut().filter(|l| ids.contains(&l.id)) {
+ l.switches.quality = q;
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+fn sampling(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, ids) = layers_p(s, p)?;
+ let q = match str_p(p, "sampling").unwrap_or("bilinear").to_ascii_lowercase().as_str() {
+ "bilinear" => Sampling::Bilinear,
+ "bicubic" => Sampling::Bicubic,
+ q => return Err(bad("layer.sampling", format!("sampling must be bilinear|bicubic, not `{q}`"))),
+ };
+ s.edit("Layer Sampling", None, |proj, _| {
+ for l in proj.comp_mut(cid).ok_or(EngineError::NoComp)?.layers.iter_mut().filter(|l| ids.contains(&l.id)) {
+ l.switches.sampling = q;
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+fn frame_blending(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, ids) = layers_p(s, p)?;
+ let m = match str_p(p, "mode").unwrap_or("off") {
+ "off" => FrameBlend::Off,
+ "frameMix" => FrameBlend::FrameMix,
+ "pixelMotion" => FrameBlend::PixelMotion,
+ m => return Err(bad("layer.frameBlending", format!("mode must be off|frameMix|pixelMotion, not `{m}`"))),
+ };
+ s.edit("Frame Blending", None, |proj, _| {
+ for l in proj.comp_mut(cid).ok_or(EngineError::NoComp)?.layers.iter_mut().filter(|l| ids.contains(&l.id)) {
+ l.switches.frame_blend = m;
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+// ---------------------------------------------------------------- switches
+
+fn hide_other_video(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, ids) = layers_p(s, p)?;
+ s.edit("Hide Other Video", None, |proj, _| {
+ for l in proj.comp_mut(cid).ok_or(EngineError::NoComp)?.layers.iter_mut() {
+ if !ids.contains(&l.id) && l.source.is_av() {
+ l.switches.video = false;
+ }
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+fn show_all_video(s: &mut Session, p: &Value) -> Result<Value> {
+ let cid = comp_id(s, p)?;
+ s.edit("Show All Video", None, |proj, _| {
+ let c = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
+ // Track mattes stay hidden (their video switch is off by design).
+ let mattes: Vec<LayerId> = c.layers.iter().filter_map(|l| l.track_matte.map(|m| m.layer)).collect();
+ for l in c.layers.iter_mut().filter(|l| !mattes.contains(&l.id)) {
+ l.switches.video = true;
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+fn unlock_all(s: &mut Session, p: &Value) -> Result<Value> {
+ let cid = comp_id(s, p)?;
+ s.edit("Unlock All Layers", None, |proj, _| {
+ for l in proj.comp_mut(cid).ok_or(EngineError::NoComp)?.layers.iter_mut() {
+ l.switches.locked = false;
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+fn expressions(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, ids) = layers_p(s, p)?;
+ let on = b_p(p, "enabled").unwrap_or(true);
+ let n = s.edit(if on { "Enable Expressions" } else { "Disable Expressions" }, None, |proj, _| {
+ let mut n = 0;
+ for l in proj.comp_mut(cid).ok_or(EngineError::NoComp)?.layers.iter_mut().filter(|l| ids.contains(&l.id)) {
+ l.props.walk_mut(&mut |pr| {
+ if let Some(e) = &mut pr.expr {
+ e.enabled = on;
+ n += 1;
+ }
+ });
+ }
+ Ok(n)
+ })?;
+ Ok(json!({"expressions": n}))
+}
+
+// ---------------------------------------------------------------- transform
+
+fn transform_member(prop: &str) -> Option<&'static str> {
+ Some(match prop {
+ "anchor" | "anchorPoint" => "anchor",
+ "position" => "position",
+ "scale" => "scale",
+ "orientation" => "orientation",
+ "rotation" => "rotation",
+ "opacity" => "opacity",
+ _ => return None,
+ })
+}
+
+fn set_transform(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, ids) = layers_p(s, p)?;
+ let prop = str_p(p, "prop").ok_or_else(|| bad("layer.setTransform", "missing `prop`"))?;
+ let m = transform_member(prop).ok_or_else(|| bad("layer.setTransform", "prop: anchor|position|scale|orientation|rotation|opacity"))?;
+ let v = p.get("value").ok_or_else(|| bad("layer.setTransform", "missing `value`"))?.clone();
+ let t = s.time();
+ let label = match m {
+ "anchor" => "Anchor Point",
+ "position" => "Position",
+ "scale" => "Scale",
+ "orientation" => "Orientation",
+ "rotation" => "Rotation",
+ _ => "Opacity",
+ };
+ s.edit(label, merge_p(p), |proj, _| {
+ for lid in &ids {
+ let l = layer_mut(proj, cid, *lid)?;
+ let lt = l.layer_time(t);
+ let Some(pr) = l.transform_mut().and_then(|tr| tr.get_mut(m)) else { continue };
+ let cur = pr.value_at(lt);
+ // Two numbers for a 3D value keep the current z.
+ let j = match (&cur, &v) {
+ (KV::Vec3(c), Value::Array(a)) if a.len() == 2 => json!([a[0], a[1], c[2]]),
+ _ => v.clone(),
+ };
+ let nv = cur.coerce_json(&j).ok_or_else(|| bad("layer.setTransform", format!("can't use {v} for {label}")))?;
+ pr.set_value_at(lt, nv);
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+fn center_anchor(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, ids) = layers_p(s, p)?;
+ let t = s.time();
+ let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
+ let ctx = effectcraft_render::EvalCtx::new(&s.project, cid, comp, t);
+ let mut centers = vec![];
+ for lid in &ids {
+ let Some(l) = comp.layer(*lid) else { continue };
+ if let Some([x0, y0, x1, y1]) = effectcraft_render::content_bounds(&ctx, l) {
+ centers.push((*lid, [(x0 + x1) / 2.0, (y0 + y1) / 2.0]));
+ }
+ }
+ s.edit("Center Anchor Point", None, |proj, _| {
+ for (lid, c) in &centers {
+ let l = layer_mut(proj, cid, *lid)?;
+ let lt = l.layer_time(t);
+ let Some(tr) = l.transform_mut() else { continue };
+ let get = |tr: &effectcraft_project::PropGroup, m: &str, d: [f64; 3]| tr.get(m).map(|p| p.value_at(lt).as_vec3()).unwrap_or(d);
+ let anchor = get(tr, "anchor", [0.0; 3]);
+ let scale = get(tr, "scale", [100.0; 3]);
+ let rot = tr.get("rotation").map(|p| p.value_at(lt).as_f64()).unwrap_or(0.0).to_radians();
+ let (dx, dy) = ((c[0] - anchor[0]) * scale[0] / 100.0, (c[1] - anchor[1]) * scale[1] / 100.0);
+ let (sn, cs) = rot.sin_cos();
+ let shift = [dx * cs - dy * sn, dx * sn + dy * cs];
+ if let Some(a) = tr.get_mut("anchor") {
+ a.set_value_at(lt, KV::Vec3([c[0], c[1], anchor[2]]));
+ }
+ if let Some(pos) = tr.get_mut("position") {
+ // Shift every key so the layer stays put over its whole animation.
+ if pos.keys.is_empty() {
+ let v = pos.value.as_vec3();
+ pos.value = KV::Vec3([v[0] + shift[0], v[1] + shift[1], v[2]]);
+ } else {
+ for k in &mut pos.keys {
+ let v = k.value.as_vec3();
+ k.value = KV::Vec3([v[0] + shift[0], v[1] + shift[1], v[2]]);
+ }
+ }
+ }
+ }
+ Ok(())
+ })?;
+ Ok(json!({"layers": centers.len()}))
+}
+
- fn auto_orient(s: &mut Session, p: &Value) -> Result<Value> {
- let (cid, ids) = layers_p(s, p)?;
- let mode = match str_p(p, "mode").ok_or_else(|| bad("layer.autoOrient", "missing `mode`"))? {
- "off" => AutoOrient::Off,
- "alongPath" => AutoOrient::AlongPath,
- "towardsCamera" => AutoOrient::TowardsCamera,
- "towardsPointOfInterest" => AutoOrient::TowardsPointOfInterest,
- m => return Err(bad("layer.autoOrient", format!("mode: off|alongPath|towardsCamera|towardsPointOfInterest, not `{m}`"))),
- };
- s.edit("Auto-Orient", None, |proj, _| {
- for l in proj.comp_mut(cid).ok_or(EngineError::NoComp)?.layers.iter_mut().filter(|l| ids.contains(&l.id)) {
- l.auto_orient = mode;
- }
- Ok(())
- })?;
- Ok(Value::Null)
- }
-
+// ---------------------------------------------------------------- masks
+
+/// Masks the command applies to: `mask` (index / uid / name) on `layer`, else selected masks,
+/// else every mask of the selected layers.
+fn target_masks(s: &Session, p: &Value) -> Result<(ItemId, Vec<(LayerId, Uid)>)> {
+ let (cid, ids) = layers_p(s, p)?;
+ let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
+ let mut out = vec![];
+ if let Some(m) = p.get("mask") {
+ for lid in &ids {
+ let Some(masks) = comp.layer(*lid).and_then(|l| l.masks()) else { continue };
+ let g = match m {
+ Value::Number(n) => {
+ let n = n.as_u64().unwrap_or(1);
+ masks.children.iter().find(|c| c.uid() == n).or_else(|| masks.children.get(n.saturating_sub(1) as usize))
+ }
+ Value::String(name) => masks.children.iter().find(|c| c.name() == name),
+ _ => None,
+ };
+ if let Some(g) = g {
+ out.push((*lid, g.uid()));
+ }
+ }
+ return Ok((cid, out));
+ }
+ for (lid, uid) in &s.state.selected_props {
+ let Some(masks) = comp.layer(*lid).and_then(|l| l.masks()) else { continue };
+ for g in masks.groups() {
+ if g.uid == *uid || g.find(*uid).is_some() {
+ out.push((*lid, g.uid));
+ }
+ }
+ }
+ if out.is_empty() {
+ for lid in &ids {
+ if let Some(masks) = comp.layer(*lid).and_then(|l| l.masks()) {
+ out.extend(masks.groups().map(|g| (*lid, g.uid)));
+ }
+ }
+ }
+ out.dedup();
+ Ok((cid, out))
+}
+
+fn edit_masks(
+ s: &mut Session,
+ p: &Value,
+ label: &str,
+ mut f: impl FnMut(&mut effectcraft_project::PropGroup, (f64, f64), Tick) -> Result<()>,
+) -> Result<Value> {
+ let (cid, targets) = target_masks(s, p)?;
+ if targets.is_empty() {
+ return Err(EngineError::Other("no masks".into()));
+ }
+ let t = s.time();
+ let sizes: Vec<(LayerId, (f64, f64))> = targets
+ .iter()
+ .filter_map(|(lid, _)| s.project.comp(cid)?.layer(*lid).map(|l| (*lid, effectcraft_render::source_size(&s.project, l))))
+ .map(|(l, (w, h))| (l, (w as f64, h as f64)))
+ .collect();
+ let n = targets.len();
+ s.edit(label, merge_p(p), |proj, _| {
+ for (lid, uid) in &targets {
+ let size = sizes.iter().find(|(l, _)| l == lid).map(|x| x.1).unwrap_or((0.0, 0.0));
+ let l = layer_mut(proj, cid, *lid)?;
+ let lt = l.layer_time(t);
+ let Some(g) = l.props.sub_mut("masks").and_then(|m| m.find_group_mut(*uid)) else { continue };
+ f(g, size, lt)?;
+ }
+ Ok(())
+ })?;
+ Ok(json!({"masks": n}))
+}
+
+fn mask_kind(g: &mut effectcraft_project::PropGroup) -> Option<(&mut MaskMode, &mut bool, &mut bool)> {
+ match &mut g.kind {
+ GroupKind::Mask { mode, inverted, locked, .. } => Some((mode, inverted, locked)),
+ _ => None,
+ }
+}
+
+fn mask_set(s: &mut Session, p: &Value) -> Result<Value> {
+ let field = str_p(p, "field").ok_or_else(|| bad("layer.mask.set", "missing `field` (feather|opacity|expansion)"))?.to_string();
+ if !matches!(field.as_str(), "feather" | "opacity" | "expansion") {
+ return Err(bad("layer.mask.set", "field: feather|opacity|expansion"));
+ }
+ let v = p.get("value").ok_or_else(|| bad("layer.mask.set", "missing `value`"))?.clone();
+ let label = match field.as_str() {
+ "feather" => "Mask Feather",
+ "opacity" => "Mask Opacity",
+ _ => "Mask Expansion",
+ };
+ edit_masks(s, p, label, |g, _, lt| {
+ let pr = g.get_mut(&field).ok_or_else(|| bad("layer.mask.set", "mask has no such property"))?;
+ let cur = pr.value_at(lt);
+ let j = match (&cur, &v) {
+ (KV::Vec2(_), Value::Number(n)) => json!([n, n]),
+ _ => v.clone(),
+ };
+ let nv = cur.coerce_json(&j).ok_or_else(|| bad("layer.mask.set", format!("can't use {v} for {label}")))?;
+ pr.set_value_at(lt, nv);
+ Ok(())
+ })
+}
+
+fn mask_shape(s: &mut Session, p: &Value) -> Result<Value> {
+ let r = p.get("rect").and_then(Value::as_array).filter(|a| a.len() == 4).map(|a| [0, 1, 2, 3].map(|i| a[i].as_f64().unwrap_or(0.0)));
+ let r = r.ok_or_else(|| bad("layer.mask.shape", "missing `rect` [left, top, width, height] (layer px)"))?;
+ let ellipse = str_p(p, "shape") == Some("ellipse");
+ edit_masks(s, p, "Mask Shape", |g, _, lt| {
+ let (cx, cy) = (r[0] + r[2] / 2.0, r[1] + r[3] / 2.0);
+ let path = if ellipse { ShapePath::ellipse([cx, cy], r[2], r[3]) } else { ShapePath::rect([cx, cy], r[2], r[3]) };
+ if let Some(pr) = g.get_mut("path") {
+ pr.set_value_at(lt, KV::Path(path));
+ }
+ Ok(())
+ })
+}
+
+fn mask_reset(s: &mut Session, p: &Value) -> Result<Value> {
+ edit_masks(s, p, "Reset Mask", |g, (w, h), _| {
+ let (w, h) = if w > 0.0 { (w, h) } else { (400.0, 300.0) };
+ let reset = |g: &mut effectcraft_project::PropGroup, m: &str, v: KV| {
+ if let Some(pr) = g.get_mut(m) {
+ pr.keys.clear();
+ pr.expr = None;
+ pr.value = v;
+ }
+ };
+ reset(g, "path", KV::Path(ShapePath::rect([w / 2.0, h / 2.0], w, h)));
+ reset(g, "feather", KV::Vec2([0.0, 0.0]));
+ reset(g, "opacity", KV::Scalar(100.0));
+ reset(g, "expansion", KV::Scalar(0.0));
+ if let Some((mode, inv, _)) = mask_kind(g) {
+ *mode = MaskMode::Add;
+ *inv = false;
+ }
+ Ok(())
+ })
+}
+
+fn mask_remove(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, targets) = target_masks(s, p)?;
+ // Without an explicit `mask`, Remove Mask only removes selected masks (AE), else the first.
+ let selected: Vec<(LayerId, Uid)> = targets
+ .iter()
+ .copied()
+ .filter(|(l, u)| {
+ p.get("mask").is_some()
+ || s.state.selected_props.iter().any(|(sl, su)| {
+ sl == l
+ && (su == u || s.active_comp().and_then(|c| c.layer(*l)).and_then(|ly| ly.props.find_group(*u)).is_some_and(|g| g.find(*su).is_some()))
+ })
+ })
+ .collect();
+ let remove = if selected.is_empty() { targets.into_iter().take(1).collect() } else { selected };
+ remove_masks(s, cid, remove, "Remove Mask")
+}
+
+fn remove_masks(s: &mut Session, cid: ItemId, remove: Vec<(LayerId, Uid)>, label: &str) -> Result<Value> {
+ let n = remove.len();
+ s.edit(label, None, |proj, st| {
+ for (lid, uid) in &remove {
+ if let Some(m) = layer_mut(proj, cid, *lid)?.props.sub_mut("masks") {
+ m.children.retain(|c| c.uid() != *uid);
+ }
+ }
+ st.selected_props.retain(|(l, u)| !remove.iter().any(|(rl, ru)| rl == l && ru == u));
+ Ok(())
+ })?;
+ Ok(json!({"removed": n}))
+}
+
+fn mask_remove_all(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, ids) = layers_p(s, p)?;
+ let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
+ let all: Vec<(LayerId, Uid)> =
+ ids.iter().filter_map(|l| comp.layer(*l)).flat_map(|l| l.masks().into_iter().flat_map(|m| m.groups().map(|g| (l.id, g.uid)))).collect();
+ remove_masks(s, cid, all, "Remove All Masks")
+}
+
+fn mask_mode(s: &mut Session, p: &Value) -> Result<Value> {
+ let m =
+ str_p(p, "mode").and_then(MaskMode::from_name).ok_or_else(|| bad("layer.mask.mode", "mode: None|Add|Subtract|Intersect|Lighten|Darken|Difference"))?;
+ edit_masks(s, p, "Mask Mode", |g, _, _| {
+ if let Some((mode, ..)) = mask_kind(g) {
+ *mode = m;
+ }
+ Ok(())
+ })
+}
+
+fn mask_invert(s: &mut Session, p: &Value) -> Result<Value> {
+ let v = b_p(p, "value");
+ edit_masks(s, p, "Mask Inverted", |g, _, _| {
+ if let Some((_, inv, _)) = mask_kind(g) {
+ *inv = v.unwrap_or(!*inv);
+ }
+ Ok(())
+ })
+}
+
+fn mask_lock(s: &mut Session, p: &Value) -> Result<Value> {
+ let v = b_p(p, "value");
+ edit_masks(s, p, "Mask Locked", |g, _, _| {
+ if let Some((_, _, locked)) = mask_kind(g) {
+ *locked = v.unwrap_or(!*locked);
+ }
+ Ok(())
+ })
+}
+
+fn mask_unlock_all(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, ids) = layers_p(s, p)?;
+ s.edit("Unlock All Masks", None, |proj, _| {
+ for lid in &ids {
+ if let Some(m) = layer_mut(proj, cid, *lid)?.props.sub_mut("masks") {
+ for c in &mut m.children {
+ if let Node::Group(g) = c
+ && let Some((_, _, locked)) = mask_kind(g)
+ {
+ *locked = false;
+ }
+ }
+ }
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+fn mask_lock_others(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, keep) = target_masks(s, p)?;
+ let layers: Vec<LayerId> = keep.iter().map(|(l, _)| *l).collect();
+ s.edit("Lock Other Masks", None, |proj, _| {
+ for lid in &layers {
+ if let Some(m) = layer_mut(proj, cid, *lid)?.props.sub_mut("masks") {
+ for c in &mut m.children {
+ let uid = c.uid();
+ if let Node::Group(g) = c
+ && let Some((_, _, locked)) = mask_kind(g)
+ {
+ *locked = !keep.contains(&(*lid, uid));
+ }
+ }
+ }
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+// ---------------------------------------------------------------- markers
+
+fn add_marker(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, ids) = layers_p(s, p)?;
+ if ids.is_empty() {
+ return Err(bad("layer.addMarker", "no layer"));
+ }
+ let t = f_p(p, "time").map(Tick::from_seconds_f64).unwrap_or(s.time());
+ let comment = str_p(p, "comment").unwrap_or_default().to_string();
+ s.edit("Add Marker", None, |proj, _| {
+ for lid in &ids {
+ let l = layer_mut(proj, cid, *lid)?;
+ if l.markers_locked {
+ continue;
+ }
+ // Layer markers are stored in layer time.
+ let lt = l.layer_time(t);
+ l.markers.retain(|m| m.time != lt);
+ l.markers.push(Marker { time: lt, comment: comment.clone(), ..Default::default() });
+ l.markers.sort_by_key(|m| m.time);
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+fn markers_lock(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, ids) = layers_p(s, p)?;
+ let v = b_p(p, "value");
+ let r = s.edit("Lock Markers", None, |proj, _| {
+ let c = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
+ let target = v.unwrap_or_else(|| !c.layers.iter().find(|l| ids.contains(&l.id)).is_some_and(|l| l.markers_locked));
+ for l in c.layers.iter_mut().filter(|l| ids.contains(&l.id)) {
+ l.markers_locked = target;
+ }
+ Ok(target)
+ })?;
+ Ok(json!(r))
+}
+
+fn delete_all_markers(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, ids) = layers_p(s, p)?;
+ s.edit("Delete All Markers", None, |proj, _| {
+ for l in proj.comp_mut(cid).ok_or(EngineError::NoComp)?.layers.iter_mut().filter(|l| ids.contains(&l.id) && !l.markers_locked) {
+ l.markers.clear();
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+// ---------------------------------------------------------------- track matte
+
+fn track_matte_op(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, ids) = layers_p(s, p)?;
+ let op = str_p(p, "op").ok_or_else(|| bad("layer.trackMatte", "missing `op`"))?.to_string();
+ let kind = match op.as_str() {
+ "alpha" => Some(MatteKind::Alpha),
+ "alphaInverted" => Some(MatteKind::AlphaInverted),
+ "luma" => Some(MatteKind::Luma),
+ "lumaInverted" => Some(MatteKind::LumaInverted),
+ "none" | "above" | "below" => None,
+ o => return Err(bad("layer.trackMatte", format!("op: none|alpha|alphaInverted|luma|lumaInverted|above|below, not `{o}`"))),
+ };
+ s.edit("Track Matte", None, |proj, _| {
+ let c = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
+ let order: Vec<LayerId> = c.layers.iter().map(|l| l.id).collect();
+ let mut hide = vec![];
+ for lid in &ids {
+ let i = order.iter().position(|x| x == lid).unwrap_or(0);
+ let l = c.layer_mut(*lid).ok_or(EngineError::NoComp)?;
+ let cur_kind = l.track_matte.map(|m| m.kind).unwrap_or_default();
+ l.track_matte = match op.as_str() {
+ "none" => None,
+ "above" | "below" => {
+ let j = if op == "above" { i.checked_sub(1) } else { Some(i + 1) };
+ match j.and_then(|j| order.get(j)) {
+ Some(m) => Some(TrackMatte { layer: *m, kind: cur_kind }),
+ None => return Err(bad("layer.trackMatte", format!("there is no layer {op}"))),
+ }
+ }
+ _ => match (l.track_matte, i.checked_sub(1).and_then(|j| order.get(j))) {
+ (Some(m), _) => Some(TrackMatte { layer: m.layer, kind: kind.unwrap_or_default() }),
+ (None, Some(above)) => Some(TrackMatte { layer: *above, kind: kind.unwrap_or_default() }),
+ (None, None) => return Err(bad("layer.trackMatte", "the top layer has no layer above to use as a matte")),
+ },
+ };
+ if let Some(m) = l.track_matte {
+ hide.push(m.layer);
+ }
+ }
+ for m in hide {
+ if let Some(ml) = c.layer_mut(m) {
+ ml.switches.video = false;
+ }
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+// ---------------------------------------------------------------- open / reveal
+
+fn source_item(s: &Session, p: &Value, cmd: &str) -> Result<ItemId> {
+ let (cid, lid) = layer_p(s, p, cmd)?;
+ s.project.comp(cid).and_then(|c| c.layer(lid)).and_then(|l| l.source.item()).ok_or_else(|| bad(cmd, "the layer has no source item"))
+}
+
+fn open_source(s: &mut Session, p: &Value) -> Result<Value> {
+ let item = source_item(s, p, "layer.openSource")?;
+ if s.project.comp(item).is_some() {
+ s.open_comp(item);
+ return Ok(json!({"comp": item.0}));
+ }
+ frontend(s, "window.panel", &json!({"panel": "layer"}))
+}
+
+/// Folder containing a file as a `file://` URL.
+pub(crate) fn folder_url(path: &str) -> String {
+ let dir = std::path::Path::new(path).parent().map(|d| d.to_string_lossy().to_string()).unwrap_or_default();
+ format!("file://{dir}")
+}
+
+fn reveal_in_finder(s: &mut Session, p: &Value) -> Result<Value> {
+ let item = source_item(s, p, "layer.revealInFinder")?;
+ let path = match s.project.item(item).map(|i| &i.kind) {
+ Some(effectcraft_project::ItemKind::Footage(f)) if !f.path.is_empty() => f.path.clone(),
+ _ => return Err(bad("layer.revealInFinder", "the layer's source is not a file")),
+ };
+ let url = folder_url(&path);
+ s.events.push(crate::Event::OpenUrl(url.clone()));
+ Ok(json!({"url": url}))
+}
+
+fn reveal_source(s: &mut Session, p: &Value) -> Result<Value> {
+ let item = source_item(s, p, "layer.revealSource")?;
+ s.state.project_selection = vec![item];
+ frontend(s, "window.panel", &json!({"panel": "project"}))?;
+ Ok(json!({"item": item.0}))
+}
+
+fn reveal_comp(s: &mut Session, p: &Value) -> Result<Value> {
+ let cid = comp_id(s, p)?;
+ s.state.project_selection = vec![cid];
+ frontend(s, "window.panel", &json!({"panel": "project"}))?;
+ Ok(json!({"item": cid.0}))
+}
+
+fn reveal_expression_errors(s: &mut Session, p: &Value) -> Result<Value> {
+ let cid = comp_id(s, p)?;
+ let t = s.time();
+ let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
+ let mut errors = vec![];
+ for l in &comp.layers {
+ let mut has = vec![];
+ l.props.walk("", &mut |_, pr| {
+ if pr.has_expression() {
+ has.push(pr);
+ }
+ });
+ for pr in has {
+ let text = pr.expr.as_ref().map(|e| e.text.clone()).unwrap_or_default();
+ let err = match &s.expr {
+ Some(host) => {
+ let mut ctx = effectcraft_render::EvalCtx::new(&s.project, cid, comp, t);
+ ctx.expr = Some(host.as_ref());
+ host.eval(&ctx, l, pr, &pr.value_at(l.layer_time(t))).err()
+ }
+ None => None,
+ };
+ if let Some(e) = err {
+ errors.push(json!({"layer": l.id.0, "prop": pr.uid, "name": pr.name, "expression": text, "error": e}));
+ }
+ }
+ }
+ let props: Vec<Value> = errors.iter().map(|e| json!({"layer": e["layer"], "prop": e["prop"]})).collect();
+ frontend(s, "timeline.revealProps", &json!({"props": props}))?;
+ if errors.is_empty() {
+ s.toast("No expression errors");
+ }
+ Ok(json!({"errors": errors}))
+}
+
+// ---------------------------------------------------------------- sequence layers
+
+fn sequence(s: &mut Session, p: &Value) -> Result<Value> {
+ let cid = comp_id(s, p)?;
+ // Selection order (AE sequences in the order layers were selected).
+ let ids: Vec<LayerId> = match p.get("layers") {
+ Some(_) => layers_p(s, p)?.1,
+ None => s.state.selected_layers.clone(),
+ };
+ if ids.len() < 2 {
+ return Err(bad("layer.sequence", "select two or more layers"));
+ }
+ let overlap = b_p(p, "overlap").unwrap_or(false);
+ let dur = if overlap { Tick::from_seconds_f64(f_p(p, "duration").unwrap_or(1.0)) } else { Tick::ZERO };
+ let transition = str_p(p, "transition").unwrap_or("off").to_string();
+ s.edit("Sequence Layers", None, |proj, _| {
+ let c = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
+ let mut next: Option<Tick> = None;
+ for (k, lid) in ids.iter().enumerate() {
+ let l = c.layer_mut(*lid).ok_or(EngineError::NoComp)?;
+ if let Some(at) = next {
+ let d = at - l.in_point;
+ l.start_time += d;
+ l.in_point += d;
+ l.out_point += d;
+ }
+ if overlap && transition != "off" {
+ let (a, b) = (l.layer_time(l.in_point), l.layer_time(l.in_point + dur));
+ let (oa, ob) = (l.layer_time(l.out_point - dur), l.layer_time(l.out_point));
+ let last = k + 1 == ids.len();
+ if let Some(op) = l.transform_mut().and_then(|tr| tr.get_mut("opacity")) {
+ op.keys.clear();
+ if k > 0 {
+ op.keys.push(Keyframe::new(a, KV::Scalar(0.0)));
+ op.keys.push(Keyframe::new(b, KV::Scalar(100.0)));
+ }
+ if transition == "crossDissolve" && !last {
+ op.keys.push(Keyframe::new(oa, KV::Scalar(100.0)));
+ op.keys.push(Keyframe::new(ob, KV::Scalar(0.0)));
+ }
+ op.keys.sort_by_key(|k| k.time);
+ op.keys.dedup_by_key(|k| k.time);
+ }
+ }
+ next = Some(l.out_point - dur);
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ cmd!("layer.quality", "Quality", [], None, "{layers?, quality: best|draft|wireframe}", has_layers, quality),
+ cmd!("layer.sampling", "Sampling", [], None, "{layers?, sampling: bilinear|bicubic}", has_layers, sampling),
+ cmd!("layer.frameBlending", "Frame Blending", [], None, "{layers?, mode: off|frameMix|pixelMotion}", has_layers, frame_blending),
+ cmd!("layer.hideOtherVideo", "Hide Other Video", ["Layer", "Switches"], Some("Cmd+Alt+Shift+V"), "{layers?}", has_layers, hide_other_video),
+ cmd!("layer.showAllVideo", "Show All Video", ["Layer", "Switches"], None, "{comp?}", has_comp, show_all_video),
+ cmd!("layer.unlockAll", "Unlock All Layers", ["Layer", "Switches"], Some("Cmd+Shift+L"), "{comp?}", has_comp, unlock_all),
+ cmd!("layer.expressions", "Enable/Disable Expressions", [], None, "{layers?, enabled: bool}", has_layers, expressions),
+ cmd!(
+ "layer.setTransform",
+ "Transform Value",
+ [],
+ None,
+ "{layers?, prop: anchor|position|scale|orientation|rotation|opacity, value}",
+ has_layers,
+ set_transform
+ ),
+ cmd!(
+ "layer.centerAnchor",
+ "Center Anchor Point in Layer Content",
+ ["Layer", "Transform"],
+ Some("Cmd+Alt+Home"),
+ "{layers?}",
+ has_layers,
+ center_anchor
+ ),
- cmd!(
- "layer.autoOrient",
- "Auto-Orient...",
- ["Layer", "Transform"],
- Some("Cmd+Alt+O"),
- "{layers?, mode: off|alongPath|towardsCamera|towardsPointOfInterest}",
- has_layers,
- auto_orient
- ),
+ cmd!(
+ "layer.mask.shape",
+ "Mask Shape...",
+ ["Layer", "Mask"],
+ Some("Cmd+Shift+M"),
+ "{layer?, mask?, rect: [x, y, w, h], shape?: rect|ellipse}",
+ has_masks,
+ mask_shape
+ ),
+ cmd!("layer.mask.set", "Mask Settings", [], None, "{layer?, mask?, field: feather|opacity|expansion, value}", has_masks, mask_set),
+ cmd!("layer.mask.reset", "Reset Mask", ["Layer", "Mask"], None, "{layer?, mask?}", has_masks, mask_reset),
+ cmd!("layer.mask.remove", "Remove Mask", ["Layer", "Mask"], None, "{layer?, mask?}", has_masks, mask_remove),
+ cmd!("layer.mask.removeAll", "Remove All Masks", ["Layer", "Mask"], None, "{layers?}", has_masks, mask_remove_all),
+ cmd!("layer.mask.mode", "Mask Mode", [], None, "{layer?, mask?, mode: None|Add|Subtract|Intersect|Lighten|Darken|Difference}", has_masks, mask_mode),
+ cmd!("layer.mask.invert", "Inverted", ["Layer", "Mask"], Some("Cmd+Shift+I"), "{layer?, mask?, value?}", has_masks, mask_invert),
+ cmd!("layer.mask.lock", "Locked", ["Layer", "Mask"], None, "{layer?, mask?, value?}", has_masks, mask_lock),
+ cmd!("layer.mask.unlockAll", "Unlock All Masks", ["Layer", "Mask"], None, "{layers?}", has_masks, mask_unlock_all),
+ cmd!("layer.mask.lockOthers", "Lock Other Masks", ["Layer", "Mask"], None, "{layer?, mask?}", has_masks, mask_lock_others),
+ cmd!("layer.addMarker", "Add Marker", ["Layer", "Markers"], None, "{layers?, time?, comment?}", has_layers, add_marker),
+ cmd!("layer.markersLock", "Lock Markers", ["Layer", "Markers"], None, "{layers?, value?}", has_layers, markers_lock),
+ cmd!("layer.deleteAllMarkers", "Delete All Markers", ["Layer", "Markers"], None, "{layers?}", has_markers, delete_all_markers),
+ cmd!("layer.trackMatte", "Track Matte", [], None, "{layers?, op: none|alpha|alphaInverted|luma|lumaInverted|above|below}", has_layers, track_matte_op),
+ cmd!("layer.openSource", "Open Layer Source", ["Layer"], None, "{layer?}", has_source_item, open_source),
+ cmd!("layer.revealInFinder", "Reveal in Finder", ["Layer"], None, "{layer?}", has_footage_layer, reveal_in_finder),
+ cmd!("layer.revealSource", "Reveal Layer Source in Project", ["Layer", "Reveal"], None, "{layer?}", has_source_item, reveal_source),
+ cmd!("comp.revealInProject", "Reveal Composition in Project", ["Layer", "Reveal"], None, "{comp?}", has_comp, reveal_comp),
+ cmd!("layer.revealExpressionErrors", "Reveal Expression Errors", ["Layer", "Reveal"], None, "{comp?}", has_comp, reveal_expression_errors),
+ cmd!(
+ "layer.sequence",
+ "Sequence Layers...",
+ ["Animation", "Keyframe Assistant"],
+ None,
+ "{layers? (in order), overlap?: bool, duration? (s), transition?: off|dissolveFront|crossDissolve}",
+ has_multiple_layers,
+ sequence
+ ),
+ ]
+}
diff --cc crates/engine/src/commands/layer_time.rs
index 000000000,2bc031aac..d8090352f
mode 000000,100644..100644
--- a/crates/engine/src/commands/layer_time.rs
+++ b/crates/engine/src/commands/layer_time.rs
@@@ -1,0 -1,188 +1,188 @@@
+ //! Layer ▸ Time: Time Stretch, Time-Reverse Layer, Enable Time Remapping, Freeze Frame and
+ //! Freeze on Last Frame.
+ //!
+ //! Time Remap is a `timeRemap` property at the top of the layer's tree whose value is the
+ //! source time (seconds) to show; its keys live in layer time like every other property.
+
+ use effectcraft_keyframe::{Keyframe, Value as KV};
+ use effectcraft_project::build::Ids;
+ use effectcraft_project::{Layer, LayerSource, Node, ParamUi, Property};
+ use effectcraft_time::Tick;
+ use serde_json::{Value, json};
+
+ use super::{CommandSpec, b_p, bad, f_p, has_layers, layers_p, str_p};
+ use crate::{EngineError, Result, Session, cmd};
+
+ /// Layers whose source has its own time (precomps and footage) can be remapped.
+ fn remappable(l: &Layer) -> bool {
+ matches!(l.source, LayerSource::Comp { .. } | LayerSource::Footage { .. })
+ }
+
+ fn time_stretch(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, ids) = layers_p(s, p)?;
+ let reverse = str_p(p, "op") == Some("reverse");
+ let pct = f_p(p, "percent");
+ let dur = f_p(p, "duration");
+ let hold = str_p(p, "hold").unwrap_or("in").to_string();
+ let cti = s.time();
+ let comp_rate = s.project.comp(cid).ok_or(EngineError::NoComp)?.frame_rate;
+ let fd = comp_rate.frame_duration();
+ s.edit(if reverse { "Time-Reverse Layer" } else { "Time Stretch" }, None, |proj, _| {
+ let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
+ for l in comp.layers.iter_mut().filter(|l| ids.contains(&l.id)) {
+ let old = l.stretch;
+ if reverse {
+ // Keep the in/out points; play the visible span backwards.
+ let last = l.layer_time(l.out_point - fd);
+ l.stretch = -old;
+ l.start_time = l.in_point - Tick((last.0 as f64 * l.stretch / 100.0).round() as i64);
+ continue;
+ }
+ let span = (l.out_point - l.in_point).seconds();
+ let new = match (pct, dur) {
+ (Some(v), _) => v,
+ (None, Some(d)) if span > 0.0 => old * d / span,
+ _ => old,
+ };
+ if new.abs() < 1.0 {
+ return Err(bad("layer.timeStretch", "the stretch factor must be at least 1 %"));
+ }
+ // The hold point keeps showing the same layer time.
+ let h = match hold.as_str() {
+ "current" => cti,
+ "out" => l.out_point,
+ _ => l.in_point,
+ };
+ let lt_h = l.layer_time(h);
+ let (lin, lout) = (l.layer_time(l.in_point), l.layer_time(l.out_point));
+ l.stretch = new;
+ l.start_time = h - Tick((lt_h.0 as f64 * new / 100.0).round() as i64);
+ let (a, b) = (l.comp_time(lin), l.comp_time(lout));
+ let fr = comp_rate;
+ l.in_point = fr.snap_nearest(a.min(b));
+ l.out_point = fr.snap_nearest(a.max(b)).max(l.in_point + fr.frame_duration());
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+ }
+
+ fn remap_prop(ids: &mut Ids) -> Property {
+ let mut p = ids.prop("timeRemap", "Time Remap", KV::Scalar(0.0)).with_ui(ParamUi::Number);
+ p.ui = ParamUi::Number;
+ p
+ }
+
+ /// Source time (seconds) a layer shows at comp time `t` without remapping.
+ fn source_secs(l: &Layer, t: Tick) -> f64 {
+ l.layer_time(t).seconds()
+ }
+
+ fn enable_time_remap(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, ids) = layers_p(s, p)?;
+ let want = b_p(p, "value");
+ let fd = s.project.comp(cid).ok_or(EngineError::NoComp)?.frame_duration();
+ let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
+ if !comp.layers.iter().filter(|l| ids.contains(&l.id)).any(remappable) {
+ return Err(bad("layer.enableTimeRemap", "time remapping needs a footage or composition layer"));
+ }
+ let on = s.edit("Enable Time Remapping", None, |proj, _| {
+ let mut next = proj.next_id;
+ let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
+ let mut on = false;
+ for l in comp.layers.iter_mut().filter(|l| ids.contains(&l.id) && remappable(l)) {
+ let has = l.props.get("timeRemap").is_some();
+ let target = want.unwrap_or(!has);
+ on |= target;
+ if target && !has {
+ let mut pr = remap_prop(&mut Ids(&mut next));
+ let (lin, lout) = (l.layer_time(l.in_point), l.layer_time(l.out_point));
+ let (a, b) = (lin.min(lout), lin.max(lout));
+ pr.value = KV::Scalar(source_secs(l, l.in_point));
+ pr.keys = vec![Keyframe::new(a, KV::Scalar(a.seconds())), Keyframe::new(b, KV::Scalar(b.seconds()))];
+ if lin > lout {
+ // Reversed layers keep showing what they showed.
+ pr.keys[0].value = KV::Scalar(source_secs(l, l.out_point - fd));
+ pr.keys[1].value = KV::Scalar(source_secs(l, l.in_point));
+ }
+ l.props.children.insert(0, Node::Prop(pr));
+ } else if !target && has {
+ l.props.children.retain(|c| c.match_id() != "timeRemap");
+ }
+ }
+ proj.next_id = next;
+ Ok(on)
+ })?;
+ Ok(json!(on))
+ }
+
+ /// Freeze Frame: time remapping holding the current source frame for the whole layer.
+ fn freeze(s: &mut Session, p: &Value, last: bool) -> Result<Value> {
+ let (cid, ids) = layers_p(s, p)?;
+ let cti = s.time();
+ let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
+ let (fd, cdur) = (comp.frame_duration(), comp.duration);
+ if !comp.layers.iter().filter(|l| ids.contains(&l.id)).any(remappable) {
+ return Err(bad("layer.freezeFrame", "freezing needs a footage or composition layer"));
+ }
+ // What each layer shows now (honouring an existing remap) — evaluated before the edit.
+ let ectx = effectcraft_render::EvalCtx { project: &s.project, comp_id: cid, comp, time: cti, expr: s.expr.as_deref() };
+ let now: Vec<(effectcraft_project::LayerId, f64)> = comp
+ .layers
+ .iter()
+ .filter(|l| ids.contains(&l.id) && remappable(l))
+ .map(|l| {
+ let at = if last { ectx.at(l.out_point - fd) } else { ectx };
+ (l.id, at.source_time(l).seconds())
+ })
+ .collect();
- s.edit(if last { "Freeze on Last Frame" } else { "Freeze Frame" }, None, |proj, _| {
++ s.edit(if last { "Freeze On Last Frame" } else { "Freeze Frame" }, None, |proj, _| {
+ let mut next = proj.next_id;
+ let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
+ for (lid, src) in &now {
+ let Some(l) = comp.layer_mut(*lid) else { continue };
+ if l.props.get("timeRemap").is_none() {
+ l.props.children.insert(0, Node::Prop(remap_prop(&mut Ids(&mut next))));
+ }
+ let lt = if last { l.layer_time(l.out_point - fd) } else { l.layer_time(cti) };
+ let lin = l.layer_time(l.in_point);
+ let pr = l.props.get_mut("timeRemap").ok_or(EngineError::NoComp)?;
+ pr.value = KV::Scalar(*src);
+ if last {
+ // Play normally up to the last frame, then hold it to the end of the comp.
+ let mut end = Keyframe::new(lt.max(lin), KV::Scalar(*src));
+ end.out_interp = effectcraft_keyframe::Interp::Hold;
+ pr.keys = vec![Keyframe::new(lin.min(lt), KV::Scalar(lin.min(lt).seconds())), end];
+ pr.keys.dedup_by_key(|k| k.time);
+ l.out_point = cdur;
+ } else {
+ pr.keys = vec![Keyframe::new(lt, KV::Scalar(*src)).hold()];
+ }
+ }
+ proj.next_id = next;
+ Ok(())
+ })?;
+ Ok(Value::Null)
+ }
+
+ pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ cmd!(
+ "layer.timeStretch",
- "Time Stretch…",
++ "Time Stretch...",
+ ["Layer", "Time"],
+ None,
+ "{layers?, percent?|duration? (s), hold?: in|current|out, op?: reverse}",
+ has_layers,
+ time_stretch
+ ),
+ cmd!("layer.timeReverse", "Time-Reverse Layer", ["Layer", "Time"], Some("Cmd+Alt+R"), "{layers?}", has_layers, |s, p| {
+ let mut p = p.clone();
+ p["op"] = json!("reverse");
+ time_stretch(s, &p)
+ }),
+ cmd!("layer.enableTimeRemap", "Enable Time Remapping", ["Layer", "Time"], Some("Cmd+Alt+T"), "{layers?, value?}", has_layers, enable_time_remap),
+ cmd!("layer.freezeFrame", "Freeze Frame", ["Layer", "Time"], None, "{layers?}", has_layers, |s, p| freeze(s, p, false)),
- cmd!("layer.freezeOnLastFrame", "Freeze on Last Frame", ["Layer", "Time"], None, "{layers?}", has_layers, |s, p| freeze(s, p, true)),
++ cmd!("layer.freezeOnLastFrame", "Freeze On Last Frame", ["Layer", "Time"], None, "{layers?}", has_layers, |s, p| freeze(s, p, true)),
+ ]
+ }
diff --cc crates/engine/src/commands/mask.rs
index 000000000,9387055b3..617346c1d
mode 000000,100644..100644
--- a/crates/engine/src/commands/mask.rs
+++ b/crates/engine/src/commands/mask.rs
@@@ -1,0 -1,260 +1,260 @@@
+ //! Masks drawn and edited in the viewer: Pen tool (new mask, add vertex, Bezier tangents, close
+ //! path), vertex selection, moving and deleting vertices, and Layer ▸ Mask ▸ Remove (All).
+ //!
+ //! Coordinates are in layer space. Edits of an animated Mask Path set a key at the current time.
+
+ use effectcraft_keyframe::{ShapePath, Value as KV};
+ use effectcraft_project::build::{self, Ids};
+ use effectcraft_project::{Layer, MaskMode, PropGroup, Uid};
+ use serde_json::{Value, json};
+
+ use super::{CommandSpec, b_p, bad, has_comp, has_layers, layer_mut, layer_p, merge_p, resolve_layer, str_p};
+ use crate::{EngineError, Result, Session, VertexRef, cmd};
+
+ fn pt(v: Option<&Value>) -> Option<[f64; 2]> {
+ let a = v?.as_array()?;
+ Some([a.first()?.as_f64()?, a.get(1)?.as_f64()?])
+ }
+
+ fn pts(v: Option<&Value>) -> Vec<[f64; 2]> {
+ v.and_then(Value::as_array).map(|a| a.iter().filter_map(|p| pt(Some(p))).collect()).unwrap_or_default()
+ }
+
+ /// Find a mask group by uid, 1-based index or name.
+ fn find_mask<'a>(masks: &'a mut PropGroup, key: &Value) -> Option<&'a mut PropGroup> {
+ let i = match key {
+ Value::Number(n) => {
+ let n = n.as_u64()?;
+ masks.children.iter().position(|c| c.uid() == n).or_else(|| (n as usize).checked_sub(1).filter(|i| *i < masks.children.len()))?
+ }
+ Value::String(s) => masks.children.iter().position(|c| c.name() == s)?,
+ _ => return None,
+ };
+ masks.children.get_mut(i)?.as_group_mut()
+ }
+
+ /// Edit the mask path of (layer, mask) at the current time.
+ fn edit_path<T>(s: &mut Session, p: &Value, label: &str, f: impl FnOnce(&mut ShapePath) -> Result<T>) -> Result<(Uid, T)> {
+ let (cid, lid) = layer_p(s, p, label)?;
+ let key = p.get("mask").cloned().ok_or_else(|| bad(label, "missing `mask` (uid, index or name)"))?;
+ let t = s.time();
+ s.edit(label, merge_p(p), |proj, _| {
+ let l = layer_mut(proj, cid, lid)?;
+ let lt = l.layer_time(t);
+ let masks = l.props.sub_mut("masks").ok_or_else(|| bad(label, "this layer has no masks"))?;
+ let g = find_mask(masks, &key).ok_or_else(|| bad(label, "no such mask"))?;
+ let uid = g.uid;
+ let pr = g.get_mut("path").ok_or_else(|| bad(label, "mask has no path"))?;
+ let KV::Path(mut sp) = pr.value_at(lt) else { return Err(bad(label, "not a path")) };
+ let r = f(&mut sp)?;
+ pr.set_value_at(lt, KV::Path(sp));
+ Ok((uid, r))
+ })
+ }
+
+ /// Pen tool: a new (open by default) mask from points.
+ fn new_mask(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, lid) = layer_p(s, p, "mask.new")?;
+ let v = pts(p.get("vertices"));
+ if v.is_empty() {
+ return Err(bad("mask.new", "need `vertices` [[x,y], …] in layer space"));
+ }
+ let n = v.len();
+ let mut ins = pts(p.get("inTangents"));
+ let mut outs = pts(p.get("outTangents"));
+ ins.resize(n, [0.0; 2]);
+ outs.resize(n, [0.0; 2]);
+ let path = ShapePath { vertices: v, in_tangents: ins, out_tangents: outs, closed: b_p(p, "closed").unwrap_or(false) };
+ let mode = str_p(p, "mode").and_then(MaskMode::from_name).unwrap_or(MaskMode::Add);
+ let uid = s.edit("New Mask", None, |proj, st| {
+ let mut next = proj.next_id;
+ let l = layer_mut(proj, cid, lid)?;
+ let masks = l.props.sub_mut("masks").ok_or_else(|| bad("mask.new", "this layer can't have masks"))?;
+ let k = masks.children.len();
+ let g = build::mask(&mut Ids(&mut next), &format!("Mask {}", k + 1), path, mode, build::MASK_COLORS[k % build::MASK_COLORS.len()]);
+ let uid = g.uid;
+ masks.children.push(g.into());
+ proj.next_id = next;
+ st.selected_vertices = vec![VertexRef { layer: lid, mask: uid, index: n - 1 }];
+ Ok(uid)
+ })?;
+ Ok(json!({"mask": uid}))
+ }
+
+ fn add_vertex(s: &mut Session, p: &Value) -> Result<Value> {
+ let point = pt(p.get("point")).ok_or_else(|| bad("mask.addVertex", "missing `point` [x,y]"))?;
+ let tin = pt(p.get("in")).unwrap_or([0.0; 2]);
+ let tout = pt(p.get("out")).unwrap_or([0.0; 2]);
+ let at = p.get("index").and_then(Value::as_u64).map(|i| i as usize);
+ let (_, lid) = layer_p(s, p, "mask.addVertex")?;
+ let (uid, i) = edit_path(s, p, "mask.addVertex", |sp| {
+ let i = at.unwrap_or(sp.vertices.len()).min(sp.vertices.len());
+ sp.vertices.insert(i, point);
+ sp.in_tangents.insert(i, tin);
+ sp.out_tangents.insert(i, tout);
+ Ok(i)
+ })?;
+ s.state.selected_vertices = vec![VertexRef { layer: lid, mask: uid, index: i }];
+ Ok(json!(i))
+ }
+
+ fn set_vertex(s: &mut Session, p: &Value) -> Result<Value> {
+ let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad("mask.setVertex", "missing `index`"))? as usize;
+ let (point, tin, tout) = (pt(p.get("point")), pt(p.get("in")), pt(p.get("out")));
+ edit_path(s, p, "mask.setVertex", |sp| {
+ if i >= sp.vertices.len() {
+ return Err(bad("mask.setVertex", "no such vertex"));
+ }
+ if let Some(v) = point {
+ sp.vertices[i] = v;
+ }
+ if let Some(v) = tin {
+ sp.in_tangents[i] = v;
+ }
+ if let Some(v) = tout {
+ sp.out_tangents[i] = v;
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+ }
+
+ fn set_closed(s: &mut Session, p: &Value) -> Result<Value> {
+ let c = b_p(p, "closed").unwrap_or(true);
+ edit_path(s, p, "mask.setClosed", |sp| {
+ sp.closed = c;
+ Ok(())
+ })?;
+ Ok(json!(c))
+ }
+
+ /// Selected (or given) vertices grouped per (layer, mask).
+ fn vertex_groups(s: &Session, p: &Value) -> Result<std::collections::BTreeMap<(u64, Uid), Vec<usize>>> {
+ let comp = s.active_comp().ok_or(EngineError::NoComp)?;
+ let mut g: std::collections::BTreeMap<(u64, Uid), Vec<usize>> = Default::default();
+ if let Some(Value::Array(a)) = p.get("vertices") {
+ for v in a {
+ let l = v.get("layer").and_then(|x| resolve_layer(comp, x)).ok_or_else(|| bad("mask", "vertex needs `layer`"))?;
+ let m = v.get("mask").and_then(Value::as_u64).ok_or_else(|| bad("mask", "vertex needs `mask` uid"))?;
+ let i = v.get("index").and_then(Value::as_u64).ok_or_else(|| bad("mask", "vertex needs `index`"))?;
+ g.entry((l.0, m)).or_default().push(i as usize);
+ }
+ } else {
+ for v in &s.state.selected_vertices {
+ g.entry((v.layer.0, v.mask)).or_default().push(v.index);
+ }
+ }
+ Ok(g)
+ }
+
+ fn select_vertices(s: &mut Session, p: &Value) -> Result<Value> {
+ let g = vertex_groups(s, &json!({"vertices": p.get("vertices").cloned().unwrap_or(json!([]))}))?;
+ let sel: Vec<VertexRef> =
+ g.into_iter().flat_map(|((l, m), is)| is.into_iter().map(move |i| VertexRef { layer: effectcraft_project::LayerId(l), mask: m, index: i })).collect();
+ if b_p(p, "add").unwrap_or(false) {
+ for v in sel {
+ if let Some(i) = s.state.selected_vertices.iter().position(|x| *x == v) {
+ if b_p(p, "toggle").unwrap_or(false) {
+ s.state.selected_vertices.remove(i);
+ }
+ } else {
+ s.state.selected_vertices.push(v);
+ }
+ }
+ } else {
+ s.state.selected_vertices = sel;
+ }
+ Ok(json!(s.state.selected_vertices.len()))
+ }
+
+ fn has_vertices(s: &Session) -> std::result::Result<(), String> {
+ has_comp(s)?;
+ if s.state.selected_vertices.is_empty() { Err("select mask vertices first".into()) } else { Ok(()) }
+ }
+
+ /// Apply `f` to the selected vertices' paths (each mask once).
+ fn edit_vertices(s: &mut Session, p: &Value, label: &str, f: impl Fn(&mut ShapePath, &[usize])) -> Result<Value> {
+ let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
+ let groups = vertex_groups(s, p)?;
+ let t = s.time();
+ s.edit(label, merge_p(p), |proj, _| {
+ let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
+ for ((l, m), idx) in &groups {
+ let Some(layer) = comp.layer_mut(effectcraft_project::LayerId(*l)) else { continue };
+ let lt = layer.layer_time(t);
+ let Some(pr) = layer.props.sub_mut("masks").and_then(|ms| ms.find_group_mut(*m)).and_then(|g| g.get_mut("path")) else { continue };
+ let KV::Path(mut sp) = pr.value_at(lt) else { continue };
+ f(&mut sp, idx);
+ pr.set_value_at(lt, KV::Path(sp));
+ }
+ Ok(())
+ })?;
+ Ok(json!(groups.values().map(Vec::len).sum::<usize>()))
+ }
+
+ fn move_vertices(s: &mut Session, p: &Value) -> Result<Value> {
+ let d = pt(p.get("delta")).ok_or_else(|| bad("mask.moveVertices", "missing `delta` [dx,dy] (layer space)"))?;
+ edit_vertices(s, p, "Move Mask Vertices", |sp, idx| {
+ for &i in idx {
+ if let Some(v) = sp.vertices.get_mut(i) {
+ v[0] += d[0];
+ v[1] += d[1];
+ }
+ }
+ })
+ }
+
+ fn delete_vertices(s: &mut Session, p: &Value) -> Result<Value> {
+ let n = edit_vertices(s, p, "Delete Mask Vertices", |sp, idx| {
+ let mut idx = idx.to_vec();
+ idx.sort_unstable();
+ idx.dedup();
+ for &i in idx.iter().rev() {
+ if i < sp.vertices.len() {
+ sp.vertices.remove(i);
+ sp.in_tangents.remove(i);
+ sp.out_tangents.remove(i);
+ }
+ }
+ if sp.vertices.len() < 3 {
+ sp.closed = false;
+ }
+ })?;
+ s.state.selected_vertices.clear();
+ Ok(n)
+ }
+
+ fn remove_masks(s: &mut Session, p: &Value, all: bool) -> Result<Value> {
+ let (cid, lid) = layer_p(s, p, "mask.remove")?;
+ let key = p.get("mask").cloned();
+ if !all && key.is_none() {
+ return Err(bad("mask.remove", "missing `mask`"));
+ }
+ s.edit(if all { "Remove All Masks" } else { "Remove Mask" }, None, |proj, st| {
+ let l: &mut Layer = layer_mut(proj, cid, lid)?;
+ let masks = l.props.sub_mut("masks").ok_or_else(|| bad("mask.remove", "this layer has no masks"))?;
+ if all {
+ masks.children.clear();
+ } else if let Some(k) = &key {
+ let uid = find_mask(masks, k).map(|g| g.uid).ok_or_else(|| bad("mask.remove", "no such mask"))?;
+ masks.children.retain(|c| c.uid() != uid);
+ }
+ st.selected_vertices.retain(|v| v.layer != lid);
+ Ok(())
+ })?;
+ Ok(Value::Null)
+ }
+
+ pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ cmd!("mask.new", "New Mask from Points", [], None, "{layer?, vertices: [[x,y]…], inTangents?, outTangents?, closed?, mode?}", has_layers, new_mask),
+ cmd!("mask.addVertex", "Add Mask Vertex", [], None, "{layer?, mask, point: [x,y], in?, out?, index?}", has_layers, add_vertex),
+ cmd!("mask.setVertex", "Set Mask Vertex", [], None, "{layer?, mask, index, point?, in?, out?, merge?}", has_layers, set_vertex),
+ cmd!("mask.setClosed", "Closed", ["Layer", "Mask and Shape Path"], None, "{layer?, mask, closed?}", has_layers, set_closed),
+ cmd!("mask.selectVertices", "Select Mask Vertices", [], None, "{vertices: [{layer, mask, index}], add?, toggle?}", has_comp, select_vertices),
+ cmd!("mask.moveVertices", "Move Mask Vertices", [], None, "{vertices?: [{layer, mask, index}], delta: [dx,dy], merge?}", has_vertices, move_vertices),
+ cmd!("mask.deleteVertices", "Delete Mask Vertices", [], None, "{vertices?}", has_vertices, delete_vertices),
- cmd!("mask.remove", "Remove Mask", ["Layer", "Mask"], None, "{layer?, mask}", has_layers, |s, p| remove_masks(s, p, false)),
- cmd!("mask.removeAll", "Remove All Masks", ["Layer", "Mask"], None, "{layer?}", has_layers, |s, p| remove_masks(s, p, true)),
++ cmd!("mask.remove", "Remove Mask", [], None, "{layer?, mask}", has_layers, |s, p| remove_masks(s, p, false)),
++ cmd!("mask.removeAll", "Remove All Masks", [], None, "{layer?}", has_layers, |s, p| remove_masks(s, p, true)),
+ ]
+ }
diff --cc crates/engine/src/commands/mod.rs
index 2553ef53a,4abdc7a8e..d5210b423
--- a/crates/engine/src/commands/mod.rs
+++ b/crates/engine/src/commands/mod.rs
@@@ -2,21 -2,20 +2,27 @@@
//! shortcut and viewer/timeline gesture maps to one of these.
mod anim;
++mod animation;
mod comp;
+mod comp_more;
mod edit;
mod effect;
mod file;
+mod file_more;
+mod frontend;
mod help;
mod layer;
+mod layer_menu;
+ mod layer_time;
+ mod link;
+ mod mask;
mod prop;
mod query;
+ mod render_queue;
+mod stubs;
+ mod three_d;
mod time;
+mod view;
use std::sync::OnceLock;
@@@ -75,18 -74,17 +81,24 @@@ pub fn command_specs() -> &'static [Com
v.extend(edit::specs());
v.extend(comp::specs());
v.extend(layer::specs());
+ v.extend(three_d::specs());
+ v.extend(layer_time::specs());
v.extend(prop::specs());
+ v.extend(anim::specs());
+ v.extend(link::specs());
+ v.extend(mask::specs());
v.extend(effect::specs());
v.extend(time::specs());
+ v.extend(render_queue::specs());
v.extend(help::specs());
v.extend(query::specs());
+ v.extend(layer_menu::specs());
- v.extend(anim::specs());
++ v.extend(animation::specs());
+ v.extend(view::specs());
+ v.extend(file_more::specs());
+ v.extend(comp_more::specs());
+ v.extend(frontend::specs());
+ v.extend(stubs::specs());
v
})
}
diff --cc crates/engine/src/commands/prop.rs
index df415537e,1c5313e4a..3164274c5
--- a/crates/engine/src/commands/prop.rs
+++ b/crates/engine/src/commands/prop.rs
@@@ -432,19 -590,19 +590,19 @@@ pub fn specs() -> Vec<CommandSpec>
cmd!("keys.toggleHold", "Toggle Hold Keyframe", ["Animation"], Some("Cmd+Alt+H"), "{}", has_keys, toggle_hold),
cmd!(
"keys.interpolation",
- "Keyframe Interpolation…",
+ "Keyframe Interpolation...",
["Animation"],
Some("Cmd+Alt+K"),
- "{interpolation?|in?|out?: linear|bezier|hold, autoBezier?}",
+ "{interpolation?: linear|bezier|continuousBezier|autoBezier|hold, in?|out?: linear|bezier|hold, autoBezier?, continuous?, spatial?: linear|bezier|continuousBezier|autoBezier, roving?}",
has_keys,
interpolation
),
cmd!(
"keys.velocity",
- "Keyframe Velocity…",
+ "Keyframe Velocity...",
["Animation"],
Some("Cmd+Shift+K"),
- "{inSpeed?, inInfluence? %, outSpeed?, outInfluence? %}",
+ "{inSpeed?, inInfluence? %, outSpeed?, outInfluence? % (numbers or per-dimension arrays), continuous?}",
has_keys,
velocity
),
diff --cc crates/engine/src/commands/render_queue.rs
index 000000000,10c44eb72..ecf01b35d
mode 000000,100644..100644
--- a/crates/engine/src/commands/render_queue.rs
+++ b/crates/engine/src/commands/render_queue.rs
@@@ -1,0 -1,428 +1,428 @@@
+ //! Render Queue: Composition ▸ Add to Render Queue, the queue's Render Settings / Output Module /
+ //! Output To, Render and Stop.
+ //!
+ //! Items are addressed by `item` (the stable id from `renderQueue.add` / `renderQueue.list`) or
+ //! `index` (1-based, the # column).
+
+ use effectcraft_project::render_queue::{
+ AudioOutput, Channels, OutputFormat, OutputModule, ProResProfile, RenderQuality, RenderQueueItem, RenderSettings, RenderStatus, TimeSpan,
+ };
+ use effectcraft_time::{FrameRate, Tick};
+ use serde_json::{Value, json};
+
+ use super::{CommandSpec, b_p, bad, f_p, str_p};
+ use crate::{EngineError, Result, Session, cmd, query};
+
+ fn can_add(s: &Session) -> std::result::Result<(), String> {
+ not_rendering(s)?;
+ if s.comp_for_queue(&Value::Null).is_some() { Ok(()) } else { Err("select or open a composition".into()) }
+ }
+ fn not_rendering(s: &Session) -> std::result::Result<(), String> {
+ if s.is_rendering() { Err("the render queue is rendering".into()) } else { Ok(()) }
+ }
+ fn has_items(s: &Session) -> std::result::Result<(), String> {
+ not_rendering(s)?;
+ if s.project.render_queue.is_empty() { Err("the render queue is empty".into()) } else { Ok(()) }
+ }
+ fn has_queued(s: &Session) -> std::result::Result<(), String> {
+ not_rendering(s)?;
+ if s.exporter.is_none() {
+ return Err("export is not available in this build".into());
+ }
+ if s.project.render_queue.iter().any(RenderQueueItem::is_queued) { Ok(()) } else { Err("nothing is queued".into()) }
+ }
+ fn rendering(s: &Session) -> std::result::Result<(), String> {
+ if s.is_rendering() { Ok(()) } else { Err("not rendering".into()) }
+ }
+
+ /// Index of the item named by `item` (id) or `index` (1-based).
+ fn item_index(s: &Session, p: &Value, cmd: &str) -> Result<usize> {
+ let q = &s.project.render_queue;
+ if let Some(id) = p.get("item").and_then(Value::as_u64) {
+ return q.iter().position(|i| i.id == id).ok_or_else(|| bad(cmd, format!("no render queue item {id}")));
+ }
+ if let Some(n) = p.get("index").and_then(Value::as_u64) {
+ return (n as usize).checked_sub(1).filter(|i| *i < q.len()).ok_or_else(|| bad(cmd, format!("no render queue item #{n}")));
+ }
+ if q.len() == 1 {
+ return Ok(0);
+ }
+ Err(bad(cmd, "pass `item` (id) or `index` (1-based)"))
+ }
+
+ fn time_p(p: &Value, k: &str) -> Option<Tick> {
+ f_p(p, k).map(Tick::from_seconds_f64)
+ }
+
+ /// Apply Render Settings parameters.
+ fn apply_settings(rs: &mut RenderSettings, p: &Value, cmd: &str) -> Result<bool> {
+ let mut any = false;
+ if let Some(q) = str_p(p, "quality") {
+ rs.quality = match q.to_ascii_lowercase().as_str() {
+ "best" => RenderQuality::Best,
+ "draft" => RenderQuality::Draft,
+ _ => return Err(bad(cmd, "quality: best|draft")),
+ };
+ any = true;
+ }
+ match p.get("resolution") {
+ Some(Value::String(r)) => {
+ rs.resolution = match r.to_ascii_lowercase().as_str() {
+ "full" => 1.0,
+ "half" => 0.5,
+ "third" => 1.0 / 3.0,
+ "quarter" => 0.25,
+ _ => return Err(bad(cmd, "resolution: full|half|third|quarter|<scale>")),
+ };
+ any = true;
+ }
+ Some(Value::Number(n)) => {
+ rs.resolution = n.as_f64().unwrap_or(1.0).clamp(0.01, 4.0);
+ any = true;
+ }
+ _ => {}
+ }
+ let (start, end) = (time_p(p, "start"), time_p(p, "end"));
+ if let Some(ts) = str_p(p, "timeSpan") {
+ rs.time_span = match ts.to_ascii_lowercase().replace([' ', '_', '-'], "").as_str() {
+ "workarea" | "workareaonly" => TimeSpan::WorkArea,
+ "comp" | "lengthofcomp" | "full" => TimeSpan::LengthOfComp,
+ "custom" => TimeSpan::Custom { start: start.unwrap_or(Tick::ZERO), end: end.unwrap_or(Tick::from_seconds_f64(1.0)) },
+ _ => return Err(bad(cmd, "timeSpan: workArea|comp|custom")),
+ };
+ any = true;
+ } else if start.is_some() || end.is_some() {
+ let (a, b) = match rs.time_span {
+ TimeSpan::Custom { start, end } => (start, end),
+ _ => (Tick::ZERO, Tick(i64::MAX / 4)),
+ };
+ rs.time_span = TimeSpan::Custom { start: start.unwrap_or(a), end: end.unwrap_or(b) };
+ any = true;
+ }
+ if let TimeSpan::Custom { start, end } = rs.time_span
+ && end <= start
+ {
+ return Err(bad(cmd, "end must be after start"));
+ }
+ match p.get("frameRate") {
+ Some(Value::Null) => {
+ rs.frame_rate = None;
+ any = true;
+ }
+ Some(v) => {
+ let f = v.as_f64().filter(|f| *f > 0.0 && *f <= 1000.0).ok_or_else(|| bad(cmd, "frameRate: fps > 0 or null (comp rate)"))?;
+ rs.frame_rate = Some(FrameRate::from_f64(f));
+ any = true;
+ }
+ None => {}
+ }
+ if let Some(b) = b_p(p, "motionBlur") {
+ rs.motion_blur = b;
+ any = true;
+ }
+ if let Some(b) = b_p(p, "skipExisting") {
+ rs.skip_existing = b;
+ any = true;
+ }
+ Ok(any)
+ }
+
+ /// Apply Output Module parameters.
+ fn apply_output(om: &mut OutputModule, p: &Value, cmd: &str) -> Result<bool> {
+ let mut any = false;
+ if let Some(f) = str_p(p, "format") {
+ let f = OutputFormat::from_name(f).ok_or_else(|| bad(cmd, "format: h264|prores|png|jpeg|tiff|exr|gif"))?;
+ om.set_format(f);
+ any = true;
+ }
+ if let Some(c) = str_p(p, "channels") {
+ om.channels = match c.to_ascii_lowercase().replace([' ', '+'], "").as_str() {
+ "rgb" => Channels::Rgb,
+ "rgba" | "rgbalpha" => Channels::Rgba,
+ _ => return Err(bad(cmd, "channels: rgb|rgba")),
+ };
+ if om.channels == Channels::Rgba && !om.format.supports_alpha() {
+ return Err(bad(cmd, format!("{} has no alpha channel", om.format.label())));
+ }
+ any = true;
+ }
+ if let Some(q) = f_p(p, "quality") {
+ om.quality = q.clamp(1.0, 100.0) as u8;
+ any = true;
+ }
+ if let Some(b) = f_p(p, "bitrate") {
+ om.bitrate_kbps = b.clamp(100.0, 500_000.0) as u32;
+ any = true;
+ }
+ if let Some(pp) = str_p(p, "proresProfile") {
+ om.prores_profile = ProResProfile::from_name(pp).ok_or_else(|| bad(cmd, "proresProfile: proxy|lt|standard|hq|4444|4444xq"))?;
+ any = true;
+ }
+ if let Some(a) = p.get("audio") {
+ om.audio = match a {
+ Value::Bool(true) => AudioOutput::On,
+ Value::Bool(false) => AudioOutput::Off,
+ Value::String(s) => match s.to_ascii_lowercase().as_str() {
+ "auto" => AudioOutput::Auto,
+ "on" => AudioOutput::On,
+ "off" => AudioOutput::Off,
+ _ => return Err(bad(cmd, "audio: auto|on|off")),
+ },
+ _ => return Err(bad(cmd, "audio: auto|on|off")),
+ };
+ any = true;
+ }
+ if let Some(r) = p.get("sampleRate").and_then(Value::as_u64) {
+ om.audio_sample_rate = (r as u32).clamp(8_000, 192_000);
+ any = true;
+ }
+ if let Some(l) = b_p(p, "loop") {
+ om.gif_loop = l;
+ any = true;
+ }
+ if let Some(o) = str_p(p, "output").or(str_p(p, "path")) {
+ om.output = o.to_string();
+ if p.get("format").is_none()
+ && let Some(f) = OutputFormat::from_path(o).filter(|f| *f != om.format && !o.contains("[fileExtension]"))
+ {
+ // `out.mov` with an H.264 module → ProRes, like picking a file type in Output To.
+ let keep = om.output.clone();
+ om.set_format(f);
+ om.output = keep;
+ }
+ any = true;
+ }
+ Ok(any)
+ }
+
+ /// A finished item that is edited goes back to Queued (AE re-queues on change).
+ fn requeue(it: &mut RenderQueueItem) {
+ if it.render && !matches!(it.status, RenderStatus::Rendering) {
+ it.status = RenderStatus::Queued;
+ }
+ }
+
+ fn item_json(s: &Session, it: &RenderQueueItem, index: usize) -> Value {
+ let comp = s.project.comp(it.comp);
+ let name = s.project.item(it.comp).map(|i| i.name.clone());
+ let (w, h) = comp.map(|c| it.settings.output_size(c)).map(|(w, h)| it.output.format.coded_size(w, h)).unwrap_or((0, 0));
+ let frames = comp.map(|c| it.settings.frame_count(c)).unwrap_or(0);
+ let mut v = serde_json::to_value(it).unwrap_or(Value::Null);
+ if let Some(o) = v.as_object_mut() {
+ o.insert("index".into(), json!(index + 1));
+ o.insert("compName".into(), json!(name));
+ o.insert("statusLabel".into(), json!(it.status.label()));
+ o.insert("outputPath".into(), json!(s.resolve_output(it)));
+ o.insert("renderSettingsSummary".into(), json!(it.settings.summary()));
+ o.insert("outputModuleSummary".into(), json!(it.output.summary()));
+ o.insert("width".into(), json!(w));
+ o.insert("height".into(), json!(h));
+ o.insert("frames".into(), json!(frames));
+ }
+ v
+ }
+
+ fn add(s: &mut Session, p: &Value) -> Result<Value> {
+ let cid = s.comp_for_queue(p).ok_or(EngineError::NoComp)?;
+ let mut it = RenderQueueItem::new(0, cid);
+ if let Some(f) = str_p(p, "format") {
+ let f = OutputFormat::from_name(f).ok_or_else(|| bad("renderQueue.add", "format: h264|prores|png|jpeg|tiff|exr|gif"))?;
+ it.output = OutputModule::for_format(f);
+ }
+ apply_settings(&mut it.settings, p, "renderQueue.add")?;
+ let mut op = p.clone();
+ if let Some(o) = op.as_object_mut() {
+ o.remove("format");
+ }
+ apply_output(&mut it.output, &op, "renderQueue.add")?;
+ let id = s.edit("Add to Render Queue", None, |proj, _| {
+ it.id = proj.render_queue.iter().map(|i| i.id).max().unwrap_or(0) + 1;
+ let id = it.id;
+ proj.render_queue.push(it);
+ Ok(id)
+ })?;
+ let idx = s.project.render_queue.len() - 1;
+ let mut v = item_json(s, &s.project.render_queue[idx], idx);
+ v["item"] = json!(id);
+ Ok(v)
+ }
+
+ fn remove(s: &mut Session, p: &Value) -> Result<Value> {
+ let i = item_index(s, p, "renderQueue.remove")?;
+ s.edit("Remove from Render Queue", None, |proj, _| {
+ proj.render_queue.remove(i);
+ Ok(())
+ })?;
+ Ok(json!({"remaining": s.project.render_queue.len()}))
+ }
+
+ fn set_render(s: &mut Session, p: &Value) -> Result<Value> {
+ let i = item_index(s, p, "renderQueue.setRender")?;
+ let on = b_p(p, "render").unwrap_or(!s.project.render_queue[i].render);
+ s.edit("Render Queue: Render", None, |proj, _| {
+ let it = &mut proj.render_queue[i];
+ it.render = on;
+ it.status = if on { RenderStatus::Queued } else { RenderStatus::Unqueued };
+ Ok(())
+ })?;
+ Ok(json!({"render": on}))
+ }
+
+ fn set_render_settings(s: &mut Session, p: &Value) -> Result<Value> {
+ let i = item_index(s, p, "renderQueue.setRenderSettings")?;
+ let mut rs = s.project.render_queue[i].settings.clone();
+ if !apply_settings(&mut rs, p, "renderQueue.setRenderSettings")? {
+ return Err(bad("renderQueue.setRenderSettings", "nothing to change"));
+ }
+ s.edit("Render Settings", None, |proj, _| {
+ let it = &mut proj.render_queue[i];
+ it.settings = rs;
+ requeue(it);
+ Ok(())
+ })?;
+ Ok(item_json(s, &s.project.render_queue[i], i))
+ }
+
+ fn set_output_module(s: &mut Session, p: &Value) -> Result<Value> {
+ let i = item_index(s, p, "renderQueue.setOutputModule")?;
+ let mut om = s.project.render_queue[i].output.clone();
+ if !apply_output(&mut om, p, "renderQueue.setOutputModule")? {
+ return Err(bad("renderQueue.setOutputModule", "nothing to change"));
+ }
+ s.edit("Output Module Settings", None, |proj, _| {
+ let it = &mut proj.render_queue[i];
+ it.output = om;
+ requeue(it);
+ Ok(())
+ })?;
+ Ok(item_json(s, &s.project.render_queue[i], i))
+ }
+
+ fn set_output(s: &mut Session, p: &Value) -> Result<Value> {
+ let i = item_index(s, p, "renderQueue.setOutput")?;
+ let path = str_p(p, "path").or(str_p(p, "output")).ok_or_else(|| bad("renderQueue.setOutput", "pass `path` (file path or template)"))?;
+ let mut om = s.project.render_queue[i].output.clone();
+ apply_output(&mut om, &json!({"output": path}), "renderQueue.setOutput")?;
+ s.edit("Output To", None, |proj, _| {
+ let it = &mut proj.render_queue[i];
+ it.output = om;
+ requeue(it);
+ Ok(())
+ })?;
+ Ok(item_json(s, &s.project.render_queue[i], i))
+ }
+
+ fn move_item(s: &mut Session, p: &Value) -> Result<Value> {
+ let i = item_index(s, p, "renderQueue.move")?;
+ let n = s.project.render_queue.len();
+ let to = p.get("to").and_then(Value::as_u64).ok_or_else(|| bad("renderQueue.move", "pass `to` (1-based position)"))? as usize;
+ let to = to.clamp(1, n) - 1;
+ s.edit("Reorder Render Queue", None, |proj, _| {
+ let it = proj.render_queue.remove(i);
+ proj.render_queue.insert(to, it);
+ Ok(())
+ })?;
+ Ok(json!({"index": to + 1}))
+ }
+
+ fn duplicate(s: &mut Session, p: &Value) -> Result<Value> {
+ let i = item_index(s, p, "renderQueue.duplicate")?;
+ let id = s.edit("Duplicate Render Item", None, |proj, _| {
+ let mut it = proj.render_queue[i].clone();
+ it.id = proj.render_queue.iter().map(|i| i.id).max().unwrap_or(0) + 1;
+ it.render = true;
+ it.status = RenderStatus::Queued;
+ it.started = None;
+ it.render_time = None;
+ it.last_output = None;
+ let id = it.id;
+ proj.render_queue.insert(i + 1, it);
+ Ok(id)
+ })?;
+ Ok(json!({"item": id, "index": i + 2}))
+ }
+
+ fn render(s: &mut Session, p: &Value) -> Result<Value> {
+ let wait = b_p(p, "wait").unwrap_or(true);
+ let ids = s.start_render(wait).map_err(EngineError::Other)?;
+ let items: Vec<Value> = s.project.render_queue.iter().enumerate().filter(|(_, i)| ids.contains(&i.id)).map(|(k, i)| item_json(s, i, k)).collect();
+ Ok(json!({"rendering": s.is_rendering(), "items": items}))
+ }
+
+ fn stop(s: &mut Session, _: &Value) -> Result<Value> {
+ Ok(json!({"stopped": s.stop_render()}))
+ }
+
+ fn list(s: &mut Session, _: &Value) -> Result<Value> {
+ s.poll_render();
+ let items: Vec<Value> = s.project.render_queue.iter().enumerate().map(|(k, i)| item_json(s, i, k)).collect();
+ Ok(json!({"items": items, "rendering": s.is_rendering(), "progress": s.render_progress()}))
+ }
+
+ fn formats(s: &mut Session, _: &Value) -> Result<Value> {
+ let avail = s.exporter.as_ref().map(|e| e.formats()).unwrap_or_default();
+ let v: Vec<Value> = OutputFormat::ALL
+ .iter()
+ .map(|f| {
+ json!({
+ "id": format!("{f:?}"),
+ "label": f.label(),
+ "extension": f.extension(),
+ "sequence": f.is_sequence(),
+ "alpha": f.supports_alpha(),
+ "audio": f.supports_audio(),
+ "available": avail.contains(f),
+ })
+ })
+ .collect();
+ Ok(json!({"formats": v, "proresProfiles": ProResProfile::ALL.iter().map(|p| p.label()).collect::<Vec<_>>()}))
+ }
+
+ pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ cmd!(
+ "renderQueue.add",
+ "Add to Render Queue",
+ ["Composition"],
+ Some("Cmd+M"),
+ "{comp?: id|name, format?: h264|prores|png|jpeg|tiff|exr|gif, output?: path|template, …renderSettings, …outputModule}",
+ can_add,
+ add
+ ),
+ cmd!("renderQueue.remove", "Remove from Render Queue", [], None, "{item?: id, index?: n}", has_items, remove),
+ cmd!("renderQueue.setRender", "Render Queue: Render Checkbox", [], None, "{item?|index?, render?: bool (toggles)}", has_items, set_render),
+ cmd!(
+ "renderQueue.setRenderSettings",
- "Render Settings…",
++ "Render Settings...",
+ [],
+ None,
+ "{item?|index?, quality?: best|draft, resolution?: full|half|third|quarter|scale, timeSpan?: workArea|comp|custom, start?: s, end?: s, frameRate?: fps|null, motionBlur?: bool, skipExisting?: bool}",
+ has_items,
+ set_render_settings
+ ),
+ cmd!(
+ "renderQueue.setOutputModule",
- "Output Module Settings…",
++ "Output Module Settings...",
+ [],
+ None,
+ "{item?|index?, format?, channels?: rgb|rgba, quality?: 1-100, bitrate?: kbps, proresProfile?: proxy|lt|standard|hq|4444|4444xq, audio?: auto|on|off, sampleRate?, loop?: bool, output?}",
+ has_items,
+ set_output_module
+ ),
+ cmd!(
+ "renderQueue.setOutput",
- "Output To…",
++ "Output To...",
+ [],
+ None,
+ "{item?|index?, path: file path or template like [compName].[fileExtension]}",
+ has_items,
+ set_output
+ ),
+ cmd!("renderQueue.move", "Move in Render Queue", [], None, "{item?|index?, to: n (1-based)}", has_items, move_item),
+ cmd!("renderQueue.duplicate", "Duplicate Render Item", [], None, "{item?|index?}", has_items, duplicate),
+ cmd!("renderQueue.render", "Render", [], None, "{wait?: bool (default true; the UI renders in the background)}", has_queued, render),
+ cmd!("renderQueue.stop", "Stop Rendering", [], None, "{}", rendering, stop),
+ query!("renderQueue.list", "Render Queue Items", "{}", list),
+ query!("renderQueue.formats", "Output Formats", "{}", formats),
+ ]
+ }
diff --cc crates/engine/src/commands/stubs.rs
index 7a0cccc4d,000000000..5b58bdaae
mode 100644,000000..100644
--- a/crates/engine/src/commands/stubs.rs
+++ b/crates/engine/src/commands/stubs.rs
@@@ -1,112 -1,0 +1,103 @@@
+//! Menu entries whose implementation is owned by another milestone (3D, render queue/export,
+//! time remapping, pen/mask-vertex editing, motion tracking, layer styles…) or that have no
+//! EffectCraft equivalent yet. They are registered so the menu bar matches After Effects, and are
+//! always disabled. When a feature lands, delete its line here and register the real command
+//! with the same id (the menu tree in `menus.rs` already points at it).
+
+use super::{CommandSpec, not_yet, not_yet_run};
+
+macro_rules! stub {
+ ($id:literal, $label:literal, [$($m:literal),*], $params:literal) => {
+ CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: None, params: $params, enabled: not_yet, run: not_yet_run, journal: true }
+ };
+ ($id:literal, $label:literal, [$($m:literal),*], $sc:literal, $params:literal) => {
+ CommandSpec { id: $id, label: $label, menu: &[$($m),*], shortcut: Some($sc), params: $params, enabled: not_yet, run: not_yet_run, journal: true }
+ };
+}
+
+pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ // macOS application menu items handled by the OS.
+ stub!("app.hideOthers", "Hide Others", [], "{}"),
+ stub!("app.showAll", "Show All", [], "{}"),
+ // Render queue / export (export milestone).
- stub!("render.addToQueue", "Add to Render Queue", ["Composition"], "Cmd+M", "{comp?}"),
+ stub!("render.addOutputModule", "Add Output Module", ["Composition"], "{}"),
+ stub!("render.preRender", "Pre-render...", ["Composition"], "{}"),
+ stub!("render.saveCurrentPreview", "Save Current Preview...", ["Composition"], "{path}"),
+ stub!("file.createProxy", "Create Proxy", [], "{kind: still|movie}"),
+ // Proxies (no proxy model yet).
+ stub!("file.setProxy", "File...", ["File", "Set Proxy"], "{path}"),
+ stub!("file.setProxyNone", "None", ["File", "Set Proxy"], "{}"),
+ stub!("file.interpretProxy", "Proxy...", ["File", "Interpret Footage"], "{}"),
+ // Text editing in the viewer.
+ stub!("edit.pasteTextMatchFormatting", "Paste Text and Match Formatting", ["Edit"], "{}"),
+ stub!("edit.pasteTextFormattingOnly", "Paste Text Formatting Only", ["Edit"], "{}"),
+ stub!("keys.selectLabelGroup", "Select Keyframe Label Group", [], "{scope}"),
+ // Preview audio.
+ stub!("playback.audio", "Audio", ["Composition", "Preview"], "{}"),
+ // Layer ▸ New (3D / content-aware fill).
+ stub!("layer.newContentAwareFill", "Content-Aware Fill Layer...", ["Layer", "New"], "{}"),
+ stub!("layer.new3dPrimitive", "3D Primitive", [], "{kind: cube|sphere|plane|torus|cone|cylinder}"),
+ // Mask options not in the mask model yet; pen / vertex editing (timeline milestone).
+ stub!("layer.mask.motionBlur", "Motion Blur", [], "{mode: sameAsLayer|on|off}"),
+ stub!("layer.mask.featherFalloff", "Feather Falloff", [], "{mode: smooth|linear}"),
+ stub!("layer.mask.hideLocked", "Hide Locked Masks", ["Layer", "Mask"], "{}"),
+ stub!("path.rotoBezier", "RotoBezier", ["Layer", "Mask and Shape Path"], "{}"),
- stub!("path.closed", "Closed", ["Layer", "Mask and Shape Path"], "{}"),
+ stub!("path.convertToBezier", "Convert To Bezier Path", ["Layer", "Mask and Shape Path"], "{}"),
+ stub!("path.groupShapes", "Group Shapes", ["Layer", "Mask and Shape Path"], "Cmd+G", "{}"),
+ stub!("path.ungroupShapes", "Ungroup Shapes", ["Layer", "Mask and Shape Path"], "Cmd+Shift+G", "{}"),
+ stub!("path.setFirstVertex", "Set First Vertex", ["Layer", "Mask and Shape Path"], "{}"),
+ stub!("path.freeTransform", "Free Transform Points", ["Layer", "Mask and Shape Path"], "{}"),
+ // Time (timeline milestone).
- stub!("layer.timeRemap", "Enable Time Remapping", ["Layer", "Time"], "Cmd+Alt+T", "{layers?}"),
- stub!("layer.freezeFrame", "Freeze Frame", ["Layer", "Time"], "{layers?}"),
- stub!("layer.freezeOnLastFrame", "Freeze On Last Frame", ["Layer", "Time"], "{layers?}"),
+ stub!("layer.alignVideoToData", "Align Video to Data", ["Layer", "Time"], "{}"),
+ stub!("layer.environment", "Environment Layer", ["Layer"], "{}"),
+ stub!("layer.updateMarkersFromSource", "Update Markers From Source", ["Layer", "Markers"], "{}"),
+ stub!("layer.styles", "Layer Styles", [], "{op?|style?}"),
+ stub!("layer.create", "Create", [], "{op}"),
+ stub!("layer.autoTrace", "Auto-trace...", ["Layer"], "{}"),
+ stub!("layer.sceneEditDetection", "Scene Edit Detection...", ["Layer"], "{}"),
+ // Cameras / lights / materials / 3D views (3D milestone).
+ stub!("camera.fromView", "Create Camera from 3D View", ["Layer", "Camera"], "{}"),
+ stub!("camera.stereoRig", "Create Stereo 3D Rig", ["Layer", "Camera"], "{}"),
+ stub!("camera.orbitNull", "Create Orbit Null", ["Layer", "Camera"], "{}"),
+ stub!("camera.fromModel", "Create Cameras from 3D Model", ["Layer", "Camera"], "{}"),
+ stub!("camera.linkFocusToPoi", "Link Focus Distance to Point of Interest", ["Layer", "Camera"], "{}"),
+ stub!("camera.linkFocusToLayer", "Link Focus Distance to Layer", ["Layer", "Camera"], "{}"),
+ stub!("camera.setFocusToLayer", "Set Focus Distance to Layer", ["Layer", "Camera"], "{}"),
- stub!("camera.settings", "Camera Settings...", ["Layer", "Camera"], "{}"),
- stub!("view.reset3dView", "Reset 3D View", ["Layer", "Camera"], "{}"),
+ stub!("light.fromModel", "Create Lights from 3D Model", ["Layer", "Light"], "{}"),
+ stub!("light.controlWithCamera", "Control Light with Camera", ["Layer", "Light"], "{}"),
+ stub!("light.environmentBackground", "Create Environment Light Background Layer", ["Layer", "Light"], "{}"),
+ stub!("material.revealSource", "Reveal Material Source in Project", ["Layer", "Material"], "{}"),
+ stub!("material.reset", "Reset Material", ["Layer", "Material"], "{}"),
+ stub!("material.duplicateAssign", "Duplicate and Assign Material", ["Layer", "Material"], "{}"),
+ stub!("view.layout", "Switch View Layout", [], "{views: 1|2|4}"),
+ stub!("view.shareViewOptions", "Share View Options", ["View", "Switch View Layout"], "{}"),
- stub!("view.3d", "Switch 3D View", [], "{view}"),
- stub!("view.last3dView", "Switch to Last 3D View", ["View"], "Escape", "{}"),
++ stub!("view.3d.default", "Default", ["View", "Switch 3D View"], "{}"),
+ stub!("view.lookAtSelected", "Look at Selected Layers", ["View"], "Cmd+Alt+Shift+\\", "{}"),
+ stub!("view.lookAtAll", "Look at All Layers", ["View"], "{}"),
+ stub!("view.splitLockedViewer", "Split with New Locked Viewer", ["View"], "{}"),
+ stub!("view.res.custom", "Custom...", ["View", "Resolution"], "{}"),
+ // Color management.
+ stub!("view.displayColorManagement", "Use Display Color Management", ["View"], "{}"),
+ stub!("view.simulateOutput", "Simulate Output", [], "{profile}"),
+ // Keyframes / text / tracking.
+ stub!("keys.audioToKeyframes", "Convert Audio to Keyframes", ["Animation", "Keyframe Assistant"], "{}"),
+ stub!("keys.rpfCameraImport", "RPF Camera Import", ["Animation", "Keyframe Assistant"], "{}"),
+ stub!("text.perCharacter3d", "Enable Per-character 3D", ["Animation", "Animate Text"], "{}"),
+ stub!("text.animatorLineAnchor", "Line Anchor", ["Animation", "Animate Text"], "{}"),
+ stub!("text.animatorCharacterValue", "Character Value", ["Animation", "Animate Text"], "{}"),
+ stub!("text.animatorFontAxes", "Variable Font Axes", ["Animation", "Animate Text"], "{}"),
+ stub!("text.addWigglySelector", "Wiggly", ["Animation", "Add Text Selector"], "{}"),
+ stub!("text.addExpressionSelector", "Expression", ["Animation", "Add Text Selector"], "{}"),
- stub!("prop.separateDimensions", "Separate Dimensions", ["Animation"], "{}"),
+ stub!("track.camera", "Track Camera", ["Animation"], "{}"),
+ stub!("track.warpStabilizer", "Warp Stabilizer VFX", ["Animation"], "{}"),
+ stub!("track.motion", "Track Motion", ["Animation"], "{}"),
+ stub!("track.mask", "Track Mask", ["Animation"], "{}"),
+ stub!("track.property", "Track this Property", ["Animation"], "{}"),
+ // Workspaces and panels that don't exist yet.
+ stub!("window.saveWorkspace", "Save Changes to this Workspace", ["Window", "Workspace"], "{}"),
+ stub!("window.saveWorkspaceAs", "Save as New Workspace...", ["Window", "Workspace"], "{name}"),
+ stub!("window.editWorkspaces", "Edit Workspaces...", ["Window", "Workspace"], "{}"),
+ stub!("window.unavailablePanel", "Panel", [], "{panel}"),
+ ]
+}
diff --cc crates/engine/src/commands/three_d.rs
index 000000000,48fca323e..de7331289
mode 000000,100644..100644
--- a/crates/engine/src/commands/three_d.rs
+++ b/crates/engine/src/commands/three_d.rs
@@@ -1,0 -1,614 +1,614 @@@
+ //! 3D: cameras (Layer ▸ New ▸ Camera, Camera Settings), lights (Layer ▸ New ▸ Light, Light
+ //! Settings), the viewer's 3D views (View ▸ Switch 3D View, Reset 3D View) and the camera tools
+ //! (Orbit, Pan, Dolly) acting on the current 3D view.
+
+ use effectcraft_geom::{Mat4, Vec3, vec3};
+ use effectcraft_keyframe::Value as KV;
+ use effectcraft_project::build;
+ use effectcraft_project::{AutoOrient, Comp, ItemId, Layer, LayerId, LayerSource, LightKind};
+ use effectcraft_render::EvalCtx;
+ use effectcraft_render::three_d::camera::{self, PRESETS, Rig, View3D, ViewCam, Views3D, orientation_for, zoom_for_focal};
+ use effectcraft_time::Tick;
+ use serde_json::{Value, json};
+
+ use super::layer::{color_p, insert_layer};
+ use super::{CommandSpec, b_p, bad, comp_id, f_p, has_comp, layer_mut, layer_p, merge_p, str_p, time_p};
+ use crate::{EngineError, Result, Session, cmd, query};
+
+ fn v3_p(p: &Value, k: &str) -> Option<[f64; 3]> {
+ let a = p.get(k)?.as_array()?;
+ let g = |i: usize| a.get(i).and_then(Value::as_f64);
+ Some([g(0)?, g(1)?, g(2).unwrap_or(0.0)])
+ }
+
+ /// Set a property at comp time `t` (adds a key when it is animated).
+ fn set_at(l: &mut Layer, path: &str, t: Tick, v: KV) {
+ let lt = l.layer_time(t);
+ if let Some(pr) = l.props.prop_mut(path) {
+ pr.set_value_at(lt, v);
+ }
+ }
+
+ fn get_at(l: &Layer, path: &str, t: Tick) -> Option<KV> {
+ l.props.prop(path).map(|pr| pr.value_at(l.layer_time(t)))
+ }
+
+ // ---------------------------------------------------------------- cameras
+
+ /// Parse a camera type: `oneNode`/`twoNode` (or "One-Node Camera"…). Some(true) = two-node.
+ fn two_node_p(p: &Value) -> Option<bool> {
+ let t = str_p(p, "type")?.to_ascii_lowercase().replace(['-', ' ', '_'], "");
+ if t.starts_with("one") {
+ Some(false)
+ } else if t.starts_with("two") {
+ Some(true)
+ } else {
+ None
+ }
+ }
+
+ /// Zoom from `zoom`, `preset` ("50mm"), `focalLength` (mm) or `angleOfView` (degrees).
+ fn zoom_p(p: &Value, comp_w: f64) -> Result<Option<f64>> {
+ if let Some(z) = f_p(p, "zoom") {
+ return Ok(Some(z.max(0.1)));
+ }
+ if let Some(pr) = p.get("preset") {
+ let focal = match pr {
+ Value::Number(n) => n.as_f64(),
+ Value::String(s) => {
+ let k = s.trim().to_ascii_lowercase();
+ PRESETS.iter().find(|(n, _)| n.eq_ignore_ascii_case(&k)).map(|(_, f)| *f).or_else(|| k.trim_end_matches("mm").trim().parse().ok())
+ }
+ _ => None,
+ }
+ .ok_or_else(|| bad("layer.newCamera", format!("unknown preset {pr}; use one of 15mm, 20mm, 24mm, 28mm, 35mm, 50mm, 80mm, 135mm, 200mm")))?;
+ return Ok(Some(zoom_for_focal(comp_w, focal)));
+ }
+ if let Some(f) = f_p(p, "focalLength") {
+ return Ok(Some(zoom_for_focal(comp_w, f)));
+ }
+ if let Some(a) = f_p(p, "angleOfView") {
+ return Ok(Some(comp_w * 0.5 / (a.clamp(0.1, 179.0).to_radians() * 0.5).tan()));
+ }
+ Ok(None)
+ }
+
+ /// Apply Camera Settings parameters to a camera layer at comp time `t`.
+ fn apply_camera(l: &mut Layer, comp: &Comp, p: &Value, t: Tick, cmd: &str) -> Result<()> {
+ let w = comp.width as f64;
+ if let Some(z) = zoom_p(p, w)? {
+ set_at(l, "cameraOptions/zoom", t, KV::Scalar(z));
+ // "Lock to Zoom" (default): the focus distance follows the zoom unless one is given.
+ if b_p(p, "lockToZoom").unwrap_or(true) && f_p(p, "focusDistance").is_none() {
+ set_at(l, "cameraOptions/focusDistance", t, KV::Scalar(z));
+ }
+ }
+ if let Some(v) = b_p(p, "dof").or_else(|| b_p(p, "depthOfField")) {
+ set_at(l, "cameraOptions/dof", t, KV::Bool(v));
+ }
+ for (k, path) in [("focusDistance", "cameraOptions/focusDistance"), ("aperture", "cameraOptions/aperture"), ("blurLevel", "cameraOptions/blurLevel")] {
+ if let Some(v) = f_p(p, k) {
+ set_at(l, path, t, KV::Scalar(v.max(0.0)));
+ }
+ }
+ if let Some(fs) = f_p(p, "fStop") {
+ // F-Stop = focal length / aperture, apertures in mm scaled like the presets (25.3 mm at 1920 px).
+ let z = get_at(l, "cameraOptions/zoom", t).map(|v| v.as_f64()).unwrap_or(1000.0);
+ let focal = camera::focal_for_zoom(w, z);
+ set_at(l, "cameraOptions/aperture", t, KV::Scalar(focal / fs.max(0.01) * w / 1920.0));
+ }
+ if let Some(pos) = v3_p(p, "position") {
+ set_at(l, "transform/position", t, KV::Vec3(pos));
+ }
+ if let Some(poi) = v3_p(p, "poi").or_else(|| v3_p(p, "pointOfInterest")) {
+ set_at(l, "transform/poi", t, KV::Vec3(poi));
+ }
+ if let Some(two) = two_node_p(p) {
+ let was = l.auto_orient == AutoOrient::TowardsPointOfInterest;
+ if two != was {
+ let pos = Vec3::from(get_at(l, "transform/position", t).map(|v| v.as_vec3()).unwrap_or([0.0; 3]));
+ let zoom = get_at(l, "cameraOptions/zoom", t).map(|v| v.as_f64()).unwrap_or(1000.0);
+ if two {
+ // Keep the view: put the POI where the camera looks, clear the orientation.
+ let o = get_at(l, "transform/orientation", t).map(|v| v.as_vec3()).unwrap_or([0.0; 3]);
+ let fwd = Mat4::orientation(Vec3::from(o)).apply_vec(vec3(0.0, 0.0, 1.0));
+ let poi = pos + fwd * zoom;
+ set_at(l, "transform/poi", t, KV::Vec3([poi.x, poi.y, poi.z]));
+ set_at(l, "transform/orientation", t, KV::Vec3([0.0; 3]));
+ l.auto_orient = AutoOrient::TowardsPointOfInterest;
+ } else {
+ let poi = Vec3::from(get_at(l, "transform/poi", t).map(|v| v.as_vec3()).unwrap_or([0.0; 3]));
+ set_at(l, "transform/orientation", t, KV::Vec3(orientation_for(poi - pos)));
+ l.auto_orient = AutoOrient::Off;
+ }
+ }
+ } else if p.get("type").is_some() {
+ return Err(bad(cmd, "type: oneNode|twoNode"));
+ }
+ Ok(())
+ }
+
+ fn new_camera(s: &mut Session, p: &Value) -> Result<Value> {
+ let cid = comp_id(s, p)?;
+ let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
+ let name = str_p(p, "name").unwrap_or("Camera 1").to_string();
+ let t = time_p(s, p, Some(&comp));
+ let id = s.edit("New Camera", None, |proj, st| {
+ let mut l = build::layer(proj, &comp, &name, LayerSource::Camera, (comp.width, comp.height), None);
+ apply_camera(&mut l, &comp, p, t, "layer.newCamera")?;
+ insert_layer(proj, st, cid, l)
+ })?;
+ Ok(json!({"layer": id.0}))
+ }
+
+ /// The camera or light layer a settings command targets.
+ fn target(s: &Session, p: &Value, cmd: &str, want_camera: bool) -> Result<(ItemId, LayerId)> {
+ let (cid, lid) = layer_p(s, p, cmd)?;
+ let l = s.project.comp(cid).and_then(|c| c.layer(lid)).ok_or(EngineError::NoComp)?;
+ let ok = if want_camera { l.is_camera() } else { l.is_light() };
+ if !ok {
+ return Err(bad(cmd, format!("layer `{}` is not a {}", l.name, if want_camera { "camera" } else { "light" })));
+ }
+ Ok((cid, lid))
+ }
+
+ fn camera_settings(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, lid) = target(s, p, "layer.cameraSettings", true)?;
+ let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
+ let t = time_p(s, p, Some(&comp));
+ let name = str_p(p, "name").map(str::to_string);
+ s.edit("Camera Settings", None, |proj, _| {
+ let l = layer_mut(proj, cid, lid)?;
+ if let Some(n) = &name {
+ l.name = n.clone();
+ }
+ apply_camera(l, &comp, p, t, "layer.cameraSettings")
+ })?;
+ Ok(Value::Null)
+ }
+
+ // ---------------------------------------------------------------- lights
+
+ fn light_kind_p(p: &Value, k: &str) -> Option<LightKind> {
+ let v = str_p(p, k)?;
+ LightKind::ALL.into_iter().find(|l| l.label().eq_ignore_ascii_case(v.trim()))
+ }
+
+ fn apply_light(l: &mut Layer, p: &Value, t: Tick, cmd: &str) -> Result<()> {
+ if let Some(c) = color_p(p, "color") {
+ set_at(l, "lightOptions/color", t, KV::Color([c[0] as f64, c[1] as f64, c[2] as f64, 1.0]));
+ }
+ for k in ["intensity", "coneAngle", "coneFeather", "radius", "falloffDistance", "shadowDarkness", "shadowDiffusion"] {
+ if let Some(v) = f_p(p, k) {
+ set_at(l, &format!("lightOptions/{k}"), t, KV::Scalar(v));
+ }
+ }
+ if let Some(v) = b_p(p, "castsShadows") {
+ set_at(l, "lightOptions/castsShadows", t, KV::Bool(v));
+ }
+ if let Some(f) = p.get("falloff") {
+ let i = match f {
+ Value::Number(n) => n.as_u64().map(|v| v as u32),
+ Value::String(s) => {
+ let k = s.to_ascii_lowercase();
+ if k.starts_with("none") {
+ Some(0)
+ } else if k.starts_with("smooth") {
+ Some(1)
+ } else if k.starts_with("inverse") {
+ Some(2)
+ } else {
+ None
+ }
+ }
+ _ => None,
+ }
+ .filter(|i| *i <= 2)
+ .ok_or_else(|| bad(cmd, "falloff: None|Smooth|Inverse Square Clamped"))?;
+ set_at(l, "lightOptions/falloff", t, KV::Enum(i));
+ }
+ if let Some(pos) = v3_p(p, "position") {
+ set_at(l, "transform/position", t, KV::Vec3(pos));
+ }
+ if let Some(poi) = v3_p(p, "poi").or_else(|| v3_p(p, "pointOfInterest")) {
+ set_at(l, "transform/poi", t, KV::Vec3(poi));
+ }
+ Ok(())
+ }
+
+ fn new_light(s: &mut Session, p: &Value) -> Result<Value> {
+ let cid = comp_id(s, p)?;
+ let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
+ let kind = match p.get("kind").or_else(|| p.get("type")) {
+ Some(_) => light_kind_p(p, "kind").or_else(|| light_kind_p(p, "type")).ok_or_else(|| bad("layer.newLight", "kind: Parallel|Spot|Point|Ambient"))?,
+ None => LightKind::Spot,
+ };
+ let name = str_p(p, "name").unwrap_or("Light 1").to_string();
+ let t = time_p(s, p, Some(&comp));
+ let id = s.edit("New Light", None, |proj, st| {
+ let mut l = build::layer(proj, &comp, &name, LayerSource::Light { kind }, (comp.width, comp.height), None);
+ apply_light(&mut l, p, t, "layer.newLight")?;
+ insert_layer(proj, st, cid, l)
+ })?;
+ Ok(json!({"layer": id.0}))
+ }
+
+ fn light_settings(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, lid) = target(s, p, "layer.lightSettings", false)?;
+ let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
+ let t = time_p(s, p, Some(&comp));
+ let name = str_p(p, "name").map(str::to_string);
+ let kind = match p.get("kind").or_else(|| p.get("type")) {
+ Some(_) => {
+ Some(light_kind_p(p, "kind").or_else(|| light_kind_p(p, "type")).ok_or_else(|| bad("layer.lightSettings", "kind: Parallel|Spot|Point|Ambient"))?)
+ }
+ None => None,
+ };
+ s.edit("Light Settings", None, |proj, _| {
+ let old = proj.comp(cid).and_then(|c| c.layer(lid)).cloned().ok_or(EngineError::NoComp)?;
+ let mut l = old.clone();
+ if let Some(k) = kind
+ && old.source != (LayerSource::Light { kind: k })
+ {
+ // Light Type change: rebuild the light's groups, carrying over shared values.
+ let fresh = build::layer(proj, &comp, &old.name, LayerSource::Light { kind: k }, (comp.width, comp.height), None);
+ l.source = fresh.source.clone();
+ l.auto_orient = fresh.auto_orient;
+ l.props = fresh.props;
+ for path in [
+ "transform/position",
+ "transform/poi",
+ "transform/orientation",
+ "transform/rotationX",
+ "transform/rotationY",
+ "transform/rotation",
+ "lightOptions/intensity",
+ "lightOptions/color",
+ "lightOptions/coneAngle",
+ "lightOptions/coneFeather",
+ "lightOptions/falloff",
+ "lightOptions/radius",
+ "lightOptions/falloffDistance",
+ "lightOptions/castsShadows",
+ "lightOptions/shadowDarkness",
+ "lightOptions/shadowDiffusion",
+ ] {
+ if let (Some(src), Some(dst)) = (old.props.prop(path), l.props.prop_mut(path)) {
+ dst.value = src.value.clone();
+ dst.keys = src.keys.clone();
+ dst.expr = src.expr.clone();
+ }
+ }
+ }
+ if let Some(n) = &name {
+ l.name = n.clone();
+ }
+ apply_light(&mut l, p, t, "layer.lightSettings")?;
+ *layer_mut(proj, cid, lid)? = l;
+ Ok(())
+ })?;
+ Ok(Value::Null)
+ }
+
+ // ---------------------------------------------------------------- 3D views
+
+ fn views(s: &mut Session, cid: ItemId) -> &mut Views3D {
+ s.state.views3d.entry(cid).or_default()
+ }
+
+ fn view_p(p: &Value, cmd: &str) -> Result<View3D> {
+ let v = str_p(p, "view").ok_or_else(|| bad(cmd, "missing `view` (activeCamera|front|left|top|back|right|bottom|custom1|custom2|custom3)"))?;
+ View3D::from_id(v).ok_or_else(|| bad(cmd, format!("unknown view `{v}`")))
+ }
+
+ fn switch_view(s: &mut Session, cid: ItemId, v: View3D) -> Value {
+ let vs = views(s, cid);
+ if vs.current != v {
+ vs.last = vs.current;
+ vs.current = v;
+ }
+ json!({"view": v.id()})
+ }
+
+ fn set_3d_view(s: &mut Session, p: &Value) -> Result<Value> {
+ let cid = comp_id(s, p)?;
+ let v = view_p(p, "view.set3DView")?;
+ Ok(switch_view(s, cid, v))
+ }
+
+ macro_rules! view_cmd {
+ ($f:ident, $v:expr) => {
+ fn $f(s: &mut Session, p: &Value) -> Result<Value> {
+ let cid = comp_id(s, p)?;
+ Ok(switch_view(s, cid, $v))
+ }
+ };
+ }
+ view_cmd!(view_active, View3D::ActiveCamera);
+ view_cmd!(view_front, View3D::Front);
+ view_cmd!(view_left, View3D::Left);
+ view_cmd!(view_top, View3D::Top);
+ view_cmd!(view_back, View3D::Back);
+ view_cmd!(view_right, View3D::Right);
+ view_cmd!(view_bottom, View3D::Bottom);
+ view_cmd!(view_custom1, View3D::Custom1);
+ view_cmd!(view_custom2, View3D::Custom2);
+ view_cmd!(view_custom3, View3D::Custom3);
+
+ fn last_view(s: &mut Session, p: &Value) -> Result<Value> {
+ let cid = comp_id(s, p)?;
+ let last = views(s, cid).last;
+ Ok(switch_view(s, cid, last))
+ }
+
+ fn reset_view(s: &mut Session, p: &Value) -> Result<Value> {
+ let cid = comp_id(s, p)?;
+ let cur = views(s, cid).current;
+ if cur != View3D::ActiveCamera {
+ views(s, cid).cams.remove(&cur);
+ return Ok(json!({"view": cur.id()}));
+ }
+ // Active camera: back to the default framing (50 mm-style distance, looking at the centre).
+ let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
+ let t = s.state.times.get(&cid).copied().unwrap_or(Tick::ZERO);
+ let cam = comp.active_camera(t).map(|l| l.id).ok_or_else(|| bad("view.reset3DView", "the comp has no camera layer"))?;
+ let (w, h) = (comp.width as f64, comp.height as f64);
+ s.edit("Reset 3D View", None, |proj, _| {
+ let l = layer_mut(proj, cid, cam)?;
+ let zoom = get_at(l, "cameraOptions/zoom", t).map(|v| v.as_f64()).unwrap_or(effectcraft_geom::default_camera_zoom(w));
+ set_at(l, "transform/position", t, KV::Vec3([w / 2.0, h / 2.0, -zoom]));
+ set_at(l, "transform/poi", t, KV::Vec3([w / 2.0, h / 2.0, 0.0]));
+ set_at(l, "transform/orientation", t, KV::Vec3([0.0; 3]));
+ Ok(())
+ })?;
+ Ok(json!({"view": "activeCamera"}))
+ }
+
+ fn set_view_camera(s: &mut Session, p: &Value) -> Result<Value> {
+ let cid = comp_id(s, p)?;
+ let v = view_p(p, "view.set3DViewCamera")?;
+ if v == View3D::ActiveCamera {
+ return Err(bad("view.set3DViewCamera", "edit the camera layer for the active camera view"));
+ }
+ let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
+ let (w, h) = (comp.width as f64, comp.height as f64);
+ let vs = views(s, cid);
+ let mut c = vs.cam(v, w, h);
+ if let Some(e) = v3_p(p, "eye") {
+ c.eye = e;
+ }
+ if let Some(e) = v3_p(p, "poi") {
+ c.poi = e;
+ }
+ if let Some(z) = f_p(p, "zoom") {
+ c.zoom = z.max(1e-3);
+ }
+ vs.cams.insert(v, c);
+ Ok(json!({"view": v.id()}))
+ }
+
+ fn get_3d(s: &mut Session, p: &Value) -> Result<Value> {
+ let cid = comp_id(s, p)?;
+ let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
+ let (w, h) = (comp.width as f64, comp.height as f64);
+ let vs = s.state.views3d.get(&cid).cloned().unwrap_or_default();
+ let t = s.state.times.get(&cid).copied().unwrap_or(Tick::ZERO);
+ let ctx = EvalCtx { project: &s.project, comp_id: cid, comp, time: t, expr: s.expr.as_deref() };
+ let cam = vs.override_camera(w, h).unwrap_or_else(|| camera::active_camera(&ctx));
+ let f = cam.forward();
+ let lights: Vec<Value> = comp
+ .layers
+ .iter()
+ .filter_map(|l| match l.source {
+ LayerSource::Light { kind } => Some(json!({"id": l.id.0, "name": l.name, "kind": kind.label()})),
+ _ => None,
+ })
+ .collect();
+ let active = comp.active_camera(t).map(|l| json!({"id": l.id.0, "name": l.name, "twoNode": camera::is_two_node(l)}));
+ Ok(json!({
+ "view": vs.current.id(),
+ "label": vs.current.label(),
+ "views": View3D::ALL.iter().map(|v| v.id()).collect::<Vec<_>>(),
+ "camera": {"eye": [cam.eye.x, cam.eye.y, cam.eye.z], "forward": [f.x, f.y, f.z], "zoom": cam.zoom, "ortho": cam.ortho},
+ "activeCameraLayer": active,
+ "lights": lights,
+ }))
+ }
+
+ // ---------------------------------------------------------------- camera tools
+
+ enum ToolOp {
+ Orbit(f64, f64),
+ Pan(f64, f64),
+ Dolly(f64),
+ }
+
+ fn camera_tool(s: &mut Session, p: &Value, op: ToolOp, cmd: &str, label: &str) -> Result<Value> {
+ let cid = comp_id(s, p)?;
+ let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?.clone();
+ let (w, h) = (comp.width as f64, comp.height as f64);
+ let cur = s.state.views3d.get(&cid).map(|v| v.current).unwrap_or_default();
+ let apply = |r: &mut Rig, layer: bool| match op {
+ ToolOp::Orbit(yaw, pitch) => r.orbit(yaw, pitch),
+ ToolOp::Pan(dx, dy) => r.pan(dx, dy),
+ ToolOp::Dolly(a) => r.dolly(a, layer),
+ };
+ if cur != View3D::ActiveCamera {
+ let vs = views(s, cid);
+ let vc = vs.cam(cur, w, h);
+ let mut r = Rig::from_view(&vc);
+ apply(&mut r, false);
+ let nc = ViewCam { eye: camera::arr(r.eye), poi: camera::arr(r.poi), zoom: r.zoom, ..vc };
+ vs.cams.insert(cur, nc);
+ return Ok(json!({"view": cur.id(), "eye": nc.eye, "poi": nc.poi, "zoom": nc.zoom}));
+ }
+ let t = s.state.times.get(&cid).copied().unwrap_or(Tick::ZERO);
+ let cam = match p.get("layer") {
+ Some(v) => super::resolve_layer(&comp, v).filter(|id| comp.layer(*id).is_some_and(|l| l.is_camera())),
+ None => comp.active_camera(t).map(|l| l.id),
+ }
+ .ok_or_else(|| bad(cmd, "the comp has no active camera layer (Layer ▸ New ▸ Camera), or switch to a custom 3D view"))?;
+ let merge = merge_p(p).map(str::to_string);
+ let r = s.edit(label, merge.as_deref(), |proj, _| {
+ let l = layer_mut(proj, cid, cam)?;
+ let pos = Vec3::from(get_at(l, "transform/position", t).map(|v| v.as_vec3()).unwrap_or([w / 2.0, h / 2.0, -1000.0]));
+ let zoom = get_at(l, "cameraOptions/zoom", t).map(|v| v.as_f64()).unwrap_or(1000.0);
+ let two = camera::is_two_node(l);
+ let o = get_at(l, "transform/orientation", t).map(|v| v.as_vec3()).unwrap_or([0.0; 3]);
+ let rx = get_at(l, "transform/rotationX", t).map(|v| v.as_f64()).unwrap_or(0.0);
+ let ry = get_at(l, "transform/rotationY", t).map(|v| v.as_f64()).unwrap_or(0.0);
+ let poi = if two {
+ Vec3::from(get_at(l, "transform/poi", t).map(|v| v.as_vec3()).unwrap_or([w / 2.0, h / 2.0, 0.0]))
+ } else {
+ let fwd = (Mat4::orientation(Vec3::from(o)) * Mat4::rotate_y(ry) * Mat4::rotate_x(rx)).apply_vec(vec3(0.0, 0.0, 1.0));
+ pos + fwd * zoom
+ };
+ let mut rig = Rig { eye: pos, poi, zoom, ortho: false };
+ apply(&mut rig, true);
+ set_at(l, "transform/position", t, KV::Vec3(camera::arr(rig.eye)));
+ if two {
+ set_at(l, "transform/poi", t, KV::Vec3(camera::arr(rig.poi)));
+ } else {
+ set_at(l, "transform/orientation", t, KV::Vec3(orientation_for(rig.poi - rig.eye)));
+ set_at(l, "transform/rotationX", t, KV::Scalar(0.0));
+ set_at(l, "transform/rotationY", t, KV::Scalar(0.0));
+ }
+ Ok(json!({"layer": cam.0, "position": camera::arr(rig.eye), "poi": camera::arr(rig.poi)}))
+ })?;
+ Ok(r)
+ }
+
+ fn orbit(s: &mut Session, p: &Value) -> Result<Value> {
+ camera_tool(
+ s,
+ p,
+ ToolOp::Orbit(f_p(p, "yaw").or_else(|| f_p(p, "dx")).unwrap_or(0.0), f_p(p, "pitch").or_else(|| f_p(p, "dy")).unwrap_or(0.0)),
+ "camera.orbit",
+ "Orbit Camera",
+ )
+ }
+ fn pan(s: &mut Session, p: &Value) -> Result<Value> {
+ camera_tool(s, p, ToolOp::Pan(f_p(p, "dx").unwrap_or(0.0), f_p(p, "dy").unwrap_or(0.0)), "camera.pan", "Pan Camera")
+ }
+ fn dolly(s: &mut Session, p: &Value) -> Result<Value> {
+ camera_tool(s, p, ToolOp::Dolly(f_p(p, "amount").or_else(|| f_p(p, "dz")).unwrap_or(0.0)), "camera.dolly", "Dolly Camera")
+ }
+
+ /// Layer ▸ Transform ▸ Auto-Orient: off | alongPath | towardsCamera (3D layers) |
+ /// towardsPointOfInterest (cameras and spot/parallel lights).
+ fn auto_orient(s: &mut Session, p: &Value) -> Result<Value> {
+ let (cid, ids) = super::layers_p(s, p)?;
+ if ids.is_empty() {
+ return Err(bad("layer.autoOrient", "select a layer first"));
+ }
+ let raw = str_p(p, "mode").ok_or_else(|| bad("layer.autoOrient", "missing `mode` (off|alongPath|towardsCamera|towardsPointOfInterest)"))?;
+ let k = raw.to_ascii_lowercase().replace([' ', '-', '_'], "");
+ let mode = match k.as_str() {
+ "off" => AutoOrient::Off,
+ "alongpath" | "orientalongpath" => AutoOrient::AlongPath,
+ "towardscamera" | "orienttowardscamera" => AutoOrient::TowardsCamera,
+ "towardspointofinterest" | "towardspoi" | "orienttowardspointofinterest" => AutoOrient::TowardsPointOfInterest,
+ _ => return Err(bad("layer.autoOrient", format!("unknown mode `{raw}`"))),
+ };
+ s.edit("Auto-Orient", None, |proj, _| {
+ let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
+ for l in comp.layers.iter_mut().filter(|l| ids.contains(&l.id)) {
+ let rig = l.is_camera() || l.is_light();
+ let ok = match mode {
+ AutoOrient::Off | AutoOrient::AlongPath => true,
+ AutoOrient::TowardsCamera => !rig,
+ AutoOrient::TowardsPointOfInterest => rig && l.transform().is_some_and(|t| t.get("poi").is_some()),
+ };
+ if !ok {
+ return Err(bad("layer.autoOrient", format!("`{raw}` is not available for layer `{}`", l.name)));
+ }
+ l.auto_orient = mode;
+ }
+ Ok(())
+ })?;
+ Ok(Value::Null)
+ }
+
+ pub fn specs() -> Vec<CommandSpec> {
+ vec![
+ cmd!(
+ "layer.autoOrient",
- "Auto-Orient…",
++ "Auto-Orient...",
+ ["Layer", "Transform"],
+ Some("Cmd+Alt+O"),
+ "{mode: off|alongPath|towardsCamera|towardsPointOfInterest, layers?}",
+ super::has_layers,
+ auto_orient
+ ),
+ cmd!(
+ "layer.newLight",
- "Light…",
++ "Light...",
+ ["Layer", "New"],
+ Some("Cmd+Alt+Shift+L"),
+ "{kind?: Parallel|Spot|Point|Ambient (default Spot), name?, color?, intensity?, coneAngle?, coneFeather?, falloff?: None|Smooth|Inverse Square Clamped, radius?, falloffDistance?, castsShadows?, shadowDarkness?, shadowDiffusion?, position? [x,y,z], poi? [x,y,z]}",
+ has_comp,
+ new_light
+ ),
+ cmd!(
+ "layer.newCamera",
- "Camera…",
++ "Camera...",
+ ["Layer", "New"],
+ Some("Cmd+Alt+Shift+C"),
+ "{name?, type?: oneNode|twoNode (default twoNode), preset?: 15mm|20mm|24mm|28mm|35mm|50mm|80mm|135mm|200mm, zoom?, focalLength? mm, angleOfView? deg, dof?, focusDistance?, aperture?, fStop?, blurLevel?, lockToZoom?, position? [x,y,z], poi? [x,y,z]}",
+ has_comp,
+ new_camera
+ ),
+ cmd!(
+ "layer.cameraSettings",
- "Camera Settings…",
- ["Layer"],
++ "Camera Settings...",
++ ["Layer", "Camera"],
+ None,
+ "{layer?, name?, type?, preset?, zoom?, focalLength?, angleOfView?, dof?, focusDistance?, aperture?, fStop?, blurLevel?, position?, poi?}",
+ has_comp,
+ camera_settings
+ ),
+ cmd!(
+ "layer.lightSettings",
- "Light Settings…",
- ["Layer"],
++ "Light Settings...",
++ [],
+ None,
+ "{layer?, name?, kind?, color?, intensity?, coneAngle?, coneFeather?, falloff?, radius?, falloffDistance?, castsShadows?, shadowDarkness?, shadowDiffusion?, position?, poi?}",
+ has_comp,
+ light_settings
+ ),
+ cmd!(
+ "view.set3DView",
+ "Switch 3D View",
+ [],
+ None,
+ "{view: activeCamera|front|left|top|back|right|bottom|custom1|custom2|custom3, comp?}",
+ has_comp,
+ set_3d_view
+ ),
+ cmd!("view.3d.activeCamera", "Active Camera", ["View", "Switch 3D View"], Some("F12"), "{comp?}", has_comp, view_active),
+ cmd!("view.3d.front", "Front", ["View", "Switch 3D View"], Some("F10"), "{comp?}", has_comp, view_front),
+ cmd!("view.3d.left", "Left", ["View", "Switch 3D View"], None, "{comp?}", has_comp, view_left),
+ cmd!("view.3d.top", "Top", ["View", "Switch 3D View"], None, "{comp?}", has_comp, view_top),
+ cmd!("view.3d.back", "Back", ["View", "Switch 3D View"], None, "{comp?}", has_comp, view_back),
+ cmd!("view.3d.right", "Right", ["View", "Switch 3D View"], None, "{comp?}", has_comp, view_right),
+ cmd!("view.3d.bottom", "Bottom", ["View", "Switch 3D View"], None, "{comp?}", has_comp, view_bottom),
+ cmd!("view.3d.custom1", "Custom View 1", ["View", "Switch 3D View"], Some("F11"), "{comp?}", has_comp, view_custom1),
+ cmd!("view.3d.custom2", "Custom View 2", ["View", "Switch 3D View"], None, "{comp?}", has_comp, view_custom2),
+ cmd!("view.3d.custom3", "Custom View 3", ["View", "Switch 3D View"], None, "{comp?}", has_comp, view_custom3),
+ cmd!("view.3d.last", "Switch to Last 3D View", ["View"], None, "{comp?}", has_comp, last_view),
+ cmd!("view.reset3DView", "Reset 3D View", ["View"], None, "{comp?}", has_comp, reset_view),
+ cmd!("view.set3DViewCamera", "Set 3D View Camera", [], None, "{view, eye? [x,y,z], poi? [x,y,z], zoom?}", has_comp, set_view_camera),
+ cmd!(
+ "camera.orbit",
+ "Orbit Camera",
+ [],
+ None,
+ "{yaw|dx deg, pitch|dy deg, layer?, merge?} — current 3D view (camera layer in Active Camera)",
+ has_comp,
+ orbit
+ ),
+ cmd!("camera.pan", "Pan Camera", [], None, "{dx, dy (comp px), layer?, merge?}", has_comp, pan),
+ cmd!("camera.dolly", "Dolly Camera", [], None, "{amount (px, + = forward), layer?, merge?}", has_comp, dolly),
+ query!("view.get3D", "3D View State", "{comp?} → current 3D view, view camera, active camera layer, lights", get_3d),
+ ]
+ }
diff --cc crates/engine/src/lib.rs
index 5506e675f,7dd18722c..30d6bc6d3
--- a/crates/engine/src/lib.rs
+++ b/crates/engine/src/lib.rs
@@@ -11,7 -11,7 +11,8 @@@
pub mod commands;
pub mod demo;
pub mod links;
+pub mod menus;
+ pub mod render_queue;
use std::sync::Arc;
@@@ -111,37 -139,11 +140,30 @@@ pub struct EditorState
pub snapping: bool,
/// Last applied effect id (Effect ▸ last effect).
pub last_effect: Option<String>,
+ /// Viewer region of interest `[x, y, w, h]` in comp pixels (Composition ▸ Crop Comp to Region
+ /// of Interest).
+ #[serde(default)]
+ pub region_of_interest: Option<[f64; 4]>,
- /// Keyframe clipboard (Edit ▸ Copy with keys selected; Paste / Paste Reversed Keyframes).
- #[serde(skip)]
- pub key_clipboard: Vec<KeyClip>,
+ /// Property-link clipboard (Edit ▸ Copy with Property Links / Copy Expression Only).
+ #[serde(skip)]
+ pub link_clipboard: Option<LinkClip>,
+ /// File ▸ Interpret Footage ▸ Remember Interpretation.
+ #[serde(skip)]
+ pub interpretation: Option<effectcraft_project::Footage>,
- }
-
- /// Copied keyframes of one property, addressed by its match path (`transform/position`).
- #[derive(Clone, Debug, PartialEq)]
- pub struct KeyClip {
- pub path: String,
- pub keys: Vec<effectcraft_keyframe::Keyframe>,
+ /// Viewer 3D view per comp (Active Camera / Front / … / Custom View 3 and edited view cameras).
+ #[serde(default)]
+ pub views3d: std::collections::BTreeMap<ItemId, effectcraft_render::three_d::Views3D>,
}
+/// What Copy with Property Links / Copy Expression Only put on the clipboard.
+#[derive(Clone, Debug, PartialEq)]
+pub enum LinkClip {
+ /// Expressions that link back to the source properties: (match path, expression text).
+ Links { relative: bool, links: Vec<(String, String)> },
+ /// Expressions only: (match path, expression).
+ Expressions(Vec<(String, effectcraft_project::Expression)>),
+}
+
/// Events for frontends (drained each frame).
#[derive(Clone, Debug, PartialEq, Serialize)]
pub enum Event {
@@@ -368,7 -417,9 +450,11 @@@ mod rq_tests
#[cfg(test)]
mod tests;
#[cfg(test)]
+ mod tests_3d;
+ #[cfg(test)]
+mod tests_menu_cmds;
++#[cfg(test)]
+ mod tests_timeline;
/// Font families available to text layers (bundled + scanned system fonts).
pub fn text_families() -> Vec<String> {
diff --cc crates/engine/src/menus.rs
index 25059484c,000000000..2c887db32
mode 100644,000000..100644
--- a/crates/engine/src/menus.rs
+++ b/crates/engine/src/menus.rs
@@@ -1,925 -1,0 +1,925 @@@
+//! The menu bar, laid out like After Effects' (same menus, order, submenus, separators and
+//! labels). Every entry runs a registered command (`commands::find`), optionally with bound
+//! parameters (e.g. `layer.setBlendMode {"mode":"Multiply"}`). Frontends render this tree; agents
+//! read it through `ui.menu.list` / the command registry.
+//!
+//! The tree is written in a small indented text format (two spaces per level):
+//!
+//! ```text
+//! Layer top-level menu
+//! Blending Mode submenu (has deeper lines below it)
+//! Multiply | layer.setBlendMode {"mode":"Multiply"}
+//! Next Blending Mode | layer.setBlendMode {"step":1} | Shift+=
+//! --- separator
+//! @effects the effect categories (Effect menu)
+//! [mac] Quit EffectCraft | app.quit only on macOS ([!mac] = everywhere else)
+//! ```
+//!
+//! An entry's shortcut is the command's default shortcut unless the line gives one (needed for
+//! entries with bound parameters). Adobe-service entries (Team Projects, Libraries, Bridge, Media
+//! Encoder, Essential Graphics, Behance, Creative Cloud…) are intentionally absent.
+
+use std::sync::OnceLock;
+
+use serde::Serialize;
+use serde_json::Value;
+
+use crate::Session;
+use crate::commands::{self, CommandSpec};
+
+/// One node of the menu tree.
+#[derive(Clone, Debug, Serialize)]
+#[serde(tag = "type", rename_all = "camelCase")]
+pub enum MenuNode {
+ Item(MenuEntry),
+ Separator,
+ Submenu { label: String, children: Vec<MenuNode> },
+}
+
+/// A clickable menu entry.
+#[derive(Clone, Debug, Serialize)]
+pub struct MenuEntry {
+ pub label: String,
+ pub command: String,
+ /// Parameters bound to the entry (`null` = none).
+ #[serde(skip_serializing_if = "Value::is_null")]
+ pub params: Value,
+ pub shortcut: Option<String>,
+}
+
+impl MenuEntry {
+ pub fn spec(&self) -> Option<&'static CommandSpec> {
+ commands::find(&self.command)
+ }
+ pub fn params_or_empty(&self) -> Value {
+ if self.params.is_null() { Value::Object(Default::default()) } else { self.params.clone() }
+ }
+}
+
+/// Top-level menus in order (macOS has the application menu first).
+pub fn top_level() -> Vec<&'static str> {
+ menu_bar()
+ .iter()
+ .filter_map(|n| match n {
+ MenuNode::Submenu { label, .. } => Some(label.as_str()),
+ _ => None,
+ })
+ .collect()
+}
+
+/// The menu bar for this platform.
+pub fn menu_bar() -> &'static [MenuNode] {
+ static BAR: OnceLock<Vec<MenuNode>> = OnceLock::new();
+ BAR.get_or_init(|| parse(TREE, cfg!(target_os = "macos")).expect("menu tree parses"))
+}
+
+/// Every entry with its submenu path (`["Layer", "Blending Mode"]`), depth first.
+pub fn entries() -> Vec<(Vec<String>, &'static MenuEntry)> {
+ fn rec(nodes: &'static [MenuNode], path: &mut Vec<String>, out: &mut Vec<(Vec<String>, &'static MenuEntry)>) {
+ for n in nodes {
+ match n {
+ MenuNode::Item(e) => out.push((path.clone(), e)),
+ MenuNode::Separator => {}
+ MenuNode::Submenu { label, children } => {
+ path.push(label.clone());
+ rec(children, path, out);
+ path.pop();
+ }
+ }
+ }
+ }
+ let mut out = vec![];
+ rec(menu_bar(), &mut vec![], &mut out);
+ out
+}
+
+/// Check-mark state of an entry (`None` = not a toggle / radio entry). Frontend-only toggles
+/// (rulers, grid…) are answered by the frontend.
+pub fn checked(s: &Session, command: &str, params: &Value) -> Option<bool> {
+ let comp = s.active_comp()?;
+ let layer = s.state.selected_layers.first().and_then(|l| comp.layer(*l));
+ let pstr = |k: &str| params.get(k).and_then(Value::as_str);
+ match command {
+ "layer.setBlendMode" => {
+ let want = effectcraft_color::BlendMode::from_name(pstr("mode")?)?;
+ Some(layer?.blend_mode == want)
+ }
+ "layer.setSwitch" => {
+ let l = layer?;
+ let sw = &l.switches;
+ Some(match pstr("switch")? {
+ "shy" => sw.shy,
+ "lock" => sw.locked,
+ "audio" => sw.audio,
+ "video" => sw.video,
+ "solo" => sw.solo,
+ "fx" => sw.effects,
+ "collapse" => sw.collapse,
+ "motionBlur" => sw.motion_blur,
+ "adjustment" => sw.adjustment,
+ "threeD" => sw.three_d,
+ "guide" => sw.guide,
+ "preserveTransparency" => l.preserve_transparency,
+ _ => return None,
+ })
+ }
+ "layer.quality" => {
+ use effectcraft_project::Quality::*;
+ let q = layer?.switches.quality;
+ Some(matches!((pstr("quality")?, q), ("best", Best) | ("draft", Draft) | ("wireframe", Wireframe)))
+ }
+ "layer.sampling" => {
+ use effectcraft_project::Sampling::*;
+ let q = layer?.switches.sampling;
+ Some(matches!((pstr("sampling")?, q), ("bilinear", Bilinear) | ("bicubic", Bicubic)))
+ }
+ "layer.frameBlending" => {
+ use effectcraft_project::FrameBlend::*;
+ let q = layer?.switches.frame_blend;
+ Some(matches!((pstr("mode")?, q), ("off", Off) | ("frameMix", FrameMix) | ("pixelMotion", PixelMotion)))
+ }
+ "layer.trackMatte" => {
+ use effectcraft_project::MatteKind::*;
+ let m = layer?.track_matte;
+ Some(match (pstr("op")?, m) {
+ ("none", None) => true,
+ ("alpha", Some(m)) => m.kind == Alpha,
+ ("alphaInverted", Some(m)) => m.kind == AlphaInverted,
+ ("luma", Some(m)) => m.kind == Luma,
+ ("lumaInverted", Some(m)) => m.kind == LumaInverted,
+ _ => false,
+ })
+ }
+ "layer.markersLock" => Some(layer?.markers_locked),
+ _ => None,
+ }
+}
+
+/// Parse the tree text. `mac` selects `[mac]` / `[!mac]` lines.
+pub fn parse(text: &str, mac: bool) -> Result<Vec<MenuNode>, String> {
+ struct Line<'a> {
+ depth: usize,
+ body: &'a str,
+ }
+ let mut lines = vec![];
+ // Depth of a skipped (other-platform) line: its whole subtree is skipped too.
+ let mut skip_below: Option<usize> = None;
+ for (n, raw) in text.lines().enumerate() {
+ if raw.trim().is_empty() || raw.trim_start().starts_with("//") {
+ continue;
+ }
+ let indent = raw.len() - raw.trim_start().len();
+ if indent % 2 != 0 {
+ return Err(format!("line {}: odd indentation", n + 1));
+ }
+ let depth = indent / 2;
+ match skip_below {
+ Some(d) if depth > d => continue,
+ _ => skip_below = None,
+ }
+ let mut body = raw.trim();
+ let tagged = |tag: &str, keep: bool, body: &mut &str| -> Option<bool> {
+ let rest = body.strip_prefix(tag)?;
+ *body = rest;
+ Some(keep)
+ };
+ if let Some(false) = tagged("[mac] ", mac, &mut body).or_else(|| tagged("[!mac] ", !mac, &mut body)) {
+ skip_below = Some(depth);
+ continue;
+ }
+ lines.push(Line { depth, body });
+ }
+ fn build(lines: &[Line], i: &mut usize, depth: usize) -> Result<Vec<MenuNode>, String> {
+ let mut out = vec![];
+ while *i < lines.len() {
+ let l = &lines[*i];
+ if l.depth < depth {
+ break;
+ }
+ if l.depth > depth {
+ return Err(format!("unexpected indentation at `{}`", l.body));
+ }
+ *i += 1;
+ if l.body == "---" {
+ out.push(MenuNode::Separator);
+ continue;
+ }
+ if l.body == "@effects" {
+ out.extend(effect_categories());
+ continue;
+ }
+ let mut parts = l.body.split(" | ");
+ let label = parts.next().unwrap_or_default().trim().to_string();
+ match parts.next() {
+ Some(cmd) => {
+ let cmd = cmd.trim();
+ let (command, params) = match cmd.split_once(' ') {
+ Some((c, json)) => (c.to_string(), serde_json::from_str(json.trim()).map_err(|e| format!("`{}`: {e}", l.body))?),
+ None => (cmd.to_string(), Value::Null),
+ };
+ // Entries with bound params state their own shortcut; plain entries use the command's.
+ let inherited = if params.is_null() { commands::find(&command).and_then(|c| c.shortcut).map(str::to_string) } else { None };
+ let shortcut = parts.next().map(|s| s.trim().to_string()).or(inherited);
+ out.push(MenuNode::Item(MenuEntry { label, command, params, shortcut }));
+ }
+ None => {
+ let children = build(lines, i, depth + 1)?;
+ if children.is_empty() {
+ return Err(format!("`{label}` has neither a command nor children"));
+ }
+ out.push(MenuNode::Submenu { label, children });
+ }
+ }
+ }
+ Ok(out)
+ }
+ let mut i = 0;
+ build(&lines, &mut i, 0)
+}
+
+/// Effect ▸ category submenus from the effect registry.
+fn effect_categories() -> Vec<MenuNode> {
+ let mut cats: Vec<(&str, Vec<MenuNode>)> = vec![];
+ for e in crate::effects::registry() {
+ let entry =
+ MenuNode::Item(MenuEntry { label: e.name.into(), command: "effect.apply".into(), params: serde_json::json!({"effect": e.id}), shortcut: None });
+ match cats.iter_mut().find(|(c, _)| *c == e.category) {
+ Some((_, v)) => v.push(entry),
+ None => cats.push((e.category, vec![entry])),
+ }
+ }
+ cats.sort_by_key(|c| c.0.to_ascii_lowercase());
+ for (_, v) in &mut cats {
+ v.sort_by_key(|n| match n {
+ MenuNode::Item(e) => e.label.to_ascii_lowercase(),
+ _ => String::new(),
+ });
+ }
+ cats.into_iter().map(|(c, children)| MenuNode::Submenu { label: c.to_string(), children }).collect()
+}
+
+/// The After Effects menu layout. Labels use "..." like AE's macOS menus.
+pub const TREE: &str = r#"
+[mac] EffectCraft
+ About EffectCraft... | app.about
+ ---
+ Settings...
+ General... | app.settings {"page":"general"} | Cmd+Alt+;
+ Startup & Repair... | app.settings {"page":"startup"}
+ Project... | app.settings {"page":"project"}
+ Composition... | app.settings {"page":"composition"}
+ Previews... | app.settings {"page":"previews"}
+ Appearance... | app.settings {"page":"appearance"}
+ Grids & Guides... | app.settings {"page":"grids"}
+ Labels... | app.settings {"page":"labels"}
+ Type... | app.settings {"page":"type"}
+ Import... | app.settings {"page":"import"}
+ Export... | app.settings {"page":"export"}
+ Audio... | app.settings {"page":"audio"}
+ Disk... | app.settings {"page":"disk"}
+ Memory & CPU... | app.settings {"page":"memory"}
+ Video... | app.settings {"page":"video"}
+ 3D... | app.settings {"page":"3d"}
+ Scripting & Expressions... | app.settings {"page":"scripting"}
+ ---
+ Hide EffectCraft | app.hide
+ Hide Others | app.hideOthers
+ Show All | app.showAll
+ ---
+ Quit EffectCraft | app.quit
+File
+ New
+ New Project | file.newProject
+ New Folder | project.newFolder
+ Open Project... | file.open
+ ---
+ Close | file.close
+ Close Project | file.closeProject
+ Save | file.save
+ Save As
+ Save As... | file.saveAs
+ Save a Copy... | file.saveCopy
+ Increment and Save | file.incrementAndSave
+ Revert | file.revert
+ ---
+ Import
+ File... | file.import
+ Multiple Files... | file.importMultiple
+ Placeholder... | file.importPlaceholder
+ Solid... | file.importSolid
+ Export
- Add to Render Queue | render.addToQueue
++ Add to Render Queue | renderQueue.add
+ ---
+ Find | app.find
+ ---
+ Add Footage to Comp | layer.addItem
+ New Comp from Selection... | file.newCompFromSelection
+ ---
+ Dependencies
+ Collect Files... | file.collectFiles
+ Consolidate All Footage | file.consolidateFootage
+ Remove Unused Footage | file.removeUnusedFootage
+ Reduce Project | file.reduceProject
+ Find Missing Effects | file.findMissing {"what":"effects"}
+ Find Missing Fonts | file.findMissing {"what":"fonts"}
+ Find Missing Footage | file.findMissing {"what":"footage"}
+ ---
+ Scripts
+ Run Script File... | file.runScript
+ ---
+ Create Proxy
+ Still... | file.createProxy {"kind":"still"}
+ Movie... | file.createProxy {"kind":"movie"}
+ Set Proxy
+ File... | file.setProxy
+ None | file.setProxyNone
+ Interpret Footage
+ Main... | file.interpretFootage
+ Proxy... | file.interpretProxy
+ Remember Interpretation | file.rememberInterpretation
+ Apply Interpretation | file.applyInterpretation
+ Replace Footage
+ File... | file.replaceFootage
+ Placeholder... | file.replaceWithPlaceholder
+ Solid... | file.replaceWithSolid
+ Reload Footage | file.reloadFootage
+ Reveal in Finder | file.revealInFinder
+ ---
+ Project Settings... | file.projectSettings
+ [!mac] ---
+ [!mac] Exit | app.quit
+Edit
+ Undo | edit.undo
+ Redo | edit.redo
+ ---
+ Quick Apply... | app.commandPalette
+ ---
+ Cut | edit.cut
+ Copy | edit.copy
+ Copy with Property Links | edit.copyWithPropertyLinks
+ Copy with Relative Property Links | edit.copyWithRelativePropertyLinks
+ Copy Expression Only | edit.copyExpressionOnly
+ Paste | edit.paste
+ Paste Reversed Keyframes | edit.pasteReversedKeyframes
+ Paste Text and Match Formatting | edit.pasteTextMatchFormatting
+ Paste Text Formatting Only | edit.pasteTextFormattingOnly
+ Clear | edit.clear
+ ---
+ Duplicate | edit.duplicate
+ Split Layer | edit.splitLayer
+ Lift Work Area | edit.liftWorkArea
+ Extract Work Area | edit.extractWorkArea
+ Select All | edit.selectAll
+ Deselect All | edit.deselectAll
+ ---
+ Label
+ Select Label Group | edit.selectLabelGroup
+ ---
+ None | edit.label {"label":"None"}
+ Red | edit.label {"label":"Red"}
+ Yellow | edit.label {"label":"Yellow"}
+ Aqua | edit.label {"label":"Aqua"}
+ Pink | edit.label {"label":"Pink"}
+ Lavender | edit.label {"label":"Lavender"}
+ Peach | edit.label {"label":"Peach"}
+ Sea Foam | edit.label {"label":"Sea Foam"}
+ Blue | edit.label {"label":"Blue"}
+ Green | edit.label {"label":"Green"}
+ Purple | edit.label {"label":"Purple"}
+ Orange | edit.label {"label":"Orange"}
+ Brown | edit.label {"label":"Brown"}
+ Fuchsia | edit.label {"label":"Fuchsia"}
+ Cyan | edit.label {"label":"Cyan"}
+ Sandstone | edit.label {"label":"Sandstone"}
+ Dark Green | edit.label {"label":"Dark Green"}
+ ---
+ Edit Label Colors... | app.settings {"page":"labels"}
+ Select Keyframe Label Group
+ On Selected Layers | keys.selectLabelGroup {"scope":"selected"}
+ On All Layers | keys.selectLabelGroup {"scope":"all"}
+ Visible Keyframes on Selected Layers | keys.selectLabelGroup {"scope":"visibleSelected"}
+ Visible Keyframes on All Layers | keys.selectLabelGroup {"scope":"visibleAll"}
+ ---
+ Purge
+ All Cache... | edit.purge {"what":"all"}
+ All Memory & Disk Cache... | edit.purge {"what":"memoryAndDisk"}
+ All Memory | edit.purge {"what":"memory"}
+ All Disk Cache... | edit.purge {"what":"disk"}
+ All 3D Cache... | edit.purge {"what":"3d"}
+ Undo | edit.purgeUndo
+ Image Cache Memory | edit.purge {"what":"image"}
+ Snapshot | edit.purge {"what":"snapshot"}
+ ---
+ Edit Original... | edit.editOriginal
+ ---
+ Templates
+ Render Settings... | app.templates {"kind":"renderSettings"}
+ Output Module... | app.templates {"kind":"outputModule"}
+ Keyboard Shortcuts | app.keyboardShortcuts
+ [!mac] Preferences
+ [!mac] General... | app.settings {"page":"general"} | Cmd+Alt+;
+ [!mac] Startup & Repair... | app.settings {"page":"startup"}
+ [!mac] Project... | app.settings {"page":"project"}
+ [!mac] Composition... | app.settings {"page":"composition"}
+ [!mac] Previews... | app.settings {"page":"previews"}
+ [!mac] Appearance... | app.settings {"page":"appearance"}
+ [!mac] Grids & Guides... | app.settings {"page":"grids"}
+ [!mac] Labels... | app.settings {"page":"labels"}
+ [!mac] Type... | app.settings {"page":"type"}
+ [!mac] Import... | app.settings {"page":"import"}
+ [!mac] Export... | app.settings {"page":"export"}
+ [!mac] Audio... | app.settings {"page":"audio"}
+ [!mac] Disk... | app.settings {"page":"disk"}
+ [!mac] Memory & CPU... | app.settings {"page":"memory"}
+ [!mac] Video... | app.settings {"page":"video"}
+ [!mac] 3D... | app.settings {"page":"3d"}
+ [!mac] Scripting & Expressions... | app.settings {"page":"scripting"}
+Composition
+ New Composition... | comp.new
+ ---
+ Composition Settings... | comp.settings
+ Set Poster Time | comp.setPosterTime
+ Trim Comp to Work Area | comp.trimToWorkArea
+ Crop Comp to Region of Interest | comp.cropToRegionOfInterest
+ Crop Comp to Selected Layer(s) Bounds | comp.cropToLayerBounds
+ ---
- Add to Render Queue | render.addToQueue
++ Add to Render Queue | renderQueue.add
+ Add Output Module | render.addOutputModule
+ ---
+ Preview
+ Play Current Preview | playback.toggle
+ Cache Frames When Idle | playback.cacheWhenIdle
+ Audio | playback.audio
+ Save Frame As
+ File... | comp.saveFrameAs
+ Pre-render... | render.preRender
+ Save Current Preview... | render.saveCurrentPreview
+ ---
+ Responsive Design — Time
+ Create Intro | comp.responsiveTime {"op":"intro"}
+ Create Outro | comp.responsiveTime {"op":"outro"}
+ Create Protected Region from Work Area | comp.responsiveTime {"op":"workArea"}
+ ---
+ Composition Flowchart | comp.flowchart
+ Composition Mini-Flowchart | comp.miniFlowchart
+Layer
+ New
+ Text | layer.newText
+ Solid... | layer.newSolid
+ Light... | layer.newLight
+ Camera... | layer.newCamera
+ Null Object | layer.newNull
+ Shape Layer | layer.newShape
+ Adjustment Layer | layer.newAdjustment
+ Content-Aware Fill Layer... | layer.newContentAwareFill
+ Cube | layer.new3dPrimitive {"kind":"cube"}
+ Sphere | layer.new3dPrimitive {"kind":"sphere"}
+ Plane | layer.new3dPrimitive {"kind":"plane"}
+ Torus | layer.new3dPrimitive {"kind":"torus"}
+ Cone | layer.new3dPrimitive {"kind":"cone"}
+ Cylinder | layer.new3dPrimitive {"kind":"cylinder"}
+ Layer Settings... | layer.settings
+ ---
+ Open Layer | layer.openLayer
+ Open Layer Source | layer.openSource
+ Reveal in Finder | layer.revealInFinder
+ ---
+ Mask
+ New Mask | layer.addMask
+ Mask Shape... | layer.mask.shape
+ Mask Feather... | layer.mask.set {"field":"feather"} | Cmd+Shift+F
+ Mask Opacity... | layer.mask.set {"field":"opacity"}
+ Mask Expansion... | layer.mask.set {"field":"expansion"}
+ Reset Mask | layer.mask.reset
+ Remove Mask | layer.mask.remove
+ Remove All Masks | layer.mask.removeAll
+ Mode
+ None | layer.mask.mode {"mode":"None"}
+ Add | layer.mask.mode {"mode":"Add"}
+ Subtract | layer.mask.mode {"mode":"Subtract"}
+ Intersect | layer.mask.mode {"mode":"Intersect"}
+ Lighten | layer.mask.mode {"mode":"Lighten"}
+ Darken | layer.mask.mode {"mode":"Darken"}
+ Difference | layer.mask.mode {"mode":"Difference"}
+ Inverted | layer.mask.invert
+ Locked | layer.mask.lock
+ Motion Blur
+ Same As Layer | layer.mask.motionBlur {"mode":"sameAsLayer"}
+ On | layer.mask.motionBlur {"mode":"on"}
+ Off | layer.mask.motionBlur {"mode":"off"}
+ Feather Falloff
+ Smooth | layer.mask.featherFalloff {"mode":"smooth"}
+ Linear | layer.mask.featherFalloff {"mode":"linear"}
+ Unlock All Masks | layer.mask.unlockAll
+ Lock Other Masks | layer.mask.lockOthers
+ Hide Locked Masks | layer.mask.hideLocked
+ Mask and Shape Path
+ RotoBezier | path.rotoBezier
- Closed | path.closed
++ Closed | mask.setClosed
+ Convert To Bezier Path | path.convertToBezier
+ Group Shapes | path.groupShapes
+ Ungroup Shapes | path.ungroupShapes
+ Set First Vertex | path.setFirstVertex
+ Free Transform Points | path.freeTransform
+ Quality
+ Best | layer.quality {"quality":"best"} | Cmd+U
+ Draft | layer.quality {"quality":"draft"} | Cmd+Shift+U
+ Wireframe | layer.quality {"quality":"wireframe"} | Cmd+Alt+Shift+U
+ ---
+ Bilinear | layer.sampling {"sampling":"bilinear"}
+ Bicubic | layer.sampling {"sampling":"bicubic"}
+ Switches
+ Hide Other Video | layer.hideOtherVideo
+ Show All Video | layer.showAllVideo
+ Unlock All Layers | layer.unlockAll
+ Enable Expressions | layer.expressions {"enabled":true}
+ Disable Expressions | layer.expressions {"enabled":false}
+ ---
+ Shy | layer.setSwitch {"switch":"shy"}
+ Lock | layer.setSwitch {"switch":"lock"} | Cmd+L
+ Audio | layer.setSwitch {"switch":"audio"}
+ Video | layer.setSwitch {"switch":"video"}
+ Solo | layer.setSwitch {"switch":"solo"}
+ Effect | layer.setSwitch {"switch":"fx"}
+ Collapse | layer.setSwitch {"switch":"collapse"}
+ Motion Blur | layer.setSwitch {"switch":"motionBlur"}
+ Adjustment Layer | layer.setSwitch {"switch":"adjustment"}
+ Transform
+ Reset | layer.transform {"op":"reset"}
+ Anchor Point... | layer.setTransform {"prop":"anchor"}
+ Position... | layer.setTransform {"prop":"position"} | Cmd+Shift+P
+ Scale... | layer.setTransform {"prop":"scale"}
+ Orientation... | layer.setTransform {"prop":"orientation"} | Cmd+Alt+Shift+R
+ Rotation... | layer.setTransform {"prop":"rotation"} | Cmd+Shift+R
+ Opacity... | layer.setTransform {"prop":"opacity"} | Cmd+Shift+O
+ ---
+ Flip Horizontal | layer.transform {"op":"flipH"}
+ Flip Vertical | layer.transform {"op":"flipV"}
+ Center In View | layer.transform {"op":"center"}
+ Center Anchor Point in Layer Content | layer.centerAnchor
+ Fit to Comp | layer.transform {"op":"fit"} | Cmd+Alt+F
+ Fit to Comp Width | layer.transform {"op":"fitWidth"} | Cmd+Alt+Shift+H
+ Fit to Comp Height | layer.transform {"op":"fitHeight"} | Cmd+Alt+Shift+G
+ ---
+ Auto-Orient... | layer.autoOrient
+ Time
- Enable Time Remapping | layer.timeRemap
- Time-Reverse Layer | layer.timeStretch {"op":"reverse"} | Cmd+Alt+R
++ Enable Time Remapping | layer.enableTimeRemap
++ Time-Reverse Layer | layer.timeReverse
+ Time Stretch... | layer.timeStretch
+ Freeze Frame | layer.freezeFrame
+ Freeze On Last Frame | layer.freezeOnLastFrame
+ Align Video to Data | layer.alignVideoToData
+ Frame Blending
+ Off | layer.frameBlending {"mode":"off"}
+ Frame Mix | layer.frameBlending {"mode":"frameMix"}
+ Pixel Motion | layer.frameBlending {"mode":"pixelMotion"}
+ 3D Layer | layer.setSwitch {"switch":"threeD"}
+ Guide Layer | layer.setSwitch {"switch":"guide"}
+ Environment Layer | layer.environment
+ Markers
+ Add Marker | layer.addMarker
+ Update Markers From Source | layer.updateMarkersFromSource
+ Lock Markers | layer.markersLock
+ Delete All Markers | layer.deleteAllMarkers
+ ---
+ Preserve Transparency | layer.setSwitch {"switch":"preserveTransparency"}
+ Blending Mode
+ Normal | layer.setBlendMode {"mode":"Normal"}
+ Dissolve | layer.setBlendMode {"mode":"Dissolve"}
+ Dancing Dissolve | layer.setBlendMode {"mode":"Dancing Dissolve"}
+ ---
+ Darken | layer.setBlendMode {"mode":"Darken"}
+ Multiply | layer.setBlendMode {"mode":"Multiply"}
+ Color Burn | layer.setBlendMode {"mode":"Color Burn"}
+ Classic Color Burn | layer.setBlendMode {"mode":"Classic Color Burn"}
+ Linear Burn | layer.setBlendMode {"mode":"Linear Burn"}
+ Darker Color | layer.setBlendMode {"mode":"Darker Color"}
+ ---
+ Add | layer.setBlendMode {"mode":"Add"}
+ Lighten | layer.setBlendMode {"mode":"Lighten"}
+ Screen | layer.setBlendMode {"mode":"Screen"}
+ Color Dodge | layer.setBlendMode {"mode":"Color Dodge"}
+ Classic Color Dodge | layer.setBlendMode {"mode":"Classic Color Dodge"}
+ Linear Dodge | layer.setBlendMode {"mode":"Linear Dodge"}
+ Lighter Color | layer.setBlendMode {"mode":"Lighter Color"}
+ ---
+ Overlay | layer.setBlendMode {"mode":"Overlay"}
+ Soft Light | layer.setBlendMode {"mode":"Soft Light"}
+ Hard Light | layer.setBlendMode {"mode":"Hard Light"}
+ Linear Light | layer.setBlendMode {"mode":"Linear Light"}
+ Vivid Light | layer.setBlendMode {"mode":"Vivid Light"}
+ Pin Light | layer.setBlendMode {"mode":"Pin Light"}
+ Hard Mix | layer.setBlendMode {"mode":"Hard Mix"}
+ ---
+ Difference | layer.setBlendMode {"mode":"Difference"}
+ Classic Difference | layer.setBlendMode {"mode":"Classic Difference"}
+ Exclusion | layer.setBlendMode {"mode":"Exclusion"}
+ Subtract | layer.setBlendMode {"mode":"Subtract"}
+ Divide | layer.setBlendMode {"mode":"Divide"}
+ ---
+ Hue | layer.setBlendMode {"mode":"Hue"}
+ Saturation | layer.setBlendMode {"mode":"Saturation"}
+ Color | layer.setBlendMode {"mode":"Color"}
+ Luminosity | layer.setBlendMode {"mode":"Luminosity"}
+ ---
+ Stencil Alpha | layer.setBlendMode {"mode":"Stencil Alpha"}
+ Stencil Luma | layer.setBlendMode {"mode":"Stencil Luma"}
+ Silhouette Alpha | layer.setBlendMode {"mode":"Silhouette Alpha"}
+ Silhouette Luma | layer.setBlendMode {"mode":"Silhouette Luma"}
+ ---
+ Alpha Add | layer.setBlendMode {"mode":"Alpha Add"}
+ Luminescent Premul | layer.setBlendMode {"mode":"Luminescent Premul"}
+ Next Blending Mode | layer.setBlendMode {"step":1} | Shift+=
+ Previous Blending Mode | layer.setBlendMode {"step":-1} | Shift+-
+ Track Matte
+ No Track Matte | layer.trackMatte {"op":"none"}
+ Alpha Matte | layer.trackMatte {"op":"alpha"}
+ Alpha Inverted Matte | layer.trackMatte {"op":"alphaInverted"}
+ Luma Matte | layer.trackMatte {"op":"luma"}
+ Luma Inverted Matte | layer.trackMatte {"op":"lumaInverted"}
+ ---
+ Matte with Layer Above | layer.trackMatte {"op":"above"}
+ Matte with Layer Below | layer.trackMatte {"op":"below"}
+ Layer Styles
+ Convert to Editable Styles | layer.styles {"op":"convert"}
+ Show All | layer.styles {"op":"showAll"}
+ Remove All | layer.styles {"op":"removeAll"}
+ ---
+ Drop Shadow | layer.styles {"style":"dropShadow"}
+ Inner Shadow | layer.styles {"style":"innerShadow"}
+ Outer Glow | layer.styles {"style":"outerGlow"}
+ Inner Glow | layer.styles {"style":"innerGlow"}
+ Bevel and Emboss | layer.styles {"style":"bevelEmboss"}
+ Satin | layer.styles {"style":"satin"}
+ Color Overlay | layer.styles {"style":"colorOverlay"}
+ Gradient Overlay | layer.styles {"style":"gradientOverlay"}
+ Stroke | layer.styles {"style":"stroke"}
+ ---
+ Arrange
+ Bring Layer to Front | layer.arrange {"to":"front"} | Cmd+Shift+]
+ Bring Layer Forward | layer.arrange {"to":"forward"} | Cmd+]
+ Send Layer Backward | layer.arrange {"to":"backward"} | Cmd+[
+ Send Layer to Back | layer.arrange {"to":"back"} | Cmd+Shift+[
+ ---
+ Reveal
+ Reveal in Finder | layer.revealInFinder
+ Reveal Layer Source in Project | layer.revealSource
+ Reveal Layer in Project Flowchart | comp.flowchart
+ Reveal Composition in Project | comp.revealInProject
+ Reveal Expression Errors | layer.revealExpressionErrors
+ Create
+ Convert to Editable Text | layer.create {"op":"editableText"}
+ Create Shapes from Text | layer.create {"op":"shapesFromText"}
+ Create Masks from Text | layer.create {"op":"masksFromText"}
+ Create Shapes from Vector Layer | layer.create {"op":"shapesFromVector"}
+ Create Keyframes from Data | layer.create {"op":"keyframesFromData"}
+ Null Controllers for Positional Points | layer.create {"op":"nullsPositional"}
+ Null Controllers for Path Points | layer.create {"op":"nullsPathPoints"}
+ Nulls Following Path Points | layer.create {"op":"nullsFollowing"}
+ Null Tracing Along Path | layer.create {"op":"nullTracing"}
+ Create 3D Layer Instance | layer.create {"op":"instance3d"}
+ ---
+ Camera
+ Create Camera from 3D View | camera.fromView
+ Create Stereo 3D Rig | camera.stereoRig
+ Create Orbit Null | camera.orbitNull
+ Create Cameras from 3D Model | camera.fromModel
+ Link Focus Distance to Point of Interest | camera.linkFocusToPoi
+ Link Focus Distance to Layer | camera.linkFocusToLayer
+ Set Focus Distance to Layer | camera.setFocusToLayer
- Camera Settings... | camera.settings
- Reset 3D View | view.reset3dView
++ Camera Settings... | layer.cameraSettings
++ Reset 3D View | view.reset3DView
+ Light
+ Create Lights from 3D Model | light.fromModel
+ Control Light with Camera | light.controlWithCamera
+ Create Environment Light Background Layer | light.environmentBackground
+ Material
+ Reveal Material Source in Project | material.revealSource
+ Reset Material | material.reset
+ Duplicate and Assign Material | material.duplicateAssign
+ Auto-trace... | layer.autoTrace
+ Pre-compose... | layer.precompose
+ Scene Edit Detection... | layer.sceneEditDetection
+Effect
+ Effect Controls | window.panel {"panel":"effectControls"} | F3
+ Last Effect | effect.applyLast
+ Remove All | effect.removeAll
+ ---
+ Manage Effects... | effect.manage
+ ---
+ @effects
+Animation
+ Save Animation Preset... | anim.savePreset
+ Apply Animation Preset... | anim.applyPreset
+ Browse Presets... | anim.browsePresets
+ ---
+ Add Keyframe | anim.addKeyframe
+ Toggle Hold Keyframe | keys.toggleHold
+ Keyframe Interpolation... | keys.interpolation
+ Keyframe Velocity... | keys.velocity
+ Keyframe Assistant
+ Convert Audio to Keyframes | keys.audioToKeyframes
+ Convert Expression to Keyframes | prop.convertExpressionToKeyframes
+ Create Keyframes from Data | layer.create {"op":"keyframesFromData"}
+ Easy Ease | keys.easyEase
+ Easy Ease In | keys.easyEaseIn
+ Easy Ease Out | keys.easyEaseOut
+ Exponential Scale | keys.exponentialScale
+ Null Controllers for Path Points | layer.create {"op":"nullsPathPoints"}
+ Null Controllers for Positional Points | layer.create {"op":"nullsPositional"}
+ Null Tracing Along Path | layer.create {"op":"nullTracing"}
+ Nulls Following Path Points | layer.create {"op":"nullsFollowing"}
+ RPF Camera Import | keys.rpfCameraImport
+ Sequence Layers... | layer.sequence
+ Time-Reverse Keyframes | keys.timeReverse
+ ---
+ Animate Text
+ Enable Per-character 3D | text.perCharacter3d
+ ---
+ Anchor Point | layer.addTextAnimator {"properties":["anchor"]}
+ Position | layer.addTextAnimator {"properties":["position"]}
+ Scale | layer.addTextAnimator {"properties":["scale"]}
+ Skew | layer.addTextAnimator {"properties":["skew"]}
+ Rotation | layer.addTextAnimator {"properties":["rotation"]}
+ Opacity | layer.addTextAnimator {"properties":["opacity"]}
+ ---
+ All Transform Properties | layer.addTextAnimator {"properties":["anchor","position","scale","skew","rotation","opacity"]}
+ ---
+ Fill Color | layer.addTextAnimator {"properties":["fillColor"]}
+ Stroke Color | layer.addTextAnimator {"properties":["strokeColor"]}
+ Stroke Width | layer.addTextAnimator {"properties":["strokeWidth"]}
+ ---
+ Tracking | layer.addTextAnimator {"properties":["tracking"]}
+ Line Anchor | text.animatorLineAnchor
+ Line Spacing | layer.addTextAnimator {"properties":["lineSpacing"]}
+ ---
+ Character Offset | layer.addTextAnimator {"properties":["characterOffset"]}
+ Character Value | text.animatorCharacterValue
+ ---
+ Blur | layer.addTextAnimator {"properties":["blur"]}
+ Variable Font Axes | text.animatorFontAxes
+ Add Text Selector
+ Range | text.addSelector {"kind":"range"}
+ Wiggly | text.addWigglySelector
+ Expression | text.addExpressionSelector
+ Remove All Text Animators | text.removeAllAnimators
+ ---
+ Add Expression | prop.setExpression
+ Separate Dimensions | prop.separateDimensions
+ Track Camera | track.camera
+ Warp Stabilizer VFX | track.warpStabilizer
+ Track Motion | track.motion
+ Track Mask | track.mask
+ Track this Property | track.property
+ ---
+ Reveal Properties with Keyframes | anim.reveal {"kind":"keyframes"} | U
+ Reveal Properties with Animation | anim.reveal {"kind":"animation"}
+ Reveal All Modified Properties | anim.reveal {"kind":"modified"}
+View
+ Split with New Locked Viewer | view.splitLockedViewer
+ ---
+ Zoom In | view.zoomIn
+ Zoom Out | view.zoomOut
+ ---
+ Resolution
+ Full | view.res.full
+ Half | view.res.half
+ Third | view.res.third
+ Quarter | view.res.quarter
+ Custom... | view.res.custom
+ ---
+ Use Display Color Management | view.displayColorManagement
+ Simulate Output
+ No Output Simulation | view.simulateOutput {"profile":"none"}
+ HDTV (Rec. 709) | view.simulateOutput {"profile":"rec709"}
+ SDTV NTSC | view.simulateOutput {"profile":"ntsc"}
+ SDTV PAL | view.simulateOutput {"profile":"pal"}
+ Legacy Macintosh RGB (Gamma 1.8) | view.simulateOutput {"profile":"mac18"}
+ Internet Standard RGB (sRGB) | view.simulateOutput {"profile":"srgb"}
+ Custom... | view.simulateOutput {"profile":"custom"}
+ ---
+ Show Rulers | view.rulers
+ Panel Background Color
+ Black | view.panelBackground {"color":"black"}
+ Dark Gray | view.panelBackground {"color":"darkGray"}
+ Medium Gray (Default) | view.panelBackground {"color":"mediumGray"}
+ Light Gray | view.panelBackground {"color":"lightGray"}
+ White | view.panelBackground {"color":"white"}
+ ---
+ Custom | view.panelBackground {"color":"custom"}
+ Select Custom Background Color... | view.panelBackground {"pick":true}
+ ---
+ Show Guides | view.guides
+ Snap to Guides | view.snapToGuides
+ Lock Guides | view.lockGuides
+ Add Guide... | view.addGuide
+ Clear Guides | view.clearGuides
+ Import Guides... | view.importGuides
+ Export Guides... | view.exportGuides
+ ---
+ Show Grid | view.grid
+ Snap to Grid | view.snapToGrid
+ ---
+ View Options... | view.options
+ Show Layer Controls | view.layerControls
+ ---
- Camera Settings... | camera.settings
- Reset 3D View | view.reset3dView
++ Camera Settings... | layer.cameraSettings
++ Reset 3D View | view.reset3DView
+ Create Camera from 3D View | camera.fromView
+ Switch View Layout
+ 1 View | view.layout {"views":1}
+ 2 Views | view.layout {"views":2}
+ 4 Views | view.layout {"views":4}
+ ---
+ Share View Options | view.shareViewOptions
+ Switch 3D View
- Active Camera | view.3d {"view":"activeCamera"} | F12
- Default | view.3d {"view":"default"}
++ Active Camera | view.3d.activeCamera
++ Default | view.3d.default
+ ---
- Front | view.3d {"view":"front"} | F10
- Left | view.3d {"view":"left"}
- Top | view.3d {"view":"top"}
- Back | view.3d {"view":"back"}
- Right | view.3d {"view":"right"}
- Bottom | view.3d {"view":"bottom"}
++ Front | view.3d.front
++ Left | view.3d.left
++ Top | view.3d.top
++ Back | view.3d.back
++ Right | view.3d.right
++ Bottom | view.3d.bottom
+ ---
- Custom View 1 | view.3d {"view":"custom1"} | F11
- Custom View 2 | view.3d {"view":"custom2"}
- Custom View 3 | view.3d {"view":"custom3"}
++ Custom View 1 | view.3d.custom1
++ Custom View 2 | view.3d.custom2
++ Custom View 3 | view.3d.custom3
+ ---
- Reset 3D View | view.reset3dView
- Switch to Last 3D View | view.last3dView
++ Reset 3D View | view.reset3DView
++ Switch to Last 3D View | view.3d.last | Escape
+ Look at Selected Layers | view.lookAtSelected
+ Look at All Layers | view.lookAtAll
+ ---
+ Go to Time... | time.set
+ Enter Full Screen | view.fullScreen
+Window
+ Workspace
+ All Panels | window.workspace {"name":"All Panels"}
+ Animation | window.workspace {"name":"Animation"}
+ Default | window.workspace {"name":"Default"} | Shift+F10
+ Effects | window.workspace {"name":"Effects"}
+ Minimal | window.workspace {"name":"Minimal"}
+ Motion Tracking | window.workspace {"name":"Motion Tracking"}
+ Paint | window.workspace {"name":"Paint"}
+ Small Screen | window.workspace {"name":"Small Screen"} | Shift+F12
+ Standard | window.workspace {"name":"Standard"} | Shift+F11
+ Text | window.workspace {"name":"Text"}
+ ---
+ Reset to Saved Layout | window.resetWorkspace
+ Save Changes to this Workspace | window.saveWorkspace
+ Save as New Workspace... | window.saveWorkspaceAs
+ Edit Workspaces... | window.editWorkspaces
+ ---
+ Align | window.panel {"panel":"align"}
+ Audio | window.panel {"panel":"audio"} | Cmd+4
+ Brushes | window.panel {"panel":"brushes"} | Cmd+9
+ Character | window.panel {"panel":"character"} | Cmd+6
+ Content-Aware Fill | window.unavailablePanel {"panel":"contentAwareFill"}
+ Effects & Presets | window.panel {"panel":"effectsPresets"} | Cmd+5
+ Info | window.panel {"panel":"info"} | Cmd+2
+ Lumetri Scopes | window.unavailablePanel {"panel":"lumetriScopes"}
+ Mask Interpolation | window.unavailablePanel {"panel":"maskInterpolation"}
+ Media Browser | window.unavailablePanel {"panel":"mediaBrowser"}
+ Metadata | window.unavailablePanel {"panel":"metadata"}
+ Motion Sketch | window.panel {"panel":"motionSketch"}
+ Paint | window.panel {"panel":"paint"} | Cmd+8
+ Paragraph | window.panel {"panel":"paragraph"} | Cmd+7
+ Preview | window.panel {"panel":"preview"} | Cmd+3
+ Progress | window.unavailablePanel {"panel":"progress"}
+ Properties | window.panel {"panel":"properties"}
+ Smoother | window.panel {"panel":"smoother"}
+ Tools | window.panel {"panel":"tools"} | Cmd+1
+ Tracker | window.panel {"panel":"tracker"}
+ Wiggler | window.panel {"panel":"wiggler"}
+ ---
+ Composition | window.panel {"panel":"composition"}
+ Effect Controls | window.panel {"panel":"effectControls"} | F3
+ Flowchart | window.panel {"panel":"flowchart"}
+ Footage | window.unavailablePanel {"panel":"footage"}
+ Layer | window.panel {"panel":"layer"}
+ Project | window.panel {"panel":"project"} | Cmd+0
+ Render Queue | window.panel {"panel":"renderQueue"} | Cmd+Alt+0
+ Timeline | window.panel {"panel":"timeline"}
+Help
+ EffectCraft Help... | help.docs {"page":"help"} | F1
+ Scripting Help... | help.docs {"page":"scripting"}
+ Expression Reference... | help.docs {"page":"expressions"}
+ Effect Reference... | help.docs {"page":"effects"}
+ Animation Presets... | anim.browsePresets
+ Keyboard Shortcuts... | app.keyboardShortcuts
+ ---
+ Join the ArtCraft Discord... | help.discord
+ Provide Feedback... | help.reportIssue
+ ---
+ ArtCraft Website | help.website
+ EffectCraft Home Page | help.appPage
+ EffectCraft on GitHub | help.github
+ Open Demo Project | file.openDemoProject
+ [!mac] ---
+ [!mac] About EffectCraft... | app.about
+"#;
+
+#[cfg(test)]
+mod tests;
diff --cc crates/engine/src/menus/tests.rs
index 672734bf6,000000000..ee8790c7d
mode 100644,000000..100644
--- a/crates/engine/src/menus/tests.rs
+++ b/crates/engine/src/menus/tests.rs
@@@ -1,148 -1,0 +1,157 @@@
+use std::collections::BTreeMap;
+
+use super::*;
+
+fn all_entries(nodes: &[MenuNode], path: &mut Vec<String>, out: &mut Vec<(Vec<String>, MenuEntry)>) {
+ for n in nodes {
+ match n {
+ MenuNode::Item(e) => out.push((path.clone(), e.clone())),
+ MenuNode::Separator => {}
+ MenuNode::Submenu { label, children } => {
+ path.push(label.clone());
+ all_entries(children, path, out);
+ path.pop();
+ }
+ }
+ }
+}
+
+fn platform_entries(mac: bool) -> Vec<(Vec<String>, MenuEntry)> {
+ let tree = parse(TREE, mac).unwrap();
+ let mut out = vec![];
+ all_entries(&tree, &mut vec![], &mut out);
+ out
+}
+
+#[test]
+fn top_level_order_matches_after_effects() {
+ let mac: Vec<String> =
+ parse(TREE, true).unwrap().iter().filter_map(|n| if let MenuNode::Submenu { label, .. } = n { Some(label.clone()) } else { None }).collect();
+ assert_eq!(mac, ["EffectCraft", "File", "Edit", "Composition", "Layer", "Effect", "Animation", "View", "Window", "Help"]);
+ let other: Vec<String> =
+ parse(TREE, false).unwrap().iter().filter_map(|n| if let MenuNode::Submenu { label, .. } = n { Some(label.clone()) } else { None }).collect();
+ assert_eq!(other, ["File", "Edit", "Composition", "Layer", "Effect", "Animation", "View", "Window", "Help"]);
+ // The live bar is one of the two.
+ assert!(top_level().len() == mac.len() || top_level().len() == other.len());
+}
+
+#[test]
+fn every_menu_entry_resolves_to_a_registered_command() {
+ for mac in [true, false] {
+ for (path, e) in platform_entries(mac) {
+ assert!(crate::commands::find(&e.command).is_some(), "{} ▸ {}: unknown command `{}`", path.join(" ▸ "), e.label, e.command);
+ assert!(e.params.is_null() || e.params.is_object(), "{}: params must be an object", e.label);
+ }
+ }
+}
+
+#[test]
+fn command_menu_paths_and_labels_agree_with_the_tree() {
+ let entries = platform_entries(true);
+ let mut by_cmd: BTreeMap<&str, Vec<&(Vec<String>, MenuEntry)>> = BTreeMap::new();
+ for e in &entries {
+ by_cmd.entry(e.1.command.as_str()).or_default().push(e);
+ }
+ for spec in crate::command_specs() {
+ if spec.menu.is_empty() {
+ continue;
+ }
+ let places = by_cmd.get(spec.id).unwrap_or_else(|| panic!("`{}` declares menu {:?} but is not in the menu tree", spec.id, spec.menu));
+ assert!(
+ places.iter().any(|(p, _)| p.iter().map(String::as_str).eq(spec.menu.iter().copied())),
+ "`{}` declares menu {:?}; the tree has it at {:?}",
+ spec.id,
+ spec.menu,
+ places.iter().map(|(p, _)| p.join(" ▸ ")).collect::<Vec<_>>()
+ );
+ for (p, e) in places {
+ if e.params.is_null() && p.iter().map(String::as_str).eq(spec.menu.iter().copied()) {
+ assert_eq!(e.label, spec.label, "label of `{}`", spec.id);
+ }
+ }
+ }
+}
+
+#[test]
+fn dialog_labels_use_ascii_ellipsis() {
+ for (_, e) in platform_entries(true) {
+ assert!(!e.label.contains('…'), "`{}` uses a Unicode ellipsis; AE's menus use \"...\"", e.label);
+ }
+}
+
+#[test]
+fn shortcuts_are_unambiguous() {
+ // shortcut → (command, params) from command defaults and menu entries.
+ let mut seen: BTreeMap<String, (String, String)> = BTreeMap::new();
+ let mut add = |sc: &str, id: &str, params: String| {
+ if sc == "Num*" {
+ return;
+ }
+ if let Some(prev) = seen.get(sc) {
+ assert_eq!(prev, &(id.to_string(), params.clone()), "shortcut {sc} is bound twice");
+ } else {
+ seen.insert(sc.to_string(), (id.to_string(), params));
+ }
+ };
+ for (_, e) in platform_entries(true) {
+ if let Some(sc) = &e.shortcut {
+ add(sc, &e.command, e.params.to_string());
+ }
+ }
+ for c in crate::command_specs() {
+ // Defaults of commands whose menu entries bind params are carried by the entries.
+ if let Some(sc) = c.shortcut
+ && !platform_entries(true).iter().any(|(_, e)| e.command == c.id && !e.params.is_null())
+ {
+ add(sc, c.id, "null".into());
+ }
+ }
+}
+
+#[test]
+fn menus_cover_after_effects_structure() {
+ let entries = platform_entries(true);
+ let count = |m: &str| entries.iter().filter(|(p, _)| p[0] == m).count();
+ // Floors (AE 2026 minus Adobe-service, history and user-specific entries).
+ assert!(count("File") >= 40, "File {}", count("File"));
+ assert!(count("Edit") >= 54, "Edit {}", count("Edit"));
+ assert!(count("Composition") >= 19, "Composition {}", count("Composition"));
+ assert!(count("Layer") >= 197, "Layer {}", count("Layer"));
+ assert!(count("Animation") >= 53, "Animation {}", count("Animation"));
+ assert!(count("View") >= 59, "View {}", count("View"));
+ assert!(count("Window") >= 43, "Window {}", count("Window"));
+ // 38 blending modes + next/previous.
+ let modes = entries.iter().filter(|(p, e)| p.last().map(String::as_str) == Some("Blending Mode") && e.command == "layer.setBlendMode").count();
+ assert_eq!(modes, 38);
+ // 16 label colours + None.
+ let labels = entries.iter().filter(|(_, e)| e.command == "edit.label").count();
+ assert_eq!(labels, 17);
+}
+
+#[test]
+fn checked_reflects_layer_state() {
+ let mut s = crate::Session::default();
+ s.execute("comp.new", serde_json::json!({"width": 320, "height": 180})).unwrap();
+ s.execute("layer.newSolid", serde_json::json!({})).unwrap();
+ s.execute("layer.setBlendMode", serde_json::json!({"mode": "Screen"})).unwrap();
+ assert_eq!(checked(&s, "layer.setBlendMode", &serde_json::json!({"mode": "Screen"})), Some(true));
+ assert_eq!(checked(&s, "layer.setBlendMode", &serde_json::json!({"mode": "Normal"})), Some(false));
+ assert_eq!(checked(&s, "layer.quality", &serde_json::json!({"quality": "best"})), Some(true));
+ assert_eq!(checked(&s, "file.save", &serde_json::json!({})), None);
+}
+
++/// `cargo test -p effectcraft-engine dump_specs -- --ignored --nocapture`: every command as TSV.
++#[test]
++#[ignore]
++fn dump_specs() {
++ for c in crate::command_specs() {
++ eprintln!("SPEC\t{}\t{}\t{}\t{}\t{}", c.id, c.label, c.menu.join(" > "), c.shortcut.unwrap_or(""), c.params);
++ }
++}
++
+#[test]
+fn parse_rejects_bad_trees() {
+ assert!(parse("File\n Empty\n", true).is_err());
+ assert!(parse("File\n Odd | file.save\n", true).is_err());
+ assert!(parse("File\n Bad | file.save {nope}\n", true).is_err());
+}
diff --cc crates/engine/src/tests_menu_cmds.rs
index de6ce1ea3,000000000..169dddfb4
mode 100644,000000..100644
--- a/crates/engine/src/tests_menu_cmds.rs
+++ b/crates/engine/src/tests_menu_cmds.rs
@@@ -1,491 -1,0 +1,492 @@@
+//! Tests for the menu-parity command families (Layer / Edit / Animation / File / Composition /
+//! View menus), including undo.
+
+use effectcraft_keyframe::Value as KV;
+use effectcraft_project::{FrameBlend, ItemKind, MatteKind, Quality, Sampling};
+use serde_json::{Value, json};
+
+use crate::{EngineError, Event, Session};
+
+fn comp() -> Session {
+ let mut s = Session::default();
+ s.execute("comp.new", json!({"name": "Main", "width": 640, "height": 360, "frameRate": 30, "duration": 10})).unwrap();
+ s
+}
+
+fn solid(s: &mut Session, color: &str) -> u64 {
+ s.execute("layer.newSolid", json!({"color": color, "width": 200, "height": 100})).unwrap()["layer"].as_u64().unwrap()
+}
+
+fn layer(s: &Session, id: u64) -> effectcraft_project::Layer {
+ s.active_comp().unwrap().layer(effectcraft_project::LayerId(id)).unwrap().clone()
+}
+
+fn tmp(name: &str) -> String {
+ let d = std::env::temp_dir().join(format!("effectcraft-menu-tests-{}", std::process::id()));
+ std::fs::create_dir_all(&d).unwrap();
+ d.join(name).to_string_lossy().to_string()
+}
+
+fn frontend_events(s: &mut Session) -> Vec<(String, Value)> {
+ s.drain_events()
+ .into_iter()
+ .filter_map(|e| match e {
+ Event::Frontend { command, params } => Some((command, params)),
+ _ => None,
+ })
+ .collect()
+}
+
+#[test]
+fn layer_quality_sampling_frame_blending_and_undo() {
+ let mut s = comp();
+ let a = solid(&mut s, "#ff0000");
+ s.execute("layer.quality", json!({"quality": "wireframe"})).unwrap();
+ s.execute("layer.sampling", json!({"sampling": "bicubic"})).unwrap();
+ s.execute("layer.frameBlending", json!({"mode": "pixelMotion"})).unwrap();
+ let l = layer(&s, a);
+ assert_eq!((l.switches.quality, l.switches.sampling, l.switches.frame_blend), (Quality::Wireframe, Sampling::Bicubic, FrameBlend::PixelMotion));
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(layer(&s, a).switches.frame_blend, FrameBlend::Off);
+ assert!(s.execute("layer.quality", json!({"quality": "fancy"})).is_err());
+}
+
+#[test]
+fn layer_switches_menu() {
+ let mut s = comp();
+ let a = solid(&mut s, "#ff0000");
+ let b = solid(&mut s, "#00ff00");
+ s.execute("layer.select", json!({"layers": [b]})).unwrap();
+ s.execute("layer.hideOtherVideo", json!({})).unwrap();
+ assert!(!layer(&s, a).switches.video && layer(&s, b).switches.video);
+ s.execute("layer.showAllVideo", json!({})).unwrap();
+ assert!(layer(&s, a).switches.video);
+ s.execute("layer.setSwitch", json!({"layers": [a, b], "switch": "lock"})).unwrap();
+ assert!(layer(&s, a).switches.locked);
+ s.execute("layer.unlockAll", json!({})).unwrap();
+ assert!(!layer(&s, a).switches.locked && !layer(&s, b).switches.locked);
+ s.execute("edit.undo", json!({})).unwrap();
+ assert!(layer(&s, a).switches.locked);
+ // Expressions on / off.
+ s.execute("prop.setExpression", json!({"layer": a, "path": "transform/opacity", "expression": "50"})).unwrap();
+ s.execute("layer.expressions", json!({"layers": [a], "enabled": false})).unwrap();
+ assert!(!layer(&s, a).props.prop("transform/opacity").unwrap().expr.as_ref().unwrap().enabled);
+ s.execute("layer.expressions", json!({"layers": [a], "enabled": true})).unwrap();
+ assert!(layer(&s, a).props.prop("transform/opacity").unwrap().has_expression());
+}
+
+#[test]
+fn transform_dialog_values_and_center_anchor() {
+ let mut s = comp();
+ let a = solid(&mut s, "#ff0000");
+ s.execute("layer.setTransform", json!({"prop": "position", "value": [100, 50]})).unwrap();
+ s.execute("layer.setTransform", json!({"prop": "rotation", "value": 90})).unwrap();
+ s.execute("layer.setTransform", json!({"prop": "opacity", "value": 25})).unwrap();
+ let l = layer(&s, a);
+ assert_eq!(l.props.prop("transform/position").unwrap().value, KV::Vec3([100.0, 50.0, 0.0]));
+ assert_eq!(l.props.prop("transform/opacity").unwrap().value.as_f64(), 25.0);
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(layer(&s, a).props.prop("transform/opacity").unwrap().value.as_f64(), 100.0);
+ assert!(s.execute("layer.setTransform", json!({"prop": "skew", "value": 1})).is_err());
+
+ // Move the anchor off-centre, then Center Anchor Point keeps the layer in place.
+ s.execute("layer.setTransform", json!({"prop": "anchor", "value": [0, 0]})).unwrap();
+ s.execute("layer.setTransform", json!({"prop": "rotation", "value": 0})).unwrap();
+ let before = layer(&s, a).props.prop("transform/position").unwrap().value.as_vec3();
+ s.execute("layer.centerAnchor", json!({})).unwrap();
+ let l = layer(&s, a);
+ assert_eq!(l.props.prop("transform/anchor").unwrap().value.as_vec2(), [100.0, 50.0]);
+ let after = l.props.prop("transform/position").unwrap().value.as_vec3();
+ assert!((after[0] - before[0] - 100.0).abs() < 1e-6 && (after[1] - before[1] - 50.0).abs() < 1e-6, "{before:?} → {after:?}");
+
+ s.execute("layer.autoOrient", json!({"mode": "alongPath"})).unwrap();
+ assert_eq!(layer(&s, a).auto_orient, effectcraft_project::AutoOrient::AlongPath);
+}
+
+#[test]
+fn mask_menu_on_existing_masks() {
+ let mut s = comp();
+ let a = solid(&mut s, "#ff0000");
+ assert!(!s.is_enabled("layer.mask.reset"));
+ s.execute("layer.addMask", json!({})).unwrap();
+ s.execute("layer.addMask", json!({"shape": "ellipse"})).unwrap();
+ assert!(s.is_enabled("layer.mask.reset"));
+ let masks = |s: &Session| layer(s, a).masks().unwrap().groups().cloned().collect::<Vec<_>>();
+ s.execute("layer.mask.set", json!({"field": "feather", "value": 12, "mask": 1})).unwrap();
+ assert_eq!(masks(&s)[0].get("feather").unwrap().value, KV::Vec2([12.0, 12.0]));
+ s.execute("layer.mask.set", json!({"field": "opacity", "value": 40})).unwrap();
+ assert!(masks(&s).iter().all(|m| m.get("opacity").unwrap().value.as_f64() == 40.0));
+ s.execute("layer.mask.invert", json!({"mask": 2})).unwrap();
+ s.execute("layer.mask.mode", json!({"mode": "Subtract", "mask": 2})).unwrap();
+ s.execute("layer.mask.lock", json!({"mask": 1})).unwrap();
+ let kinds: Vec<_> = masks(&s).iter().map(|m| m.kind.clone()).collect();
+ assert!(matches!(kinds[1], effectcraft_project::GroupKind::Mask { inverted: true, mode: effectcraft_project::MaskMode::Subtract, .. }));
+ assert!(matches!(kinds[0], effectcraft_project::GroupKind::Mask { locked: true, .. }));
+ s.execute("layer.mask.unlockAll", json!({})).unwrap();
+ assert!(matches!(masks(&s)[0].kind, effectcraft_project::GroupKind::Mask { locked: false, .. }));
+ s.execute("layer.mask.lockOthers", json!({"mask": 1})).unwrap();
+ assert!(matches!(masks(&s)[1].kind, effectcraft_project::GroupKind::Mask { locked: true, .. }));
+ s.execute("layer.mask.reset", json!({"mask": 1})).unwrap();
+ assert_eq!(masks(&s)[0].get("opacity").unwrap().value.as_f64(), 100.0);
+ s.execute("layer.mask.shape", json!({"mask": 1, "rect": [10, 10, 50, 40], "shape": "ellipse"})).unwrap();
+ s.execute("layer.mask.remove", json!({"mask": 2})).unwrap();
+ assert_eq!(masks(&s).len(), 1);
+ s.execute("layer.mask.removeAll", json!({})).unwrap();
+ assert!(masks(&s).is_empty());
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(masks(&s).len(), 1);
+}
+
+#[test]
+fn layer_markers_lock_and_delete() {
+ let mut s = comp();
+ let a = solid(&mut s, "#ff0000");
+ s.execute("time.set", json!({"time": 1.0})).unwrap();
+ s.execute("layer.addMarker", json!({"comment": "hit"})).unwrap();
+ s.execute("layer.addMarker", json!({"time": 2.0})).unwrap();
+ assert_eq!(layer(&s, a).markers.len(), 2);
+ s.execute("layer.markersLock", json!({})).unwrap();
+ assert!(layer(&s, a).markers_locked);
+ s.execute("layer.deleteAllMarkers", json!({})).unwrap();
+ assert_eq!(layer(&s, a).markers.len(), 2, "locked markers survive");
+ s.execute("layer.markersLock", json!({"value": false})).unwrap();
+ s.execute("layer.deleteAllMarkers", json!({})).unwrap();
+ assert!(layer(&s, a).markers.is_empty());
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(layer(&s, a).markers.len(), 2);
+}
+
+#[test]
+fn track_matte_menu() {
+ let mut s = comp();
+ let below = solid(&mut s, "#ff0000");
+ let top = solid(&mut s, "#00ff00");
+ s.execute("layer.select", json!({"layers": [below]})).unwrap();
+ s.execute("layer.trackMatte", json!({"op": "luma"})).unwrap();
+ let m = layer(&s, below).track_matte.unwrap();
+ assert_eq!((m.layer.0, m.kind), (top, MatteKind::Luma));
+ assert!(!layer(&s, top).switches.video);
+ s.execute("layer.trackMatte", json!({"op": "alphaInverted"})).unwrap();
+ assert_eq!(layer(&s, below).track_matte.unwrap().kind, MatteKind::AlphaInverted);
+ s.execute("layer.trackMatte", json!({"op": "none"})).unwrap();
+ assert!(layer(&s, below).track_matte.is_none());
+ s.execute("layer.select", json!({"layers": [top]})).unwrap();
+ assert!(s.execute("layer.trackMatte", json!({"op": "above"})).is_err());
+ s.execute("layer.trackMatte", json!({"op": "below"})).unwrap();
+ assert_eq!(layer(&s, top).track_matte.unwrap().layer.0, below);
+}
+
+#[test]
+fn keyframe_clipboard_paste_and_paste_reversed() {
+ let mut s = comp();
+ let a = solid(&mut s, "#ff0000");
+ let b = solid(&mut s, "#00ff00");
+ s.execute("prop.toggleAnimation", json!({"layer": a, "path": "transform/opacity"})).unwrap();
+ s.execute("time.set", json!({"time": 1.0})).unwrap();
+ s.execute("prop.set", json!({"layer": a, "path": "transform/opacity", "value": 0})).unwrap();
+ s.execute("prop.select", json!({"layer": a, "path": "transform/opacity"})).unwrap();
- assert_eq!(s.execute("edit.copy", json!({})).unwrap()["keys"], 2);
++ s.execute("edit.copy", json!({})).unwrap();
++ assert_eq!(s.state.key_clipboard.iter().map(|c| c.keys.len()).sum::<usize>(), 2);
+ s.execute("layer.select", json!({"layers": [b]})).unwrap();
+ s.execute("time.set", json!({"time": 2.0})).unwrap();
+ s.execute("edit.paste", json!({})).unwrap();
+ let keys = layer(&s, b).props.prop("transform/opacity").unwrap().keys.clone();
+ assert_eq!(keys.len(), 2);
+ assert!((keys[0].time.seconds() - 2.0).abs() < 1e-6 && keys[0].value.as_f64() == 100.0);
+ s.execute("edit.undo", json!({})).unwrap();
+ s.execute("edit.pasteReversedKeyframes", json!({})).unwrap();
+ let keys = layer(&s, b).props.prop("transform/opacity").unwrap().keys.clone();
+ assert_eq!((keys[0].value.as_f64(), keys[1].value.as_f64()), (0.0, 100.0));
+}
+
+#[test]
+fn property_links_and_expression_only() {
+ let mut s = comp();
+ let a = solid(&mut s, "#ff0000");
+ let b = solid(&mut s, "#00ff00");
+ s.execute("prop.select", json!({"layer": a, "path": "transform/position"})).unwrap();
+ s.execute("edit.copyWithPropertyLinks", json!({})).unwrap();
+ s.execute("layer.select", json!({"layers": [b]})).unwrap();
+ s.execute("edit.paste", json!({})).unwrap();
+ let e = layer(&s, b).props.prop("transform/position").unwrap().expr.clone().unwrap();
+ let name = layer(&s, a).name;
+ assert_eq!(e.text, format!("comp(\"Main\").layer({}).transform(\"Position\")", serde_json::to_string(&name).unwrap()));
+ // Relative links use thisComp.
+ s.execute("prop.select", json!({"layer": a, "path": "transform/opacity"})).unwrap();
+ s.execute("edit.copyWithRelativePropertyLinks", json!({})).unwrap();
+ s.execute("layer.select", json!({"layers": [b]})).unwrap();
+ s.execute("edit.paste", json!({})).unwrap();
+ assert!(layer(&s, b).props.prop("transform/opacity").unwrap().expr.as_ref().unwrap().text.starts_with("thisComp.layer("));
+ // Copy Expression Only.
+ s.execute("prop.setExpression", json!({"layer": a, "path": "transform/rotation", "expression": "time * 90"})).unwrap();
+ s.execute("prop.select", json!({"layer": a, "path": "transform/rotation"})).unwrap();
+ s.execute("edit.copyExpressionOnly", json!({})).unwrap();
+ s.execute("layer.select", json!({"layers": [b]})).unwrap();
+ s.execute("edit.paste", json!({})).unwrap();
+ assert_eq!(layer(&s, b).props.prop("transform/rotation").unwrap().expr.as_ref().unwrap().text, "time * 90");
+ // Layers with property links: the pasted copy follows the original.
+ s.state.selected_props.clear();
+ s.execute("layer.select", json!({"layers": [a]})).unwrap();
+ s.execute("edit.copyWithPropertyLinks", json!({})).unwrap();
+ let new = s.execute("edit.paste", json!({})).unwrap();
+ let nid = new[0].as_u64().unwrap();
+ assert!(layer(&s, nid).props.prop("transform/scale").unwrap().has_expression());
+}
+
+#[test]
+fn lift_and_extract_work_area() {
+ let mut s = comp();
+ let a = solid(&mut s, "#ff0000");
+ s.execute("comp.workArea", json!({"start": 2.0, "end": 4.0})).unwrap();
+ s.execute("edit.liftWorkArea", json!({})).unwrap();
+ let c = s.active_comp().unwrap();
+ assert_eq!(c.layers.len(), 2, "split around the gap");
+ let mut spans: Vec<(f64, f64)> = c.layers.iter().map(|l| (l.in_point.seconds(), l.out_point.seconds())).collect();
+ spans.sort_by(|x, y| x.0.total_cmp(&y.0));
+ assert!((spans[0].1 - 2.0).abs() < 1e-6 && (spans[1].0 - 4.0).abs() < 1e-6);
+ s.execute("edit.undo", json!({})).unwrap();
+ s.execute("layer.select", json!({"layers": [a]})).unwrap();
+ s.execute("edit.extractWorkArea", json!({})).unwrap();
+ let c = s.active_comp().unwrap();
+ let mut spans: Vec<(f64, f64)> = c.layers.iter().map(|l| (l.in_point.seconds(), l.out_point.seconds())).collect();
+ spans.sort_by(|x, y| x.0.total_cmp(&y.0));
+ assert!((spans[1].0 - 2.0).abs() < 1e-6 && (spans[1].1 - 8.0).abs() < 1e-6, "{spans:?}");
+}
+
+#[test]
+fn label_group_purge_and_edit_original() {
+ let mut s = comp();
+ let a = solid(&mut s, "#ff0000");
+ let b = solid(&mut s, "#00ff00");
+ let _c = solid(&mut s, "#0000ff");
+ s.execute("edit.label", json!({"layers": [a, b], "label": "Cyan"})).unwrap();
+ s.execute("layer.select", json!({"layers": [a]})).unwrap();
+ s.execute("edit.selectLabelGroup", json!({})).unwrap();
+ assert_eq!(s.state.selected_layers.len(), 2);
+ s.drain_events();
+ s.execute("edit.purge", json!({"what": "memory"})).unwrap();
+ assert!(s.drain_events().contains(&Event::PurgeCaches));
+ assert!(!s.is_enabled("edit.editOriginal"));
+}
+
+#[test]
+fn animation_menu_keys_presets_text() {
+ let mut s = comp();
+ let a = solid(&mut s, "#ff0000");
+ // Add Keyframe on selected properties.
+ s.execute("prop.select", json!({"layer": a, "path": "transform/scale"})).unwrap();
+ s.execute("anim.addKeyframe", json!({})).unwrap();
+ s.execute("time.set", json!({"time": 1.0})).unwrap();
+ s.execute("prop.set", json!({"layer": a, "path": "transform/scale", "value": [400, 400]})).unwrap();
+ assert_eq!(layer(&s, a).props.prop("transform/scale").unwrap().keys.len(), 2);
+ // Exponential Scale: a key per frame, geometric in between.
+ s.execute("prop.select", json!({"layer": a, "path": "transform/scale"})).unwrap();
+ s.execute("keys.exponentialScale", json!({})).unwrap();
+ let keys = layer(&s, a).props.prop("transform/scale").unwrap().keys.clone();
+ assert_eq!(keys.len(), 31);
+ assert!((keys[15].value.as_vec3()[0] - 200.0).abs() < 1e-6, "{:?}", keys[15].value);
+ s.execute("edit.undo", json!({})).unwrap();
+ // Time-Reverse Keyframes.
+ s.execute("prop.select", json!({"layer": a, "path": "transform/scale"})).unwrap();
+ s.execute("keys.timeReverse", json!({})).unwrap();
+ let keys = layer(&s, a).props.prop("transform/scale").unwrap().keys.clone();
+ assert_eq!((keys[0].value.as_vec3()[0], keys[1].value.as_vec3()[0]), (400.0, 100.0));
+
+ // Presets round-trip through a file onto another layer at the CTI.
+ let path = tmp("scale.ecpreset");
+ s.execute("prop.select", json!({"layer": a, "path": "transform/scale"})).unwrap();
+ s.execute("anim.savePreset", json!({"path": path})).unwrap();
+ let b = solid(&mut s, "#00ff00");
+ s.execute("time.set", json!({"time": 3.0})).unwrap();
+ let r = s.execute("anim.applyPreset", json!({"path": path, "layers": [b]})).unwrap();
+ assert_eq!(r["applied"], 1);
+ let keys = layer(&s, b).props.prop("transform/scale").unwrap().keys.clone();
+ assert_eq!(keys.len(), 2);
+ assert!((keys[0].time.seconds() - 3.0).abs() < 1e-6);
+
+ // Text: animate, add selector, reveal, remove all.
+ let t = s.execute("layer.newText", json!({"text": "Hi"})).unwrap()["layer"].as_u64().unwrap();
+ s.execute("layer.addTextAnimator", json!({"properties": ["anchor", "position", "scale", "skew", "rotation", "opacity"]})).unwrap();
+ s.execute("text.addSelector", json!({"kind": "range"})).unwrap();
+ let anim = layer(&s, t).props.group("text/animators").unwrap().groups().next().unwrap().clone();
+ assert_eq!(anim.sub("selectors").unwrap().children.len(), 2);
+ assert_eq!(anim.sub("properties").unwrap().children.len(), 6);
+ assert!(s.execute("text.addSelector", json!({"kind": "wiggly"})).is_err());
+ s.execute("text.removeAllAnimators", json!({})).unwrap();
+ assert!(layer(&s, t).props.group("text/animators").unwrap().children.is_empty());
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(layer(&s, t).props.group("text/animators").unwrap().children.len(), 1);
+}
+
+#[test]
+fn reveal_properties() {
+ let mut s = comp();
+ let a = solid(&mut s, "#ff0000");
+ s.execute("prop.toggleAnimation", json!({"layer": a, "path": "transform/rotation"})).unwrap();
+ s.execute("prop.setExpression", json!({"layer": a, "path": "transform/opacity", "expression": "50"})).unwrap();
+ s.execute("prop.set", json!({"layer": a, "path": "transform/scale", "value": [50, 50]})).unwrap();
+ s.drain_events();
+ let n = |v: &Value| v["props"].as_array().unwrap().len();
+ assert_eq!(n(&s.execute("anim.reveal", json!({"kind": "keyframes"})).unwrap()), 1);
+ assert_eq!(n(&s.execute("anim.reveal", json!({"kind": "animation"})).unwrap()), 2);
+ assert_eq!(n(&s.execute("anim.reveal", json!({"kind": "modified"})).unwrap()), 3);
+ assert!(frontend_events(&mut s).iter().all(|(c, _)| c == "timeline.revealProps"));
+}
+
+#[test]
+fn sequence_layers() {
+ let mut s = comp();
+ let a = solid(&mut s, "#ff0000");
+ let b = solid(&mut s, "#00ff00");
+ let c = solid(&mut s, "#0000ff");
+ for (id, out) in [(a, 2.0), (b, 3.0), (c, 1.0)] {
+ s.execute("layer.timing", json!({"layers": [id], "out": out})).unwrap();
+ }
+ s.execute("layer.sequence", json!({"layers": [a, b, c], "overlap": true, "duration": 0.5, "transition": "dissolveFront"})).unwrap();
+ assert!((layer(&s, b).in_point.seconds() - 1.5).abs() < 1e-6);
+ assert!((layer(&s, c).in_point.seconds() - 4.0).abs() < 1e-6);
+ assert_eq!(layer(&s, c).props.prop("transform/opacity").unwrap().keys.len(), 2);
+}
+
+#[test]
+fn file_menu_project_ops() {
+ let mut s = comp();
+ let f = s.execute("project.newFolder", json!({"name": "Stuff"})).unwrap()["item"].as_u64().unwrap();
+ assert!(s.project.item(effectcraft_project::ItemId(f)).unwrap().is_folder());
+ let p1 = s.execute("file.importPlaceholder", json!({"name": "Shot 1", "width": 320, "height": 240})).unwrap()["item"].as_u64().unwrap();
+ let p2 = s.execute("file.importPlaceholder", json!({"name": "Unused"})).unwrap()["item"].as_u64().unwrap();
+ s.execute("file.importSolid", json!({"name": "Grey"})).unwrap();
+ s.state.project_selection = vec![effectcraft_project::ItemId(p1)];
+ let r = s.execute("file.newCompFromSelection", json!({})).unwrap();
+ let nc = effectcraft_project::ItemId(r["comps"][0].as_u64().unwrap());
+ assert_eq!((s.project.comp(nc).unwrap().width, s.project.comp(nc).unwrap().layers.len()), (320, 1));
+ // Missing footage = the placeholders.
+ let miss = s.execute("file.findMissing", json!({"what": "footage"})).unwrap();
+ assert_eq!(miss["items"].as_array().unwrap().len(), 2);
+ assert!(s.execute("file.findMissing", json!({"what": "fonts"})).is_ok());
+ // Interpretation.
+ s.state.project_selection = vec![effectcraft_project::ItemId(p1)];
+ s.execute("file.interpretFootage", json!({"frameRate": 24, "alpha": "premultiplied", "loop": 3})).unwrap();
+ s.execute("file.rememberInterpretation", json!({})).unwrap();
+ s.state.project_selection = vec![effectcraft_project::ItemId(p2)];
+ s.execute("file.applyInterpretation", json!({})).unwrap();
+ match &s.project.item(effectcraft_project::ItemId(p2)).unwrap().kind {
+ ItemKind::Footage(f) => assert_eq!((f.alpha, f.loop_count, f.frame_rate.as_f64().round()), (effectcraft_project::AlphaMode::Premultiplied, 3, 24.0)),
+ _ => panic!(),
+ }
+ // Remove Unused Footage drops the unused placeholder and the unused solid.
+ let before = s.project.items.len();
+ s.execute("file.removeUnusedFootage", json!({})).unwrap();
+ assert_eq!(s.project.items.len(), before - 2);
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(s.project.items.len(), before);
+ // Replace with a solid retargets the layer.
+ s.state.project_selection = vec![effectcraft_project::ItemId(p1)];
+ s.execute("file.replaceWithSolid", json!({"color": "#336699"})).unwrap();
+ assert!(matches!(s.project.comp(nc).unwrap().layers[0].source, effectcraft_project::LayerSource::Solid { .. }));
+ // Reduce Project keeps only the selected comp and what it uses (+ folders of kept items).
+ s.state.project_selection = vec![nc];
+ s.execute("file.reduceProject", json!({})).unwrap();
+ assert!(s.project.items.len() <= 2, "{:?}", s.project.items.values().map(|i| &i.name).collect::<Vec<_>>());
+ // Save a copy leaves the session path alone.
+ let path = tmp("copy.ecproj");
+ s.execute("file.saveCopy", json!({"path": path})).unwrap();
+ assert!(s.path.is_none() && std::fs::metadata(&path).is_ok());
+ s.execute("file.closeProject", json!({})).unwrap();
+ assert!(s.project.items.is_empty());
+}
+
+#[test]
+fn consolidate_duplicate_footage() {
+ let mut s = comp();
+ let f = |s: &mut Session| s.execute("file.importPlaceholder", json!({})).unwrap()["item"].as_u64().unwrap();
+ let a = f(&mut s);
+ let b = f(&mut s);
+ // Give both the same file path.
+ let mut p = (*s.project).clone();
+ for id in [a, b] {
+ if let Some(ItemKind::Footage(ft)) = p.item_mut(effectcraft_project::ItemId(id)).map(|i| &mut i.kind) {
+ ft.path = "/media/shot.mov".into();
+ }
+ }
+ s.project = std::sync::Arc::new(p);
+ s.execute("layer.addItem", json!({"item": b})).unwrap();
+ assert_eq!(s.execute("file.consolidateFootage", json!({})).unwrap()["removed"], 1);
+ let c = s.active_comp().unwrap();
+ assert_eq!(c.layers[0].source.item().unwrap().0, a);
+}
+
+#[test]
+fn run_script_steps() {
+ let mut s = comp();
+ let path = tmp("script.jsonl");
+ std::fs::write(&path, "// make two solids\n{\"command\":\"layer.newSolid\",\"params\":{\"color\":\"#ff0000\"}}\n{\"method\":\"engine.execute\",\"params\":{\"id\":\"layer.newNull\",\"params\":{}}}\n").unwrap();
+ let r = s.execute("file.runScript", json!({"path": path})).unwrap();
+ assert_eq!(r["steps"], 2);
+ assert_eq!(s.active_comp().unwrap().layers.len(), 2);
+ assert!(s.execute("file.runScript", json!({"steps": [{"command": "nope.nope"}]})).is_err());
+}
+
+#[test]
+fn crop_comp_and_save_frame() {
+ let mut s = comp();
+ let a = solid(&mut s, "#ff0000");
+ // ROI crop moves layers so nothing shifts on screen.
+ assert!(!s.is_enabled("comp.cropToRegionOfInterest"));
+ s.execute("view.setRegionOfInterest", json!({"rect": [100, 50, 200, 100]})).unwrap();
+ s.execute("comp.cropToRegionOfInterest", json!({})).unwrap();
+ let c = s.active_comp().unwrap();
+ assert_eq!((c.width, c.height), (200, 100));
+ assert_eq!(layer(&s, a).props.prop("transform/position").unwrap().value.as_vec2(), [220.0, 130.0]);
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(s.active_comp().unwrap().width, 640);
+ // Crop to the selected layer's bounds (a 200×100 solid centred in 640×360).
+ s.execute("layer.select", json!({"layers": [a]})).unwrap();
+ let r = s.execute("comp.cropToLayerBounds", json!({})).unwrap();
+ assert_eq!((r["width"].as_u64(), r["height"].as_u64()), (Some(200), Some(100)));
+ assert_eq!(layer(&s, a).props.prop("transform/position").unwrap().value.as_vec2(), [100.0, 50.0]);
+ // Save Frame As ▸ File… writes a PNG.
+ let path = tmp("frame.png");
+ let r = s.execute("comp.saveFrameAs", json!({"path": path, "scale": 0.5})).unwrap();
+ assert_eq!(r["width"], 100);
+ let bytes = std::fs::read(&path).unwrap();
+ assert_eq!(&bytes[..8], b"\x89PNG\r\n\x1a\n");
+ // Responsive Design — Time.
+ s.execute("time.set", json!({"time": 2.0})).unwrap();
+ s.execute("comp.responsiveTime", json!({"op": "intro"})).unwrap();
+ let m = &s.active_comp().unwrap().markers[0];
+ assert!(m.protected && (m.duration.seconds() - 2.0).abs() < 1e-6);
+}
+
+#[test]
+fn guides_add_clear_import_export() {
+ let mut s = comp();
+ s.execute("view.addGuide", json!({"orientation": "horizontal", "position": 40})).unwrap();
+ s.execute("view.addGuide", json!({})).unwrap();
+ assert_eq!(s.active_comp().unwrap().guides.len(), 2);
+ assert_eq!(s.active_comp().unwrap().guides[1].position, 320.0);
+ let path = tmp("guides.json");
+ s.execute("view.exportGuides", json!({"path": path})).unwrap();
+ s.execute("view.clearGuides", json!({})).unwrap();
+ assert!(s.active_comp().unwrap().guides.is_empty());
+ s.execute("edit.undo", json!({})).unwrap();
+ assert_eq!(s.active_comp().unwrap().guides.len(), 2);
+ s.execute("view.clearGuides", json!({})).unwrap();
+ s.execute("view.importGuides", json!({"path": path})).unwrap();
+ assert_eq!(s.active_comp().unwrap().guides.len(), 2);
+}
+
+#[test]
+fn frontend_commands_emit_events_and_stubs_are_disabled() {
+ let mut s = comp();
+ s.drain_events();
+ s.execute("view.zoomIn", json!({})).unwrap();
+ s.execute("window.panel", json!({"panel": "align"})).unwrap();
+ let ev = frontend_events(&mut s);
+ assert_eq!(ev[0].0, "view.zoomIn");
+ assert_eq!(ev[1], ("window.panel".to_string(), json!({"panel": "align"})));
- for id in ["render.addToQueue", "layer.timeRemap", "camera.fromView", "view.3d", "layer.styles", "prop.separateDimensions"] {
++ for id in ["render.addOutputModule", "path.rotoBezier", "camera.fromView", "view.3d.default", "layer.styles", "track.motion"] {
+ assert!(!s.is_enabled(id), "{id}");
+ assert!(matches!(s.execute(id, json!({})), Err(EngineError::Disabled(..))), "{id}");
+ }
+}
diff --cc crates/project/src/build.rs
index ece3d2574,9f78aa500..0e582de92
--- a/crates/project/src/build.rs
+++ b/crates/project/src/build.rs
@@@ -501,8 -535,7 +535,8 @@@ pub fn layer(project: &mut Project, com
track_matte: None,
parent: None,
markers: vec![],
+ markers_locked: false,
- auto_orient: Default::default(),
+ auto_orient,
props: root,
}
}
diff --cc crates/ui-egui/src/lib.rs
index 898c51142,606136057..ea7464512
--- a/crates/ui-egui/src/lib.rs
+++ b/crates/ui-egui/src/lib.rs
@@@ -41,16 -41,11 +41,21 @@@ pub enum Dialog
CompSettings,
SolidSettings,
CommandPalette,
+ /// Settings (Preferences) on `dialog_state.settings_page`.
+ Settings,
+ /// Edit ▸ Keyboard Shortcuts.
+ Shortcuts,
+ /// A generic parameter form for a command (`dialog_state.form`).
+ Form,
+ /// A message (`dialog_state.info`).
+ Info,
+ /// View ▸ View Options.
+ ViewOptions,
+ CameraSettings,
+ LightSettings,
+ KeyVelocity,
+ KeyInterpolation,
+ TimeStretch,
}
/// Host hooks provided by the native app (file pickers etc.).
diff --cc crates/ui-egui/src/menus.rs
index 3a5e014b0,efc9efbfc..d3c01f687
--- a/crates/ui-egui/src/menus.rs
+++ b/crates/ui-egui/src/menus.rs
@@@ -105,9 -121,14 +105,13 @@@ fn no_params(p: &Value) -> bool
/// Execute a UI or engine command by id.
pub fn invoke(app: &mut EffectcraftApp, ctx: &egui::Context, id: &str, params: Value) -> Result<Value, String> {
let now = ctx.input(|i| i.time);
+ // New Camera/Light and Camera/Light Settings without parameters open their dialogs.
+ if crate::panels::dialogs_3d::route(app, id, &params)? {
+ return Ok(Value::Null);
+ }
+ // Legacy per-panel / per-workspace ids (`window.panel.Project`, `window.workspace.default`).
if let Some(rest) = id.strip_prefix("window.panel.") {
- let p = PanelKind::from_name(rest).ok_or_else(|| format!("unknown panel `{rest}`"))?;
- app.show_panel(p);
- return Ok(Value::Null);
+ return frontend(app, ctx, "window.panel", json!({"panel": rest}));
}
if let Some(ws) = id.strip_prefix("window.workspace.") {
if ws == "reset" {
@@@ -201,17 -237,51 +205,58 @@@
"timeline.moveOutToTime" => return timing(app, "moveOutToTime"),
"timeline.trimInToTime" => return timing(app, "trimInToTime"),
"timeline.trimOutToTime" => return timing(app, "trimOutToTime"),
- "app.about" => app.dialog = Some(crate::Dialog::About),
"app.home" => app.ui.start_screen = !app.ui.start_screen,
- "app.commandPalette" => {
- app.dialog_state.palette_query.clear();
- app.dialog = Some(crate::Dialog::CommandPalette);
- }
- "app.newComp" | "comp.new" if params.as_object().is_none_or(|m| m.is_empty()) => {
- crate::panels::dialogs::open_new_comp(app);
- }
- "app.compSettings" | "comp.settings" if params.as_object().is_none_or(|m| m.is_empty()) => {
- crate::panels::dialogs::open_comp_settings(app)?;
- }
- "keys.velocity" if params.as_object().is_none_or(|m| m.is_empty()) => crate::panels::key_dialogs::open_velocity(app)?,
- "keys.interpolation" if params.as_object().is_none_or(|m| m.is_empty()) => crate::panels::key_dialogs::open_interpolation(app)?,
- "layer.timeStretch" if params.as_object().is_none_or(|m| m.is_empty()) => crate::panels::key_dialogs::open_time_stretch(app)?,
- "app.solidSettings" | "layer.newSolid" if params.as_object().is_none_or(|m| m.is_empty()) => {
- crate::panels::dialogs::open_new_solid(app)?;
- }
+ "app.newComp" | "comp.new" if no_params(&params) => crate::panels::dialogs::open_new_comp(app),
+ "app.compSettings" | "comp.settings" if no_params(&params) => crate::panels::dialogs::open_comp_settings(app)?,
+ "app.solidSettings" | "layer.newSolid" if no_params(&params) => crate::panels::dialogs::open_new_solid(app)?,
++ "keys.velocity" if no_params(&params) => crate::panels::key_dialogs::open_velocity(app)?,
++ "keys.interpolation" if no_params(&params) => crate::panels::key_dialogs::open_interpolation(app)?,
++ "layer.timeStretch" if no_params(&params) => crate::panels::key_dialogs::open_time_stretch(app)?,
_ => {
- if (id == "file.import" && params.get("paths").is_none() && params.get("path").is_none())
- || (id == "file.saveAs" && params.get("path").is_none())
- || (id == "file.open" && params.get("path").is_none())
- || (id == "file.save" && params.get("path").is_none() && app.session.path.is_none())
- {
- return file_dialog(app, id);
++ if id == "renderQueue.render" && params.get("wait").is_none() {
++ // The UI renders in the background; the panel shows progress.
++ let mut p = params.clone();
++ if let Some(m) = p.as_object_mut() {
++ m.insert("wait".into(), json!(false));
++ } else {
++ p = json!({"wait": false});
++ }
++ app.show_panel(PanelKind::RenderQueue);
++ return app.session.execute(id, p).map_err(|e| e.to_string());
++ }
++ if id == "renderQueue.add" {
++ let r = app.session.execute(id, params).map_err(|e| e.to_string());
++ match &r {
++ Ok(_) => app.show_panel(PanelKind::RenderQueue),
++ Err(e) => app.ui.status = e.clone(),
++ }
++ return r;
++ }
+ if let Some(r) = file_dialog(app, id, &params) {
+ return r;
+ }
+ if crate::panels::dialogs::open_form(app, id, &params) {
+ return Ok(json!({"dialog": id}));
}
+ if id == "renderQueue.render" && params.get("wait").is_none() {
+ // The UI renders in the background; the panel shows progress.
+ let mut p = params.clone();
+ if let Some(m) = p.as_object_mut() {
+ m.insert("wait".into(), json!(false));
+ } else {
+ p = json!({"wait": false});
+ }
+ app.show_panel(PanelKind::RenderQueue);
+ return app.session.execute(id, p).map_err(|e| e.to_string());
+ }
+ if id == "renderQueue.add" {
+ let r = app.session.execute(id, params).map_err(|e| e.to_string());
+ match &r {
+ Ok(_) => app.show_panel(PanelKind::RenderQueue),
+ Err(e) => app.ui.status = e.clone(),
+ }
+ return r;
+ }
if id == "layer.rename" && params.get("name").is_none() {
crate::panels::timeline::begin_rename(app, ctx);
return Ok(Value::Null);
diff --cc crates/ui-egui/src/panels/dialogs.rs
index 9b401c2ad,e277af46a..a92c3db3f
--- a/crates/ui-egui/src/panels/dialogs.rs
+++ b/crates/ui-egui/src/panels/dialogs.rs
@@@ -35,12 -19,11 +20,17 @@@ pub struct DialogState
pub solid_size: [u32; 2],
pub palette_query: String,
pub palette_sel: usize,
+ /// Settings dialog page id (`general`, `appearance`…).
+ pub settings_page: String,
+ /// The open parameter form.
+ pub form: super::forms::Form,
+ /// Message box (title, body).
+ pub info: (String, String),
+ pub camera: super::dialogs_3d::CameraDraft,
+ pub light: super::dialogs_3d::LightDraft,
+ pub velocity: super::key_dialogs::VelocityDraft,
+ pub interp: super::key_dialogs::InterpDraft,
+ pub stretch: super::key_dialogs::StretchDraft,
}
pub fn open_new_comp(app: &mut EffectcraftApp) {
@@@ -102,11 -91,11 +98,16 @@@ pub fn show(app: &mut EffectcraftApp, c
Dialog::NewComp | Dialog::CompSettings => comp_settings(app, ctx, &t, d == Dialog::CompSettings),
Dialog::SolidSettings => solid(app, ctx, &t),
Dialog::CommandPalette => palette(app, ctx, &t),
+ Dialog::Settings => super::forms::show_settings(app, ctx, &t),
+ Dialog::Shortcuts => super::forms::show_shortcuts(app, ctx, &t),
+ Dialog::Form => super::forms::show_form(app, ctx, &t),
+ Dialog::Info => super::forms::show_info(app, ctx, &t),
+ Dialog::ViewOptions => super::forms::show_view_options(app, ctx, &t),
+ Dialog::CameraSettings => super::dialogs_3d::camera(app, ctx, &t),
+ Dialog::LightSettings => super::dialogs_3d::light(app, ctx, &t),
+ Dialog::KeyVelocity => super::key_dialogs::velocity(app, ctx, &t),
+ Dialog::KeyInterpolation => super::key_dialogs::interpolation(app, ctx, &t),
+ Dialog::TimeStretch => super::key_dialogs::time_stretch(app, ctx, &t),
}
}
diff --cc crates/ui-egui/src/panels/forms.rs
index b02340b35,000000000..8965076e5
mode 100644,000000..100644
--- a/crates/ui-egui/src/panels/forms.rs
+++ b/crates/ui-egui/src/panels/forms.rs
@@@ -1,547 -1,0 +1,544 @@@
+//! Menu dialogs: a generic parameter form (numeric Transform dialogs, Mask Feather/Opacity/
+//! Expansion, Auto-Orient, Go to Time, Add Guide, Sequence Layers, Interpret Footage, Project
+//! Settings, placeholders…), Settings (Preferences), Keyboard Shortcuts, View Options and simple
+//! message boxes. Every form runs an engine command with the collected parameters, so whatever a
+//! dialog does an agent can do with one `engine.execute`.
+
+use egui::{Color32, vec2};
+use serde_json::{Map, Value, json};
+
+use crate::theme::Tokens;
+use crate::{Dialog, EffectcraftApp};
+
+#[derive(Clone, Debug)]
+pub enum FieldKind {
+ Number {
+ value: f64,
+ speed: f64,
+ },
+ Text(String),
+ Bool(bool),
+ /// Options as (label, value); `sel` is the chosen index.
+ Choice {
+ options: Vec<(String, Value)>,
+ sel: usize,
+ },
+}
+
+/// One form field. `key` may index into an array param (`value[1]`).
+#[derive(Clone, Debug)]
+pub struct Field {
+ pub key: String,
+ pub label: String,
+ pub kind: FieldKind,
+}
+
+impl Field {
+ pub fn num(key: &str, label: &str, value: f64) -> Field {
+ Field { key: key.into(), label: label.into(), kind: FieldKind::Number { value, speed: 1.0 } }
+ }
+ pub fn text(key: &str, label: &str, value: &str) -> Field {
+ Field { key: key.into(), label: label.into(), kind: FieldKind::Text(value.into()) }
+ }
+ pub fn bool(key: &str, label: &str, value: bool) -> Field {
+ Field { key: key.into(), label: label.into(), kind: FieldKind::Bool(value) }
+ }
+ pub fn choice(key: &str, label: &str, options: &[(&str, Value)], sel: usize) -> Field {
+ Field {
+ key: key.into(),
+ label: label.into(),
+ kind: FieldKind::Choice { options: options.iter().map(|(l, v)| (l.to_string(), v.clone())).collect(), sel },
+ }
+ }
+}
+
+#[derive(Clone, Debug, Default)]
+pub struct Form {
+ pub title: String,
+ pub command: String,
+ pub base: Value,
+ pub fields: Vec<Field>,
+}
+
+impl Form {
+ /// The command parameters: `base` plus every field.
+ pub fn params(&self) -> Value {
+ let mut m: Map<String, Value> = self.base.as_object().cloned().unwrap_or_default();
+ for f in &self.fields {
+ let v = match &f.kind {
+ FieldKind::Number { value, .. } => json!(value),
+ FieldKind::Text(s) => json!(s),
+ FieldKind::Bool(b) => json!(b),
+ FieldKind::Choice { options, sel } => options.get(*sel).map(|o| o.1.clone()).unwrap_or(Value::Null),
+ };
+ match f.key.split_once('[') {
+ Some((name, idx)) => {
+ let i: usize = idx.trim_end_matches(']').parse().unwrap_or(0);
+ let arr = m.entry(name.to_string()).or_insert_with(|| json!([]));
+ if let Value::Array(a) = arr {
+ while a.len() <= i {
+ a.push(json!(0));
+ }
+ a[i] = v;
+ }
+ }
+ None => {
+ m.insert(f.key.clone(), v);
+ }
+ }
+ }
+ Value::Object(m)
+ }
+}
+
+/// Open a form dialog.
+pub fn form(app: &mut EffectcraftApp, title: &str, command: &str, base: Value, fields: Vec<Field>) {
+ app.dialog_state.form = Form { title: title.into(), command: command.into(), base, fields };
+ app.dialog = Some(Dialog::Form);
+}
+
+/// Open a message box.
+pub fn info(app: &mut EffectcraftApp, title: &str, body: &str) {
+ app.dialog_state.info = (title.into(), body.into());
+ app.dialog = Some(Dialog::Info);
+}
+
+fn has(p: &Value, keys: &[&str]) -> bool {
+ keys.iter().any(|k| p.get(*k).is_some())
+}
+
+/// If `id` is a dialog command invoked without its parameters, open its form and return true.
+pub fn open_form(app: &mut EffectcraftApp, id: &str, p: &Value) -> bool {
+ let s = &app.session;
+ let comp = s.active_comp();
+ let layer = comp.and_then(|c| s.state.selected_layers.first().and_then(|l| c.layer(*l)));
+ let t = s.time();
+ let lt = layer.map(|l| l.layer_time(t)).unwrap_or(t);
+ let base = p.clone();
+ let (title, fields): (String, Vec<Field>) = match id {
+ "layer.setTransform" if !has(p, &["value"]) => {
+ let prop = p.get("prop").and_then(Value::as_str).unwrap_or("position");
+ let cur = layer.and_then(|l| l.transform()).and_then(|tr| tr.get(if prop == "anchorPoint" { "anchor" } else { prop })).map(|pr| pr.value_at(lt));
+ let v = cur.map(|c| c.as_vec3()).unwrap_or([0.0; 3]);
+ let three = layer.is_some_and(|l| l.is_3d());
+ let title = match prop {
+ "anchor" => "Anchor Point",
+ "position" => "Position",
+ "scale" => "Scale",
+ "orientation" => "Orientation",
+ "rotation" => "Rotation",
+ _ => "Opacity",
+ };
+ let fields = match prop {
+ "rotation" | "opacity" => vec![Field::num("value", if prop == "rotation" { "Degrees" } else { "Opacity (%)" }, v[0])],
+ "orientation" => vec![Field::num("value[0]", "X", v[0]), Field::num("value[1]", "Y", v[1]), Field::num("value[2]", "Z", v[2])],
+ _ if three => vec![Field::num("value[0]", "X", v[0]), Field::num("value[1]", "Y", v[1]), Field::num("value[2]", "Z", v[2])],
+ _ => vec![Field::num("value[0]", "X", v[0]), Field::num("value[1]", "Y", v[1])],
+ };
+ (title.into(), fields)
+ }
+ "layer.mask.set" if !has(p, &["value"]) => {
+ let field = p.get("field").and_then(Value::as_str).unwrap_or("feather");
+ let first = layer.and_then(|l| l.masks()).and_then(|m| m.groups().next()).and_then(|g| g.get(field)).map(|pr| pr.value_at(lt).as_f64());
+ let (title, label, d) = match field {
+ "feather" => ("Mask Feather", "Feather (pixels)", 0.0),
+ "opacity" => ("Mask Opacity", "Opacity (%)", 100.0),
+ _ => ("Mask Expansion", "Expansion (pixels)", 0.0),
+ };
+ (title.into(), vec![Field::num("value", label, first.unwrap_or(d))])
+ }
+ "layer.mask.shape" if !has(p, &["rect"]) => {
+ let (w, h) = layer.map(|l| effectcraft_engine::render::source_size(&s.project, l)).unwrap_or((100, 100));
+ (
+ "Mask Shape".into(),
+ vec![
+ Field::num("rect[0]", "Left", 0.0),
+ Field::num("rect[1]", "Top", 0.0),
+ Field::num("rect[2]", "Width", w as f64),
+ Field::num("rect[3]", "Height", h as f64),
+ Field::choice("shape", "Shape", &[("Rectangle", json!("rect")), ("Ellipse", json!("ellipse"))], 0),
+ ],
+ )
+ }
+ "layer.autoOrient" if !has(p, &["mode"]) => {
+ let cur = layer.map(|l| l.auto_orient as usize).unwrap_or(0);
+ (
+ "Auto-Orientation".into(),
+ vec![Field::choice(
+ "mode",
+ "Mode",
+ &[
+ ("Off", json!("off")),
+ ("Orient Along Path", json!("alongPath")),
+ ("Orient Towards Camera", json!("towardsCamera")),
+ ("Orient Towards Point of Interest", json!("towardsPointOfInterest")),
+ ],
+ cur.min(3),
+ )],
+ )
+ }
+ "time.set" if !has(p, &["time", "frame", "timecode"]) => {
+ let frame = comp.map(|c| c.frame_rate.frame_at(t)).unwrap_or(0);
+ ("Go to Time".into(), vec![Field::num("frame", "Frame", frame as f64)])
+ }
+ "view.addGuide" if !has(p, &["position"]) => {
+ let (w, _) = comp.map(|c| (c.width, c.height)).unwrap_or((1920, 1080));
+ (
+ "Add Guide".into(),
+ vec![
+ Field::choice("orientation", "Orientation", &[("Vertical", json!("vertical")), ("Horizontal", json!("horizontal"))], 0),
+ Field::num("position", "Position (pixels)", w as f64 / 2.0),
+ ],
+ )
+ }
+ "layer.sequence" if !has(p, &["overlap"]) => (
+ "Sequence Layers".into(),
+ vec![
+ Field::bool("overlap", "Overlap", false),
+ Field::num("duration", "Duration (seconds)", 1.0),
+ Field::choice(
+ "transition",
+ "Transition",
+ &[
+ ("Off", json!("off")),
+ ("Dissolve Front Layer", json!("dissolveFront")),
+ ("Cross Dissolve Front and Back Layers", json!("crossDissolve")),
+ ],
+ 0,
+ ),
+ ],
+ ),
+ "file.interpretFootage" if !has(p, &["frameRate", "alpha", "loop", "pixelAspect"]) => {
+ let f = s.state.project_selection.first().and_then(|i| s.project.item(*i)).and_then(|it| match &it.kind {
+ effectcraft_engine::project::ItemKind::Footage(f) => Some(f.clone()),
+ _ => None,
+ });
+ let Some(f) = f else { return false };
+ (
+ "Interpret Footage".into(),
+ vec![
+ Field::num("frameRate", "Frame rate", f.frame_rate.as_f64()),
+ Field::choice(
+ "alpha",
+ "Alpha",
+ &[("Straight", json!("straight")), ("Premultiplied", json!("premultiplied")), ("Ignore", json!("ignore"))],
+ f.alpha as usize,
+ ),
+ Field::num("loop", "Loop (times)", f.loop_count as f64),
+ Field::num("pixelAspect", "Pixel aspect ratio", f.pixel_aspect),
+ ],
+ )
+ }
+ "file.projectSettings" if p.as_object().is_none_or(|m| m.is_empty()) => {
+ let st = &s.project.settings;
+ let depth = match st.bit_depth.label() {
+ l if l.starts_with("16") => 1,
+ l if l.starts_with("32") => 2,
+ _ => 0,
+ };
+ (
+ "Project Settings".into(),
+ vec![
+ Field::choice(
+ "bitDepth",
+ "Depth",
+ &[("8 bits per channel", json!(8)), ("16 bits per channel", json!(16)), ("32 bits per channel (float)", json!(32))],
+ depth,
+ ),
+ Field::choice(
+ "timeDisplay",
+ "Time display style",
+ &[("Timecode", json!("timecode")), ("Frames", json!("frames"))],
+ usize::from(matches!(st.time_display, effectcraft_engine::project::TimeDisplayStyle::Frames)),
+ ),
+ Field::bool("linearize", "Linearize working space", st.linearize),
+ ],
+ )
+ }
- "layer.timeStretch" if !has(p, &["percent", "op"]) => {
- ("Time Stretch".into(), vec![Field::num("percent", "Stretch factor (%)", layer.map(|l| l.stretch).unwrap_or(100.0))])
- }
+ "layer.precompose" if !has(p, &["name"]) => {
+ let n = s.project.comps().count() + 1;
+ ("Pre-compose".into(), vec![Field::text("name", "New composition name", &format!("Pre-comp {n}"))])
+ }
+ "file.importPlaceholder" | "file.replaceWithPlaceholder" if p.as_object().is_none_or(|m| m.is_empty()) => (
+ "New Placeholder".into(),
+ vec![
+ Field::text("name", "Name", "Placeholder"),
+ Field::num("width", "Width", 1920.0),
+ Field::num("height", "Height", 1080.0),
+ Field::num("frameRate", "Frame rate", 29.97),
+ Field::num("duration", "Duration (seconds)", 30.0),
+ ],
+ ),
+ "file.importSolid" | "file.replaceWithSolid" if p.as_object().is_none_or(|m| m.is_empty()) => {
+ let (w, h) = comp.map(|c| (c.width, c.height)).unwrap_or((1920, 1080));
+ (
+ "Solid Settings".into(),
+ vec![
+ Field::text("name", "Name", "Solid"),
+ Field::text("color", "Color (#rrggbb)", "#808080"),
+ Field::num("width", "Width", w as f64),
+ Field::num("height", "Height", h as f64),
+ ],
+ )
+ }
+ _ => return false,
+ };
+ form(app, &title, id, base, fields);
+ true
+}
+
+pub fn show_form(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
+ let mut f = app.dialog_state.form.clone();
+ let (mut ok, mut close) = (false, false);
+ let h = 120.0 + f.fields.len() as f32 * 30.0;
+ super::dialogs::modal(ctx, &f.title.clone(), vec2(440.0, h), t, |ui| {
+ egui::Grid::new("form-grid").num_columns(2).spacing([14.0, 10.0]).show(ui, |ui| {
+ for fl in &mut f.fields {
+ ui.label(&fl.label);
+ match &mut fl.kind {
+ FieldKind::Number { value, speed } => {
+ ui.add(egui::DragValue::new(value).speed(*speed).max_decimals(3));
+ }
+ FieldKind::Text(s) => {
+ ui.add(egui::TextEdit::singleline(s).desired_width(220.0));
+ }
+ FieldKind::Bool(b) => {
+ ui.checkbox(b, "");
+ }
+ FieldKind::Choice { options, sel } => {
+ let cur = options.get(*sel).map(|o| o.0.clone()).unwrap_or_default();
+ egui::ComboBox::from_id_salt(("form", fl.key.as_str())).selected_text(cur).width(240.0).show_ui(ui, |ui| {
+ for (i, (l, _)) in options.iter().enumerate() {
+ ui.selectable_value(sel, i, l);
+ }
+ });
+ }
+ }
+ ui.end_row();
+ }
+ });
+ ui.add_space(14.0);
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent)).clicked() {
+ ok = true;
+ }
+ if ui.button("Cancel").clicked() {
+ close = true;
+ }
+ });
+ });
+ let enter = !ctx.egui_wants_keyboard_input() && ctx.input(|i| i.key_pressed(egui::Key::Enter));
+ app.dialog_state.form = f.clone();
+ if ok || enter {
+ app.dialog = None;
+ let params = f.params();
+ if let Err(e) = app.session.execute(&f.command, params) {
+ app.ui.status = e.to_string();
+ }
+ return;
+ }
+ if close {
+ app.dialog = None;
+ }
+}
+
+pub fn show_info(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
+ let (title, body) = app.dialog_state.info.clone();
+ let mut close = false;
+ super::dialogs::modal(ctx, &title, vec2(440.0, 160.0), t, |ui| {
+ ui.label(body);
+ ui.add_space(16.0);
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent)).clicked() {
+ close = true;
+ }
+ });
+ });
+ if close {
+ app.dialog = None;
+ }
+}
+
+pub const SETTINGS_PAGES: [(&str, &str); 17] = [
+ ("general", "General"),
+ ("startup", "Startup & Repair"),
+ ("project", "Project"),
+ ("composition", "Composition"),
+ ("previews", "Previews"),
+ ("appearance", "Appearance"),
+ ("grids", "Grids & Guides"),
+ ("labels", "Labels"),
+ ("type", "Type"),
+ ("import", "Import"),
+ ("export", "Export"),
+ ("audio", "Audio"),
+ ("disk", "Disk"),
+ ("memory", "Memory & CPU"),
+ ("video", "Video"),
+ ("3d", "3D"),
+ ("scripting", "Scripting & Expressions"),
+];
+
+pub fn show_settings(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
+ let mut page = app.dialog_state.settings_page.clone();
+ let mut close = false;
+ let mut theme = None;
+ super::dialogs::modal(ctx, "Settings", vec2(640.0, 440.0), t, |ui| {
+ ui.horizontal_top(|ui| {
+ ui.vertical(|ui| {
+ ui.set_width(170.0);
+ for (id, label) in SETTINGS_PAGES {
+ if ui.selectable_label(page == id, label).clicked() {
+ page = id.to_string();
+ }
+ }
+ });
+ ui.separator();
+ ui.vertical(|ui| {
+ let title = SETTINGS_PAGES.iter().find(|p| p.0 == page).map(|p| p.1).unwrap_or("General");
+ ui.label(egui::RichText::new(title).font(Tokens::semibold(13.0)));
+ ui.add_space(8.0);
+ match page.as_str() {
+ "general" => {
+ ui.checkbox(&mut app.ui.show_menu_bar, "Show the in-window menu bar");
+ ui.checkbox(&mut app.ui.snapping, "Snapping");
+ }
+ "appearance" => {
+ for (k, name) in [("dark", "Dark"), ("darker", "Darker"), ("light", "Light")] {
+ if ui.button(name).clicked() {
+ theme = crate::theme::ThemeKind::from_name(k);
+ }
+ }
+ }
+ "previews" => {
+ ui.checkbox(&mut app.ui.cache_when_idle, "Cache frames when idle");
+ ui.checkbox(&mut app.ui.viewer.fast_preview, "Fast previews");
+ }
+ "grids" => {
+ ui.checkbox(&mut app.ui.viewer.grid, "Show grid");
+ ui.checkbox(&mut app.ui.viewer.guides, "Show guides");
+ ui.checkbox(&mut app.ui.viewer.safe_margins, "Show title/action safe");
+ }
+ "labels" => {
+ for l in effectcraft_engine::color::Label::ALL.into_iter().skip(1) {
+ ui.horizontal(|ui| {
+ let [r, g, b] = l.rgb();
+ let (rect, _) = ui.allocate_exact_size(vec2(26.0, 14.0), egui::Sense::hover());
+ ui.painter().rect_filled(rect, 2.0, Color32::from_rgb(r, g, b));
+ ui.label(l.name());
+ });
+ }
+ }
+ _ => {
+ ui.label(egui::RichText::new("No options on this page yet.").color(t.text_dim));
+ }
+ }
+ });
+ });
+ ui.add_space(10.0);
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent)).clicked() {
+ close = true;
+ }
+ });
+ });
+ app.dialog_state.settings_page = page;
+ if let Some(k) = theme {
+ app.set_theme(ctx, k);
+ }
+ if close {
+ app.dialog = None;
+ }
+}
+
+pub fn show_shortcuts(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
+ let mut q = app.dialog_state.palette_query.clone();
+ let mut close = false;
+ // (shortcut, where, label)
+ let mut rows: Vec<(String, String, String)> = vec![];
+ for (path, e) in effectcraft_engine::menus::entries() {
+ if let Some(sc) = &e.shortcut {
+ rows.push((crate::menus::shortcut_text(sc), path.join(" ▸ "), e.label.clone()));
+ }
+ }
+ for c in effectcraft_engine::command_specs().iter().filter(|c| c.menu.is_empty()) {
+ if let Some(sc) = c.shortcut
+ && !rows.iter().any(|r| r.2 == c.label)
+ {
+ rows.push((crate::menus::shortcut_text(sc), "Commands".into(), c.label.to_string()));
+ }
+ }
+ for c in crate::menus::UI_COMMANDS {
+ if let Some(sc) = c.shortcut {
+ rows.push((crate::menus::shortcut_text(sc), "Panels & Tools".into(), c.label.to_string()));
+ }
+ }
+ super::dialogs::modal(ctx, "Keyboard Shortcuts", vec2(640.0, 520.0), t, |ui| {
+ ui.add(egui::TextEdit::singleline(&mut q).hint_text("Search commands or shortcuts").desired_width(f32::INFINITY));
+ ui.add_space(8.0);
+ let ql = q.to_lowercase();
+ egui::ScrollArea::vertical().max_height(400.0).show(ui, |ui| {
+ egui::Grid::new("shortcut-grid").num_columns(3).striped(true).spacing([18.0, 4.0]).show(ui, |ui| {
+ for (sc, place, label) in rows.iter().filter(|r| ql.is_empty() || format!("{} {} {}", r.0, r.1, r.2).to_lowercase().contains(&ql)) {
+ ui.label(egui::RichText::new(sc).monospace());
+ ui.label(label);
+ ui.label(egui::RichText::new(place).color(t.text_dim));
+ ui.end_row();
+ }
+ });
+ });
+ ui.add_space(8.0);
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent)).clicked() {
+ close = true;
+ }
+ });
+ });
+ app.dialog_state.palette_query = q;
+ if close {
+ app.dialog = None;
+ }
+}
+
+pub fn show_view_options(app: &mut EffectcraftApp, ctx: &egui::Context, t: &Tokens) {
+ let mut close = false;
+ super::dialogs::modal(ctx, "View Options", vec2(360.0, 330.0), t, |ui| {
+ let v = &mut app.ui.viewer;
+ ui.checkbox(&mut v.show_layer_controls, "Layer controls");
+ ui.checkbox(&mut v.show_masks, "Masks");
+ ui.checkbox(&mut v.rulers, "Rulers");
+ ui.checkbox(&mut v.guides, "Guides");
+ ui.checkbox(&mut v.grid, "Grid");
+ ui.checkbox(&mut v.safe_margins, "Title/action safe");
+ ui.checkbox(&mut v.transparency_grid, "Transparency grid");
+ ui.add_space(12.0);
+ ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
+ if ui.add(egui::Button::new(egui::RichText::new(" OK ").color(Color32::WHITE)).fill(t.accent)).clicked() {
+ close = true;
+ }
+ });
+ });
+ if close {
+ app.dialog = None;
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn form_params_build_arrays_and_choices() {
+ let f = Form {
+ title: "T".into(),
+ command: "layer.setTransform".into(),
+ base: json!({"prop": "position"}),
+ fields: vec![
+ Field::num("value[0]", "X", 10.0),
+ Field::num("value[1]", "Y", 20.0),
+ Field::choice("mode", "M", &[("A", json!("a")), ("B", json!("b"))], 1),
+ ],
+ };
+ assert_eq!(f.params(), json!({"prop": "position", "value": [10.0, 20.0], "mode": "b"}));
+ }
+}
diff --cc crates/ui-egui/src/panels/mod.rs
index 0e51c6fec,8cd26cb5e..a16f3e306
--- a/crates/ui-egui/src/panels/mod.rs
+++ b/crates/ui-egui/src/panels/mod.rs
@@@ -1,10 -1,13 +1,14 @@@
//! Panel bodies.
+ pub mod comp_settings;
pub mod dialogs;
+ pub mod dialogs_3d;
pub mod effect_controls;
pub mod effects_presets;
+pub mod forms;
+ pub mod graph;
pub mod info;
+ pub mod key_dialogs;
pub mod misc;
pub mod project;
pub mod properties;
diff --cc crates/ui-egui/src/state.rs
index c06ff70d1,b06b0e388..4cb2d9aba
--- a/crates/ui-egui/src/state.rs
+++ b/crates/ui-egui/src/state.rs
@@@ -264,9 -249,28 +264,31 @@@ pub struct TimelineState
pub open_groups: BTreeSet<u64>,
/// "Reveal" filter: only show these property match ids (P/S/R/T/A…) — empty = normal.
pub reveal: Vec<String>,
+ /// Properties / groups (uids) shown by the `props` reveal (Animation ▸ Reveal Properties…).
+ #[serde(default)]
+ pub reveal_props: BTreeSet<u64>,
+ /// Graph Editor: `value` or `speed` graph.
+ #[serde(default = "value_graph")]
+ pub graph_mode: String,
+ /// Show only the selected properties (else every animated property of the selected layers).
+ #[serde(default = "yes")]
+ pub graph_show_selected: bool,
+ /// Auto-zoom the graph height to the visible curves.
+ #[serde(default = "yes")]
+ pub graph_auto_zoom: bool,
+ /// Manual graph value range (when auto-zoom is off).
+ #[serde(default)]
+ pub graph_range: Option<(f64, f64)>,
+ /// Properties whose inline expression editor is collapsed.
+ #[serde(default)]
+ pub expr_closed: BTreeSet<u64>,
+ }
+
+ fn value_graph() -> String {
+ "value".into()
+ }
+ fn yes() -> bool {
+ true
}
impl Default for TimelineState {
@@@ -282,7 -286,11 +304,12 @@@
open_layers: BTreeSet::new(),
open_groups: BTreeSet::new(),
reveal: vec![],
+ reveal_props: BTreeSet::new(),
+ graph_mode: value_graph(),
+ graph_show_selected: true,
+ graph_auto_zoom: true,
+ graph_range: None,
+ expr_closed: BTreeSet::new(),
}
}
}