diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index 3462794..3986046 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -118,6 +118,9 @@ actions! { /// ctrl-click that builds a selection by hand, for the times everything /// wants selecting at once. SelectAll, + /// Bare escape with nothing else claiming it: empties a multi-clip + /// selection without touching picks, cards or fullscreen. + Deselect, Delete, Lift, Color, @@ -262,6 +265,7 @@ impl ActionId { ActionId::SelectNext => "Select the next clip in the lane", ActionId::SelectPrev => "Select the previous clip in the lane", ActionId::SelectAll => "Select everything (every clip and caption)", + ActionId::Deselect => "Clear the selection", ActionId::Delete => "Delete", ActionId::Lift => "Lift (leave a gap)", ActionId::Color => "Colour…", @@ -342,6 +346,7 @@ impl ActionId { ActionId::SelectNext => "select-next", ActionId::SelectPrev => "select-prev", ActionId::SelectAll => "select-all", + ActionId::Deselect => "deselect", ActionId::Delete => "delete", ActionId::Lift => "lift", ActionId::Color => "color", @@ -421,6 +426,7 @@ impl ActionId { | ActionId::SelectNext | ActionId::SelectPrev | ActionId::SelectAll + | ActionId::Deselect | ActionId::Delete | ActionId::Lift | ActionId::Color @@ -1067,6 +1073,10 @@ impl Keymap { // below had to move off ctrl+a: a stroke that universal was // never really the removal's to keep. b(ActionId::SelectAll, "a", true), + // Bare escape, last in the precedence chain behind every card, + // search and fullscreen close (render.rs) -- just empties the + // selection when nothing else claims the key. + b(ActionId::Deselect, "escape", false), b(ActionId::Delete, "x", false), b(ActionId::Delete, "delete", false), b(ActionId::Lift, "l", false), @@ -1519,7 +1529,7 @@ mod tests { #[test] fn every_default_stroke_reaches_its_action() { let k = Keymap::defaults(); - assert_eq!(k.entries().len(), 75); + assert_eq!(k.entries().len(), 76); // The cut odometer: bare walks one, `<`/`>` (what shift+,/shift+. // actually type) strides ten. assert_eq!(k.lookup(".", false), Some(ActionId::WalkCutNext)); @@ -1603,9 +1613,9 @@ mod tests { assert_eq!(k.lookup("=", false), Some(ActionId::VolumeUp)); assert_eq!(k.lookup("-", false), Some(ActionId::VolumeDown)); assert_eq!(k.lookup("+", false), None); - // The chord, and *only* the chord: bare escape reaches no action at all. + // The chord cancels an export; bare escape falls through to Deselect. assert_eq!(k.lookup("escape", true), Some(ActionId::CancelExport)); - assert_eq!(k.lookup("escape", false), None); + assert_eq!(k.lookup("escape", false), Some(ActionId::Deselect)); // The modifier is half the chord: ctrl+e is not e. assert_eq!(k.lookup("e", true), None); assert_eq!(k.lookup("space", true), None); diff --git a/crates/app/src/layout.rs b/crates/app/src/layout.rs index c414781..fc72785 100644 --- a/crates/app/src/layout.rs +++ b/crates/app/src/layout.rs @@ -398,12 +398,19 @@ pub(crate) enum Split { } impl Split { - /// The two persisted seams -- library/inspector/timeline stay - /// unpersisted, out of this diff's scope, same as before it. Read by - /// [`load_stance_splits`] and [`save_stance_splits`] together so the - /// two can never learn a different set of keys from each other, the - /// gap a sixth region would otherwise fall through silently. - const PERSISTED: [Split; 2] = [Split::Dock, Split::Bench]; + /// Every seam that survives a restart -- all five regions, the file + /// itself the only store (view state stays out of `.edith`, the + /// settled convention). Read by [`load_stance_splits`] and + /// [`save_stance_splits`] together so the set can never learn a + /// different set of keys from each other, the gap a sixth region + /// would otherwise fall through silently. + pub(crate) const PERSISTED: [Split; 5] = [ + Split::Library, + Split::Inspector, + Split::Timeline, + Split::Dock, + Split::Bench, + ]; fn key(self) -> &'static str { match self { @@ -518,23 +525,30 @@ impl Splits { } } -/// Where the darkroom's own two dragged sizes live -- dock and bench, the -/// only pair with a hand on them so far. Same small, silent round trip as -/// [`crate::ui::dock_stance`]'s tab pick: unreadable or absent leaves both +/// Where every seam's dragged size lives. Same small, silent round trip as +/// [`crate::ui::dock_stance`]'s tab pick: unreadable or absent leaves a seam /// `None`, which [`split_size`] already reads as "give it the window's own /// share". pub(crate) fn stance_splits_config_path() -> std::path::PathBuf { crate::keymap::Keymap::config_path().with_file_name("stance-splits") } -pub(crate) fn load_stance_splits() -> Splits { - load_stance_splits_from(&stance_splits_config_path()) +pub(crate) fn load_stance_splits(window: Size) -> Splits { + load_stance_splits_from(&stance_splits_config_path(), window) } /// One `split=pixels` line per touched seam, read from `path` -- factored out /// of [`load_stance_splits`] so a test can round-trip a scratch file instead -/// of the real config. -pub(crate) fn load_stance_splits_from(path: &std::path::Path) -> Splits { +/// of the real config. `window` is the size the layout is about to be drawn +/// at -- a file written by a wider or taller window can hold a seam past +/// this one's own ceiling, so each value is clamped to it here, before it +/// ever reaches [`Splits`]. [`split_size`] still re-clamps every frame on +/// top of this, but that clamp needs a lane count and a scroll state +/// nothing here has yet; this one runs on the three bounds that do not -- +/// [`SIDE_MAX_FRAC`], [`TIMELINE_MAX_SHARE`] and [`BENCH_MIN_H`] -- so a +/// value this open never reaches even the first frame. +pub(crate) fn load_stance_splits_from(path: &std::path::Path, window: Size) -> Splits { + let (w, h) = (f32::from(window.width), f32::from(window.height)); let mut splits = Splits::default(); if let Ok(text) = std::fs::read_to_string(path) { for line in text.lines() { @@ -547,15 +561,19 @@ pub(crate) fn load_stance_splits_from(path: &std::path::Path) -> Splits { let Some(split) = Split::PERSISTED.into_iter().find(|s| s.key() == key) else { continue; }; + let px = match split { + Split::Library | Split::Inspector | Split::Dock => px.min(w * SIDE_MAX_FRAC), + Split::Timeline => px.min(h * TIMELINE_MAX_SHARE), + Split::Bench => px.max(BENCH_MIN_H), + }; splits.set(split, px); } } splits } -/// Writes the sizes a hand has actually dragged -- the legacy three stay -/// unpersisted, as they already were before this diff (out of its scope). -/// Walks [`Split::PERSISTED`] rather than a hand-written `if let` per field, +/// Writes the sizes a hand has actually dragged, one line per seam a hand +/// has touched. Walks [`Split::PERSISTED`] rather than a hand-written `if let` per field, /// so a region added there needs no second, separately-maintained list here. pub(crate) fn save_stance_splits(splits: &Splits) { save_stance_splits_to(splits, &stance_splits_config_path()); diff --git a/crates/app/src/library_meta.rs b/crates/app/src/library_meta.rs index 4ffa497..e08cd8b 100644 --- a/crates/app/src/library_meta.rs +++ b/crates/app/src/library_meta.rs @@ -9,19 +9,26 @@ use crate::*; /// **a different file** -- the next one along -- over the range it was copied /// from. /// -/// The clip's own file gone means there is nothing to paste: `None`, and the -/// next paste says the clipboard is empty rather than putting some other take -/// down. Every index past it moves down by one, exactly as the lanes' clips do. -pub(crate) fn clipboard_after_remove(clip: Option, removed: usize) -> Option { - let mut clip = clip?; - match clip.source.cmp(&removed) { - std::cmp::Ordering::Equal => None, - std::cmp::Ordering::Greater => { - clip.source -= 1; - Some(clip) - } - std::cmp::Ordering::Less => Some(clip), - } +/// An entry whose own file is gone drops out of the clipboard rather than +/// pasting some other take down in its place; a set with even one such +/// member is trimmed, not emptied whole, the way a lane keeps every clip a +/// removal did not touch. Every index past `removed` moves down by one, +/// exactly as the lanes' clips do. +pub(crate) fn clipboard_after_remove( + clipboard: Vec<(Lane, Clip)>, + removed: usize, +) -> Vec<(Lane, Clip)> { + clipboard + .into_iter() + .filter_map(|(lane, mut clip)| match clip.source.cmp(&removed) { + std::cmp::Ordering::Equal => None, + std::cmp::Ordering::Greater => { + clip.source -= 1; + Some((lane, clip)) + } + std::cmp::Ordering::Less => Some((lane, clip)), + }) + .collect() } /// One library row: a file and one of its audio streams. Plain data, planned diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 7169851..975f35c 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -298,9 +298,13 @@ struct Player { /// reason (a VA-API init), and kept for the life of the process because the /// answer cannot change while we run. `None` is "not asked yet". hw_caps: Option, - /// The copied clip. Frame ranges only, so it survives the clip it was taken - /// from being deleted -- and it outlives the selection. - clipboard: Option, + /// The copied clip, or clips: frame ranges and the lane each was on, in + /// click order, so it survives the clip (or clips) it was taken from + /// being deleted -- and it outlives the selection. One entry for a plain + /// Copy, the whole ctrl-click set for one made over a selection; either + /// way [`Player::paste`] drops the set at the playhead keeping the gaps + /// and lanes between its members intact. + clipboard: Vec<(Lane, Clip)>, /// A drag that started on the ruler. Moves anywhere in the window scrub /// while it is set; the release commits the exact position. scrubbing: bool, @@ -385,8 +389,11 @@ struct Player { /// over no lane: the shadow every proper editor draws under a drag. Set by /// the lane the pointer is actually over -- that is the one question the /// line above does not answer -- and drawn only while a drag is live, for - /// [`Player::snap_cue`]'s reason. - ghost: Option, + /// [`Player::snap_cue`]'s reason. More than one entry only while a + /// set-drag ([`Player::move_clip`]'s `set_move`) is carrying more than + /// the clip under the hand: every other pick draws its own shadow too, at + /// the same delta the anchor's is landing at ([`Player::preview_ghost`]). + ghost: Vec, /// The slot a track header being dragged is about to drop into, or `None` /// while the pointer is over no lane: the line drawn between two headers, /// for the reason [`Player::ghost`] draws a shadow -- where a gesture lands @@ -935,9 +942,9 @@ fn main() { decoders: HashMap::new(), export_seat: None, hw_caps: None, - clipboard: None, + clipboard: Vec::new(), scrubbing: false, - splits: load_stance_splits(), + splits: load_stance_splits(bounds.size), split_drag: None, trim: None, fade_drag: None, @@ -948,7 +955,7 @@ fn main() { sub_folded: HashSet::new(), sub_lane: None, snap_cue: None, - ghost: None, + ghost: Vec::new(), lane_drop: None, last_scrub: Instant::now(), last_target: 0, diff --git a/crates/app/src/player/actions.rs b/crates/app/src/player/actions.rs index 3915821..5dd2924 100644 --- a/crates/app/src/player/actions.rs +++ b/crates/app/src/player/actions.rs @@ -98,6 +98,12 @@ impl Player { ActionId::SelectNext => self.select_step(true, cx), ActionId::SelectPrev => self.select_step(false, cx), ActionId::SelectAll => self.select_all(cx), + // Last in escape's precedence chain (render.rs): nothing else + // claimed the key, so it just empties the selection. + ActionId::Deselect => { + self.selected = Selection::new(); + cx.notify(); + } ActionId::Delete => self.delete_selected(cx), ActionId::Lift => self.lift_selected(cx), ActionId::Color => self.open_color(cx), @@ -241,7 +247,7 @@ impl Player { pub(crate) fn toggle_snap(&mut self, cx: &mut Context) { self.snap = !self.snap; self.snap_cue = None; - self.ghost = None; + self.ghost.clear(); self.notify_user(match self.snap { true => "SNAP ON — drags land on clip edges, the playhead and the start".into(), false => "SNAP OFF — drags land exactly where the hand leaves them".into(), @@ -364,7 +370,7 @@ impl Player { }), playhead: frame_at(session.now(), self.fps), timeline: true, - clipboard: self.clipboard.is_some(), + clipboard: !self.clipboard.is_empty(), subtitles: !session.subtitles().is_empty(), playable: !nothing_to_play(self.active_session()), exporting: self.exporting().is_some(), diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index 1061652..1652dd5 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -164,7 +164,7 @@ impl Player { // A copied clip names its source by *index*, and every index // past the one that went has just moved down: without this the // next paste puts some other file on the timeline. - self.clipboard = clipboard_after_remove(self.clipboard, idx); + self.clipboard = clipboard_after_remove(std::mem::take(&mut self.clipboard), idx); self.reset_after_reseek(); // The last row leaves a session naming no file: nothing to // play, nothing to save and nothing to show, which is the empty @@ -305,7 +305,7 @@ impl Player { self.image = None; // The drawn cue with it, and its tile for the same reason as above. self.sub_image = None; - self.clipboard = None; + self.clipboard.clear(); self.selected.clear(); self.selected_asset = None; // The subtitle rows go with the timeline they were on, and so does the @@ -1486,7 +1486,7 @@ impl Player { self.name = file_name(path).into(); // A copied clip names its source by index, which means a // different file -- or none -- in another project. - self.clipboard = None; + self.clipboard.clear(); self.selected.clear(); // A menu can be up while a project is dropped on the window -- // the scrim swallows clicks, never a drop -- and its index diff --git a/crates/app/src/player/timeline_edit.rs b/crates/app/src/player/timeline_edit.rs index 61693d9..99b20a0 100644 --- a/crates/app/src/player/timeline_edit.rs +++ b/crates/app/src/player/timeline_edit.rs @@ -12,7 +12,7 @@ use crate::*; /// from a live `MouseExitEvent` still cannot be, and is proven by driving /// instead. pub(crate) fn split_drag_owes_save(split: Option) -> bool { - matches!(split, Some(Split::Dock) | Some(Split::Bench)) + split.is_some_and(|split| Split::PERSISTED.contains(&split)) } impl Player { @@ -250,18 +250,26 @@ impl Player { cx.notify(); } - /// Copies the selected clip. Nothing on screen changes, so no notify. + /// Copies the selection: one entry for a plain click, the whole + /// ctrl-click set -- every pick, its own lane and its own frames -- for + /// one made over more than a clip. Out of the lane each was clicked in: + /// the audio half of a group is a different clip from the video one, and + /// copying the wrong lane's frames is a paste of the wrong thing. Nothing + /// on screen changes, so no notify. Empty rather than touched at all for + /// a selection naming nothing any more, so a stale Copy leaves the + /// clipboard exactly as a stale Paste would find it. pub(crate) fn copy_selected(&mut self) { - let session = self.session.as_ref(); - // Out of the lane it was clicked in: the audio half of a group is a - // different clip from the video one, and copying the wrong lane's - // frames is a paste of the wrong thing. - if let Some(clip) = self + let Some(session) = self.session.as_ref() else { + return; + }; + let picks: Vec<(Lane, Clip)> = self .selected - .anchor() - .and_then(|(lane, idx)| session?.lane_clips(lane).get(idx).copied()) - { - self.clipboard = Some(clip); + .picks() + .iter() + .filter_map(|&(lane, idx)| Some((lane, session.lane_clips(lane).get(idx).copied()?))) + .collect(); + if !picks.is_empty() { + self.clipboard = picks; } } @@ -288,17 +296,37 @@ impl Player { (picks, links) } - /// Drops the copied clip in at the playhead. The engine reseeks itself, so - /// like a delete this owes the flag reset -- and the selection, whose index - /// the insert has just moved. + /// Drops the copied clip -- or the whole copied set -- in at the + /// playhead. A single clipboard entry takes the door it always has + /// ([`PlaybackSession::paste_at`]): across `V1`/`A1`, splitting whatever + /// it lands inside of and rippling the room open, byte-identical to + /// before a set could be copied at all. More than one takes + /// [`PlaybackSession::paste_set_at`] instead: every member lands on the + /// lane it was copied off, at the same distance from the others it had on + /// the bed it was copied from, refused whole rather than opening room -- + /// see [`Project::paste_set`] for why a set-paste cannot ripple. The + /// engine reseeks itself either way, so like a delete this owes the flag + /// reset -- and the selection, whose index the insert has just moved. pub(crate) fn paste(&mut self, cx: &mut Context) { - let pasted = match (&mut self.session, self.clipboard) { - (Some(session), Some(clip)) => session.paste_at(session.now(), clip), + let pasted = match (&mut self.session, self.clipboard.as_slice()) { + (Some(session), [(_, clip)]) => session.paste_at(session.now(), *clip), + (Some(session), items) if !items.is_empty() => { + session.paste_set_at(session.now(), items) + } _ => false, }; if pasted { self.selected.clear(); self.reset_after_reseek(); + } else if self.clipboard.len() > 1 { + // The set-paste's own refusal, worded like a set-drag's + // ([`Player::move_clip`]) -- a single-clip paste stays silent on + // failure exactly as it always has. + self.notify_user( + "NOT PASTED — another clip already covers where one of the copied clips would \ + land" + .into(), + ); } cx.notify(); } @@ -310,6 +338,13 @@ impl Player { /// nothing is said about it. The engine reseeks, so all this owes is the /// flag reset -- and the selection, whose index was that lane's own and now /// names a different clip there. + /// + /// A dragged clip that is *itself* one of the selection's picks carries the + /// whole selection with it: every other pick moves the same frame delta, + /// all-or-nothing ([`PlaybackSession::move_selection_to`]), and the picks + /// survive the move -- their indices remapped rather than cleared, since a + /// pick that travels still names the clip it named before. A clip dragged + /// from outside the selection moves alone, exactly as it always has. pub(crate) fn move_clip( &mut self, from: Lane, @@ -330,10 +365,23 @@ impl Player { ) else { return; }; - let moved = self - .session - .as_mut() - .is_some_and(|session| session.move_clip_to(from, idx, to, start)); + let set_move = self.selected.contains((from, idx)) && self.selected.len() > 1; + let picks: Vec<(Lane, usize)> = self.selected.picks().to_vec(); + // Every pick's own start, read before the move touches anything -- the + // only way to find a pick again afterwards, since a lane change or an + // insert can move the index it was named by. + let pre_starts: Vec> = picks + .iter() + .map(|&(lane, i)| { + self.session + .as_ref() + .and_then(|session| session.lane_clips(lane).get(i).map(|c| c.start)) + }) + .collect(); + let moved = self.session.as_mut().is_some_and(|session| match set_move { + true => session.move_selection_to(&picks, from, idx, to, start), + false => session.move_clip_to(from, idx, to, start), + }); let (kind, lanes) = match from.kind { LaneKind::Video => ("picture", "video"), LaneKind::Audio => ("sound", "audio"), @@ -343,7 +391,18 @@ impl Player { }; match moved { true => { - self.selected.clear(); + // Every pick named a `(lane, ...)` by index into that lane's + // clips, sorted by start -- exactly what an insert or a lane + // change reorders. Re-read by the frame each pick's clip now + // starts at (recorded before the move moved anything), so the + // selection survives naming the clips it named, not the slots + // they used to sit in. + if set_move { + self.selected = + self.remap_selection(&picks, &pre_starts, from, idx, to, was, start); + } else { + self.selected.clear(); + } self.reset_after_reseek(); } // The three ways a drag is refused, told apart by what the @@ -360,6 +419,15 @@ impl Player { // Picked up and put back down where it was: a click, and a click // says nothing. false if from == to && start == was => {} + false if set_move => self.notify_user( + format!( + "NOT MOVED — {} clips selected, and another clip already covers where one of \ + them would land on {}", + picks.len(), + to.label() + ) + .into(), + ), false => self.notify_user( format!( "NOT MOVED — another clip already covers those frames on {}", @@ -371,6 +439,50 @@ impl Player { cx.notify(); } + /// What a selection's picks are called after a set-move that shifted every + /// one of them by `landed - was` timeline frames (the delta the dragged + /// clip's own head travelled, which every pick travelled too -- see + /// [`Project::move_selection`]): the clip a pick named is found again by + /// where it now starts, on the lane it stays on (or `to`, for the one + /// that changed lane), rather than by the index it had, which a lane + /// change or an insert can have moved. A pick whose clip cannot be found + /// there any more (a bad index handed in) is dropped rather than guessed + /// at. + fn remap_selection( + &self, + picks: &[(Lane, usize)], + pre_starts: &[Option], + from: Lane, + dragged: usize, + to: Lane, + was: u32, + landed: u32, + ) -> Selection { + let mut out = Selection::new(); + let Some(session) = self.session.as_ref() else { + return out; + }; + let delta = i64::from(landed) - i64::from(was); + for (&pick, &old_start) in picks.iter().zip(pre_starts) { + let Some(old_start) = old_start else { + continue; + }; + let want = (i64::from(old_start) + delta) as u32; + // Every pick but the dragged clip itself stays on the lane it was + // already on; only the exact clip the hand let go of changed + // lane, so only its own pick is found on `to` rather than `from`. + let now_lane = if pick == (from, dragged) { to } else { pick.0 }; + if let Some(found) = session + .lane_clips(now_lane) + .iter() + .position(|c| c.start == want) + { + out.add((now_lane, found)); + } + } + out + } + /// The whole of a palette track as a placement: from its own first /// microsecond to its last cue, and as many timeline frames as that is worth /// at this rate. What a row dragged out of the Subtitles list carries, and @@ -405,7 +517,7 @@ impl Player { } self.mark_dirty(); self.snap_cue = None; - self.ghost = None; + self.ghost.clear(); let at = self.place_frame(x).0; // What the mark is on, before the lane is renumbered: a caption's start // frame is its name on its lane ([`sub_mark`]). @@ -493,7 +605,7 @@ impl Player { } self.mark_dirty(); self.snap_cue = None; - self.ghost = None; + self.ghost.clear(); let Some(idx) = self.dragged_sub(drag) else { return; }; @@ -669,7 +781,7 @@ impl Player { tint: CLIP_TEXT(), refused: to.kind != LaneKind::Subtitle, }; - self.set_ghost(Some(ghost), cx); + self.set_ghost(vec![ghost], cx); } /// The same for a palette row on its way down: it lands at the frame it is @@ -689,7 +801,7 @@ impl Player { tint: CLIP_TEXT(), refused: to.kind != LaneKind::Subtitle, }; - self.set_ghost(Some(ghost), cx); + self.set_ghost(vec![ghost], cx); } /// Where a clip let go at window `x` over lane `to` wants its head: the @@ -779,6 +891,15 @@ impl Player { /// are one answer -- and its own length at this zoom. A lane of the other /// kind refuses the drop ([`Project::move_clip`]), and the shadow says so /// before the release does. + /// + /// When the dragged clip is itself one of a multi-pick selection (the same + /// `set_move` test [`Player::move_clip`] commits by), every other pick + /// draws its own shadow too, at the delta the anchor above is landing at -- + /// [`Project::move_selection`]'s own clamp is not reread here, so a wall + /// that would narrow the group's travel is seen only at the release, not + /// in the shadow; the anchor's own room is still exact; corner-cut, ceiling + /// a shadow a member or two too wide on a tight bed, upgrade is exposing + /// `move_room` to preview against. pub(crate) fn preview_ghost( &mut self, drag: &ClipDrag, @@ -786,17 +907,46 @@ impl Player { x: Pixels, cx: &mut Context, ) { - let ghost = self - .dragged(drag) - .and_then(|idx| self.drop_frame(drag.lane, idx, x)) - .map(|(start, _)| Ghost { - lane: to, - start, - frames: drag.clip.frames(), - tint: self.clip_tint(drag.clip.source), - refused: drag.lane.kind != to.kind, - }); - self.set_ghost(ghost, cx); + let Some(idx) = self.dragged(drag) else { + self.set_ghost(Vec::new(), cx); + return; + }; + let Some((start, _)) = self.drop_frame(drag.lane, idx, x) else { + self.set_ghost(Vec::new(), cx); + return; + }; + let anchor = Ghost { + lane: to, + start, + frames: drag.clip.frames(), + tint: self.clip_tint(drag.clip.source), + refused: drag.lane.kind != to.kind, + }; + let mut ghosts = vec![anchor]; + if self.selected.contains((drag.lane, idx)) && self.selected.len() > 1 { + let delta = i64::from(start) - i64::from(drag.clip.start); + for &(lane, i) in self.selected.picks() { + if (lane, i) == (drag.lane, idx) { + continue; + } + let Some(clip) = self + .session + .as_ref() + .and_then(|session| session.lane_clips(lane).get(i).copied()) + else { + continue; + }; + let want = (i64::from(clip.start) + delta).max(0) as u32; + ghosts.push(Ghost { + lane, + start: want, + frames: clip.frames(), + tint: self.clip_tint(clip.source), + refused: anchor.refused, + }); + } + } + self.set_ghost(ghosts, cx); } /// The line the track in the hand would drop into, on the row the pointer @@ -860,7 +1010,7 @@ impl Player { tint: file_tint(self.sources(), path).unwrap_or(BG_RAISED()), refused: lane_refuses(path, to).is_some(), }; - self.set_ghost(Some(ghost), cx); + self.set_ghost(vec![ghost], cx); } /// Sets the shadow, or takes it away, repainting only when it moved -- the @@ -868,7 +1018,7 @@ impl Player { /// root and set again by the lane under the pointer, in that order (gpui /// runs the capture phase parent-first), so a pointer over no lane at all /// leaves nothing drawn. - pub(crate) fn set_ghost(&mut self, ghost: Option, cx: &mut Context) { + pub(crate) fn set_ghost(&mut self, ghost: Vec, cx: &mut Context) { if ghost != self.ghost { self.ghost = ghost; cx.notify(); @@ -1550,6 +1700,38 @@ impl Player { cx.notify(); } + /// Widens or narrows the transition the anchor already carries, one + /// frame at a step, from the inspector's duration row -- ctrl+f/ctrl+x + /// stay the toggle that seeds a fresh one at one second; this is what + /// moves it afterwards. The engine clamps both kinds to what the two + /// clips actually offer ([`Project::set_transition_out`], + /// [`Project::crossfade`]), so a step past the successor's own length + /// lands at the successor's length instead of asking for more than + /// there is. + pub(crate) fn nudge_transition(&mut self, lane: Lane, idx: usize, step: i32, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + let Some(session) = &mut self.session else { + return; + }; + let current = match lane.kind { + LaneKind::Video => session.transition_out_of(lane, idx), + LaneKind::Audio => session.lane_clips(lane).get(idx).map_or(0, |c| c.fade_out), + _ => return, + }; + let frames = (current as i32 + step).max(0) as u32; + let ok = match lane.kind { + LaneKind::Video => session.set_transition_out(lane, idx, frames), + LaneKind::Audio => session.crossfade(lane, idx, frames), + _ => false, + }; + if ok { + self.mark_dirty(); + cx.notify(); + } + } + /// The clip as the drag is showing it: an edge under the pointer moves its /// own box, and the boxes of everything linked to it, before anything is /// committed. Display only -- the project is not touched until the release. @@ -1750,9 +1932,9 @@ impl Player { Some(MouseButton::Left) => self.drag_split(split, event.position, window, cx), // Released outside the window: the up below never came, so this // is where the gesture ends. The size is already written to - // `self.splits`, but the darkroom's two persisted seams still - // owe the save `drag_release` would have paid -- without it - // the drag holds for the session and reverts on restart. + // `self.splits`, but a persisted seam still owes the save + // `drag_release` would have paid -- without it the drag + // holds for the session and reverts on restart. _ => { self.split_drag = None; if split_drag_owes_save(Some(split)) { @@ -1889,10 +2071,10 @@ impl Player { } if let Some(split) = self.split_drag.take() { self.drag_split(split, event.position, window, cx); - // The darkroom's own two seams outlive the window: written once, - // on the release that ends the gesture, the same small-file - // round trip `ui::dock_stance`'s tab pick uses -- not on every - // sample in between, which `drag_move` above never owed a write. + // Every seam outlives the window: written once, on the release + // that ends the gesture, the same small-file round trip + // `ui::dock_stance`'s tab pick uses -- not on every sample in + // between, which `drag_move` above never owed a write. if split_drag_owes_save(Some(split)) { save_stance_splits(&self.splits); } diff --git a/crates/app/src/player/transport.rs b/crates/app/src/player/transport.rs index 2926681..3eb43c9 100644 --- a/crates/app/src/player/transport.rs +++ b/crates/app/src/player/transport.rs @@ -46,14 +46,17 @@ impl Player { let Some(session) = self.preview_session.as_mut().or(self.session.as_mut()) else { return; }; - // Loop-trim (DESIGN.md §6): the transport is kept inside the subject - // cut's own span while the mode is on, so a trim can be heard and - // seen without a manual replay after every nudge. Checked off the - // engine's own clock, not a frame counter this pump keeps -- the - // same `now()` [`Player::step`] reads. - if session.is_playing() && should_loop_restart(frame_at(session.now(), fps), self.loop_trim) + // Loop-trim and the i/o range (DESIGN.md §6): the transport is kept + // inside the active window while one is armed, so a trim or a marked + // range can be heard and seen without a manual replay after every + // nudge. The range wins over the trim when both are set + // ([`active_loop_window`]). Checked off the engine's own clock, not + // a frame counter this pump keeps -- the same `now()` + // [`Player::step`] reads. + let loop_window = active_loop_window(self.loop_on, self.range, self.loop_trim); + if session.is_playing() && should_loop_restart(frame_at(session.now(), fps), loop_window) { - let start = self.loop_trim.map_or(0, |(lo, _)| lo); + let start = loop_window.map_or(0, |(lo, _)| lo); session.seek(f64::from(start) / fps); } // Whether the span now decoding has yet to hand over a picture, read @@ -172,6 +175,10 @@ impl Player { // whole-timeline loop already used, so that race has nothing // left to win: reaching the end while *either* loop is armed // restarts rather than halts, regardless of which one owns it. + // A bare i/o range never arms this crossing on its own -- it is + // an export mark first ([`active_loop_window`]) -- so `range` + // only ever widens `armed` through the `loop_on`/`loop_trim` + // terms already here, never past them. let armed = self.loop_on || self.loop_trim.is_some(); if crosses_into_loop(was, Transport::Ended, armed) { // The same door the restart button and key use @@ -179,7 +186,8 @@ impl Player { // spends only on a repaint -- the pump is already inside one. // One seam of a one-frame seam: the restart is a fresh seek // and its reopen, not a gapless splice. - let start = loop_restart_frame(self.loop_on, self.loop_trim).unwrap_or(0); + let start = + loop_restart_frame(self.loop_on, self.range, self.loop_trim).unwrap_or(0); if let Some(session) = self.active_session_mut() { session.seek(f64::from(start) / fps); } @@ -246,7 +254,7 @@ impl Player { // ...and the shadow a drag is drawn under promises a landing on a lane // this edit has just reshaped. The next move of the drag draws it // again; until then it says nothing. - self.ghost = None; + self.ghost.clear(); } /// Jumps the timeline. @@ -474,20 +482,45 @@ mod tests { } /// `loop_restart_frame` picks the seek target the crossing above plays - /// from: the trim window's near edge when one is armed (it wins over the - /// whole-timeline loop when both happen to be set), the top of the - /// timeline for the whole-timeline loop alone, and no restart at all - /// with neither armed. + /// from: the i/o range's near edge when one is armed and set (it wins + /// over both the trim window and the whole-timeline loop), the trim + /// window's near edge next, the top of the timeline for the + /// whole-timeline loop alone, and no restart at all with nothing armed. #[test] fn loop_restart_frame_prefers_the_trim_window_then_the_whole_timeline_then_nothing() { - assert_eq!(loop_restart_frame(false, Some((30, 60))), Some(30)); + assert_eq!(loop_restart_frame(false, None, Some((30, 60))), Some(30)); assert_eq!( - loop_restart_frame(true, Some((30, 60))), + loop_restart_frame(true, None, Some((30, 60))), Some(30), "the trim window wins over the whole-timeline loop" ); - assert_eq!(loop_restart_frame(true, None), Some(0)); - assert_eq!(loop_restart_frame(false, None), None); + assert_eq!(loop_restart_frame(true, None, None), Some(0)); + assert_eq!(loop_restart_frame(false, None, None), None); + // The i/o range beats the trim window when both are set... + assert_eq!( + loop_restart_frame(true, Some((10, 20)), Some((30, 60))), + Some(10), + "the marked range wins over the subject-cut trim" + ); + // ...and a range alone, with loop off and no trim, never arms a + // restart at all -- it is an export mark first. + assert_eq!( + loop_restart_frame(false, Some((10, 20)), None), + None, + "a bare i/o range must not start looping un-looped playback" + ); + // Clearing the range falls back to the trim window, then to the + // whole timeline. + assert_eq!( + loop_restart_frame(true, None, Some((30, 60))), + Some(30), + "clearing the range falls back to the trim window" + ); + assert_eq!( + loop_restart_frame(true, None, None), + Some(0), + "clearing both the range and the trim falls back to the whole timeline" + ); } /// The bug this session fixed: a loop-trim window whose far edge (60) @@ -509,7 +542,7 @@ mod tests { Transport::Ended, armed )); - assert_eq!(loop_restart_frame(loop_on, loop_trim), Some(30)); + assert_eq!(loop_restart_frame(loop_on, None, loop_trim), Some(30)); } /// A loop window sitting entirely before the film's end never reaches diff --git a/crates/app/src/render.rs b/crates/app/src/render.rs index 7de0a68..186a913 100644 --- a/crates/app/src/render.rs +++ b/crates/app/src/render.rs @@ -607,12 +607,12 @@ impl Render for Player { // (`lane_row`), which gpui runs straight after this one: the // capture phase goes parent first, so a pointer over no lane at // all -- up in the library, say -- promises nothing. - this.set_ghost(None, cx); + this.set_ghost(Vec::new(), cx); })) .on_drag_move( cx.listener(|this, event: &DragMoveEvent, _, cx| { this.preview_place(event.event.position.x, cx); - this.set_ghost(None, cx); + this.set_ghost(Vec::new(), cx); }), ) // The same pair for the two subtitle gestures, for the same reason: @@ -620,7 +620,7 @@ impl Render for Player { // lane, and both are let go somewhere else entirely. .on_drag_move(cx.listener(|this, event: &DragMoveEvent, _, cx| { this.preview_place(event.event.position.x, cx); - this.set_ghost(None, cx); + this.set_ghost(Vec::new(), cx); })) .on_drag_move(cx.listener(|this, event: &DragMoveEvent, _, cx| { // The placement gpui froze into the payload, whose *length* is @@ -629,7 +629,7 @@ impl Render for Player { let (drag, x) = (*event.drag(cx), event.event.position.x); let cue = this.sub_drop_frame(drag.sub, x).1; this.set_cue(cue, x, cx); - this.set_ghost(None, cx); + this.set_ghost(Vec::new(), cx); })) // Scrubbing is tracked on the root because the pointer leaves the // 6 px ruler on the first drag and its own listeners then stop diff --git a/crates/app/src/tests/cards.rs b/crates/app/src/tests/cards.rs index 55a6017..9389498 100644 --- a/crates/app/src/tests/cards.rs +++ b/crates/app/src/tests/cards.rs @@ -3,6 +3,7 @@ use super::*; use crate::audio_cards::EQ_GRAPH_MAX_H; +use crate::ui::inspector::transition_of; use std::sync::atomic::Ordering; /// FAULT 2's general shape (not just the source dot's menu): `overlaid()` @@ -186,8 +187,9 @@ fn only_a_chord_gets_out_of_an_export() { assert!(!cancels_export("e", false, Some(ActionId::Export))); assert!(!cancels_export("space", false, Some(ActionId::Play))); assert!(!cancels_export("q", false, None)); - // The default keymap is what the handler feeds this: the chord reaches the - // action, the bare key reaches nothing. + // The default keymap is what the handler feeds this: the chord reaches + // CancelExport, the bare key reaches Deselect instead -- neither of which + // this guard lets cancel a running export. let k = keymap::Keymap::defaults(); assert!(cancels_export("escape", true, k.lookup("escape", true))); assert!(!cancels_export("escape", false, k.lookup("escape", false))); @@ -1207,6 +1209,72 @@ fn a_typed_bitrate_is_a_field_and_not_a_key_capture() { assert!(detail.starts_with("6▏"), "{detail}"); } +/// [`crate::ui::inspector::transition_of`]: the inspector's duration row +/// appears only for an anchor that actually carries a dissolve or a +/// crossfade, and the room it offers is capped at what the successor clip +/// actually has -- the same clamp [`engine::project::Project::set_transition_out`]/ +/// [`engine::project::Project::crossfade`] enforce, read back here without +/// either engine call so the row can never claim more than a step could land +/// in. +#[test] +fn a_duration_row_shows_only_for_a_transition_and_its_room_is_the_successors() { + // `len` is the clip's own source length (`out_frame`, `in_frame` fixed at + // 0, `speed` 1x, so `Clip::frames()` reads back exactly `len`). + fn clip(start: u32, len: u32, transition_out: u32, fade_in: u32, fade_out: u32) -> Clip { + Clip { + start, + in_frame: 0, + out_frame: len, + source: 0, + link: None, + eq: None, + color: None, + transform: None, + fit: FitPolicy::default(), + speed: Speed::NORMAL, + fade_in, + fade_out, + transition_out, + } + } + // A plain cut carries neither field, so the row has nothing to show. + let plain = clip(0, 10, 0, 0, 0); + let plain_next = clip(10, 15, 0, 0, 0); + assert_eq!(transition_of(LaneKind::Video, &plain, Some(&plain_next)), None); + + // A dissolve: video lane, `transition_out` set, an adjacent successor. + // The room offered is the shorter of the two -- here the successor's own + // 5-frame length, less than the anchor's 10. + let a = clip(0, 10, 4, 0, 0); + let b = clip(10, 5, 0, 0, 0); + assert_eq!( + transition_of(LaneKind::Video, &a, Some(&b)), + Some(("Dissolve", 4, 5)) + ); + // No successor, or a gap before one: no row, same as no transition. + assert_eq!(transition_of(LaneKind::Video, &a, None), None); + let gap = clip(11, 5, 0, 0, 0); + assert_eq!(transition_of(LaneKind::Video, &a, Some(&gap)), None); + + // A crossfade: audio lane, both ends of the join set + // ([`Project::crossfade`]'s own signature) -- a one-sided fade (the + // successor's `fade_in` still 0) is not one, and stays a plain fade. + let a = clip(0, 10, 0, 0, 3); + let b = clip(10, 2, 0, 3, 0); + assert_eq!( + transition_of(LaneKind::Audio, &a, Some(&b)), + Some(("Crossfade", 3, 2)), + "capped at the successor's own 2-frame length, though 3 was asked for" + ); + let one_sided = clip(10, 2, 0, 0, 0); + assert_eq!(transition_of(LaneKind::Audio, &a, Some(&one_sided)), None); + + // A dissolve field on an audio lane, or a fade-only pair on a video + // lane, name no transition either -- each kind reads only its own lane. + let dissolving = clip(0, 10, 4, 0, 0); + assert_eq!(transition_of(LaneKind::Audio, &dissolving, Some(&b)), None); +} + #[test] fn a_clip_with_no_sound_is_refused_in_the_same_words_whichever_kind_it_is() { // A still and a video with no audio track are one answer to one diff --git a/crates/app/src/tests/editing.rs b/crates/app/src/tests/editing.rs index 1cc1631..a3fa040 100644 --- a/crates/app/src/tests/editing.rs +++ b/crates/app/src/tests/editing.rs @@ -1688,19 +1688,35 @@ fn a_copied_clip_is_renumbered_or_dropped_when_a_row_leaves_the_library() { }; // Copied from source 2, source 0 removed: the same file is source 1 now. assert_eq!( - clipboard_after_remove(Some(clip(2)), 0).map(|c| c.source), - Some(1), + clipboard_after_remove(vec![(Lane::V1, clip(2))], 0) + .into_iter() + .map(|(_, c)| c.source) + .collect::>(), + vec![1], "the clipboard follows its file down the list" ); // Copied from a source *before* the one that went: untouched. assert_eq!( - clipboard_after_remove(Some(clip(0)), 2).map(|c| c.source), - Some(0) + clipboard_after_remove(vec![(Lane::V1, clip(0))], 2) + .into_iter() + .map(|(_, c)| c.source) + .collect::>(), + vec![0] ); // Copied from the row that was just removed: there is nothing left to // paste, and pasting the next file along would be a lie. - assert!(clipboard_after_remove(Some(clip(1)), 1).is_none()); - assert!(clipboard_after_remove(None, 0).is_none()); + assert!(clipboard_after_remove(vec![(Lane::V1, clip(1))], 1).is_empty()); + assert!(clipboard_after_remove(Vec::new(), 0).is_empty()); + // A set with one member's file gone loses only that member -- the rest + // of the set survives to be pasted, gaps and lanes intact. + let trimmed = clipboard_after_remove( + vec![(Lane::V1, clip(1)), (Lane::A1, clip(2))], + 1, + ); + assert_eq!( + trimmed.into_iter().map(|(_, c)| c.source).collect::>(), + vec![1] + ); } /// The trim-a-clip path through the doors the edge drag uses: @@ -1900,6 +1916,259 @@ fn a_track_can_be_added_dropped_on_edited_and_taken_back() { assert_eq!(format_refusal(&session, Format::Mp4), None); } +/// [`PlaybackSession::move_selection_to`], the door a selection drag uses +/// ([`Player::move_clip`]'s set path): three picks across two lanes, one of +/// them the dragged clip, all travel the *same* frame delta in one call -- +/// the same all-or-nothing clamp [`Project::move_room`] already gave a +/// linked group, generalised to an arbitrary selection. +#[test] +fn a_selection_drag_moves_every_pick_by_the_same_delta() { + use engine::project::LaneKind; + + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + let path = session.sources()[0].path.clone(); + session.import(&asset("test_av2.mp4")).expect("av2 matches"); + let second = session.sources()[1].path.clone(); + + // clip0 on V1 at the fixture's own start; clip1 on V1 ten seconds in, + // appended to the open bed and rippling nothing. + assert!(session + .place_stream_at(10.0, &second, 0, None) + .expect("av2 is on this timeline")); + let clip0 = session.lane_clips(Lane::V1)[0]; + let clip1 = session.lane_clips(Lane::V1)[1]; + assert_eq!((clip0.start, clip1.start), (0, 300)); + + // clipC on a second video row, well past both of the above. + let v2 = session.add_lane(LaneKind::Video); + assert!(session + .place_stream_at(20.0, &path, 0, Some(v2)) + .expect("test_av.mp4 is on this timeline")); + let clip_c = session.lane_clips(v2)[0]; + assert_eq!(clip_c.start, 600); + + let picks = [(Lane::V1, 0), (Lane::V1, 1), (v2, 0)]; + // Drag clip1 fifty frames along its own lane -- the other two picks own + // no neighbours of their own here, so nothing narrows the room and the + // full fifty-frame ask goes through for all three. + assert!(session.move_selection_to(&picks, Lane::V1, 1, Lane::V1, clip1.start + 50)); + assert_eq!(session.lane_clips(Lane::V1)[0].start, clip0.start + 50); + assert_eq!(session.lane_clips(Lane::V1)[1].start, clip1.start + 50); + assert_eq!(session.lane_clips(v2)[0].start, clip_c.start + 50); + // Every pick still names the clip it named: found again by the frame it + // now starts at -- exactly the lookup `Player::remap_selection` makes + // once the move lands, which is what keeps a set-move's selection alive + // rather than clearing it. + assert_eq!( + session.lane_clips(Lane::V1)[0], + Clip { start: clip0.start + 50, ..clip0 } + ); + assert_eq!( + session.lane_clips(v2)[0], + Clip { start: clip_c.start + 50, ..clip_c } + ); + + assert!(session.undo(), "one step for the whole set-move"); + assert_eq!(session.lane_clips(Lane::V1)[0].start, clip0.start); + assert_eq!(session.lane_clips(Lane::V1)[1].start, clip1.start); + assert_eq!(session.lane_clips(v2)[0].start, clip_c.start); +} + +/// One pick with nowhere to go refuses the whole set: the walk onto another +/// clip's own span that already refuses a lone drag +/// (`move_clip_keeps_the_frames_and_refuses_the_rest`, in this crate's own +/// engine tests) refuses a selection drag exactly the same way, and every +/// *other* pick -- which had all the room in the world -- stays exactly +/// where it was rather than moving on its own. +#[test] +fn a_selection_drag_refuses_as_one_set_when_any_pick_cannot_land() { + use engine::project::LaneKind; + + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + let path = session.sources()[0].path.clone(); + session.import(&asset("test_av2.mp4")).expect("av2 matches"); + let second = session.sources()[1].path.clone(); + + assert!(session + .place_stream_at(10.0, &second, 0, None) + .expect("av2 is on this timeline")); + let clip0 = session.lane_clips(Lane::V1)[0]; + let clip1 = session.lane_clips(Lane::V1)[1]; + + let v2 = session.add_lane(LaneKind::Video); + assert!(session + .place_stream_at(0.0, &path, 0, Some(v2)) + .expect("test_av.mp4 is on this timeline")); + let clip_c = session.lane_clips(v2)[0]; + // A clip clip1 is not picked, blocking the road on V2 the drag is about + // to try: clip1 dragged onto V2 lands its head inside this one. + assert!(session + .place_stream_at(10.0, &second, 0, Some(v2)) + .expect("av2 is on this timeline")); + let blocker = session.lane_clips(v2)[1]; + assert_eq!(blocker.start, 300); + + let picks = [(Lane::V1, 0), (Lane::V1, 1), (v2, 0)]; + // Dragged onto V2 at a frame inside the blocker: refused outright, the + // way a lone drag onto another clip already is. + assert!(!session.move_selection_to( + &picks, + Lane::V1, + 1, + v2, + blocker.start + 10 + )); + // Nothing moved -- not clip1 clamped short of the blocker, and not the + // two picks that had all the room to spare. + assert_eq!(session.lane_clips(Lane::V1)[0], clip0); + assert_eq!(session.lane_clips(Lane::V1)[1], clip1); + assert_eq!(session.lane_clips(v2)[0], clip_c); + assert_eq!(session.lane_clips(v2)[1], blocker); +} + +/// A plain click's copy is one clipboard entry, and one entry still takes +/// [`PlaybackSession::paste_at`] -- the door it always has, unchanged by a +/// set ever being able to ride [`PlaybackSession::paste_set_at`] instead. +#[test] +fn a_single_pick_copy_paste_round_trips_unchanged() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + // `open` seeds V1 with the whole fixture as its own clip -- what a plain + // click would copy. + let copied = session.lane_clips(Lane::V1)[0]; + + let at = session.timeline_duration(); + assert!(session.paste_at(at, copied), "a free spot always takes it"); + let pasted = session.lane_clips(Lane::V1)[1]; + assert_eq!( + (pasted.source, pasted.in_frame, pasted.out_frame), + (copied.source, copied.in_frame, copied.out_frame), + "the pasted clip plays the same source frames the copy did" + ); + + assert!(session.undo(), "one step for the paste"); + assert_eq!(session.lane_clips(Lane::V1).len(), 1); +} + +/// [`PlaybackSession::paste_set_at`], the set-copy's own door +/// ([`Player::paste`]'s multi-entry path): three picks across two lanes, some +/// distance apart, keep that same distance and the same lane each landed on +/// -- the offset [`Project::paste_set`] moves every item by is the one from +/// the earliest pick to `at`, not a collapse onto `V1`/`A1`. +#[test] +fn a_three_pick_copy_paste_preserves_gaps_and_lane_assignment() { + use engine::project::LaneKind; + + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + let path = session.sources()[0].path.clone(); + session.import(&asset("test_av2.mp4")).expect("av2 matches"); + let second = session.sources()[1].path.clone(); + + assert!(session + .place_stream_at(10.0, &second, 0, None) + .expect("av2 is on this timeline")); + let clip0 = session.lane_clips(Lane::V1)[0]; + let clip1 = session.lane_clips(Lane::V1)[1]; + + let v2 = session.add_lane(LaneKind::Video); + assert!(session + .place_stream_at(20.0, &path, 0, Some(v2)) + .expect("test_av.mp4 is on this timeline")); + let clip_c = session.lane_clips(v2)[0]; + + // Copied in click order, out of the lanes each was clicked in -- exactly + // what `Player::copy_selected` builds. + let items = [(Lane::V1, clip0), (Lane::V1, clip1), (v2, clip_c)]; + let at = session.timeline_duration(); + assert!(session.paste_set_at(at, &items), "a free spot takes the set"); + + let new0 = session.lane_clips(Lane::V1)[2]; + let new1 = session.lane_clips(Lane::V1)[3]; + let new_c = session.lane_clips(v2)[1]; + // The gaps between picks survive the trip untouched. + assert_eq!(new1.start - new0.start, clip1.start - clip0.start); + assert_eq!(new_c.start - new0.start, clip_c.start - clip0.start); + // And each still plays the source frames it was copied with, off the + // lane it was copied off of. + assert_eq!( + (new0.source, new0.in_frame, new0.out_frame), + (clip0.source, clip0.in_frame, clip0.out_frame) + ); + assert_eq!( + (new_c.source, new_c.in_frame, new_c.out_frame), + (clip_c.source, clip_c.in_frame, clip_c.out_frame) + ); + + assert!(session.undo(), "one step for the whole set-paste"); + assert_eq!(session.lane_clips(Lane::V1).len(), 2); + assert_eq!(session.lane_clips(v2).len(), 1); +} + +/// A set-paste never ripples the bed: a landing that would overlap so much +/// as one existing clip on its own lane refuses the *whole* set, exactly as +/// [`Project::paste_set`] documents, leaving the project as it was rather +/// than placing the picks that had room to spare. +#[test] +fn a_colliding_set_paste_refuses_whole() { + use engine::project::LaneKind; + + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + let path = session.sources()[0].path.clone(); + session.import(&asset("test_av2.mp4")).expect("av2 matches"); + let second = session.sources()[1].path.clone(); + + assert!(session + .place_stream_at(10.0, &second, 0, None) + .expect("av2 is on this timeline")); + let clip0 = session.lane_clips(Lane::V1)[0]; + let clip1 = session.lane_clips(Lane::V1)[1]; + + let v2 = session.add_lane(LaneKind::Video); + assert!(session + .place_stream_at(20.0, &path, 0, Some(v2)) + .expect("test_av.mp4 is on this timeline")); + let clip_c = session.lane_clips(v2)[0]; + + let items = [(Lane::V1, clip0), (Lane::V1, clip1), (v2, clip_c)]; + // A blocker sat right where the V1 half of the set would land: pasting + // at the timeline's own start walks every item straight back onto the + // lanes it was copied off of, colliding with everything already there. + assert!(!session.paste_set_at(0.0, &items)); + + assert_eq!(session.lane_clips(Lane::V1)[0], clip0); + assert_eq!(session.lane_clips(Lane::V1)[1], clip1); + assert_eq!(session.lane_clips(v2)[0], clip_c); + assert_eq!(session.lane_clips(Lane::V1).len(), 2); + assert_eq!(session.lane_clips(v2).len(), 1); +} + +/// The refactor `move_clip` -> `move_selection` owes: a clip dragged from +/// outside the selection (or with nothing else selected) moves exactly as it +/// always has -- `move_clip_to`'s own door and `move_selection_to`'s +/// selection-of-one both walk the same code, so they cannot drift apart. +#[test] +fn a_lone_clip_drag_is_unchanged_by_the_selection_path() { + use engine::project::LaneKind; + + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + let v2 = session.add_lane(LaneKind::Video); + + assert!(session.move_clip_to(Lane::V1, 0, v2, 0), "V1 -> V2"); + assert!(session.lane_clips(Lane::V1).is_empty()); + assert_eq!(session.lane_clips(v2).len(), 1); + + // The other kind of lane is refused exactly as before. + assert!(!session.move_clip_to(v2, 0, Lane::A1, 0)); + // A drop back where it was picked up is a click, still refused. + let clip = session.lane_clips(v2)[0]; + assert!(!session.move_clip_to(v2, 0, v2, clip.start)); +} + /// A caption grouped with a clip on an *added* lane closes its lane's hole /// too, not just the first pair's: the same law commit `cdc53a6` gave `V1` /// (`whole_take` -> `Project::delete_members`) has to hold from every anchor @@ -2182,3 +2451,63 @@ fn should_loop_restart_is_play_state_blind_the_pump_gates_it() { into-it -- that distinction is pump's is_playing() guard, not this" ); } + +/// This binary has no `TestAppContext` to press a live escape through, so the +/// guard reads the ordering `render.rs`'s key listener actually runs: every +/// card/menu/list close returns before the fallthrough that dispatches +/// `ActionId::Deselect` ever runs, so escape with one of them open closes it +/// and never touches `self.selected` -- the picks made before the card opened +/// are still there once it is gone. +#[test] +fn escape_closes_a_card_before_it_can_ever_reach_deselect() { + let render_rs = src_text("render.rs"); + let dispatch = render_rs + .find("if let Some(action) = action {") + .expect("the keymap fallthrough that fires Deselect"); + for (guard, label) in [ + ("if this.keys_open {", "the keys overlay"), + ("if this.dock_filter_edit {", "the dock filter"), + ( + "if this.param_card_key(key, event.keystroke.modifiers.shift, cx) {", + "a param card", + ), + ( + "if escape_leaves_player_fullscreen(key, ctrl, this.player_fullscreen) {", + "player fullscreen", + ), + ("let clip_menu = this.context_menu.take().is_some();", "the clip/row menu or a list"), + ( + "if key == ESCAPE && !ctrl && this.preview_session.is_some() {", + "an open preview", + ), + ] { + let at = render_rs + .find(guard) + .unwrap_or_else(|| panic!("{label}'s own escape guard moved or was renamed")); + assert!( + at < dispatch, + "{label}'s guard reads after the Deselect dispatch -- escape would \ + clear the selection before this card ever got a look at the key" + ); + } +} + +/// The other half: with nothing on screen to claim the key, bare escape falls +/// all the way through to `Player::act`, whose `ActionId::Deselect` arm is +/// the one place `self.selected` is emptied by a bare stroke rather than by +/// picking something else. +#[test] +fn escape_with_nothing_open_empties_the_selection() { + let actions_rs = src_text("player/actions.rs"); + assert!( + actions_rs.contains("ActionId::Deselect => {") + && actions_rs.contains("self.selected = Selection::new();"), + "the Deselect arm no longer clears self.selected" + ); + let k = keymap::Keymap::defaults(); + assert_eq!( + k.lookup("escape", false), + Some(ActionId::Deselect), + "bare escape must still route to Deselect for that arm to ever run" + ); +} diff --git a/crates/app/src/tests/layout.rs b/crates/app/src/tests/layout.rs index f855e36..e297058 100644 --- a/crates/app/src/tests/layout.rs +++ b/crates/app/src/tests/layout.rs @@ -2135,22 +2135,48 @@ fn the_notice_plate_declares_a_bounded_wrapping_text_layout() { } /// A round trip through the file: what is saved is what the next load reads -/// back, one seam touched and the other left at its default -- a scratch -/// path, not the real config, the same isolation `keymap::tests`' own -/// `load_from`/`save_to` already takes. +/// back, all five seams touched -- a scratch path, not the real config, the +/// same isolation `keymap::tests`' own `load_from`/`save_to` already takes. +/// One of the five is written past its own ceiling (the library, past +/// `SIDE_MAX_FRAC` of the window it is loaded back into): a file written at +/// a wider window must not hand a narrower one an illegal layout, so the +/// load clamps it back down rather than reading it verbatim. #[test] fn a_saved_seam_survives_a_reload() { - use crate::{Split, Splits, load_stance_splits_from, save_stance_splits_to}; + use crate::{ + BENCH_MIN_H, SIDE_MAX_FRAC, Split, Splits, load_stance_splits_from, save_stance_splits_to, + }; + use gpui::{Pixels, Size, px, size}; let dir = engine::scratch::Scratch::dir("edith-stance-splits"); let path = dir.join("stance-splits"); + let window: Size = size(px(1280.), px(720.)); let mut splits = Splits::default(); + splits.set(Split::Library, 9000.); + splits.set(Split::Inspector, 200.); + splits.set(Split::Timeline, 250.); splits.set(Split::Dock, 333.); + splits.set(Split::Bench, 200.); save_stance_splits_to(&splits, &path); - let loaded = load_stance_splits_from(&path); + let loaded = load_stance_splits_from(&path, window); + assert_eq!( + loaded.get(Split::Library), + Some(1280. * SIDE_MAX_FRAC), + "a library past its own ceiling should clamp to it on load" + ); + assert_eq!(loaded.get(Split::Inspector), Some(200.)); + assert_eq!(loaded.get(Split::Timeline), Some(250.)); assert_eq!(loaded.get(Split::Dock), Some(333.)); - assert_eq!(loaded.get(Split::Bench), None); + assert_eq!(loaded.get(Split::Bench), Some(200.)); + + // A bench saved below its own floor clamps up to it, the same ceiling + // logic mirrored on the one seam whose bound is a minimum. + let mut low_bench = Splits::default(); + low_bench.set(Split::Bench, 1.); + save_stance_splits_to(&low_bench, &path); + let loaded = load_stance_splits_from(&path, window); + assert_eq!(loaded.get(Split::Bench), Some(BENCH_MIN_H)); } /// The guard [`crate::split_drag_owes_save`] runs at the moment a drag ends @@ -2158,18 +2184,18 @@ fn a_saved_seam_survives_a_reload() { /// wired to a live `MouseExitEvent` a `TestAppContext`-less test binary /// cannot raise -- see `tests/media.rs`'s own note on the same limit, and /// the harness drive `D2` in this session's report for the wiring itself). -/// What *is* checkable here without a window: exactly the two persisted +/// What *is* checkable here without a window: exactly the persisted /// seams owe that save, the same set `Split::PERSISTED` already names, and a /// drag that never started (`None`) owes nothing. #[test] -fn only_the_two_persisted_seams_owe_a_save_when_a_drag_loses_the_window() { +fn only_the_persisted_seams_owe_a_save_when_a_drag_loses_the_window() { use crate::{Split, player::timeline_edit::split_drag_owes_save}; assert!(split_drag_owes_save(Some(Split::Dock))); assert!(split_drag_owes_save(Some(Split::Bench))); - assert!(!split_drag_owes_save(Some(Split::Library))); - assert!(!split_drag_owes_save(Some(Split::Inspector))); - assert!(!split_drag_owes_save(Some(Split::Timeline))); + assert!(split_drag_owes_save(Some(Split::Library))); + assert!(split_drag_owes_save(Some(Split::Inspector))); + assert!(split_drag_owes_save(Some(Split::Timeline))); assert!(!split_drag_owes_save(None)); } @@ -2178,9 +2204,14 @@ fn only_the_two_persisted_seams_owe_a_save_when_a_drag_loses_the_window() { #[test] fn a_missing_stance_splits_file_leaves_every_region_at_its_default() { use crate::{Split, load_stance_splits_from}; + use gpui::{Pixels, Size, px, size}; let dir = engine::scratch::Scratch::dir("edith-stance-splits-missing"); - let splits = load_stance_splits_from(&dir.join("nothing-here")); + let window: Size = size(px(1280.), px(720.)); + let splits = load_stance_splits_from(&dir.join("nothing-here"), window); + assert_eq!(splits.get(Split::Library), None); + assert_eq!(splits.get(Split::Inspector), None); + assert_eq!(splits.get(Split::Timeline), None); assert_eq!(splits.get(Split::Dock), None); assert_eq!(splits.get(Split::Bench), None); } @@ -2639,6 +2670,11 @@ fn every_action_has_a_darkroom_widget_home_or_explicit_owner() { clicks, so a click-through door for \"move keyboard focus\" \ has nothing to do that a click has not already done", ), + ( + ActionId::Deselect, + "clicking empty timeline space already clears the selection with the mouse; \ + bare escape is a keyboard-only accelerator for that existing door, not a new one", + ), ]; let darkroom = [ "ui/bench_stance.rs", diff --git a/crates/app/src/timeline_math.rs b/crates/app/src/timeline_math.rs index f3cf214..636ef04 100644 --- a/crates/app/src/timeline_math.rs +++ b/crates/app/src/timeline_math.rs @@ -362,15 +362,37 @@ pub(crate) fn should_loop_restart(frame: u32, window: Option<(u32, u32)>) -> boo window.is_some_and(|(_, hi)| frame >= hi) } +/// Which window is actually looping, in priority order: the i/o range +/// ([`Player::range`]) beats the subject-cut trim ([`Player::loop_trim`]) +/// beats the whole timeline -- but only once *something* is already armed +/// (`loop_on` or `loop_trim`). A bare in/out mark with neither on is an +/// export mark first, not a loop request, so it answers `None` here and +/// never restarts anything on its own. +pub(crate) fn active_loop_window( + loop_on: bool, + range: Option<(u32, u32)>, + loop_trim: Option<(u32, u32)>, +) -> Option<(u32, u32)> { + if !loop_on && loop_trim.is_none() { + return None; + } + range.or(loop_trim) +} + /// Where a play resumes from on crossing into [`Transport::Ended`] -/// (`Player::pump`): the loop-trim window's own near edge when one is armed, -/// *even when its far edge is the film's own last frame* -- half of all cuts -/// in a two-clip film sit on the final clip (DESIGN.md §6), so that coincidence -/// is not an edge case and must not read as "reached the end, stop". Falls -/// back to the whole-timeline loop's top, and `None` -- neither armed -- -/// restarts nothing, which is the halt this crossing otherwise means. -pub(crate) fn loop_restart_frame(loop_on: bool, loop_trim: Option<(u32, u32)>) -> Option { - match loop_trim { +/// (`Player::pump`): the active window's own near edge +/// ([`active_loop_window`]) when one is armed, *even when its far edge is +/// the film's own last frame* -- half of all cuts in a two-clip film sit on +/// the final clip (DESIGN.md §6), so that coincidence is not an edge case +/// and must not read as "reached the end, stop". Falls back to the +/// whole-timeline loop's top, and `None` -- nothing armed -- restarts +/// nothing, which is the halt this crossing otherwise means. +pub(crate) fn loop_restart_frame( + loop_on: bool, + range: Option<(u32, u32)>, + loop_trim: Option<(u32, u32)>, +) -> Option { + match active_loop_window(loop_on, range, loop_trim) { Some((lo, _)) => Some(lo), None => loop_on.then_some(0), } diff --git a/crates/app/src/ui/bench_stance.rs b/crates/app/src/ui/bench_stance.rs index 9ca54b8..87c8d9b 100644 --- a/crates/app/src/ui/bench_stance.rs +++ b/crates/app/src/ui/bench_stance.rs @@ -1124,6 +1124,8 @@ fn lane_row( .children( player .ghost + .iter() + .copied() .filter(|g| g.lane == lane && cx.has_active_drag()) .map(|g| { div() diff --git a/crates/app/src/ui/inspector.rs b/crates/app/src/ui/inspector.rs index 51ae599..97fa15c 100644 --- a/crates/app/src/ui/inspector.rs +++ b/crates/app/src/ui/inspector.rs @@ -121,6 +121,19 @@ impl Player { let sub = self.session.as_ref()?.sub_lane(lane).get(idx).copied()?; Some((lane, sub)) }); + // The transition the anchor's clip carries into its successor, if + // any -- a dissolve on a video lane ([`Clip::transition_out`]) or a + // crossfade on an audio lane, told apart from a plain one-sided fade + // by [`Project::crossfade`]'s own signature: both ends of the join + // set together. `cap` is what the pair actually offers, the same + // ceiling the engine's own setters clamp to, so the row never claims + // more room than a step could land in. + let transition = self.selected.anchor().and_then(|(lane, idx)| { + let session = self.session.as_ref()?; + let clips = session.lane_clips(lane); + let (label, frames, cap) = transition_of(lane.kind, clips.get(idx)?, clips.get(idx + 1))?; + Some((lane, idx, label, frames, cap)) + }); // A multi-selection is named for its anchor and counted: what the // panel shows is the anchor's settings, and the count says there is // more in hand than the panel is showing. @@ -190,6 +203,14 @@ impl Player { .text_color(rgb(FG_SECONDARY())) .child(detail), ) + // The duration field: a value and its own two steppers, the + // shape `mbps_steppers` already draws for the export card's + // bitrate -- present only while the anchor carries a transition, + // since a row for a number that means nothing is a row lying + // about what is selected. + .when_some(transition, |d, (lane, idx, label, frames, cap)| { + d.child(self.transition_duration_row(lane, idx, label, frames, cap, cx)) + }) .child( div() .flex() @@ -268,6 +289,56 @@ impl Player { ) } + /// The duration row a transition-carrying anchor grows under + /// `selection_section`'s detail line: `frames` as the engine counts it, + /// flanked by the −/+ steppers [`Player::mbps_steppers`] already draws + /// for the export card's bitrate row -- a field, not the drag handle + /// `659770a` deliberately shrank the join's hit target away from. Each + /// press nudges by one frame ([`Player::nudge_transition`]); the engine's + /// own setters clamp to `cap`, so a run of presses past what the + /// successor offers stops there rather than erroring. + fn transition_duration_row( + &self, + lane: Lane, + idx: usize, + label: &'static str, + frames: u32, + cap: u32, + cx: &mut Context, + ) -> impl IntoElement { + let step = |id: &'static str, glyph: &'static str, by: i32, cx: &mut Context| { + div() + .id(id) + .flex() + .w(px(HIT_MIN)) + .h(px(HIT_MIN)) + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(BG_RAISED())) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER()))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.nudge_transition(lane, idx, by, cx); + })) + .child(glyph) + }; + div() + .flex_none() + .flex() + .items_center() + .gap(px(6.)) + .child( + div() + .flex_1() + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY())) + .child(format!("{label} {frames}f (of {cap}f offered)")), + ) + .child(step("transition-down", "−", -1, cx)) + .child(step("transition-up", "+", 1, cx)) + } + /// The settings that are the *project's* rather than any clip's: the canvas /// every clip is composed onto, the rate it is cut at, the HDR rendition it /// is watched in, and the mix everything sums into. They used to be four @@ -418,6 +489,35 @@ impl Player { } } +/// The transition a clip carries into its immediate successor, if any -- a +/// dissolve on a video lane ([`Clip::transition_out`]) or a crossfade on an +/// audio lane, told apart from a plain one-sided fade drag by +/// [`Project::crossfade`]'s own signature: both ends of the join set +/// together, not just this clip's tail. `cap` is what the pair actually +/// offers -- the shorter of the two clips' own lengths -- the same ceiling +/// [`Project::set_transition_out`]/[`Project::crossfade`] clamp to, so the +/// row this feeds never claims more room than a step could land in. +/// +/// Free of `Context` and of [`PlaybackSession`] alike, so it is testable +/// without either -- this test binary has neither a `TestAppContext` nor +/// real media to open one with (`split_drag_owes_save`'s own reason for +/// being pulled out the same way). +pub(crate) fn transition_of( + lane_kind: LaneKind, + clip: &Clip, + next: Option<&Clip>, +) -> Option<(&'static str, u32, u32)> { + let next = next.filter(|n| n.start == clip.end())?; + let cap = clip.frames().min(next.frames()); + match lane_kind { + LaneKind::Video if clip.transition_out > 0 => Some(("Dissolve", clip.transition_out, cap)), + LaneKind::Audio if clip.fade_out > 0 && next.fade_in > 0 => { + Some(("Crossfade", clip.fade_out, cap)) + } + _ => None, + } +} + /// A region's own title bar: the same 24 px strip in the library and the /// inspector, so the two columns read as the pair they are. pub(crate) fn section_head(title: &'static str) -> impl IntoElement { diff --git a/crates/app/src/ui/timeline.rs b/crates/app/src/ui/timeline.rs index 11c51e5..6470b11 100644 --- a/crates/app/src/ui/timeline.rs +++ b/crates/app/src/ui/timeline.rs @@ -850,11 +850,15 @@ impl Player { .snap_cue .filter(|_| self.trim.is_some() || cx.has_active_drag()) .map(|frame| scale.px_at(f64::from(frame) / self.fps)); - // The shadow, on the one lane the pointer is over -- and, like the line, - // only while the drag that asked for it is still in flight. - let ghost = self + // The shadow (or shadows, on a set-drag -- [`Player::preview_ghost`]), + // on the one lane each names -- and, like the line, only while the + // drag that asked for it is still in flight. + let ghost: Vec = self .ghost - .filter(|g| g.lane == lane && cx.has_active_drag()); + .iter() + .copied() + .filter(|g| g.lane == lane && cx.has_active_drag()) + .collect(); let clips = self .session .as_ref() @@ -1919,7 +1923,7 @@ impl Player { // under a drag. Over the clips (it is translucent, so what // it would cover shows through) and under the line, which // marks the frame this box merely fills. - .children(ghost.map(|g| { + .children(ghost.into_iter().map(|g| { div() .absolute() .top_0() diff --git a/crates/app/src/ui/toolbar.rs b/crates/app/src/ui/toolbar.rs index 258858f..c9fbbcd 100644 --- a/crates/app/src/ui/toolbar.rs +++ b/crates/app/src/ui/toolbar.rs @@ -170,6 +170,18 @@ impl Player { - 2. * SPLIT_W; let clock_w = TIME_W.min(room - 140.).max(96.); let slider = room >= TRANSPORT_ROOMY; + // Which window the loop button actually restarts, in the same + // priority [`active_loop_window`] picks it in: the marked i/o range + // once something is armed, the subject-cut trim next, the whole + // timeline last. + let armed = self.loop_on || self.loop_trim.is_some(); + let loop_hint = if armed && self.range.is_some() { + "restarts from the marked in point on reaching the marked out point, instead of stopping" + } else if self.loop_trim.is_some() { + "restarts from the subject cut's own start on reaching its end, instead of stopping" + } else { + "restarts from the top on reaching the end, instead of stopping" + }; div() .flex_none() .h(px(TRANSPORT_H)) @@ -213,7 +225,7 @@ impl Player { }, None, "Loop", - "restarts from the top on reaching the end, instead of stopping", + loop_hint, ActionId::Loop, cx.listener(|this, _: &ClickEvent, window, cx| { this.act(ActionId::Loop, window, cx) diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index bf9ecc1..2c7ce84 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -2374,6 +2374,22 @@ impl PlaybackSession { self.edit(Dirty::Both, |p| p.move_clip(from, idx, to, start)) } + /// [`move_clip_to`](Self::move_clip_to)'s general form: every one of + /// `picks` travels the same frame delta as the dragged clip at `idx` of + /// `from`, all-or-nothing, one undo step for the lot -- what a hand drags + /// on a selection rather than a lone clip. See + /// [`Project::move_selection`] for the clamp that makes it all-or-nothing. + pub fn move_selection_to( + &mut self, + picks: &[(Lane, usize)], + from: Lane, + idx: usize, + to: Lane, + start: u32, + ) -> bool { + self.edit(Dirty::Both, |p| p.move_selection(picks, from, idx, to, start)) + } + /// Drags one end of that clip to timeline frame `to`, changing how much of /// its source it plays and nothing else on the lane -- see [`Project::trim`] /// for the walls it is clamped by, which this fills the source lengths in @@ -2937,6 +2953,16 @@ impl PlaybackSession { self.edit(Dirty::Both, |p| p.paste(at, clip)) } + /// [`paste_at`](Self::paste_at)'s general form: [`Project::paste_set`]'s + /// door, clamped to the timeline's own end the same way -- a set let go + /// past the last frame lands there rather than carrying black in front of + /// it, exactly as a lone clip's paste does. + pub fn paste_set_at(&mut self, timeline_secs: f64, items: &[(Lane, Clip)]) -> bool { + let at = secs_to_frame(timeline_secs, self.meta.frame_rate) + .min(self.project.timeline_frames()); + self.edit(Dirty::Both, |p| p.paste_set(at, items)) + } + /// Places the whole of `path` played on its audio `stream` at /// `timeline_secs`, the way [`paste_at`](Self::paste_at) places a copy -- /// the door a library row goes through, and the only way a stream other diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 43643a4..31d946c 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -3591,23 +3591,71 @@ impl Project { /// is on, and a drop that changes neither lane nor frame, which is a clip /// picked up and put back down, i.e. a click. pub fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, start: u32) -> bool { + self.move_selection(&[(from, idx)], from, idx, to, start) + } + + /// [`move_clip`](Self::move_clip)'s general form: every pick in `picks` + /// (each with its own link group, exactly as [`group_of`](Self::group_of) + /// reads it) travels the same distance as the clip at `idx` of `from`, + /// which alone changes lane, onto `to`. One clamp across the whole set + /// ([`move_room`](Self::move_room)) is what makes this all-or-nothing: a + /// neighbour that boxes in *any* member narrows the delta every member + /// moves by, and a member with no room at all (`lo > hi`) refuses the + /// whole set rather than moving the rest and leaving that one behind. + /// `move_clip` is this with a selection of one -- the dragged clip's own + /// group and nothing else -- so a drag on a clip outside the selection is + /// byte-identical to before this existed. + pub fn move_selection( + &mut self, + picks: &[(Lane, usize)], + from: Lane, + idx: usize, + to: Lane, + start: u32, + ) -> bool { let (Some(dest), Some(clip)) = (self.index(to), self.lane(from).get(idx).copied()) else { return false; }; if from.kind != to.kind { return false; } - let members = self.group_of(from, idx).expect("the clip was found"); let held = self.index(from).expect("the clip was found on it"); - // The two halves of one group would land on one span of one lane, which - // is the one thing a link may never mean. Refused rather than clamped: - // the partner moves the same distance, so there is no room for it - // anywhere on that lane. + // Every pick's own group, unioned: the whole selection moves as one, + // and a pick's link partners (not themselves picked) come along with + // it exactly as a lone drag's do. + let mut members = Members::default(); + for &(lane, i) in picks { + let Some(group) = self.group_of(lane, i) else { + continue; + }; + for m in group.clips { + if !members.clips.contains(&m) { + members.clips.push(m); + } + } + for m in group.subs { + if !members.subs.contains(&m) { + members.subs.push(m); + } + } + } + if !members.clips.contains(&(held, idx)) { + members.clips.push((held, idx)); + } + // The two halves of *the dragged clip's own* group would land on one + // span of one lane, which is the one thing a link may never mean -- + // checked against that group alone, not the whole moving set: an + // unlinked fellow pick already sitting on `dest` is no conflict at + // all, since it travels by the same delta and `move_room` below + // leaves it the room to. Refused rather than clamped: the partner + // moves the same distance, so there is no room for it anywhere on + // that lane. + let own_group = self.group_of(from, idx).expect("the clip was found"); if dest != held - && members + && own_group .clips .iter() - .chain(&members.subs) + .chain(&own_group.subs) .any(|&(l, _)| l == dest) { return false; @@ -4156,6 +4204,70 @@ impl Project { true } + /// [`paste`](Project::paste)'s general form: every `(lane, clip)` in + /// `items` lands on the lane it names, its head moved by the offset every + /// other item moves by too -- `at` less the earliest `start` among them, + /// so the set's own gaps and lane assignment survive the trip from + /// clipboard to bed unchanged, rather than collapsing onto `V1`/`A1` the + /// way a lone clip's copy does. + /// + /// All-or-nothing, and **refused** rather than opening room or splitting + /// a neighbour the way [`paste`](Project::paste) does for one clip: + /// a set-paste never ripples the bed, so a landing that overlaps so much + /// as one existing clip on its own lane refuses the whole set, changing + /// nothing -- the paste's own [`move_selection`](Project::move_selection) + /// clamps instead of refusing, but a paste has no drag to clamp against, + /// and a landing moved off the frame asked for is not what a paste means. + /// `items` empty, naming a lane or a source that is not there, or a clip + /// with `out_frame <= in_frame`, refuses too, before anything is touched. + /// + /// Exactly one history snapshot for the whole set, so one + /// [`Project::undo`] takes it back. Changes the timeline->source mapping + /// on every lane an item lands on: the caller must reseek. + pub fn paste_set(&mut self, at: u32, items: &[(Lane, Clip)]) -> bool { + let Some(anchor) = items.iter().map(|(_, c)| c.start).min() else { + return false; + }; + // Resolved once, up front, off the lanes as they stand now: a lane or + // source that is not there, or a landing that would overlap a + // neighbour, refuses the whole set before any of it is written. + let mut landings: Vec<(usize, Clip)> = Vec::with_capacity(items.len()); + for &(lane, clip) in items { + let Some(li) = self.index(lane) else { + return false; + }; + if self.sources.get(clip.source).is_none() || clip.out_frame <= clip.in_frame { + return false; + } + let delta = i64::from(clip.start) - i64::from(anchor); + let Ok(start) = u32::try_from(i64::from(at) + delta) else { + return false; + }; + let Some(end) = start.checked_add(clip.frames()) else { + return false; + }; + if self.lanes[li] + .clips + .iter() + .any(|c| c.start < end && start < c.end()) + { + return false; + } + landings.push((li, Clip { start, ..clip })); + } + self.snapshot(); + for (li, mut clip) in landings { + clip.link = Some(self.new_link()); + clip.fade_in = 0; + clip.fade_out = 0; + clip.transition_out = 0; + let clips = &mut self.lanes[li].clips; + let idx = clips.partition_point(|c| c.start < clip.start); + clips.insert(idx, clip); + } + true + } + /// Lift the clip at `idx` out of `lane`, leaving a gap: black frames or /// silence, and nothing else moves. Refused only for an out-of-range index /// (which a lane that is not there always is) -- lifting the last placement