diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index 0f11820..413905c 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -53,6 +53,8 @@ pub enum ActionId { Paste, Cut, Regroup, + Detach, + Group, Select, SelectNext, SelectPrev, @@ -74,7 +76,7 @@ pub enum ActionId { impl ActionId { /// Display order everywhere -- the editor lists them in it and /// [`Keymap::defaults`] binds them in it. - pub const ALL: [ActionId; 29] = [ + pub const ALL: [ActionId; 31] = [ ActionId::Play, ActionId::StepBack, ActionId::StepForward, @@ -88,6 +90,8 @@ impl ActionId { ActionId::Paste, ActionId::Cut, ActionId::Regroup, + ActionId::Detach, + ActionId::Group, ActionId::Select, ActionId::SelectNext, ActionId::SelectPrev, @@ -122,6 +126,8 @@ impl ActionId { ActionId::Paste => "Paste", ActionId::Cut => "Cut", ActionId::Regroup => "Regroup", + ActionId::Detach => "Detach the sound from the picture", + ActionId::Group => "Group with the clip on another track", ActionId::Select => "Select the clip under the playhead (again for the next lane)", ActionId::SelectNext => "Select the next clip in the lane", ActionId::SelectPrev => "Select the previous clip in the lane", @@ -158,6 +164,8 @@ impl ActionId { ActionId::Paste => "paste", ActionId::Cut => "cut", ActionId::Regroup => "regroup", + ActionId::Detach => "detach", + ActionId::Group => "group", ActionId::Select => "select", ActionId::SelectNext => "select-next", ActionId::SelectPrev => "select-prev", @@ -207,6 +215,8 @@ impl ActionId { ActionId::Resolution => Category::View, ActionId::Cut | ActionId::Regroup + | ActionId::Detach + | ActionId::Group | ActionId::Undo | ActionId::AddVideoLane | ActionId::AddAudioLane => Category::Editing, @@ -268,7 +278,7 @@ pub struct Fixed { pub const FIXED: [Fixed; 12] = [ Fixed { chord: "esc", - label: "Close this card or clip menu, or cancel a capture", + label: "Close this card or menu, or cancel a capture", category: Category::View, }, Fixed { @@ -453,6 +463,12 @@ impl Keymap { // The two lane keys, on the letters they are named after: both // were free, and neither is next to a key that edits. b(ActionId::Regroup, "g", false), + // The pair that takes a take apart and puts it back: "d" for + // detach was free and is one press like the rest of the clip + // keys, and grouping two clips is the "g" that rejoins a cut one + // lane over -- the chord beside it, so the two read as one idea. + b(ActionId::Detach, "d", false), + b(ActionId::Group, "g", true), // Selection without a pointer. Tab is what a keyboard already // means by "move on to the next thing", and the two brackets // are the pair either side of it in the lane -- shift+tab is @@ -753,7 +769,7 @@ mod tests { #[test] fn every_default_stroke_reaches_its_action() { let k = Keymap::defaults(); - assert_eq!(k.entries().len(), 31); + assert_eq!(k.entries().len(), 33); assert_eq!(k.lookup("space", false), Some(ActionId::Play)); // The seek keys: bare arrows a frame, ctrl arrows a second, and the two // ends of the timeline. @@ -769,6 +785,9 @@ mod tests { assert_eq!(k.lookup("v", true), Some(ActionId::Paste)); assert_eq!(k.lookup("c", false), Some(ActionId::Cut)); assert_eq!(k.lookup("g", false), Some(ActionId::Regroup)); + // The take apart / put back pair beside it. + assert_eq!(k.lookup("d", false), Some(ActionId::Detach)); + assert_eq!(k.lookup("g", true), Some(ActionId::Group)); // The keyboard's way onto a clip, and the pair that walks the lane. assert_eq!(k.lookup("tab", false), Some(ActionId::Select)); assert_eq!(k.lookup("]", false), Some(ActionId::SelectNext)); @@ -977,7 +996,7 @@ mod tests { assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound"); // The label is the editor's column, and never the file's word for it. assert_eq!(ActionId::CancelExport.label(), "Cancel export"); - assert_eq!(ActionId::ALL.len(), 29); + assert_eq!(ActionId::ALL.len(), 31); } #[test] diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 7193422..edd4b06 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -254,15 +254,70 @@ struct ContextMenu { details: bool, } +/// An open library menu: which row it was opened on -- the file and the stream, +/// the pair [`Player::selected_asset`] holds, so a list rebuilt under it (a +/// probe landing, a source going) cannot slide another row beneath the menu the +/// way a row *index* would -- where it hangs, and whether it has been turned +/// over to show what the file *is*. +#[derive(Clone)] +struct LibraryMenu { + path: PathBuf, + stream: usize, + at: Point, + details: bool, +} + +/// What a library row's menu offers, in the order it lists them. Unlike the clip +/// menu's items none of these is a stroke -- there is no keyboard way to a row -- +/// so the label and the hint are written here rather than read off the keymap. +#[derive(Clone, Copy, PartialEq)] +enum RowItem { + Add, + Remove, + Reveal, + Properties, +} + +const ROW_ITEMS: [RowItem; 4] = [ + RowItem::Add, + RowItem::Remove, + RowItem::Reveal, + RowItem::Properties, +]; + +impl RowItem { + fn label(self) -> &'static str { + match self { + Self::Add => "Add at playhead", + Self::Remove => "Remove from library", + Self::Reveal => "Reveal in files", + Self::Properties => "Properties", + } + } + + /// The dim right-hand column, where the clip menu prints the stroke: what + /// the item will do to the timeline, so nothing here is a surprise. + fn hint(self) -> &'static str { + match self { + Self::Add => "inserts the whole file", + Self::Remove => "only if nothing plays it", + Self::Reveal => "file manager", + Self::Properties => "…", + } + } +} + /// What the menu offers, in the order it lists them. Every one of these is an /// action a stroke already reaches -- the menu is a second way *to* the actions /// and never a second version of them -- so both the label and the hint come /// out of the keymap registry and the two can never disagree. -const MENU_ITEMS: [ActionId; 8] = [ +const MENU_ITEMS: [ActionId; 10] = [ ActionId::Cut, ActionId::Delete, ActionId::Lift, ActionId::Regroup, + ActionId::Detach, + ActionId::Group, ActionId::Equalizer, ActionId::Color, ActionId::Fit, @@ -385,6 +440,10 @@ struct Player { /// `selected` does, so it is closed by anything that can move indices -- /// every stroke, and every item of its own. context_menu: Option, + /// The library menu a right-click on a row opened, if one is up. Names its + /// row by file and stream rather than by position, so it acts on the row it + /// was opened on however the list is rebuilt under it. + library_menu: Option, /// Which library row is picked: the file and the audio stream that row /// names, which is what an insert needs and what survives a row list being /// rebuilt. Its own selection and not the timeline's: Delete keeps acting @@ -626,6 +685,8 @@ impl Player { ActionId::Paste => self.paste(cx), ActionId::Cut => self.cut(cx), ActionId::Regroup => self.regroup(cx), + ActionId::Detach => self.detach(cx), + ActionId::Group => self.group(cx), ActionId::Select => self.select_under_playhead(cx), ActionId::SelectNext => self.select_step(true, cx), ActionId::SelectPrev => self.select_step(false, cx), @@ -1084,6 +1145,63 @@ impl Player { cx.notify(); } + /// Takes the selected clip out of its group, so the picture and the sound + /// under it are edited apart from here on: each half selects, moves, trims + /// and is removed alone, and both draw outlined instead of tinted. The + /// selection stays -- the half that was clicked is still the half in hand. + fn detach(&mut self, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + match (&mut self.session, self.selected) { + (Some(session), Some((lane, idx))) => { + if !session.ungroup(lane, idx) { + self.notice = + Some("NOTHING DETACHED — that clip is not grouped with another".into()); + } + } + (Some(_), None) => { + self.notice = Some("NOTHING DETACHED — click the take to take apart first".into()) + } + (None, _) => {} + } + cx.notify(); + } + + /// Puts the selected clip back in a group with the clip covering exactly the + /// same frames on another track -- the way back from [`Player::detach`], and + /// the way to group a picture with sound it was never opened with. The + /// partner is not clicked because there is nothing to choose: a group id + /// names one span, so only a clip covering these very frames could join it, + /// and the engine words what to do when none does. + fn group(&mut self, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + let partner = match (&self.session, self.selected) { + (Some(session), Some((lane, idx))) => span_partner(session, lane, idx), + _ => None, + }; + match (&mut self.session, self.selected, partner) { + (Some(session), Some((lane, idx)), Some((other, o_idx))) => { + if let Err(e) = session.group(lane, idx, other, o_idx) { + self.notice = Some(format!("NOT GROUPED — {e}").into()); + } + } + (Some(_), Some(_), None) => { + self.notice = Some( + "NOTHING TO GROUP WITH — no clip on another track covers exactly these frames" + .into(), + ) + } + (Some(_), None, _) => { + self.notice = Some("NOTHING GROUPED — click one of the halves first".into()) + } + (None, ..) => {} + } + cx.notify(); + } + /// Drops the selected clip and closes the hole: a whole take goes, both /// lanes of it, and everything after it moves up. A half with no take under /// it in the video lane -- what a lift leaves behind -- has nothing to @@ -1469,6 +1587,75 @@ impl Player { cx.notify(); } + /// Takes a library row's file out of the list, which is the one thing a row + /// can lose. Refused in the engine's own words while clips still play from + /// it -- and those words name the lanes holding them, so the refusal says + /// what to delete first. The list itself is the report that it worked: the + /// row is gone from it. + fn remove_source(&mut self, path: &Path, stream: usize, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + let removed = self + .session + .as_mut() + .map(|session| session.remove_source(path, stream)); + let text = match removed { + Some(Ok(())) => { + // The picked row may be the one that just went, and the engine + // reseeks, so this owes the flag reset like every other edit. + if self.selected_asset.as_ref() == Some(&(path.to_path_buf(), stream)) { + self.selected_asset = None; + } + self.reset_after_reseek(); + // The undo stack goes with it (`Project::remove_source`): said + // here, because a `z` that does nothing afterwards would + // otherwise read as a bug. + format!( + "REMOVED {} — there is nothing left to undo", + file_name(path) + ) + } + Some(Err(e)) => format!("NOT REMOVED — {e}"), + None => "NO TIMELINE — open a file first".to_string(), + }; + self.notice = Some(text.into()); + cx.notify(); + } + + /// One item of a library row's menu, done. Every one of them closes the + /// menu first -- the list under it is about to be rebuilt -- except the one + /// that turns the card over. + fn act_on_row(&mut self, item: RowItem, cx: &mut Context) { + let Some(menu) = self.library_menu.clone() else { + return; + }; + match item { + RowItem::Properties => { + if let Some(open) = &mut self.library_menu { + open.details = true; + } + } + RowItem::Add => { + self.library_menu = None; + self.insert_source(&menu.path, menu.stream, None, cx); + } + RowItem::Remove => { + self.library_menu = None; + self.remove_source(&menu.path, menu.stream, cx); + } + RowItem::Reveal => { + self.library_menu = None; + // Another process starting: off the UI thread, exactly as the + // export notice's own click starts it. + cx.background_executor() + .spawn(async move { show_in_file_manager(&menu.path) }) + .detach(); + } + } + cx.notify(); + } + /// The rate and layout the whole timeline's audio is, taken from source 0's /// own stream: what a library row has to match to be placeable. `None` /// until that file has been probed, and then nothing is greyed for it. @@ -2130,7 +2317,12 @@ impl Render for Player { // indices -- so a stroke closes it before it acts. Escape means // that and nothing else, which is the `esc` the keys menu // already lists (keymap.rs `FIXED`). - if this.context_menu.take().is_some() { + // Both menus, taken rather than short-circuited: the library's + // one names a row the edits below can remove, so it closes on a + // stroke exactly as the clip menu does. + let clip_menu = this.context_menu.take().is_some(); + let row_menu = this.library_menu.take().is_some(); + if clip_menu || row_menu { cx.notify(); if key == ESCAPE { return; @@ -2307,6 +2499,10 @@ impl Render for Player { // Over the panel it was opened on, and under the cards: it is only // ever up while neither of them is (`modal`). .children(self.context_card(window.viewport_size(), cx)) + // The library's own menu, the same way and for the same reason: + // over the panel it was opened on, under the cards, and never up + // while one of them is. + .children(self.library_card(window.viewport_size(), cx)) // Last, so they are over everything -- they take no room in the // column, and only one of the two is ever up. .children(self.keys_overlay(cx)) @@ -2354,7 +2550,7 @@ impl Player { .as_ref() .is_some_and(|p| *p == (row.path.clone(), row.stream)); let name: SharedString = row.name.clone().into(); - let tip: SharedString = match (&row.unusable, meta) { + let says: String = match (&row.unusable, meta) { // A greyed row says why in full, where its length would be: // the list is the one place the file's own tracks are named. (Some(why), _) => format!("{} — {why}", row.path.display()), @@ -2373,8 +2569,10 @@ impl Player { meta.frame_rate ), (None, None) => row.path.display().to_string(), - } - .into(); + }; + // The menu is the third way into a row, after the click and the + // drag, and a right-click nothing advertises is one nobody finds. + let tip: SharedString = format!("{says} · right-click for more").into(); let ghost = name.clone(); // What the second line says: the stream, then either its length or // the reason it cannot be used. @@ -2388,6 +2586,7 @@ impl Player { let usable = row.unusable.is_none(); let (path, stream) = (row.path.clone(), row.stream); let dragged = (path.clone(), stream); + let menu_path = path.clone(); div() .id(("asset", i)) .flex_none() @@ -2415,6 +2614,33 @@ impl Player { cx.new(|_| Tip(ghost.clone())) }) }) + // The right button hangs the row's own menu at the pointer. + // Every row takes it, greyed ones included: a file that cannot + // join this timeline can still be revealed, described and taken + // out of the list, and Add is the one item that then refuses -- + // in the engine's words, where the row's grey already says why. + .on_mouse_down( + MouseButton::Right, + cx.listener(move |this, event: &MouseDownEvent, _, cx| { + if this.modal() { + return; + } + // Picked as a left-click would pick it, so the row the + // menu is about is the row that reads as chosen -- but + // only a row that *can* be picked, which is what keeps + // the Add button under the list honest. + if usable { + this.selected_asset = Some((menu_path.clone(), stream)); + } + this.library_menu = Some(LibraryMenu { + path: menu_path.clone(), + stream, + at: event.position, + details: false, + }); + cx.notify(); + }), + ) .when(picked, |d| d.bg(rgb(SELECTED)).border_1()) .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into()) // Full height and hard against the edge: the tint reads as @@ -3551,6 +3777,163 @@ impl Player { ) } + /// The menu a right-click on a library row opens: what can be done with the + /// *file* rather than with a clip of it, and a turn-over side saying what + /// that file is. Built like [`Player::context_card`] down to the scrim, the + /// row height and the clamp, because it is the same menu on the other panel + /// -- a click away or any stroke closes it. + fn library_card( + &self, + viewport: Size, + cx: &mut Context, + ) -> Option { + let menu = self.library_menu.clone()?; + let path = menu.path.clone(); + let row = |n: usize| { + div() + .id(("library-menu", n)) + .flex() + .min_h(px(MENU_ROW_H)) + .items_center() + .justify_between() + .gap(px(12.)) + .px(px(6.)) + .rounded(px(3.)) + }; + let mut rows: Vec = Vec::new(); + if menu.details { + // What the library knows about this row and nothing probed for the + // card: the streams table is filled once per file at import. + let info = self + .streams + .get(&path) + .and_then(|of_file| of_file.iter().find(|s| s.index == menu.stream)); + let frames = self + .session + .as_ref() + .map_or(0, |session| session.file_frames(&path)); + // How many clips play from this exact row -- the number that + // decides whether Remove is refused, so the card answers the + // question the refusal would otherwise raise. + let placed = self.session.as_ref().map_or(0, |session| { + let of_row = session + .sources() + .iter() + .position(|s| s.path == path && s.audio_stream == menu.stream); + of_row.map_or(0, |idx| { + session + .lanes() + .into_iter() + .flat_map(|lane| session.lane_clips(lane)) + .filter(|c| c.source == idx) + .count() + }) + }); + for (label, value) in [ + ("File", file_name(&path)), + ("Path", path.display().to_string()), + ( + "Audio", + info.map_or_else(|| "no track of its own".to_string(), stream_detail), + ), + ("Length", timecode(f64::from(frames) / self.fps, self.fps)), + ("On the timeline", format!("{placed} clips")), + ] { + rows.push( + row(rows.len()) + .child(label) + .child( + div() + .min_w(px(0.)) + .truncate() + .text_size(px(11.)) + .text_color(rgb(INK_DIM)) + .child(value), + ) + .into_any_element(), + ); + } + } else { + // Everything but Add works without a timeline open -- and with no + // timeline there are no rows to right-click at all, so this is the + // export guard's shape and not a second policy. + let live = self.session.is_some() && self.exporting().is_none(); + for item in ROW_ITEMS { + let enabled = match item { + RowItem::Add | RowItem::Remove => live, + RowItem::Reveal | RowItem::Properties => true, + }; + rows.push( + row(rows.len()) + .child(item.label()) + .child(div().text_color(rgb(INK_DIM)).child(item.hint())) + .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) + .when(enabled, |d| { + d.cursor_pointer() + .hover(|s| s.bg(rgb(HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.act_on_row(item, cx); + })) + }) + .into_any_element(), + ); + } + } + let (x, y) = menu_at( + menu.at, + viewport, + MENU_PAD * 2. + rows.len() as f32 * MENU_ROW_H, + ); + let full: SharedString = path.display().to_string().into(); + Some( + div() + .absolute() + .inset_0() + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _: &MouseDownEvent, _, cx| { + this.library_menu = None; + cx.notify(); + cx.stop_propagation(); + }), + ) + .on_mouse_down( + MouseButton::Right, + cx.listener(|this, _: &MouseDownEvent, _, cx| { + this.library_menu = None; + cx.notify(); + cx.stop_propagation(); + }), + ) + .child( + div() + .id("library-menu-card") + .absolute() + .left(px(x)) + .top(px(y)) + .w(px(MENU_W)) + .flex() + .flex_col() + .p(px(MENU_PAD)) + .rounded(px(6.)) + .bg(rgb(SURFACE)) + // Painted after the scrim, so this listener runs first + // and a press meant for an item never closes the menu + // out from under its own click (`context_card`). + .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| { + cx.stop_propagation() + }) + .on_mouse_down(MouseButton::Right, |_: &MouseDownEvent, _, cx| { + cx.stop_propagation() + }) + .when(menu.details, |d| { + d.tooltip(move |_, cx| cx.new(|_| Tip(full.clone())).into()) + }) + .children(rows), + ), + ) + } + /// The menu a right-click on a clip opens: what that clip can be given, /// each item beside the stroke that does the very same thing, and a /// turn-over side that says what the clip *is*. An item that would do @@ -4262,6 +4645,10 @@ fn applicable(clip: &Clip, lane: Lane, action: ActionId, playhead: u32) -> bool // at an edge of this clip. Whether those two halves were ever one take // is the engine's question, and it words that refusal itself. ActionId::Regroup => playhead == clip.start || playhead == clip.end(), + // Nothing to take apart in a clip that names no group at all. Whether + // the group it names still has another half is the engine's question, + // like the regroup above, and it words that refusal itself. + ActionId::Detach => clip.link.is_some(), _ => true, } } @@ -4785,20 +5172,57 @@ fn whole_take(session: &PlaybackSession, lane: Lane, idx: usize) -> bool { let Some(clip) = session.lane_clips(lane).get(idx) else { return false; }; - match (lane.kind, lane.ord) { - (_, 1..) => false, - (LaneKind::Video, _) => true, - // The sound of a take, only while the take is still there: its group is - // carried by a clip on some other lane. - (LaneKind::Audio, _) => session + let paired = || { + session .lanes() .into_iter() .filter(|&other| other != lane) .flat_map(|other| session.lane_clips(other)) - .any(|o| o.link.is_some() && o.link == clip.link), + .any(|o| o.link.is_some() && o.link == clip.link) + }; + match (lane.kind, lane.ord) { + (_, 1..) => false, + // The picture of a take -- unless the take has been taken apart: a + // detached picture (a group id no other lane carries, which is also what + // a lift of the sound leaves) is a half like the sound is, and a ripple + // under it would drag away the very half it was detached from. A clip in + // no group at all is not a half but a placement, and on `V1` a placement + // is the take there is. + (LaneKind::Video, _) => clip.link.is_none() || paired(), + // The sound of a take, only while the take is still there: its group is + // carried by a clip on some other lane. + (LaneKind::Audio, _) => paired(), } } +/// The clip a Group would pair this one with: the first clip on another track, +/// in the order the lanes are drawn, covering exactly the same frames and not in +/// this clip's group already. Exactly the same frames because that is all a +/// group id can mean (engine `links_are_consistent`), which is what leaves +/// nothing for a second click to choose. `None` when no track has one, and the +/// notice says so. +fn span_partner(session: &PlaybackSession, lane: Lane, idx: usize) -> Option<(Lane, usize)> { + let clip = *session.lane_clips(lane).get(idx)?; + let matches = |other: Lane| { + let i = session.lane_clips(other).iter().position(|c| { + (c.start, c.end()) == (clip.start, clip.end()) + && !(c.link.is_some() && c.link == clip.link) + })?; + Some((other, i)) + }; + // Sound before picture (and picture before sound): "group this" means the + // other half of the take, and a project whose audio lane was added after a + // second video one has that half *after* the layer in storage order -- which + // is the order the lanes come in. A same-kind lane is still groupable (V1 + // and V2 may be one take), but only where no opposite one covers the span. + let (opposite, same): (Vec, Vec) = session + .lanes() + .into_iter() + .filter(|&other| other != lane) + .partition(|other| other.kind != lane.kind); + opposite.into_iter().chain(same).find_map(matches) +} + /// Whether a click marks this clip: the clip that was clicked always, and the /// other lane's clip of the same group with it. A clip whose group has no other /// half -- what a lift leaves behind -- marks only itself, which is what makes a @@ -5203,8 +5627,8 @@ mod tests { envelope, eq_x, eq_y, export_path, export_settings, format_line, frac_along, frac_down, frame_at, histogram, is_bare_modifier, is_project, keymap, lanes_h, marked, menu_at, mp4_refusal, normalise, panel_h, project_path, push_digit, retarget, scrub_due, show_label, - source_tint, start_frac, timecode, unseen_paths, unseen_sources, whole_take, width_frac, - window_title, + source_tint, span_partner, start_frac, timecode, unseen_paths, unseen_sources, whole_take, + width_frac, window_title, }; use super::{file_name, file_uri, library_rows}; @@ -5497,6 +5921,16 @@ mod tests { assert!(applicable(&clip, v1, ActionId::Regroup, 30)); assert!(applicable(&clip, v1, ActionId::Regroup, 90)); assert!(!applicable(&clip, v1, ActionId::Regroup, 60)); + // Detach is the clip's own business: nothing to take apart in one that + // names no group, and whether the group still has another half is the + // engine's question. Group is offered on every clip, for that reason. + assert!(!applicable(&clip, v1, ActionId::Detach, 0)); + let grouped = Clip { + link: Some(3), + ..clip + }; + assert!(applicable(&grouped, v1, ActionId::Detach, 60)); + assert!(applicable(&clip, a1, ActionId::Group, 0)); // The equalizer is the one item the *lane* decides: it filters samples, // and a video clip has none of its own. Never the playhead's business. assert!(applicable(&clip, a1, ActionId::Equalizer, 0)); @@ -5538,6 +5972,113 @@ mod tests { } } + /// What the Detach and Group items do to a real timeline: a music video's + /// sound comes off its picture, Delete on the loose half takes that half + /// only, undo puts both back, and Group makes the two one take again -- + /// whole-take delete and all. + #[test] + fn a_detached_half_is_removed_alone_and_groups_again() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + assert!(whole_take(&session, Lane::V1, 0), "one take to start with"); + assert!(whole_take(&session, Lane::A1, 0)); + let frames = session.lane_clips(Lane::V1)[0].len(); + + // Detach audio: neither half is a whole take any more, so Delete on + // either leaves the other exactly where it is. + assert!(session.ungroup(Lane::V1, 0)); + assert!( + !whole_take(&session, Lane::A1, 0), + "the sound is a half now" + ); + assert!(!whole_take(&session, Lane::V1, 0), "and so is the picture"); + assert!(session.lift_clip(Lane::A1, 0)); + assert!(session.lane_clips(Lane::A1).is_empty(), "the sound went"); + assert_eq!(session.lane_clips(Lane::V1).len(), 1, "the picture stayed"); + assert_eq!(session.lane_clips(Lane::V1)[0].len(), frames, "untrimmed"); + + // One undo per edit, the removal then the detach. + assert!(session.undo()); + assert_eq!(session.lane_clips(Lane::A1).len(), 1, "the sound is back"); + assert!(session.undo()); + assert!(whole_take(&session, Lane::A1, 0), "one take again"); + + // Group: the partner is the clip covering these very frames on the + // other track, which is what the item hands the engine. + assert!(session.ungroup(Lane::V1, 0)); + assert_eq!(span_partner(&session, Lane::V1, 0), Some((Lane::A1, 0))); + session + .group(Lane::V1, 0, Lane::A1, 0) + .expect("both halves still cover the same frames"); + assert!( + whole_take(&session, Lane::A1, 0), + "a take that ripples again" + ); + assert_eq!( + span_partner(&session, Lane::V1, 0), + None, + "and nothing left on another track to group with" + ); + } + + /// Which clip Group reaches when more than one covers the span: the sound, + /// whatever order the lanes are stored in. A project file may hold them in + /// any order -- a video layer *before* the audio lane among them -- and + /// "group this" means the other half of the take, never the layer above it. + #[test] + fn group_reaches_the_sound_before_a_video_layer_over_it() { + 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); + let path = session.sources()[0].path.clone(); + assert!( + session + .place_stream_at(0.0, &path, 0, Some(v2)) + .expect("its own file is on this timeline"), + "a layer covering the same frames as the take" + ); + + // Saved and loaded back with the lanes in the order a hand-written + // project may hold them: the sound last, behind the layer. + let dir = std::env::temp_dir().join(format!("ve_group_{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("a scratch directory"); + let file = dir.join("lanes.edith"); + session.save_project(&file).expect("save the project"); + let text = std::fs::read_to_string(&file).expect("read it back"); + let (sound, rest): (Vec<&str>, Vec<&str>) = + text.lines().partition(|l| l.starts_with("audio ")); + std::fs::write( + &file, + format!("{}\n{}\n", rest.join("\n"), sound.join("\n")), + ) + .expect("write the reordered project"); + let mut session = PlaybackSession::open_project(&file).expect("it loads as it stands"); + std::fs::remove_dir_all(&dir).ok(); + assert_eq!( + session.lanes(), + vec![Lane::V1, v2, Lane::A1], + "the sound is the last lane there" + ); + + // Detached, so Group has a choice to get wrong: the layer covers these + // frames too, and it is the lane the walk meets first. + assert!(session.ungroup(Lane::V1, 0)); + // Group on the picture reaches the sound, not that layer. + assert_eq!(span_partner(&session, Lane::V1, 0), Some((Lane::A1, 0))); + session + .group(Lane::V1, 0, Lane::A1, 0) + .expect("the two halves cover the same frames"); + // ...and a lane of its own kind is still groupable, once the sound is + // spoken for: two video lanes may be one take. + assert_eq!( + span_partner(&session, Lane::V1, 0), + Some((v2, 0)), + "the layer is what is left to group with" + ); + } + /// The refusal path, end to end against the real files: an incompatible /// import changes nothing, and the library mirrors `sources()` 1:1, so a /// refused file cannot leave a row behind. @@ -5624,6 +6165,61 @@ mod tests { assert_eq!(session.file_frames(&path), frames); } + /// Remove from library, through the door the menu item uses + /// ([`Player::remove_source`] calls exactly this): refused by name while + /// clips play from the file, and once they do not the row leaves the list. + #[test] + fn removing_a_row_is_refused_while_it_plays_and_takes_the_row_away() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + // Imported, then dragged onto the end: an import alone fills the + // library, and a row with no clip is removable without any refusal to + // test. This one has to have a take on the timeline. + session.import(&asset("test_av2.mp4")).expect("av2 matches"); + let second = session.sources()[1].path.clone(); + let end = session.timeline_duration(); + assert!( + session + .place_stream_at(end, &second, 0, None) + .expect("a file just imported is on this timeline") + ); + let streams = HashMap::new(); + let rows = |session: &PlaybackSession| { + library_rows(session.sources(), &streams, None, |_| 0).len() + }; + assert_eq!(rows(&session), 2, "a row per source"); + + let refusal = session + .remove_source(&second, 0) + .expect_err("its take is still on the timeline") + .to_string(); + assert!(refusal.contains("still plays"), "{refusal}"); + assert!( + refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"), + "the refusal names the lanes to clear: {refusal}" + ); + assert_eq!(rows(&session), 2, "and the row is still there"); + + // Delete that take -- the whole group, from either half -- and the file + // can go. The list is what says so. + let last = session.lane_clips(Lane::V1).len() - 1; + assert!(session.delete_clip(Lane::V1, last)); + session + .remove_source(&second, 0) + .expect("nothing plays av2 any more"); + assert_eq!(rows(&session), 1, "the row went with it"); + assert_eq!(session.sources().len(), 1); + // The one file left cannot go: a project that names none is not one + // that reopens. + let refusal = session + .remove_source(&session.sources()[0].path.clone(), 0) + .expect_err("the last file stays") + .to_string(); + assert!(refusal.contains("only file"), "{refusal}"); + // A row this timeline never had is refused, not panicked on. + assert!(session.remove_source(&second, 0).is_err()); + } + /// The trim-a-clip path through the doors the edge drag uses: /// [`Player::trim_to`] clamps the pointer with `trim_room` and /// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less @@ -6853,6 +7449,7 @@ fn main() { ruler: Rc::default(), selected: None, context_menu: None, + library_menu: None, selected_asset: None, waves: HashMap::new(), streams: HashMap::new(), diff --git a/crates/engine/src/playback.rs b/crates/engine/src/playback.rs index c8235af..09a3a52 100644 --- a/crates/engine/src/playback.rs +++ b/crates/engine/src/playback.rs @@ -143,7 +143,8 @@ pub struct PlaybackSession { /// end of a file, which is a save that would not open again /// ([`Self::open_project`] refuses one by name). Append-only for /// `sources`'s reason: an index handed out stays valid, undone import or - /// not. + /// not -- with the single exception `sources` itself has, + /// [`Self::remove_source`], which takes the same entry out of both. counts: Vec, /// What the current video worker was opened for: where it sits on the /// timeline, how long it runs, and which source frame it started at -- @@ -723,6 +724,21 @@ impl PlaybackSession { .regroup(secs_to_frame(timeline_secs, self.meta.frame_rate)) } + /// Takes that clip out of its group, so its picture and its sound are edited + /// apart from here on. Metadata only like a cut -- no reseek -- and one undo + /// step. `false` for a bad index and for a clip that is not grouped with + /// anything, which is already detached. + pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool { + self.project.ungroup(lane, idx) + } + + /// Puts two clips covering the same frames back into one group: the regroup + /// of what [`ungroup`](Self::ungroup) took apart. Metadata only, one undo + /// step, and the error says why when it refuses. + pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> { + self.project.group(a, a_idx, b, b_idx) + } + /// What the clip at `idx` of `lane` is equalized with, or `None` for one /// that plays flat -- what a card shows before it lets anyone drag a band. pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> { @@ -1005,6 +1021,37 @@ impl PlaybackSession { }) } + /// Takes `path` played on `stream` out of the library -- the door a library + /// row's own remove goes through, naming the row exactly as + /// [`place_stream_at`](Self::place_stream_at) does. Refused in + /// [`Project::remove_source`]'s words while a clip still plays from it, and + /// for a row this timeline does not have. + /// + /// Reseeks like an edit even though nothing playable changed: the clip + /// indexes into the source list have just moved, and the running workers + /// were opened against the old numbering. + pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result<()> { + let wanted = Source::new(path, stream); + let idx = self + .project + .sources() + .iter() + .position(|s| *s == wanted) + .ok_or_else(|| format!("{} is not on this timeline", path.display()))?; + self.project.remove_source(idx)?; + // The one thing that shortens the source list, so the one place + // [`Self::counts`] shortens with it: left behind, the gone file's length + // would become the wall a *surviving* source is trimmed against + // ([`trim_room`](Self::trim_room)) and the next import would land its + // count one index late. + if idx < self.counts.len() { + self.counts.remove(idx); + } + let now = self.now(); + self.seek(now); + Ok(()) + } + /// What the timeline's audio *is*: source 0's chosen stream, probed. Every /// other source is held to it. fn first_audio(&self) -> crate::Result> { @@ -1511,7 +1558,67 @@ fn secs_to_frame(secs: f64, fps: f64) -> u32 { #[cfg(test)] mod tests { - use super::secs_to_frame; + use super::{Edge, Lane, PlaybackSession, secs_to_frame}; + use std::path::PathBuf; + + fn asset(name: &str) -> PathBuf { + PathBuf::from(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) + } + + /// The seam between the two lists a source index reaches: dropping a file + /// from the library shortens `sources`, and `counts` -- the frame length + /// per source, which is what a trim is walled by -- has to lose the same + /// entry. Left behind, the dead file's length would wall the survivor. + #[test] + fn removing_a_source_takes_its_frame_count_with_it() { + // Source 0 is 5 s, source 1 is 4 s: two different walls, so a stale + // count cannot pass for the right one. + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + // Imported, then dragged onto the end -- an import alone places nothing + // ([`PlaybackSession::import`]), and this test needs both takes there. + session.import(&asset("test_av2.mp4")).expect("av2 matches"); + let end = session.timeline_duration(); + assert!( + session + .place_stream_at(end, &asset("test_av2.mp4"), 0, None) + .expect("a file just imported is on this timeline") + ); + let (long, short) = (session.counts[0], session.counts[1]); + assert!(long > short, "{long} vs {short}"); + + // Clear source 0's take, then take the file itself out: av2's clip is + // the only one left and it is source 0 now. + assert!(session.delete_clip(Lane::V1, 0)); + session + .remove_source(&asset("test_av.mp4"), 0) + .expect("nothing plays it any more"); + assert_eq!(session.counts, vec![short], "the dead length went with it"); + assert_eq!(session.sources().len(), session.counts.len()); + + // The wall is the surviving file's own length, not the gone one's: a + // whole-file clip cannot be dragged out any further at all. + let clip = session.lane_clips(Lane::V1)[0]; + assert_eq!(clip.len(), short, "av2's take, whole"); + assert_eq!( + session.trim_room(Lane::V1, 0, Edge::End), + Some((clip.start + 1, clip.end())) + ); + assert!( + !session.trim_clip(Lane::V1, 0, Edge::End, clip.end() + 30), + "past the file's last frame is refused, by ITS length" + ); + + // ...and the next import still lines the two lists up, which is the + // alignment `note_frames` asserts on. + session + .import(&asset("test_av.mp4")) + .expect("it may come back"); + assert_eq!(session.counts, vec![short, long]); + assert_eq!(session.sources().len(), session.counts.len()); + } #[test] fn boundary_seconds_round_trip_to_their_own_frame() { diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 9752f56..231d989 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -524,6 +524,60 @@ impl Project { true } + /// Drops a source entry -- the file a library row *is* -- and renumbers + /// every clip that indexed past it, which is why this is more than a + /// `Vec::remove`. + /// + /// Refused, changing nothing, while any clip still plays from it: the + /// refusal names the lanes and how many clips each holds, so a caller can + /// say what has to be deleted first. Refused too for the last entry left, + /// because a project that names no file cannot be reopened + /// (`PlaybackSession::open_project`) and the timeline's audio parameters + /// are read off source 0. + /// + /// ponytail: this retires the undo stack. `history` holds lanes alone, so a + /// snapshot older than the removal can name the very source being removed + /// (delete a file's clips, then remove the file) and restoring it would + /// point a clip at an entry that is gone. The upgrade path is snapshotting + /// `sources` beside `lanes` in [`snapshot`](Project::snapshot) -- which the + /// "indexes are forever" rule ([`append_clip`](Project::append_clip), and + /// the reason [`without_orphan_sources`](Project::without_orphan_sources) + /// exists) currently rules out. + pub fn remove_source(&mut self, idx: usize) -> crate::Result<()> { + let Some(source) = self.sources.get(idx) else { + return Err(format!("there is no source {idx} to remove").into()); + }; + let name = source.path.display().to_string(); + // Asked before the clips are counted: with one file left the answer is + // the same whatever plays, and "the only file" is the more useful half + // of it. + if self.sources.len() == 1 { + return Err(format!("{name} is the only file this project names").into()); + } + let used: Vec = handles(&self.lanes) + .into_iter() + .zip(&self.lanes) + .filter_map( + |(lane, data)| match data.clips.iter().filter(|c| c.source == idx).count() { + 0 => None, + 1 => Some(format!("{} (1 clip)", lane.label())), + n => Some(format!("{} ({n} clips)", lane.label())), + }, + ) + .collect(); + if !used.is_empty() { + return Err(format!("{name} still plays on {}", used.join(", ")).into()); + } + self.sources.remove(idx); + for c in self.lanes.iter_mut().flat_map(|l| &mut l.clips) { + if c.source > idx { + c.source -= 1; + } + } + self.history.clear(); + Ok(()) + } + /// The sources a clip actually names, with the clips reindexed onto them /// -- what a save writes. Indexes are forever *inside* a session (see /// [`Project::append_clip`]), so an undone import leaves an orphan source @@ -1002,6 +1056,115 @@ impl Project { true } + /// Take the clip at `idx` of `lane` out of its group: every clip carrying + /// its id -- on however many lanes -- is handed an id of its own, so from + /// here on each half moves, trims and is deleted alone. The music video + /// whose sound is to be cut against its picture starts here. + /// + /// An id of its own rather than none at all: a half no other lane is grouped + /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal + /// (see [`links_are_consistent`]), and it is what a front-end already draws + /// as detached. `None` would instead say "was never part of a take", which + /// is what a one-lane [`place`](Project::place) means. + /// + /// Metadata only, like a [`split`](Project::split): no mapping changes, so + /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts + /// the group back. Refused (`false`, nothing changed) for an index that is + /// not there, a clip in no group at all, and one whose group has no other + /// half -- that one is already detached, and a refusal must not cost an undo + /// step. + pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool { + let Some(id) = self.lane(lane).get(idx).and_then(|c| c.link) else { + return false; + }; + let members = self + .lanes + .iter() + .flat_map(|l| &l.clips) + .filter(|c| c.link == Some(id)) + .count(); + if members < 2 { + return false; + } + self.snapshot(); + // Drawn before the walk: `new_link` takes the whole project, and the + // walk holds the lanes. + let mut fresh = (0..members).map(|_| self.new_link()).collect::>(); + for data in &mut self.lanes { + for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) { + c.link = fresh.pop(); + } + } + debug_assert!(links_are_consistent(&self.lanes).is_ok()); + true + } + + /// Put two clips on two lanes into one group, so what moves one moves the + /// other again -- the undo of a [`ungroup`](Project::ungroup) by hand, and + /// how a picture is regrouped with sound it was never opened with. Whatever + /// either of them was grouped with comes along: those clips cover this same + /// span already, so the result is one group and not two overlapping ones. + /// + /// Same frames or nothing: a group id names **one span** on however many + /// lanes ([`links_are_consistent`] refuses to load anything else), so two + /// clips that do not cover the same frames cannot be one take, and the + /// refusal says which bounds to trim to. Kinds are *not* checked: a take may + /// run on `V1` and `V2` at once, and picture-with-sound is the case people + /// mean, not the rule. + /// + /// Metadata only, one snapshot. The error says what is wrong, because + /// `false` would not: a bad index, one lane twice (a group is at most one + /// clip per lane), spans that disagree, and a pair that is already one take + /// -- nothing changes, and none of them costs an undo step. + pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> { + if a == b { + return Err(format!( + "a group is one clip per lane: pick the clip to group with on another track, not a second one on {}", + a.label() + ) + .into()); + } + let clip = |p: &Self, lane: Lane, idx: usize| -> crate::Result { + p.lane(lane) + .get(idx) + .copied() + .ok_or_else(|| format!("there is no clip {idx} on {}", lane.label()).into()) + }; + let (x, y) = (clip(self, a, a_idx)?, clip(self, b, b_idx)?); + if (x.start, x.end()) != (y.start, y.end()) { + return Err(format!( + "{} covers [{}, {}) and {} covers [{}, {}): trim them to matching bounds first", + a.label(), + x.start, + x.end(), + b.label(), + y.start, + y.end() + ) + .into()); + } + if x.link.is_some() && x.link == y.link { + return Err("those two are one take already".into()); + } + self.snapshot(); + let id = self.new_link(); + // Every clip either of them was grouped with, by the same rule: all of + // them cover this span, so one id over the lot stays consistent. + let old = [x.link, y.link]; + for data in &mut self.lanes { + for c in data.clips.iter_mut().filter(|c| c.link.is_some()) { + if old.contains(&c.link) { + c.link = Some(id); + } + } + } + // And the two themselves, which a `place` may have left in no group. + self.lane_mut(a).expect("read above")[a_idx].link = Some(id); + self.lane_mut(b).expect("read above")[b_idx].link = Some(id); + debug_assert!(links_are_consistent(&self.lanes).is_ok()); + Ok(()) + } + /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it /// lands on and leaving every other clip exactly where it is -- the /// per-lane paste. Anything already there is trimmed away (and split in two @@ -1841,6 +2004,103 @@ mod tests { ); } + /// The music video's own path: the take comes apart into halves that carry + /// ids of their own, one undo puts it back, and two clips over the same + /// frames become one take again by hand. + #[test] + fn a_take_comes_apart_and_goes_back_together() { + let mut p = Project::single(FILE, 9); + let one = p.clips()[0].link.expect("a fresh project is one take"); + assert_eq!(p.lane(Lane::A1)[0].link, Some(one)); + + // A third lane in the same group -- and the merge case with it: a + // placement is in no group, and grouping it in leaves *one* group. + let v2 = p.add_lane(LaneKind::Video); + assert!(p.place(v2, 0, clip(0, 0, 9, 0))); + assert!(p.lane(v2)[0].link.is_none(), "a placement joins no group"); + p.group(Lane::V1, 0, v2, 0) + .expect("the same frames, one lane over"); + let id = p.clips()[0].link.expect("still a group"); + assert!( + p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)), + "one id over the three, not two groups sharing a span" + ); + links_are_consistent(&p.lanes).expect("one id, one span"); + + // Detached by the sound: every half of the group, not only the two. + assert!(p.ungroup(Lane::A1, 0)); + let ids: Vec> = p.lanes().into_iter().map(|l| p.lane(l)[0].link).collect(); + assert!( + ids.iter().all(Option::is_some), + "a half keeps an id of its own" + ); + assert!( + ids.iter() + .enumerate() + .all(|(i, a)| ids[..i].iter().all(|b| a != b)), + "and no two halves are the same group any more: {ids:?}" + ); + links_are_consistent(&p.lanes).expect("a lone id is legal"); + + // One snapshot for the whole detach. + assert!(p.undo()); + assert!( + p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)), + "one undo puts the whole group back" + ); + + // And back together by hand: the two the pointer named, and only them. + assert!(p.ungroup(Lane::V1, 0)); + p.group(Lane::V1, 0, Lane::A1, 0) + .expect("both cover [0, 9)"); + assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link); + assert_ne!( + p.lane(v2)[0].link, + p.lane(Lane::V1)[0].link, + "the third half stayed detached" + ); + links_are_consistent(&p.lanes).expect("one id, one span"); + } + + /// What a group may not be, and what a detach has nothing to take apart -- + /// none of which may cost an undo step. + #[test] + fn a_group_is_one_span_and_one_clip_per_lane() { + let mut p = three(); + let before = shape(&p); + let why = |r: crate::Result<()>| r.expect_err("refused").to_string(); + + assert!( + why(p.group(Lane::V1, 0, Lane::V1, 1)).contains("one clip per lane"), + "two clips of one lane are never one take" + ); + assert!(why(p.group(Lane::V1, 0, Lane::A1, 9)).contains("there is no clip 9 on A1")); + let spans = why(p.group(Lane::V1, 0, Lane::A1, 1)); + assert!( + spans.contains("V1 covers [0, 3) and A1 covers [3, 5)"), + "{spans}" + ); + assert!( + spans.contains("trim them to matching bounds first"), + "{spans}" + ); + assert!(why(p.group(Lane::V1, 0, Lane::A1, 0)).contains("one take already")); + + // A half nothing else is grouped with is already detached, a placement + // is in no group at all, and an index that is not there has nothing to + // detach either. + assert!(p.place(Lane::V1, 20, clip(20, 0, 3, 0))); + assert!(!p.ungroup(Lane::V1, 3), "a placement is in no group"); + assert!(p.lift(Lane::A1, 0)); + assert!(!p.ungroup(Lane::V1, 0), "its group has no other half"); + assert!(!p.ungroup(Lane::V1, 9), "no clip there"); + + // Two undos, one per edit: not one of the refusals pushed a snapshot. + assert!(p.undo()); + assert!(p.undo()); + assert_eq!(shape(&p), before); + } + #[test] fn split_refused_at_zero_boundary_end_and_in_a_gap() { let mut p = three(); @@ -2699,6 +2959,87 @@ mod tests { assert_eq!(reloaded.sources().len(), 2); } + /// Taking a file out of the library: refused by name -- lanes and counts -- + /// while a clip still plays from it, and once nothing does, the entry goes + /// and every clip that indexed past it is renumbered onto the short list. + #[test] + fn remove_source_refuses_what_plays_and_renumbers_what_is_left() { + // Sources 0 (FILE, three clips) and 1 (FILE2, one take on both lanes), + // plus a second stream of FILE as source 2 with a take of its own. + let mut p = two_sources(); + assert_eq!(p.import(FILE, 1), 2, "another stream is another source"); + assert!(p.append_clip(2, 4)); + + let refusal = p + .remove_source(1) + .expect_err("a source with clips on it cannot go") + .to_string(); + assert!(refusal.contains(FILE2), "names the file: {refusal}"); + assert!( + refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"), + "names the lanes holding it: {refusal}" + ); + assert!(refusal.contains("still plays"), "{refusal}"); + assert_eq!(p.sources().len(), 3, "a refusal changes nothing"); + assert_eq!(shape(&p)[0][3].source, 1); + + // Delete FILE2's take -- the whole span, on every lane -- and the entry + // is free to go. Source 2's clips become source 1's. + assert!(p.delete_in(Lane::V1, 3)); + assert!(!p.clips().iter().any(|c| c.source == 1), "nothing plays it"); + p.remove_source(1).expect("nothing plays FILE2 any more"); + assert_eq!( + p.sources(), + [Source::new(FILE, 0), Source::new(FILE, 1)], + "the middle entry is gone" + ); + assert_eq!( + shape(&p)[0].iter().map(|c| c.source).collect::>(), + [0, 0, 0, 1], + "the clips past it renumbered" + ); + assert_eq!( + shape(&p)[1].iter().map(|c| c.source).collect::>(), + [0, 0, 0, 1], + "on every lane" + ); + // What is left is a project that still loads, which is the whole point + // of renumbering rather than leaving a hole. + let (sources, lanes, eq, color) = p.without_orphan_sources(); + Project::from_parts(sources, lanes, eq, color).expect("from_parts"); + } + + /// The two edges of a removal: it retires the undo stack (the ponytail on + /// [`Project::remove_source`]), and the last entry standing cannot go -- + /// source 0 is where a reopened project reads its frame rate. + #[test] + fn remove_source_retires_undo_and_keeps_the_last_file() { + let mut p = two_sources(); + assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first"); + assert!(!p.history.is_empty(), "there is something to undo"); + p.remove_source(1).expect("nothing plays FILE2"); + assert!( + p.history.is_empty(), + "a snapshot naming the removed source must not survive it" + ); + assert!(!p.undo(), "and so there is nothing left to undo"); + + // The last file standing stays, whatever plays from it: + // `PlaybackSession::open_project` refuses a project that names no + // sources at all, and the timeline's frame rate lives in source 0. + assert_eq!(p.sources().len(), 1); + let refusal = p + .remove_source(0) + .expect_err("the only source must stay") + .to_string(); + assert!(refusal.contains("only file"), "{refusal}"); + assert_eq!(p.sources().len(), 1); + assert!( + p.remove_source(1).is_err(), + "and an index that is not there is refused, not panicked on" + ); + } + /// A clip's equalizer is the clip's: it survives every edit that copies a /// placement, and it comes back with an undo. #[test] diff --git a/crates/engine/tests/audio_files.rs b/crates/engine/tests/audio_files.rs index 9146981..8169baf 100644 --- a/crates/engine/tests/audio_files.rs +++ b/crates/engine/tests/audio_files.rs @@ -322,6 +322,60 @@ fn an_audio_only_project_saves_reloads_and_exports_its_sound() { let _ = std::fs::remove_dir_all(&dir); } +/// A *song* as the first import into an empty window: `open_library` takes the +/// audio-only fork of `open` (there is no picture to scaffold a canvas from) and +/// still leaves the timeline empty. The row is there at the song's own length, +/// the canvas and the clock a song would have set are set, and the drag that +/// follows is what makes it play. +#[test] +fn the_first_import_of_a_song_opens_a_library_over_an_empty_timeline() { + let mp3 = asset("test_tone.mp3"); + let mut session = PlaybackSession::open_library(&mp3).expect("open into the library"); + session.set_gain(0.0); + assert!(session.is_empty(), "the timeline must start empty"); + assert_eq!(session.timeline_duration(), 0.0); + assert!(session.lane_clips(Lane::A1).is_empty(), "nothing placed"); + assert!(session.lane_clips(Lane::V1).is_empty(), "no picture either"); + // The canvas a song scaffolds, and the clock that goes with it -- a session + // with an empty timeline is still this file's session. + let meta = *session.meta(); + assert_eq!((meta.width, meta.height), (1920, 1080), "the song canvas"); + assert_eq!(meta.frame_rate, 30.0); + assert_eq!(session.sources().len(), 1, "the library row"); + assert_eq!(session.file_frames(&mp3), 90, "3 s at 30 fps, never placed"); + assert!(!session.undo(), "opening a library is not an undo step"); + // A file this session never took in has no length and cannot be placed. + assert_eq!(session.file_frames(&asset("test_tone.flac")), 0); + assert_eq!( + refusal(session.place_stream_at(0.0, &asset("test_tone.flac"), 0, None)), + format!( + "{} is not on this timeline", + asset("test_tone.flac").display() + ) + ); + + // The drag: onto the audio lane and nowhere else, at the song's own length. + assert!( + session + .place_stream_at(0.0, &mp3, 0, None) + .expect("its own file is on this timeline") + ); + assert!(!session.is_empty()); + assert!((session.timeline_duration() - 3.0).abs() < 0.05); + assert_eq!(session.lane_clips(Lane::A1).len(), 1); + assert!(session.lane_clips(Lane::V1).is_empty(), "still no picture"); + let clip = session.lane_clips(Lane::A1)[0]; + assert_eq!((clip.source, clip.in_frame, clip.len()), (0, 0, 90)); + // And it plays: the segment list names the song, so the worker opens it + // rather than running silent. + session.seek(1.0); + assert!(!session.lane_spans_by_source(Lane::A1).is_empty()); + // One `z` takes the drag back to the empty timeline, row and all. + assert!(session.undo(), "undo the drag"); + assert!(session.is_empty()); + assert_eq!(session.sources().len(), 1, "the row survives the undo"); +} + /// The other half of the door: a *video* joining a timeline a song scaffolded. /// It is held to the canvas the song set (H.264, 30 fps), so a matching file /// brings its picture in -- and the timeline stops being audio-only, mp4 export