Merge pull request #1144 from tylerjenningsw/enhance/quick-offset

# Conflicts:
#	crates/ui-egui/src/i18n/ui.rs
This commit is contained in:
Brandon Thomas
2026-10-13 04:28:43 -04:00
12 changed files with 896 additions and 68 deletions
+2
View File
@@ -49,6 +49,7 @@ mod prop_groups;
mod proxy;
pub mod puppet;
mod query;
mod quick_offset;
mod relink;
mod render_queue;
pub(crate) mod rig3d;
@@ -190,6 +191,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(focus::specs());
v.extend(key_labels::specs());
v.extend(key_transform::specs());
v.extend(quick_offset::specs());
v.extend(file_more::specs());
v.extend(relink::specs());
v.extend(lottie::specs());
+85 -54
View File
@@ -862,67 +862,98 @@ pub(crate) fn edit_keys(s: &mut Session, label: &str, merge: Option<&str>, f: im
})
}
/// Move the selected keys by `d` comp seconds, snapped to the comp's frames in comp time (keys
/// of time-stretched layers move with the pointer, not by the layer-time distance). Keys of
/// locked layers stay. A key landing on another key of its property replaces it.
/// The keys a key drag's step applies to, the drag's total and the project as it was before the
/// drag. Steps of one drag (one `merge` key) start again from the keys as they were then, so a key
/// passed over survives; `d` adds to the drag's total, or is that total (`absolute`).
pub(crate) fn key_gesture(
s: &Session,
merge: Option<&str>,
d: Tick,
absolute: bool,
) -> (Vec<KeyRef>, Tick, Option<std::sync::Arc<effectcraft_project::Project>>) {
let gesture = merge.is_some_and(|m| s.history.merge_key.as_deref() == Some(m)) && s.key_move.as_ref().map(|g| g.merge.as_str()) == merge;
match (&s.key_move, s.history.undo.last()) {
(Some(g), Some((_, base))) if gesture => (g.from.clone(), if absolute { d } else { g.total + d }, Some(base.clone())),
_ => (s.state.selected_keys.clone(), d, None),
}
}
/// Move keys `from` to the layer times `to` gives (from a key's layer and layer time). A key
/// landing on another key of its property replaces it, roving keys follow their neighbours and
/// keys of locked layers stay. Returns the keys' new references in `from`'s order: the selection
/// keeps the order it was made in.
pub(crate) fn move_key_refs(comp: &mut effectcraft_project::Comp, from: &[KeyRef], to: impl Fn(&Layer, Tick) -> Result<Tick>) -> Result<Vec<KeyRef>> {
let mut remapped: std::collections::HashMap<KeyRef, KeyRef> = Default::default();
let mut groups: std::collections::BTreeMap<(LayerId, Uid), Vec<Tick>> = Default::default();
for k in from {
groups.entry((k.layer, k.prop)).or_default().push(k.time);
}
for ((lid, uid), times) in groups {
let Some(l) = comp.layer_mut(lid) else { continue };
let at = |time| KeyRef { layer: lid, prop: uid, time };
if l.switches.locked {
remapped.extend(times.iter().map(|t| (at(*t), at(*t))));
continue;
}
let moves: Vec<(Tick, Tick)> = times.iter().map(|t| Ok((*t, to(l, *t)?))).collect::<Result<_>>()?;
let Some(pr) = l.props.find_mut(uid) else { continue };
// Take the moving keys out, then put them back at their new times.
let mut moved = vec![];
for (old, new) in &moves {
if let Some(i) = key_at(&pr.keys, *old) {
let mut k = pr.keys.remove(i);
k.time = *new;
moved.push((*old, k));
}
}
// Target time -> the key's time before the move.
let mut targets: std::collections::HashMap<Tick, Tick> = Default::default();
for (old, k) in moved {
targets.insert(k.time, old);
match pr.keys.binary_search_by(|x| x.time.cmp(&k.time)) {
Ok(j) => pr.keys[j] = k,
Err(j) => pr.keys.insert(j, k),
}
}
// Resolve stored indices before roving keys change their times.
let tracked: Vec<(Tick, usize)> = targets.into_iter().filter_map(|(t, old)| key_at(&pr.keys, t).map(|i| (old, i))).collect();
effectcraft_keyframe::retime_roving(&mut pr.keys, pr.spatial);
for (old, i) in tracked {
if let Some(key) = pr.keys.get(i) {
remapped.insert(at(old), at(key.time));
}
}
}
let mut seen = std::collections::HashSet::new();
Ok(from.iter().filter_map(|k| remapped.get(k).copied()).filter(|k| seen.insert(*k)).collect())
}
/// A move of `d` in comp time as the move of `l`'s layer times (through its stretch, reversed
/// too), without a round trip through comp time.
pub(crate) fn layer_shift(l: &Layer, d: Tick) -> Tick {
l.layer_time(l.start_time + d)
}
/// Move the selected keys by `d` comp seconds, rounded to whole frames: the keys keep their
/// spacing, subframe offsets (Quick Offset) included, and keys of time-stretched layers move with
/// the pointer, not by the layer-time distance. Keys of locked layers stay. A key landing on
/// another key of its property replaces it.
pub(crate) fn shift_keys(s: &mut Session, label: &str, merge: Option<&str>, d: Tick) -> Result<Value> {
let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
// A drag (steps with one merge key) starts again from the keys before it each step.
let gesture = merge.is_some_and(|m| s.history.merge_key.as_deref() == Some(m)) && s.key_move.as_ref().map(|g| g.merge.as_str()) == merge;
let (from, total, base) = match (&s.key_move, s.history.undo.last()) {
(Some(g), Some((_, base))) if gesture => (g.from.clone(), g.total + d, Some(base.clone())),
_ => (s.state.selected_keys.clone(), d, None),
};
s.key_move = merge.map(|m| crate::KeyMove { merge: m.to_string(), from: from.clone(), total });
s.edit(label, merge, |proj, st| {
let (from, total, base) = key_gesture(s, merge, d, false);
let next = merge.map(|m| crate::KeyMove { merge: m.to_string(), from: from.clone(), total });
let moved = s.edit(label, merge, |proj, st| {
if let Some(b) = base {
*proj = (*b).clone();
}
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
let fr = comp.frame_rate;
let mut groups: std::collections::BTreeMap<(LayerId, Uid), Vec<Tick>> = Default::default();
for k in &from {
groups.entry((k.layer, k.prop)).or_default().push(k.time);
}
let mut sel = vec![];
for ((lid, uid), times) in groups {
let Some(l) = comp.layer_mut(lid) else { continue };
let to = |t: Tick| l.layer_time(fr.snap_nearest(l.comp_time(t) + total));
let moves: Vec<(Tick, Tick)> = times.iter().map(|t| (*t, to(*t))).collect();
if l.switches.locked {
sel.extend(times.iter().map(|t| KeyRef { layer: lid, prop: uid, time: *t }));
continue;
}
let Some(pr) = l.props.find_mut(uid) else { continue };
// Take the moving keys out, then put them back at their new times.
let mut moved = vec![];
for (old, new) in &moves {
if let Some(i) = key_at(&pr.keys, *old) {
let mut k = pr.keys.remove(i);
k.time = *new;
moved.push(k);
}
}
for k in moved {
sel.push(KeyRef { layer: lid, prop: uid, time: k.time });
match pr.keys.binary_search_by(|x| x.time.cmp(&k.time)) {
Ok(j) => pr.keys[j] = k,
Err(j) => pr.keys.insert(j, k),
}
}
// Roving keys follow their neighbours: keep the selection on them.
let before: Vec<Tick> = pr.keys.iter().map(|k| k.time).collect();
if effectcraft_keyframe::retime_roving(&mut pr.keys, pr.spatial) {
for r in sel.iter_mut().filter(|r| r.layer == lid && r.prop == uid) {
if let Some(i) = before.iter().position(|t| *t == r.time) {
r.time = pr.keys[i].time;
}
}
}
}
st.selected_keys = sel;
let d = comp.frame_rate.snap_nearest(total);
st.selected_keys = move_key_refs(comp, &from, |l, t| Ok(t + layer_shift(l, d)))?;
Ok(json!(st.selected_keys.len()))
})
})?;
// Only a step that applied counts towards the drag.
s.key_move = next;
Ok(moved)
}
fn move_keys(s: &mut Session, p: &Value) -> Result<Value> {
+144
View File
@@ -0,0 +1,144 @@
//! Quick Offset (After Effects 25.4): Ctrl/Cmd+Alt dragging selected layers or keyframes in the
//! Timeline staggers them in the order they were selected. The first stays, the last moves by the
//! whole drag and the ones between spread evenly, so they land on subframes; each layer's
//! selected keys move together.
use std::collections::HashMap;
use effectcraft_project::LayerId;
use effectcraft_time::{TICKS_PER_SECOND, Tick};
use serde_json::{Value, json};
use super::prop::{key_gesture, layer_shift, move_key_refs};
use super::{CommandSpec, b_p, bad, f_p, has_keys, has_layers, layers_p, merge_p};
use crate::{EngineError, Result, Session, cmd};
/// `delta` (comp seconds) in ticks; out of range is an error, not a clamped drag.
fn delta_p(p: &Value, name: &str) -> Result<Tick> {
let d = f_p(p, "delta").ok_or_else(|| bad(name, "missing `delta` (comp seconds)"))?;
let t = (d * TICKS_PER_SECOND as f64).round();
if !t.is_finite() || t.abs() > Tick::MAX.0 as f64 {
return Err(bad(name, "`delta` is out of range"));
}
Ok(Tick(t as i64))
}
/// How far each of `n` layers moves, in order, when the last moves by `total`: `total × i / (n − 1)`
/// to the nearest tick, so the steps between them are equal.
fn shares(total: Tick, n: usize) -> Vec<Tick> {
let last = n.saturating_sub(1).max(1) as i128;
(0..n)
.map(|i| {
let x = total.0 as i128 * i as i128;
Tick(((x + x.signum() * (last / 2)) / last) as i64)
})
.collect()
}
/// `t + d`, or an error (`what` names the time) when that leaves the range of times.
fn shifted(t: Tick, d: Tick, name: &str, what: &str) -> Result<Tick> {
let v = t.0 as i128 + d.0 as i128;
if v < Tick::MIN.0 as i128 || v > Tick::MAX.0 as i128 {
return Err(bad(name, format!("{what} would move out of range")));
}
Ok(Tick(v as i64))
}
/// The layers to stagger, in order: unlocked, each once. At least two.
fn order(name: &str, layers: impl IntoIterator<Item = LayerId>, unlocked: impl Fn(LayerId) -> bool) -> Result<Vec<LayerId>> {
let mut out: Vec<LayerId> = vec![];
for l in layers {
if unlocked(l) && !out.contains(&l) {
out.push(l);
}
}
if out.len() < 2 {
return Err(bad(name, "select at least two unlocked layers (or keys on two layers), in the order to offset them"));
}
Ok(out)
}
/// `layer.quickOffset`: move the layers (`layers`, else the selection, in that order) by their
/// share of `delta`, the last layer's move. With `merge` and `fromStart`, `delta` is the whole drag
/// and every step applies to the layers as they were before it.
fn layers(s: &mut Session, p: &Value) -> Result<Value> {
const NAME: &str = "layer.quickOffset";
let d = delta_p(p, NAME)?;
let (cid, ids) = layers_p(s, p)?;
let merge = merge_p(p);
let gesture = b_p(p, "fromStart").unwrap_or(false) && merge.is_some_and(|m| s.history.merge_key.as_deref() == Some(m));
let base = s.history.undo.last().filter(|_| gesture).map(|(_, b)| b.clone());
let start = base.clone().unwrap_or_else(|| s.project.clone());
let comp = start.comp(cid).ok_or(EngineError::NoComp)?;
let order = order(NAME, ids, |id| comp.layer(id).is_some_and(|l| !l.switches.locked))?;
let moves: Vec<(LayerId, Tick)> = order.iter().copied().zip(shares(d, order.len())).collect();
s.edit("Quick Offset", merge, |proj, _| {
if let Some(b) = &base {
*proj = (**b).clone();
}
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
for (id, d) in &moves {
let l = comp.layer_mut(*id).ok_or(EngineError::NoComp)?;
let what = format!("layer \"{}\"", l.name);
let times = (shifted(l.start_time, *d, NAME, &what)?, shifted(l.in_point, *d, NAME, &what)?, shifted(l.out_point, *d, NAME, &what)?);
(l.start_time, l.in_point, l.out_point) = times;
}
Ok(json!({"layers": moves.iter().map(|(id, d)| json!({"layer": id.0, "offset": d.seconds()})).collect::<Vec<_>>()}))
})
}
/// `keys.quickOffset`: the selected keys of each layer move together by the layer's share of
/// `delta` (comp seconds, the last layer's move), the layers in the order their first key was
/// selected. Like `keys.move`, steps sharing `merge` are one drag; with `fromStart`, `delta` is the
/// whole drag.
fn keys(s: &mut Session, p: &Value) -> Result<Value> {
const NAME: &str = "keys.quickOffset";
let d = delta_p(p, NAME)?;
let cid = s.active_comp_id().ok_or(EngineError::NoComp)?;
let merge = merge_p(p);
let (from, total, base) = key_gesture(s, merge, d, b_p(p, "fromStart").unwrap_or(false));
let start = base.clone().unwrap_or_else(|| s.project.clone());
let comp = start.comp(cid).ok_or(EngineError::NoComp)?;
let order = order(NAME, from.iter().map(|k| k.layer), |id| comp.layer(id).is_some_and(|l| !l.switches.locked))?;
let by_layer: HashMap<LayerId, Tick> = order.iter().copied().zip(shares(total, order.len())).collect();
let next = merge.map(|m| crate::KeyMove { merge: m.to_string(), from: from.clone(), total });
let moved = s.edit("Quick Offset Keyframes", merge, |proj, st| {
if let Some(b) = &base {
*proj = (**b).clone();
}
let comp = proj.comp_mut(cid).ok_or(EngineError::NoComp)?;
st.selected_keys = move_key_refs(comp, &from, |l, t| {
let Some(d) = by_layer.get(&l.id) else { return Ok(t) };
let what = format!("a key of \"{}\"", l.name);
shifted(l.start_time, *d, NAME, &what)?;
shifted(t, layer_shift(l, *d), NAME, &what)
})?;
Ok(json!({"keys": st.selected_keys.len(), "layers": order.iter().map(|id| json!({"layer": id.0, "offset": by_layer.get(id).copied().unwrap_or_default().seconds()})).collect::<Vec<_>>()}))
})?;
// Only a step that applied counts towards the drag (a refused one is as if never sent).
s.key_move = next;
Ok(moved)
}
pub fn specs() -> Vec<CommandSpec> {
vec![
cmd!(
"layer.quickOffset",
"Quick Offset",
[],
None,
"{delta (comp s: the last layer's move), layers? (in order; default the selection), merge?, fromStart?: bool (with merge: delta is the whole drag)}",
has_layers,
layers
),
cmd!(
"keys.quickOffset",
"Quick Offset Keyframes",
[],
None,
"{delta (comp s: the last layer's keys' move), merge?, fromStart?: bool (with merge: delta is the whole drag)}",
has_keys,
keys
),
]
}