Skip to content

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

perf(project): typed command errors, honest outcomes, indexed hot paths

Jareer9db61fc70d5f
diff --git a/desktop/src-tauri/src/editor_api.rs b/desktop/src-tauri/src/editor_api.rs
index f1ad1eee..afac43a9 100644
--- a/desktop/src-tauri/src/editor_api.rs
+++ b/desktop/src-tauri/src/editor_api.rs
@@ -162,7 +162,7 @@ pub fn editor_apply(
command: Command,
) -> Result<EditorView, String> {
with_session(&state, |session| {
- let outcome = session.editor.apply(command)?;
+ let outcome = session.editor.apply(command).map_err(|error| error.to_string())?;
Ok(view(session, outcome.created_id))
})
}
diff --git a/engine/crates/wolfcut-project/Cargo.toml b/engine/crates/wolfcut-project/Cargo.toml
index 1a7696a4..b717fdee 100644
--- a/engine/crates/wolfcut-project/Cargo.toml
+++ b/engine/crates/wolfcut-project/Cargo.toml
@@ -9,6 +9,7 @@ description = "The edit itself: the project document, its operations, and undo.
[dependencies]
serde = { version = "1", features = ["derive"] }
serde_json.workspace = true
+thiserror.workspace = true
[lints]
workspace = true
diff --git a/engine/crates/wolfcut-project/src/commands.rs b/engine/crates/wolfcut-project/src/commands.rs
index 9b9ef519..ab57f5cb 100644
--- a/engine/crates/wolfcut-project/src/commands.rs
+++ b/engine/crates/wolfcut-project/src/commands.rs
@@ -6,6 +6,8 @@
//! because during the migration both sides must agree about every edit, and
//! after it this file is simply the only copy.
+use std::collections::HashSet;
+
use serde::{Deserialize, Serialize};
use crate::model::{
@@ -391,7 +393,7 @@ pub enum Command {
}
/// What a command produced, beyond the new state: the ids it minted, so the
-/// UI can select what it just created.
+/// UI can select what it just created, and whether anything changed at all.
#[derive(Clone, Default, PartialEq, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Outcome {
@@ -400,6 +402,48 @@ pub struct Outcome {
/// when nothing was created, including tolerated no-ops.
#[serde(skip_serializing_if = "Option::is_none")]
pub created_id: Option<String>,
+ /// Whether the command actually changed the project. A tolerated no-op -
+ /// a missing id, a field set to the value it already had - succeeds but
+ /// reports false, which is how the editor knows not to record an undo
+ /// snapshot for it. For a batch: whether any member changed anything.
+ #[serde(default)]
+ pub applied: bool,
+}
+
+/// Why a command was refused. Every variant renders through `Display` as the
+/// exact user-facing sentence the UI shows - byte for byte the strings
+/// `desktop/src/lib/editor.ts` treats as the contract; the enum only gives
+/// those sentences names a host can match on.
+#[derive(Clone, PartialEq, Eq, Debug, thiserror::Error)]
+pub enum CommandError {
+ /// [`Command::FillSlot`] named a media id no longer in the bin.
+ #[error("That template slot no longer exists.")]
+ SlotGone,
+ /// [`Command::FillSlot`] targeted ordinary media rather than a slot.
+ #[error("That media is not a template slot.")]
+ NotASlot,
+ /// A clip-placing command named media no longer in the bin.
+ #[error("That media is no longer in the bin.")]
+ MediaGone,
+ /// A clip-placing command named a track no longer on the timeline.
+ #[error("That track no longer exists.")]
+ TrackGone,
+ /// A first-free-track placement found a timeline with no tracks at all.
+ #[error("There are no tracks.")]
+ NoTracks,
+ /// [`Command::MergeClips`] was refused, for whichever [`why_not_merge`]
+ /// reason applied.
+ #[error("{reason}")]
+ CannotMerge {
+ /// The [`why_not_merge`] sentence, verbatim.
+ reason: String,
+ },
+ /// [`Command::RemoveTrack`] would have deleted the last track.
+ #[error("A timeline needs at least one track.")]
+ LastTrack,
+ /// [`Command::RemoveTimeline`] would have deleted the last timeline.
+ #[error("A project needs at least one timeline.")]
+ LastTimeline,
}
/// Mints ids. Owned by the editor so restored projects advance it past every
@@ -563,10 +607,29 @@ pub fn why_not_merge(timeline: &Timeline, clip_ids: &[String]) -> Option<String>
None
}
-/// Applies one command. Errors are user-meaningful sentences; a command that
-/// legitimately does nothing (a no-op rename, an out-of-range split) returns
-/// Ok with no created id, matching the tolerant TS operations it replaces.
-pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Result<Outcome, String> {
+/// Assigns `value` into `slot`, reporting whether that changed anything.
+/// This is how command arms notice a field being set to the value it already
+/// holds - which must count as "nothing happened" ([`Outcome::applied`]
+/// false), or the undo history would record phantom edits.
+fn assign<T: PartialEq>(slot: &mut T, value: T) -> bool {
+ if *slot == value {
+ false
+ } else {
+ *slot = value;
+ true
+ }
+}
+
+/// Applies one command. Errors are [`CommandError`]s, each rendering as a
+/// user-meaningful sentence; a command that legitimately does nothing (a
+/// no-op rename, an out-of-range split) returns Ok with no created id and
+/// [`Outcome::applied`] false, matching the tolerant TS operations it
+/// replaces.
+pub fn apply(
+ project: &mut Project,
+ mint: &mut IdMint,
+ command: Command,
+) -> Result<Outcome, CommandError> {
match command {
Command::AddMedia { item } => {
if project.media.iter().any(|existing| existing.path == item.path) {
@@ -588,14 +651,16 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
has_audio: item.has_audio,
placeholder: false,
});
- Ok(Outcome { created_id: Some(id) })
+ Ok(Outcome { created_id: Some(id), applied: true })
}
Command::SetMediaPlaceholder { media_id, placeholder } => {
- if let Some(item) = project.media.iter_mut().find(|item| item.id == media_id) {
- item.placeholder = placeholder;
- }
- Ok(Outcome::default())
+ let applied = project
+ .media
+ .iter_mut()
+ .find(|item| item.id == media_id)
+ .is_some_and(|item| assign(&mut item.placeholder, placeholder));
+ Ok(Outcome { created_id: None, applied })
}
Command::FillSlot { media_id, item } => {
@@ -603,9 +668,9 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
.media
.iter_mut()
.find(|existing| existing.id == media_id)
- .ok_or("That template slot no longer exists.")?;
+ .ok_or(CommandError::SlotGone)?;
if !media.placeholder {
- return Err("That media is not a template slot.".to_owned());
+ return Err(CommandError::NotASlot);
}
// The slot keeps its id, so every clip that references it keeps
@@ -643,7 +708,9 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
}
}
}
- Ok(Outcome::default())
+ // Filling always changes the project: the target was a
+ // placeholder and is one no longer.
+ Ok(Outcome { created_id: None, applied: true })
}
Command::Batch { commands } => {
@@ -652,44 +719,50 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
// batch behind (and the editor records it as one undo step).
let mut staged = project.clone();
let mut created = None;
+ let mut applied = false;
for command in commands {
let outcome = apply(&mut staged, mint, command)?;
if outcome.created_id.is_some() {
created = outcome.created_id;
}
+ applied |= outcome.applied;
}
*project = staged;
- Ok(Outcome { created_id: created })
+ Ok(Outcome { created_id: created, applied })
}
Command::RemoveMedia { media_id } => {
// All timelines, not just the active one: a shelved clip whose
// media is gone would linger as a dead reference.
+ 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 {
+ let clip_count = timeline.clips.len();
timeline.clips.retain(|clip| clip.media_id != media_id);
+ applied |= timeline.clips.len() != clip_count;
}
- Ok(Outcome::default())
+ Ok(Outcome { created_id: None, applied })
}
Command::AddClip { media_id, track_id, start } => {
let media = project
.media_by_id(&media_id)
- .ok_or("That media is no longer in the bin.")?
+ .ok_or(CommandError::MediaGone)?
.clone();
let timeline = project.active_mut();
if timeline.track(&track_id).is_none() {
- return Err("That track no longer exists.".to_owned());
+ return Err(CommandError::TrackGone);
}
let id = mint.next("c");
timeline.clips.push(default_clip(id.clone(), track_id, &media, start));
- Ok(Outcome { created_id: Some(id) })
+ Ok(Outcome { created_id: Some(id), applied: true })
}
Command::AddClipAtFirstFree { media_id, start } => {
let media = project
.media_by_id(&media_id)
- .ok_or("That media is no longer in the bin.")?
+ .ok_or(CommandError::MediaGone)?
.clone();
let duration = match media.kind {
MediaKind::Image => DEFAULT_IMAGE_DURATION,
@@ -697,10 +770,10 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
};
let timeline = project.active_mut();
let track_id =
- first_free_track(timeline, start, duration).ok_or("There are no tracks.")?;
+ first_free_track(timeline, start, duration).ok_or(CommandError::NoTracks)?;
let id = mint.next("c");
timeline.clips.push(default_clip(id.clone(), track_id, &media, start));
- Ok(Outcome { created_id: Some(id) })
+ Ok(Outcome { created_id: Some(id), applied: true })
}
Command::AddTextClip { track_id, start, style, duration, offset_y } => {
@@ -709,9 +782,9 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
let timeline = project.active_mut();
let track_id = match track_id {
Some(id) if timeline.track(&id).is_some() => id,
- Some(_) => return Err("That track no longer exists.".to_owned()),
+ Some(_) => return Err(CommandError::TrackGone),
None => first_free_track(timeline, start, duration)
- .ok_or("There are no tracks.")?,
+ .ok_or(CommandError::NoTracks)?,
};
let id = mint.next("c");
timeline.clips.push(Clip {
@@ -740,22 +813,23 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
transition_in: None,
text: Some(style),
});
- Ok(Outcome { created_id: Some(id) })
+ Ok(Outcome { created_id: Some(id), applied: true })
}
Command::MoveClips { moves } => {
let timeline = project.active_mut();
- let track_ids: Vec<String> =
+ let track_ids: HashSet<String> =
timeline.tracks.iter().map(|track| track.id.clone()).collect();
+ let mut applied = false;
for wanted in moves {
if let Some(clip) = timeline.clip_mut(&wanted.clip_id) {
- clip.start = wanted.start.max(0.0);
+ applied |= assign(&mut clip.start, wanted.start.max(0.0));
if track_ids.contains(&wanted.track_id) {
- clip.track_id = wanted.track_id;
+ applied |= assign(&mut clip.track_id, wanted.track_id);
}
}
}
- Ok(Outcome::default())
+ Ok(Outcome { created_id: None, applied })
}
Command::TrimClip { clip_id, edge, delta } => {
@@ -763,22 +837,26 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
let Some(clip) = timeline.clip_mut(&clip_id) else {
return Ok(Outcome::default());
};
- match edge {
+ let applied = match edge {
TrimEdge::End => {
- clip.duration = (clip.duration + delta).max(MIN_CLIP_DURATION);
+ let duration = (clip.duration + delta).max(MIN_CLIP_DURATION);
+ assign(&mut clip.duration, duration)
}
TrimEdge::Start => {
// Dragging the head moves the in-point too, so the pixels
// under the remaining part of the clip do not slide.
let shift = delta.min(clip.duration - MIN_CLIP_DURATION);
let start = (clip.start + shift).max(0.0);
- let applied = start - clip.start;
- clip.start = start;
- clip.duration -= applied;
- clip.source_start = (clip.source_start + applied * clip.speed).max(0.0);
+ let moved = start - clip.start;
+ let duration = clip.duration - moved;
+ let source_start = (clip.source_start + moved * clip.speed).max(0.0);
+ // Bitwise so no assignment is short-circuited away.
+ assign(&mut clip.start, start)
+ | assign(&mut clip.duration, duration)
+ | assign(&mut clip.source_start, source_start)
}
- }
- Ok(Outcome::default())
+ };
+ Ok(Outcome { created_id: None, applied })
}
Command::SplitClips { clip_ids, time } => {
@@ -806,13 +884,16 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
timeline.clips[index].duration = offset;
timeline.clips.insert(index + 1, tail);
}
- Ok(Outcome { created_id: created })
+ // A split always mints the tail, so "minted anything" and
+ // "changed anything" are the same fact here.
+ let applied = created.is_some();
+ Ok(Outcome { created_id: created, applied })
}
Command::MergeClips { clip_ids } => {
let timeline = project.active_mut();
if let Some(reason) = why_not_merge(timeline, &clip_ids) {
- return Err(reason);
+ return Err(CommandError::CannotMerge { reason });
}
let mut ordered: Vec<Clip> =
clip_ids.iter().filter_map(|id| timeline.clip(id).cloned()).collect();
@@ -821,19 +902,25 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
let last = ordered.last().expect("validated above");
let merged_duration = last.start + last.duration - first.start;
- let doomed: Vec<String> =
+ // A set, not a Vec: the retain below tests every clip on the
+ // timeline against it.
+ let doomed: HashSet<String> =
ordered.iter().skip(1).map(|clip| clip.id.clone()).collect();
timeline.clips.retain(|clip| !doomed.contains(&clip.id));
let survivor =
timeline.clip_mut(&first.id).expect("the first piece survives the retain");
survivor.duration = merged_duration;
- Ok(Outcome { created_id: Some(first.id) })
+ // A validated merge always absorbs at least one piece.
+ Ok(Outcome { created_id: Some(first.id), applied: true })
}
Command::RemoveClips { clip_ids } => {
let timeline = project.active_mut();
- timeline.clips.retain(|clip| !clip_ids.contains(&clip.id));
- Ok(Outcome::default())
+ let doomed: HashSet<&str> = clip_ids.iter().map(String::as_str).collect();
+ let clip_count = timeline.clips.len();
+ timeline.clips.retain(|clip| !doomed.contains(clip.id.as_str()));
+ let applied = timeline.clips.len() != clip_count;
+ Ok(Outcome { created_id: None, applied })
}
Command::UpdateClip { clip_id, patch } => {
@@ -841,41 +928,42 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
let Some(clip) = timeline.clip_mut(&clip_id) else {
return Ok(Outcome::default());
};
+ let mut applied = false;
if let Some(name) = patch.name {
- clip.name = name;
+ applied |= assign(&mut clip.name, name);
}
if let Some(volume) = patch.volume {
- clip.volume = volume.max(0.0);
+ applied |= assign(&mut clip.volume, volume.max(0.0));
}
if let Some(fade_in) = patch.fade_in {
- clip.fade_in = fade_in.max(0.0);
+ applied |= assign(&mut clip.fade_in, fade_in.max(0.0));
}
if let Some(fade_out) = patch.fade_out {
- clip.fade_out = fade_out.max(0.0);
+ applied |= assign(&mut clip.fade_out, fade_out.max(0.0));
}
if let Some(opacity) = patch.opacity {
- clip.opacity = opacity.clamp(0.0, 1.0);
+ applied |= assign(&mut clip.opacity, opacity.clamp(0.0, 1.0));
}
if let Some(preserve) = patch.preserve_pitch {
- clip.preserve_pitch = preserve;
+ applied |= assign(&mut clip.preserve_pitch, preserve);
}
if let Some(filters) = patch.filters {
- clip.filters = filters;
+ applied |= assign(&mut clip.filters, filters);
}
if let Some(effects) = patch.video_effects {
- clip.video_effects = effects;
+ applied |= assign(&mut clip.video_effects, effects);
}
if let Some(transition) = patch.transition_in {
- clip.transition_in = transition;
+ applied |= assign(&mut clip.transition_in, transition);
}
if let Some(text) = patch.text {
// The name follows the words, like addTextClip snapshots it.
if let Some(style) = &text {
- clip.name = first_line(&style.content);
+ applied |= assign(&mut clip.name, first_line(&style.content));
}
- clip.text = text;
+ applied |= assign(&mut clip.text, text);
}
- Ok(Outcome::default())
+ Ok(Outcome { created_id: None, applied })
}
Command::SetClipSpeed { clip_id, speed } => {
@@ -887,9 +975,10 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
// makes this a speed change rather than a trim.
let next = speed.clamp(MIN_SPEED, MAX_SPEED);
let source_covered = clip.duration * clip.speed;
- clip.speed = next;
- clip.duration = (source_covered / next).max(MIN_CLIP_DURATION);
- Ok(Outcome::default())
+ // Bitwise so no assignment is short-circuited away.
+ let applied = assign(&mut clip.speed, next)
+ | assign(&mut clip.duration, (source_covered / next).max(MIN_CLIP_DURATION));
+ Ok(Outcome { created_id: None, applied })
}
Command::SetClipTransform { clip_id, scale, offset_x, offset_y, rotation } => {
@@ -897,21 +986,23 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
let Some(clip) = timeline.clip_mut(&clip_id) else {
return Ok(Outcome::default());
};
+ let mut applied = false;
if let Some(scale) = scale {
- clip.scale = scale.clamp(MIN_SCALE, MAX_SCALE);
+ applied |= assign(&mut clip.scale, scale.clamp(MIN_SCALE, MAX_SCALE));
}
if let Some(offset) = offset_x {
- clip.offset_x = offset.clamp(-MAX_OFFSET, MAX_OFFSET);
+ applied |= assign(&mut clip.offset_x, offset.clamp(-MAX_OFFSET, MAX_OFFSET));
}
if let Some(offset) = offset_y {
- clip.offset_y = offset.clamp(-MAX_OFFSET, MAX_OFFSET);
+ applied |= assign(&mut clip.offset_y, offset.clamp(-MAX_OFFSET, MAX_OFFSET));
}
if let Some(rotation) = rotation {
// Kept in (-180, 180] so a full drag never accumulates turns.
let wrapped = ((rotation % 360.0) + 540.0) % 360.0 - 180.0;
- clip.rotation = if wrapped == -180.0 { 180.0 } else { wrapped };
+ let next = if wrapped == -180.0 { 180.0 } else { wrapped };
+ applied |= assign(&mut clip.rotation, next);
}
- Ok(Outcome::default())
+ Ok(Outcome { created_id: None, applied })
}
Command::DetachAudio { clip_id } => {
@@ -979,7 +1070,7 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
let video = timeline.clip_mut(&clip_id).expect("still present");
video.muted = Some(true);
video.filters = Vec::new();
- Ok(Outcome { created_id: Some(sound_id) })
+ Ok(Outcome { created_id: Some(sound_id), applied: true })
}
Command::ReattachAudio { clip_id } => {
@@ -1003,12 +1094,15 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
if sounds.is_empty() {
return Ok(Outcome::default());
}
- let doomed: Vec<String> = sounds.iter().map(|sound| sound.id.clone()).collect();
+ // A set, not a Vec: the retain below tests every clip on the
+ // timeline against it.
+ let doomed: HashSet<String> = sounds.iter().map(|sound| sound.id.clone()).collect();
timeline.clips.retain(|other| !doomed.contains(&other.id));
let video = timeline.clip_mut(&video_id).expect("checked above");
video.muted = None;
video.filters = sounds[0].filters.clone();
- Ok(Outcome::default())
+ // Reaching here means at least one sound clip was deleted.
+ Ok(Outcome { created_id: None, applied: true })
}
Command::AddTrack => {
@@ -1017,17 +1111,21 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
let name =
next_numbered("Track", timeline.tracks.iter().map(|track| track.name.clone()));
timeline.tracks.push(Track { id: id.clone(), name, visible: true, muted: false });
- Ok(Outcome { created_id: Some(id) })
+ Ok(Outcome { created_id: Some(id), applied: true })
}
Command::RemoveTrack { track_id } => {
let timeline = project.active_mut();
if timeline.tracks.len() <= 1 {
- return Err("A timeline needs at least one track.".to_owned());
+ return Err(CommandError::LastTrack);
}
+ let track_count = timeline.tracks.len();
timeline.tracks.retain(|track| track.id != track_id);
timeline.clips.retain(|clip| clip.track_id != track_id);
- Ok(Outcome::default())
+ // Clips only ever sit on existing tracks, so an unknown id - the
+ // tolerated no-op - removes neither.
+ let applied = timeline.tracks.len() != track_count;
+ Ok(Outcome { created_id: None, applied })
}
Command::RenameTrack { track_id, name } => {
@@ -1036,21 +1134,25 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
return Ok(Outcome::default());
}
let timeline = project.active_mut();
- if let Some(track) = timeline.tracks.iter_mut().find(|track| track.id == track_id) {
- track.name = trimmed.to_owned();
- }
- Ok(Outcome::default())
+ let applied = timeline
+ .tracks
+ .iter_mut()
+ .find(|track| track.id == track_id)
+ .is_some_and(|track| assign(&mut track.name, trimmed.to_owned()));
+ Ok(Outcome { created_id: None, applied })
}
Command::SetTrackFlag { track_id, flag, value } => {
let timeline = project.active_mut();
- if let Some(track) = timeline.tracks.iter_mut().find(|track| track.id == track_id) {
- match flag {
- TrackFlag::Visible => track.visible = value,
- TrackFlag::Muted => track.muted = value,
- }
- }
- Ok(Outcome::default())
+ let applied = timeline
+ .tracks
+ .iter_mut()
+ .find(|track| track.id == track_id)
+ .is_some_and(|track| match flag {
+ TrackFlag::Visible => assign(&mut track.visible, value),
+ TrackFlag::Muted => assign(&mut track.muted, value),
+ });
+ Ok(Outcome { created_id: None, applied })
}
Command::AddTimeline => {
@@ -1069,12 +1171,12 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
.collect();
project.timelines.push(Timeline { id: id.clone(), name, tracks, clips: Vec::new() });
project.active_timeline_id = id.clone();
- Ok(Outcome { created_id: Some(id) })
+ Ok(Outcome { created_id: Some(id), applied: true })
}
Command::RemoveTimeline { timeline_id } => {
if project.timelines.len() <= 1 {
- return Err("A project needs at least one timeline.".to_owned());
+ return Err(CommandError::LastTimeline);
}
let Some(index) =
project.timelines.iter().position(|timeline| timeline.id == timeline_id)
@@ -1086,7 +1188,7 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
project.active_timeline_id = project.timelines[neighbour].id.clone();
}
project.timelines.remove(index);
- Ok(Outcome::default())
+ Ok(Outcome { created_id: None, applied: true })
}
Command::RenameTimeline { timeline_id, name } => {
@@ -1094,33 +1196,37 @@ pub fn apply(project: &mut Project, mint: &mut IdMint, command: Command) -> Resu
if trimmed.is_empty() {
return Ok(Outcome::default());
}
- if let Some(timeline) =
- project.timelines.iter_mut().find(|timeline| timeline.id == timeline_id)
- {
- timeline.name = trimmed.to_owned();
- }
- Ok(Outcome::default())
+ let applied = project
+ .timelines
+ .iter_mut()
+ .find(|timeline| timeline.id == timeline_id)
+ .is_some_and(|timeline| assign(&mut timeline.name, trimmed.to_owned()));
+ Ok(Outcome { created_id: None, applied })
}
Command::SelectTimeline { timeline_id } => {
- if project.timelines.iter().any(|timeline| timeline.id == timeline_id) {
- project.active_timeline_id = timeline_id;
- }
- Ok(Outcome::default())
+ // Short-circuiting is right here: an unknown id must not touch
+ // the selection at all.
+ let applied = project.timelines.iter().any(|timeline| timeline.id == timeline_id)
+ && assign(&mut project.active_timeline_id, timeline_id);
+ Ok(Outcome { created_id: None, applied })
}
Command::AddFont { family, path } => {
- if !project.fonts.iter().any(|font| font.path == path) {
- project.fonts.push(CustomFont { family, path });
+ if project.fonts.iter().any(|font| font.path == path) {
+ return Ok(Outcome::default());
}
- Ok(Outcome::default())
+ project.fonts.push(CustomFont { family, path });
+ Ok(Outcome { created_id: None, applied: true })
}
Command::RemoveFont { family } => {
// Clips keep the family name: the face may come back when the
// file does.
+ let font_count = project.fonts.len();
project.fonts.retain(|font| font.family != family);
- Ok(Outcome::default())
+ let applied = project.fonts.len() != font_count;
+ Ok(Outcome { created_id: None, applied })
}
}
}
diff --git a/engine/crates/wolfcut-project/src/editor.rs b/engine/crates/wolfcut-project/src/editor.rs
index 82034cba..c618e6d6 100644
--- a/engine/crates/wolfcut-project/src/editor.rs
+++ b/engine/crates/wolfcut-project/src/editor.rs
@@ -6,9 +6,11 @@
//! memory; two hundred undos of a large project is tens of megabytes, which
//! an editor holding gigabytes of frame data does not notice.
+use std::collections::VecDeque;
+
use serde_json::Value;
-use crate::commands::{Command, IdMint, Outcome, apply};
+use crate::commands::{Command, CommandError, IdMint, Outcome, apply};
use crate::doc::{DocumentSettings, from_document, to_document};
use crate::model::Project;
@@ -20,14 +22,21 @@ const UNDO_DEPTH: usize = 200;
pub struct Editor {
project: Project,
mint: IdMint,
- undo: Vec<Project>,
+ /// 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>,
redo: Vec<Project>,
}
impl Editor {
/// A fresh, empty project.
pub fn new() -> Self {
- Self { project: Project::new(), mint: IdMint::default(), undo: Vec::new(), redo: Vec::new() }
+ Self {
+ project: Project::new(),
+ mint: IdMint::default(),
+ undo: VecDeque::new(),
+ redo: Vec::new(),
+ }
}
/// Restores a project from a document, adopting every id it uses so the
@@ -37,7 +46,7 @@ impl Editor {
let project = from_document(document)?;
let mut mint = IdMint::default();
mint.adopt_project(&project);
- Some(Self { project, mint, undo: Vec::new(), redo: Vec::new() })
+ Some(Self { project, mint, undo: VecDeque::new(), redo: Vec::new() })
}
/// The current state, read-only: all mutation goes through
@@ -48,16 +57,17 @@ impl Editor {
/// Applies one command, recording the state before it for undo.
///
- /// A command that fails leaves the project and history untouched - the
- /// snapshot is only kept when something actually changed, so undo never
- /// replays a no-op.
- pub fn apply(&mut self, command: Command) -> Result<Outcome, String> {
+ /// A command that fails leaves the project and history untouched, and
+ /// the snapshot is only kept when the command reports it actually
+ /// 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> {
let before = self.project.clone();
let outcome = apply(&mut self.project, &mut self.mint, command)?;
- if self.project != before {
- self.undo.push(before);
+ if outcome.applied {
+ self.undo.push_back(before);
if self.undo.len() > UNDO_DEPTH {
- self.undo.remove(0);
+ self.undo.pop_front();
}
self.redo.clear();
}
@@ -66,7 +76,7 @@ impl Editor {
/// Steps back one edit. Returns whether anything changed.
pub fn undo(&mut self) -> bool {
- match self.undo.pop() {
+ match self.undo.pop_back() {
Some(previous) => {
self.redo.push(std::mem::replace(&mut self.project, previous));
true
@@ -79,7 +89,7 @@ impl Editor {
pub fn redo(&mut self) -> bool {
match self.redo.pop() {
Some(next) => {
- self.undo.push(std::mem::replace(&mut self.project, next));
+ self.undo.push_back(std::mem::replace(&mut self.project, next));
true
}
None => false,
diff --git a/engine/crates/wolfcut-project/src/lib.rs b/engine/crates/wolfcut-project/src/lib.rs
index 3d51c939..8b17566d 100644
--- a/engine/crates/wolfcut-project/src/lib.rs
+++ b/engine/crates/wolfcut-project/src/lib.rs
@@ -23,7 +23,7 @@ pub mod doc;
pub mod editor;
pub mod model;
-pub use commands::{Command, Outcome, why_not_merge};
+pub use commands::{Command, CommandError, Outcome, why_not_merge};
pub use doc::{DocumentSettings, from_document, to_document};
pub use editor::Editor;
pub use model::Project;
@@ -32,7 +32,7 @@ pub use model::Project;
mod tests {
use serde_json::json;
- use crate::commands::{ClipMove, ClipPatch, Command, TrimEdge};
+ use crate::commands::{ClipMove, ClipPatch, Command, TrackFlag, TrimEdge};
use crate::doc::DocumentSettings;
use crate::editor::Editor;
use crate::model::{ClipKind, MediaKind, TextStyle};
@@ -133,7 +133,7 @@ mod tests {
})
.expect("moves");
let refused = editor.apply(Command::MergeClips { clip_ids: vec![tail_id, clip_id] });
- assert!(refused.unwrap_err().contains("no longer in their original order"));
+ assert!(refused.unwrap_err().to_string().contains("no longer in their original order"));
}
#[test]
@@ -427,7 +427,7 @@ mod tests {
has_audio: false,
},
});
- assert!(refused.unwrap_err().contains("not a template slot"));
+ assert!(refused.unwrap_err().to_string().contains("not a template slot"));
}
#[test]
@@ -534,4 +534,566 @@ mod tests {
let restored = Editor::from_document(&document).expect("loads");
assert_eq!(restored.project(), editor.project());
}
+
+ #[test]
+ fn a_tolerated_no_op_records_no_undo_entry() {
+ // The applied flag replaced a deep state compare; if a missing-id
+ // command ever reported true, undo would gain phantom steps.
+ let (mut editor, _, _) = fixture();
+ let outcome = editor
+ .apply(Command::TrimClip {
+ clip_id: "nope".to_owned(),
+ edge: TrimEdge::End,
+ delta: 1.0,
+ })
+ .expect("tolerated");
+ assert!(!outcome.applied);
+
+ assert!(editor.undo(), "history still holds the fixture's edits");
+ assert_eq!(
+ editor.project().active().clips.len(),
+ 0,
+ "the first undo steps over the add-clip, not a phantom no-op"
+ );
+ }
+
+ #[test]
+ fn setting_a_value_already_in_place_records_no_undo_entry() {
+ let (mut editor, _, clip_id) = fixture();
+ // Volume is already 1.0; the old deep-compare saw no change here and
+ // pushed nothing - the applied flag must agree exactly.
+ let outcome = editor
+ .apply(Command::UpdateClip {
+ clip_id,
+ patch: ClipPatch { volume: Some(1.0), ..ClipPatch::default() },
+ })
+ .expect("tolerated");
+ assert!(!outcome.applied);
+ assert!(editor.undo());
+ assert!(editor.project().active().clips.is_empty(), "straight back past the add-clip");
+ }
+
+ #[test]
+ fn a_batch_reports_applied_only_when_a_member_changed_something() {
+ let (mut editor, _, clip_id) = fixture();
+ let track_id = editor.project().active().tracks[0].id.clone();
+ // Visible is already true; only the speed change is real.
+ let outcome = editor
+ .apply(Command::Batch {
+ commands: vec![
+ Command::SetTrackFlag {
+ track_id: track_id.clone(),
+ flag: TrackFlag::Visible,
+ value: true,
+ },
+ Command::SetClipSpeed { clip_id, speed: 2.0 },
+ ],
+ })
+ .expect("applies");
+ assert!(outcome.applied);
+ assert!(editor.undo());
+ assert_eq!(editor.project().active().clips[0].speed, 1.0, "one undo undoes the batch");
+
+ // A batch of nothing-but-no-ops is itself a no-op: no undo entry.
+ let outcome = editor
+ .apply(Command::Batch {
+ commands: vec![
+ Command::SetTrackFlag { track_id, flag: TrackFlag::Visible, value: true },
+ Command::TrimClip {
+ clip_id: "nope".to_owned(),
+ edge: TrimEdge::End,
+ delta: 1.0,
+ },
+ ],
+ })
+ .expect("tolerated");
+ assert!(!outcome.applied);
+ assert!(editor.undo());
+ assert!(
+ editor.project().active().clips.is_empty(),
+ "the next undo steps over the add-clip, not a phantom batch"
+ );
+ }
+
+ #[test]
+ fn undo_depth_evicts_the_oldest_snapshot_first() {
+ // The cap used to remove(0) on a Vec; the VecDeque must keep the
+ // same outward behaviour - the newest 200 steps stay undoable.
+ let (mut editor, _, clip_id) = fixture();
+ for step in 0..205 {
+ editor
+ .apply(Command::SetClipTransform {
+ clip_id: clip_id.clone(),
+ scale: None,
+ offset_x: Some(f64::from(step) / 1000.0 + 0.001),
+ offset_y: None,
+ rotation: None,
+ })
+ .expect("applies");
+ }
+ let mut undos = 0;
+ while editor.undo() {
+ undos += 1;
+ }
+ assert_eq!(undos, 200);
+ }
+
+ #[test]
+ fn moves_to_a_vanished_track_keep_the_time_change_and_drop_the_track_change() {
+ // Pinned deliberately: a drag that races a track deletion still
+ // lands its horizontal half, exactly as the TS operation tolerated.
+ let (mut editor, _, clip_id) = fixture();
+ let outcome = editor
+ .apply(Command::MoveClips {
+ moves: vec![ClipMove {
+ clip_id: clip_id.clone(),
+ start: 3.0,
+ track_id: "gone".to_owned(),
+ }],
+ })
+ .expect("tolerated");
+ assert!(outcome.applied, "the start change is real");
+ let clip = editor.project().active().clip(&clip_id).expect("exists");
+ assert_eq!(clip.start, 3.0);
+ assert_eq!(clip.track_id, "T1", "the vanished destination is ignored");
+ }
+
+ #[test]
+ fn a_multi_move_skips_unknown_clips_and_floors_start_at_zero() {
+ let (mut editor, _, clip_id) = fixture();
+ let target = editor.project().active().tracks[1].id.clone();
+ editor
+ .apply(Command::MoveClips {
+ moves: vec![
+ // The unknown clip is skipped; the rest still lands.
+ ClipMove { clip_id: "nope".to_owned(), start: 9.0, track_id: target.clone() },
+ ClipMove { clip_id: clip_id.clone(), start: -2.0, track_id: target.clone() },
+ ],
+ })
+ .expect("tolerated");
+ let clip = editor.project().active().clip(&clip_id).expect("exists");
+ assert_eq!(clip.start, 0.0, "negative starts clamp to the timeline head");
+ assert_eq!(clip.track_id, target);
+ }
+
+ #[test]
+ fn a_tail_trim_stretches_only_the_duration_and_stops_at_the_minimum() {
+ let (mut editor, _, clip_id) = fixture();
+ editor
+ .apply(Command::TrimClip { clip_id: clip_id.clone(), edge: TrimEdge::End, delta: -4.0 })
+ .expect("trims");
+ let clip = editor.project().active().clip(&clip_id).expect("exists");
+ assert_eq!(clip.duration, 6.0);
+ assert_eq!(clip.start, 0.0, "the head does not move");
+ assert_eq!(clip.source_start, 0.0, "nor the in-point");
+
+ // Dragging far past the head floors at a sixtieth of a second
+ // rather than inverting the clip.
+ editor
+ .apply(Command::TrimClip {
+ clip_id: clip_id.clone(),
+ edge: TrimEdge::End,
+ delta: -100.0,
+ })
+ .expect("trims");
+ assert_eq!(
+ editor.project().active().clip(&clip_id).expect("exists").duration,
+ 1.0 / 60.0
+ );
+ }
+
+ #[test]
+ fn add_at_first_free_takes_the_lowest_empty_lane_or_the_bottom_one() {
+ let (mut editor, media_id, _) = fixture();
+ // Track one is occupied for [0, 10), so the same span lands on two.
+ let second = editor
+ .apply(Command::AddClipAtFirstFree { media_id: media_id.clone(), start: 0.0 })
+ .expect("adds")
+ .created_id
+ .expect("id");
+ assert_eq!(
+ editor.project().active().clip(&second).expect("exists").track_id,
+ editor.project().active().tracks[1].id
+ );
+
+ // Fill the remaining lanes, then ask again: rather than refusing,
+ // the clip overlaps on the first track.
+ editor
+ .apply(Command::AddClipAtFirstFree { media_id: media_id.clone(), start: 0.0 })
+ .expect("adds");
+ editor
+ .apply(Command::AddClipAtFirstFree { media_id: media_id.clone(), start: 0.0 })
+ .expect("adds");
+ let overflow = editor
+ .apply(Command::AddClipAtFirstFree { media_id: media_id.clone(), start: 0.0 })
+ .expect("adds")
+ .created_id
+ .expect("id");
+ assert_eq!(
+ editor.project().active().clip(&overflow).expect("exists").track_id,
+ editor.project().active().tracks[0].id,
+ "a full timeline falls back to the first track, overlap and all"
+ );
+
+ // A clear span later in time finds track one free again.
+ let clear = editor
+ .apply(Command::AddClipAtFirstFree { media_id, start: 20.0 })
+ .expect("adds")
+ .created_id
+ .expect("id");
+ assert_eq!(
+ editor.project().active().clip(&clear).expect("exists").track_id,
+ editor.project().active().tracks[0].id
+ );
+ }
+
+ #[test]
+ fn removing_a_track_takes_its_clips_and_stops_at_the_floor_of_one() {
+ let (mut editor, _, _) = fixture();
+ let track_id = editor.project().active().tracks[0].id.clone();
+ editor.apply(Command::RemoveTrack { track_id: track_id.clone() }).expect("removes");
+ let timeline = editor.project().active();
+ assert_eq!(timeline.tracks.len(), 3);
+ assert!(timeline.clips.is_empty(), "the clip on the removed track went with it");
+
+ // An unknown id is the tolerated no-op, not an error.
+ let outcome = editor.apply(Command::RemoveTrack { track_id }).expect("tolerated");
+ assert!(!outcome.applied);
+
+ while editor.project().active().tracks.len() > 1 {
+ let next = editor.project().active().tracks[0].id.clone();
+ editor.apply(Command::RemoveTrack { track_id: next }).expect("removes");
+ }
+ let last = editor.project().active().tracks[0].id.clone();
+ let refused = editor.apply(Command::RemoveTrack { track_id: last });
+ assert_eq!(refused.unwrap_err().to_string(), "A timeline needs at least one track.");
+ }
+
+ #[test]
+ fn removing_media_sweeps_its_clips_from_every_timeline() {
+ let (mut editor, media_id, _) = fixture();
+ editor.apply(Command::AddTimeline).expect("adds");
+ let track_id = editor.project().active().tracks[0].id.clone();
+ editor
+ .apply(Command::AddClip { media_id: media_id.clone(), track_id, start: 0.0 })
+ .expect("adds");
+
+ editor.apply(Command::RemoveMedia { media_id: media_id.clone() }).expect("removes");
+ assert!(editor.project().media.is_empty());
+ assert!(
+ editor.project().timelines.iter().all(|timeline| timeline.clips.is_empty()),
+ "the inactive timeline's clip is swept too, not left dangling"
+ );
+
+ // Removing what is already gone is a tolerated no-op.
+ let outcome = editor.apply(Command::RemoveMedia { media_id }).expect("tolerated");
+ assert!(!outcome.applied);
+ }
+
+ #[test]
+ fn renames_trim_whitespace_and_refuse_to_blank_a_name() {
+ let (mut editor, _, _) = fixture();
+ let track_id = editor.project().active().tracks[0].id.clone();
+ editor
+ .apply(Command::RenameTrack {
+ track_id: track_id.clone(),
+ name: " Cutaways ".to_owned(),
+ })
+ .expect("renames");
+ assert_eq!(editor.project().active().tracks[0].name, "Cutaways");
+
+ // Whitespace-only would leave the lane unlabelled, so it is ignored.
+ let outcome = editor
+ .apply(Command::RenameTrack { track_id, name: " ".to_owned() })
+ .expect("tolerated");
+ assert!(!outcome.applied);
+ assert_eq!(editor.project().active().tracks[0].name, "Cutaways");
+
+ editor
+ .apply(Command::RenameTimeline {
+ timeline_id: "TL1".to_owned(),
+ name: "\tCut A\n".to_owned(),
+ })
+ .expect("renames");
+ assert_eq!(editor.project().timelines[0].name, "Cut A");
+ let outcome = editor
+ .apply(Command::RenameTimeline { timeline_id: "TL1".to_owned(), name: String::new() })
+ .expect("tolerated");
+ assert!(!outcome.applied);
+ assert_eq!(editor.project().timelines[0].name, "Cut A");
+ }
+
+ #[test]
+ fn track_flags_flip_independently_and_report_no_ops_honestly() {
+ let (mut editor, _, _) = fixture();
+ let track_id = editor.project().active().tracks[0].id.clone();
+ editor
+ .apply(Command::SetTrackFlag {
+ track_id: track_id.clone(),
+ flag: TrackFlag::Visible,
+ value: false,
+ })
+ .expect("sets");
+ editor
+ .apply(Command::SetTrackFlag {
+ track_id: track_id.clone(),
+ flag: TrackFlag::Muted,
+ value: true,
+ })
+ .expect("sets");
+ let track = &editor.project().active().tracks[0];
+ assert!(!track.visible);
+ assert!(track.muted);
+
+ // Setting the value already in place is a no-op, exactly as the old
+ // deep-compare judged it.
+ let outcome = editor
+ .apply(Command::SetTrackFlag { track_id, flag: TrackFlag::Muted, value: true })
+ .expect("tolerated");
+ assert!(!outcome.applied);
+ }
+
+ #[test]
+ fn rotation_wraps_into_the_half_open_degree_range() {
+ // (-180, 180]: a knob dragged through full turns must not carry the
+ // turns with it, and the boundary itself belongs to +180.
+ let (mut editor, _, clip_id) = fixture();
+ let cases = [
+ (361.0, 1.0),
+ (-1.0, -1.0),
+ (720.0, 0.0),
+ (180.0, 180.0),
+ (-180.0, 180.0),
+ (540.0, 180.0),
+ ];
+ for (sent, landed) in cases {
+ editor
+ .apply(Command::SetClipTransform {
+ clip_id: clip_id.clone(),
+ scale: None,
+ offset_x: None,
+ offset_y: None,
+ rotation: Some(sent),
+ })
+ .expect("sets");
+ assert_eq!(
+ editor.project().active().clip(&clip_id).expect("exists").rotation,
+ landed,
+ "{sent} degrees should land at {landed}"
+ );
+ }
+ }
+
+ #[test]
+ fn removing_a_timeline_moves_the_active_tab_to_a_neighbour() {
+ let mut editor = Editor::new();
+ let second = editor.apply(Command::AddTimeline).expect("adds").created_id.expect("id");
+ let third = editor.apply(Command::AddTimeline).expect("adds").created_id.expect("id");
+ assert_eq!(editor.project().active_timeline_id, third);
+
+ // An unknown id is a tolerated no-op while the floor allows it.
+ let outcome = editor
+ .apply(Command::RemoveTimeline { timeline_id: "ghost".to_owned() })
+ .expect("tolerated");
+ assert!(!outcome.applied);
+
+ // Removing the active last tab falls back to the previous one.
+ editor.apply(Command::RemoveTimeline { timeline_id: third }).expect("removes");
+ assert_eq!(editor.project().active_timeline_id, second);
+
+ // Removing an active middle tab prefers the neighbour to its right.
+ let third = editor.apply(Command::AddTimeline).expect("adds").created_id.expect("id");
+ editor
+ .apply(Command::SelectTimeline { timeline_id: second.clone() })
+ .expect("selects");
+ editor.apply(Command::RemoveTimeline { timeline_id: second }).expect("removes");
+ assert_eq!(editor.project().active_timeline_id, third);
+
+ // Removing an inactive tab leaves the selection alone.
+ editor.apply(Command::RemoveTimeline { timeline_id: "TL1".to_owned() }).expect("removes");
+ assert_eq!(editor.project().active_timeline_id, third);
+ }
+
+ #[test]
+ fn fonts_deduplicate_by_path_and_removal_leaves_titles_alone() {
+ let mut editor = Editor::new();
+ editor
+ .apply(Command::AddFont {
+ family: "Inter".to_owned(),
+ path: "/fonts/inter.ttf".to_owned(),
+ })
+ .expect("adds");
+ // Same path again: a re-import must not duplicate the entry.
+ let outcome = editor
+ .apply(Command::AddFont {
+ family: "Inter Again".to_owned(),
+ path: "/fonts/inter.ttf".to_owned(),
+ })
+ .expect("tolerated");
+ assert!(!outcome.applied);
+ assert_eq!(editor.project().fonts.len(), 1);
+
+ let clip_id = editor
+ .apply(Command::AddTextClip {
+ track_id: None,
+ start: 0.0,
+ style: Some(TextStyle { font_family: "Inter".to_owned(), ..TextStyle::default() }),
+ duration: None,
+ offset_y: None,
+ })
+ .expect("adds")
+ .created_id
+ .expect("id");
+
+ editor.apply(Command::RemoveFont { family: "Inter".to_owned() }).expect("removes");
+ assert!(editor.project().fonts.is_empty());
+ let clip = editor.project().active().clip(&clip_id).expect("exists");
+ assert_eq!(
+ clip.text.as_ref().expect("text").font_family,
+ "Inter",
+ "the title keeps the family name so the face can come back"
+ );
+
+ // Removing what is already gone is a tolerated no-op.
+ let outcome =
+ editor.apply(Command::RemoveFont { family: "Inter".to_owned() }).expect("tolerated");
+ assert!(!outcome.applied);
+ }
+
+ #[test]
+ fn every_command_round_trips_through_serde() {
+ // One of each variant. Grow this list with the enum, or a new
+ // command ships without proof its wire shape survives a round trip.
+ let item = match media("/a.mp4", 10.0, true) {
+ Command::AddMedia { item } => item,
+ _ => unreachable!("the helper builds AddMedia"),
+ };
+ let commands = vec![
+ Command::AddMedia { item: item.clone() },
+ Command::RemoveMedia { media_id: "m1".to_owned() },
+ Command::SetMediaPlaceholder { media_id: "m1".to_owned(), placeholder: true },
+ Command::FillSlot { media_id: "m1".to_owned(), item },
+ Command::Batch { commands: vec![Command::AddTrack] },
+ Command::AddClip { media_id: "m1".to_owned(), track_id: "T1".to_owned(), start: 1.0 },
+ Command::AddClipAtFirstFree { media_id: "m1".to_owned(), start: 2.0 },
+ Command::AddTextClip {
+ track_id: Some("T1".to_owned()),
+ start: 0.0,
+ style: Some(TextStyle::default()),
+ duration: Some(2.0),
+ offset_y: Some(0.4),
+ },
+ Command::MoveClips {
+ moves: vec![ClipMove {
+ clip_id: "c1".to_owned(),
+ start: 0.0,
+ track_id: "T2".to_owned(),
+ }],
+ },
+ Command::TrimClip { clip_id: "c1".to_owned(), edge: TrimEdge::End, delta: -0.5 },
+ Command::SplitClips { clip_ids: vec!["c1".to_owned()], time: 3.0 },
+ Command::MergeClips { clip_ids: vec!["c1".to_owned(), "c2".to_owned()] },
+ Command::RemoveClips { clip_ids: vec!["c1".to_owned()] },
+ Command::UpdateClip {
+ clip_id: "c1".to_owned(),
+ patch: ClipPatch {
+ volume: Some(0.5),
+ transition_in: Some(None),
+ ..ClipPatch::default()
+ },
+ },
+ Command::SetClipSpeed { clip_id: "c1".to_owned(), speed: 2.0 },
+ Command::SetClipTransform {
+ clip_id: "c1".to_owned(),
+ scale: Some(1.5),
+ offset_x: None,
+ offset_y: Some(-0.25),
+ rotation: Some(90.0),
+ },
+ Command::DetachAudio { clip_id: "c1".to_owned() },
+ Command::ReattachAudio { clip_id: "c1".to_owned() },
+ Command::AddTrack,
+ Command::RemoveTrack { track_id: "T1".to_owned() },
+ Command::RenameTrack { track_id: "T1".to_owned(), name: "Cutaways".to_owned() },
+ Command::SetTrackFlag {
+ track_id: "T1".to_owned(),
+ flag: TrackFlag::Muted,
+ value: true,
+ },
+ Command::AddTimeline,
+ Command::RemoveTimeline { timeline_id: "TL1".to_owned() },
+ Command::RenameTimeline { timeline_id: "TL1".to_owned(), name: "Cut A".to_owned() },
+ Command::SelectTimeline { timeline_id: "TL1".to_owned() },
+ Command::AddFont { family: "Inter".to_owned(), path: "/fonts/inter.ttf".to_owned() },
+ Command::RemoveFont { family: "Inter".to_owned() },
+ ];
+ for command in commands {
+ let wire = serde_json::to_value(&command).expect("serialises");
+ let back: Command = serde_json::from_value(wire).expect("parses");
+ assert_eq!(back, command);
+ }
+ }
+
+ #[test]
+ fn clips_for_vanished_tracks_or_media_are_dropped_on_load() {
+ // A hand-edited or truncated file must degrade to something
+ // openable: a clip with nowhere to live (or nothing to show) is
+ // dropped, while a text clip - which needs no media - survives.
+ let document = json!({
+ "name": "Damaged", "version": 1,
+ "media": [{ "id": "m1", "path": "/a.mp4", "name": "a.mp4", "kind": "video",
+ "hasAudio": false }],
+ "tracks": [{ "id": "T1", "name": "Track 1", "visible": true, "muted": false }],
+ "clips": [
+ { "id": "c1", "trackId": "ghost", "mediaId": "m1", "kind": "video",
+ "start": 0.0, "duration": 1.0 },
+ { "id": "c2", "trackId": "T1", "mediaId": "ghost", "kind": "video",
+ "start": 0.0, "duration": 1.0 },
+ { "id": "c3", "trackId": "T1", "mediaId": "m1", "kind": "video",
+ "start": 0.0, "duration": 1.0 },
+ { "id": "c4", "trackId": "T1", "kind": "text", "start": 0.0, "duration": 1.0 }
+ ]
+ });
+ let editor = Editor::from_document(&document).expect("loads");
+ let ids: Vec<&str> =
+ editor.project().active().clips.iter().map(|clip| clip.id.as_str()).collect();
+ assert_eq!(ids, ["c3", "c4"]);
+ }
+
+ #[test]
+ fn hand_edited_values_are_clamped_on_load() {
+ // The reader trusts nothing: values that would render invisibly or
+ // fall outside the engine's ranges are pulled back in, not obeyed.
+ let document = json!({
+ "name": "Edited", "version": 1,
+ "media": [{ "id": "m1", "path": "/a.mp4", "name": "a.mp4", "kind": "video",
+ "hasAudio": false }],
+ "tracks": [{ "id": "T1", "name": "Track 1", "visible": true, "muted": false }],
+ "clips": [
+ { "id": "c1", "trackId": "T1", "mediaId": "m1", "kind": "video",
+ "start": -4.0, "duration": -3.0, "sourceStart": -1.0,
+ "volume": -2.0, "opacity": 2.0, "speed": 100.0, "scale": 0.0,
+ "transitionIn": { "id": "cross-fade", "duration": 0.0 } },
+ { "id": "c2", "trackId": "T1", "kind": "text", "start": 0.0, "duration": 1.0,
+ "text": { "content": "Hi", "fontSize": 0.0, "fontWeight": 9999.0,
+ "lineHeight": 0.1, "opacity": 5.0 } }
+ ]
+ });
+ let editor = Editor::from_document(&document).expect("loads");
+ let clip = &editor.project().active().clips[0];
+ assert_eq!(clip.start, 0.0);
+ assert_eq!(clip.duration, 0.01);
+ assert_eq!(clip.source_start, 0.0);
+ assert_eq!(clip.volume, 0.0);
+ assert_eq!(clip.opacity, 1.0);
+ assert_eq!(clip.speed, 16.0);
+ assert_eq!(clip.scale, 0.05);
+ assert_eq!(clip.transition_in.as_ref().expect("kept").duration, 0.1);
+
+ let text = editor.project().active().clips[1].text.as_ref().expect("text");
+ assert_eq!(text.font_size, 0.01, "a zero size would render an invisible title");
+ assert_eq!(text.font_weight, 900.0);
+ assert_eq!(text.line_height, 0.5, "lines cannot collapse onto each other");
+ assert_eq!(text.opacity, 1.0);
+ }
}