forge
Explore
Log in

Don't you dare go Hollow

The cues arrive, show over the picture and sit on the timeline

Browse files at this commit

863eb6380ecab196738a04021c905abb19ac361eAhmet Kaan GümüşParent: 75bfb8e
  • feat
    • the cues arrive, show over the picture and sit on the timeline
Show full message
✨ feat(subtitles): the cues arrive, show over the picture and sit on the timeline

Subtitle management, both halves the user asked for: a .srt/.vtt/.ass/.ssa
beside the media goes in through the import door it is dropped on, and an
mkv opened or imported brings its own text tracks with it — every door
(drop, Import, argv, argv extras) picks them up, so a file never arrives
with invisible subtitles.

The library grows a Subtitles section under the media list: a row per
track, its cue count under its name, the picked one marked, and a click
picks another — rows rather than a cycle, because four PGS tracks off a
remux is an ordinary number. A track that cannot be read is in that list,
greyed, saying why in the engine's own words.

Over the picture the cue under the playhead is drawn bottom-centred,
white on a plate so the film cannot swallow it, one plate per cue so two
at once stack and the line breaks the parser kept stay breaks. Under the
lanes a thin strip shows where the cues are, through the same Scale every
clip box goes through. ToggleSubtitles (t) hides and shows the overlay,
from the keyboard, the Actions card or the Subs button beside the snap.

