Refresh shared dotLottie cutover and propagate archive errors

This commit is contained in:
Dylan M. Taylor committed 2026-11-15 10:24:25 -05:00
commit 8fdbbc604c
169 files changed
+24932 -16810

No files matched your search

+174 -13
View File
@@ -17,10 +17,15 @@ use crate::{EngineError, KeyRef, Result, Session, cmd};
/// Preset file format version tag (`*.ecpreset`, JSON).
pub const PRESET_TAG: &str = "effectcraftAnimationPreset";
/// The preset format version that `anim.savePreset` writes.
pub const PRESET_VERSION: u64 = 3;
/// The first preset version that stores effect keys relative to the earliest key (#1971).
const RELATIVE_EFFECT_KEYS: u64 = 2;
/// The first preset version that stores text animators and selectors under `textAnimators`.
const TEXT_ANIMATORS: u64 = 3;
/// The preset format version written under [`PRESET_TAG`]. 4: a property that is a Cineon
/// Converter's Gamma, directly or through Essential Properties, records that Cineon Converter's
/// version in `cineonVersion`; the Gamma properties of version 1 to 3 presets are version 1 Gammas.
pub const PRESET_VERSION: u64 = 4;
fn has_selected_props(s: &Session) -> std::result::Result<(), String> {
has_comp(s)?;
@@ -105,7 +110,8 @@ fn save_preset(s: &mut Session, p: &Value) -> Result<Value> {
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()));
let version = cineon_gamma_version(&s.project, l, uid, Some(t), NESTING);
props.push((l.layer_time(t), mp, pr.clone(), version));
}
if props.is_empty() && effects.is_empty() && animators.is_empty() {
return Err(bad("anim.savePreset", "select properties or effects to save"));
@@ -113,7 +119,7 @@ fn save_preset(s: &mut Session, p: &Value) -> Result<Value> {
// 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))
.flat_map(|(_, _, pr, _)| pr.keys.iter().map(|k| k.time))
.chain(earliest_key(effects.iter().map(|(_, g)| g).chain(&animators)))
.min()
.unwrap_or(Tick::ZERO);
@@ -122,12 +128,16 @@ fn save_preset(s: &mut Session, p: &Value) -> Result<Value> {
}
let props_json: Vec<Value> = props
.iter()
.map(|(_, mp, pr)| {
.map(|(_, mp, pr, version)| {
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})
let mut v = json!({"path": mp, "value": pr.value, "keys": pr.keys, "expression": pr.expr});
if let Some((version, _)) = version {
v["cineonVersion"] = json!(version);
}
v
})
.collect();
let fx_json: Vec<Value> = effects.iter().map(|(_, g)| serde_json::to_value(g).unwrap_or_default()).collect();
@@ -198,7 +208,19 @@ fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {
retime_effect(g, 1.0, "anim.applyPreset", |t| Ok(Tick(t.0.checked_sub(first.0).ok_or_else(|| effect_time_error("anim.applyPreset"))?)))?;
}
}
let props: Vec<(String, Property)> = doc["properties"]
// A Cineon Converter saved before version 2 gets its Version (1), as when a project opens.
if let Some(spec) = effectcraft_effects::find("ec.utility.cineon") {
for g in &mut effects {
if matches!(&g.kind, GroupKind::Effect { effect } if effect == spec.id) {
// The uids are reassigned when the group is applied.
let mut next = 0;
effectcraft_effects::migrate::upgrade_instance(spec, g, &mut Ids(&mut next), [0.0; 2]);
}
}
}
// The Cineon Converter version of each saved Gamma; a format 1 to 3 preset holds version 1 Gammas.
let legacy = doc[PRESET_TAG].as_u64().unwrap_or(1) < PRESET_VERSION;
let props: Vec<(String, Property, Option<f64>)> = doc["properties"]
.as_array()
.map(|a| {
a.iter()
@@ -210,12 +232,29 @@ fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {
let mut pr = Property::new(0, "", "", value);
pr.keys = keys;
pr.expr = expr;
Some((path, pr))
let version = v["cineonVersion"].as_f64().or(legacy.then_some(1.0));
Some((path, pr, version))
})
.collect()
})
.unwrap_or_default();
let saved_3d = props.iter().any(|(path, src)| path == "text/perChar3d" && src.value.as_bool());
// Per layer and property: the version of the Cineon Converter Gammas the property drives
// through Essential Properties.
let exposed: Vec<Vec<Option<f64>>> = ids
.iter()
.map(|lid| {
let l = s.project.comp(cid).and_then(|c| c.layer(*lid));
props
.iter()
.map(|(path, _, _)| {
let l = l?;
let pr = l.props.prop(&resolve_effect_path(l, path))?;
cineon_gamma_version(&s.project, l, pr.uid, Some(s.time()), NESTING).and_then(|(v, direct)| (!direct).then_some(v))
})
.collect()
})
.collect();
let saved_3d = props.iter().any(|(path, src, _)| path == "text/perChar3d" && src.value.as_bool());
let t = s.time();
// Effect bounds per layer size the point defaults of parameters added since the preset was saved.
let comp = s.project.comp(cid).ok_or(EngineError::NoComp)?;
@@ -225,7 +264,7 @@ fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {
let mut skipped = vec![];
s.edit("Apply Animation Preset", None, |proj, _| {
let mut next = proj.next_id;
for lid in &ids {
for (li, lid) in ids.iter().enumerate() {
let size = sizes.get(lid).copied().unwrap_or([100.0, 100.0]);
let l = layer_mut(proj, cid, *lid)?;
let lt = l.layer_time(t);
@@ -248,7 +287,41 @@ fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {
applied += 1;
}
}
for (path, src) in &props {
for (pi, (path, src, version)) in props.iter().enumerate() {
// A Gamma of a Cineon Converter whose Version is keyframed is converted to that
// Version, and skipped when the keys hold more than one version or an expression
// sets the Version. A preset that holds the Version too sets it.
let version_path = cineon_version_path(path).filter(|vp| !props.iter().any(|(p, v, _)| p == vp && matches!(v.value, KV::Scalar(_))));
let keyed = match (version, &version_path) {
(Some(_), Some(vp)) => {
l.props.prop(&resolve_effect_path(l, vp)).filter(|pr| pr.has_expression() || pr.keys.iter().any(|k| !k.muted)).map(constant_version)
}
_ => None,
};
let target = match keyed {
Some(None) => {
skipped.push(path.clone());
continue;
}
Some(to) => to,
None => exposed[li][pi],
};
// An exposed Gamma is converted to the scale of the Cineon Converters it drives.
// One with an enabled expression is skipped: expressions are applied as saved.
let rescaled;
let src = match (version, target) {
(Some(from), Some(to)) if *from != to && src.has_expression() => {
skipped.push(path.clone());
continue;
}
(Some(from), Some(to)) if *from != to => {
let mut c = src.clone();
rescale_gamma(&mut c, effectcraft_effects::cineon_gamma_scale(*from) / effectcraft_effects::cineon_gamma_scale(to));
rescaled = c;
&rescaled
}
_ => src,
};
let resolved = resolve_effect_path(l, path);
match l.props.prop_mut(&resolved) {
Some(pr) if std::mem::discriminant(&pr.value) == std::mem::discriminant(&src.value) => {
@@ -267,7 +340,18 @@ fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {
}
applied += 1;
}
_ => skipped.push(path.clone()),
_ => {
skipped.push(path.clone());
continue;
}
}
// A Cineon Converter's Gamma sets the instance's Version to the one it was saved
// with, unless that Version is keyframed or the preset holds it.
if keyed.is_none()
&& let (Some(v), Some(vp)) = (version, &version_path)
&& let Some(pr) = l.props.prop_mut(&resolve_effect_path(l, vp))
{
pr.value = KV::Scalar(*v);
}
}
// After the properties, so a saved Per-character 3D setting counts: it needs a 3D layer
@@ -299,7 +383,7 @@ fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {
}
// Without this, a preset that fits no layer does nothing and says nothing.
if applied == 0 && !skipped.is_empty() {
let legacy_text = doc[PRESET_TAG].as_u64().unwrap_or(1) < PRESET_VERSION && props.iter().any(|(path, _)| path.starts_with("text/animators/"));
let legacy_text = doc[PRESET_TAG].as_u64().unwrap_or(1) < TEXT_ANIMATORS && props.iter().any(|(path, _, _)| path.starts_with("text/animators/"));
let message = if legacy_text {
"nothing in this preset fits the layer. A text animation preset saved by an earlier version only updates animators a layer already has: save it again"
} else {
@@ -319,6 +403,83 @@ fn apply_preset(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({"applied": applied, "skipped": skipped}))
}
/// The preset path of the Version of the Cineon Converter whose Gamma is at preset path `path`
/// (`effects/<match name>[#n]/gamma`, as [`match_path_of`] writes it).
fn cineon_version_path(path: &str) -> Option<String> {
let (seg, tail) = path.strip_prefix("effects/")?.split_once('/')?;
(seg.rsplit_once('#').map_or(seg, |(m, _)| m) == "ec.utility.cineon" && tail == "gamma").then(|| format!("effects/{seg}/version"))
}
/// How many nested comps [`cineon_gamma_version`] follows Essential Properties through.
const NESTING: u32 = 16;
/// The version of the Cineon Converter whose Gamma property `uid` of `l` is, and whether that
/// Cineon Converter is on `l`. With `t`, a keyframed Version is read at comp time `t`; without
/// it, a Version whose keyframes hold more than one value has no version. A Version that an
/// expression sets has none either. An Essential
/// Properties value of a precomp layer counts when its control drives only Cineon Converter
/// Gammas of one version, in the nested comp or, through further Essential Properties, in comps
/// up to `depth` levels deeper.
fn cineon_gamma_version(p: &Project, l: &Layer, uid: Uid, t: Option<Tick>, depth: u32) -> Option<(f64, bool)> {
let direct = l.effects().and_then(|fx| {
fx.groups().find(|g| matches!(&g.kind, GroupKind::Effect { effect } if effect == "ec.utility.cineon") && g.get("gamma").is_some_and(|pr| pr.uid == uid))
});
if let Some(g) = direct {
let Some(pr) = g.get("version") else { return Some((1.0, true)) };
if pr.has_expression() {
return None;
}
let version = match t {
Some(t) => pr.value_at(l.layer_time(t)).as_f64(),
None => constant_version(pr)?,
};
return Some((version, true));
}
let LayerSource::Comp { item } = l.source else { return None };
let depth = depth.checked_sub(1)?;
let ctl = effectcraft_project::essential::group(l)?.find(uid).and_then(|pr| effectcraft_project::essential::control_of(&pr.match_id))?;
let c = p.comp(item)?;
let mut version = None;
for (lid, target) in c.essential.as_ref()?.resolve(ctl)?.kind.targets() {
let (v, _) = cineon_gamma_version(p, c.layer(lid)?, target, None, depth)?;
if version.is_some_and(|x| x != v) {
return None;
}
version = Some(v);
}
version.map(|v| (v, false))
}
/// The value a Cineon Converter's Version holds at every time: its value without keyframes
/// that play, and none when the keyframes that play hold more than one value or ease with a
/// speed that moves the value between them, or when an expression sets it.
fn constant_version(pr: &Property) -> Option<f64> {
if pr.has_expression() {
return None;
}
let keys: Vec<&Keyframe> = pr.keys.iter().filter(|k| !k.muted).collect();
let first = keys.first().map_or_else(|| pr.value.as_f64(), |k| k.value.as_f64());
let still = |interp: Interp, eases: &[effectcraft_keyframe::Ease]| interp != Interp::Bezier || eases.iter().all(|e| e.speed == 0.0);
let eases_between =
keys.windows(2).any(|w| w[0].out_interp != Interp::Hold && (!still(w[0].out_interp, &w[0].out_ease) || !still(w[1].in_interp, &w[1].in_ease)));
(keys.iter().all(|k| k.value.as_f64() == first) && !eases_between).then_some(first)
}
/// Multiplies a Gamma value, its keyframes and their speeds by `f`.
fn rescale_gamma(pr: &mut Property, f: f64) {
if let KV::Scalar(x) = &mut pr.value {
*x *= f;
}
for k in &mut pr.keys {
if let KV::Scalar(x) = &mut k.value {
*x *= f;
}
for e in k.in_ease.iter_mut().chain(k.out_ease.iter_mut()) {
e.speed *= f;
}
}
}
// ---------------------------------------------------------------- keyframes
fn add_keyframe(s: &mut Session, _: &Value) -> Result<Value> {
+5
View File
@@ -1173,9 +1173,14 @@ fn reset(s: &mut Session, p: &Value) -> Result<Value> {
}
.ok_or_else(|| bad("effect.reset", "unknown effect"))?;
let name = g.name.clone();
// Reset keeps a Cineon Converter's Version.
let cineon_version = if spec.id == "ec.utility.cineon" { g.get("version").map(|v| v.value.as_f64()) } else { None };
s.edit(&format!("Reset {name}"), None, |proj, _| {
let g = layer_mut(proj, cid, lid)?.props.find_group_mut(uid).ok_or_else(|| bad("effect.reset", "gone"))?;
for ps in &spec.params {
if ps.id == "version" && cineon_version.is_some() {
continue;
}
// (`group/param` ids live in twirl-down groups.)
if let Some(pr) = g.prop_mut(ps.id) {
pr.set_value_at(lt, effectcraft_effects::default_value(ps, size));
+26 -12
View File
@@ -2,7 +2,7 @@
//! Language menu (the ⓕ button next to an expression), written from the public Expression
//! Language Reference.
use effectcraft_project::{Expression, ItemId, Layer, Property};
use effectcraft_project::{Comp, Expression, ItemId, Layer, Property};
use effectcraft_render::EvalCtx;
use effectcraft_time::Tick;
use serde::Serialize;
@@ -42,8 +42,16 @@ impl ExprError {
/// expressions and the syntax errors that disabled others.
pub fn errors(s: &Session, cid: ItemId, t: Tick) -> Vec<ExprError> {
let Some(comp) = s.project.comp(cid) else { return vec![] };
let ctx = EvalCtx { footage: Some(s.footage.as_ref()), expr: s.expr.as_deref(), ..EvalCtx::new(&s.project, cid, comp, t) };
errors_in(&ctx, s.expr_check, || true).unwrap_or_default()
errors_in(&eval_ctx(s, cid, comp, t), s.expr_check, || true).unwrap_or_default()
}
/// The context to evaluate expressions of comp `cid` at comp time `t` as the render does for the
/// comp at top level: with the session's expression host and its footage source, so
/// `sampleImage()` reads footage pixels instead of failing or sampling transparent (#1000,
/// #3231). `expr.errors`, `prop.get`, [`Session::expression_errors`] and the script value query
/// all evaluate through this one context.
pub fn eval_ctx<'a>(s: &'a Session, cid: ItemId, comp: &'a Comp, t: Tick) -> EvalCtx<'a> {
EvalCtx { footage: Some(s.footage.as_ref()), expr: s.expr.as_deref(), ..EvalCtx::new(&s.project, cid, comp, t) }
}
/// Evaluate diagnostics against an immutable snapshot. Background callers can cancel between
@@ -65,15 +73,7 @@ pub fn errors_in(ctx: &EvalCtx, check: Option<fn(&str) -> std::result::Result<()
if !keep_going() {
return None;
}
let msg = if e.enabled {
match &ctx.expr {
Some(h) => h.eval(ctx, l, p, &p.value_at(l.layer_time(ctx.time))).err(),
None => None,
}
} else {
check.and_then(|check| check(&e.text).err())
};
if let Some(message) = msg {
if let Some(message) = property_error(ctx, check, l, p) {
out.push(error_of(ctx.comp_id, i, l, p, message, !e.enabled));
}
}
@@ -81,6 +81,20 @@ pub fn errors_in(ctx: &EvalCtx, check: Option<fn(&str) -> std::result::Result<()
keep_going().then_some(out)
}
/// Why property `p` of layer `l` fails at `ctx.time` (comp time), as `expr.errors` reports it and
/// scripts read it as `Property.expressionError`: the evaluation error (an exception or a
/// non-finite result) of an enabled expression, or the syntax error that disabled one. `None`
/// without an expression or when it evaluates. Evaluates this one expression; renders nothing.
/// Without an evaluator an enabled expression gets the syntax check, so a broken one (from a
/// project file) still reports why.
pub fn property_error(ctx: &EvalCtx, check: Option<fn(&str) -> std::result::Result<(), String>>, l: &Layer, p: &Property) -> Option<String> {
let e = p.expr.as_ref().filter(|e| !e.text.trim().is_empty())?;
match ctx.expr {
Some(h) if e.enabled => h.eval(ctx, l, p, &p.value_at(l.layer_time(ctx.time))).err(),
_ => check.and_then(|check| check(&e.text).err()),
}
}
fn error_of(cid: ItemId, i: usize, l: &Layer, p: &Property, message: String, disabled: bool) -> ExprError {
ExprError {
comp: cid.0,
+15 -6
View File
@@ -143,7 +143,8 @@ fn import_cmd(s: &mut Session, p: &Value) -> Result<Value> {
_ => format!("Importing {total} files"),
};
let p = p.clone();
return s.spawn_task("import", label, false, move |ctl| {
let immediate_errors = pending.errors.clone();
let mut result = s.spawn_task("import", label, false, move |ctl| {
let mut probed = Vec::with_capacity(total);
for (k, src) in sources.iter().enumerate() {
ctl.message(format!("{} ({} of {total})", src.name(), k + 1));
@@ -162,13 +163,19 @@ fn import_cmd(s: &mut Session, p: &Value) -> Result<Value> {
match errors.as_slice() {
[] => {}
[one] => toast = format!("{toast}. {one}"),
[first, rest @ ..] => toast = format!("{toast}. {first} (and {} more)", rest.len()),
[first, rest @ ..] => toast = format!("{toast}. {first} (and {} more)\n{}", rest.len(), errors.join("\n")),
}
r["toast"] = json!(toast);
Ok(r)
});
Ok(apply)
});
})?;
// Preparation can reject layered files before the remaining footage needs probing.
// Report those failures now as well as in the eventual job result.
if result["started"] == true {
result["errors"] = json!(immediate_errors);
}
return Ok(result);
}
let probed = pending.sources.iter().map(|src| pending.prober.probe(src)).collect();
let mut r = add_footage(s, pending, probed)?;
@@ -346,8 +353,9 @@ impl Prober {
None => ask_alpha = true,
}
}
// Page: another page of a PDF / Illustrator file.
if self.page > 0 && matches!(f.codec.as_str(), "PDF" | "AI") {
// Page: another page of a PDF / Illustrator file, or another artboard of a VectorCraft
// document's PDF.
if self.page > 0 && matches!(f.codec.as_str(), "PDF" | "AI" | "VectorCraft") {
let doc = self
.services
.read_file(path)
@@ -563,7 +571,8 @@ fn add_footage(s: &mut Session, pending: PendingImport, probed: Vec<std::result:
/// definition, OpenEXR premultiplied); TGA, TIFF and movies with alpha don't.
fn alpha_is_labeled(path: &str, codec: &str) -> bool {
let ext = std::path::Path::new(path).extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default();
matches!(ext.as_str(), "png" | "gif" | "webp" | "psd" | "psb" | "exr" | "svg" | "jpg" | "jpeg" | "ai" | "pdf" | "eps") || codec.eq_ignore_ascii_case("PSD")
matches!(ext.as_str(), "png" | "gif" | "webp" | "psd" | "psb" | "exr" | "svg" | "jpg" | "jpeg" | "ai" | "pdf" | "eps" | "vectorcraft")
|| codec.eq_ignore_ascii_case("PSD")
}
/// A Photoshop layer by index or name (pixel layers only).
+34 -2
View File
@@ -56,15 +56,39 @@ fn items_p(s: &Session, p: &Value) -> Vec<ItemId> {
}
}
/// `project.newFolder {name?, parent?, items?}`. With `items` (ids or names), they move into the
/// new folder in the same undo step: Project items dropped on the panel's New Folder button, as
/// in After Effects (#3196). A folder can't end up inside itself.
fn new_folder(s: &mut Session, p: &Value) -> Result<Value> {
let c = "project.newFolder";
let name = str_p(p, "name").unwrap_or("Untitled Folder").to_string();
let parent = p.get("parent").and_then(Value::as_u64).map(ItemId).filter(|i| s.project.item(*i).is_some_and(|x| x.is_folder()));
let mut items: Vec<ItemId> = vec![];
if let Some(v) = p.get("items") {
let Value::Array(a) = v else { return Err(bad(c, "`items` must be an array of item ids or names")) };
for v in a {
let id = super::project_items::item_ref(s, v, c)?;
if !items.contains(&id) {
items.push(id);
}
}
if let Some(f) = parent
&& let Some(inside) = items.iter().find(|i| super::project_items::is_within(&s.project, f, **i))
{
return Err(bad(c, format!("can't move folder {} into a folder inside itself", inside.0)));
}
}
let id = s.edit("New Folder", None, |proj, st| {
let id = proj.add_item(&name, Label::Yellow, parent, ItemKind::Folder);
for i in &items {
if let Some(it) = proj.item_mut(*i) {
it.parent = Some(id);
}
}
st.project_selection = vec![id];
Ok(id)
})?;
Ok(json!({"item": id.0}))
if p.get("items").is_some() { Ok(json!({"item": id.0, "moved": items.len()})) } else { Ok(json!({"item": id.0})) }
}
fn close(s: &mut Session, p: &Value) -> Result<Value> {
@@ -1211,7 +1235,15 @@ fn reveal_in_finder(s: &mut Session, p: &Value) -> Result<Value> {
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!("project.newFolder", "New Folder", ["File", "New"], Some("Cmd+Alt+Shift+N"), "{name?, parent?}", always, new_folder),
cmd!(
"project.newFolder",
"New Folder",
["File", "New"],
Some("Cmd+Alt+Shift+N"),
"{name?, parent?, items?: [id|name] (moved into it)}",
always,
new_folder
),
cmd!("file.close", "Close", ["File"], Some("Cmd+W"), "{comp?}", has_comp, close),
cmd!("file.closeProject", "Close Project", ["File"], None, "{}", always, close_project),
cmd!("file.saveCopy", "Save a Copy...", ["File", "Save As"], None, "{path}", always, save_copy),
+2 -2
View File
@@ -867,8 +867,8 @@ impl Session {
});
for pr in has {
let text = pr.expr.as_ref().map(|e| e.text.clone()).unwrap_or_default();
let mut ctx = effectcraft_render::EvalCtx::new(&self.project, cid, comp, t);
ctx.expr = Some(host.as_ref());
// With the footage source, so `sampleImage()` doesn't fail here only (#3231).
let ctx = super::expr_tools::eval_ctx(self, cid, comp, t);
if let Err(e) = host.eval(&ctx, l, pr, &pr.value_at(l.layer_time(t))) {
errors.push(json!({"layer": l.id.0, "prop": pr.uid, "name": pr.name, "expression": text, "error": e}));
}
+1 -1
View File
@@ -17,7 +17,7 @@ fn export_lottie(s: &mut Session, p: &Value) -> Result<Value> {
let dot = path.to_ascii_lowercase().ends_with(".lottie");
let bytes = if dot {
let stem = std::path::Path::new(&path).file_stem().map(|n| n.to_string_lossy().to_string()).unwrap_or_default();
effectcraft_lottie::to_dotlottie(&res, &stem)
effectcraft_lottie::try_to_dotlottie(&res, &stem).map_err(|e| EngineError::Other(e.to_string()))?
} else {
res.to_string_compact().into_bytes()
};
+1 -1
View File
@@ -8,7 +8,7 @@ use super::{CommandSpec, always, b_p, bad, str_p};
use crate::{EngineError, Result, Session, cmd, query};
/// `item` (id or name) → id.
fn item_ref(s: &Session, v: &Value, cmd: &str) -> Result<ItemId> {
pub(super) fn item_ref(s: &Session, v: &Value, cmd: &str) -> Result<ItemId> {
match v {
Value::Number(n) => n.as_u64().map(ItemId).filter(|i| s.project.item(*i).is_some()),
Value::String(name) => s.project.find_by_name(name).map(|i| i.id),
+54 -8
View File
@@ -371,20 +371,41 @@ fn set_selected(s: &mut Session, p: &Value) -> Result<Value> {
};
let follow: Vec<usize> =
p.get("follow").and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_u64).filter_map(|d| usize::try_from(d).ok()).collect();
// A typed `*2`, `/2` (`factor`) or `+10` (`addend`) (#3195): each layer's own value times it
// or plus it, not the edited layer's result (which its range may have clamped).
let factor = p.get("factor").and_then(Value::as_f64).filter(|k| k.is_finite() && delta.is_none());
let addend = p.get("addend").and_then(Value::as_f64).filter(|n| n.is_finite() && delta.is_none());
let own_step = |v: f64| -> Option<f64> {
let r = match (factor, addend) {
(Some(k), _) => v * k,
(None, Some(n)) => v + n,
(None, None) => return None,
};
r.is_finite().then_some(r)
};
// Each layer's own value where `set` writes it (a `time` other than the CTI keys there).
let typed = |s: &Session, q: &mut Value, olid: LayerId, ouid: Uid| {
let at = snapped_key_time(s, cid, olid, q, "prop.set").ok().flatten();
if scalar && let Some(v) = components_at(s, cid, olid, ouid, at).and_then(|c| c.first().copied()).and_then(own_step) {
q["value"] = json!(v);
}
if let (Some(dims), Some(n)) = (&dims, &new)
&& let Some(mut c) = components_at(s, cid, olid, ouid, snapped_key_time(s, cid, olid, q, "prop.set").ok().flatten())
&& let Some(mut c) = components_at(s, cid, olid, ouid, at)
{
let change = dims.first().and_then(|&d| Some(n.get(d)? - c.get(d)?)).unwrap_or(0.0);
// The typed components' new values on this layer.
let typed_value = |c: &[f64], d: usize| {
if factor.is_some() || addend.is_some() { c.get(d).copied().and_then(own_step) } else { n.get(d).copied() }
};
let change = dims.first().and_then(|&d| Some(typed_value(&c, d)? - c.get(d)?)).unwrap_or(0.0);
let values: Vec<Option<f64>> = dims.iter().map(|&d| typed_value(&c, d)).collect();
for &d in &follow {
if let Some(slot) = c.get_mut(d) {
*slot += change;
}
}
for &d in dims {
if let (Some(slot), Some(v)) = (c.get_mut(d), n.get(d)) {
*slot = *v;
for (&d, v) in dims.iter().zip(values) {
if let (Some(slot), Some(v)) = (c.get_mut(d), v) {
*slot = v;
}
}
q["value"] = json!(c);
@@ -421,6 +442,9 @@ fn set_selected(s: &mut Session, p: &Value) -> Result<Value> {
let mut q = twin_params(p, olid, ouid);
shifted(s, &mut q, olid, ouid, k);
typed(s, &mut q, olid, ouid);
if is_mask_feather(s, cid, olid, ouid) {
non_negative(&mut q["value"]);
}
// (a layer that can't take it, e.g. a clamped or static property, keeps its value)
let _ = set(s, &q);
}
@@ -429,6 +453,26 @@ fn set_selected(s: &mut Session, p: &Value) -> Result<Value> {
if merge_p(p).is_some() { run(s) } else { super::app_more::grouped(s, "Change Property", run) }
}
/// Whether property `uid` of `lid` is a mask's Mask Feather, which is never negative (After
/// Effects; the panels clamp a typed or scrubbed value at 0).
fn is_mask_feather(s: &Session, cid: ItemId, lid: LayerId, uid: Uid) -> bool {
let Some(l) = s.project.comp(cid).and_then(|c| c.layer(lid)) else { return false };
l.props.find(uid).is_some_and(|q| q.match_id == "feather") && l.props.parent_of(uid).is_some_and(|g| matches!(g.kind, GroupKind::Mask { .. }))
}
/// A JSON number, or each number of an array, raised to at least 0.
fn non_negative(v: &mut Value) {
match v {
Value::Number(n) => {
if let Some(x) = n.as_f64().filter(|x| *x < 0.0) {
*v = json!(x.max(0.0));
}
}
Value::Array(a) => a.iter_mut().for_each(non_negative),
_ => {}
}
}
/// `prop.toggleAnimation`; with `selected`, the other selected layers' same property follows.
fn toggle_anim_selected(s: &mut Session, p: &Value) -> Result<Value> {
let twins = selected_twins(s, p, "prop.toggleAnimation")?;
@@ -558,8 +602,9 @@ fn get(s: &mut Session, p: &Value) -> Result<Value> {
} else if pr.has_expression()
&& let (Some(h), Some(comp)) = (s.expr.as_deref(), s.project.comp(cid))
{
let mut ctx = crate::render::EvalCtx::new(&s.project, cid, comp, t);
ctx.expr = Some(h);
// The render's context, footage source included, so `sampleImage()` evaluates here as it
// renders and as `expr.errors` reports it (#3231).
let ctx = super::expr_tools::eval_ctx(s, cid, comp, t);
match h.eval(&ctx, l, pr, &raw) {
Ok(v) => out["evaluated"] = v.to_json(),
Err(e) => {
@@ -1445,6 +1490,7 @@ fn convert_one_expr(s: &mut Session, cid: ItemId, lid: LayerId, uid: Uid) -> Res
})
}
/// Returns the command specs for the property commands (get, set, keyframes, expressions and the rest).
pub fn specs() -> Vec<CommandSpec> {
vec![
query!("prop.get", "Get Property", "{layer?, path|prop, time? (comp s)}", get),
@@ -1453,7 +1499,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Set Property Value",
[],
None,
"{layer?, path|prop, value, time? (layer s by default), timeBase?: layer|comp, merge?, selected? (also the other selected layers), offset? (them by the same change), proportional? (with offset: Proportional Scrubbing, each layer by its share in selection order, the first none, the last all), dims? (with selected, a typed value: the components edited, e.g. [2] for Z; the other layers keep the rest of their own value), follow? (with dims: components that move on each other layer by the change its first typed component takes)}",
"{layer?, path|prop, value, time? (layer s by default), timeBase?: layer|comp, merge?, selected? (also the other selected layers), offset? (them by the same change), proportional? (with offset: Proportional Scrubbing, each layer by its share in selection order, the first none, the last all), dims? (with selected, a typed value: the components edited, e.g. [2] for Z; the other layers keep the rest of their own value), follow? (with dims: components that move on each other layer by the change its first typed component takes), factor? (with selected, a typed `*` or `/`: the other layers take their own value times it, in the dims components of a vector), addend? (the same for a typed `+`: their own value plus it)}",
has_layers,
set_selected
),