forge
Explore
Log in

Don't you dare go Hollow

Media panel with tint swatches, drag-to-timeline

Browse files at this commit

5bc0cf50f34c4ac16a4cd013dc207dd64ebd2542Ahmet Kaan GümüşParent: 591afa3
  • feat
    • media panel with tint swatches, drag-to-timeline
Show full message
✨ feat(library): media panel with tint swatches, drag-to-timeline

A column beside the picture lists every source the timeline knows: name,
duration and the tint its clips wear, which is what ties a row to the
boxes below. A click picks a row, the button under the list drops that
source in at the playhead, and a row dragged onto either lane goes
through the same call, so there is one answer to what adding does.

Import moves into the list it adds to. Peaks now decode on a background
thread with a bed drawn meanwhile, so a long file no longer stops the
window painting on its first repaint. The window finally tells the
compositor its name and its app id.
crates/app/src/main.rsmodified+624 -71
@@ -72,6 +72,19 @@ const WAVE_COL: f32 = 2.;
72 /// WCAG 2.5.8: nothing clickable is smaller than this. The scrub bar stays 6 px72 /// WCAG 2.5.8: nothing clickable is smaller than this. The scrub bar stays 6 px
73 /// to look at -- `RULER_HIT_H` is the strip that has to be hit.73 /// to look at -- `RULER_HIT_H` is the strip that has to be hit.
74 const HIT_MIN: f32 = 24.;74 const HIT_MIN: f32 = 24.;
75+/// The media library's column: a share of the window rather than a fixed width,
76+/// so it yields on a narrow one, and never more than a third of it -- the
77+/// picture is what this program is for and keeps the majority at every size.
78+/// The floor is what a file name and a timecode need to be readable at all.
79+const LIBRARY_FRAC: f32 = 0.2;
80+const LIBRARY_MIN_W: f32 = 120.;
81+const LIBRARY_MAX_W: f32 = 220.;
82+/// A library row: a name over its duration, two lines and a click target, so
83+/// `HIT_MIN` binds it like every other one.
84+const ROW_H: f32 = 32.;
85+/// The tint swatch down the left of a row: the same colour that source's clips
86+/// wear in the lanes, which is the whole of the panel<->timeline association.
87+const SWATCH_W: f32 = 4.;
75 const CONTROL_H: f32 = 28.;88 const CONTROL_H: f32 = 28.;
76 const RULER_HIT_H: f32 = HIT_MIN;89 const RULER_HIT_H: f32 = HIT_MIN;
77 /// Wide enough for `HH:MM:SS:FF / HH:MM:SS:FF`, and fixed so changing digits90 /// Wide enough for `HH:MM:SS:FF / HH:MM:SS:FF`, and fixed so changing digits
@@ -92,6 +105,10 @@ const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H;
92 /// through the keymap to find it.105 /// through the keymap to find it.
93 const ESCAPE: &str = "escape";106 const ESCAPE: &str = "escape";
94 107
108+/// What the header says with no timeline open, and what the window title reads
109+/// as a program name rather than as a file name.
110+const NO_FILE: &str = "no file open";
111+
95 /// What the monitoring output is set to. Two things, not one: the level the112 /// What the monitoring output is set to. Two things, not one: the level the
96 /// user picked, and whether it is being held silent -- so unmuting comes back113 /// user picked, and whether it is being held silent -- so unmuting comes back
97 /// to the level rather than to a guess.114 /// to the level rather than to a guess.
@@ -154,6 +171,23 @@ impl Default for Volume {
154 }171 }
155 }172 }
156 173
174+/// What is known about a source's audio. Three states and not two, because a
175+/// file whose peaks have not come back yet must not be drawn as one that has no
176+/// audio at all: the first shows a bed, the second shows nothing.
177+#[derive(Clone)]
178+enum Wave {
179+ /// Asked for; the decode is running on a background thread.
180+ Loading,
181+ /// The file has no audio track. An answer, not a miss.
182+ Silent,
183+ Peaks(Arc<Vec<(f32, f32)>>),
184+}
185+
186+/// A library row being dragged. The source index and nothing else: the row is
187+/// only a way of naming a source, and where it lands does not change what is
188+/// inserted.
189+struct AssetDrag(usize);
190+
157 struct Player {191 struct Player {
158 /// The timeline, once there is one. A run with no file opens without it and192 /// The timeline, once there is one. A run with no file opens without it and
159 /// waits: the first media import or project load is what fills it, and193 /// waits: the first media import or project load is what fills it, and
@@ -181,10 +215,16 @@ struct Player {
181 /// screen, but Lift has to know which half it was aimed at. Indices move215 /// screen, but Lift has to know which half it was aimed at. Indices move
182 /// under every edit, so this is cleared by all of them.216 /// under every edit, so this is cleared by all of them.
183 selected: Option<(Lane, usize)>,217 selected: Option<(Lane, usize)>,
184- /// Peaks per source file, taken once and kept. `None` is a source with no218+ /// Which library row is picked, as an index into the session's sources.
185- /// audio track, which is an answer and not a miss: it must not be asked219+ /// Its own selection and not the timeline's: Delete keeps acting on the
186- /// again every repaint.220+ /// clip that was clicked in a lane, whatever the library is showing. Source
187- waves: HashMap<PathBuf, Option<Arc<Vec<(f32, f32)>>>>,221+ /// indexes are forever (project.rs:264), so this cannot go stale under an
222+ /// edit -- only a new session clears it.
223+ selected_asset: Option<usize>,
224+ /// What is known about each source's audio, taken once and kept. Keyed on
225+ /// the path, and the key is inserted the moment the decode is *started*:
226+ /// presence means "asked", so a repaint mid-decode cannot ask again.
227+ waves: HashMap<PathBuf, Wave>,
188 /// The copied clip. Frame ranges only, so it survives the clip it was taken228 /// The copied clip. Frame ranges only, so it survives the clip it was taken
189 /// from being deleted -- and it outlives the selection.229 /// from being deleted -- and it outlives the selection.
190 clipboard: Option<Clip>,230 clipboard: Option<Clip>,
@@ -237,6 +277,10 @@ struct Player {
237 /// until it is answered -- any key retires it, so does a click on it -- so a277 /// until it is answered -- any key retires it, so does a click on it -- so a
238 /// failure is read in full instead of blinking past.278 /// failure is read in full instead of blinking past.
239 notice: Option<SharedString>,279 notice: Option<SharedString>,
280+ /// What the compositor was last told this window is called. Setting a title
281+ /// is a protocol round trip and a repaint is sixty a second, so the title is
282+ /// pushed only when it is not this any more.
283+ titled: String,
240 displayed: u32,284 displayed: u32,
241 dropped: u32,285 dropped: u32,
242 /// Wall clock of the first displayed frame -- the real-speed measurement.286 /// Wall clock of the first displayed frame -- the real-speed measurement.
@@ -430,31 +474,50 @@ impl Player {
430 }474 }
431 }475 }
432 476
433- /// Fills the peak cache for every source that has arrived since the last477+ /// Starts a peak decode for every source that has arrived since the last
434 /// repaint. One call from the render rather than three at the doors,478 /// repaint. One call from the render rather than three at the doors,
435 /// because argv, an import and a project load are all doors and only this479 /// because argv, an import and a project load are all doors and only this
436 /// one is guaranteed to run after each of them.480 /// one is guaranteed to run after each of them.
437 ///481 ///
438- /// ponytail: the decode is synchronous, so the first repaint after a long482+ /// The decode itself runs on a background thread, like the file chooser:
439- /// file arrives waits on it -- ~0.3 s for ten minutes at the decoder's483+ /// whole-file audio decode is ~1 s for a half-hour source, and on the render
440- /// ~1700x realtime. Upgrade path is `cx.background_executor().spawn` with484+ /// path that is the window not painting for a second. The lane draws a bed
441- /// the peaks posted back, the way the file chooser already runs off-thread.485+ /// meanwhile and the repaint comes with the peaks. The entry is written
442- fn cache_waves(&mut self) {486+ /// *before* the spawn, so the sixty repaints that happen while a decode runs
487+ /// start no further ones.
488+ fn cache_waves(&mut self, cx: &mut Context<Self>) {
443 let Some(session) = &self.session else {489 let Some(session) = &self.session else {
444 return;490 return;
445 };491 };
446- let sources: Vec<PathBuf> = session492+ for path in unseen_sources(session.sources(), &self.waves) {
447- .sources()493+ self.waves.insert(path.clone(), Wave::Loading);
448- .iter()494+ let decoded = cx.background_executor().spawn({
449- .filter(|path| !self.waves.contains_key(*path))495+ let path = path.clone();
450- .cloned()496+ async move {
451- .collect();497+ engine::waveform::peaks(&path, WAVE_BPS)
452- for path in sources {498+ .ok()
453- let peaks = engine::waveform::peaks(&path, WAVE_BPS)499+ .flatten()
454- .ok()500+ .map(|peaks| Arc::new(normalise(peaks)))
455- .flatten()501+ }
456- .map(|peaks| Arc::new(normalise(peaks)));502+ });
457- self.waves.insert(path, peaks);503+ cx.spawn(async move |this, cx| {
504+ let decoded = decoded.await;
505+ this.update(cx, |this, cx| {
506+ this.waves.insert(
507+ path,
508+ match decoded {
509+ Some(peaks) => Wave::Peaks(peaks),
510+ // Either no audio track or a file we could not read
511+ // it from; both mean the lane has nothing to draw,
512+ // and neither is worth asking about again.
513+ None => Wave::Silent,
514+ },
515+ );
516+ cx.notify();
517+ })
518+ .ok();
519+ })
520+ .detach();
458 }521 }
459 }522 }
460 523
@@ -479,6 +542,45 @@ impl Player {
479 cx.notify();542 cx.notify();
480 }543 }
481 544
545+ /// The one way a library row reaches the timeline: the Add button and a row
546+ /// dragged onto a lane both come here, so there is a single answer to what
547+ /// "add this source" does. The whole source goes in at the playhead as one
548+ /// grouped take -- the same insert a paste makes, so everything after it
549+ /// moves along rather than being painted over. Reseeks like every other
550+ /// edit, and drops the timeline's selection with it: the insert has just
551+ /// moved the indices it pointed at.
552+ fn insert_source(&mut self, source: usize, cx: &mut Context<Self>) {
553+ if self.exporting().is_some() {
554+ return;
555+ }
556+ let clip = self.session.as_ref().and_then(|session| {
557+ let frames = source_frames(lane_clips(session), source);
558+ // Zero means nothing on the timeline plays from that file any more
559+ // -- an undone import leaves the source entry behind (project.rs:264)
560+ // -- so there is no length to insert and no file to ask for one.
561+ (frames > 0).then_some(Clip {
562+ start: 0,
563+ in_frame: 0,
564+ out_frame: frames,
565+ source,
566+ link: None,
567+ })
568+ });
569+ let added = match (&mut self.session, clip) {
570+ (Some(session), Some(clip)) => session.paste_at(session.now(), clip),
571+ _ => false,
572+ };
573+ if added {
574+ self.selected = None;
575+ self.reset_after_reseek();
576+ } else {
577+ self.notice = Some(
578+ "NOTHING ADDED — no clip on the timeline plays from that file any more".into(),
579+ );
580+ }
581+ cx.notify();
582+ }
583+
482 /// Appends a file to the end of the timeline. A drop is not a key press, so584 /// Appends a file to the end of the timeline. A drop is not a key press, so
483 /// the export guard on the key handler does not cover it and this checks for585 /// the export guard on the key handler does not cover it and this checks for
484 /// itself. The engine reseeks, so like a delete it owes the flag reset; a586 /// itself. The engine reseeks, so like a delete it owes the flag reset; a
@@ -577,6 +679,9 @@ impl Player {
577 // different file -- or none -- in another project.679 // different file -- or none -- in another project.
578 self.clipboard = None;680 self.clipboard = None;
579 self.selected = None;681 self.selected = None;
682+ // A different set of sources: the row that was picked is not
683+ // the file that index names any more.
684+ self.selected_asset = None;
580 // The counters describe one timeline; the eof line must not685 // The counters describe one timeline; the eof line must not
581 // report the old one's frames against the new one.686 // report the old one's frames against the new one.
582 self.displayed = 0;687 self.displayed = 0;
@@ -831,7 +936,14 @@ impl Render for Player {
831 // Every way a source can arrive -- argv, an import, a project load --936 // Every way a source can arrive -- argv, an import, a project load --
832 // has been through a repaint by the time its clips are drawn, so this937 // has been through a repaint by the time its clips are drawn, so this
833 // is the one place that has to notice a new one.938 // is the one place that has to notice a new one.
834- self.cache_waves();939+ self.cache_waves(cx);
940+ // What the compositor calls this window. Pushed only when it changes:
941+ // it is a protocol round trip and this runs at vsync.
942+ let title = window_title(&self.name);
943+ if title != self.titled {
944+ window.set_window_title(&title);
945+ self.titled = title;
946+ }
835 // No shadow flag: the clock is the only truth about play state.947 // No shadow flag: the clock is the only truth about play state.
836 let playing = self948 let playing = self
837 .session949 .session
@@ -1022,32 +1134,44 @@ impl Render for Player {
1022 .bg(rgb(CHROME))1134 .bg(rgb(CHROME))
1023 .child(self.name.clone()),1135 .child(self.name.clone()),
1024 )1136 )
1137+ // The library beside the picture rather than under it: a media pool
1138+ // is a column in every editor that has one, and the timeline below
1139+ // already owns the full width. `library_w` is what keeps the
1140+ // picture the majority of the row at every window size.
1025 .child(1141 .child(
1026 div()1142 div()
1027 .flex_1()1143 .flex_1()
1028 .min_h(px(0.))1144 .min_h(px(0.))
1029- .overflow_hidden()
1030 .flex()1145 .flex()
1031- .justify_center()1146+ .child(self.library(library_w(f32::from(window.viewport_size().width)), cx))
1032- .items_center()1147+ .child(
1033- .children(1148+ div()
1034- self.image1149+ .flex_1()
1035- .clone()1150+ .min_w(px(0.))
1036- .map(|i| {1151+ .overflow_hidden()
1037- img(i)1152+ .flex()
1038- .size_full()1153+ .justify_center()
1039- .object_fit(gpui::ObjectFit::Contain)1154+ .items_center()
1040- .into_any_element()1155+ .children(
1041- })1156+ self.image
1042- // With no file open the letterbox is the whole1157+ .clone()
1043- // window, and a black rectangle says only that1158+ .map(|i| {
1044- // something is broken -- so it says what it wants1159+ img(i)
1045- // instead. The window is already the drop target.1160+ .size_full()
1046- .or_else(|| {1161+ .object_fit(gpui::ObjectFit::Contain)
1047- self.session1162+ .into_any_element()
1048- .is_none()1163+ })
1049- .then(|| empty_hint().into_any_element())1164+ // With no file open the letterbox is the
1050- }),1165+ // whole window, and a black rectangle says
1166+ // only that something is broken -- so it
1167+ // says what it wants instead. The window is
1168+ // already the drop target.
1169+ .or_else(|| {
1170+ self.session
1171+ .is_none()
1172+ .then(|| empty_hint().into_any_element())
1173+ }),
1174+ ),
1051 ),1175 ),
1052 )1176 )
1053 // Above the panel and only when there is one to show, so it costs1177 // Above the panel and only when there is one to show, so it costs
@@ -1062,6 +1186,173 @@ impl Render for Player {
1062 }1186 }
1063 1187
1064 impl Player {1188 impl Player {
1189+ /// The media library: a row per source the timeline knows, in the order
1190+ /// they arrived, each wearing the tint its clips wear in the lanes -- the
1191+ /// swatch *is* what says which boxes down there came from this file. A
1192+ /// click picks a row, the button under the list drops that source in at the
1193+ /// playhead, and a row dragged onto either lane does the same thing through
1194+ /// the same call.
1195+ ///
1196+ /// Import lives here, because this is the list it adds to. Plain divs like
1197+ /// the rest of this window: nothing in it takes focus, so the root keeps
1198+ /// the keyboard and the play key still works after a row is clicked
1199+ /// (ledger:182).
1200+ fn library(&self, width: f32, cx: &mut Context<Self>) -> impl IntoElement {
1201+ let exporting = self.exporting().is_some();
1202+ let sources = self
1203+ .session
1204+ .as_ref()
1205+ .map_or(&[][..], PlaybackSession::sources);
1206+ // Every source matches the first in size and rate or it was refused at
1207+ // the door (the import policy, ledger:436), so the session's own meta
1208+ // describes every row and nothing has to be probed to say so.
1209+ let meta = self.session.as_ref().map(PlaybackSession::meta);
1210+ let rows: Vec<_> = sources
1211+ .iter()
1212+ .enumerate()
1213+ .map(|(i, path)| {
1214+ let picked = self.selected_asset == Some(i);
1215+ let frames = self
1216+ .session
1217+ .as_ref()
1218+ .map_or(0, |session| source_frames(lane_clips(session), i));
1219+ let name: SharedString = file_name(path).into();
1220+ let tip: SharedString = match meta {
1221+ Some(meta) => format!(
1222+ "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead",
1223+ path.display(),
1224+ meta.width,
1225+ meta.height,
1226+ meta.frame_rate
1227+ ),
1228+ None => path.display().to_string(),
1229+ }
1230+ .into();
1231+ let ghost = name.clone();
1232+ div()
1233+ .id(("asset", i))
1234+ .flex_none()
1235+ .h(px(ROW_H))
1236+ .flex()
1237+ .items_center()
1238+ .gap(px(6.))
1239+ .pr(px(6.))
1240+ .rounded(px(3.))
1241+ .cursor_pointer()
1242+ .hover(|s| s.bg(rgb(HOVER)))
1243+ .when(picked, |d| d.bg(rgb(SELECTED)).border_1())
1244+ .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())
1245+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
1246+ this.selected_asset = Some(i);
1247+ cx.notify();
1248+ }))
1249+ // The drag carries the row's source and the row's name: one
1250+ // for the drop to insert, one for the pointer to carry, so
1251+ // what is being dragged is legible on the way down.
1252+ .on_drag(AssetDrag(i), move |_, _, _, cx| {
1253+ cx.new(|_| Tip(ghost.clone()))
1254+ })
1255+ // Full height and hard against the edge: the tint reads as
1256+ // the lane's colour continuing into the list, not as a chip
1257+ // that happens to be near it.
1258+ .child(
1259+ div()
1260+ .flex_none()
1261+ .w(px(SWATCH_W))
1262+ .h_full()
1263+ .rounded(px(2.))
1264+ .bg(rgb(source_tint(i))),
1265+ )
1266+ .child(
1267+ div()
1268+ .flex_1()
1269+ .min_w(px(0.))
1270+ .flex()
1271+ .flex_col()
1272+ // Two lines rather than two columns: at the width
1273+ // this panel yields to, a name and a timecode side
1274+ // by side leave room for neither.
1275+ .child(div().truncate().text_size(px(11.)).child(name))
1276+ .child(
1277+ div()
1278+ .text_size(px(10.))
1279+ .text_color(rgb(INK_DIM))
1280+ .child(timecode(f64::from(frames) / self.fps, self.fps)),
1281+ ),
1282+ )
1283+ })
1284+ .collect();
1285+ div()
1286+ .flex_none()
1287+ .w(px(width))
1288+ .h_full()
1289+ .flex()
1290+ .flex_col()
1291+ .gap(px(6.))
1292+ .p(px(8.))
1293+ .bg(rgb(CHROME))
1294+ .child(
1295+ div()
1296+ .flex_none()
1297+ .flex()
1298+ .items_center()
1299+ .gap(px(6.))
1300+ .child(
1301+ div()
1302+ .flex_1()
1303+ .min_w(px(0.))
1304+ .truncate()
1305+ .text_size(px(11.))
1306+ .text_color(rgb(INK_DIM))
1307+ .child("Media"),
1308+ )
1309+ .child(control(
1310+ "import",
1311+ None,
1312+ "Import",
1313+ "opens a file chooser — or drop a file on the window".to_string(),
1314+ !exporting,
1315+ cx.listener(|this, _: &ClickEvent, _, cx| this.pick_and_import(cx)),
1316+ )),
1317+ )
1318+ .child(
1319+ div()
1320+ .id("library-rows")
1321+ .flex_1()
1322+ .min_h(px(0.))
1323+ .flex()
1324+ .flex_col()
1325+ .gap(px(2.))
1326+ .overflow_y_scroll()
1327+ // Never a blank column: with nothing imported the list is
1328+ // where the way in is said.
1329+ .when(rows.is_empty(), |d| {
1330+ d.child(
1331+ div()
1332+ .text_size(px(11.))
1333+ .text_color(rgb(INK_DIM))
1334+ .child("No media yet — Import, or drop a file on the window"),
1335+ )
1336+ })
1337+ .children(rows),
1338+ )
1339+ .child(control(
1340+ "add-asset",
1341+ None,
1342+ "Add at playhead",
1343+ match self.selected_asset {
1344+ Some(_) => "inserts the picked file at the playhead".to_string(),
1345+ None => "click a file above first — or drag one onto a lane".to_string(),
1346+ },
1347+ can_add(self.selected_asset, self.session.is_some(), exporting),
1348+ cx.listener(|this, _: &ClickEvent, _, cx| {
1349+ if let Some(source) = this.selected_asset {
1350+ this.insert_source(source, cx);
1351+ }
1352+ }),
1353+ ))
1354+ }
1355+
1065 /// Transport, edit and file buttons, timecode, playhead, clips lane.1356 /// Transport, edit and file buttons, timecode, playhead, clips lane.
1066 fn panel(1357 fn panel(
1067 &self,1358 &self,
@@ -1176,14 +1467,9 @@ impl Player {
1176 }),1467 }),
1177 ))1468 ))
1178 .child(separator())1469 .child(separator())
1179- .child(control(1470+ // Import is not here: it belongs to the media list it adds
1180- "import",1471+ // to, and two doors into one action is a question about
1181- None,1472+ // which one is the real one.
1182- "Import",
1183- "opens a file chooser — or drop a file on the window".to_string(),
1184- !exporting,
1185- cx.listener(|this, _: &ClickEvent, _, cx| this.pick_and_import(cx)),
1186- ))
1187 .child(control(1473 .child(control(
1188 "export",1474 "export",
1189 None,1475 None,
@@ -1654,6 +1940,14 @@ impl Player {
1654 .rounded(px(3.))1940 .rounded(px(3.))
1655 .bg(rgb(LETTERBOX))1941 .bg(rgb(LETTERBOX))
1656 .overflow_hidden()1942 .overflow_hidden()
1943+ // A library row let go over a lane is the same insert the
1944+ // Add button makes, through the same call -- at the
1945+ // playhead, not at the pointer: clips here are placed end
1946+ // to end, so where along the bed it landed says nothing.
1947+ .on_drop(
1948+ cx.listener(|this, drag: &AssetDrag, _, cx| this.insert_source(drag.0, cx)),
1949+ )
1950+ .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))
1657 .children(clips.iter().enumerate().map(|(i, clip)| {1951 .children(clips.iter().enumerate().map(|(i, clip)| {
1658 let (start, len) = (1952 let (start, len) = (
1659 f64::from(clip.start) / self.fps,1953 f64::from(clip.start) / self.fps,
@@ -1668,11 +1962,14 @@ impl Player {
1668 let tint = source_tint(clip.source);1962 let tint = source_tint(clip.source);
1669 let width = width_frac(len, duration);1963 let width = width_frac(len, duration);
1670 let label = sources.get(clip.source).map(|path| file_name(path));1964 let label = sources.get(clip.source).map(|path| file_name(path));
1671- let peaks = sources1965+ let wave = sources
1672 .get(clip.source)1966 .get(clip.source)
1673 .and_then(|path| self.waves.get(path))1967 .and_then(|path| self.waves.get(path))
1674- .cloned()1968+ .cloned();
1675- .flatten();1969+ let (from, to) = (
1970+ f64::from(clip.in_frame) / self.fps,
1971+ f64::from(clip.out_frame) / self.fps,
1972+ );
1676 let tip = tip.clone();1973 let tip = tip.clone();
1677 div()1974 div()
1678 .id((if audio { "aclip" } else { "vclip" }, i))1975 .id((if audio { "aclip" } else { "vclip" }, i))
@@ -1703,21 +2000,35 @@ impl Player {
1703 }),2000 }),
1704 )2001 )
1705 // Under the label row, never through it.2002 // Under the label row, never through it.
1706- .when_some(peaks.filter(|_| audio), |d, peaks| {2003+ .children(wave.filter(|_| audio).and_then(|wave| {
1707- d.child(2004+ let inner: AnyElement = match wave {
2005+ Wave::Peaks(peaks) => {
2006+ waveform(peaks, from, to).into_any_element()
2007+ }
2008+ // A bed while the decode runs, and dimmer
2009+ // than any waveform is drawn: a flat
2010+ // `INK_DIM` line here would be the shape a
2011+ // silent file makes, which this file is not
2012+ // known to be yet.
2013+ Wave::Loading => div()
2014+ .h_full()
2015+ .flex()
2016+ .items_center()
2017+ .child(div().w_full().h(px(1.)).bg(rgb(HOVER)))
2018+ .into_any_element(),
2019+ // No audio track: nothing, never a fake.
2020+ Wave::Silent => return None,
2021+ };
2022+ Some(
1708 div()2023 div()
1709 .absolute()2024 .absolute()
1710 .left_0()2025 .left_0()
1711 .right_0()2026 .right_0()
1712 .top(px(LABEL_H))2027 .top(px(LABEL_H))
1713 .bottom_0()2028 .bottom_0()
1714- .child(waveform(2029+ .child(inner),
1715- peaks,
1716- f64::from(clip.in_frame) / self.fps,
1717- f64::from(clip.out_frame) / self.fps,
1718- )),
1719 )2030 )
1720- })2031+ }))
1721 .when_some(label.filter(|_| show_label(bed_w * width)), |d, label| {2032 .when_some(label.filter(|_| show_label(bed_w * width)), |d, label| {
1722 d.child(2033 d.child(
1723 div()2034 div()
@@ -1844,6 +2155,70 @@ fn file_name(path: &std::path::Path) -> String {
1844 )2155 )
1845 }2156 }
1846 2157
2158+/// The sources a repaint has not asked about yet. A key that is already there
2159+/// means "asked", whatever state it is in, which is what stops a decode already
2160+/// running from being started again by the next of sixty repaints a second.
2161+fn unseen_sources(sources: &[PathBuf], waves: &HashMap<PathBuf, Wave>) -> Vec<PathBuf> {
2162+ sources
2163+ .iter()
2164+ .filter(|path| !waves.contains_key(*path))
2165+ .cloned()
2166+ .collect()
2167+}
2168+
2169+/// Both lanes' clips, which is everything the timeline knows about its sources.
2170+fn lane_clips(session: &PlaybackSession) -> impl Iterator<Item = &Clip> {
2171+ session
2172+ .lane_clips(Lane::Video)
2173+ .iter()
2174+ .chain(session.lane_clips(Lane::Audio))
2175+}
2176+
2177+/// How long a source is, as the timeline knows it: the furthest frame any clip
2178+/// plays from it. Exact for a source the timeline still holds whole -- which is
2179+/// every source the moment it is imported -- and never longer than the file,
2180+/// since every clip was checked against it, so a clip built from this can
2181+/// always be played. Zero for a source nothing plays from any more.
2182+///
2183+/// ponytail: a source trimmed on the timeline reads as its trimmed length. The
2184+/// file's own length would need a `Demuxer::open` probe per source, off the
2185+/// render path like the peak decode is -- that is the upgrade path.
2186+fn source_frames<'a>(clips: impl Iterator<Item = &'a Clip>, source: usize) -> u32 {
2187+ clips
2188+ .filter(|clip| clip.source == source)
2189+ .map(|clip| clip.out_frame)
2190+ .max()
2191+ .unwrap_or(0)
2192+}
2193+
2194+/// Whether the Add button does anything: a row picked, a timeline to put it on,
2195+/// and no export reading that timeline. A button that would do nothing is dimmed
2196+/// and takes no click, like every other one here.
2197+fn can_add(picked: Option<usize>, timeline: bool, exporting: bool) -> bool {
2198+ picked.is_some() && timeline && !exporting
2199+}
2200+
2201+/// What the media list is given of the window. A share of it, so a narrow
2202+/// window gives the panel less rather than giving the picture nothing, floored
2203+/// where a name stops being readable and capped at a third of the window --
2204+/// the picture is what the program is for and keeps the majority at every size.
2205+fn library_w(window_w: f32) -> f32 {
2206+ (window_w * LIBRARY_FRAC)
2207+ .clamp(LIBRARY_MIN_W, LIBRARY_MAX_W)
2208+ .min(window_w / 3.)
2209+}
2210+
2211+/// What the window is called: the program, and what is open in it. The name is
2212+/// what the header shows, so an empty window says the program alone rather than
2213+/// "no file open — edith".
2214+fn window_title(name: &str) -> String {
2215+ if name == NO_FILE {
2216+ "edith".to_string()
2217+ } else {
2218+ format!("{name} — edith")
2219+ }
2220+}
2221+
1847 /// The tint a clip from source `n` wears. Cycled rather than extended: past the2222 /// The tint a clip from source `n` wears. Cycled rather than extended: past the
1848 /// palette two sources share a colour, which is a smaller lie than a fifth tint2223 /// palette two sources share a colour, which is a smaller lie than a fifth tint
1849 /// bright enough to leave the family.2224 /// bright enough to leave the family.
@@ -2200,7 +2575,7 @@ fn empty_hint() -> impl IntoElement {
2200 .child(2575 .child(
2201 div()2576 div()
2202 .text_size(px(11.))2577 .text_size(px(11.))
2203- .child("or click Import below to choose one"),2578+ .child("or click Import in the media list"),
2204 )2579 )
2205 }2580 }
2206 2581
@@ -2255,16 +2630,184 @@ fn timecode(t: f64, fps: f64) -> String {
2255 #[cfg(test)]2630 #[cfg(test)]
2256 mod tests {2631 mod tests {
2257 use super::{2632 use super::{
2258- ACCENT, CONTROL_H, HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H,2633+ ACCENT, CONTROL_H, Clip, HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM, KEYS_ROW_H,
2259- KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LETTERBOX, Lane, PANEL_H, Quality, RULER_HIT_H,2634+ KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W,
2260- SELECTED, SOURCE_TINTS, SURFACE, Volume, WAVE_BPS, WAVE_COL, cancels_export, envelope,2635+ Lane, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE,
2261- export_path, export_settings, frac_along, is_bare_modifier, is_project, keymap, marked,2636+ SWATCH_W, Volume, WAVE_BPS, WAVE_COL, Wave, can_add, cancels_export, envelope, export_path,
2262- normalise, project_path, push_digit, scrub_due, show_label, source_tint, start_frac,2637+ export_settings, frac_along, is_bare_modifier, is_project, keymap, lane_clips, marked,
2263- timecode, width_frac,2638+ normalise, project_path, push_digit, scrub_due, show_label, source_frames, source_tint,
2639+ start_frac, timecode, unseen_sources, width_frac, window_title,
2264 };2640 };
2641+ use engine::PlaybackSession;
2265 use gpui::{Bounds, Pixels, point, px, size};2642 use gpui::{Bounds, Pixels, point, px, size};
2643+ use std::collections::HashMap;
2644+ use std::path::{Path, PathBuf};
2266 use std::time::Duration;2645 use std::time::Duration;
2267 2646
2647+ fn asset(name: &str) -> PathBuf {
2648+ Path::new(env!("CARGO_MANIFEST_DIR"))
2649+ .join("../../assets")
2650+ .join(name)
2651+ }
2652+
2653+ /// A clip of `source`, `frames` long, at the top of the timeline. Only the
2654+ /// two fields the library reads are meant to be looked at.
2655+ fn clip(source: usize, frames: u32) -> Clip {
2656+ Clip {
2657+ start: 0,
2658+ in_frame: 0,
2659+ out_frame: frames,
2660+ source,
2661+ link: None,
2662+ }
2663+ }
2664+
2665+ /// The whole of the library's row data comes off the clips: which sources
2666+ /// there are, how long each one is, and therefore which tint each row wears
2667+ /// -- one index into one list, so a swatch cannot name a different file from
2668+ /// the boxes it is meant to point at.
2669+ #[test]
2670+ fn a_rows_swatch_and_duration_come_off_the_clips_that_name_it() {
2671+ // Source 0 whole, source 1 trimmed to half of what it was, source 2 on
2672+ // the audio lane only (its picture was lifted), source 3 imported and
2673+ // then undone -- an entry with nothing playing from it.
2674+ let video = [clip(0, 150), clip(1, 60)];
2675+ let audio = [clip(0, 150), clip(1, 30), clip(2, 90)];
2676+ for (row, frames) in [(0, 150), (1, 60), (2, 90), (3, 0)] {
2677+ assert_eq!(
2678+ source_frames(video.iter().chain(&audio), row),
2679+ frames,
2680+ "row {row}"
2681+ );
2682+ // The swatch is the clip colour, by the same index and the same
2683+ // function -- what makes the panel and the lanes one association.
2684+ assert_eq!(source_tint(row), SOURCE_TINTS[row % SOURCE_TINTS.len()]);
2685+ }
2686+ // The longest clip of a source wins, whichever lane it is in and
2687+ // whatever order the lanes are read in.
2688+ assert_eq!(source_frames([clip(0, 10), clip(0, 90)].iter(), 0), 90);
2689+ assert_eq!(source_frames([clip(0, 90), clip(0, 10)].iter(), 0), 90);
2690+ assert_eq!(source_frames([].iter(), 0), 0);
2691+ }
2692+
2693+ /// The refusal path, end to end against the real files: an incompatible
2694+ /// import changes nothing, and the library mirrors `sources()` 1:1, so a
2695+ /// refused file cannot leave a row behind.
2696+ #[test]
2697+ fn a_refused_import_leaves_no_row_and_an_accepted_one_is_whole() {
2698+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
2699+ // Silent like the engine suite: this opens the real device.
2700+ session.set_gain(0.0);
2701+ assert_eq!(session.sources().len(), 1);
2702+ let refusal = session
2703+ .import(&asset("test_mismatch.mp4"))
2704+ .expect_err("640x360 must not join a 1280x720 timeline")
2705+ .to_string();
2706+ assert!(refusal.contains("640"), "refusal must name it: {refusal}");
2707+ assert_eq!(session.sources().len(), 1, "a refusal added a row");
2708+ // An accepted one does add a row, and it reads as the whole file: 4 s
2709+ // at 30 fps, exactly what was appended.
2710+ session.import(&asset("test_av2.mp4")).expect("av2 matches");
2711+ assert_eq!(session.sources().len(), 2);
2712+ assert_eq!(source_frames(lane_clips(&session), 1), 120);
2713+ assert_eq!(timecode(120. / 30., 30.), "00:00:04:00");
2714+ }
2715+
2716+ /// What the Add button and a dropped row both do, minus the pointer: the
2717+ /// clip [`Player::insert_source`] builds, put in where the playhead is. One
2718+ /// call, so what a drop does cannot drift from what the button does.
2719+ #[test]
2720+ fn adding_a_row_drops_the_whole_source_in_at_the_playhead() {
2721+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
2722+ session.set_gain(0.0);
2723+ session.import(&asset("test_av2.mp4")).expect("av2 matches");
2724+ assert_eq!(session.timeline_duration(), 9.0);
2725+ // Two seconds in, which is inside the first take: the insert splits it.
2726+ session.seek(2.0);
2727+ let frames = source_frames(lane_clips(&session), 1);
2728+ assert!(session.paste_at(
2729+ 2.0,
2730+ Clip {
2731+ start: 0,
2732+ in_frame: 0,
2733+ out_frame: frames,
2734+ source: 1,
2735+ link: None,
2736+ }
2737+ ));
2738+ // The whole of source 1 went in and nothing was painted over: the
2739+ // timeline is longer by exactly that file.
2740+ assert_eq!(session.timeline_duration(), 13.0);
2741+ let (video, audio) = (
2742+ session.lane_clips(Lane::Video),
2743+ session.lane_clips(Lane::Audio),
2744+ );
2745+ // One take, not a video clip with no sound under it: both lanes hold
2746+ // the same clip at the same place, in the same group.
2747+ let at = |lane: &[Clip]| {
2748+ *lane
2749+ .iter()
2750+ .find(|c| c.start == 60)
2751+ .expect("inserted at 2 s")
2752+ };
2753+ assert_eq!(at(video), at(audio));
2754+ assert_eq!(at(video).source, 1);
2755+ assert_eq!(at(video).len(), frames);
2756+ assert!(at(video).link.is_some());
2757+ assert_eq!(video.len(), audio.len());
2758+ }
2759+
2760+ #[test]
2761+ fn a_source_is_only_ever_asked_for_its_peaks_once() {
2762+ let (a, b) = (asset("test_av.mp4"), asset("test_av2.mp4"));
2763+ let sources = [a.clone(), b.clone()];
2764+ let mut waves: HashMap<PathBuf, Wave> = HashMap::new();
2765+ assert_eq!(unseen_sources(&sources, &waves), sources);
2766+ // The entry goes in when the decode *starts*, so the sixty repaints a
2767+ // second that happen while it runs must not start it again -- which is
2768+ // what this asserts about a key whose value is not an answer yet.
2769+ waves.insert(a, Wave::Loading);
2770+ assert_eq!(unseen_sources(&sources, &waves), vec![b.clone()]);
2771+ // A file with no audio is an answer like any other: never re-asked.
2772+ waves.insert(b, Wave::Silent);
2773+ assert!(unseen_sources(&sources, &waves).is_empty());
2774+ }
2775+
2776+ #[test]
2777+ fn the_add_button_is_dead_unless_it_would_do_something() {
2778+ assert!(can_add(Some(0), true, false));
2779+ // Nothing picked, nothing to put it on, or an export reading the very
2780+ // edit list this would change.
2781+ assert!(!can_add(None, true, false));
2782+ assert!(!can_add(Some(0), false, false));
2783+ assert!(!can_add(Some(0), true, true));
2784+ }
2785+
2786+ #[test]
2787+ fn the_media_column_never_takes_the_picture_over() {
2788+ for window in [360., 640., 1280., 1920., 3840.] {
2789+ let w = super::library_w(window);
2790+ // The whole point of the budget: the picture keeps the majority of
2791+ // the row at every size a window can be.
2792+ assert!(w <= window / 3., "{window}px window gave the list {w}px");
2793+ assert!(w >= LIBRARY_MIN_W.min(window / 3.), "{window}px: {w}px");
2794+ assert!(w <= LIBRARY_MAX_W);
2795+ }
2796+ // It yields: a narrower window gives the list less, never the same.
2797+ assert!(super::library_w(640.) < super::library_w(1280.));
2798+ // Rows are clickable, so WCAG 2.5.8 binds them like every other target,
2799+ // and a name over a timecode has to fit inside one.
2800+ assert!(ROW_H >= HIT_MIN);
2801+ assert!(SWATCH_W < LIBRARY_MIN_W);
2802+ }
2803+
2804+ #[test]
2805+ fn the_window_is_named_after_the_program_and_what_is_open() {
2806+ assert_eq!(window_title("test_av.mp4"), "test_av.mp4 — edith");
2807+ // An empty window is the program, not "no file open — edith".
2808+ assert_eq!(window_title(NO_FILE), "edith");
2809+ }
2810+
2268 #[test]2811 #[test]
2269 fn frac_along_measures_from_the_elements_own_left_edge() {2812 fn frac_along_measures_from_the_elements_own_left_edge() {
2270 // A ruler inset by the panel's 12 px padding: window x is not bar x.2813 // A ruler inset by the panel's 12 px padding: window x is not bar x.
@@ -2800,7 +3343,7 @@ fn main() {
2800 };3343 };
2801 let name: SharedString = arg3344 let name: SharedString = arg
2802 .as_deref()3345 .as_deref()
2803- .map_or_else(|| "no file open".into(), |arg| file_name(arg).into());3346+ .map_or_else(|| NO_FILE.into(), |arg| file_name(arg).into());
2804 if let (Some(arg), Some(meta)) = (&arg, &meta) {3347 if let (Some(arg), Some(meta)) = (&arg, &meta) {
2805 println!(3348 println!(
2806 "{}: {}x{} @ {:.2} fps, {} samples",3349 "{}: {}x{} @ {:.2} fps, {} samples",
@@ -2826,6 +3369,12 @@ fn main() {
2826 title: Some("edith".into()),3369 title: Some("edith".into()),
2827 ..Default::default()3370 ..Default::default()
2828 }),3371 }),
3372+ // What a desktop groups this window under. The title beside it
3373+ // is pushed from the render, because wayland takes neither of
3374+ // them from the titlebar options above (gpui's wayland window
3375+ // reads only `app_id`, window.rs:1202 / window.rs:939) and the
3376+ // title has to follow the file being opened anyway.
3377+ app_id: Some("edith".to_string()),
2829 ..Default::default()3378 ..Default::default()
2830 },3379 },
2831 |window, cx| {3380 |window, cx| {
@@ -2849,6 +3398,7 @@ fn main() {
2849 done: false,3398 done: false,
2850 ruler: Rc::default(),3399 ruler: Rc::default(),
2851 selected: None,3400 selected: None,
3401+ selected_asset: None,
2852 waves: HashMap::new(),3402 waves: HashMap::new(),
2853 clipboard: None,3403 clipboard: None,
2854 scrubbing: false,3404 scrubbing: false,
@@ -2867,6 +3417,9 @@ fn main() {
2867 custom_mbps: 0,3417 custom_mbps: 0,
2868 rebinding: None,3418 rebinding: None,
2869 notice: notice.clone().map(SharedString::from),3419 notice: notice.clone().map(SharedString::from),
3420+ // Nothing pushed yet, and never a real title: the first
3421+ // render is what names the window.
3422+ titled: String::new(),
2870 displayed: 0,3423 displayed: 0,
2871 dropped: 0,3424 dropped: 0,
2872 started: None,3425 started: None,