Skip to content

The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.

refactor(project): undo snapshots share what a command did not touch, and a gesture is one step

Jareer6897bf32e27d
diff --git a/src/crates/concat-export/src/flatten.rs b/src/crates/concat-export/src/flatten.rs
index b10b27ad..f3b2361f 100644
--- a/src/crates/concat-export/src/flatten.rs
+++ b/src/crates/concat-export/src/flatten.rs
@@ -191,6 +191,7 @@ fn pick_timeline<'a>(project: &'a Project, timeline_id: Option<&str>) -> Option<
.iter()
.find(|timeline| timeline.id == wanted)
.or_else(|| project.timelines.first())
+ .map(|timeline| timeline.as_ref())
}
/// The constant the engine should receive for a keyable property.
diff --git a/src/crates/concat-host/src/session.rs b/src/crates/concat-host/src/session.rs
index 70985265..6031a60f 100644
--- a/src/crates/concat-host/src/session.rs
+++ b/src/crates/concat-host/src/session.rs
@@ -191,13 +191,30 @@ impl Session {
/// Applies one edit command and returns the new state.
pub fn apply(&mut self, command: Command) -> Result<EditorView, String> {
+ self.apply_within(None, command)
+ }
+
+ /// Applies one edit command as a move of `gesture`, so that a knob
+ /// dragged through many values is one undo step; see
+ /// `concat_project::Editor::apply_within`. `None` is a step of its own.
+ pub fn apply_within(
+ &mut self,
+ gesture: Option<&str>,
+ command: Command,
+ ) -> Result<EditorView, String> {
let outcome = self
.editor
- .apply(command)
+ .apply_within(gesture, command)
.map_err(|error| error.to_string())?;
Ok(self.view_with(outcome.created_id))
}
+ /// Ends the gesture in progress: the next command naming it starts a
+ /// new undo step.
+ pub fn end_gesture(&mut self) {
+ self.editor.end_gesture();
+ }
+
/// Steps the history back one edit.
pub fn undo(&mut self) -> EditorView {
self.editor.undo();
diff --git a/src/crates/concat-project/Cargo.toml b/src/crates/concat-project/Cargo.toml
index f0e51d3f..532232fc 100644
--- a/src/crates/concat-project/Cargo.toml
+++ b/src/crates/concat-project/Cargo.toml
@@ -9,7 +9,9 @@ description = "The edit itself: the project document, its operations, and undo.
[dependencies]
# The speed curve's arithmetic lives with the engine's time map.
concat-core.workspace = true
-serde = { version = "1", features = ["derive"] }
+# `rc`: timelines and clips sit behind Arc so an undo snapshot shares what
+# a command did not touch; the document still reads and writes them plain.
+serde = { version = "1", features = ["derive", "rc"] }
serde_json.workspace = true
thiserror.workspace = true
diff --git a/src/crates/concat-project/src/commands.rs b/src/crates/concat-project/src/commands.rs
index fb1e6e6f..9c6a94cf 100644
--- a/src/crates/concat-project/src/commands.rs
+++ b/src/crates/concat-project/src/commands.rs
@@ -8,6 +8,7 @@
//! the contract the window's gesture echo mirrors and tests against.
use std::collections::HashSet;
+use std::sync::Arc;
use serde::{Deserialize, Serialize};
@@ -824,6 +825,16 @@ fn next_numbered(name: &str, existing: impl Iterator<Item = String>) -> String {
}
impl Command {
+ /// True for a command that changes what the person is looking at, not
+ /// the edit: which timeline tab is showing and the order of the tabs.
+ /// Saved with the document, never recorded in undo history.
+ pub fn is_view_state(&self) -> bool {
+ matches!(
+ self,
+ Command::SelectTimeline { .. } | Command::MoveTimeline { .. }
+ )
+ }
+
/// True when any number in the command is NaN or infinite. JSON cannot
/// spell one, but a caller in Rust can, and `NaN.clamp()` is NaN: one
/// stored would poison every duration and key it touched, and the
@@ -1107,8 +1118,8 @@ pub fn apply(
// slot freeze-frames on its last frame downstream, which is the
// renderer's existing behaviour for a trim past the media's end.
// All timelines, like RemoveMedia: slots are not per-timeline.
- for timeline in &mut project.timelines {
- for clip in &mut timeline.clips {
+ for timeline in project.timelines.iter_mut().map(Arc::make_mut) {
+ for clip in timeline.clips_mut() {
if clip.media_id == media_id {
clip.source_start = 0.0;
clip.kind = kind;
@@ -1154,7 +1165,7 @@ pub fn apply(
let media_count = project.media.len();
project.media.retain(|item| item.id != media_id);
let mut applied = project.media.len() != media_count;
- for timeline in &mut project.timelines {
+ for timeline in project.timelines.iter_mut().map(Arc::make_mut) {
let clip_count = timeline.clips.len();
timeline.clips.retain(|clip| clip.media_id != media_id);
applied |= timeline.clips.len() != clip_count;
@@ -1181,7 +1192,7 @@ pub fn apply(
let id = mint.next("c");
timeline
.clips
- .push(default_clip(id.clone(), track_id, &media, start));
+ .push(Arc::new(default_clip(id.clone(), track_id, &media, start)));
Ok(Outcome {
created_id: Some(id),
applied: true,
@@ -1203,7 +1214,7 @@ pub fn apply(
let id = mint.next("c");
timeline
.clips
- .push(default_clip(id.clone(), track_id, &media, start));
+ .push(Arc::new(default_clip(id.clone(), track_id, &media, start)));
Ok(Outcome {
created_id: Some(id),
applied: true,
@@ -1230,7 +1241,7 @@ pub fn apply(
}
};
let id = mint.next("c");
- timeline.clips.push(Clip {
+ timeline.clips.push(Arc::new(Clip {
id: id.clone(),
track_id,
media_id: String::new(),
@@ -1269,7 +1280,7 @@ pub fn apply(
detached_from: None,
transition_in: None,
text: Some(style),
- });
+ }));
Ok(Outcome {
created_id: Some(id),
applied: true,
@@ -1295,7 +1306,7 @@ pub fn apply(
}
};
let id = mint.next("c");
- timeline.clips.push(Clip {
+ timeline.clips.push(Arc::new(Clip {
id: id.clone(),
track_id,
media_id: String::new(),
@@ -1338,7 +1349,7 @@ pub fn apply(
detached_from: None,
transition_in: None,
text: None,
- });
+ }));
Ok(Outcome {
created_id: Some(id),
applied: true,
@@ -1424,7 +1435,7 @@ pub fn apply(
// here to the source is not affine, so both halves go to
// the constant mean, which is what they averaged. A
// reverse is affine and survives: see `split_source`.
- let clip = &mut timeline.clips[index];
+ let clip = timeline.clip_at_mut(index);
let offset = time - clip.start;
if offset > MIN_CLIP_DURATION
&& offset < clip.duration - MIN_CLIP_DURATION
@@ -1433,7 +1444,7 @@ pub fn apply(
clip.speed_curve = None;
}
}
- let clip = &timeline.clips[index];
+ let clip: &Clip = &timeline.clips[index];
let offset = time - clip.start;
if offset <= MIN_CLIP_DURATION || offset >= clip.duration - MIN_CLIP_DURATION {
continue;
@@ -1454,9 +1465,9 @@ pub fn apply(
// start, which the head keeps.
tail.transition_in = None;
created = Some(tail.id.clone());
- timeline.clips[index].duration = offset;
- timeline.clips[index].source_start = head_source;
- timeline.clips.insert(index + 1, tail);
+ timeline.clip_at_mut(index).duration = offset;
+ timeline.clip_at_mut(index).source_start = head_source;
+ timeline.clips.insert(index + 1, Arc::new(tail));
}
// A split always mints the tail, so "minted anything" and
// "changed anything" are the same fact here.
@@ -1540,24 +1551,24 @@ pub fn apply(
// under a curve the map is not affine, and the in-point below
// assumes it is, so both pieces go to the constant mean they
// averaged. A reverse is affine and is kept; see `split_source`.
- timeline.clips[index].speed_curve = None;
+ timeline.clip_at_mut(index).speed_curve = None;
let reverse = timeline.clips[index].reverse;
let offset = time - start;
let (head_source, tail_source) =
split_source(source_start, clip_duration, speed, offset, reverse);
- let mut tail = timeline.clips[index].clone();
+ let mut tail = Clip::clone(&timeline.clips[index]);
tail.id = mint.next("c");
tail.start = time;
tail.duration = clip_duration - offset;
tail.source_start = tail_source;
tail.transition_in = None;
- timeline.clips[index].duration = offset;
- timeline.clips[index].source_start = head_source;
- timeline.clips.insert(index + 1, tail);
+ timeline.clip_at_mut(index).duration = offset;
+ timeline.clip_at_mut(index).source_start = head_source;
+ timeline.clips.insert(index + 1, Arc::new(tail));
// Ripple every later placement on this track (including the new
// tail) so the freeze does not sit on top of the remainder.
- for clip in &mut timeline.clips {
+ for clip in timeline.clips_mut() {
if clip.track_id == track_id && clip.start >= time {
clip.start += hold;
}
@@ -1587,7 +1598,7 @@ pub fn apply(
frozen.detached_from = None;
frozen.transition_in = None;
frozen.text = None;
- timeline.clips.push(frozen);
+ timeline.clips.push(Arc::new(frozen));
Ok(Outcome {
created_id: Some(freeze_id),
@@ -2067,7 +2078,7 @@ pub fn apply(
sound.muted = None;
sound.audio_stream = stream;
first_sound.get_or_insert_with(|| sound.id.clone());
- timeline.clips.push(sound);
+ timeline.clips.push(Arc::new(sound));
}
let video = timeline.clip_mut(&clip_id).expect("still present");
@@ -2095,7 +2106,7 @@ pub fn apply(
.clips
.iter()
.filter(|other| other.detached_from.as_deref() == Some(video_id.as_str()))
- .cloned()
+ .map(|other| Clip::clone(other))
.collect();
if sounds.is_empty() {
return Ok(Outcome::default());
@@ -2185,13 +2196,13 @@ pub fn apply(
// likeliest second timeline is another cut of the same picture,
// and the one that is not is a sheet away from being told so.
let video = project.active().video;
- project.timelines.push(Timeline {
+ project.timelines.push(Arc::new(Timeline {
id: id.clone(),
name,
video,
tracks,
clips: Vec::new(),
- });
+ }));
project.active_timeline_id = id.clone();
Ok(Outcome {
created_id: Some(id),
@@ -2207,7 +2218,7 @@ pub fn apply(
.timelines
.iter_mut()
.find(|timeline| timeline.id == timeline_id)
- .is_some_and(|timeline| assign(&mut timeline.video, video));
+ .is_some_and(|timeline| assign(&mut Arc::make_mut(timeline).video, video));
Ok(Outcome {
created_id: None,
applied,
@@ -2249,7 +2260,9 @@ pub fn apply(
.timelines
.iter_mut()
.find(|timeline| timeline.id == timeline_id)
- .is_some_and(|timeline| assign(&mut timeline.name, trimmed.to_owned()));
+ .is_some_and(|timeline| {
+ assign(&mut Arc::make_mut(timeline).name, trimmed.to_owned())
+ });
Ok(Outcome {
created_id: None,
applied,
diff --git a/src/crates/concat-project/src/doc.rs b/src/crates/concat-project/src/doc.rs
index fbba1222..30f29f85 100644
--- a/src/crates/concat-project/src/doc.rs
+++ b/src/crates/concat-project/src/doc.rs
@@ -20,6 +20,8 @@
use std::collections::BTreeMap;
+use std::sync::Arc;
+
use serde_json::{Map, Value, json};
use crate::commands::{
@@ -346,7 +348,7 @@ pub fn from_document(document: &Value) -> Option<Project> {
// The timelines array is the source of truth when present and usable; a
// file from before multiple timelines loads its flat fields as the one
// timeline they always were.
- let mut timelines: Vec<Timeline> = Vec::new();
+ let mut timelines: Vec<Arc<Timeline>> = Vec::new();
if let Some(entries) = document.get("timelines").and_then(Value::as_array) {
for entry in entries {
let Some(id) = entry.get("id").and_then(Value::as_str) else {
@@ -360,13 +362,13 @@ pub fn from_document(document: &Value) -> Option<Project> {
continue;
}
let clips = read_clips(entry.get("clips"), &tracks, &media);
- timelines.push(Timeline {
+ timelines.push(Arc::new(Timeline {
id: id.to_owned(),
name: text(entry.get("name"), "Timeline"),
video: read_video(entry.get("video"), shared),
tracks,
- clips,
- });
+ clips: clips.into_iter().map(Arc::new).collect(),
+ }));
}
}
if timelines.is_empty() {
@@ -375,13 +377,13 @@ pub fn from_document(document: &Value) -> Option<Project> {
return None;
}
let clips = read_clips(document.get("clips"), &tracks, &media);
- timelines.push(Timeline {
+ timelines.push(Arc::new(Timeline {
id: "TL1".to_owned(),
name: "Timeline 1".to_owned(),
video: shared,
tracks,
- clips,
- });
+ clips: clips.into_iter().map(Arc::new).collect(),
+ }));
}
let active_timeline_id = document
diff --git a/src/crates/concat-project/src/editor.rs b/src/crates/concat-project/src/editor.rs
index 36847e3b..f731558e 100644
--- a/src/crates/concat-project/src/editor.rs
+++ b/src/crates/concat-project/src/editor.rs
@@ -3,11 +3,22 @@
//! The editing session: a project, its id mint, and undo.
//!
-//! Undo is whole-state snapshots. The document is small - a heavy project is
-//! a few hundred kilobytes - so cloning per edit is cheaper than maintaining
-//! inverse operations and impossible to get wrong. The depth cap bounds the
-//! memory; two hundred undos of a large project is tens of megabytes, which
-//! an editor holding gigabytes of frame data does not notice.
+//! Undo is whole-state snapshots, and they are cheap: the project's
+//! timelines and clips sit behind `Arc`, so a snapshot copies pointers and
+//! a command copies only the clip it writes to. Impossible to get wrong in
+//! the way inverse operations are, and a heavy project's two hundred undos
+//! are a few megabytes, not a few hundred.
+//!
+//! Two refinements on "one snapshot per command":
+//!
+//! - A **gesture** is one undo step. A knob being dragged commits on every
+//! pause of the pointer; the caller names the gesture, and commits that
+//! name the same gesture as the last recorded step fold into it. See
+//! [`Editor::apply_within`].
+//! - **View state is not an edit.** Which timeline tab is showing, and the
+//! order of the tabs, is saved with the document but never recorded in
+//! history: undo steps back through what changed the picture, not
+//! through what the person was looking at.
use std::collections::VecDeque;
@@ -19,6 +30,14 @@ use crate::model::Project;
const UNDO_DEPTH: usize = 200;
+/// The state before one recorded step, and the gesture it belonged to.
+struct Snapshot {
+ before: Project,
+ /// Set while the gesture that produced this step may still continue;
+ /// cleared by [`Editor::end_gesture`] or by any step of another kind.
+ gesture: Option<String>,
+}
+
/// One editing session: the project, the id mint that keeps its ids unique,
/// and the undo/redo stacks. This is the object a host holds per open
/// project; everything else in the crate is reachable through it.
@@ -27,7 +46,7 @@ pub struct Editor {
mint: IdMint,
/// Oldest snapshot at the front: overflowing the depth cap evicts from
/// the front in constant time, where a Vec would shuffle the whole stack.
- undo: VecDeque<Project>,
+ undo: VecDeque<Snapshot>,
redo: Vec<Project>,
}
@@ -75,24 +94,63 @@ impl Editor {
/// changed something ([`Outcome::applied`]), so undo never replays a
/// no-op - a missing id, a value already in place.
pub fn apply(&mut self, command: Command) -> Result<Outcome, CommandError> {
+ self.apply_within(None, command)
+ }
+
+ /// [`Editor::apply`] as one move of a gesture.
+ ///
+ /// The first command naming a gesture records a step as usual; every
+ /// later command naming the same gesture, with no other step recorded
+ /// in between, folds into that step, so undo lands where the gesture
+ /// began. Commands that set absolute values (every inspector knob) are
+ /// the ones this is for. `None` is a step of its own, and ends any
+ /// gesture in progress.
+ pub fn apply_within(
+ &mut self,
+ gesture: Option<&str>,
+ command: Command,
+ ) -> Result<Outcome, CommandError> {
+ if command.is_view_state() {
+ return apply(&mut self.project, &mut self.mint, command);
+ }
let before = self.project.clone();
let outcome = apply(&mut self.project, &mut self.mint, command)?;
- if outcome.applied {
- self.undo.push_back(before);
+ if !outcome.applied {
+ return Ok(outcome);
+ }
+ let continues = match (gesture, self.undo.back()) {
+ (Some(gesture), Some(last)) => last.gesture.as_deref() == Some(gesture),
+ _ => false,
+ };
+ if !continues {
+ self.undo.push_back(Snapshot {
+ before,
+ gesture: gesture.map(str::to_owned),
+ });
if self.undo.len() > UNDO_DEPTH {
self.undo.pop_front();
}
- self.redo.clear();
}
+ self.redo.clear();
Ok(outcome)
}
+ /// Ends the gesture in progress, if any: the next command naming it
+ /// starts a new step rather than folding into the last one. Called when
+ /// the pointer goes up, or when enough time has passed that a second
+ /// drag of the same knob is a second edit.
+ pub fn end_gesture(&mut self) {
+ if let Some(last) = self.undo.back_mut() {
+ last.gesture = None;
+ }
+ }
+
/// Steps back one edit. Returns whether anything changed.
pub fn undo(&mut self) -> bool {
match self.undo.pop_back() {
Some(previous) => {
self.redo
- .push(std::mem::replace(&mut self.project, previous));
+ .push(std::mem::replace(&mut self.project, previous.before));
true
}
None => false,
@@ -103,8 +161,11 @@ impl Editor {
pub fn redo(&mut self) -> bool {
match self.redo.pop() {
Some(next) => {
- self.undo
- .push_back(std::mem::replace(&mut self.project, next));
+ let before = std::mem::replace(&mut self.project, next);
+ self.undo.push_back(Snapshot {
+ before,
+ gesture: None,
+ });
true
}
None => false,
diff --git a/src/crates/concat-project/src/lib.rs b/src/crates/concat-project/src/lib.rs
index dd7b64bc..bacac42a 100644
--- a/src/crates/concat-project/src/lib.rs
+++ b/src/crates/concat-project/src/lib.rs
@@ -540,6 +540,129 @@ mod tests {
assert_eq!(editor.project().timelines[2].name, "Timeline 2");
}
+ #[test]
+ fn a_gesture_is_one_undo_step() {
+ let (mut editor, _, clip_id) = fixture();
+ let start = editor.project().active().clips[0].scale;
+ for scale in [1.1, 1.2, 1.3] {
+ editor
+ .apply_within(
+ Some("scale"),
+ Command::SetClipTransform {
+ clip_id: clip_id.clone(),
+ scale: Some(scale),
+ offset_x: None,
+ offset_y: None,
+ rotation: None,
+ stretch_x: None,
+ stretch_y: None,
+ },
+ )
+ .expect("scales");
+ }
+ editor.end_gesture();
+ editor
+ .apply_within(
+ Some("scale"),
+ Command::SetClipTransform {
+ clip_id: clip_id.clone(),
+ scale: Some(2.0),
+ offset_x: None,
+ offset_y: None,
+ rotation: None,
+ stretch_x: None,
+ stretch_y: None,
+ },
+ )
+ .expect("scales again");
+ assert_eq!(editor.project().active().clips[0].scale, 2.0);
+ // Two steps: the drag, then the second drag after the gesture ended.
+ assert!(editor.undo());
+ assert_eq!(editor.project().active().clips[0].scale, 1.3);
+ assert!(editor.undo());
+ assert_eq!(editor.project().active().clips[0].scale, start);
+ assert!(editor.redo());
+ assert_eq!(editor.project().active().clips[0].scale, 1.3);
+ }
+
+ #[test]
+ fn switching_and_reordering_tabs_is_not_an_edit() {
+ let (mut editor, _, _) = fixture();
+ editor.apply(Command::AddTimeline).expect("adds");
+ let (first, second) = (
+ editor.project().timelines[0].id.clone(),
+ editor.project().timelines[1].id.clone(),
+ );
+ let steps_before = {
+ let mut count = 0;
+ while editor.undo() {
+ count += 1;
+ }
+ while editor.redo() {}
+ count
+ };
+ editor
+ .apply(Command::SelectTimeline {
+ timeline_id: first.clone(),
+ })
+ .expect("selects");
+ editor
+ .apply(Command::MoveTimeline {
+ timeline_id: second.clone(),
+ index: 0,
+ })
+ .expect("moves");
+ assert_eq!(editor.project().active_timeline_id, first);
+ assert_eq!(editor.project().timelines[0].id, second);
+ let mut count = 0;
+ while editor.undo() {
+ count += 1;
+ }
+ assert_eq!(
+ count, steps_before,
+ "neither the switch nor the move was a step"
+ );
+ }
+
+ #[test]
+ fn a_command_copies_only_what_it_writes() {
+ let (mut editor, _, clip_id) = fixture();
+ editor
+ .apply(Command::SplitClips {
+ clip_ids: vec![clip_id.clone()],
+ time: 4.0,
+ })
+ .expect("splits");
+ editor.apply(Command::AddTimeline).expect("adds");
+ editor
+ .apply(Command::SelectTimeline {
+ timeline_id: "TL1".to_owned(),
+ })
+ .expect("back to the first");
+ let other = std::sync::Arc::clone(&editor.project().timelines[1]);
+ let untouched = std::sync::Arc::clone(&editor.project().active().clips[1]);
+ editor
+ .apply(Command::UpdateClip {
+ clip_id: clip_id.clone(),
+ patch: ClipPatch {
+ volume: Some(0.5),
+ ..Default::default()
+ },
+ })
+ .expect("edits the head");
+ assert!(
+ std::sync::Arc::ptr_eq(&other, &editor.project().timelines[1]),
+ "the other timeline is still shared with the snapshot"
+ );
+ assert!(
+ std::sync::Arc::ptr_eq(&untouched, &editor.project().active().clips[1]),
+ "the clip the edit did not touch is still shared"
+ );
+ assert_eq!(editor.project().active().clips[0].volume, 0.5);
+ assert!(editor.undo());
+ assert_eq!(editor.project().active().clips[0].volume, 1.0);
+ }
+
#[test]
fn rearranged_pieces_refuse_to_merge() {
let (mut editor, _, clip_id) = fixture();
@@ -683,6 +806,7 @@ mod tests {
let sounds: Vec<&crate::model::Clip> = timeline
.clips
.iter()
+ .map(|clip| clip.as_ref())
.filter(|clip| clip.kind == ClipKind::Audio)
.collect();
assert_eq!(sounds.len(), 2);
diff --git a/src/crates/concat-project/src/model.rs b/src/crates/concat-project/src/model.rs
index 6d3778d6..03ec6204 100644
--- a/src/crates/concat-project/src/model.rs
+++ b/src/crates/concat-project/src/model.rs
@@ -12,6 +12,7 @@
//! Serde names are camelCase: that is the document's spelling.
use std::collections::BTreeMap;
+use std::sync::Arc;
use serde::{Deserialize, Serialize};
@@ -1124,7 +1125,12 @@ pub struct Timeline {
pub tracks: Vec<Track>,
/// Every clip on this timeline, in insertion order, not time order -
/// readers must sort by `start` where order matters.
- pub clips: Vec<Clip>,
+ ///
+ /// Behind `Arc` so that cloning the timeline - which undo does before
+ /// every command - copies one pointer per clip, and only the clip a
+ /// command then writes to is copied for real ([`Arc::make_mut`] in
+ /// [`Timeline::clip_mut`]). Reading through the `Arc` is transparent.
+ pub clips: Vec<Arc<Clip>>,
}
/// A timeline's output frame and rate.
@@ -1194,8 +1200,10 @@ pub struct Project {
pub media: Vec<MediaItem>,
/// Fonts the user added from disk, available to every title.
pub fonts: Vec<CustomFont>,
- /// Every timeline, in tab order. Always at least one.
- pub timelines: Vec<Timeline>,
+ /// Every timeline, in tab order. Always at least one. Behind `Arc` for
+ /// the reason [`Timeline::clips`] is: a command on one timeline leaves
+ /// the others shared with the undo snapshot.
+ pub timelines: Vec<Arc<Timeline>>,
/// Which timeline commands act on. Maintained by the command layer, so
/// it always names a member of `timelines`; [`Project::active`] degrades
/// to the first timeline if it somehow does not.
@@ -1225,7 +1233,7 @@ impl Project {
Self {
media: Vec::new(),
fonts: Vec::new(),
- timelines: vec![Timeline {
+ timelines: vec![Arc::new(Timeline {
id: "TL1".to_owned(),
name: "Timeline 1".to_owned(),
video,
@@ -1237,7 +1245,7 @@ impl Project {
})
.collect(),
clips: Vec::new(),
- }],
+ })],
active_timeline_id: "TL1".to_owned(),
}
}
@@ -1260,7 +1268,7 @@ impl Project {
.iter()
.position(|timeline| timeline.id == self.active_timeline_id)
.unwrap_or(0);
- &mut self.timelines[index]
+ Arc::make_mut(&mut self.timelines[index])
}
/// The bin entry with this id, or None if it was removed.
@@ -1308,12 +1316,31 @@ impl Timeline {
/// The clip with this id, or None if it is not on this timeline - which
/// most commands treat as a tolerated no-op, not an error.
pub fn clip(&self, clip_id: &str) -> Option<&Clip> {
- self.clips.iter().find(|clip| clip.id == clip_id)
+ self.clips
+ .iter()
+ .find(|clip| clip.id == clip_id)
+ .map(Arc::as_ref)
}
- /// Mutable twin of [`Timeline::clip`].
+ /// Mutable twin of [`Timeline::clip`]. The clip is copied out of any
+ /// undo snapshot still sharing it before the reference is handed back.
pub fn clip_mut(&mut self, clip_id: &str) -> Option<&mut Clip> {
- self.clips.iter_mut().find(|clip| clip.id == clip_id)
+ self.clips
+ .iter_mut()
+ .find(|clip| clip.id == clip_id)
+ .map(Arc::make_mut)
+ }
+
+ /// Mutable access to the clip at `index`, copied out of any snapshot
+ /// sharing it first. The `Vec` index twin of [`Timeline::clip_mut`].
+ pub fn clip_at_mut(&mut self, index: usize) -> &mut Clip {
+ Arc::make_mut(&mut self.clips[index])
+ }
+
+ /// Every clip, mutable, each copied out of any snapshot sharing it as
+ /// it is reached.
+ pub fn clips_mut(&mut self) -> impl Iterator<Item = &mut Clip> {
+ self.clips.iter_mut().map(Arc::make_mut)
}
/// The track with this id, or None if it was removed.
diff --git a/src/crates/concat/src/studio.rs b/src/crates/concat/src/studio.rs
index 9579c5ec..bba628ea 100644
--- a/src/crates/concat/src/studio.rs
+++ b/src/crates/concat/src/studio.rs
@@ -1676,6 +1676,20 @@ impl Studio {
}
}
+ /// [`Studio::apply`] as one move of an inspector gesture: the same
+ /// bookkeeping, but the editor folds it into the gesture's undo step
+ /// and the coalescing window stays open for the next move.
+ fn apply_within(&mut self, gesture: &str, command: Command) {
+ self.echo = None;
+ let Some(session) = self.session.as_mut() else {
+ return;
+ };
+ match session.apply_within(Some(gesture), command) {
+ Ok(_) => self.after_change(),
+ Err(error) => self.notify(&error, true),
+ }
+ }
+
/// The bookkeeping every change to the edit needs: the caches that
/// follow the document, the autosave, the monitor and the mix.
fn after_change(&mut self) {
@@ -3719,29 +3733,23 @@ impl Studio {
}
// One undo step per gesture, not per pointer move: a commit that
// changes the same things on the same clip as the last, within a
- // moment of it, takes the last one's place. Every command here sets
- // absolute values, so undoing the previous and applying this lands
- // where this alone would have.
+ // moment of it, folds into the last one's step. The editor does the
+ // folding; this decides when a pause is long enough to be a new
+ // gesture on the same knob.
let key = format!("{}:{}", after.id, commit_key(&commands));
let now = std::time::Instant::now();
- let coalesce = self
+ let continues = self
.last_commit
.as_ref()
.is_some_and(|(last, at)| *last == key && now.duration_since(*at).as_millis() < 900);
- if coalesce
- && let Some(session) = self.session.as_mut()
- && session.can_undo()
- {
- session.undo();
- }
- match commands.len() {
- 1 => {
- self.apply(commands.remove(0));
- }
- _ => {
- self.apply(Command::Batch { commands });
- }
+ if !continues && let Some(session) = self.session.as_mut() {
+ session.end_gesture();
}
+ let command = match commands.len() {
+ 1 => commands.remove(0),
+ _ => Command::Batch { commands },
+ };
+ self.apply_within(&key, command);
self.last_commit = Some((key, now));
}
@@ -3874,6 +3882,7 @@ impl Studio {
let mut clips: Vec<&Clip> = timeline
.clips
.iter()
+ .map(|clip| clip.as_ref())
.filter(|clip| {
(clip.kind.is_visual() || clip.kind == model::ClipKind::Text)
&& showing.contains(clip.track_id.as_str())