forge
Explore
Log in

Don't you dare go Hollow

A right-click on a media row opens its own menu

Browse files at this commit

97d941eb8687e122856eba5fd2bd3958e68429caAhmet Kaan GümüşParent: c3b6ce2
  • feat
    • a right-click on a media row opens its own menu
Show full message
✨ feat(library): a right-click on a media row opens its own menu

Add at playhead, Remove from library, Reveal in files and Properties,
built like the clip menu down to the scrim and the clamp -- a click away
or any stroke closes it.

Remove goes through a new `Project::remove_source`, which refuses by name
while clips still play from the file (the refusal names the lanes and how
many clips each holds), keeps the last entry standing, and renumbers every
clip that indexed past the one that went. It retires the undo stack: the
history holds lanes alone, so a snapshot older than the removal could name
a source that is gone -- the notice says so, and the ponytail names the
upgrade path.
crates/app/src/keymap.rsmodified+1 -1
@@ -268,7 +268,7 @@ pub struct Fixed {
268 pub const FIXED: [Fixed; 12] = [268 pub const FIXED: [Fixed; 12] = [
269 Fixed {269 Fixed {
270 chord: "esc",270 chord: "esc",
271- label: "Close this card or clip menu, or cancel a capture",271+ label: "Close this card or menu, or cancel a capture",
272 category: Category::View,272 category: Category::View,
273 },273 },
274 Fixed {274 Fixed {
crates/app/src/main.rsmodified+364 -4
@@ -228,6 +228,59 @@ struct ContextMenu {
228 details: bool,228 details: bool,
229 }229 }
230 230
231+/// An open library menu: which row it was opened on -- the file and the stream,
232+/// the pair [`Player::selected_asset`] holds, so a list rebuilt under it (a
233+/// probe landing, a source going) cannot slide another row beneath the menu the
234+/// way a row *index* would -- where it hangs, and whether it has been turned
235+/// over to show what the file *is*.
236+#[derive(Clone)]
237+struct LibraryMenu {
238+ path: PathBuf,
239+ stream: usize,
240+ at: Point<Pixels>,
241+ details: bool,
242+}
243+
244+/// What a library row's menu offers, in the order it lists them. Unlike the clip
245+/// menu's items none of these is a stroke -- there is no keyboard way to a row --
246+/// so the label and the hint are written here rather than read off the keymap.
247+#[derive(Clone, Copy, PartialEq)]
248+enum RowItem {
249+ Add,
250+ Remove,
251+ Reveal,
252+ Properties,
253+}
254+
255+const ROW_ITEMS: [RowItem; 4] = [
256+ RowItem::Add,
257+ RowItem::Remove,
258+ RowItem::Reveal,
259+ RowItem::Properties,
260+];
261+
262+impl RowItem {
263+ fn label(self) -> &'static str {
264+ match self {
265+ Self::Add => "Add at playhead",
266+ Self::Remove => "Remove from library",
267+ Self::Reveal => "Reveal in files",
268+ Self::Properties => "Properties",
269+ }
270+ }
271+
272+ /// The dim right-hand column, where the clip menu prints the stroke: what
273+ /// the item will do to the timeline, so nothing here is a surprise.
274+ fn hint(self) -> &'static str {
275+ match self {
276+ Self::Add => "inserts the whole file",
277+ Self::Remove => "only if nothing plays it",
278+ Self::Reveal => "file manager",
279+ Self::Properties => "…",
280+ }
281+ }
282+}
283+
231 /// What the menu offers, in the order it lists them. Every one of these is an284 /// What the menu offers, in the order it lists them. Every one of these is an
232 /// action a stroke already reaches -- the menu is a second way *to* the actions285 /// action a stroke already reaches -- the menu is a second way *to* the actions
233 /// and never a second version of them -- so both the label and the hint come286 /// and never a second version of them -- so both the label and the hint come
@@ -338,6 +391,10 @@ struct Player {
338 /// `selected` does, so it is closed by anything that can move indices --391 /// `selected` does, so it is closed by anything that can move indices --
339 /// every stroke, and every item of its own.392 /// every stroke, and every item of its own.
340 context_menu: Option<ContextMenu>,393 context_menu: Option<ContextMenu>,
394+ /// The library menu a right-click on a row opened, if one is up. Names its
395+ /// row by file and stream rather than by position, so it acts on the row it
396+ /// was opened on however the list is rebuilt under it.
397+ library_menu: Option<LibraryMenu>,
341 /// Which library row is picked: the file and the audio stream that row398 /// Which library row is picked: the file and the audio stream that row
342 /// names, which is what an insert needs and what survives a row list being399 /// names, which is what an insert needs and what survives a row list being
343 /// rebuilt. Its own selection and not the timeline's: Delete keeps acting400 /// rebuilt. Its own selection and not the timeline's: Delete keeps acting
@@ -1227,6 +1284,72 @@ impl Player {
1227 cx.notify();1284 cx.notify();
1228 }1285 }
1229 1286
1287+ /// Takes a library row's file out of the list, which is the one thing a row
1288+ /// can lose. Refused in the engine's own words while clips still play from
1289+ /// it -- and those words name the lanes holding them, so the refusal says
1290+ /// what to delete first. The list itself is the report that it worked: the
1291+ /// row is gone from it.
1292+ fn remove_source(&mut self, path: &Path, stream: usize, cx: &mut Context<Self>) {
1293+ if self.exporting().is_some() {
1294+ return;
1295+ }
1296+ let removed = self
1297+ .session
1298+ .as_mut()
1299+ .map(|session| session.remove_source(path, stream));
1300+ let text = match removed {
1301+ Some(Ok(())) => {
1302+ // The picked row may be the one that just went, and the engine
1303+ // reseeks, so this owes the flag reset like every other edit.
1304+ if self.selected_asset.as_ref() == Some(&(path.to_path_buf(), stream)) {
1305+ self.selected_asset = None;
1306+ }
1307+ self.reset_after_reseek();
1308+ // The undo stack goes with it (`Project::remove_source`): said
1309+ // here, because a `z` that does nothing afterwards would
1310+ // otherwise read as a bug.
1311+ format!("REMOVED {} — there is nothing left to undo", file_name(path))
1312+ }
1313+ Some(Err(e)) => format!("NOT REMOVED — {e}"),
1314+ None => "NO TIMELINE — open a file first".to_string(),
1315+ };
1316+ self.notice = Some(text.into());
1317+ cx.notify();
1318+ }
1319+
1320+ /// One item of a library row's menu, done. Every one of them closes the
1321+ /// menu first -- the list under it is about to be rebuilt -- except the one
1322+ /// that turns the card over.
1323+ fn act_on_row(&mut self, item: RowItem, cx: &mut Context<Self>) {
1324+ let Some(menu) = self.library_menu.clone() else {
1325+ return;
1326+ };
1327+ match item {
1328+ RowItem::Properties => {
1329+ if let Some(open) = &mut self.library_menu {
1330+ open.details = true;
1331+ }
1332+ }
1333+ RowItem::Add => {
1334+ self.library_menu = None;
1335+ self.insert_source(&menu.path, menu.stream, None, cx);
1336+ }
1337+ RowItem::Remove => {
1338+ self.library_menu = None;
1339+ self.remove_source(&menu.path, menu.stream, cx);
1340+ }
1341+ RowItem::Reveal => {
1342+ self.library_menu = None;
1343+ // Another process starting: off the UI thread, exactly as the
1344+ // export notice's own click starts it.
1345+ cx.background_executor()
1346+ .spawn(async move { show_in_file_manager(&menu.path) })
1347+ .detach();
1348+ }
1349+ }
1350+ cx.notify();
1351+ }
1352+
1230 /// The rate and layout the whole timeline's audio is, taken from source 0's1353 /// The rate and layout the whole timeline's audio is, taken from source 0's
1231 /// own stream: what a library row has to match to be placeable. `None`1354 /// own stream: what a library row has to match to be placeable. `None`
1232 /// until that file has been probed, and then nothing is greyed for it.1355 /// until that file has been probed, and then nothing is greyed for it.
@@ -1848,7 +1971,12 @@ impl Render for Player {
1848 // indices -- so a stroke closes it before it acts. Escape means1971 // indices -- so a stroke closes it before it acts. Escape means
1849 // that and nothing else, which is the `esc` the keys menu1972 // that and nothing else, which is the `esc` the keys menu
1850 // already lists (keymap.rs `FIXED`).1973 // already lists (keymap.rs `FIXED`).
1851- if this.context_menu.take().is_some() {1974+ // Both menus, taken rather than short-circuited: the library's
1975+ // one names a row the edits below can remove, so it closes on a
1976+ // stroke exactly as the clip menu does.
1977+ let clip_menu = this.context_menu.take().is_some();
1978+ let row_menu = this.library_menu.take().is_some();
1979+ if clip_menu || row_menu {
1852 cx.notify();1980 cx.notify();
1853 if key == ESCAPE {1981 if key == ESCAPE {
1854 return;1982 return;
@@ -1989,6 +2117,10 @@ impl Render for Player {
1989 // Over the panel it was opened on, and under the cards: it is only2117 // Over the panel it was opened on, and under the cards: it is only
1990 // ever up while neither of them is (`modal`).2118 // ever up while neither of them is (`modal`).
1991 .children(self.context_card(window.viewport_size(), cx))2119 .children(self.context_card(window.viewport_size(), cx))
2120+ // The library's own menu, the same way and for the same reason:
2121+ // over the panel it was opened on, under the cards, and never up
2122+ // while one of them is.
2123+ .children(self.library_card(window.viewport_size(), cx))
1992 // Last, so they are over everything -- they take no room in the2124 // Last, so they are over everything -- they take no room in the
1993 // column, and only one of the two is ever up.2125 // column, and only one of the two is ever up.
1994 .children(self.keys_overlay(cx))2126 .children(self.keys_overlay(cx))
@@ -2035,7 +2167,7 @@ impl Player {
2035 .as_ref()2167 .as_ref()
2036 .is_some_and(|p| *p == (row.path.clone(), row.stream));2168 .is_some_and(|p| *p == (row.path.clone(), row.stream));
2037 let name: SharedString = row.name.clone().into();2169 let name: SharedString = row.name.clone().into();
2038- let tip: SharedString = match (&row.unusable, meta) {2170+ let says: String = match (&row.unusable, meta) {
2039 // A greyed row says why in full, where its length would be:2171 // A greyed row says why in full, where its length would be:
2040 // the list is the one place the file's own tracks are named.2172 // the list is the one place the file's own tracks are named.
2041 (Some(why), _) => format!("{} — {why}", row.path.display()),2173 (Some(why), _) => format!("{} — {why}", row.path.display()),
@@ -2054,8 +2186,10 @@ impl Player {
2054 meta.frame_rate2186 meta.frame_rate
2055 ),2187 ),
2056 (None, None) => row.path.display().to_string(),2188 (None, None) => row.path.display().to_string(),
2057- }2189+ };
2058- .into();2190+ // The menu is the third way into a row, after the click and the
2191+ // drag, and a right-click nothing advertises is one nobody finds.
2192+ let tip: SharedString = format!("{says} · right-click for more").into();
2059 let ghost = name.clone();2193 let ghost = name.clone();
2060 // What the second line says: the stream, then either its length or2194 // What the second line says: the stream, then either its length or
2061 // the reason it cannot be used.2195 // the reason it cannot be used.
@@ -2069,6 +2203,7 @@ impl Player {
2069 let usable = row.unusable.is_none();2203 let usable = row.unusable.is_none();
2070 let (path, stream) = (row.path.clone(), row.stream);2204 let (path, stream) = (row.path.clone(), row.stream);
2071 let dragged = (path.clone(), stream);2205 let dragged = (path.clone(), stream);
2206+ let menu_path = path.clone();
2072 div()2207 div()
2073 .id(("asset", i))2208 .id(("asset", i))
2074 .flex_none()2209 .flex_none()
@@ -2096,6 +2231,33 @@ impl Player {
2096 cx.new(|_| Tip(ghost.clone()))2231 cx.new(|_| Tip(ghost.clone()))
2097 })2232 })
2098 })2233 })
2234+ // The right button hangs the row's own menu at the pointer.
2235+ // Every row takes it, greyed ones included: a file that cannot
2236+ // join this timeline can still be revealed, described and taken
2237+ // out of the list, and Add is the one item that then refuses --
2238+ // in the engine's words, where the row's grey already says why.
2239+ .on_mouse_down(
2240+ MouseButton::Right,
2241+ cx.listener(move |this, event: &MouseDownEvent, _, cx| {
2242+ if this.modal() {
2243+ return;
2244+ }
2245+ // Picked as a left-click would pick it, so the row the
2246+ // menu is about is the row that reads as chosen -- but
2247+ // only a row that *can* be picked, which is what keeps
2248+ // the Add button under the list honest.
2249+ if usable {
2250+ this.selected_asset = Some((menu_path.clone(), stream));
2251+ }
2252+ this.library_menu = Some(LibraryMenu {
2253+ path: menu_path.clone(),
2254+ stream,
2255+ at: event.position,
2256+ details: false,
2257+ });
2258+ cx.notify();
2259+ }),
2260+ )
2099 .when(picked, |d| d.bg(rgb(SELECTED)).border_1())2261 .when(picked, |d| d.bg(rgb(SELECTED)).border_1())
2100 .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())2262 .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())
2101 // Full height and hard against the edge: the tint reads as2263 // Full height and hard against the edge: the tint reads as
@@ -3211,6 +3373,157 @@ impl Player {
3211 )3373 )
3212 }3374 }
3213 3375
3376+ /// The menu a right-click on a library row opens: what can be done with the
3377+ /// *file* rather than with a clip of it, and a turn-over side saying what
3378+ /// that file is. Built like [`Player::context_card`] down to the scrim, the
3379+ /// row height and the clamp, because it is the same menu on the other panel
3380+ /// -- a click away or any stroke closes it.
3381+ fn library_card(
3382+ &self,
3383+ viewport: Size<Pixels>,
3384+ cx: &mut Context<Self>,
3385+ ) -> Option<impl IntoElement> {
3386+ let menu = self.library_menu.clone()?;
3387+ let path = menu.path.clone();
3388+ let row = |n: usize| {
3389+ div()
3390+ .id(("library-menu", n))
3391+ .flex()
3392+ .min_h(px(MENU_ROW_H))
3393+ .items_center()
3394+ .justify_between()
3395+ .gap(px(12.))
3396+ .px(px(6.))
3397+ .rounded(px(3.))
3398+ };
3399+ let mut rows: Vec<AnyElement> = Vec::new();
3400+ if menu.details {
3401+ // What the library knows about this row and nothing probed for the
3402+ // card: the streams table is filled once per file at import.
3403+ let info = self
3404+ .streams
3405+ .get(&path)
3406+ .and_then(|of_file| of_file.iter().find(|s| s.index == menu.stream));
3407+ let frames = self.session.as_ref().map_or(0, |session| {
3408+ source_frames(lane_clips(session), session.sources(), &path)
3409+ });
3410+ // How many clips play from this exact row -- the number that
3411+ // decides whether Remove is refused, so the card answers the
3412+ // question the refusal would otherwise raise.
3413+ let placed = self.session.as_ref().map_or(0, |session| {
3414+ let of_row = session
3415+ .sources()
3416+ .iter()
3417+ .position(|s| s.path == path && s.audio_stream == menu.stream);
3418+ of_row.map_or(0, |idx| {
3419+ lane_clips(session).filter(|c| c.source == idx).count()
3420+ })
3421+ });
3422+ for (label, value) in [
3423+ ("File", file_name(&path)),
3424+ ("Path", path.display().to_string()),
3425+ (
3426+ "Audio",
3427+ info.map_or_else(|| "no track of its own".to_string(), stream_detail),
3428+ ),
3429+ ("Length", timecode(f64::from(frames) / self.fps, self.fps)),
3430+ ("On the timeline", format!("{placed} clips")),
3431+ ] {
3432+ rows.push(
3433+ row(rows.len())
3434+ .child(label)
3435+ .child(
3436+ div()
3437+ .min_w(px(0.))
3438+ .truncate()
3439+ .text_size(px(11.))
3440+ .text_color(rgb(INK_DIM))
3441+ .child(value),
3442+ )
3443+ .into_any_element(),
3444+ );
3445+ }
3446+ } else {
3447+ // Everything but Add works without a timeline open -- and with no
3448+ // timeline there are no rows to right-click at all, so this is the
3449+ // export guard's shape and not a second policy.
3450+ let live = self.session.is_some() && self.exporting().is_none();
3451+ for item in ROW_ITEMS {
3452+ let enabled = match item {
3453+ RowItem::Add | RowItem::Remove => live,
3454+ RowItem::Reveal | RowItem::Properties => true,
3455+ };
3456+ rows.push(
3457+ row(rows.len())
3458+ .child(item.label())
3459+ .child(div().text_color(rgb(INK_DIM)).child(item.hint()))
3460+ .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed())
3461+ .when(enabled, |d| {
3462+ d.cursor_pointer()
3463+ .hover(|s| s.bg(rgb(HOVER)))
3464+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
3465+ this.act_on_row(item, cx);
3466+ }))
3467+ })
3468+ .into_any_element(),
3469+ );
3470+ }
3471+ }
3472+ let (x, y) = menu_at(
3473+ menu.at,
3474+ viewport,
3475+ MENU_PAD * 2. + rows.len() as f32 * MENU_ROW_H,
3476+ );
3477+ let full: SharedString = path.display().to_string().into();
3478+ Some(
3479+ div()
3480+ .absolute()
3481+ .inset_0()
3482+ .on_mouse_down(
3483+ MouseButton::Left,
3484+ cx.listener(|this, _: &MouseDownEvent, _, cx| {
3485+ this.library_menu = None;
3486+ cx.notify();
3487+ cx.stop_propagation();
3488+ }),
3489+ )
3490+ .on_mouse_down(
3491+ MouseButton::Right,
3492+ cx.listener(|this, _: &MouseDownEvent, _, cx| {
3493+ this.library_menu = None;
3494+ cx.notify();
3495+ cx.stop_propagation();
3496+ }),
3497+ )
3498+ .child(
3499+ div()
3500+ .id("library-menu-card")
3501+ .absolute()
3502+ .left(px(x))
3503+ .top(px(y))
3504+ .w(px(MENU_W))
3505+ .flex()
3506+ .flex_col()
3507+ .p(px(MENU_PAD))
3508+ .rounded(px(6.))
3509+ .bg(rgb(SURFACE))
3510+ // Painted after the scrim, so this listener runs first
3511+ // and a press meant for an item never closes the menu
3512+ // out from under its own click (`context_card`).
3513+ .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| {
3514+ cx.stop_propagation()
3515+ })
3516+ .on_mouse_down(MouseButton::Right, |_: &MouseDownEvent, _, cx| {
3517+ cx.stop_propagation()
3518+ })
3519+ .when(menu.details, |d| {
3520+ d.tooltip(move |_, cx| cx.new(|_| Tip(full.clone())).into())
3521+ })
3522+ .children(rows),
3523+ ),
3524+ )
3525+ }
3526+
3214 /// The menu a right-click on a clip opens: what that clip can be given,3527 /// The menu a right-click on a clip opens: what that clip can be given,
3215 /// each item beside the stroke that does the very same thing, and a3528 /// each item beside the stroke that does the very same thing, and a
3216 /// turn-over side that says what the clip *is*. An item that would do3529 /// turn-over side that says what the clip *is*. An item that would do
@@ -5179,6 +5492,52 @@ mod tests {
5179 );5492 );
5180 }5493 }
5181 5494
5495+ /// Remove from library, through the door the menu item uses
5496+ /// ([`Player::remove_source`] calls exactly this): refused by name while
5497+ /// clips play from the file, and once they do not the row leaves the list.
5498+ #[test]
5499+ fn removing_a_row_is_refused_while_it_plays_and_takes_the_row_away() {
5500+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
5501+ session.set_gain(0.0);
5502+ session.import(&asset("test_av2.mp4")).expect("av2 matches");
5503+ let second = session.sources()[1].path.clone();
5504+ let streams = HashMap::new();
5505+ let rows = |session: &PlaybackSession| {
5506+ library_rows(session.sources(), &streams, None, |_| 0).len()
5507+ };
5508+ assert_eq!(rows(&session), 2, "a row per source");
5509+
5510+ let refusal = session
5511+ .remove_source(&second, 0)
5512+ .expect_err("its take is still on the timeline")
5513+ .to_string();
5514+ assert!(refusal.contains("still plays"), "{refusal}");
5515+ assert!(
5516+ refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
5517+ "the refusal names the lanes to clear: {refusal}"
5518+ );
5519+ assert_eq!(rows(&session), 2, "and the row is still there");
5520+
5521+ // Delete that take -- the whole group, from either half -- and the file
5522+ // can go. The list is what says so.
5523+ let last = session.lane_clips(Lane::V1).len() - 1;
5524+ assert!(session.delete_clip(Lane::V1, last));
5525+ session
5526+ .remove_source(&second, 0)
5527+ .expect("nothing plays av2 any more");
5528+ assert_eq!(rows(&session), 1, "the row went with it");
5529+ assert_eq!(session.sources().len(), 1);
5530+ // The one file left cannot go: a project that names none is not one
5531+ // that reopens.
5532+ let refusal = session
5533+ .remove_source(&session.sources()[0].path.clone(), 0)
5534+ .expect_err("the last file stays")
5535+ .to_string();
5536+ assert!(refusal.contains("only file"), "{refusal}");
5537+ // A row this timeline never had is refused, not panicked on.
5538+ assert!(session.remove_source(&second, 0).is_err());
5539+ }
5540+
5182 /// The move-a-clip-between-tracks path through the door the drop uses5541 /// The move-a-clip-between-tracks path through the door the drop uses
5183 /// ([`Player::move_clip`] calls exactly this): the clip changes row, the5542 /// ([`Player::move_clip`] calls exactly this): the clip changes row, the
5184 /// *picture* comes from the new row afterwards -- which is what "it plays5543 /// *picture* comes from the new row afterwards -- which is what "it plays
@@ -6221,6 +6580,7 @@ fn main() {
6221 ruler: Rc::default(),6580 ruler: Rc::default(),
6222 selected: None,6581 selected: None,
6223 context_menu: None,6582 context_menu: None,
6583+ library_menu: None,
6224 selected_asset: None,6584 selected_asset: None,
6225 waves: HashMap::new(),6585 waves: HashMap::new(),
6226 streams: HashMap::new(),6586 streams: HashMap::new(),
crates/engine/src/playback.rsmodified+23 -0
@@ -764,6 +764,29 @@ impl PlaybackSession {
764 })764 })
765 }765 }
766 766
767+ /// Takes `path` played on `stream` out of the library -- the door a library
768+ /// row's own remove goes through, naming the row exactly as
769+ /// [`place_stream_at`](Self::place_stream_at) does. Refused in
770+ /// [`Project::remove_source`]'s words while a clip still plays from it, and
771+ /// for a row this timeline does not have.
772+ ///
773+ /// Reseeks like an edit even though nothing playable changed: the clip
774+ /// indexes into the source list have just moved, and the running workers
775+ /// were opened against the old numbering.
776+ pub fn remove_source(&mut self, path: &Path, stream: usize) -> crate::Result<()> {
777+ let wanted = Source::new(path, stream);
778+ let idx = self
779+ .project
780+ .sources()
781+ .iter()
782+ .position(|s| *s == wanted)
783+ .ok_or_else(|| format!("{} is not on this timeline", path.display()))?;
784+ self.project.remove_source(idx)?;
785+ let now = self.now();
786+ self.seek(now);
787+ Ok(())
788+ }
789+
767 /// What the timeline's audio *is*: source 0's chosen stream, probed. Every790 /// What the timeline's audio *is*: source 0's chosen stream, probed. Every
768 /// other source is held to it.791 /// other source is held to it.
769 fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> {792 fn first_audio(&self) -> crate::Result<Option<crate::AudioProbe>> {
crates/engine/src/project.rsmodified+135 -0
@@ -508,6 +508,60 @@ impl Project {
508 true508 true
509 }509 }
510 510
511+ /// Drops a source entry -- the file a library row *is* -- and renumbers
512+ /// every clip that indexed past it, which is why this is more than a
513+ /// `Vec::remove`.
514+ ///
515+ /// Refused, changing nothing, while any clip still plays from it: the
516+ /// refusal names the lanes and how many clips each holds, so a caller can
517+ /// say what has to be deleted first. Refused too for the last entry left,
518+ /// because a project that names no file cannot be reopened
519+ /// (`PlaybackSession::open_project`) and the timeline's audio parameters
520+ /// are read off source 0.
521+ ///
522+ /// ponytail: this retires the undo stack. `history` holds lanes alone, so a
523+ /// snapshot older than the removal can name the very source being removed
524+ /// (delete a file's clips, then remove the file) and restoring it would
525+ /// point a clip at an entry that is gone. The upgrade path is snapshotting
526+ /// `sources` beside `lanes` in [`snapshot`](Project::snapshot) -- which the
527+ /// "indexes are forever" rule ([`append_clip`](Project::append_clip), and
528+ /// the reason [`without_orphan_sources`](Project::without_orphan_sources)
529+ /// exists) currently rules out.
530+ pub fn remove_source(&mut self, idx: usize) -> crate::Result<()> {
531+ let Some(source) = self.sources.get(idx) else {
532+ return Err(format!("there is no source {idx} to remove").into());
533+ };
534+ let name = source.path.display().to_string();
535+ // Asked before the clips are counted: with one file left the answer is
536+ // the same whatever plays, and "the only file" is the more useful half
537+ // of it.
538+ if self.sources.len() == 1 {
539+ return Err(format!("{name} is the only file this project names").into());
540+ }
541+ let used: Vec<String> = handles(&self.lanes)
542+ .into_iter()
543+ .zip(&self.lanes)
544+ .filter_map(
545+ |(lane, data)| match data.clips.iter().filter(|c| c.source == idx).count() {
546+ 0 => None,
547+ 1 => Some(format!("{} (1 clip)", lane.label())),
548+ n => Some(format!("{} ({n} clips)", lane.label())),
549+ },
550+ )
551+ .collect();
552+ if !used.is_empty() {
553+ return Err(format!("{name} still plays on {}", used.join(", ")).into());
554+ }
555+ self.sources.remove(idx);
556+ for c in self.lanes.iter_mut().flat_map(|l| &mut l.clips) {
557+ if c.source > idx {
558+ c.source -= 1;
559+ }
560+ }
561+ self.history.clear();
562+ Ok(())
563+ }
564+
511 /// The sources a clip actually names, with the clips reindexed onto them565 /// The sources a clip actually names, with the clips reindexed onto them
512 /// -- what a save writes. Indexes are forever *inside* a session (see566 /// -- what a save writes. Indexes are forever *inside* a session (see
513 /// [`Project::append_clip`]), so an undone import leaves an orphan source567 /// [`Project::append_clip`]), so an undone import leaves an orphan source
@@ -2362,6 +2416,87 @@ mod tests {
2362 assert_eq!(reloaded.sources().len(), 2);2416 assert_eq!(reloaded.sources().len(), 2);
2363 }2417 }
2364 2418
2419+ /// Taking a file out of the library: refused by name -- lanes and counts --
2420+ /// while a clip still plays from it, and once nothing does, the entry goes
2421+ /// and every clip that indexed past it is renumbered onto the short list.
2422+ #[test]
2423+ fn remove_source_refuses_what_plays_and_renumbers_what_is_left() {
2424+ // Sources 0 (FILE, three clips) and 1 (FILE2, one take on both lanes),
2425+ // plus a second stream of FILE as source 2 with a take of its own.
2426+ let mut p = two_sources();
2427+ assert_eq!(p.import(FILE, 1), 2, "another stream is another source");
2428+ assert!(p.append_clip(2, 4));
2429+
2430+ let refusal = p
2431+ .remove_source(1)
2432+ .expect_err("a source with clips on it cannot go")
2433+ .to_string();
2434+ assert!(refusal.contains(FILE2), "names the file: {refusal}");
2435+ assert!(
2436+ refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
2437+ "names the lanes holding it: {refusal}"
2438+ );
2439+ assert!(refusal.contains("still plays"), "{refusal}");
2440+ assert_eq!(p.sources().len(), 3, "a refusal changes nothing");
2441+ assert_eq!(shape(&p)[0][3].source, 1);
2442+
2443+ // Delete FILE2's take -- the whole span, on every lane -- and the entry
2444+ // is free to go. Source 2's clips become source 1's.
2445+ assert!(p.delete_in(Lane::V1, 3));
2446+ assert!(!p.clips().iter().any(|c| c.source == 1), "nothing plays it");
2447+ p.remove_source(1).expect("nothing plays FILE2 any more");
2448+ assert_eq!(
2449+ p.sources(),
2450+ [Source::new(FILE, 0), Source::new(FILE, 1)],
2451+ "the middle entry is gone"
2452+ );
2453+ assert_eq!(
2454+ shape(&p)[0].iter().map(|c| c.source).collect::<Vec<_>>(),
2455+ [0, 0, 0, 1],
2456+ "the clips past it renumbered"
2457+ );
2458+ assert_eq!(
2459+ shape(&p)[1].iter().map(|c| c.source).collect::<Vec<_>>(),
2460+ [0, 0, 0, 1],
2461+ "on every lane"
2462+ );
2463+ // What is left is a project that still loads, which is the whole point
2464+ // of renumbering rather than leaving a hole.
2465+ let (sources, lanes, eq, color) = p.without_orphan_sources();
2466+ Project::from_parts(sources, lanes, eq, color).expect("from_parts");
2467+ }
2468+
2469+ /// The two edges of a removal: it retires the undo stack (the ponytail on
2470+ /// [`Project::remove_source`]), and the last entry standing cannot go --
2471+ /// source 0 is where a reopened project reads its frame rate.
2472+ #[test]
2473+ fn remove_source_retires_undo_and_keeps_the_last_file() {
2474+ let mut p = two_sources();
2475+ assert!(p.delete_in(Lane::V1, 3), "FILE2's take goes first");
2476+ assert!(!p.history.is_empty(), "there is something to undo");
2477+ p.remove_source(1).expect("nothing plays FILE2");
2478+ assert!(
2479+ p.history.is_empty(),
2480+ "a snapshot naming the removed source must not survive it"
2481+ );
2482+ assert!(!p.undo(), "and so there is nothing left to undo");
2483+
2484+ // The last file standing stays, whatever plays from it:
2485+ // `PlaybackSession::open_project` refuses a project that names no
2486+ // sources at all, and the timeline's frame rate lives in source 0.
2487+ assert_eq!(p.sources().len(), 1);
2488+ let refusal = p
2489+ .remove_source(0)
2490+ .expect_err("the only source must stay")
2491+ .to_string();
2492+ assert!(refusal.contains("only file"), "{refusal}");
2493+ assert_eq!(p.sources().len(), 1);
2494+ assert!(
2495+ p.remove_source(1).is_err(),
2496+ "and an index that is not there is refused, not panicked on"
2497+ );
2498+ }
2499+
2365 /// A clip's equalizer is the clip's: it survives every edit that copies a2500 /// A clip's equalizer is the clip's: it survives every edit that copies a
2366 /// placement, and it comes back with an undo.2501 /// placement, and it comes back with an undo.
2367 #[test]2502 #[test]