forge
Explore
Log in

Don't you dare go Hollow

🔀 merge(import): library-only import meets the library row menu

Browse files at this commit

b5141872ca60df8ac80c87e40fbeb3807de31333Ahmet Kaan GümüşParent: 5cb33d85f60e19
The row menu (C3) and the source lengths this branch made native meet in one
place: the card's Length line and its "plays in N clips" count now read the
engine's own `file_frames` and walk `session.lanes()`, since the app's
clips-derived length helper and its free `lane_clips` walker are gone.

Two tests assumed an import that places: `removing_a_source_takes_its_frame_
count_with_it` and `removing_a_row_is_refused_while_it_plays_and_takes_the_
row_away` both need a take on the timeline to have something to refuse, so
each drags its import onto the end first.

New coverage: the audio fork of `open_library` -- a song as the first import
into an empty window. Empty timeline over the 1920x1080@30 song canvas, the
row at its own 90 frames, not undoable, a file it never took in refused by
name, and the drag that follows plays it on A1 alone.
crates/app/src/keymap.rsmodified+23 -4
@@ -53,6 +53,8 @@ pub enum ActionId {
53 Paste,53 Paste,
54 Cut,54 Cut,
55 Regroup,55 Regroup,
56+ Detach,
57+ Group,
56 Select,58 Select,
57 SelectNext,59 SelectNext,
58 SelectPrev,60 SelectPrev,
@@ -74,7 +76,7 @@ pub enum ActionId {
74 impl ActionId {76 impl ActionId {
75 /// Display order everywhere -- the editor lists them in it and77 /// Display order everywhere -- the editor lists them in it and
76 /// [`Keymap::defaults`] binds them in it.78 /// [`Keymap::defaults`] binds them in it.
77- pub const ALL: [ActionId; 29] = [79+ pub const ALL: [ActionId; 31] = [
78 ActionId::Play,80 ActionId::Play,
79 ActionId::StepBack,81 ActionId::StepBack,
80 ActionId::StepForward,82 ActionId::StepForward,
@@ -88,6 +90,8 @@ impl ActionId {
88 ActionId::Paste,90 ActionId::Paste,
89 ActionId::Cut,91 ActionId::Cut,
90 ActionId::Regroup,92 ActionId::Regroup,
93+ ActionId::Detach,
94+ ActionId::Group,
91 ActionId::Select,95 ActionId::Select,
92 ActionId::SelectNext,96 ActionId::SelectNext,
93 ActionId::SelectPrev,97 ActionId::SelectPrev,
@@ -122,6 +126,8 @@ impl ActionId {
122 ActionId::Paste => "Paste",126 ActionId::Paste => "Paste",
123 ActionId::Cut => "Cut",127 ActionId::Cut => "Cut",
124 ActionId::Regroup => "Regroup",128 ActionId::Regroup => "Regroup",
129+ ActionId::Detach => "Detach the sound from the picture",
130+ ActionId::Group => "Group with the clip on another track",
125 ActionId::Select => "Select the clip under the playhead (again for the next lane)",131 ActionId::Select => "Select the clip under the playhead (again for the next lane)",
126 ActionId::SelectNext => "Select the next clip in the lane",132 ActionId::SelectNext => "Select the next clip in the lane",
127 ActionId::SelectPrev => "Select the previous clip in the lane",133 ActionId::SelectPrev => "Select the previous clip in the lane",
@@ -158,6 +164,8 @@ impl ActionId {
158 ActionId::Paste => "paste",164 ActionId::Paste => "paste",
159 ActionId::Cut => "cut",165 ActionId::Cut => "cut",
160 ActionId::Regroup => "regroup",166 ActionId::Regroup => "regroup",
167+ ActionId::Detach => "detach",
168+ ActionId::Group => "group",
161 ActionId::Select => "select",169 ActionId::Select => "select",
162 ActionId::SelectNext => "select-next",170 ActionId::SelectNext => "select-next",
163 ActionId::SelectPrev => "select-prev",171 ActionId::SelectPrev => "select-prev",
@@ -207,6 +215,8 @@ impl ActionId {
207 ActionId::Resolution => Category::View,215 ActionId::Resolution => Category::View,
208 ActionId::Cut216 ActionId::Cut
209 | ActionId::Regroup217 | ActionId::Regroup
218+ | ActionId::Detach
219+ | ActionId::Group
210 | ActionId::Undo220 | ActionId::Undo
211 | ActionId::AddVideoLane221 | ActionId::AddVideoLane
212 | ActionId::AddAudioLane => Category::Editing,222 | ActionId::AddAudioLane => Category::Editing,
@@ -268,7 +278,7 @@ pub struct Fixed {
268 pub const FIXED: [Fixed; 12] = [278 pub const FIXED: [Fixed; 12] = [
269 Fixed {279 Fixed {
270 chord: "esc",280 chord: "esc",
271- label: "Close this card or clip menu, or cancel a capture",281+ label: "Close this card or menu, or cancel a capture",
272 category: Category::View,282 category: Category::View,
273 },283 },
274 Fixed {284 Fixed {
@@ -453,6 +463,12 @@ impl Keymap {
453 // The two lane keys, on the letters they are named after: both463 // The two lane keys, on the letters they are named after: both
454 // were free, and neither is next to a key that edits.464 // were free, and neither is next to a key that edits.
455 b(ActionId::Regroup, "g", false),465 b(ActionId::Regroup, "g", false),
466+ // The pair that takes a take apart and puts it back: "d" for
467+ // detach was free and is one press like the rest of the clip
468+ // keys, and grouping two clips is the "g" that rejoins a cut one
469+ // lane over -- the chord beside it, so the two read as one idea.
470+ b(ActionId::Detach, "d", false),
471+ b(ActionId::Group, "g", true),
456 // Selection without a pointer. Tab is what a keyboard already472 // Selection without a pointer. Tab is what a keyboard already
457 // means by "move on to the next thing", and the two brackets473 // means by "move on to the next thing", and the two brackets
458 // are the pair either side of it in the lane -- shift+tab is474 // are the pair either side of it in the lane -- shift+tab is
@@ -753,7 +769,7 @@ mod tests {
753 #[test]769 #[test]
754 fn every_default_stroke_reaches_its_action() {770 fn every_default_stroke_reaches_its_action() {
755 let k = Keymap::defaults();771 let k = Keymap::defaults();
756- assert_eq!(k.entries().len(), 31);772+ assert_eq!(k.entries().len(), 33);
757 assert_eq!(k.lookup("space", false), Some(ActionId::Play));773 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
758 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two774 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two
759 // ends of the timeline.775 // ends of the timeline.
@@ -769,6 +785,9 @@ mod tests {
769 assert_eq!(k.lookup("v", true), Some(ActionId::Paste));785 assert_eq!(k.lookup("v", true), Some(ActionId::Paste));
770 assert_eq!(k.lookup("c", false), Some(ActionId::Cut));786 assert_eq!(k.lookup("c", false), Some(ActionId::Cut));
771 assert_eq!(k.lookup("g", false), Some(ActionId::Regroup));787 assert_eq!(k.lookup("g", false), Some(ActionId::Regroup));
788+ // The take apart / put back pair beside it.
789+ assert_eq!(k.lookup("d", false), Some(ActionId::Detach));
790+ assert_eq!(k.lookup("g", true), Some(ActionId::Group));
772 // The keyboard's way onto a clip, and the pair that walks the lane.791 // The keyboard's way onto a clip, and the pair that walks the lane.
773 assert_eq!(k.lookup("tab", false), Some(ActionId::Select));792 assert_eq!(k.lookup("tab", false), Some(ActionId::Select));
774 assert_eq!(k.lookup("]", false), Some(ActionId::SelectNext));793 assert_eq!(k.lookup("]", false), Some(ActionId::SelectNext));
@@ -977,7 +996,7 @@ mod tests {
977 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");996 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");
978 // The label is the editor's column, and never the file's word for it.997 // The label is the editor's column, and never the file's word for it.
979 assert_eq!(ActionId::CancelExport.label(), "Cancel export");998 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
980- assert_eq!(ActionId::ALL.len(), 29);999+ assert_eq!(ActionId::ALL.len(), 31);
981 }1000 }
982 1001
983 #[test]1002 #[test]
crates/app/src/main.rsmodified+611 -14
@@ -254,15 +254,70 @@ struct ContextMenu {
254 details: bool,254 details: bool,
255 }255 }
256 256
257+/// An open library menu: which row it was opened on -- the file and the stream,
258+/// the pair [`Player::selected_asset`] holds, so a list rebuilt under it (a
259+/// probe landing, a source going) cannot slide another row beneath the menu the
260+/// way a row *index* would -- where it hangs, and whether it has been turned
261+/// over to show what the file *is*.
262+#[derive(Clone)]
263+struct LibraryMenu {
264+ path: PathBuf,
265+ stream: usize,
266+ at: Point<Pixels>,
267+ details: bool,
268+}
269+
270+/// What a library row's menu offers, in the order it lists them. Unlike the clip
271+/// menu's items none of these is a stroke -- there is no keyboard way to a row --
272+/// so the label and the hint are written here rather than read off the keymap.
273+#[derive(Clone, Copy, PartialEq)]
274+enum RowItem {
275+ Add,
276+ Remove,
277+ Reveal,
278+ Properties,
279+}
280+
281+const ROW_ITEMS: [RowItem; 4] = [
282+ RowItem::Add,
283+ RowItem::Remove,
284+ RowItem::Reveal,
285+ RowItem::Properties,
286+];
287+
288+impl RowItem {
289+ fn label(self) -> &'static str {
290+ match self {
291+ Self::Add => "Add at playhead",
292+ Self::Remove => "Remove from library",
293+ Self::Reveal => "Reveal in files",
294+ Self::Properties => "Properties",
295+ }
296+ }
297+
298+ /// The dim right-hand column, where the clip menu prints the stroke: what
299+ /// the item will do to the timeline, so nothing here is a surprise.
300+ fn hint(self) -> &'static str {
301+ match self {
302+ Self::Add => "inserts the whole file",
303+ Self::Remove => "only if nothing plays it",
304+ Self::Reveal => "file manager",
305+ Self::Properties => "…",
306+ }
307+ }
308+}
309+
257 /// What the menu offers, in the order it lists them. Every one of these is an310 /// What the menu offers, in the order it lists them. Every one of these is an
258 /// action a stroke already reaches -- the menu is a second way *to* the actions311 /// action a stroke already reaches -- the menu is a second way *to* the actions
259 /// and never a second version of them -- so both the label and the hint come312 /// and never a second version of them -- so both the label and the hint come
260 /// out of the keymap registry and the two can never disagree.313 /// out of the keymap registry and the two can never disagree.
261-const MENU_ITEMS: [ActionId; 8] = [314+const MENU_ITEMS: [ActionId; 10] = [
262 ActionId::Cut,315 ActionId::Cut,
263 ActionId::Delete,316 ActionId::Delete,
264 ActionId::Lift,317 ActionId::Lift,
265 ActionId::Regroup,318 ActionId::Regroup,
319+ ActionId::Detach,
320+ ActionId::Group,
266 ActionId::Equalizer,321 ActionId::Equalizer,
267 ActionId::Color,322 ActionId::Color,
268 ActionId::Fit,323 ActionId::Fit,
@@ -385,6 +440,10 @@ struct Player {
385 /// `selected` does, so it is closed by anything that can move indices --440 /// `selected` does, so it is closed by anything that can move indices --
386 /// every stroke, and every item of its own.441 /// every stroke, and every item of its own.
387 context_menu: Option<ContextMenu>,442 context_menu: Option<ContextMenu>,
443+ /// The library menu a right-click on a row opened, if one is up. Names its
444+ /// row by file and stream rather than by position, so it acts on the row it
445+ /// was opened on however the list is rebuilt under it.
446+ library_menu: Option<LibraryMenu>,
388 /// Which library row is picked: the file and the audio stream that row447 /// Which library row is picked: the file and the audio stream that row
389 /// names, which is what an insert needs and what survives a row list being448 /// names, which is what an insert needs and what survives a row list being
390 /// rebuilt. Its own selection and not the timeline's: Delete keeps acting449 /// rebuilt. Its own selection and not the timeline's: Delete keeps acting
@@ -626,6 +685,8 @@ impl Player {
626 ActionId::Paste => self.paste(cx),685 ActionId::Paste => self.paste(cx),
627 ActionId::Cut => self.cut(cx),686 ActionId::Cut => self.cut(cx),
628 ActionId::Regroup => self.regroup(cx),687 ActionId::Regroup => self.regroup(cx),
688+ ActionId::Detach => self.detach(cx),
689+ ActionId::Group => self.group(cx),
629 ActionId::Select => self.select_under_playhead(cx),690 ActionId::Select => self.select_under_playhead(cx),
630 ActionId::SelectNext => self.select_step(true, cx),691 ActionId::SelectNext => self.select_step(true, cx),
631 ActionId::SelectPrev => self.select_step(false, cx),692 ActionId::SelectPrev => self.select_step(false, cx),
@@ -1084,6 +1145,63 @@ impl Player {
1084 cx.notify();1145 cx.notify();
1085 }1146 }
1086 1147
1148+ /// Takes the selected clip out of its group, so the picture and the sound
1149+ /// under it are edited apart from here on: each half selects, moves, trims
1150+ /// and is removed alone, and both draw outlined instead of tinted. The
1151+ /// selection stays -- the half that was clicked is still the half in hand.
1152+ fn detach(&mut self, cx: &mut Context<Self>) {
1153+ if self.exporting().is_some() {
1154+ return;
1155+ }
1156+ match (&mut self.session, self.selected) {
1157+ (Some(session), Some((lane, idx))) => {
1158+ if !session.ungroup(lane, idx) {
1159+ self.notice =
1160+ Some("NOTHING DETACHED — that clip is not grouped with another".into());
1161+ }
1162+ }
1163+ (Some(_), None) => {
1164+ self.notice = Some("NOTHING DETACHED — click the take to take apart first".into())
1165+ }
1166+ (None, _) => {}
1167+ }
1168+ cx.notify();
1169+ }
1170+
1171+ /// Puts the selected clip back in a group with the clip covering exactly the
1172+ /// same frames on another track -- the way back from [`Player::detach`], and
1173+ /// the way to group a picture with sound it was never opened with. The
1174+ /// partner is not clicked because there is nothing to choose: a group id
1175+ /// names one span, so only a clip covering these very frames could join it,
1176+ /// and the engine words what to do when none does.
1177+ fn group(&mut self, cx: &mut Context<Self>) {
1178+ if self.exporting().is_some() {
1179+ return;
1180+ }
1181+ let partner = match (&self.session, self.selected) {
1182+ (Some(session), Some((lane, idx))) => span_partner(session, lane, idx),
1183+ _ => None,
1184+ };
1185+ match (&mut self.session, self.selected, partner) {
1186+ (Some(session), Some((lane, idx)), Some((other, o_idx))) => {
1187+ if let Err(e) = session.group(lane, idx, other, o_idx) {
1188+ self.notice = Some(format!("NOT GROUPED — {e}").into());
1189+ }
1190+ }
1191+ (Some(_), Some(_), None) => {
1192+ self.notice = Some(
1193+ "NOTHING TO GROUP WITH — no clip on another track covers exactly these frames"
1194+ .into(),
1195+ )
1196+ }
1197+ (Some(_), None, _) => {
1198+ self.notice = Some("NOTHING GROUPED — click one of the halves first".into())
1199+ }
1200+ (None, ..) => {}
1201+ }
1202+ cx.notify();
1203+ }
1204+
1087 /// Drops the selected clip and closes the hole: a whole take goes, both1205 /// Drops the selected clip and closes the hole: a whole take goes, both
1088 /// lanes of it, and everything after it moves up. A half with no take under1206 /// lanes of it, and everything after it moves up. A half with no take under
1089 /// it in the video lane -- what a lift leaves behind -- has nothing to1207 /// it in the video lane -- what a lift leaves behind -- has nothing to
@@ -1469,6 +1587,75 @@ impl Player {
1469 cx.notify();1587 cx.notify();
1470 }1588 }
1471 1589
1590+ /// Takes a library row's file out of the list, which is the one thing a row
1591+ /// can lose. Refused in the engine's own words while clips still play from
1592+ /// it -- and those words name the lanes holding them, so the refusal says
1593+ /// what to delete first. The list itself is the report that it worked: the
1594+ /// row is gone from it.
1595+ fn remove_source(&mut self, path: &Path, stream: usize, cx: &mut Context<Self>) {
1596+ if self.exporting().is_some() {
1597+ return;
1598+ }
1599+ let removed = self
1600+ .session
1601+ .as_mut()
1602+ .map(|session| session.remove_source(path, stream));
1603+ let text = match removed {
1604+ Some(Ok(())) => {
1605+ // The picked row may be the one that just went, and the engine
1606+ // reseeks, so this owes the flag reset like every other edit.
1607+ if self.selected_asset.as_ref() == Some(&(path.to_path_buf(), stream)) {
1608+ self.selected_asset = None;
1609+ }
1610+ self.reset_after_reseek();
1611+ // The undo stack goes with it (`Project::remove_source`): said
1612+ // here, because a `z` that does nothing afterwards would
1613+ // otherwise read as a bug.
1614+ format!(
1615+ "REMOVED {} — there is nothing left to undo",
1616+ file_name(path)
1617+ )
1618+ }
1619+ Some(Err(e)) => format!("NOT REMOVED — {e}"),
1620+ None => "NO TIMELINE — open a file first".to_string(),
1621+ };
1622+ self.notice = Some(text.into());
1623+ cx.notify();
1624+ }
1625+
1626+ /// One item of a library row's menu, done. Every one of them closes the
1627+ /// menu first -- the list under it is about to be rebuilt -- except the one
1628+ /// that turns the card over.
1629+ fn act_on_row(&mut self, item: RowItem, cx: &mut Context<Self>) {
1630+ let Some(menu) = self.library_menu.clone() else {
1631+ return;
1632+ };
1633+ match item {
1634+ RowItem::Properties => {
1635+ if let Some(open) = &mut self.library_menu {
1636+ open.details = true;
1637+ }
1638+ }
1639+ RowItem::Add => {
1640+ self.library_menu = None;
1641+ self.insert_source(&menu.path, menu.stream, None, cx);
1642+ }
1643+ RowItem::Remove => {
1644+ self.library_menu = None;
1645+ self.remove_source(&menu.path, menu.stream, cx);
1646+ }
1647+ RowItem::Reveal => {
1648+ self.library_menu = None;
1649+ // Another process starting: off the UI thread, exactly as the
1650+ // export notice's own click starts it.
1651+ cx.background_executor()
1652+ .spawn(async move { show_in_file_manager(&menu.path) })
1653+ .detach();
1654+ }
1655+ }
1656+ cx.notify();
1657+ }
1658+
1472 /// The rate and layout the whole timeline's audio is, taken from source 0's1659 /// The rate and layout the whole timeline's audio is, taken from source 0's
1473 /// own stream: what a library row has to match to be placeable. `None`1660 /// own stream: what a library row has to match to be placeable. `None`
1474 /// until that file has been probed, and then nothing is greyed for it.1661 /// until that file has been probed, and then nothing is greyed for it.
@@ -2130,7 +2317,12 @@ impl Render for Player {
2130 // indices -- so a stroke closes it before it acts. Escape means2317 // indices -- so a stroke closes it before it acts. Escape means
2131 // that and nothing else, which is the `esc` the keys menu2318 // that and nothing else, which is the `esc` the keys menu
2132 // already lists (keymap.rs `FIXED`).2319 // already lists (keymap.rs `FIXED`).
2133- if this.context_menu.take().is_some() {2320+ // Both menus, taken rather than short-circuited: the library's
2321+ // one names a row the edits below can remove, so it closes on a
2322+ // stroke exactly as the clip menu does.
2323+ let clip_menu = this.context_menu.take().is_some();
2324+ let row_menu = this.library_menu.take().is_some();
2325+ if clip_menu || row_menu {
2134 cx.notify();2326 cx.notify();
2135 if key == ESCAPE {2327 if key == ESCAPE {
2136 return;2328 return;
@@ -2307,6 +2499,10 @@ impl Render for Player {
2307 // Over the panel it was opened on, and under the cards: it is only2499 // Over the panel it was opened on, and under the cards: it is only
2308 // ever up while neither of them is (`modal`).2500 // ever up while neither of them is (`modal`).
2309 .children(self.context_card(window.viewport_size(), cx))2501 .children(self.context_card(window.viewport_size(), cx))
2502+ // The library's own menu, the same way and for the same reason:
2503+ // over the panel it was opened on, under the cards, and never up
2504+ // while one of them is.
2505+ .children(self.library_card(window.viewport_size(), cx))
2310 // Last, so they are over everything -- they take no room in the2506 // Last, so they are over everything -- they take no room in the
2311 // column, and only one of the two is ever up.2507 // column, and only one of the two is ever up.
2312 .children(self.keys_overlay(cx))2508 .children(self.keys_overlay(cx))
@@ -2354,7 +2550,7 @@ impl Player {
2354 .as_ref()2550 .as_ref()
2355 .is_some_and(|p| *p == (row.path.clone(), row.stream));2551 .is_some_and(|p| *p == (row.path.clone(), row.stream));
2356 let name: SharedString = row.name.clone().into();2552 let name: SharedString = row.name.clone().into();
2357- let tip: SharedString = match (&row.unusable, meta) {2553+ let says: String = match (&row.unusable, meta) {
2358 // A greyed row says why in full, where its length would be:2554 // A greyed row says why in full, where its length would be:
2359 // the list is the one place the file's own tracks are named.2555 // the list is the one place the file's own tracks are named.
2360 (Some(why), _) => format!("{} — {why}", row.path.display()),2556 (Some(why), _) => format!("{} — {why}", row.path.display()),
@@ -2373,8 +2569,10 @@ impl Player {
2373 meta.frame_rate2569 meta.frame_rate
2374 ),2570 ),
2375 (None, None) => row.path.display().to_string(),2571 (None, None) => row.path.display().to_string(),
2376- }2572+ };
2377- .into();2573+ // The menu is the third way into a row, after the click and the
2574+ // drag, and a right-click nothing advertises is one nobody finds.
2575+ let tip: SharedString = format!("{says} · right-click for more").into();
2378 let ghost = name.clone();2576 let ghost = name.clone();
2379 // What the second line says: the stream, then either its length or2577 // What the second line says: the stream, then either its length or
2380 // the reason it cannot be used.2578 // the reason it cannot be used.
@@ -2388,6 +2586,7 @@ impl Player {
2388 let usable = row.unusable.is_none();2586 let usable = row.unusable.is_none();
2389 let (path, stream) = (row.path.clone(), row.stream);2587 let (path, stream) = (row.path.clone(), row.stream);
2390 let dragged = (path.clone(), stream);2588 let dragged = (path.clone(), stream);
2589+ let menu_path = path.clone();
2391 div()2590 div()
2392 .id(("asset", i))2591 .id(("asset", i))
2393 .flex_none()2592 .flex_none()
@@ -2415,6 +2614,33 @@ impl Player {
2415 cx.new(|_| Tip(ghost.clone()))2614 cx.new(|_| Tip(ghost.clone()))
2416 })2615 })
2417 })2616 })
2617+ // The right button hangs the row's own menu at the pointer.
2618+ // Every row takes it, greyed ones included: a file that cannot
2619+ // join this timeline can still be revealed, described and taken
2620+ // out of the list, and Add is the one item that then refuses --
2621+ // in the engine's words, where the row's grey already says why.
2622+ .on_mouse_down(
2623+ MouseButton::Right,
2624+ cx.listener(move |this, event: &MouseDownEvent, _, cx| {
2625+ if this.modal() {
2626+ return;
2627+ }
2628+ // Picked as a left-click would pick it, so the row the
2629+ // menu is about is the row that reads as chosen -- but
2630+ // only a row that *can* be picked, which is what keeps
2631+ // the Add button under the list honest.
2632+ if usable {
2633+ this.selected_asset = Some((menu_path.clone(), stream));
2634+ }
2635+ this.library_menu = Some(LibraryMenu {
2636+ path: menu_path.clone(),
2637+ stream,
2638+ at: event.position,
2639+ details: false,
2640+ });
2641+ cx.notify();
2642+ }),
2643+ )
2418 .when(picked, |d| d.bg(rgb(SELECTED)).border_1())2644 .when(picked, |d| d.bg(rgb(SELECTED)).border_1())
2419 .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())2645 .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())
2420 // Full height and hard against the edge: the tint reads as2646 // Full height and hard against the edge: the tint reads as
@@ -3551,6 +3777,163 @@ impl Player {
3551 )3777 )
3552 }3778 }
3553 3779
3780+ /// The menu a right-click on a library row opens: what can be done with the
3781+ /// *file* rather than with a clip of it, and a turn-over side saying what
3782+ /// that file is. Built like [`Player::context_card`] down to the scrim, the
3783+ /// row height and the clamp, because it is the same menu on the other panel
3784+ /// -- a click away or any stroke closes it.
3785+ fn library_card(
3786+ &self,
3787+ viewport: Size<Pixels>,
3788+ cx: &mut Context<Self>,
3789+ ) -> Option<impl IntoElement> {
3790+ let menu = self.library_menu.clone()?;
3791+ let path = menu.path.clone();
3792+ let row = |n: usize| {
3793+ div()
3794+ .id(("library-menu", n))
3795+ .flex()
3796+ .min_h(px(MENU_ROW_H))
3797+ .items_center()
3798+ .justify_between()
3799+ .gap(px(12.))
3800+ .px(px(6.))
3801+ .rounded(px(3.))
3802+ };
3803+ let mut rows: Vec<AnyElement> = Vec::new();
3804+ if menu.details {
3805+ // What the library knows about this row and nothing probed for the
3806+ // card: the streams table is filled once per file at import.
3807+ let info = self
3808+ .streams
3809+ .get(&path)
3810+ .and_then(|of_file| of_file.iter().find(|s| s.index == menu.stream));
3811+ let frames = self
3812+ .session
3813+ .as_ref()
3814+ .map_or(0, |session| session.file_frames(&path));
3815+ // How many clips play from this exact row -- the number that
3816+ // decides whether Remove is refused, so the card answers the
3817+ // question the refusal would otherwise raise.
3818+ let placed = self.session.as_ref().map_or(0, |session| {
3819+ let of_row = session
3820+ .sources()
3821+ .iter()
3822+ .position(|s| s.path == path && s.audio_stream == menu.stream);
3823+ of_row.map_or(0, |idx| {
3824+ session
3825+ .lanes()
3826+ .into_iter()
3827+ .flat_map(|lane| session.lane_clips(lane))
3828+ .filter(|c| c.source == idx)
3829+ .count()
3830+ })
3831+ });
3832+ for (label, value) in [
3833+ ("File", file_name(&path)),
3834+ ("Path", path.display().to_string()),
3835+ (
3836+ "Audio",
3837+ info.map_or_else(|| "no track of its own".to_string(), stream_detail),
3838+ ),
3839+ ("Length", timecode(f64::from(frames) / self.fps, self.fps)),
3840+ ("On the timeline", format!("{placed} clips")),
3841+ ] {
3842+ rows.push(
3843+ row(rows.len())
3844+ .child(label)
3845+ .child(
3846+ div()
3847+ .min_w(px(0.))
3848+ .truncate()
3849+ .text_size(px(11.))
3850+ .text_color(rgb(INK_DIM))
3851+ .child(value),
3852+ )
3853+ .into_any_element(),
3854+ );
3855+ }
3856+ } else {
3857+ // Everything but Add works without a timeline open -- and with no
3858+ // timeline there are no rows to right-click at all, so this is the
3859+ // export guard's shape and not a second policy.
3860+ let live = self.session.is_some() && self.exporting().is_none();
3861+ for item in ROW_ITEMS {
3862+ let enabled = match item {
3863+ RowItem::Add | RowItem::Remove => live,
3864+ RowItem::Reveal | RowItem::Properties => true,
3865+ };
3866+ rows.push(
3867+ row(rows.len())
3868+ .child(item.label())
3869+ .child(div().text_color(rgb(INK_DIM)).child(item.hint()))
3870+ .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed())
3871+ .when(enabled, |d| {
3872+ d.cursor_pointer()
3873+ .hover(|s| s.bg(rgb(HOVER)))
3874+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
3875+ this.act_on_row(item, cx);
3876+ }))
3877+ })
3878+ .into_any_element(),
3879+ );
3880+ }
3881+ }
3882+ let (x, y) = menu_at(
3883+ menu.at,
3884+ viewport,
3885+ MENU_PAD * 2. + rows.len() as f32 * MENU_ROW_H,
3886+ );
3887+ let full: SharedString = path.display().to_string().into();
3888+ Some(
3889+ div()
3890+ .absolute()
3891+ .inset_0()
3892+ .on_mouse_down(
3893+ MouseButton::Left,
3894+ cx.listener(|this, _: &MouseDownEvent, _, cx| {
3895+ this.library_menu = None;
3896+ cx.notify();
3897+ cx.stop_propagation();
3898+ }),
3899+ )
3900+ .on_mouse_down(
3901+ MouseButton::Right,
3902+ cx.listener(|this, _: &MouseDownEvent, _, cx| {
3903+ this.library_menu = None;
3904+ cx.notify();
3905+ cx.stop_propagation();
3906+ }),
3907+ )
3908+ .child(
3909+ div()
3910+ .id("library-menu-card")
3911+ .absolute()
3912+ .left(px(x))
3913+ .top(px(y))
3914+ .w(px(MENU_W))
3915+ .flex()
3916+ .flex_col()
3917+ .p(px(MENU_PAD))
3918+ .rounded(px(6.))
3919+ .bg(rgb(SURFACE))
3920+ // Painted after the scrim, so this listener runs first
3921+ // and a press meant for an item never closes the menu
3922+ // out from under its own click (`context_card`).
3923+ .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| {
3924+ cx.stop_propagation()
3925+ })
3926+ .on_mouse_down(MouseButton::Right, |_: &MouseDownEvent, _, cx| {
3927+ cx.stop_propagation()
3928+ })
3929+ .when(menu.details, |d| {
3930+ d.tooltip(move |_, cx| cx.new(|_| Tip(full.clone())).into())
3931+ })
3932+ .children(rows),
3933+ ),
3934+ )
3935+ }
3936+
3554 /// The menu a right-click on a clip opens: what that clip can be given,3937 /// The menu a right-click on a clip opens: what that clip can be given,
3555 /// each item beside the stroke that does the very same thing, and a3938 /// each item beside the stroke that does the very same thing, and a
3556 /// turn-over side that says what the clip *is*. An item that would do3939 /// 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
4262 // at an edge of this clip. Whether those two halves were ever one take4645 // at an edge of this clip. Whether those two halves were ever one take
4263 // is the engine's question, and it words that refusal itself.4646 // is the engine's question, and it words that refusal itself.
4264 ActionId::Regroup => playhead == clip.start || playhead == clip.end(),4647 ActionId::Regroup => playhead == clip.start || playhead == clip.end(),
4648+ // Nothing to take apart in a clip that names no group at all. Whether
4649+ // the group it names still has another half is the engine's question,
4650+ // like the regroup above, and it words that refusal itself.
4651+ ActionId::Detach => clip.link.is_some(),
4265 _ => true,4652 _ => true,
4266 }4653 }
4267 }4654 }
@@ -4785,20 +5172,57 @@ fn whole_take(session: &PlaybackSession, lane: Lane, idx: usize) -> bool {
4785 let Some(clip) = session.lane_clips(lane).get(idx) else {5172 let Some(clip) = session.lane_clips(lane).get(idx) else {
4786 return false;5173 return false;
4787 };5174 };
4788- match (lane.kind, lane.ord) {5175+ let paired = || {
4789- (_, 1..) => false,5176+ session
4790- (LaneKind::Video, _) => true,
4791- // The sound of a take, only while the take is still there: its group is
4792- // carried by a clip on some other lane.
4793- (LaneKind::Audio, _) => session
4794 .lanes()5177 .lanes()
4795 .into_iter()5178 .into_iter()
4796 .filter(|&other| other != lane)5179 .filter(|&other| other != lane)
4797 .flat_map(|other| session.lane_clips(other))5180 .flat_map(|other| session.lane_clips(other))
4798- .any(|o| o.link.is_some() && o.link == clip.link),5181+ .any(|o| o.link.is_some() && o.link == clip.link)
5182+ };
5183+ match (lane.kind, lane.ord) {
5184+ (_, 1..) => false,
5185+ // The picture of a take -- unless the take has been taken apart: a
5186+ // detached picture (a group id no other lane carries, which is also what
5187+ // a lift of the sound leaves) is a half like the sound is, and a ripple
5188+ // under it would drag away the very half it was detached from. A clip in
5189+ // no group at all is not a half but a placement, and on `V1` a placement
5190+ // is the take there is.
5191+ (LaneKind::Video, _) => clip.link.is_none() || paired(),
5192+ // The sound of a take, only while the take is still there: its group is
5193+ // carried by a clip on some other lane.
5194+ (LaneKind::Audio, _) => paired(),
4799 }5195 }
4800 }5196 }
4801 5197
5198+/// The clip a Group would pair this one with: the first clip on another track,
5199+/// in the order the lanes are drawn, covering exactly the same frames and not in
5200+/// this clip's group already. Exactly the same frames because that is all a
5201+/// group id can mean (engine `links_are_consistent`), which is what leaves
5202+/// nothing for a second click to choose. `None` when no track has one, and the
5203+/// notice says so.
5204+fn span_partner(session: &PlaybackSession, lane: Lane, idx: usize) -> Option<(Lane, usize)> {
5205+ let clip = *session.lane_clips(lane).get(idx)?;
5206+ let matches = |other: Lane| {
5207+ let i = session.lane_clips(other).iter().position(|c| {
5208+ (c.start, c.end()) == (clip.start, clip.end())
5209+ && !(c.link.is_some() && c.link == clip.link)
5210+ })?;
5211+ Some((other, i))
5212+ };
5213+ // Sound before picture (and picture before sound): "group this" means the
5214+ // other half of the take, and a project whose audio lane was added after a
5215+ // second video one has that half *after* the layer in storage order -- which
5216+ // is the order the lanes come in. A same-kind lane is still groupable (V1
5217+ // and V2 may be one take), but only where no opposite one covers the span.
5218+ let (opposite, same): (Vec<Lane>, Vec<Lane>) = session
5219+ .lanes()
5220+ .into_iter()
5221+ .filter(|&other| other != lane)
5222+ .partition(|other| other.kind != lane.kind);
5223+ opposite.into_iter().chain(same).find_map(matches)
5224+}
5225+
4802 /// Whether a click marks this clip: the clip that was clicked always, and the5226 /// Whether a click marks this clip: the clip that was clicked always, and the
4803 /// other lane's clip of the same group with it. A clip whose group has no other5227 /// other lane's clip of the same group with it. A clip whose group has no other
4804 /// half -- what a lift leaves behind -- marks only itself, which is what makes a5228 /// half -- what a lift leaves behind -- marks only itself, which is what makes a
@@ -5203,8 +5627,8 @@ mod tests {
5203 envelope, eq_x, eq_y, export_path, export_settings, format_line, frac_along, frac_down,5627 envelope, eq_x, eq_y, export_path, export_settings, format_line, frac_along, frac_down,
5204 frame_at, histogram, is_bare_modifier, is_project, keymap, lanes_h, marked, menu_at,5628 frame_at, histogram, is_bare_modifier, is_project, keymap, lanes_h, marked, menu_at,
5205 mp4_refusal, normalise, panel_h, project_path, push_digit, retarget, scrub_due, show_label,5629 mp4_refusal, normalise, panel_h, project_path, push_digit, retarget, scrub_due, show_label,
5206- source_tint, start_frac, timecode, unseen_paths, unseen_sources, whole_take, width_frac,5630+ source_tint, span_partner, start_frac, timecode, unseen_paths, unseen_sources, whole_take,
5207- window_title,5631+ width_frac, window_title,
5208 };5632 };
5209 use super::{file_name, file_uri, library_rows};5633 use super::{file_name, file_uri, library_rows};
5210 5634
@@ -5497,6 +5921,16 @@ mod tests {
5497 assert!(applicable(&clip, v1, ActionId::Regroup, 30));5921 assert!(applicable(&clip, v1, ActionId::Regroup, 30));
5498 assert!(applicable(&clip, v1, ActionId::Regroup, 90));5922 assert!(applicable(&clip, v1, ActionId::Regroup, 90));
5499 assert!(!applicable(&clip, v1, ActionId::Regroup, 60));5923 assert!(!applicable(&clip, v1, ActionId::Regroup, 60));
5924+ // Detach is the clip's own business: nothing to take apart in one that
5925+ // names no group, and whether the group still has another half is the
5926+ // engine's question. Group is offered on every clip, for that reason.
5927+ assert!(!applicable(&clip, v1, ActionId::Detach, 0));
5928+ let grouped = Clip {
5929+ link: Some(3),
5930+ ..clip
5931+ };
5932+ assert!(applicable(&grouped, v1, ActionId::Detach, 60));
5933+ assert!(applicable(&clip, a1, ActionId::Group, 0));
5500 // The equalizer is the one item the *lane* decides: it filters samples,5934 // The equalizer is the one item the *lane* decides: it filters samples,
5501 // and a video clip has none of its own. Never the playhead's business.5935 // and a video clip has none of its own. Never the playhead's business.
5502 assert!(applicable(&clip, a1, ActionId::Equalizer, 0));5936 assert!(applicable(&clip, a1, ActionId::Equalizer, 0));
@@ -5538,6 +5972,113 @@ mod tests {
5538 }5972 }
5539 }5973 }
5540 5974
5975+ /// What the Detach and Group items do to a real timeline: a music video's
5976+ /// sound comes off its picture, Delete on the loose half takes that half
5977+ /// only, undo puts both back, and Group makes the two one take again --
5978+ /// whole-take delete and all.
5979+ #[test]
5980+ fn a_detached_half_is_removed_alone_and_groups_again() {
5981+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
5982+ session.set_gain(0.0);
5983+ assert!(whole_take(&session, Lane::V1, 0), "one take to start with");
5984+ assert!(whole_take(&session, Lane::A1, 0));
5985+ let frames = session.lane_clips(Lane::V1)[0].len();
5986+
5987+ // Detach audio: neither half is a whole take any more, so Delete on
5988+ // either leaves the other exactly where it is.
5989+ assert!(session.ungroup(Lane::V1, 0));
5990+ assert!(
5991+ !whole_take(&session, Lane::A1, 0),
5992+ "the sound is a half now"
5993+ );
5994+ assert!(!whole_take(&session, Lane::V1, 0), "and so is the picture");
5995+ assert!(session.lift_clip(Lane::A1, 0));
5996+ assert!(session.lane_clips(Lane::A1).is_empty(), "the sound went");
5997+ assert_eq!(session.lane_clips(Lane::V1).len(), 1, "the picture stayed");
5998+ assert_eq!(session.lane_clips(Lane::V1)[0].len(), frames, "untrimmed");
5999+
6000+ // One undo per edit, the removal then the detach.
6001+ assert!(session.undo());
6002+ assert_eq!(session.lane_clips(Lane::A1).len(), 1, "the sound is back");
6003+ assert!(session.undo());
6004+ assert!(whole_take(&session, Lane::A1, 0), "one take again");
6005+
6006+ // Group: the partner is the clip covering these very frames on the
6007+ // other track, which is what the item hands the engine.
6008+ assert!(session.ungroup(Lane::V1, 0));
6009+ assert_eq!(span_partner(&session, Lane::V1, 0), Some((Lane::A1, 0)));
6010+ session
6011+ .group(Lane::V1, 0, Lane::A1, 0)
6012+ .expect("both halves still cover the same frames");
6013+ assert!(
6014+ whole_take(&session, Lane::A1, 0),
6015+ "a take that ripples again"
6016+ );
6017+ assert_eq!(
6018+ span_partner(&session, Lane::V1, 0),
6019+ None,
6020+ "and nothing left on another track to group with"
6021+ );
6022+ }
6023+
6024+ /// Which clip Group reaches when more than one covers the span: the sound,
6025+ /// whatever order the lanes are stored in. A project file may hold them in
6026+ /// any order -- a video layer *before* the audio lane among them -- and
6027+ /// "group this" means the other half of the take, never the layer above it.
6028+ #[test]
6029+ fn group_reaches_the_sound_before_a_video_layer_over_it() {
6030+ use engine::project::LaneKind;
6031+
6032+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
6033+ session.set_gain(0.0);
6034+ let v2 = session.add_lane(LaneKind::Video);
6035+ let path = session.sources()[0].path.clone();
6036+ assert!(
6037+ session
6038+ .place_stream_at(0.0, &path, 0, Some(v2))
6039+ .expect("its own file is on this timeline"),
6040+ "a layer covering the same frames as the take"
6041+ );
6042+
6043+ // Saved and loaded back with the lanes in the order a hand-written
6044+ // project may hold them: the sound last, behind the layer.
6045+ let dir = std::env::temp_dir().join(format!("ve_group_{}", std::process::id()));
6046+ std::fs::create_dir_all(&dir).expect("a scratch directory");
6047+ let file = dir.join("lanes.edith");
6048+ session.save_project(&file).expect("save the project");
6049+ let text = std::fs::read_to_string(&file).expect("read it back");
6050+ let (sound, rest): (Vec<&str>, Vec<&str>) =
6051+ text.lines().partition(|l| l.starts_with("audio "));
6052+ std::fs::write(
6053+ &file,
6054+ format!("{}\n{}\n", rest.join("\n"), sound.join("\n")),
6055+ )
6056+ .expect("write the reordered project");
6057+ let mut session = PlaybackSession::open_project(&file).expect("it loads as it stands");
6058+ std::fs::remove_dir_all(&dir).ok();
6059+ assert_eq!(
6060+ session.lanes(),
6061+ vec![Lane::V1, v2, Lane::A1],
6062+ "the sound is the last lane there"
6063+ );
6064+
6065+ // Detached, so Group has a choice to get wrong: the layer covers these
6066+ // frames too, and it is the lane the walk meets first.
6067+ assert!(session.ungroup(Lane::V1, 0));
6068+ // Group on the picture reaches the sound, not that layer.
6069+ assert_eq!(span_partner(&session, Lane::V1, 0), Some((Lane::A1, 0)));
6070+ session
6071+ .group(Lane::V1, 0, Lane::A1, 0)
6072+ .expect("the two halves cover the same frames");
6073+ // ...and a lane of its own kind is still groupable, once the sound is
6074+ // spoken for: two video lanes may be one take.
6075+ assert_eq!(
6076+ span_partner(&session, Lane::V1, 0),
6077+ Some((v2, 0)),
6078+ "the layer is what is left to group with"
6079+ );
6080+ }
6081+
5541 /// The refusal path, end to end against the real files: an incompatible6082 /// The refusal path, end to end against the real files: an incompatible
5542 /// import changes nothing, and the library mirrors `sources()` 1:1, so a6083 /// import changes nothing, and the library mirrors `sources()` 1:1, so a
5543 /// refused file cannot leave a row behind.6084 /// refused file cannot leave a row behind.
@@ -5624,6 +6165,61 @@ mod tests {
5624 assert_eq!(session.file_frames(&path), frames);6165 assert_eq!(session.file_frames(&path), frames);
5625 }6166 }
5626 6167
6168+ /// Remove from library, through the door the menu item uses
6169+ /// ([`Player::remove_source`] calls exactly this): refused by name while
6170+ /// clips play from the file, and once they do not the row leaves the list.
6171+ #[test]
6172+ fn removing_a_row_is_refused_while_it_plays_and_takes_the_row_away() {
6173+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
6174+ session.set_gain(0.0);
6175+ // Imported, then dragged onto the end: an import alone fills the
6176+ // library, and a row with no clip is removable without any refusal to
6177+ // test. This one has to have a take on the timeline.
6178+ session.import(&asset("test_av2.mp4")).expect("av2 matches");
6179+ let second = session.sources()[1].path.clone();
6180+ let end = session.timeline_duration();
6181+ assert!(
6182+ session
6183+ .place_stream_at(end, &second, 0, None)
6184+ .expect("a file just imported is on this timeline")
6185+ );
6186+ let streams = HashMap::new();
6187+ let rows = |session: &PlaybackSession| {
6188+ library_rows(session.sources(), &streams, None, |_| 0).len()
6189+ };
6190+ assert_eq!(rows(&session), 2, "a row per source");
6191+
6192+ let refusal = session
6193+ .remove_source(&second, 0)
6194+ .expect_err("its take is still on the timeline")
6195+ .to_string();
6196+ assert!(refusal.contains("still plays"), "{refusal}");
6197+ assert!(
6198+ refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
6199+ "the refusal names the lanes to clear: {refusal}"
6200+ );
6201+ assert_eq!(rows(&session), 2, "and the row is still there");
6202+
6203+ // Delete that take -- the whole group, from either half -- and the file
6204+ // can go. The list is what says so.
6205+ let last = session.lane_clips(Lane::V1).len() - 1;
6206+ assert!(session.delete_clip(Lane::V1, last));
6207+ session
6208+ .remove_source(&second, 0)
6209+ .expect("nothing plays av2 any more");
6210+ assert_eq!(rows(&session), 1, "the row went with it");
6211+ assert_eq!(session.sources().len(), 1);
6212+ // The one file left cannot go: a project that names none is not one
6213+ // that reopens.
6214+ let refusal = session
6215+ .remove_source(&session.sources()[0].path.clone(), 0)
6216+ .expect_err("the last file stays")
6217+ .to_string();
6218+ assert!(refusal.contains("only file"), "{refusal}");
6219+ // A row this timeline never had is refused, not panicked on.
6220+ assert!(session.remove_source(&second, 0).is_err());
6221+ }
6222+
5627 /// The trim-a-clip path through the doors the edge drag uses:6223 /// The trim-a-clip path through the doors the edge drag uses:
5628 /// [`Player::trim_to`] clamps the pointer with `trim_room` and6224 /// [`Player::trim_to`] clamps the pointer with `trim_room` and
5629 /// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less6225 /// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less
@@ -6853,6 +7449,7 @@ fn main() {
6853 ruler: Rc::default(),7449 ruler: Rc::default(),
6854 selected: None,7450 selected: None,
6855 context_menu: None,7451 context_menu: None,
7452+ library_menu: None,
6856 selected_asset: None,7453 selected_asset: None,
6857 waves: HashMap::new(),7454 waves: HashMap::new(),
6858 streams: HashMap::new(),7455 streams: HashMap::new(),
crates/engine/src/playback.rsmodified+109 -2
@@ -143,7 +143,8 @@ pub struct PlaybackSession {
143 /// end of a file, which is a save that would not open again143 /// end of a file, which is a save that would not open again
144 /// ([`Self::open_project`] refuses one by name). Append-only for144 /// ([`Self::open_project`] refuses one by name). Append-only for
145 /// `sources`'s reason: an index handed out stays valid, undone import or145 /// `sources`'s reason: an index handed out stays valid, undone import or
146- /// not.146+ /// not -- with the single exception `sources` itself has,
147+ /// [`Self::remove_source`], which takes the same entry out of both.
147 counts: Vec<u32>,148 counts: Vec<u32>,
148 /// What the current video worker was opened for: where it sits on the149 /// What the current video worker was opened for: where it sits on the
149 /// timeline, how long it runs, and which source frame it started at --150 /// timeline, how long it runs, and which source frame it started at --
@@ -723,6 +724,21 @@ impl PlaybackSession {
723 .regroup(secs_to_frame(timeline_secs, self.meta.frame_rate))724 .regroup(secs_to_frame(timeline_secs, self.meta.frame_rate))
724 }725 }
725 726
727+ /// Takes that clip out of its group, so its picture and its sound are edited
728+ /// apart from here on. Metadata only like a cut -- no reseek -- and one undo
729+ /// step. `false` for a bad index and for a clip that is not grouped with
730+ /// anything, which is already detached.
731+ pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
732+ self.project.ungroup(lane, idx)
733+ }
734+
735+ /// Puts two clips covering the same frames back into one group: the regroup
736+ /// of what [`ungroup`](Self::ungroup) took apart. Metadata only, one undo
737+ /// step, and the error says why when it refuses.
738+ pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
739+ self.project.group(a, a_idx, b, b_idx)
740+ }
741+
726 /// What the clip at `idx` of `lane` is equalized with, or `None` for one742 /// What the clip at `idx` of `lane` is equalized with, or `None` for one
727 /// that plays flat -- what a card shows before it lets anyone drag a band.743 /// that plays flat -- what a card shows before it lets anyone drag a band.
728 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {744 pub fn eq_of(&self, lane: Lane, idx: usize) -> Option<&EqParams> {
@@ -1005,6 +1021,37 @@ impl PlaybackSession {
1005 })1021 })
1006 }1022 }
1007 1023
1024+ /// Takes `path` played on `stream` out of the library -- the door a library
1025+ /// row's own remove goes through, naming the row exactly as
1026+ /// [`place_stream_at`](Self::place_stream_at) does. Refused in
1027+ /// [`Project::remove_source`]'s words while a clip still plays from it, and
1028+ /// for a row this timeline does not have.
1029+ ///
1030+ /// Reseeks like an edit even though nothing playable changed: the clip
1031+ /// indexes into the source list have just moved, and the running workers
1032+ /// were opened against the old numbering.
1033+ pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result<()> {
1034+ let wanted = Source::new(path, stream);
1035+ let idx = self
1036+ .project
1037+ .sources()
1038+ .iter()
1039+ .position(|s| *s == wanted)
1040+ .ok_or_else(|| format!("{} is not on this timeline", path.display()))?;
1041+ self.project.remove_source(idx)?;
1042+ // The one thing that shortens the source list, so the one place
1043+ // [`Self::counts`] shortens with it: left behind, the gone file's length
1044+ // would become the wall a *surviving* source is trimmed against
1045+ // ([`trim_room`](Self::trim_room)) and the next import would land its
1046+ // count one index late.
1047+ if idx < self.counts.len() {
1048+ self.counts.remove(idx);
1049+ }
1050+ let now = self.now();
1051+ self.seek(now);
1052+ Ok(())
1053+ }
1054+
1008 /// What the timeline's audio *is*: source 0's chosen stream, probed. Every1055 /// What the timeline's audio *is*: source 0's chosen stream, probed. Every
1009 /// other source is held to it.1056 /// other source is held to it.
1010 fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> {1057 fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> {
@@ -1511,7 +1558,67 @@ fn secs_to_frame(secs: f64, fps: f64) -> u32 {
1511 1558
1512 #[cfg(test)]1559 #[cfg(test)]
1513 mod tests {1560 mod tests {
1514- use super::secs_to_frame;1561+ use super::{Edge, Lane, PlaybackSession, secs_to_frame};
1562+ use std::path::PathBuf;
1563+
1564+ fn asset(name: &str) -> PathBuf {
1565+ PathBuf::from(env!("CARGO_MANIFEST_DIR"))
1566+ .join("../../assets")
1567+ .join(name)
1568+ }
1569+
1570+ /// The seam between the two lists a source index reaches: dropping a file
1571+ /// from the library shortens `sources`, and `counts` -- the frame length
1572+ /// per source, which is what a trim is walled by -- has to lose the same
1573+ /// entry. Left behind, the dead file's length would wall the survivor.
1574+ #[test]
1575+ fn removing_a_source_takes_its_frame_count_with_it() {
1576+ // Source 0 is 5 s, source 1 is 4 s: two different walls, so a stale
1577+ // count cannot pass for the right one.
1578+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1579+ session.set_gain(0.0);
1580+ // Imported, then dragged onto the end -- an import alone places nothing
1581+ // ([`PlaybackSession::import`]), and this test needs both takes there.
1582+ session.import(&asset("test_av2.mp4")).expect("av2 matches");
1583+ let end = session.timeline_duration();
1584+ assert!(
1585+ session
1586+ .place_stream_at(end, &asset("test_av2.mp4"), 0, None)
1587+ .expect("a file just imported is on this timeline")
1588+ );
1589+ let (long, short) = (session.counts[0], session.counts[1]);
1590+ assert!(long > short, "{long} vs {short}");
1591+
1592+ // Clear source 0's take, then take the file itself out: av2's clip is
1593+ // the only one left and it is source 0 now.
1594+ assert!(session.delete_clip(Lane::V1, 0));
1595+ session
1596+ .remove_source(&asset("test_av.mp4"), 0)
1597+ .expect("nothing plays it any more");
1598+ assert_eq!(session.counts, vec![short], "the dead length went with it");
1599+ assert_eq!(session.sources().len(), session.counts.len());
1600+
1601+ // The wall is the surviving file's own length, not the gone one's: a
1602+ // whole-file clip cannot be dragged out any further at all.
1603+ let clip = session.lane_clips(Lane::V1)[0];
1604+ assert_eq!(clip.len(), short, "av2's take, whole");
1605+ assert_eq!(
1606+ session.trim_room(Lane::V1, 0, Edge::End),
1607+ Some((clip.start + 1, clip.end()))
1608+ );
1609+ assert!(
1610+ !session.trim_clip(Lane::V1, 0, Edge::End, clip.end() + 30),
1611+ "past the file's last frame is refused, by ITS length"
1612+ );
1613+
1614+ // ...and the next import still lines the two lists up, which is the
1615+ // alignment `note_frames` asserts on.
1616+ session
1617+ .import(&asset("test_av.mp4"))
1618+ .expect("it may come back");
1619+ assert_eq!(session.counts, vec![short, long]);
1620+ assert_eq!(session.sources().len(), session.counts.len());
1621+ }
1515 1622
1516 #[test]1623 #[test]
1517 fn boundary_seconds_round_trip_to_their_own_frame() {1624 fn boundary_seconds_round_trip_to_their_own_frame() {
crates/engine/src/project.rsmodified+341 -0
@@ -524,6 +524,60 @@ impl Project {
524 true524 true
525 }525 }
526 526
527+ /// Drops a source entry -- the file a library row *is* -- and renumbers
528+ /// every clip that indexed past it, which is why this is more than a
529+ /// `Vec::remove`.
530+ ///
531+ /// Refused, changing nothing, while any clip still plays from it: the
532+ /// refusal names the lanes and how many clips each holds, so a caller can
533+ /// say what has to be deleted first. Refused too for the last entry left,
534+ /// because a project that names no file cannot be reopened
535+ /// (`PlaybackSession::open_project`) and the timeline's audio parameters
536+ /// are read off source 0.
537+ ///
538+ /// ponytail: this retires the undo stack. `history` holds lanes alone, so a
539+ /// snapshot older than the removal can name the very source being removed
540+ /// (delete a file's clips, then remove the file) and restoring it would
541+ /// point a clip at an entry that is gone. The upgrade path is snapshotting
542+ /// `sources` beside `lanes` in [`snapshot`](Project::snapshot) -- which the
543+ /// "indexes are forever" rule ([`append_clip`](Project::append_clip), and
544+ /// the reason [`without_orphan_sources`](Project::without_orphan_sources)
545+ /// exists) currently rules out.
546+ pub fn remove_source(&mut self, idx: usize) -> crate::Result<()> {
547+ let Some(source) = self.sources.get(idx) else {
548+ return Err(format!("there is no source {idx} to remove").into());
549+ };
550+ let name = source.path.display().to_string();
551+ // Asked before the clips are counted: with one file left the answer is
552+ // the same whatever plays, and "the only file" is the more useful half
553+ // of it.
554+ if self.sources.len() == 1 {
555+ return Err(format!("{name} is the only file this project names").into());
556+ }
557+ let used: Vec<String> = handles(&self.lanes)
558+ .into_iter()
559+ .zip(&self.lanes)
560+ .filter_map(
561+ |(lane, data)| match data.clips.iter().filter(|c| c.source == idx).count() {
562+ 0 => None,
563+ 1 => Some(format!("{} (1 clip)", lane.label())),
564+ n => Some(format!("{} ({n} clips)", lane.label())),
565+ },
566+ )
567+ .collect();
568+ if !used.is_empty() {
569+ return Err(format!("{name} still plays on {}", used.join(", ")).into());
570+ }
571+ self.sources.remove(idx);
572+ for c in self.lanes.iter_mut().flat_map(|l| &mut l.clips) {
573+ if c.source > idx {
574+ c.source -= 1;
575+ }
576+ }
577+ self.history.clear();
578+ Ok(())
579+ }
580+
527 /// The sources a clip actually names, with the clips reindexed onto them581 /// The sources a clip actually names, with the clips reindexed onto them
528 /// -- what a save writes. Indexes are forever *inside* a session (see582 /// -- what a save writes. Indexes are forever *inside* a session (see
529 /// [`Project::append_clip`]), so an undone import leaves an orphan source583 /// [`Project::append_clip`]), so an undone import leaves an orphan source
@@ -1002,6 +1056,115 @@ impl Project {
1002 true1056 true
1003 }1057 }
1004 1058
1059+ /// Take the clip at `idx` of `lane` out of its group: every clip carrying
1060+ /// its id -- on however many lanes -- is handed an id of its own, so from
1061+ /// here on each half moves, trims and is deleted alone. The music video
1062+ /// whose sound is to be cut against its picture starts here.
1063+ ///
1064+ /// An id of its own rather than none at all: a half no other lane is grouped
1065+ /// with is exactly what a [`lift`](Project::lift) leaves behind and is legal
1066+ /// (see [`links_are_consistent`]), and it is what a front-end already draws
1067+ /// as detached. `None` would instead say "was never part of a take", which
1068+ /// is what a one-lane [`place`](Project::place) means.
1069+ ///
1070+ /// Metadata only, like a [`split`](Project::split): no mapping changes, so
1071+ /// nothing has to be reseeked. One snapshot, so one [`Project::undo`] puts
1072+ /// the group back. Refused (`false`, nothing changed) for an index that is
1073+ /// not there, a clip in no group at all, and one whose group has no other
1074+ /// half -- that one is already detached, and a refusal must not cost an undo
1075+ /// step.
1076+ pub fn ungroup(&mut self, lane: Lane, idx: usize) -> bool {
1077+ let Some(id) = self.lane(lane).get(idx).and_then(|c| c.link) else {
1078+ return false;
1079+ };
1080+ let members = self
1081+ .lanes
1082+ .iter()
1083+ .flat_map(|l| &l.clips)
1084+ .filter(|c| c.link == Some(id))
1085+ .count();
1086+ if members < 2 {
1087+ return false;
1088+ }
1089+ self.snapshot();
1090+ // Drawn before the walk: `new_link` takes the whole project, and the
1091+ // walk holds the lanes.
1092+ let mut fresh = (0..members).map(|_| self.new_link()).collect::<Vec<_>>();
1093+ for data in &mut self.lanes {
1094+ for c in data.clips.iter_mut().filter(|c| c.link == Some(id)) {
1095+ c.link = fresh.pop();
1096+ }
1097+ }
1098+ debug_assert!(links_are_consistent(&self.lanes).is_ok());
1099+ true
1100+ }
1101+
1102+ /// Put two clips on two lanes into one group, so what moves one moves the
1103+ /// other again -- the undo of a [`ungroup`](Project::ungroup) by hand, and
1104+ /// how a picture is regrouped with sound it was never opened with. Whatever
1105+ /// either of them was grouped with comes along: those clips cover this same
1106+ /// span already, so the result is one group and not two overlapping ones.
1107+ ///
1108+ /// Same frames or nothing: a group id names **one span** on however many
1109+ /// lanes ([`links_are_consistent`] refuses to load anything else), so two
1110+ /// clips that do not cover the same frames cannot be one take, and the
1111+ /// refusal says which bounds to trim to. Kinds are *not* checked: a take may
1112+ /// run on `V1` and `V2` at once, and picture-with-sound is the case people
1113+ /// mean, not the rule.
1114+ ///
1115+ /// Metadata only, one snapshot. The error says what is wrong, because
1116+ /// `false` would not: a bad index, one lane twice (a group is at most one
1117+ /// clip per lane), spans that disagree, and a pair that is already one take
1118+ /// -- nothing changes, and none of them costs an undo step.
1119+ pub fn group(&mut self, a: Lane, a_idx: usize, b: Lane, b_idx: usize) -> crate::Result<()> {
1120+ if a == b {
1121+ return Err(format!(
1122+ "a group is one clip per lane: pick the clip to group with on another track, not a second one on {}",
1123+ a.label()
1124+ )
1125+ .into());
1126+ }
1127+ let clip = |p: &Self, lane: Lane, idx: usize| -> crate::Result<Clip> {
1128+ p.lane(lane)
1129+ .get(idx)
1130+ .copied()
1131+ .ok_or_else(|| format!("there is no clip {idx} on {}", lane.label()).into())
1132+ };
1133+ let (x, y) = (clip(self, a, a_idx)?, clip(self, b, b_idx)?);
1134+ if (x.start, x.end()) != (y.start, y.end()) {
1135+ return Err(format!(
1136+ "{} covers [{}, {}) and {} covers [{}, {}): trim them to matching bounds first",
1137+ a.label(),
1138+ x.start,
1139+ x.end(),
1140+ b.label(),
1141+ y.start,
1142+ y.end()
1143+ )
1144+ .into());
1145+ }
1146+ if x.link.is_some() && x.link == y.link {
1147+ return Err("those two are one take already".into());
1148+ }
1149+ self.snapshot();
1150+ let id = self.new_link();
1151+ // Every clip either of them was grouped with, by the same rule: all of
1152+ // them cover this span, so one id over the lot stays consistent.
1153+ let old = [x.link, y.link];
1154+ for data in &mut self.lanes {
1155+ for c in data.clips.iter_mut().filter(|c| c.link.is_some()) {
1156+ if old.contains(&c.link) {
1157+ c.link = Some(id);
1158+ }
1159+ }
1160+ }
1161+ // And the two themselves, which a `place` may have left in no group.
1162+ self.lane_mut(a).expect("read above")[a_idx].link = Some(id);
1163+ self.lane_mut(b).expect("read above")[b_idx].link = Some(id);
1164+ debug_assert!(links_are_consistent(&self.lanes).is_ok());
1165+ Ok(())
1166+ }
1167+
1005 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it1168 /// Place `clip` in one lane at `timeline_frame`, overwriting whatever it
1006 /// lands on and leaving every other clip exactly where it is -- the1169 /// lands on and leaving every other clip exactly where it is -- the
1007 /// per-lane paste. Anything already there is trimmed away (and split in two1170 /// per-lane paste. Anything already there is trimmed away (and split in two
@@ -1841,6 +2004,103 @@ mod tests {
1841 );2004 );
1842 }2005 }
1843 2006
2007+ /// The music video's own path: the take comes apart into halves that carry
2008+ /// ids of their own, one undo puts it back, and two clips over the same
2009+ /// frames become one take again by hand.
2010+ #[test]
2011+ fn a_take_comes_apart_and_goes_back_together() {
2012+ let mut p = Project::single(FILE, 9);
2013+ let one = p.clips()[0].link.expect("a fresh project is one take");
2014+ assert_eq!(p.lane(Lane::A1)[0].link, Some(one));
2015+
2016+ // A third lane in the same group -- and the merge case with it: a
2017+ // placement is in no group, and grouping it in leaves *one* group.
2018+ let v2 = p.add_lane(LaneKind::Video);
2019+ assert!(p.place(v2, 0, clip(0, 0, 9, 0)));
2020+ assert!(p.lane(v2)[0].link.is_none(), "a placement joins no group");
2021+ p.group(Lane::V1, 0, v2, 0)
2022+ .expect("the same frames, one lane over");
2023+ let id = p.clips()[0].link.expect("still a group");
2024+ assert!(
2025+ p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
2026+ "one id over the three, not two groups sharing a span"
2027+ );
2028+ links_are_consistent(&p.lanes).expect("one id, one span");
2029+
2030+ // Detached by the sound: every half of the group, not only the two.
2031+ assert!(p.ungroup(Lane::A1, 0));
2032+ let ids: Vec<Option<u32>> = p.lanes().into_iter().map(|l| p.lane(l)[0].link).collect();
2033+ assert!(
2034+ ids.iter().all(Option::is_some),
2035+ "a half keeps an id of its own"
2036+ );
2037+ assert!(
2038+ ids.iter()
2039+ .enumerate()
2040+ .all(|(i, a)| ids[..i].iter().all(|b| a != b)),
2041+ "and no two halves are the same group any more: {ids:?}"
2042+ );
2043+ links_are_consistent(&p.lanes).expect("a lone id is legal");
2044+
2045+ // One snapshot for the whole detach.
2046+ assert!(p.undo());
2047+ assert!(
2048+ p.lanes().into_iter().all(|l| p.lane(l)[0].link == Some(id)),
2049+ "one undo puts the whole group back"
2050+ );
2051+
2052+ // And back together by hand: the two the pointer named, and only them.
2053+ assert!(p.ungroup(Lane::V1, 0));
2054+ p.group(Lane::V1, 0, Lane::A1, 0)
2055+ .expect("both cover [0, 9)");
2056+ assert_eq!(p.lane(Lane::V1)[0].link, p.lane(Lane::A1)[0].link);
2057+ assert_ne!(
2058+ p.lane(v2)[0].link,
2059+ p.lane(Lane::V1)[0].link,
2060+ "the third half stayed detached"
2061+ );
2062+ links_are_consistent(&p.lanes).expect("one id, one span");
2063+ }
2064+
2065+ /// What a group may not be, and what a detach has nothing to take apart --
2066+ /// none of which may cost an undo step.
2067+ #[test]
2068+ fn a_group_is_one_span_and_one_clip_per_lane() {
2069+ let mut p = three();
2070+ let before = shape(&p);
2071+ let why = |r: crate::Result<()>| r.expect_err("refused").to_string();
2072+
2073+ assert!(
2074+ why(p.group(Lane::V1, 0, Lane::V1, 1)).contains("one clip per lane"),
2075+ "two clips of one lane are never one take"
2076+ );
2077+ assert!(why(p.group(Lane::V1, 0, Lane::A1, 9)).contains("there is no clip 9 on A1"));
2078+ let spans = why(p.group(Lane::V1, 0, Lane::A1, 1));
2079+ assert!(
2080+ spans.contains("V1 covers [0, 3) and A1 covers [3, 5)"),
2081+ "{spans}"
2082+ );
2083+ assert!(
2084+ spans.contains("trim them to matching bounds first"),
2085+ "{spans}"
2086+ );
2087+ assert!(why(p.group(Lane::V1, 0, Lane::A1, 0)).contains("one take already"));
2088+
2089+ // A half nothing else is grouped with is already detached, a placement
2090+ // is in no group at all, and an index that is not there has nothing to
2091+ // detach either.
2092+ assert!(p.place(Lane::V1, 20, clip(20, 0, 3, 0)));
2093+ assert!(!p.ungroup(Lane::V1, 3), "a placement is in no group");
2094+ assert!(p.lift(Lane::A1, 0));
2095+ assert!(!p.ungroup(Lane::V1, 0), "its group has no other half");
2096+ assert!(!p.ungroup(Lane::V1, 9), "no clip there");
2097+
2098+ // Two undos, one per edit: not one of the refusals pushed a snapshot.
2099+ assert!(p.undo());
2100+ assert!(p.undo());
2101+ assert_eq!(shape(&p), before);
2102+ }
2103+
1844 #[test]2104 #[test]
1845 fn split_refused_at_zero_boundary_end_and_in_a_gap() {2105 fn split_refused_at_zero_boundary_end_and_in_a_gap() {
1846 let mut p = three();2106 let mut p = three();
@@ -2699,6 +2959,87 @@ mod tests {
2699 assert_eq!(reloaded.sources().len(), 2);2959 assert_eq!(reloaded.sources().len(), 2);
2700 }2960 }
2701 2961
2962+ /// Taking a file out of the library: refused by name -- lanes and counts --
2963+ /// while a clip still plays from it, and once nothing does, the entry goes
2964+ /// and every clip that indexed past it is renumbered onto the short list.
2965+ #[test]
2966+ fn remove_source_refuses_what_plays_and_renumbers_what_is_left() {
2967+ // Sources 0 (FILE, three clips) and 1 (FILE2, one take on both lanes),
2968+ // plus a second stream of FILE as source 2 with a take of its own.
2969+ let mut p = two_sources();
2970+ assert_eq!(p.import(FILE, 1), 2, "another stream is another source");
2971+ assert!(p.append_clip(2, 4));
2972+
2973+ let refusal = p
2974+ .remove_source(1)
2975+ .expect_err("a source with clips on it cannot go")
2976+ .to_string();
2977+ assert!(refusal.contains(FILE2), "names the file: {refusal}");
2978+ assert!(
2979+ refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
2980+ "names the lanes holding it: {refusal}"
2981+ );
2982+ assert!(refusal.contains("still plays"), "{refusal}");
2983+ assert_eq!(p.sources().len(), 3, "a refusal changes nothing");
2984+ assert_eq!(shape(&p)[0][3].source, 1);
2985+
2986+ // Delete FILE2's take -- the whole span, on every lane -- and the entry
2987+ // is free to go. Source 2's clips become source 1's.
2988+ assert!(p.delete_in(Lane::V1, 3));
2989+ assert!(!p.clips().iter().any(|c| c.source == 1), "nothing plays it");
2990+ p.remove_source(1).expect("nothing plays FILE2 any more");
2991+ assert_eq!(
2992+ p.sources(),
2993+ [Source::new(FILE, 0), Source::new(FILE, 1)],
2994+ "the middle entry is gone"
2995+ );
2996+ assert_eq!(
2997+ shape(&p)[0].iter().map(|c| c.source).collect::<Vec<_>>(),
2998+ [0, 0, 0, 1],
2999+ "the clips past it renumbered"
3000+ );
3001+ assert_eq!(
3002+ shape(&p)[1].iter().map(|c| c.source).collect::<Vec<_>>(),
3003+ [0, 0, 0, 1],
3004+ "on every lane"
3005+ );
3006+ // What is left is a project that still loads, which is the whole point
3007+ // of renumbering rather than leaving a hole.
3008+ let (sources, lanes, eq, color) = p.without_orphan_sources();
3009+ Project::from_parts(sources, lanes, eq, color).expect("from_parts");
3010+ }
3011+
3012+ /// The two edges of a removal: it retires the undo stack (the ponytail on
3013+ /// [`Project::remove_source`]), and the last entry standing cannot go --
3014+ /// source 0 is where a reopened project reads its frame rate.
3015+ #[test]
3016+ fn remove_source_retires_undo_and_keeps_the_last_file() {
3017+ let mut p = two_sources();
3018+ assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");
3019+ assert!(!p.history.is_empty(), "there is something to undo");
3020+ p.remove_source(1).expect("nothing plays FILE2");
3021+ assert!(
3022+ p.history.is_empty(),
3023+ "a snapshot naming the removed source must not survive it"
3024+ );
3025+ assert!(!p.undo(), "and so there is nothing left to undo");
3026+
3027+ // The last file standing stays, whatever plays from it:
3028+ // `PlaybackSession::open_project` refuses a project that names no
3029+ // sources at all, and the timeline's frame rate lives in source 0.
3030+ assert_eq!(p.sources().len(), 1);
3031+ let refusal = p
3032+ .remove_source(0)
3033+ .expect_err("the only source must stay")
3034+ .to_string();
3035+ assert!(refusal.contains("only file"), "{refusal}");
3036+ assert_eq!(p.sources().len(), 1);
3037+ assert!(
3038+ p.remove_source(1).is_err(),
3039+ "and an index that is not there is refused, not panicked on"
3040+ );
3041+ }
3042+
2702 /// A clip's equalizer is the clip's: it survives every edit that copies a3043 /// A clip's equalizer is the clip's: it survives every edit that copies a
2703 /// placement, and it comes back with an undo.3044 /// placement, and it comes back with an undo.
2704 #[test]3045 #[test]
crates/engine/tests/audio_files.rsmodified+54 -0
@@ -322,6 +322,60 @@ fn an_audio_only_project_saves_reloads_and_exports_its_sound() {
322 let _ = std::fs::remove_dir_all(&dir);322 let _ = std::fs::remove_dir_all(&dir);
323 }323 }
324 324
325+/// A *song* as the first import into an empty window: `open_library` takes the
326+/// audio-only fork of `open` (there is no picture to scaffold a canvas from) and
327+/// still leaves the timeline empty. The row is there at the song's own length,
328+/// the canvas and the clock a song would have set are set, and the drag that
329+/// follows is what makes it play.
330+#[test]
331+fn the_first_import_of_a_song_opens_a_library_over_an_empty_timeline() {
332+ let mp3 = asset("test_tone.mp3");
333+ let mut session = PlaybackSession::open_library(&mp3).expect("open into the library");
334+ session.set_gain(0.0);
335+ assert!(session.is_empty(), "the timeline must start empty");
336+ assert_eq!(session.timeline_duration(), 0.0);
337+ assert!(session.lane_clips(Lane::A1).is_empty(), "nothing placed");
338+ assert!(session.lane_clips(Lane::V1).is_empty(), "no picture either");
339+ // The canvas a song scaffolds, and the clock that goes with it -- a session
340+ // with an empty timeline is still this file's session.
341+ let meta = *session.meta();
342+ assert_eq!((meta.width, meta.height), (1920, 1080), "the song canvas");
343+ assert_eq!(meta.frame_rate, 30.0);
344+ assert_eq!(session.sources().len(), 1, "the library row");
345+ assert_eq!(session.file_frames(&mp3), 90, "3 s at 30 fps, never placed");
346+ assert!(!session.undo(), "opening a library is not an undo step");
347+ // A file this session never took in has no length and cannot be placed.
348+ assert_eq!(session.file_frames(&asset("test_tone.flac")), 0);
349+ assert_eq!(
350+ refusal(session.place_stream_at(0.0, &asset("test_tone.flac"), 0, None)),
351+ format!(
352+ "{} is not on this timeline",
353+ asset("test_tone.flac").display()
354+ )
355+ );
356+
357+ // The drag: onto the audio lane and nowhere else, at the song's own length.
358+ assert!(
359+ session
360+ .place_stream_at(0.0, &mp3, 0, None)
361+ .expect("its own file is on this timeline")
362+ );
363+ assert!(!session.is_empty());
364+ assert!((session.timeline_duration() - 3.0).abs() < 0.05);
365+ assert_eq!(session.lane_clips(Lane::A1).len(), 1);
366+ assert!(session.lane_clips(Lane::V1).is_empty(), "still no picture");
367+ let clip = session.lane_clips(Lane::A1)[0];
368+ assert_eq!((clip.source, clip.in_frame, clip.len()), (0, 0, 90));
369+ // And it plays: the segment list names the song, so the worker opens it
370+ // rather than running silent.
371+ session.seek(1.0);
372+ assert!(!session.lane_spans_by_source(Lane::A1).is_empty());
373+ // One `z` takes the drag back to the empty timeline, row and all.
374+ assert!(session.undo(), "undo the drag");
375+ assert!(session.is_empty());
376+ assert_eq!(session.sources().len(), 1, "the row survives the undo");
377+}
378+
325 /// The other half of the door: a *video* joining a timeline a song scaffolded.379 /// The other half of the door: a *video* joining a timeline a song scaffolded.
326 /// It is held to the canvas the song set (H.264, 30 fps), so a matching file380 /// It is held to the canvas the song set (H.264, 30 fps), so a matching file
327 /// brings its picture in -- and the timeline stops being audio-only, mp4 export381 /// brings its picture in -- and the timeline stops being audio-only, mp4 export