No engine change: the doors were complete.
crates/app/src/keymap.rsmodified+19 -6
@@ -79,6 +79,7 @@ pub enum ActionId {
7979 Silence,
8080 Mix,
8181 ToggleSnap,
82+ ToggleSubtitles,
8283 CancelExport,
8384 /// Opens the actions card -- the list every other action is on. A door of
8485 /// its own, because a card reachable only by a button in the panel is one a
@@ -89,7 +90,7 @@ pub enum ActionId {
8990 impl ActionId {
9091 /// Display order everywhere -- the editor lists them in it and
9192 /// [`Keymap::defaults`] binds them in it.
92- pub const ALL: [ActionId; 41] = [
93+ pub const ALL: [ActionId; 42] = [
9394 ActionId::Play,
9495 ActionId::StepBack,
9596 ActionId::StepForward,
@@ -129,6 +130,7 @@ impl ActionId {
129130 ActionId::Silence,
130131 ActionId::Mix,
131132 ActionId::ToggleSnap,
133+ ActionId::ToggleSubtitles,
132134 ActionId::CancelExport,
133135 ActionId::ShowActions,
134136 ];
@@ -175,6 +177,7 @@ impl ActionId {
175177 ActionId::Silence => "Silences: cut or speed up…",
176178 ActionId::Mix => "Mix: track volumes and the limiter…",
177179 ActionId::ToggleSnap => "Snap on / off (edges, the playhead, the start)",
180+ ActionId::ToggleSubtitles => "Subtitles on / off over the picture",
178181 ActionId::CancelExport => "Cancel export",
179182 ActionId::ShowActions => "All actions and their keys…",
180183 }
@@ -223,6 +226,7 @@ impl ActionId {
223226 ActionId::Silence => "silence",
224227 ActionId::Mix => "mix",
225228 ActionId::ToggleSnap => "toggle-snap",
229+ ActionId::ToggleSubtitles => "toggle-subtitles",
226230 ActionId::CancelExport => "cancel-export",
227231 ActionId::ShowActions => "show-actions",
228232 }
@@ -265,9 +269,13 @@ impl ActionId {
265269 // a file operation either: it is what the viewer is looking at.
266270 // Neither is how much of the timeline the panel shows: a zoom edits
267271 // nothing, it magnifies.
268- ActionId::Resolution | ActionId::ZoomIn | ActionId::ZoomOut | ActionId::ZoomFit => {
269- Category::View
270- }
272+ // ...and whether the cues are drawn over that picture: a subtitle
273+ // edits nothing either, it is part of what is being watched.
274+ ActionId::Resolution
275+ | ActionId::ZoomIn
276+ | ActionId::ZoomOut
277+ | ActionId::ZoomFit
278+ | ActionId::ToggleSubtitles => Category::View,
271279 ActionId::Cut
272280 | ActionId::Regroup
273281 | ActionId::Detach
@@ -697,6 +705,10 @@ impl Keymap {
697705 // The snap takes "n", which is what every other editor toggles
698706 // it with: free here, and nowhere near the two keys that delete.
699707 b(ActionId::ToggleSnap, "n", false),
708+ // The subtitles take "t", for the word: free, one press like
709+ // the rest of the things one *looks* at, and nowhere near the
710+ // two keys that delete.
711+ b(ActionId::ToggleSubtitles, "t", false),
700712 b(ActionId::CancelExport, "escape", false),
701713 // The help key, where every program's list of what it can do
702714 // has always been. Free -- gpui names it "f1"
@@ -964,7 +976,7 @@ mod tests {
964976 #[test]
965977 fn every_default_stroke_reaches_its_action() {
966978 let k = Keymap::defaults();
967- assert_eq!(k.entries().len(), 43);
979+ assert_eq!(k.entries().len(), 44);
968980 assert_eq!(k.lookup("f1", false), Some(ActionId::ShowActions));
969981 assert_eq!(k.lookup("space", false), Some(ActionId::Play));
970982 // The seek keys: bare arrows a frame, ctrl arrows a second, and the two
@@ -1203,9 +1215,10 @@ mod tests {
12031215 assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound");
12041216 // The label is the editor's column, and never the file's word for it.
12051217 assert_eq!(ActionId::CancelExport.label(), "Cancel export");
1206- assert_eq!(ActionId::ALL.len(), 41);
1218+ assert_eq!(ActionId::ALL.len(), 42);
12071219 assert_eq!(k.display(ActionId::ToggleSnap), "n");
12081220 assert_eq!(k.display(ActionId::ShowActions), "f1");
1221+ assert_eq!(k.display(ActionId::ToggleSubtitles), "t");
12091222 assert_eq!(k.display(ActionId::ZoomIn), "ctrl+=");
12101223 }
12111224
crates/app/src/main.rsmodified+716 -15
@@ -170,6 +170,32 @@ const MENU_PAD: f32 = 6.;
170170 /// the bottom edge, where nobody can click them.
171171 const MENU_ROWS_H: f32 = 12. * MENU_ROW_H;
172172
173+/// The subtitle over the picture: white on a black plate, because a cue is read
174+/// against whatever the film happens to be showing under it and the chrome's own
175+/// greys are not a contrast the picture agrees to. 21:1 against the plate, which
176+/// is the only pair here that is not a chrome-on-chrome one.
177+const SUB_INK: u32 = 0xffffff;
178+const SUB_SHADE: u32 = 0x000000cc;
179+/// A cue's text, and the line it sits on. Fixed rather than a share of the
180+/// picture: the video region is 108 px tall at the 640x360 floor and a
181+/// proportional size there would be unreadable at exactly the size where it has
182+/// to be read.
183+const SUB_TEXT: f32 = 14.;
184+const SUB_LINE_H: f32 = 18.;
185+/// How far off the bottom of the picture the plate sits.
186+const SUB_BOTTOM: f32 = 8.;
187+/// The subtitle strip under the lanes: thin, because it is a picture of where
188+/// the cues are and nothing on it can be dragged -- `HIT_MIN` binds targets, and
189+/// this row has none.
190+const SUB_LANE_H: f32 = 16.;
191+/// A cue narrower than this is still drawn this wide: a one-frame cue on a
192+/// zoomed-out bed is worth a fraction of a pixel, and a mark nobody can see says
193+/// the track is empty.
194+const SUB_CUE_MIN_W: f32 = 2.;
195+/// How much of the subtitle list in the library column is on screen at once,
196+/// past which it scrolls -- the media list above it is what keeps the height.
197+const SUB_ROWS_H: f32 = 3. * ROW_H;
198+
173199 /// The one key name this file still spells out, and gpui's spelling of it: it
174200 /// is the way out of a capture and out of the overlay, and both have to work
175201 /// while the keymap itself is what is being changed -- so neither can go
@@ -983,6 +1009,18 @@ struct Player {
9831009 /// by one stroke ([`ActionId::ToggleSnap`]) for the frame-by-frame placement
9841010 /// no magnet may take away.
9851011 snap: bool,
1012+ /// Whether the cue under the playhead is drawn over the picture. On by
1013+ /// default -- a subtitle imported and then invisible is an import nobody can
1014+ /// tell happened -- and off by one stroke
1015+ /// ([`ActionId::ToggleSubtitles`](keymap::ActionId::ToggleSubtitles)) for
1016+ /// anyone watching the picture rather than reading it. The player's, not the
1017+ /// project's: it changes nothing that is saved and nothing that is exported.
1018+ subs_on: bool,
1019+ /// Which subtitle track is the one on screen: an index into
1020+ /// [`PlaybackSession::subtitles`], since a file may carry several and only
1021+ /// one can be read at a time. Cleared with the timeline like every other
1022+ /// index here -- track 2 of one project is not track 2 of the next.
1023+ sub_track: usize,
9861024 /// The frame the live gesture is about to land on, or `None` while it is
9871025 /// over open bed: the line every lane draws so the snap is seen before it
9881026 /// happens rather than discovered after the release. Stale between gestures,
@@ -1363,6 +1401,7 @@ impl Player {
13631401 ActionId::Silence => self.open_silence(cx),
13641402 ActionId::Mix => self.open_mix(None, cx),
13651403 ActionId::ToggleSnap => self.toggle_snap(cx),
1404+ ActionId::ToggleSubtitles => self.toggle_subtitles(cx),
13661405 // Nothing to cancel while nothing is exporting; the export guard in
13671406 // the key handler is what answers this one while there is.
13681407 ActionId::CancelExport => {}
@@ -1415,6 +1454,32 @@ impl Player {
14151454 self.keys_scroll.set_offset(point(px(0.), px(at)));
14161455 }
14171456
1457+ /// The cues over the picture, off and on. Says which it is now *and* what is
1458+ /// on screen while they are on: a toggle whose answer is invisible when the
1459+ /// playhead happens to sit between two cues would read as broken.
1460+ fn toggle_subtitles(&mut self, cx: &mut Context<Self>) {
1461+ self.subs_on = !self.subs_on;
1462+ let label = self
1463+ .subtitle_track()
1464+ .map(|track| track.label.clone())
1465+ .unwrap_or_else(|| "nothing imported".to_string());
1466+ self.notice = Some(
1467+ match self.subs_on {
1468+ true => format!("SUBTITLES ON — {label}"),
1469+ false => format!("SUBTITLES OFF — {label} is still on the timeline"),
1470+ }
1471+ .into(),
1472+ );
1473+ cx.notify();
1474+ }
1475+
1476+ /// The subtitle track the overlay and the strip are showing: the one a
1477+ /// library row picked, or the first there is. `None` with no timeline and
1478+ /// for an index left over from one that is gone.
1479+ fn subtitle_track(&self) -> Option<&engine::subtitle::SubtitleTrack> {
1480+ self.session.as_ref()?.subtitles().get(self.sub_track)
1481+ }
1482+
14181483 /// Whether the editor can be asked for `action` right now, and why not when
14191484 /// it cannot. `on` is the clip the question is about -- the one a clip menu
14201485 /// was opened on -- and `None` asks about the marked clip instead, which is
@@ -1441,6 +1506,7 @@ impl Player {
14411506 playhead: frame_at(session.now(), self.fps),
14421507 timeline: true,
14431508 clipboard: self.clipboard.is_some(),
1509+ subtitles: !session.subtitles().is_empty(),
14441510 exporting: self.exporting().is_some(),
14451511 },
14461512 )
@@ -3394,6 +3460,8 @@ impl Player {
33943460 self.clipboard = None;
33953461 self.selected = None;
33963462 self.selected_asset = None;
3463+ // The subtitle rows go with the timeline they were on.
3464+ self.sub_track = 0;
33973465 self.context_menu = None;
33983466 self.library_menu = None;
33993467 self.eq_open = None;
@@ -3501,11 +3569,47 @@ impl Player {
35013569 // whether or not a session was already up. A file *named at launch* is
35023570 // the other fork -- that one is an open, and it does become the
35033571 // timeline (`main`).
3572+ // A subtitle file is not a source and lands on no lane: it joins the
3573+ // timeline's own list of them, which is what the library's subtitle
3574+ // section shows and what the overlay draws. With no timeline open there
3575+ // is nothing for the cues to be timed against, and it says so.
3576+ if is_subtitle(path) {
3577+ let text = match self
3578+ .session
3579+ .as_mut()
3580+ .map(|session| session.import_subtitles(path))
3581+ {
3582+ Some(Ok(0)) => format!("{} is already on the timeline", file_name(path)),
3583+ Some(Ok(_)) => format!(
3584+ "SUBTITLES {} — showing over the picture, {} hides them",
3585+ file_name(path),
3586+ self.keymap.display(ActionId::ToggleSubtitles)
3587+ ),
3588+ Some(Err(e)) => format!("SUBTITLE IMPORT FAILED: {e}"),
3589+ None => {
3590+ "NO SUBTITLES ADDED — open a file for them to run against first".to_string()
3591+ }
3592+ };
3593+ eprintln!("{text}");
3594+ self.notice = Some(text.into());
3595+ cx.notify();
3596+ return;
3597+ }
35043598 let text = match self.session.as_mut().map(|session| session.import(path)) {
3505- Some(Ok(_)) => format!(
3506- "IMPORTED {} to the library — drag it onto a lane to place it",
3507- file_name(path)
3508- ),
3599+ Some(Ok(_)) => {
3600+ // The file's own subtitle tracks with it, exactly as an open
3601+ // takes them: an import is the other door the same file arrives
3602+ // through.
3603+ let subs = self
3604+ .session
3605+ .as_mut()
3606+ .and_then(|session| subtitle_notice(session, path))
3607+ .unwrap_or_default();
3608+ format!(
3609+ "IMPORTED {} to the library — drag it onto a lane to place it{subs}",
3610+ file_name(path)
3611+ )
3612+ }
35093613 Some(Err(e)) => format!("IMPORT FAILED: {e}"),
35103614 None => self.open_media(path, false),
35113615 };
@@ -3529,11 +3633,17 @@ impl Player {
35293633 false => PlaybackSession::open_library(path),
35303634 };
35313635 match opened {
3532- Ok(session) => {
3636+ Ok(mut session) => {
35333637 self.fps = session.meta().frame_rate;
35343638 // Read before the session moves: a file that plays silent says
35353639 // so here or nowhere.
35363640 let silent = audio_notice(&session);
3641+ // ...and the subtitle tracks the file carries inside it, taken
3642+ // now: nothing else ever opens this container again.
3643+ let subs = subtitle_notice(&mut session, path).unwrap_or_default();
3644+ // A file replaces the one that was open, and track 3 of that one
3645+ // is not track 3 of this.
3646+ self.sub_track = 0;
35373647 self.session = Some(session);
35383648 // A fresh session comes up at full volume; the player's own
35393649 // setting outlives the file, so it is pushed at every new one.
@@ -3553,7 +3663,7 @@ impl Player {
35533663 format!("IMPORTED {name} to the library — drag it onto a lane to place it")
35543664 }
35553665 };
3556- format!("{what}{}", silent.unwrap_or_default())
3666+ format!("{what}{}{subs}", silent.unwrap_or_default())
35573667 }
35583668 Err(e) => format!("OPEN FAILED: {e}"),
35593669 }
@@ -3621,8 +3731,10 @@ impl Player {
36213731 // Marks are timeline frames of the timeline that was.
36223732 self.close_silence();
36233733 // A different set of sources: the row that was picked is not
3624- // the file that index names any more.
3734+ // the file that index names any more -- and neither is the
3735+ // subtitle track that was showing.
36253736 self.selected_asset = None;
3737+ self.sub_track = 0;
36263738 // The counters describe one timeline; the eof line must not
36273739 // report the old one's frames against the new one.
36283740 self.displayed = 0;
@@ -4673,6 +4785,10 @@ impl Render for Player {
46734785 .flex_1()
46744786 .min_w(px(0.))
46754787 .overflow_hidden()
4788+ // The bed the cue plate is placed against: it hangs
4789+ // off the bottom of the picture region, which is the
4790+ // one box that is the picture and nothing else.
4791+ .relative()
46764792 .flex()
46774793 .justify_center()
46784794 .items_center()
@@ -4695,7 +4811,10 @@ impl Render for Player {
46954811 .is_none()
46964812 .then(|| empty_hint().into_any_element())
46974813 }),
4698- ),
4814+ )
4815+ // After the picture, so the plate is drawn over it
4816+ // rather than under: siblings paint in order.
4817+ .children(self.subtitle_overlay(position)),
46994818 ),
47004819 )
47014820 // Above the panel and only when there is one to show, so it costs
@@ -4973,6 +5092,10 @@ impl Player {
49735092 })
49745093 .children(rows),
49755094 )
5095+ // Under the media it belongs to: a subtitle track is not a source --
5096+ // it goes on no lane and is dragged nowhere -- but it is a thing the
5097+ // timeline holds, and this is the list of those.
5098+ .children(self.subtitle_section(cx))
49765099 .child(control(
49775100 "add-asset",
49785101 None,
@@ -4996,6 +5119,159 @@ impl Player {
49965119 ))
49975120 }
49985121
5122+ /// The subtitle tracks this timeline holds, under the media list: one row
5123+ /// each, the picked one marked, and a click makes another one the picked one
5124+ /// -- which is the whole of choosing between the two tracks of a film. A row
5125+ /// per track and no cycle: three of them is an ordinary number for a remux,
5126+ /// and a key that steps through three is a key nobody can aim.
5127+ ///
5128+ /// A track that could not be read is *here*, greyed and saying why, exactly
5129+ /// as a media row the timeline cannot take is: PGS subtitles are pictures,
5130+ /// and a film carrying four of them says so instead of listing nothing.
5131+ ///
5132+ /// `None` when there are none -- an empty heading is a section about
5133+ /// nothing.
5134+ fn subtitle_section(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
5135+ let tracks = self.session.as_ref()?.subtitles();
5136+ if tracks.is_empty() {
5137+ return None;
5138+ }
5139+ let rows: Vec<_> = tracks
5140+ .iter()
5141+ .enumerate()
5142+ .map(|(i, track)| {
5143+ let picked = i == self.sub_track;
5144+ let usable = track.refused.is_none();
5145+ let under = subtitle_detail(track);
5146+ let tip: SharedString = match &track.refused {
5147+ Some(why) => format!("{} — {why}", track.path.display()),
5148+ None => format!(
5149+ "{} — click to show this track over the picture",
5150+ track.path.display()
5151+ ),
5152+ }
5153+ .into();
5154+ div()
5155+ .id(("subtitle-track", i))
5156+ .flex_none()
5157+ .h(px(ROW_H))
5158+ .flex()
5159+ .flex_col()
5160+ .justify_center()
5161+ .px(px(6.))
5162+ .rounded(px(3.))
5163+ .when(!usable, |d| d.text_color(rgb(INK_DIM)).opacity(0.55))
5164+ .when(usable, |d| {
5165+ d.cursor_pointer()
5166+ .hover(|s| s.bg(rgb(HOVER)))
5167+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
5168+ this.sub_track = i;
5169+ // Picking a track is asking to see it: a click
5170+ // that changed nothing on screen because the
5171+ // toggle was off would read as a dead row.
5172+ this.subs_on = true;
5173+ cx.notify();
5174+ }))
5175+ })
5176+ .when(picked, |d| d.bg(rgb(SELECTED)))
5177+ .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())
5178+ .child(
5179+ div()
5180+ .truncate()
5181+ .text_size(px(11.))
5182+ .child(track.label.clone()),
5183+ )
5184+ .child(
5185+ div()
5186+ .truncate()
5187+ .text_size(px(10.))
5188+ .text_color(rgb(INK_DIM))
5189+ .child(under),
5190+ )
5191+ })
5192+ .collect();
5193+ Some(
5194+ div()
5195+ .flex_none()
5196+ .flex()
5197+ .flex_col()
5198+ .gap(px(2.))
5199+ .child(
5200+ div()
5201+ .truncate()
5202+ .text_size(px(11.))
5203+ .text_color(rgb(INK_DIM))
5204+ .child(match self.subs_on {
5205+ true => "Subtitles",
5206+ // The toggle's state where the tracks are listed: a
5207+ // list of subtitles nothing on screen is showing has
5208+ // to say that it is showing none.
5209+ false => "Subtitles — hidden",
5210+ }),
5211+ )
5212+ .child(
5213+ div()
5214+ .id("subtitle-rows")
5215+ .flex()
5216+ .flex_col()
5217+ .gap(px(2.))
5218+ .max_h(px(SUB_ROWS_H))
5219+ .overflow_y_scroll()
5220+ .children(rows),
5221+ ),
5222+ )
5223+ }
5224+
5225+ /// The cues of the picked track that are on screen at `at`, over the picture
5226+ /// and nothing else: bottom-centred where every player puts them, white on a
5227+ /// plate so the film underneath cannot swallow them, and each cue its own
5228+ /// plate so two at one moment stack rather than run together.
5229+ ///
5230+ /// `None` -- no element at all -- while the toggle is off, with no track
5231+ /// picked, and between cues: the picture is what this window is for, and a
5232+ /// permanent empty band across it would be in the way of exactly that.
5233+ fn subtitle_overlay(&self, at: f64) -> Option<impl IntoElement + use<>> {
5234+ if !self.subs_on {
5235+ return None;
5236+ }
5237+ let cues = cues_at(&self.subtitle_track()?.cues, at);
5238+ if cues.is_empty() {
5239+ return None;
5240+ }
5241+ Some(
5242+ div()
5243+ .absolute()
5244+ .left_0()
5245+ .right_0()
5246+ .bottom(px(SUB_BOTTOM))
5247+ .flex()
5248+ .flex_col()
5249+ .items_center()
5250+ .gap(px(2.))
5251+ // The plate takes no click: the picture behind it is still the
5252+ // drop target the whole window is.
5253+ .children(cues.into_iter().map(|cue| {
5254+ div()
5255+ .max_w(relative(0.9))
5256+ .px(px(6.))
5257+ .rounded(px(3.))
5258+ .bg(rgba(SUB_SHADE))
5259+ .text_size(px(SUB_TEXT))
5260+ .text_color(rgb(SUB_INK))
5261+ .text_align(TextAlign::Center)
5262+ // A line of the cue is a line on screen: the break the
5263+ // parser kept is not whitespace to be re-flowed. What a
5264+ // *long* line does is wrap inside its own div, which is
5265+ // what the width cap above is for.
5266+ .children(
5267+ cue.text
5268+ .split('\n')
5269+ .map(|line| div().min_h(px(SUB_LINE_H)).child(line.to_string())),
5270+ )
5271+ })),
5272+ )
5273+ }
5274+
49995275 /// What is decoding the picture right now, for the transport line: the
50005276 /// backend is the running worker's own (it is written where a hardware
50015277 /// session falls back to software, so this follows reality), and the codec
@@ -5058,6 +5334,11 @@ impl Player {
50585334 for &lane in &lanes {
50595335 rows.push(self.lane_row(lane, filled, cx));
50605336 }
5337+ // Built from the same playhead pixel the lanes are, and before the
5338+ // export takes `filled` over below: the strip is a picture of the
5339+ // timeline, not of an export's progress.
5340+ let strip = self.subtitle_strip(filled);
5341+ let strip_h = subtitle_strip_h(strip.is_some());
50615342 let (hint, filled) = if let Some(export) = self.exporting() {
50625343 let progress = export.progress();
50635344 let elapsed = self
@@ -5114,7 +5395,7 @@ impl Player {
51145395 };
51155396 div()
51165397 .flex_none()
5117- .h(px(panel_h(lanes.len())))
5398+ .h(px(panel_h(lanes.len()) + strip_h))
51185399 .flex()
51195400 .flex_col()
51205401 .gap(px(8.))
@@ -5337,6 +5618,36 @@ impl Player {
53375618 live,
53385619 cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_snap(cx)),
53395620 ))
5621+ // The cues over the picture, off and on -- beside the zoom
5622+ // and the snap, since like both of them it changes what is
5623+ // being looked at and nothing about the edit. The label is
5624+ // the state, as the snap's is, and it says what there is to
5625+ // toggle when there is nothing.
5626+ .child(control(
5627+ "subs",
5628+ None,
5629+ match (self.subtitle_track().is_some(), self.subs_on) {
5630+ (false, _) => "No subs",
5631+ (true, true) => "Subs",
5632+ (true, false) => "Subs off",
5633+ },
5634+ match self.enable(ActionId::ToggleSubtitles, None).why() {
5635+ Some(why) => format!(
5636+ "{} — {why}; drop a .srt on the window, or open an mkv that carries them",
5637+ key(ActionId::ToggleSubtitles)
5638+ ),
5639+ None => format!(
5640+ "{} — {}",
5641+ key(ActionId::ToggleSubtitles),
5642+ match self.subs_on {
5643+ true => "the cue under the playhead is drawn over the picture",
5644+ false => "the cues are on the timeline and off the picture",
5645+ }
5646+ ),
5647+ },
5648+ live && self.enable(ActionId::ToggleSubtitles, None).yes(),
5649+ cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_subtitles(cx)),
5650+ ))
53405651 // Import is not here: it belongs to the media list it adds
53415652 // to, and two doors into one action is a question about
53425653 // which one is the real one.
@@ -5531,6 +5842,11 @@ impl Player {
55315842 .overflow_y_scroll()
55325843 .children(rows),
55335844 )
5845+ // Under the tracks and outside their scrolling column: a subtitle is
5846+ // not a track -- nothing can be dropped on it and nothing dragged
5847+ // along it -- and a strip that scrolled away with the sixth lane
5848+ // would be a strip nobody could see while editing.
5849+ .children(strip)
55345850 }
55355851
55365852 /// A notice holds its own bar, full width, until it is answered: any key
@@ -7884,6 +8200,99 @@ impl Player {
78848200 /// is by its tint, and the tooltip is where every box says what clicking it
78858201 /// does. Never focusable, so the root keeps focus and the play binding still
78868202 /// works after a click (ledger:182).
8203+ /// The subtitle strip: where the picked track's cues are along the very same
8204+ /// bed the lanes are drawn on, through the very same [`Scale`], so a cue
8205+ /// lines up with the take it belongs to at every zoom.
8206+ ///
8207+ /// Display only -- no drag, no trim, no drop. What it is *for* is the
8208+ /// question "is there a subtitle here", which a timeline could not answer at
8209+ /// all before: the cues are the project's and are edited in the file they
8210+ /// came from.
8211+ ///
8212+ /// `None` with no track picked, so a timeline without subtitles is the panel
8213+ /// it has always been.
8214+ fn subtitle_strip(&self, filled: f32) -> Option<impl IntoElement + use<>> {
8215+ let track = self.subtitle_track()?;
8216+ let scale = self.scale;
8217+ let label = track.label.clone();
8218+ // The whole of what the row says in words, since a 40 px column can hold
8219+ // three characters of it: which track, how many cues, and -- for one
8220+ // that could not be read -- the engine's own reason, where the library
8221+ // row's grey already says the same thing.
8222+ let tip: SharedString = match track.refused.is_some() {
8223+ true => format!("Subtitles: {label} — {}", subtitle_detail(track)),
8224+ false => format!(
8225+ "Subtitles: {label} — {}, {} hides them",
8226+ subtitle_detail(track),
8227+ self.keymap.display(ActionId::ToggleSubtitles)
8228+ ),
8229+ }
8230+ .into();
8231+ let cues: Vec<(f32, f32)> = track.cues.iter().map(|cue| cue_box(scale, cue)).collect();
8232+ Some(
8233+ div()
8234+ .flex_none()
8235+ .h(px(SUB_LANE_H))
8236+ .flex()
8237+ .gap(px(HEADER_GAP))
8238+ .child(
8239+ // Identified for the tooltip's sake and for nothing else:
8240+ // the whole of what a 40 px column can say is three
8241+ // characters, and the rest of it hangs off the hover.
8242+ div()
8243+ .id("subtitle-lane")
8244+ .flex_none()
8245+ .w(px(HEADER_W))
8246+ .h_full()
8247+ .flex()
8248+ .items_center()
8249+ // From the left rather than centred, unlike a lane's
8250+ // `V1`: a track label is a language or a file name, and
8251+ // a centred truncation eats both of its ends.
8252+ .px(px(2.))
8253+ .rounded(px(3.))
8254+ .bg(rgb(SURFACE))
8255+ .text_size(px(9.))
8256+ .text_color(rgb(INK_DIM))
8257+ .truncate()
8258+ .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())
8259+ .child(label),
8260+ )
8261+ .child(
8262+ div()
8263+ .relative()
8264+ .flex_1()
8265+ .min_w(px(0.))
8266+ .h_full()
8267+ .rounded(px(3.))
8268+ .bg(rgb(LETTERBOX))
8269+ .overflow_hidden()
8270+ .children(cues.into_iter().map(|(left, width)| {
8271+ div()
8272+ .absolute()
8273+ .top_0()
8274+ .h_full()
8275+ .left(px(left))
8276+ .w(px(width))
8277+ .rounded(px(2.))
8278+ .bg(rgb(SELECTED))
8279+ }))
8280+ // The playhead again, last and in the lanes' own colour:
8281+ // the strip is only worth anything beside them if it
8282+ // reads as the same moment.
8283+ .child(
8284+ div()
8285+ .absolute()
8286+ .top_0()
8287+ .h_full()
8288+ .left(px(filled))
8289+ .w(px(1.))
8290+ .bg(rgb(ACCENT)),
8291+ ),
8292+ ),
8293+ )
8294+ }
8295+
78878296 fn lane_row(
78888297 &self,
78898298 lane: Lane,
@@ -8603,6 +9012,90 @@ fn audio_notice(session: &PlaybackSession) -> Option<String> {
86039012 .map(|reason| format!(" — NO AUDIO: {reason}"))
86049013 }
86059014
9015+/// Whether a dropped or named path is a subtitle file rather than media: the
9016+/// formats `engine::subtitle` parses, lowercased, for [`engine::is_audio`]'s
9017+/// reason -- the import door has to know which of the engine's two doors a file
9018+/// goes through before anything is opened.
9019+fn is_subtitle(path: &std::path::Path) -> bool {
9020+ path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
9021+ matches!(
9022+ e.to_ascii_lowercase().as_str(),
9023+ "srt" | "vtt" | "webvtt" | "ass" | "ssa"
9024+ )
9025+ })
9026+}
9027+
9028+/// Whether a media path is a container that can carry subtitle tracks *inside*
9029+/// it -- the two Matroska extensions, which is what
9030+/// [`PlaybackSession::import_subtitles`] walks for them.
9031+fn is_matroska(path: &std::path::Path) -> bool {
9032+ path.extension()
9033+ .and_then(|e| e.to_str())
9034+ .is_some_and(|e| matches!(e.to_ascii_lowercase().as_str(), "mkv" | "webm"))
9035+}
9036+
9037+/// The subtitle tracks a media file carries, taken into the session as it is
9038+/// opened, and the tail the notice grows for them: an mkv with subtitles in it
9039+/// arrives with its subtitles, because a track nobody imported is a track nobody
9040+/// knows is there. Every other container answers `None` without being read.
9041+///
9042+/// A refusal is a tail too, never a failure of the open: the picture and the
9043+/// sound of a film whose subtitle tracks cannot be walked are still the film.
9044+///
9045+/// ponytail: the walk reads the whole file for its cues
9046+/// (`engine::subtitle::of_matroska`), so a long film pauses at the open it is
9047+/// part of. Ceiling: a two-hour remux. The upgrade is the background executor
9048+/// the waveforms already use, with the rows arriving when it lands.
9049+fn subtitle_notice(session: &mut PlaybackSession, path: &std::path::Path) -> Option<String> {
9050+ if !is_matroska(path) {
9051+ return None;
9052+ }
9053+ match session.import_subtitles(path) {
9054+ Ok(0) => None,
9055+ Ok(n) => Some(format!(" — {n} subtitle track(s) in the file")),
9056+ Err(e) => Some(format!(" — SUBTITLES UNREAD: {e}")),
9057+ }
9058+}
9059+
9060+/// What a subtitle row says under its name: how many cues it holds, or -- for a
9061+/// track that could not be read -- the engine's own reason, verbatim. A refusal
9062+/// is what the row is *for*: a PGS track off a BluRay remux is pictures, and a
9063+/// list that dropped it would say the film has no subtitles at all.
9064+fn subtitle_detail(track: &engine::subtitle::SubtitleTrack) -> String {
9065+ match &track.refused {
9066+ Some(why) => why.clone(),
9067+ None => format!("{} cues", track.cues.len()),
9068+ }
9069+}
9070+
9071+/// Where a cue is drawn on the bed: left edge and width in pixels, through the
9072+/// same [`Scale`] every clip box goes through -- so a cue and the take it is
9073+/// spoken over line up at every zoom, which is the only reason the strip is
9074+/// worth drawing. Microseconds are the cue's unit and seconds are the scale's,
9075+/// and this is the one place they meet.
9076+///
9077+/// Never narrower than [`SUB_CUE_MIN_W`]: zoomed out, a one-second cue is a
9078+/// fraction of a pixel, and a mark that rounds away reads as a track with
9079+/// nothing in it.
9080+fn cue_box(scale: Scale, cue: &engine::subtitle::Cue) -> (f32, f32) {
9081+ let (start, end) = (cue.start_us as f64 / 1e6, cue.end_us as f64 / 1e6);
9082+ (
9083+ scale.px_at(start),
9084+ scale.width_px(end - start).max(SUB_CUE_MIN_W),
9085+ )
9086+}
9087+
9088+/// Which cues of a track are on screen at `at` seconds. Half-open, as the cue
9089+/// itself is: one that ends exactly where the next begins hands over rather than
9090+/// overlapping it for a frame, and several that genuinely overlap all come back
9091+/// -- a sign and a line of dialogue are two cues at one moment.
9092+fn cues_at(cues: &[engine::subtitle::Cue], at: f64) -> Vec<&engine::subtitle::Cue> {
9093+ let us = (at * 1e6) as i64;
9094+ cues.iter()
9095+ .filter(|cue| cue.start_us <= us && us < cue.end_us)
9096+ .collect()
9097+}
9098+
86069099 /// The sources a repaint has not asked about yet. A key that is already there
86079100 /// means "asked", whatever state it is in, which is what stops a decode already
86089101 /// running from being started again by the next of sixty repaints a second.
@@ -8771,6 +9264,9 @@ struct Ctx {
87719264 timeline: bool,
87729265 /// Something has been copied.
87739266 clipboard: bool,
9267+ /// This timeline has at least one subtitle track: a toggle with nothing to
9268+ /// show is a switch that does nothing, and it says so rather than flipping.
9269+ subtitles: bool,
87749270 exporting: bool,
87759271 }
87769272
@@ -8862,6 +9358,10 @@ fn enable(action: ActionId, ctx: Ctx) -> Enable {
88629358 Enable::No("click a clip first")
88639359 }
88649360 ActionId::Paste if !ctx.clipboard => Enable::No("nothing copied yet"),
9361+ // Nothing to draw over the picture, so nothing to switch off: the
9362+ // library says how subtitles arrive, and this row would flip a state
9363+ // with no visible half either way.
9364+ ActionId::ToggleSubtitles if !ctx.subtitles => Enable::No("no subtitles yet"),
88659365 ActionId::CancelExport => Enable::No("nothing is exporting"),
88669366 // A rate applies to a clip of either kind and to its whole group, so
88679367 // there is no lane it means nothing on, and the engine words the one
@@ -9744,6 +10244,16 @@ fn lanes_h(lanes: usize) -> f32 {
974410244 }
974510245 }
974610246
10247+/// What the subtitle strip adds to the panel: its own row and the panel's gap
10248+/// above it, and nothing at all for a timeline with no subtitles on it -- the
10249+/// picture does not pay for a strip that is not drawn.
10250+fn subtitle_strip_h(shown: bool) -> f32 {
10251+ match shown {
10252+ true => SUB_LANE_H + 8.,
10253+ false => 0.,
10254+ }
10255+}
10256+
974710257 /// How tall the panel is with `lanes` tracks in it: [`PANEL_H`] is sized for the
974810258 /// two a project starts with, and every further one adds its own row -- up to
974910259 /// [`LANES_MAX`], past which the lane column scrolls instead and the panel stops
@@ -10951,6 +11461,10 @@ mod tests {
1095111461 repeats, resolution_choices, resolution_ladder, span_label, trimmed_clip, unscannable,
1095211462 visible_slice,
1095311463 };
11464+ use super::{
11465+ SUB_BOTTOM, SUB_CUE_MIN_W, SUB_INK, SUB_LANE_H, SUB_LINE_H, SUB_ROWS_H, SUB_TEXT, cue_box,
11466+ cues_at, is_matroska, is_subtitle, subtitle_detail, subtitle_notice, subtitle_strip_h,
11467+ };
1095411468
1095511469 /// What the file manager is handed: the parts a path keeps as they are, and
1095611470 /// the ones the bus would otherwise read as something else.
@@ -14230,6 +14744,166 @@ mod tests {
1423014744 assert_eq!(estimated_mb(Some(0), 60.), None);
1423114745 }
1423214746
14747+ /// Which cue is on screen when: the whole of what the overlay decides, and
14748+ /// the one piece of it that is arithmetic rather than layout.
14749+ #[test]
14750+ fn a_cue_is_on_screen_from_its_start_until_the_moment_it_ends() {
14751+ use engine::subtitle::Cue;
14752+ let cue = |start_us, end_us, text: &str| Cue {
14753+ start_us,
14754+ end_us,
14755+ text: text.to_string(),
14756+ };
14757+ // Two cues that hand over exactly, and one that overlaps the second --
14758+ // a sign over a line of dialogue, which is two plates at one moment.
14759+ let cues = [
14760+ cue(500_000, 1_500_000, "first line"),
14761+ cue(1_500_000, 2_500_000, "second line"),
14762+ cue(2_000_000, 2_200_000, "a sign"),
14763+ ];
14764+ let at = |t: f64| -> Vec<&str> {
14765+ cues_at(&cues, t)
14766+ .into_iter()
14767+ .map(|c| c.text.as_str())
14768+ .collect()
14769+ };
14770+ // Before the first, between none of them: nothing, which is what makes
14771+ // the overlay disappear rather than sit there empty.
14772+ assert!(at(0.).is_empty());
14773+ assert!(at(0.4).is_empty());
14774+ assert!(at(3.).is_empty());
14775+ assert_eq!(at(0.5), ["first line"], "on at its own start");
14776+ assert_eq!(at(1.4), ["first line"]);
14777+ // Half-open: the frame the first ends on is the second's, never both.
14778+ assert_eq!(at(1.5), ["second line"]);
14779+ assert_eq!(at(2.1), ["second line", "a sign"], "two at once stack");
14780+ assert_eq!(at(2.2), ["second line"], "the sign is over");
14781+ // ...and the end of the last one is the end of it.
14782+ assert!(at(2.5).is_empty());
14783+ // A negative time is before everything rather than a panic: the
14784+ // playhead is clamped, but nothing here depends on that.
14785+ assert!(at(-1.).is_empty());
14786+ }
14787+
14788+ /// The two places a subtitle is drawn -- the plate over the picture and the
14789+ /// strip under the lanes -- inside the 640x360 floor the rest of this window
14790+ /// is sized for, and the plate readable on whatever the film is showing.
14791+ #[test]
14792+ fn the_subtitle_plate_and_strip_fit_the_smallest_window() {
14793+ // The strip costs the panel its own row and the panel's gap, and costs
14794+ // nothing at all when there is no track to draw.
14795+ assert_eq!(subtitle_strip_h(false), 0.);
14796+ assert_eq!(subtitle_strip_h(true), SUB_LANE_H + 8.);
14797+ // What is left for the picture at the floor, with the panel a project
14798+ // starts with and the strip under it.
14799+ let picture = 360. - HEADER_H - panel_h(2) - subtitle_strip_h(true);
14800+ assert!(picture > 0., "the strip pushed the picture off the window");
14801+ // A two-line cue and the gap under it fit inside that, which is the
14802+ // whole claim: the plate sits *over* the picture and must not need more
14803+ // of it than there is.
14804+ assert!(
14805+ SUB_BOTTOM + 2. * SUB_LINE_H <= picture,
14806+ "a two-line cue does not fit the smallest picture"
14807+ );
14808+ // The text sits on its line rather than being clipped by it.
14809+ assert!(SUB_LINE_H >= SUB_TEXT);
14810+ // White on the plate, not chrome on chrome: a cue is read against the
14811+ // film, and this is the one pair here that has to survive any picture.
14812+ assert!(contrast(SUB_INK, 0x000000) >= 7.);
14813+ // The strip is a picture and not a target -- nothing on it takes a
14814+ // click -- which is the only reason it may be under `HIT_MIN`.
14815+ assert!(SUB_LANE_H < HIT_MIN && SUB_LANE_H > 0.);
14816+ // The library's own list of tracks scrolls past three rather than
14817+ // taking the media list's room.
14818+ assert_eq!(SUB_ROWS_H / ROW_H, 3.);
14819+ assert!(ROW_H >= HIT_MIN, "a subtitle row is clicked to pick it");
14820+ }
14821+
14822+ /// The two doors subtitles arrive through, end to end on the fixtures: a
14823+ /// file beside the media and the tracks inside an mkv, what the overlay then
14824+ /// says at a given moment, and where the strip draws it.
14825+ #[test]
14826+ fn subtitles_arrive_beside_the_media_and_inside_it() {
14827+ // Which door a path goes through is decided before anything is opened.
14828+ for name in ["subs.srt", "SUBS.SRT", "a.vtt", "a.ass", "a.ssa"] {
14829+ assert!(is_subtitle(Path::new(name)), "{name}");
14830+ }
14831+ for name in ["a.mp4", "a.mkv", "notes.txt", "a"] {
14832+ assert!(!is_subtitle(Path::new(name)), "{name}");
14833+ }
14834+ assert!(is_matroska(Path::new("film.MKV")) && is_matroska(Path::new("clip.webm")));
14835+ assert!(!is_matroska(Path::new("clip.mp4")));
14836+
14837+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
14838+ session.set_gain(0.0);
14839+ // Beside the media: the drop door's own call, and the row it makes.
14840+ let srt = Path::new(env!("CARGO_MANIFEST_DIR"))
14841+ .join("../engine/tests/data/test_subs.srt")
14842+ .canonicalize()
14843+ .expect("the subtitle fixture");
14844+ assert_eq!(session.import_subtitles(&srt).expect("the .srt imports"), 1);
14845+ let track = &session.subtitles()[0];
14846+ assert_eq!(track.label, "test_subs.srt");
14847+ assert_eq!(subtitle_detail(track), "3 cues");
14848+ // What the overlay draws at a moment inside the first cue, and between
14849+ // two of them -- the fixture's own timings (0.5-1.5 s, 2.0-3.25 s).
14850+ let text = |t: f64| -> Vec<String> {
14851+ cues_at(&track.cues, t)
14852+ .into_iter()
14853+ .map(|c| c.text.clone())
14854+ .collect()
14855+ };
14856+ assert_eq!(text(0.7), ["first line"]);
14857+ assert!(text(1.8).is_empty(), "between two cues the plate goes");
14858+ assert_eq!(text(2.5), ["second line\nwith a break"]);
14859+ // Where the strip puts that first cue: 0.5 s in at 40 px to the second
14860+ // is 20 px along, and a second of cue is 40 px wide.
14861+ let scale = Scale::default();
14862+ assert_eq!(scale.pps, PPS_DEFAULT);
14863+ assert_eq!(cue_box(scale, &track.cues[0]), (20., 40.));
14864+ // Zoomed right out, a cue worth a fraction of a pixel is still a mark.
14865+ let far = Scale {
14866+ pps: 0.01,
14867+ start: 0.,
14868+ };
14869+ assert_eq!(cue_box(far, &track.cues[0]).1, SUB_CUE_MIN_W);
14870+ // ...and scrolled past, its left edge is negative, exactly as a clip
14871+ // box's is: the bed clips it.
14872+ let scrolled = Scale {
14873+ pps: PPS_DEFAULT,
14874+ start: 1.,
14875+ };
14876+ assert_eq!(cue_box(scrolled, &track.cues[0]).0, -20.);
14877+
14878+ // Inside the media: the tracks of an mkv, taken by the same call every
14879+ // open and import door makes. Two of them in the fixture, named by what
14880+ // the file says rather than by number.
14881+ let notice =
14882+ subtitle_notice(&mut session, &asset("test_subs.mkv")).expect("the mkv carries two");
14883+ assert!(notice.contains('2'), "{notice}");
14884+ assert_eq!(session.subtitles().len(), 3);
14885+ assert_eq!(session.subtitles()[1].label, "eng");
14886+ assert_eq!(session.subtitles()[2].label, "fra — Signs");
14887+ assert_eq!(subtitle_detail(&session.subtitles()[1]), "3 cues");
14888+ // The same file twice adds nothing and says nothing.
14889+ assert_eq!(subtitle_notice(&mut session, &asset("test_subs.mkv")), None);
14890+ // A container that cannot hold them is never even read.
14891+ assert_eq!(subtitle_notice(&mut session, &asset("test_av.mp4")), None);
14892+
14893+ // A track that could not be read says why, where its cue count would
14894+ // be: what the greyed library row prints, and the whole difference
14895+ // between "this film has no subtitles" and "these four are pictures".
14896+ let refused = engine::subtitle::SubtitleTrack {
14897+ path: PathBuf::from("/a/remux.mkv"),
14898+ track: Some(1),
14899+ label: "eng".into(),
14900+ cues: Vec::new(),
14901+ refused: Some("S_HDMV/PGS subtitles are pictures, not text".into()),
14902+ };
14903+ assert!(subtitle_detail(&refused).contains("pictures"));
14904+ assert!(cues_at(&refused.cues, 1.).is_empty());
14905+ }
14906+
1423314907 #[test]
1423414908 fn nothing_clickable_is_smaller_than_the_wcag_minimum() {
1423514909 // Every hit target in the panel, including the scrub strip -- whose bar
@@ -14733,15 +15407,40 @@ fn main() {
1473315407 // not fatal -- the others still load -- but the window must not open
1473415408 // silently pretending the file was taken, so the first one seeds the notice.
1473515409 for extra in std::env::args().skip(2) {
15410+ let extra = PathBuf::from(&extra);
1473615411 // Only reachable with a first argument, so there is a timeline.
14737- if let Some(session) = &mut session
14738- && let Err(e) = session.import(std::path::Path::new(&extra))
14739- {
14740- let text = format!("IMPORT FAILED: {e}");
14741- eprintln!("{extra}: {text}");
14742- notice.get_or_insert(text);
15412+ let Some(session) = &mut session else {
15413+ continue;
15414+ };
15415+ // A subtitle file named on the command line is not a source: it goes
15416+ // through the engine's other door, exactly as a dropped one does.
15417+ let imported = match is_subtitle(&extra) {
15418+ true => session.import_subtitles(&extra).map(|_| 0),
15419+ false => session.import(&extra),
15420+ };
15421+ match imported {
15422+ // The file's own tracks with it, as every other import door takes
15423+ // them.
15424+ Ok(_) => {
15425+ if let Some(text) = subtitle_notice(session, &extra) {
15426+ eprintln!("{}: {text}", extra.display());
15427+ }
15428+ }
15429+ Err(e) => {
15430+ let text = format!("IMPORT FAILED: {e}");
15431+ eprintln!("{}: {text}", extra.display());
15432+ notice.get_or_insert(text);
15433+ }
1474315434 }
1474415435 }
15436+ // The subtitle tracks inside the file that *is* the timeline, taken at the
15437+ // launch the window opens from -- the same pickup the drop and the Import
15438+ // button make (`open_media`).
15439+ if let (Some(session), Some(arg)) = (&mut session, &arg)
15440+ && let Some(text) = subtitle_notice(session, arg)
15441+ {
15442+ eprintln!("{text}");
15443+ }
1474515444 // A file that plays silent is as much news at launch as it is on a drop, and
1474615445 // behind the keymap notice for the same reason an import refusal is.
1474715446 if let Some(reason) = session
@@ -14840,6 +15539,8 @@ fn main() {
1484015539 trim: None,
1484115540 grab: 0,
1484215541 snap: true,
15542+ subs_on: true,
15543+ sub_track: 0,
1484315544 snap_cue: None,
1484415545 ghost: None,
1484515546 last_scrub: Instant::now(),