The truly free, open-source, local-first, cross-platform CapCut replacement. Scriptable through a JSON-RPC API & MCP.
Rust ffmpegfree-video-editormodel-context-protocolnon-linear-editoroffline-firstopen-source-video-editorself-hostedvideo-editingvideo-editing-automationvideo-editing-softwarevideo-editing-toolsvideo-editorvoice-cloningyoutube-automationyoutube-shorts
fix(timeline): a clip never lands on top of another
Jareerfaa6da969c03
diff --git a/src/crates/concat-project/src/commands/clips.rs b/src/crates/concat-project/src/commands/clips.rsindex 9decd2ba..dd75582b 100644--- a/src/crates/concat-project/src/commands/clips.rs+++ b/src/crates/concat-project/src/commands/clips.rs@@ -29,10 +29,12 @@ pub(super) fn apply(if timeline.track(&track_id).is_none() {return Err(CommandError::TrackGone);}+ // Magnetic, the lane makes room; otherwise the clip takes the+ // nearest gap it fits, never the top of another clip.let start = if ripple {ripple_room_for(timeline, &track_id, start, &media)} else {- start+ timeline.nearest_free_start(&track_id, start, clip_length(&media), &[])};let id = mint.next("c");timeline@@ -49,13 +51,10 @@ pub(super) fn apply(.media_by_id(&media_id).ok_or(CommandError::MediaGone)?.clone();- let duration = match media.kind {- MediaKind::Image => DEFAULT_IMAGE_DURATION,- _ => media.duration.unwrap_or(UNKNOWN_DURATION),- };+ let duration = clip_length(&media);let timeline = project.active_mut();- let track_id =- first_free_track(timeline, start, duration).ok_or(CommandError::NoTracks)?;+ let track_id = first_free_track(timeline, start, duration)+ .unwrap_or_else(|| fresh_track(timeline, mint));let id = mint.next("c");timeline.clips@@ -82,25 +81,14 @@ pub(super) fn apply(let track_id = match track_id {Some(id) if timeline.track(&id).is_some() => id,Some(_) => return Err(CommandError::TrackGone),- None if above => match first_free_track_above(timeline, start, duration) {- Some(id) => id,- None => {- // Every lane above the video is taken: mint one at- // the top for the words to land on.- let id = mint.next("t");- timeline.tracks.push(Track {- id: id.clone(),- visible: true,- muted: false,- extra: Default::default(),- });- id- }- },- None => {- first_free_track(timeline, start, duration).ok_or(CommandError::NoTracks)?- }+ // Every lane above the video is taken: a new one at the top+ // for the words to land on.+ None if above => first_free_track_above(timeline, start, duration)+ .unwrap_or_else(|| fresh_track(timeline, mint)),+ None => first_free_track(timeline, start, duration)+ .unwrap_or_else(|| fresh_track(timeline, mint)),};+ let start = timeline.nearest_free_start(&track_id, start, duration, &[]);let id = mint.next("c");let mut clip = Clip::blank(id.clone(),@@ -135,23 +123,12 @@ pub(super) fn apply(let track_id = match track_id {Some(id) if timeline.track(&id).is_some() => id,Some(_) => return Err(CommandError::TrackGone),- None if above => match first_free_track_above(timeline, start, duration) {- Some(id) => id,- None => {- let id = mint.next("t");- timeline.tracks.push(Track {- id: id.clone(),- visible: true,- muted: false,- extra: Default::default(),- });- id- }- },- None => {- first_free_track(timeline, start, duration).ok_or(CommandError::NoTracks)?- }+ None if above => first_free_track_above(timeline, start, duration)+ .unwrap_or_else(|| fresh_track(timeline, mint)),+ None => first_free_track(timeline, start, duration)+ .unwrap_or_else(|| fresh_track(timeline, mint)),};+ let start = timeline.nearest_free_start(&track_id, start, duration, &[]);let id = mint.next("c");let name = if name.trim().is_empty() {style.kind.id().to_owned()@@ -182,10 +159,10 @@ pub(super) fn apply(let track_id = match track_id {Some(id) if timeline.track(&id).is_some() => id,Some(_) => return Err(CommandError::TrackGone),- None => {- first_free_track(timeline, start, duration).ok_or(CommandError::NoTracks)?- }+ None => first_free_track(timeline, start, duration)+ .unwrap_or_else(|| fresh_track(timeline, mint)),};+ let start = timeline.nearest_free_start(&track_id, start, duration, &[]);let id = mint.next("c");let name = if name.trim().is_empty() {effect_id.clone()@@ -204,18 +181,17 @@ pub(super) fn apply(Command::MoveClips { moves } => {let timeline = project.active_mut();- let track_ids: HashSet<String> = timeline- .tracks- .iter()- .map(|track| track.id.clone())- .collect();+ // Onto another clip is never where a move lands: the group goes+ // to the nearest gap that holds it, and a move whose own clips+ // would cover each other stays where it was.+ let Some(moves) = timeline.resolve_moves(&moves) else {+ return Ok(Outcome::default());+ };let mut applied = false;for wanted in moves {if let Some(clip) = timeline.clip_mut(&wanted.clip_id) {- applied |= assign(&mut clip.start, wanted.start.max(0.0));- if track_ids.contains(&wanted.track_id) {- applied |= assign(&mut clip.track_id, wanted.track_id);- }+ applied |= assign(&mut clip.start, wanted.start);+ applied |= assign(&mut clip.track_id, wanted.track_id);}}Ok(Outcome {@@ -237,12 +213,27 @@ pub(super) fn apply(let track_id = clip.track_id.clone();let anchor = clip.start;let old_end = clip.start + clip.duration;+ // A plain trim stops at the neighbours; a magnetic one moves+ // them instead, so it has the lane's whole length.+ let (floor, ceiling) = if ripple {+ (0.0, f64::INFINITY)+ } else {+ let (before, after) = timeline+ .room_around(&clip_id)+ .unwrap_or((0.0, f64::INFINITY));+ (before, after)+ };+ let Some(clip) = timeline.clip_mut(&clip_id) else {+ return Ok(Outcome::default());+ };// What the trim did, and what the lane behind it does about// it when it is magnetic: `by` is how far the later clips// move, `behind` where "later" begins.let (applied, by, behind) = match edge {TrimEdge::End => {- let duration = (clip.duration + delta).max(MIN_CLIP_DURATION);+ let duration = (clip.duration + delta)+ .min(ceiling - clip.start)+ .max(MIN_CLIP_DURATION);let old = clip.duration;let applied = assign(&mut clip.duration, duration);if applied {@@ -263,7 +254,7 @@ pub(super) fn apply(let start = if ripple {clip.start + shift} else {- (clip.start + shift).max(0.0)+ (clip.start + shift).max(floor)};let moved = start - clip.start;let duration = clip.duration - moved;@@ -702,11 +693,14 @@ fn default_clip(id: String, track_id: String, media: &MediaItem, start: f64) ->MediaKind::Audio => ClipKind::Audio,MediaKind::Image => ClipKind::Image,};- let duration = match media.kind {- MediaKind::Image => DEFAULT_IMAGE_DURATION,- _ => media.duration.unwrap_or(UNKNOWN_DURATION),- };- let mut clip = Clip::blank(id, track_id, kind, media.name.clone(), start, duration);+ let mut clip = Clip::blank(+ id,+ track_id,+ kind,+ media.name.clone(),+ start,+ clip_length(media),+ );clip.media_id = media.id.clone();clip}@@ -717,10 +711,7 @@ fn default_clip(id: String, track_id: String, media: &MediaItem, start: f64) ->/// the new clip slots in and nothing is covered (#129). Returns where the/// new clip lands. A drop with room to spare changes nothing.fn ripple_room_for(timeline: &mut Timeline, track_id: &str, start: f64, media: &MediaItem) -> f64 {- let duration = match media.kind {- MediaKind::Image => DEFAULT_IMAGE_DURATION,- _ => media.duration.unwrap_or(UNKNOWN_DURATION),- };+ let duration = clip_length(media);// Dropped onto a clip: after it, rather than over it or through it.let start = timeline.clips@@ -743,22 +734,38 @@ fn ripple_room_for(timeline: &mut Timeline, track_id: &str, start: f64, media: &start}-/// The lowest track with nothing occupying `[start, start + duration)`,-/// falling back to the bottom track.+/// How long a new clip of `media` is: a still's default hold, or the+/// file's own length.+fn clip_length(media: &MediaItem) -> f64 {+ match media.kind {+ MediaKind::Image => DEFAULT_IMAGE_DURATION,+ _ => media.duration.unwrap_or(UNKNOWN_DURATION),+ }+}++/// The lowest track with nothing occupying `[start, start + duration)`.+/// `None` when every lane is taken there: the caller opens a new one+/// rather than covering a clip.fn first_free_track(timeline: &Timeline, start: f64, duration: f64) -> Option<String> {- let end = start + duration;timeline.tracks.iter()- .find(|track| {- !timeline.clips.iter().any(|clip| {- clip.track_id == track.id && clip.start < end && start < clip.start + clip.duration- })- })- .or(timeline.tracks.first())+ .find(|track| timeline.is_free(&track.id, start, duration, &[])).map(|track| track.id.clone())}+/// A new, empty lane at the top, for a clip with nowhere else to go.+fn fresh_track(timeline: &mut Timeline, mint: &mut IdMint) -> String {+ let id = mint.next("t");+ timeline.tracks.push(Track {+ id: id.clone(),+ visible: true,+ muted: false,+ extra: Default::default(),+ });+ id+}+/// First free lane *above* the highest one occupied over `[start, start +/// duration)`. `None` when every lane above is taken, which is the caller's/// cue to mint a new one at the top.diff --git a/src/crates/concat-project/src/commands/properties.rs b/src/crates/concat-project/src/commands/properties.rsindex d673362c..d24c8756 100644--- a/src/crates/concat-project/src/commands/properties.rs+++ b/src/crates/concat-project/src/commands/properties.rs@@ -96,6 +96,7 @@ pub(super) fn apply(// makes this a speed change rather than a trim.let next = speed.clamp(MIN_SPEED, MAX_SPEED);let source_covered = clip.duration * clip.speed;+ let old_end = clip.start + clip.duration;// Bitwise so no assignment is short-circuited away. A rate set// by hand is a constant rate: the curve goes.let applied = assign(&mut clip.speed, next)@@ -104,6 +105,20 @@ pub(super) fn apply((source_covered / next).max(MIN_CLIP_DURATION),)| assign(&mut clip.speed_curve, None);+ // Slowed down, the clip grows into what follows it: the rest of+ // the lane moves along by the growth, as a freeze frame's does,+ // rather than being covered.+ let (track_id, start, duration) = (clip.track_id.clone(), clip.start, clip.duration);+ let grow = start + duration - old_end;+ if grow > 0.0 && !timeline.is_free(&track_id, start, duration, &[&clip_id]) {+ for other in timeline.clips_where(|other| {+ other.id != clip_id+ && other.track_id == track_id+ && other.start >= old_end - crate::placement::TOUCH+ }) {+ other.start += grow;+ }+ }Ok(Outcome {created_id: None,applied,diff --git a/src/crates/concat-project/src/editor.rs b/src/crates/concat-project/src/editor.rsindex ed9fcb8e..d616f6dc 100644--- a/src/crates/concat-project/src/editor.rs+++ b/src/crates/concat-project/src/editor.rs@@ -158,6 +158,14 @@ impl Editor {&self.project}+ /// The project, writable around the undo stack: for tests that need a+ /// state no command makes any more, such as the stacked clips an older+ /// document can hold.+ #[cfg(test)]+ pub(crate) fn project_mut(&mut self) -> &mut Project {+ &mut self.project+ }+/// Applies one command, recording the state before it for undo.////// A command that fails leaves the project and history untouched, anddiff --git a/src/crates/concat-project/src/lib.rs b/src/crates/concat-project/src/lib.rsindex f0b230d7..a9f879e8 100644--- a/src/crates/concat-project/src/lib.rs+++ b/src/crates/concat-project/src/lib.rs@@ -25,6 +25,7 @@ pub mod commands;pub mod doc;pub mod editor;pub mod model;+pub mod placement;pub mod speed;pub use commands::{Command, CommandError, Outcome, why_not_merge};@@ -299,6 +300,21 @@ mod tests {.collect()}+ /// Clips placed exactly at these starts, on top of whatever is there:+ /// the stacks an older document can hold, which no command makes now.+ fn stacked(editor: &mut Editor, media_id: &str, track_id: &str, starts: &[f64]) -> Vec<String> {+ let ids = lane(editor, media_id, track_id, starts);+ for (id, start) in ids.iter().zip(starts) {+ editor+ .project_mut()+ .active_mut()+ .clip_mut(id)+ .expect("just added")+ .start = *start;+ }+ ids+ }+fn start_of(editor: &Editor, clip_id: &str) -> f64 {editor.project()@@ -308,6 +324,175 @@ mod tests {.start}+ fn move_to(clip_id: &str, start: f64, track_id: &str) -> Command {+ Command::MoveClips {+ moves: vec![ClipMove {+ clip_id: clip_id.to_owned(),+ start,+ track_id: track_id.to_owned(),+ }],+ }+ }++ #[test]+ fn a_move_onto_a_clip_lands_in_the_nearest_gap_beside_it() {+ let (mut editor, media_id, _first) = fixture();+ let video = editor.project().active().tracks[0].id.clone();+ let later = lane(&mut editor, &media_id, &video, &[20.0]);+ // Onto [0, 10) at five: just after it is five away, just before+ // it is before zero, so it lands at ten.+ editor+ .apply(move_to(&later[0], 5.0, &video))+ .expect("moves");+ assert_eq!(start_of(&editor, &later[0]), 10.0);+ }++ #[test]+ fn a_move_into_open_space_lands_where_it_is_dropped() {+ let (mut editor, media_id, _first) = fixture();+ let video = editor.project().active().tracks[0].id.clone();+ let later = lane(&mut editor, &media_id, &video, &[30.0]);+ editor+ .apply(move_to(&later[0], 12.0, &video))+ .expect("moves");+ assert_eq!(start_of(&editor, &later[0]), 12.0);+ }++ #[test]+ fn a_gap_too_small_for_the_clip_is_passed_over() {+ let (mut editor, media_id, _first) = fixture();+ let video = editor.project().active().tracks[0].id.clone();+ // [0, 10) and [15, 25): the five-second gap cannot hold ten.+ let more = lane(&mut editor, &media_id, &video, &[15.0, 40.0]);+ editor+ .apply(move_to(&more[1], 11.0, &video))+ .expect("moves");+ assert_eq!(start_of(&editor, &more[1]), 25.0);+ }++ #[test]+ fn a_move_onto_another_lane_avoids_what_is_there() {+ let (mut editor, media_id, _first) = fixture();+ let tracks = editor.project().active().tracks.clone();+ let above = lane(&mut editor, &media_id, &tracks[1].id, &[0.0]);+ editor+ .apply(move_to(&above[0], 3.0, &tracks[0].id))+ .expect("moves");+ let clip = editor.project().active().clip(&above[0]).expect("there");+ assert_eq!(clip.track_id, tracks[0].id);+ assert_eq!(clip.start, 10.0);+ }++ #[test]+ fn a_group_keeps_its_shape_and_moves_as_one() {+ let (mut editor, media_id, _first) = fixture();+ let tracks = editor.project().active().tracks.clone();+ let a = lane(&mut editor, &media_id, &tracks[1].id, &[20.0]);+ let b = lane(&mut editor, &media_id, &tracks[2].id, &[25.0]);+ // Both down a lane and back by eighteen: `a` would land on [0, 10)+ // at two, so the pair goes on by eight, keeping five between them.+ editor+ .apply(Command::MoveClips {+ moves: vec![+ ClipMove {+ clip_id: a[0].clone(),+ start: 2.0,+ track_id: tracks[0].id.clone(),+ },+ ClipMove {+ clip_id: b[0].clone(),+ start: 7.0,+ track_id: tracks[1].id.clone(),+ },+ ],+ })+ .expect("moves");+ assert_eq!(start_of(&editor, &a[0]), 10.0);+ assert_eq!(start_of(&editor, &b[0]), 15.0);+ }++ #[test]+ fn a_move_whose_clips_would_cover_each_other_stays_put() {+ let (mut editor, media_id, _first) = fixture();+ let tracks = editor.project().active().tracks.clone();+ let a = lane(&mut editor, &media_id, &tracks[1].id, &[0.0]);+ let b = lane(&mut editor, &media_id, &tracks[2].id, &[0.0]);+ let outcome = editor+ .apply(Command::MoveClips {+ moves: vec![+ ClipMove {+ clip_id: a[0].clone(),+ start: 40.0,+ track_id: tracks[3].id.clone(),+ },+ ClipMove {+ clip_id: b[0].clone(),+ start: 40.0,+ track_id: tracks[3].id.clone(),+ },+ ],+ })+ .expect("answers");+ assert!(!outcome.applied);+ let timeline = editor.project().active();+ assert_eq!(timeline.clip(&a[0]).expect("there").track_id, tracks[1].id);+ assert_eq!(timeline.clip(&b[0]).expect("there").track_id, tracks[2].id);+ }++ #[test]+ fn a_clip_added_onto_another_takes_the_nearest_gap() {+ let (mut editor, media_id, _first) = fixture();+ let video = editor.project().active().tracks[0].id.clone();+ let added = lane(&mut editor, &media_id, &video, &[4.0]);+ assert_eq!(start_of(&editor, &added[0]), 10.0);+ }++ #[test]+ fn a_plain_trim_stops_at_the_next_clip() {+ let (mut editor, media_id, first) = fixture();+ let video = editor.project().active().tracks[0].id.clone();+ let next = lane(&mut editor, &media_id, &video, &[12.0]);+ editor+ .apply(trim(&first, TrimEdge::End, 5.0, false))+ .expect("trims");+ let clip = editor.project().active().clip(&first).expect("there");+ assert_eq!(clip.duration, 12.0, "up to the next clip, not past it");+ assert_eq!(start_of(&editor, &next[0]), 12.0);+ }++ #[test]+ fn a_plain_head_trim_stops_at_the_clip_before() {+ let (mut editor, media_id, _first) = fixture();+ let video = editor.project().active().tracks[0].id.clone();+ let next = lane(&mut editor, &media_id, &video, &[12.0]);+ // Twenty seconds of source before the in-point, so the clip before+ // is what stops the head, not the start of the file.+ editor+ .project_mut()+ .active_mut()+ .clip_mut(&next[0])+ .expect("there")+ .source_start = 20.0;+ editor+ .apply(trim(&next[0], TrimEdge::Start, -10.0, false))+ .expect("trims");+ assert_eq!(start_of(&editor, &next[0]), 10.0);+ }++ #[test]+ fn slowing_a_clip_down_moves_what_follows_it() {+ let (mut editor, media_id, first) = fixture();+ let video = editor.project().active().tracks[0].id.clone();+ let next = lane(&mut editor, &media_id, &video, &[10.0]);+ editor+ .apply(Command::SetClipSpeed {+ clip_id: first,+ speed: 0.5,+ })+ .expect("retimes");+ assert_eq!(start_of(&editor, &next[0]), 20.0);+ }+// ── ripple delete: https://github.com/jub0t/Concat/issues/106 ──#[test]@@ -381,7 +566,7 @@ mod tests {// and a survivor at twenty. Their union is fifteen, so it lands at// five; their sum is twenty, which would send it to zero. Away// from zero on purpose: the floor there would hide the difference.- let more = lane(&mut editor, &media_id, &video, &[5.0, 20.0]);+ let more = stacked(&mut editor, &media_id, &video, &[5.0, 20.0]);editor.apply(Command::RemoveClips {clip_ids: vec![first, more[0].clone()],@@ -399,7 +584,7 @@ mod tests {// at fourteen: the survivor moves by the four seconds of span in// front of it, to ten, not by the whole ten, which would put it at// four - in front of where the doomed clip began.- let more = lane(&mut editor, &media_id, &video, &[10.0, 14.0]);+ let more = stacked(&mut editor, &media_id, &video, &[10.0, 14.0]);editor.apply(Command::RemoveClips {clip_ids: vec![more[0].clone()],@@ -414,7 +599,7 @@ mod tests {fn ripple_delete_leaves_a_clip_stacked_at_the_same_start_alone() {let (mut editor, media_id, first) = fixture();let video = editor.project().active().tracks[0].id.clone();- let twin = lane(&mut editor, &media_id, &video, &[0.0]);+ let twin = stacked(&mut editor, &media_id, &video, &[0.0]);editor.apply(Command::RemoveClips {clip_ids: vec![first],@@ -653,7 +838,7 @@ mod tests {let video = editor.project().active().tracks[0].id.clone();// A clip behind the trimmed one, and one stacked before its tail// on the same lane: a tail trim is about what is behind the tail.- let more = lane(&mut editor, &media_id, &video, &[10.0, 3.0]);+ let more = stacked(&mut editor, &media_id, &video, &[10.0, 3.0]);editor.apply(trim(&first, TrimEdge::End, -2.0, true)).expect("shortens");@@ -3112,7 +3297,7 @@ mod tests {}#[test]- fn add_at_first_free_takes_the_lowest_empty_lane_or_the_bottom_one() {+ fn add_at_first_free_takes_the_lowest_empty_lane_or_opens_one() {let (mut editor, media_id, _) = fixture();// Track one is occupied for [0, 10), so the same span lands on two.let second = editor@@ -3133,8 +3318,8 @@ mod tests {editor.project().active().tracks[1].id);- // Fill the remaining lanes, then ask again: rather than refusing,- // the clip overlaps on the first track.+ // Fill the remaining lanes, then ask again: rather than covering a+ // clip, the new one gets a lane of its own at the top.editor.apply(Command::AddClipAtFirstFree {media_id: media_id.clone(),@@ -3155,15 +3340,12 @@ mod tests {.expect("adds").created_id.expect("id");+ let timeline = editor.project().active();+ assert_eq!(timeline.tracks.len(), 5, "a fifth lane was opened");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"+ timeline.clip(&overflow).expect("exists").track_id,+ timeline.tracks[4].id,+ "a full timeline opens a lane rather than covering a clip");// A clear span later in time finds track one free again.diff --git a/src/crates/concat-project/src/placement.rs b/src/crates/concat-project/src/placement.rsnew file mode 100644index 00000000..30c1d18e--- /dev/null+++ b/src/crates/concat-project/src/placement.rs@@ -0,0 +1,174 @@+// SPDX-License-Identifier: AGPL-3.0-or-later+// SPDX-FileCopyrightText: 2026 Jareer and Concat contributors++//! Where a clip may go: no clip ever covers another on its lane.+//!+//! Lanes exist so two pieces of media never share a span of one lane. A+//! clip can sit beside another, between two, or anywhere a lane is empty;+//! it never lands on top of one. Every command that places, moves or+//! lengthens a clip asks these, and so does the window's drag, so what the+//! drag shows is what the drop does.++use std::collections::HashSet;++use crate::commands::ClipMove;+use crate::model::Timeline;++/// How far two clips may run into each other and still count as touching:+/// float seconds that should meet exactly sometimes miss by a hair.+pub const TOUCH: f64 = 1e-6;++/// Whether `[a_start, a_end)` and `[b_start, b_end)` share more than an edge.+fn covers(a_start: f64, a_end: f64, b_start: f64, b_end: f64) -> bool {+ a_start < b_end - TOUCH && b_start < a_end - TOUCH+}++impl Timeline {+ /// Whether `[start, start + duration)` on `track_id` is clear of every+ /// clip but the ones in `ignore`.+ pub fn is_free(&self, track_id: &str, start: f64, duration: f64, ignore: &[&str]) -> bool {+ let end = start + duration;+ !self.clips.iter().any(|clip| {+ clip.track_id == track_id+ && !ignore.contains(&clip.id.as_str())+ && covers(start, end, clip.start, clip.start + clip.duration)+ })+ }++ /// The start nearest `start` where `duration` fits on `track_id`+ /// without covering anything but `ignore`: `start` itself when it is+ /// clear, otherwise the closest gap before or after, never before zero.+ /// There is always one, after the lane's last clip.+ pub fn nearest_free_start(+ &self,+ track_id: &str,+ start: f64,+ duration: f64,+ ignore: &[&str],+ ) -> f64 {+ let start = start.max(0.0);+ let others = self+ .clips+ .iter()+ .filter(|clip| clip.track_id == track_id && !ignore.contains(&clip.id.as_str()));+ // Every place a gap can begin: the wanted start, the lane's start,+ // just after a clip, or just before one.+ let mut candidates = vec![start, 0.0];+ for clip in others {+ candidates.push(clip.start + clip.duration);+ candidates.push(clip.start - duration);+ }+ candidates+ .into_iter()+ .filter(|&at| at >= 0.0 && self.is_free(track_id, at, duration, ignore))+ .min_by(|a, b| (a - start).abs().total_cmp(&(b - start).abs()))+ .unwrap_or(start)+ }++ /// `moves` as they may land: every clip shifted in time by the one+ /// amount nearest zero that leaves none of them covering a clip that+ /// stays put, so a group keeps its shape and lands in the nearest gap+ /// that holds all of it. An unknown clip is dropped, and an unknown+ /// track leaves its clip on the lane it is on. None when the moved+ /// clips would cover each other, which no shift in time can fix.+ pub fn resolve_moves(&self, moves: &[ClipMove]) -> Option<Vec<ClipMove>> {+ let wanted: Vec<(ClipMove, f64)> = moves+ .iter()+ .filter_map(|wanted| {+ let clip = self.clip(&wanted.clip_id)?;+ let track_id = if self.track(&wanted.track_id).is_some() {+ wanted.track_id.clone()+ } else {+ clip.track_id.clone()+ };+ Some((+ ClipMove {+ clip_id: wanted.clip_id.clone(),+ start: wanted.start.max(0.0),+ track_id,+ },+ clip.duration,+ ))+ })+ .collect();+ if wanted.is_empty() {+ return Some(Vec::new());+ }+ for (i, (a, a_len)) in wanted.iter().enumerate() {+ for (b, b_len) in &wanted[i + 1..] {+ if a.track_id == b.track_id+ && covers(a.start, a.start + a_len, b.start, b.start + b_len)+ {+ return None;+ }+ }+ }++ let moving: HashSet<&str> = wanted.iter().map(|(m, _)| m.clip_id.as_str()).collect();+ let staying: Vec<_> = self+ .clips+ .iter()+ .filter(|clip| !moving.contains(clip.id.as_str()))+ .collect();+ let earliest = wanted+ .iter()+ .map(|(m, _)| m.start)+ .fold(f64::INFINITY, f64::min);+ let fits = |shift: f64| {+ earliest + shift >= -TOUCH+ && wanted.iter().all(|(m, len)| {+ let start = m.start + shift;+ !staying.iter().any(|clip| {+ clip.track_id == m.track_id+ && covers(start, start + len, clip.start, clip.start + clip.duration)+ })+ })+ };+ // Every shift that butts one moved clip against one that stays,+ // either side, plus none and the one that lands the group at zero.+ let mut shifts = vec![0.0, -earliest];+ for (m, len) in &wanted {+ for clip in staying.iter().filter(|clip| clip.track_id == m.track_id) {+ shifts.push(clip.start + clip.duration - m.start);+ shifts.push(clip.start - len - m.start);+ }+ }+ let shift = shifts+ .into_iter()+ .filter(|&shift| fits(shift))+ .min_by(|a, b| a.abs().total_cmp(&b.abs()))?;+ Some(+ wanted+ .into_iter()+ .map(|(m, _)| ClipMove {+ start: (m.start + shift).max(0.0),+ ..m+ })+ .collect(),+ )+ }++ /// The gap a clip sits in on its lane: where the clip before it ends+ /// (zero when there is none) and where the clip after it starts+ /// (infinity when there is none). A trim stays inside it.+ pub fn room_around(&self, clip_id: &str) -> Option<(f64, f64)> {+ let clip = self.clip(clip_id)?;+ let end = clip.start + clip.duration;+ let neighbours = self+ .clips+ .iter()+ .filter(|other| other.track_id == clip.track_id && other.id != clip.id);+ let mut before = 0.0_f64;+ let mut after = f64::INFINITY;+ for other in neighbours {+ let other_end = other.start + other.duration;+ if other_end <= clip.start + TOUCH {+ before = before.max(other_end);+ }+ if other.start >= end - TOUCH {+ after = after.min(other.start);+ }+ }+ Some((before, after))+ }+}diff --git a/src/crates/concat/src/studio.rs b/src/crates/concat/src/studio.rsindex 6959f294..764e9a39 100644--- a/src/crates/concat/src/studio.rs+++ b/src/crates/concat/src/studio.rs@@ -4174,23 +4174,45 @@ impl Studio {let shift = snapped - anchor.start;let rows = nearest_row(lanes, row_top(lanes, anchor.row) + pixels) - anchor.row;let count = self.timeline().tracks.len() as i32;- let moves: Vec<(String, f32, Option<String>)> = origins+ let moves: Vec<ClipMove> = origins.iter()- .map(|origin| {+ .filter_map(|origin| {let row = (origin.row + rows).clamp(0, count - 1);- let onto = self+ let track_id = self.row_track(row).filter(|track| !self.locked(&track.id))- .map(|track| track.id.clone());- (origin.clip.clone(), (origin.start + shift).max(0.0), onto)+ .map(|track| track.id.clone())+ .or_else(|| {+ self.clip(&origin.clip).map(|clip| clip.track_id.clone())+ })?;+ Some(ClipMove {+ clip_id: origin.clip.clone(),+ start: f64::from((origin.start + shift).max(0.0)),+ track_id,+ })}).collect();- for (id, start, track) in moves {- if let Some(clip) = self.echo_clip_mut(&id) {- clip.start = f64::from(start);- if let Some(track) = track {- clip.track_id = track;- }+ // The drop's own rule, asked of the timeline as it was before+ // the drag: the echo shows where the clips will land, in the+ // nearest gap rather than on top of a clip, or back where+ // they started when they would cover each other.+ let landed = self.timeline().resolve_moves(&moves).unwrap_or_else(|| {+ origins+ .iter()+ .filter_map(|origin| {+ let clip = self.clip(&origin.clip)?;+ Some(ClipMove {+ clip_id: clip.id.clone(),+ start: clip.start,+ track_id: clip.track_id.clone(),+ })+ })+ .collect()+ });+ for wanted in landed {+ if let Some(clip) = self.echo_clip_mut(&wanted.clip_id) {+ clip.start = wanted.start;+ clip.track_id = wanted.track_id;}}}@@ -4205,12 +4227,28 @@ impl Studio {let (start, duration, source_start) = (*start, *duration, *source_start);let threshold = 8.0 * self.lanes.seconds_per_pixel;let speed = self.clip(&id).map_or(1.0, |clip| clip.speed as f32);+ // A plain trim stops at the neighbours, as the command will;+ // a magnetic one moves them, so the lane is all its room.+ let (floor, ceiling) = if self.prefs.magnetic {+ (0.0, f32::INFINITY)+ } else {+ self.timeline()+ .room_around(&id)+ .map_or((0.0, f32::INFINITY), |(before, after)| {+ (before as f32, after as f32)+ })+ };if edge == Edge::Start {// The head cannot pass the tail, and cannot pull material// out of a file that has none before the in-point.let wanted = self.snapped(start + seconds, threshold, &id);let limit = start + duration - MIN_DURATION;- let at = wanted.clamp((start - source_start / speed.max(0.01)).max(0.0), limit);+ let at = wanted.clamp(+ (start - source_start / speed.max(0.01))+ .max(floor)+ .min(limit),+ limit,+ );let delta = at - start;if let Some(clip) = self.echo_clip_mut(&id) {clip.start = f64::from(at);@@ -4223,7 +4261,7 @@ impl Studio {}} else {let wanted = self.snapped(start + duration + seconds, threshold, &id);- let at = wanted.max(start + MIN_DURATION);+ let at = wanted.min(ceiling).max(start + MIN_DURATION);if let Some(clip) = self.echo_clip_mut(&id) {clip.duration = f64::from(at - start);}