diff --git a/crates/app/src/interact.rs b/crates/app/src/interact.rs index 101f7e8..6ac8f06 100644 --- a/crates/app/src/interact.rs +++ b/crates/app/src/interact.rs @@ -25,6 +25,25 @@ pub(crate) struct ClipDrag { pub(crate) clip: Clip, } +/// A *palette* subtitle row being dragged onto a subtitle lane: which track of +/// [`PlaybackSession::subtitles`] it is, which is the whole of what a row names. +/// The window it lands with is the track's own, from its first microsecond to +/// its last cue -- a placement is trimmed after it is placed, like every clip +/// here. +pub(crate) struct SubPick(pub(crate) usize); + +/// A subtitle already placed on a lane being dragged: [`ClipDrag`]'s twin, and +/// carrying the placement itself for that struct's reason -- an edit made during +/// the gesture moves the indices gpui froze into the payload, so the drop finds +/// its placement by value ([`Player::dragged_sub`]) rather than by an index that +/// may since have become another caption's. +#[derive(Clone, Copy)] +pub(crate) struct SubDrag { + pub(crate) lane: Lane, + pub(crate) idx: usize, + pub(crate) sub: SubClip, +} + /// A track *header* being dragged: which track the hand took hold of, to be /// let go over the header of the one whose place it is to take /// ([`Player::reorder_lane`]). The lane alone -- a track carries its own clips diff --git a/crates/app/src/layout.rs b/crates/app/src/layout.rs index bb044be..dce15ce 100644 --- a/crates/app/src/layout.rs +++ b/crates/app/src/layout.rs @@ -142,10 +142,6 @@ pub(crate) fn sub_bottom(bars_h: f32) -> f32 { // height -- either way there is nothing to clear. SUB_BOTTOM + bars_h.max(0.) } -/// The subtitle strip under the lanes: thin, because it is a picture of where -/// the cues are and nothing on it can be dragged -- `HIT_MIN` binds targets, and -/// this row has none. -pub(crate) const SUB_LANE_H: f32 = 16.; /// A mark narrower than this is still drawn this wide: a one-frame cue on a /// zoomed-out bed is worth a fraction of a pixel, and a mark nobody can see says /// the track is empty. The silence preview's marks are floored by it too -- they @@ -229,16 +225,6 @@ pub(crate) fn px_below(max_offset_h: f32, offset_y: f32) -> f32 { (max_offset_h + offset_y).max(0.) } -/// What the subtitle strip adds to the panel: its own row and the panel's gap -/// above it, and nothing at all for a timeline with no subtitles on it -- the -/// picture does not pay for a strip that is not drawn. -pub(crate) fn subtitle_strip_h(shown: bool) -> f32 { - match shown { - true => SUB_LANE_H + 8., - false => 0., - } -} - /// How tall the panel is with `lanes` tracks in it: [`PANEL_H`] is sized for the /// two a project starts with, and every further one adds its own row -- up to /// [`LANES_MAX`], past which the lane column scrolls instead and the panel stops diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 690a86d..ffba6b6 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -58,7 +58,7 @@ use engine::decode::Backend; use engine::eq::{Band, BandKind, EqParams}; use engine::export::{AUDIO_KBPS, DEFAULT_AUDIO_KBPS, EncoderSeat, ExportSettings, Format}; use engine::limiter::Limiter; -use engine::project::{Edge, Lane, LaneKind, Source, Speed}; +use engine::project::{Edge, Lane, LaneKind, Source, Speed, SubClip}; use engine::scale::FitPolicy; use engine::tonemap::Preset; use engine::{Clip, Codec, ExportHandle, Frame, MediaBitrate, PlaybackSession}; @@ -240,6 +240,24 @@ struct Player { /// one can be read at a time. Cleared with the timeline like every other /// index here -- track 2 of one project is not track 2 of the next. sub_track: usize, + /// The subtitle lanes whose eye is shut: every lane shows its captions + /// until this says otherwise, so a lane that was just added is a lane that + /// draws. Held as the lanes that are *off* rather than a flag per lane, so + /// adding one needs no bookkeeping at all. + /// + /// State only this slice: the preview reads the picked palette track still + /// ([`Player::sub_picture`]), so shutting an eye marks the header and + /// changes nothing over the picture until the slice that draws the lanes' + /// cues there reads this field. Not saved either -- a `.edith` has no line + /// for it yet. + /// + /// A [`Lane`] handle is a position among its kind, so a removal or a + /// reorder leaves every shut eye naming another track: they are dropped + /// wholesale there, exactly as the selection and the open cards are + /// ([`Player::remove_lane`], [`Player::reorder_lane`]) -- which is why a + /// lane added in a removed one's place opens with its eye open, as every + /// new lane does. + subs_off: Vec, /// The frame the live gesture is about to land on, or `None` while it is /// over open bed: the line every lane draws so the snap is seen before it /// happens rather than discovered after the release. Stale between gestures, @@ -629,6 +647,7 @@ fn main() { snap: true, subs_on: true, sub_track: 0, + subs_off: Vec::new(), snap_cue: None, ghost: None, lane_drop: None, diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index 9355c9f..0c9c696 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -147,8 +147,10 @@ impl Player { self.clipboard = None; self.selected = None; self.selected_asset = None; - // The subtitle rows go with the timeline they were on. + // The subtitle rows go with the timeline they were on, and so do the + // eyes: S1 of one project is not S1 of the next. self.sub_track = 0; + self.subs_off.clear(); self.context_menu = None; self.library_menu = None; self.eq_open = None; @@ -991,6 +993,10 @@ impl Player { self.color_open = None; self.speed_open = None; self.close_silence(); + // The eyes with them: a `Lane` is a position among its + // kind, so every shut one now names another track -- + // the same reason the selection and the cards go. + self.subs_off.clear(); format!( "{} REMOVED — {} brings it back", lane.label(), @@ -1043,6 +1049,10 @@ impl Player { self.color_open = None; self.speed_open = None; self.close_silence(); + // The eyes with them: a `Lane` is a position among its + // kind, so every shut one now names another track -- + // the same reason the selection and the cards go. + self.subs_off.clear(); } self.notify_user( format!( diff --git a/crates/app/src/player/timeline_edit.rs b/crates/app/src/player/timeline_edit.rs index 2b8d4b5..02dbf5f 100644 --- a/crates/app/src/player/timeline_edit.rs +++ b/crates/app/src/player/timeline_edit.rs @@ -264,6 +264,184 @@ impl Player { cx.notify(); } + /// The whole of a palette track as a placement: from its own first + /// microsecond to its last cue, and as many timeline frames as that is worth + /// at this rate. What a row dragged out of the Subtitles list carries, and + /// what the ghost is drawn from -- `start` is ignored by + /// [`PlaybackSession::place_sub`], which takes the frame the hand let go on. + /// + /// `None` for a track with nothing to place: one that could not be read, and + /// one that genuinely has no cues. + pub(crate) fn sub_of_track(&self, track: usize) -> Option { + let cues = &self.session.as_ref()?.subtitles().get(track)?.cues; + let out_us = cues.iter().map(|c| c.end_us).max()?; + Some(SubClip { + start: 0, + frames: frames_of_us(out_us, self.fps), + track, + in_us: 0, + out_us, + }) + } + + /// A palette row let go at window `x` over subtitle lane `to`: the whole + /// track goes down where the hand left it, one undo step + /// ([`PlaybackSession::place_sub`]). Every refusal there is words -- an + /// overlap, a lane that is not a subtitle lane, a track that is not there -- + /// and they are shown as the engine worded them. + pub(crate) fn place_sub(&mut self, track: usize, to: Lane, x: Pixels, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + self.snap_cue = None; + self.ghost = None; + let at = self.place_frame(x).0; + let text = match (self.sub_of_track(track), &mut self.session) { + (Some(sub), Some(session)) => match session.place_sub(to, at, sub) { + Ok(()) => None, + Err(e) => Some(format!("NOT PLACED — {e}")), + }, + // The row is greyed and says why in the list; here it says why at + // the moment somebody tried to use it anyway. + (None, Some(_)) => Some( + "NOT PLACED — that subtitle track has no cues to place; the list says why" + .to_string(), + ), + (_, None) => Some("NOT PLACED — open a file first".to_string()), + }; + if let Some(text) = text { + self.notify_user(text.into()); + } + cx.notify(); + } + + /// Which index its lane holds the dragged placement at *now* + /// ([`Player::dragged`]'s twin, through the same [`live_idx`]): a stroke + /// during the gesture -- an undo, another drop -- moves the indices gpui + /// froze into the payload. + pub(crate) fn dragged_sub(&self, drag: &SubDrag) -> Option { + live_idx(self.session.as_ref()?.sub_lane(drag.lane), drag.idx, drag.sub) + } + + /// A placed caption let go at window `x` over subtitle lane `to`: it lands + /// with its head where the hand carried it, on the lane it was dropped on -- + /// one undo step, and none at all for a drop that changed nothing, which is + /// why an `Ok` is never a toast ([`Project::move_sub`]). An overlap and a + /// lane of the wrong kind are refused in the engine's own words. + pub(crate) fn move_sub(&mut self, drag: &SubDrag, to: Lane, x: Pixels, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + self.snap_cue = None; + self.ghost = None; + let Some(idx) = self.dragged_sub(drag) else { + return; + }; + let start = self.sub_drop_frame(drag.sub, x).0; + if let Some(Err(e)) = self + .session + .as_mut() + .map(|session| session.move_sub(drag.lane, idx, to, start)) + { + self.notify_user(format!("NOT MOVED — {e}").into()); + } + cx.notify(); + } + + /// The × on a caption's own box: it comes off the lane and leaves the gap, + /// one undo step ([`PlaybackSession::lift_sub`]). The palette row it played + /// stays in the list, which is what makes this a lift and not a removal -- + /// and the way a subtitle lane is emptied so it can be taken off at all. + pub(crate) fn lift_sub(&mut self, lane: Lane, idx: usize, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + let lifted = self + .session + .as_mut() + .is_some_and(|session| session.lift_sub(lane, idx)); + let text = match lifted { + true => format!( + "CAPTION LIFTED — {} puts it back", + self.keymap.display(ActionId::Undo) + ), + false => "NOTHING LIFTED — that caption is not there any more".to_string(), + }; + self.notify_user(text.into()); + cx.notify(); + } + + /// A subtitle lane's eye: whether it draws its captions. State only for now + /// -- what reads it is the slice that draws the lanes over the picture -- + /// and said out loud, because a toggle whose only effect is a header glyph + /// has to say what it has and has not done yet. + pub(crate) fn toggle_sub_lane(&mut self, lane: Lane, cx: &mut Context) { + let text = match self.subs_off.iter().position(|&l| l == lane) { + Some(i) => { + self.subs_off.remove(i); + format!("{} SHOWS ITS CAPTIONS", lane.label()) + } + None => { + self.subs_off.push(lane); + format!("{} IS HIDDEN — its captions stay on the lane", lane.label()) + } + }; + self.notify_user(text.into()); + cx.notify(); + } + + /// Whether that subtitle lane's captions are drawn -- the eye, read by the + /// header that offers it and by whatever draws cues from here on. + pub(crate) fn sub_lane_on(&self, lane: Lane) -> bool { + !self.subs_off.contains(&lane) + } + + /// Where a caption let go at window `x` wants its head: [`Player::drop_frame`]'s + /// twin, and the same [`landing`] -- the grab offset the press noted, and the + /// snap onto the edges the rest of the timeline offers, so a caption lands on + /// the cut it is spoken over. + pub(crate) fn sub_drop_frame(&self, sub: SubClip, x: Pixels) -> (u32, Option) { + let marks = self.snap_targets(None); + landing( + self.frame_under(x), + self.grab, + sub.frames, + self.snap, + self.snap_frames(), + &marks, + ) + } + + /// The shadow a caption in the hand would fill, on the lane the pointer is + /// over: [`Player::preview_ghost`]'s twin, refused for any lane that is not a + /// subtitle lane -- which is the answer [`Project::move_sub`] gives at the + /// release. + pub(crate) fn preview_ghost_sub(&mut self, drag: &SubDrag, to: Lane, x: Pixels, cx: &mut Context) { + let (start, _) = self.sub_drop_frame(drag.sub, x); + let ghost = Ghost { + lane: to, + start, + frames: drag.sub.frames, + tint: CLIP_TEXT(), + refused: to.kind != LaneKind::Subtitle, + }; + self.set_ghost(Some(ghost), cx); + } + + /// The same for a palette row on its way down: it lands at the frame it is + /// let go on ([`Player::place_frame`]) and is as long as the whole track it + /// names. + pub(crate) fn preview_ghost_pick(&mut self, track: usize, to: Lane, x: Pixels, cx: &mut Context) { + let ghost = Ghost { + lane: to, + start: self.place_frame(x).0, + frames: self.sub_of_track(track).map_or(0, |sub| sub.frames), + tint: CLIP_TEXT(), + refused: to.kind != LaneKind::Subtitle, + }; + self.set_ghost(Some(ghost), cx); + } + /// Where a clip let go at window `x` over lane `to` wants its head: the /// frame under the pointer, less however far into the box the hand grabbed /// it (so the clip does not jump under the pointer), pulled onto a @@ -624,6 +802,33 @@ impl Player { if self.modal() || self.exporting().is_some() { return; } + // A caption's edge, on a lane that holds no `Clip` at all: the same + // gesture, the same `Trim`, and the branch is the lane's kind wherever + // the drag is asked about ([`Player::trim_to`], + // [`Player::commit_trim`]). No selection -- a placement is not in the + // clip selection's index space -- and no group: a caption has no half + // on another lane. + if lane.kind == LaneKind::Subtitle { + let Some(sub) = self + .session + .as_ref() + .and_then(|session| session.sub_lane(lane).get(idx).copied()) + else { + return; + }; + self.trim = Some(Trim { + lane, + idx, + edge, + to: match edge { + Edge::Start => sub.start, + Edge::End => sub.end(), + }, + link: None, + }); + cx.notify(); + return; + } let Some(clip) = self .session .as_ref() @@ -659,11 +864,16 @@ impl Player { // there is no other end travelling with it, so it snaps at length zero. let marks = self.snap_targets(Some((trim.lane, trim.idx))); let (at, cue) = self.snap_to(self.frame_under(x), 0, &marks); - let Some((lo, hi)) = self - .session - .as_ref() - .and_then(|session| session.trim_room(trim.lane, trim.idx, trim.edge)) - else { + let Some((lo, hi)) = self.session.as_ref().and_then(|session| { + match trim.lane.kind == LaneKind::Subtitle { + // The walls a caption's edge has -- its neighbour, its own + // track's first microsecond and its last cue -- asked at this + // timeline's rate, which is why the session is the door and not + // the project. + true => session.trim_sub_room(trim.lane, trim.idx, trim.edge), + false => session.trim_room(trim.lane, trim.idx, trim.edge), + } + }) else { return; }; let to = at.clamp(lo, hi); @@ -693,6 +903,22 @@ impl Player { let Some(trim) = self.trim.take() else { return; }; + // A caption's edge reaches the engine through its own door, at this + // timeline's rate. An `Ok` is *not* "something changed" -- an edge that + // stopped at a wall it already stood against is `Ok` with no undo step + // ([`Project::trim_sub`]) -- so only the refusal is ever said out loud, + // and nothing reseeks: cues are drawn over whatever is decoded. + if trim.lane.kind == LaneKind::Subtitle { + if let Some(Err(e)) = self + .session + .as_mut() + .map(|session| session.trim_sub(trim.lane, trim.idx, trim.edge, trim.to)) + { + self.notify_user(format!("NOT TRIMMED — {e}").into()); + } + cx.notify(); + return; + } let trimmed = self .session .as_mut() @@ -721,6 +947,15 @@ impl Player { trimmed_clip(clip, trim.edge, trim.to, still) } + /// The caption as the drag is showing it, [`Player::trimmed`]'s twin: + /// display only, and the engine hears about it once, at the release. + pub(crate) fn trimmed_sub(&self, lane: Lane, idx: usize, sub: SubClip) -> SubClip { + match self.trim.filter(|t| (t.lane, t.idx) == (lane, idx)) { + Some(trim) => trimmed_sub(sub, trim.edge, trim.to), + None => sub, + } + } + /// How long the timeline is *drawn* as: its own length, and while a tail is /// being dragged the furthest that tail may reach. A bed that ends exactly /// at the last frame has nowhere to put a pointer that means "longer", so diff --git a/crates/app/src/render.rs b/crates/app/src/render.rs index db07b7e..59c8870 100644 --- a/crates/app/src/render.rs +++ b/crates/app/src/render.rs @@ -515,6 +515,22 @@ impl Render for Player { this.set_ghost(None, cx); }), ) + // The same pair for the two subtitle gestures, for the same reason: + // a palette row starts up in the library and a caption starts on a + // lane, and both are let go somewhere else entirely. + .on_drag_move(cx.listener(|this, event: &DragMoveEvent, _, cx| { + this.preview_place(event.event.position.x, cx); + this.set_ghost(None, cx); + })) + .on_drag_move(cx.listener(|this, event: &DragMoveEvent, _, cx| { + // The placement gpui froze into the payload, whose *length* is + // all the line needs; which caption it is is the drop's + // question ([`Player::dragged_sub`]). + let (drag, x) = (*event.drag(cx), event.event.position.x); + let cue = this.sub_drop_frame(drag.sub, x).1; + this.set_cue(cue, x, cx); + this.set_ghost(None, cx); + })) // Scrubbing is tracked on the root because the pointer leaves the // 6 px ruler on the first drag and its own listeners then stop // firing; the root's hitbox is the whole window. diff --git a/crates/app/src/tests/layout.rs b/crates/app/src/tests/layout.rs index 0bd583a..1da5f21 100644 --- a/crates/app/src/tests/layout.rs +++ b/crates/app/src/tests/layout.rs @@ -405,6 +405,82 @@ fn a_trim_preview_lands_where_the_release_commits() { } } +/// The caption a drag is showing lands where the release commits -- the +/// subtitle twin of the trim preview above -- and the two contracts the boxes +/// on the lanes rest on: `place_sub`'s `at` wins over the placement's own +/// `start`, and a gesture that changed nothing is `Ok` and not a refusal, so a +/// front-end that toasted every `Ok` would toast a pick-up-put-back. +#[test] +fn a_caption_trim_preview_lands_where_the_release_commits() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + let fps = session.meta().frame_rate; + let srt = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../engine/tests/data/test_subs.srt") + .canonicalize() + .expect("the subtitle fixture"); + session.import_subtitles(&srt).expect("the .srt imports"); + let lane = session.add_lane(LaneKind::Subtitle); + // The whole track as a placement, exactly as `Player::sub_of_track` builds + // one from a palette row. + let out_us = session.subtitles()[0] + .cues + .iter() + .map(|c| c.end_us) + .max() + .expect("the fixture has cues"); + let whole = SubClip { + start: 0, + frames: frames_of_us(out_us, fps), + track: 0, + in_us: 0, + out_us, + }; + session + .place_sub(lane, 30, whole) + .expect("an empty subtitle lane takes it"); + assert_eq!( + session.sub_lane(lane)[0].start, + 30, + "the frame the hand let go on wins over the placement's own start" + ); + for edge in [Edge::Start, Edge::End] { + let (lo, hi) = session + .trim_sub_room(lane, 0, edge) + .expect("placement 0 is there"); + for to in [lo, (lo + hi) / 2, hi] { + let placed = session.sub_lane(lane)[0]; + let preview = trimmed_sub(placed, edge, to); + session + .trim_sub(lane, 0, edge, to) + .expect("an edge inside its own room is never refused"); + let now = session.sub_lane(lane)[0]; + assert_eq!( + (preview.start, preview.frames), + (now.start, now.frames), + "{edge:?} to {to}" + ); + // One edit, one undo step -- and none at all where the edge was + // already there, which is the `Ok` that must stay silent. + if (now.start, now.frames) != (placed.start, placed.frames) { + assert!(session.undo(), "the trim is one undo step"); + } + } + } + // Picked up and put back down: `Ok`, nothing moved, nothing to say. + let before = session.sub_lane(lane)[0]; + session + .move_sub(lane, 0, lane, before.start) + .expect("a drop that changes nothing is not a refusal"); + assert_eq!(session.sub_lane(lane)[0], before); + // ...and two captions over one frame are refused in words, which is what + // the notice shows verbatim. + let over = session + .place_sub(lane, before.start, whole) + .expect_err("two captions may not cover one frame"); + assert!(over.to_string().contains("already covers"), "{over}"); +} + /// A still trims the same way, and the preview knows it: its head grows /// forward from source frame 0 -- every frame of it is the same picture -- /// so the box stretches instead of sliding left. diff --git a/crates/app/src/tests/media.rs b/crates/app/src/tests/media.rs index cb898fc..193cc4a 100644 --- a/crates/app/src/tests/media.rs +++ b/crates/app/src/tests/media.rs @@ -796,18 +796,19 @@ fn a_cue_steps_over_whatever_bar_is_hanging_off_the_picture() { } /// The two places a subtitle is drawn -- the plate over the picture and the -/// strip under the lanes -- inside the 640x360 floor the rest of this window +/// lanes under the tracks -- inside the 640x360 floor the rest of this window /// is sized for, and the plate readable on whatever the film is showing. #[test] -fn the_subtitle_plate_and_strip_fit_the_smallest_window() { - // The strip costs the panel its own row and the panel's gap, and costs - // nothing at all when there is no track to draw. - assert_eq!(subtitle_strip_h(false), 0.); - assert_eq!(subtitle_strip_h(true), SUB_LANE_H + 8.); - // What is left for the picture at the floor, with the panel a project - // starts with and the strip under it. - let picture = 360. - HEADER_H - panel_h(2) - subtitle_strip_h(true); - assert!(picture > 0., "the strip pushed the picture off the window"); +fn the_subtitle_plate_and_lanes_fit_the_smallest_window() { + // A subtitle lane is a lane: it costs the panel exactly what a third + // track costs it, and a timeline with none costs nothing at all -- the + // strip that used to hang under the lanes is gone, and with it the one + // row nothing could be dropped on. + assert_eq!(lanes_h(3) - lanes_h(2), LANE_H + 8.); + // What is left for the picture at the floor, with a project's two tracks + // and a subtitle lane under them. + let picture = 360. - HEADER_H - panel_h(3); + assert!(picture > 0., "a subtitle lane pushed the picture off the window"); // A two-line cue and the gap under it fit inside that, which is the // whole claim: the plate sits *over* the picture and must not need more // of it than there is. @@ -822,9 +823,10 @@ fn the_subtitle_plate_and_strip_fit_the_smallest_window() { for id in crate::ui::theme::PaletteId::ALL { assert!(contrast(id.palette().SUB_FG, 0x000000) >= 7., "{id:?}"); } - // The strip is a picture and not a target -- nothing on it takes a - // click -- which is the only reason it may be under `HIT_MIN`. - assert!(SUB_LANE_H < HIT_MIN && SUB_LANE_H > 0.); + // A subtitle lane is dragged onto, trimmed on and lifted from, so its row + // is a target and binds `HIT_MIN` like every other lane's -- the whole + // reason it is a lane and no longer a 16 px strip. + assert!(LANE_H >= HIT_MIN); // The library's own list of tracks scrolls past three rather than // taking the media list's room. assert_eq!(SUB_ROWS_H / ROW_H, 3.); diff --git a/crates/app/src/tests/mod.rs b/crates/app/src/tests/mod.rs index b1939ad..85be6a3 100644 --- a/crates/app/src/tests/mod.rs +++ b/crates/app/src/tests/mod.rs @@ -39,7 +39,7 @@ use super::{ }; use super::{ - Choice, EDGE_W, ETA_SPAN, Edge, FITS, FRAME_RATES, LaneKind, PPS_DEFAULT, PPS_MIN, Preset, RESOLUTIONS, Repeat, + Choice, EDGE_W, ETA_SPAN, Edge, FITS, FRAME_RATES, LaneKind, SubClip, PPS_DEFAULT, PPS_MIN, Preset, RESOLUTIONS, Repeat, Scale, View, ZOOM_MIN_FRAMES, ZOOM_OUT_MARGIN, ZOOM_STEP, audio_rate_choices, av1_hw_warning, clock, encoder_choices, encoder_label, eta_secs, file_name, file_uri, @@ -49,16 +49,16 @@ use super::{ Landing, arrival, launch_queue, read_ahead, scan_plan, seek_line, silence_line, source_secs, stash_or_write, repeats, resolution_choices, resolution_ladder, span_label, tone_choices, tone_label, - clip_width, trimmed_clip, trims, unscannable, unusable, + clip_width, frames_of_us, trimmed_clip, trimmed_sub, trims, unscannable, unusable, visible_slice, }; use super::{ - SUB_BOTTOM, SUB_CUE_MIN_W, SUB_HEAD_H, SUB_FG, SUB_LANE_H, SUB_LINE_H, SUB_ROWS_H, + SUB_BOTTOM, SUB_CUE_MIN_W, SUB_HEAD_H, SUB_FG, SUB_LINE_H, SUB_ROWS_H, SUB_STEM_SHARE, SUB_TEXT, clip_middle, cue_box, sub_bottom, carries_subtitles, cues_at, file_tint, is_subtitle, lang_human, row_text_w, sub_headers_fit, Subs, subtitle_detail, subtitle_notice, subtitle_tail, - sub_pick_name, subtitle_rows, subtitle_strip_h, walk_subtitles, + sub_pick_name, subtitle_rows, walk_subtitles, }; use engine::PlaybackSession; diff --git a/crates/app/src/tests/view.rs b/crates/app/src/tests/view.rs index 545fb14..8ace825 100644 --- a/crates/app/src/tests/view.rs +++ b/crates/app/src/tests/view.rs @@ -126,6 +126,20 @@ fn a_lane_refuses_the_files_it_cannot_hold_before_the_release_says_so() { // engine takes its sound onto one, and the words for a video-only file // are its own. assert_eq!(lane_refuses(movie, audio), None); + // ...and a subtitle lane holds none of the three: a caption comes off the + // Subtitles list, which is where the refusal points. + for file in [sound, still, movie] { + let why = lane_refuses(file, Lane::S1).expect("a subtitle lane takes no media"); + assert!(why.starts_with("NOT ON S1 — "), "{why}"); + assert!(why.contains("Subtitles list"), "{why}"); + } + // How the two clocks a caption has meet, which is what a palette row's + // length is worked out with: a second of words at 30 fps is 30 frames, + // and a track shorter than one frame is still a caption to place. + assert_eq!(frames_of_us(1_000_000, 30.), 30); + assert_eq!(frames_of_us(500_000, 24.), 12); + assert_eq!(frames_of_us(1_000, 30.), 1); + assert_eq!(frames_of_us(1_000_000, 0.), 1); } /// Where those edges come from: every lane, not the one being dropped on -- diff --git a/crates/app/src/timeline_math.rs b/crates/app/src/timeline_math.rs index 04de7ae..0435d37 100644 --- a/crates/app/src/timeline_math.rs +++ b/crates/app/src/timeline_math.rs @@ -146,6 +146,45 @@ pub(crate) fn trimmed_clip(clip: Clip, edge: Edge, to: u32, still: bool) -> Clip } } +/// How many timeline frames a stretch of a subtitle track is worth: the one +/// conversion between the two clocks a caption has -- microseconds for its +/// words, frames for where it sits -- and the app-side twin of the engine's own +/// (`Project::trim_sub_room`). Never zero: a placement of no frames is the one +/// [`Project::place_sub`] refuses as empty, and a track shorter than a frame is +/// still a caption somebody dragged. +pub(crate) fn frames_of_us(us: i64, fps: f64) -> u32 { + match fps.is_finite() && fps > 0. { + true => ((us as f64) * fps / 1e6) + .round() + .clamp(1., f64::from(u32::MAX)) as u32, + false => 1, + } +} + +/// The *placement* a trim is showing, the same way for a caption: +/// [`Project::trim_sub`] moves the head or the tail and the window follows it, +/// so the box on screen is the frames alone -- the words it will keep are the +/// engine's arithmetic at the release, and nothing here draws them. +/// +/// An edge that has not moved draws the placement it pressed, and one dragged +/// past its other end keeps the one frame the engine's own walls always leave. +pub(crate) fn trimmed_sub(sub: SubClip, edge: Edge, to: u32) -> SubClip { + match edge { + Edge::Start => { + let to = to.min(sub.end() - 1); + SubClip { + start: to, + frames: sub.end() - to, + ..sub + } + } + Edge::End => SubClip { + frames: to.max(sub.start + 1) - sub.start, + ..sub + }, + } +} + /// Which index on its own lane a dragged clip is at *now*: the one it was picked /// up at while nothing has moved, and wherever the clip itself has slid to when /// an edit during the drag rippled the lane's indices -- a delete, an undo or a @@ -153,8 +192,9 @@ pub(crate) fn trimmed_clip(clip: Clip, edge: Edge, to: u32, still: bool) -> Clip /// `None` when the clip is gone altogether, and then the drop is not an edit at /// all: moving whatever slid into its place is the one thing the hand did not /// ask for. A lane's clips are disjoint and sorted, so at most one of them can -/// be the clip that was picked up. -pub(crate) fn live_idx(clips: &[Clip], idx: usize, clip: Clip) -> Option { +/// be the clip that was picked up. Generic over what a lane holds, because a +/// [`SubClip`] is dragged under exactly the same rule. +pub(crate) fn live_idx(clips: &[T], idx: usize, clip: T) -> Option { match clips.get(idx) { Some(&at) if at == clip => Some(idx), _ => clips.iter().position(|&c| c == clip), @@ -396,6 +436,13 @@ pub(crate) fn lane_refuses(path: &Path, lane: Lane) -> Option { LaneKind::Audio if engine::is_image(path) => { Some(format!("NOT ON {label} — {name} is a still image; drop it on a video lane")) } + // A subtitle lane holds words and no media at all: the refusal is here + // rather than at the engine's door so the shadow is tinted red on the + // way down, like every other lane a file cannot go on. + LaneKind::Subtitle => Some(format!( + "NOT ON {label} — {name} is a file; a subtitle track takes captions, dragged from the \ + Subtitles list" + )), _ => None, } } diff --git a/crates/app/src/ui/theme.rs b/crates/app/src/ui/theme.rs index 0c8e0e1..ffa39f6 100644 --- a/crates/app/src/ui/theme.rs +++ b/crates/app/src/ui/theme.rs @@ -1095,12 +1095,10 @@ pub fn clip_kind(kind: LaneKind, image: bool) -> u32 { LaneKind::Audio => CLIP_AUDIO(), LaneKind::Video if image => CLIP_IMAGE(), LaneKind::Video => CLIP_VIDEO(), - // A caption borrows the still's shade until the slice that draws - // subtitle lanes gives it one of its own in every family: nothing on - // screen paints one yet (the engine model landed first), and inventing - // a colour here for a box nobody draws is the one thing this call says - // not to do. - LaneKind::Subtitle => CLIP_IMAGE(), + // The purple every editor paints a title track, and the one clip colour + // this palette already carried and nothing drew: a caption's box is now + // that box. + LaneKind::Subtitle => CLIP_TEXT(), } } diff --git a/crates/app/src/ui/timeline.rs b/crates/app/src/ui/timeline.rs index 6689697..888a448 100644 --- a/crates/app/src/ui/timeline.rs +++ b/crates/app/src/ui/timeline.rs @@ -40,11 +40,6 @@ impl Player { for &lane in &lanes { rows.push(self.lane_row(lane, filled, cx)); } - // Built from the same playhead pixel the lanes are, and before the - // export takes `filled` over below: the strip is a picture of the - // timeline, not of an export's progress. - let strip = self.subtitle_strip(filled, cx); - let strip_h = subtitle_strip_h(strip.is_some()); let (hint, filled) = if let Some(export) = self.exporting() { let progress = export.progress(); let elapsed = self @@ -114,8 +109,8 @@ impl Player { // number a scroll is measured against, and the one the affordance below // counts with. The line it costs is taken off the box before the count, // or the row that says "1 more" would be the row hiding it. - let region_h = (timeline_h(lanes.len()) + strip_h).min(viewport_h * TIMELINE_SHARE); - let lanes_box = (region_h - TIMELINE_FIXED_H - strip_h).max(LANE_H); + let region_h = timeline_h(lanes.len()).min(viewport_h * TIMELINE_SHARE); + let lanes_box = (region_h - TIMELINE_FIXED_H).max(LANE_H); let overflows = lanes.len() > lanes_shown(lanes_box); let lanes_box = match overflows { true => (lanes_box - LABEL_H - 8.).max(LANE_H), @@ -291,11 +286,6 @@ impl Player { }), ) }) - // Under the tracks and outside their scrolling column: a subtitle is - // not a track -- nothing can be dropped on it and nothing dragged - // along it -- and a strip that scrolled away with the sixth lane - // would be a strip nobody could see while editing. - .children(strip) } /// The subtitle tracks this timeline holds, under the media list: one row @@ -373,11 +363,15 @@ impl Player { let tip: SharedString = match &row.refused { Some(why) => format!("{} — {why}", path.display()), None => format!( - "{} — click to show this track over the picture", + "{} — drag it onto a subtitle track to place it, click to show it \ + over the picture", path.display() ), } .into(); + // What the pointer carries onto a lane: the row's own + // name, the ghost a library row makes. + let carried: SharedString = title.clone().into(); // Named, because a × is the same glyph on every row and // the tooltip is what says which track it takes off. let remove_tip: SharedString = @@ -403,6 +397,15 @@ impl Player { .when(usable, |d| { d.cursor_pointer() .hover(|s| s.bg(rgb(BG_HOVER()))) + // Dragged, the whole track goes down on the + // subtitle lane it is let go over -- the + // gesture a media row already answers to, + // on the list beside it. A track that could + // not be read carries nothing: there is + // nothing of it to place. + .on_drag(SubPick(track), move |_, _, _, cx| { + cx.new(|_| Tip(carried.clone())) + }) .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { this.sub_track = track; // Picking a track is asking to see it: a @@ -579,136 +582,6 @@ impl Player { /// is by its tint, and the tooltip is where every box says what clicking it /// does. Never focusable, so the root keeps focus and the play binding still /// works after a click (ledger:182). - /// The subtitle strip: where the picked track's cues are along the very same - /// bed the lanes are drawn on, through the very same [`Scale`], so a cue - /// lines up with the take it belongs to at every zoom. - /// - /// Display only -- no drag, no trim, no drop. What it is *for* is the - /// question "is there a subtitle here", which a timeline could not answer at - /// all before: the cues are the project's and are edited in the file they - /// came from. - /// - /// `None` with no track picked, so a timeline without subtitles is the panel - /// it has always been. - pub(crate) fn subtitle_strip( - &self, - filled: f32, - cx: &mut Context, - ) -> Option> { - let track = self.subtitle_track()?; - let scale = self.scale; - // The pick with its film on it, not the raw tag: two films' "eng" - // tracks read alike otherwise, and a header saying "und" names a - // language nobody speaks. - let label = sub_pick_name(self.session.as_ref()?.subtitles(), self.sub_track)?; - // The colour the file's own rows and clips wear, so the strip says - // whose subtitles these are before the tooltip is asked. `None` for a - // standalone `.srt` -- nobody's stream, and the first film's colour - // would be a lie about where it came from. - let tint = file_tint(self.sources(), &track.path).unwrap_or(BG_RAISED()); - // The whole of what the row says in words, since a 40 px column can hold - // three characters of it: which track of which file, how many cues, the - // file itself in full -- one stem is two films when they are two cuts of - // it -- and, for a track that could not be read, the engine's own reason, - // where the library row's grey already says the same thing. - let tip: SharedString = match track.refused.is_some() { - true => format!( - "Subtitles: {label} — {} — {}", - subtitle_detail(track), - track.path.display() - ), - false => format!( - "Subtitles: {label} — {}, {} hides them — {}", - subtitle_detail(track), - self.keymap.display(ActionId::ToggleSubtitles), - track.path.display() - ), - } - .into(); - // Where the cues are on *this* timeline and not in the file they came - // from ([`PlaybackSession::timeline_cues`]) -- the same map the plate - // over the picture and the export both go through, which is what keeps - // a mark under the take it is spoken over after a cut. - let cues: Vec<(f32, f32)> = self - .session - .as_ref()? - .timeline_cues(self.sub_track) - .iter() - .map(|cue| cue_box(scale, cue)) - .collect(); - Some( - div() - .flex_none() - .h(px(SUB_LANE_H)) - .flex() - .gap(px(HEADER_GAP)) - .child( - // Identified for the tooltip's sake and for nothing else: - // the whole of what a 40 px column can say is three - // characters, and the rest of it hangs off the hover. - div() - .id("subtitle-lane") - .flex_none() - .w(px(HEADER_W)) - .h_full() - .flex() - .items_center() - // From the left rather than centred, unlike a lane's - // `V1`: a track label is a language or a file name, and - // a centred truncation eats both of its ends. - .px(px(2.)) - .rounded(px(3.)) - .bg(rgb(tint)) - .text_size(px(9.)) - .text_color(rgb(FG_SECONDARY())) - .truncate() - .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into()) - .child(label), - ) - .child( - div() - .relative() - .flex_1() - .min_w(px(0.)) - .h_full() - .rounded(px(3.)) - .bg(rgb(BG_TIMELINE())) - .overflow_hidden() - // The same bed under the same [`Scale`] answers the same - // wheel ([`Player::timeline_wheel`]): ctrl zooms about - // the pointer, bare scrolls the view along. A hand that - // wants a cue closer aims at the cue, and a timeline - // surface that ignores the wheel is a dead one. - .on_scroll_wheel(cx.listener(|this, event: &ScrollWheelEvent, _, cx| { - cx.stop_propagation(); - this.timeline_wheel(event, cx); - })) - .children(cues.into_iter().map(|(left, width)| { - div() - .absolute() - .top_0() - .h_full() - .left(px(left)) - .w(px(width)) - .rounded(px(2.)) - .bg(rgb(BG_SELECTED())) - })) - // The playhead again, last and in the lanes' own colour: - // the strip is only worth anything beside them if it - // reads as the same moment. - .child( - div() - .absolute() - .top_0() - .h_full() - .left(px(filled)) - .w(px(2.)) - .bg(rgb(ACCENT_PLAYHEAD())), - ), - ), - ) - } - pub(crate) fn lane_row( &self, lane: Lane, @@ -784,6 +657,39 @@ impl Player { .map_or(&[][..], PlaybackSession::sources); let (sel, sel_link) = (self.selected, self.selected_link()); let audio = lane.kind == LaneKind::Audio; + // A subtitle lane holds no `Clip` and every other lane holds no + // `SubClip`, so the two lists below are never both full and the bed + // draws whichever it was given -- one row, and no second kind of row to + // keep in step with this one. + let sub = lane.kind == LaneKind::Subtitle; + let shown = self.sub_lane_on(lane); + let subs: Vec = match (sub, &self.session) { + (true, Some(session)) => session.sub_lane(lane).to_vec(), + _ => Vec::new(), + }; + // Where this lane's words actually are on this timeline + // ([`PlaybackSession::sub_lane_cues`], the same map an export and the + // plate over the picture go through): the marks inside the placements' + // boxes, so a caption's box says where in it anybody speaks. + let cues: Vec<(f32, f32)> = match (sub, &self.session) { + (true, Some(session)) => session + .sub_lane_cues(lane) + .iter() + .map(|cue| cue_box(scale, cue)) + .collect(), + _ => Vec::new(), + }; + let eye_tip: SharedString = match shown { + true => format!("{name} shows its captions — click to hide this track"), + false => format!("{name} is hidden — click to show its captions again"), + } + .into(); + // What a caption's box says clicking it does; the media boxes' tooltip + // names edits a placement has none of (no group, no speed, no ripple). + let sub_tip: SharedString = + "Drag it along the lane or onto another subtitle track, an end to trim it, × takes it \ + off" + .into(); // What this track plays at, on the header it belongs to: shown only // when it is not unity, because a column 40 px wide has room for a // number or for a name, and the name is what a header is for. The @@ -881,6 +787,37 @@ impl Player { false => format!("{name} {gain_db:+.0}"), }) .into_any_element(), + // A subtitle track's own one setting, in the same + // place and for the same reason: whether this lane's + // words are drawn over the picture. The eye every + // player puts on a track, `HIT_MIN` tall like the mix + // button it sits where. + false if sub => div() + .id(("eye-lane", lane.ord)) + .flex_1() + .w_full() + .flex() + .flex_col() + .items_center() + .justify_center() + .rounded(px(3.)) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER()))) + .when(!shown, |d| d.text_color(rgb(FG_DISABLED()))) + .tooltip(move |_, cx| cx.new(|_| Tip(eye_tip.clone())).into()) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.toggle_sub_lane(lane, cx) + })) + .child(name.clone()) + .child( + div() + .text_size(px(9.)) + .child(match shown { + true => "◉", + false => "○", + }), + ) + .into_any_element(), false => div() .flex_1() .flex() @@ -993,6 +930,39 @@ impl Player { this.preview_ghost(&drag, lane, event.event.position.x, cx); }, )) + // A palette row let go over a lane places that whole + // subtitle track where the hand left it -- and over a lane + // that is not a subtitle one, `place_sub` refuses it in + // words, which is why the listener is on every bed rather + // than on the subtitle beds alone. + .on_drop(cx.listener(move |this, drag: &SubPick, window, cx| { + this.place_sub(drag.0, lane, window.mouse_position().x, cx); + })) + .drag_over::(|s, _, _, _| s.bg(rgb(BG_HOVER_DIM()))) + .on_drag_move(cx.listener( + move |this, event: &DragMoveEvent, _, cx| { + if !event.bounds.contains(&event.event.position) { + return; + } + let track = event.drag(cx).0; + this.preview_ghost_pick(track, lane, event.event.position.x, cx); + }, + )) + // ...and a caption already on a lane moves along it, or onto + // another subtitle track, exactly as a clip does. + .on_drop(cx.listener(move |this, drag: &SubDrag, window, cx| { + this.move_sub(drag, lane, window.mouse_position().x, cx); + })) + .drag_over::(|s, _, _, _| s.bg(rgb(BG_HOVER_DIM()))) + .on_drag_move(cx.listener( + move |this, event: &DragMoveEvent, _, cx| { + if !event.bounds.contains(&event.event.position) { + return; + } + let drag = *event.drag(cx); + this.preview_ghost_sub(&drag, lane, event.event.position.x, cx); + }, + )) .children(clips.iter().enumerate().map(|(i, clip)| { // The clip as the lane holds it, for the drag payload: // what a drop looks itself up by has to be the placed @@ -1290,6 +1260,180 @@ impl Player { ) }) })) + // The same bed's other kind of box: a stretch of a palette + // track placed on this lane, dragged along it, dragged onto + // another subtitle lane, trimmed at either end and lifted + // off by its own ×. Empty on every lane that is not a + // subtitle one, which is why there is one row and not two. + .children(subs.iter().enumerate().map(|(i, placed)| { + // What the drag payload names, and what an edge drag is + // *showing* -- the box moves under the pointer and the + // engine hears once, at the release. + let (placed, shown_sub) = (*placed, self.trimmed_sub(lane, i, *placed)); + let (start, len) = ( + f64::from(shown_sub.start) / self.fps, + f64::from(shown_sub.frames) / self.fps, + ); + let span = scale.width_px(len); + let width = clip_width(span); + let left = scale.px_at(start); + let (vis_x, vis_w) = visible_slice(left, width, bed); + // Which track's words these are, film and all: two + // "eng" tracks off two files read alike otherwise. + let label = self + .session + .as_ref() + .and_then(|session| sub_pick_name(session.subtitles(), placed.track)); + let ghost: SharedString = + label.clone().unwrap_or_else(|| lane.label()).into(); + let tip = sub_tip.clone(); + let head = shown_sub.start; + div() + .id((row_id.clone(), i)) + .absolute() + .top_0() + .h_full() + .left(px(left)) + .w(px(width)) + .overflow_hidden() + .rounded(px(3.)) + .border_1() + .border_color(rgb(FG_SECONDARY())) + // The captions' own colour, dimmed on a lane whose + // eye is shut: what is not being drawn over the + // picture is still on the lane, and says so. + .bg(rgb(CLIP_TEXT())) + .when(!shown, |d| d.opacity(0.55)) + .cursor_pointer() + .hover(|s| s.border_color(rgb(ACCENT_PRIMARY()))) + .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into()) + .on_drag( + SubDrag { + lane, + idx: i, + sub: placed, + }, + move |_, _, _, cx| cx.new(|_| Tip(ghost.clone())), + ) + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, event: &MouseDownEvent, _, cx| { + // Where in the box the hand took hold, so + // the caption moves with the pointer rather + // than jumping its head under it. + this.grab = + this.frame_under(event.position.x).saturating_sub(head); + cx.notify(); + }), + ) + // The two strips a drag lengthens it by, on the same + // rule a clip's are drawn by ([`trims`]). + .children( + [Edge::Start, Edge::End] + .into_iter() + .filter(|_| trims(span)) + .map(|edge| { + let mut zone = div() + .absolute() + .top_0() + .h_full() + .w(px(EDGE_W)) + .occlude() + .cursor(CursorStyle::ResizeLeftRight) + .hover(|s| s.bg(rgb(ACCENT_PRIMARY()))) + .on_mouse_down( + MouseButton::Left, + cx.listener( + move |this, _: &MouseDownEvent, _, cx| { + this.start_trim(lane, i, edge, cx); + }, + ), + ) + .on_scroll_wheel(cx.listener( + |this, event: &ScrollWheelEvent, _, cx| { + cx.stop_propagation(); + this.timeline_wheel(event, cx); + }, + )); + zone = match edge { + Edge::Start => zone.left_0(), + Edge::End => zone.right_0(), + }; + zone + }), + ) + .when_some(label.filter(|_| show_label(vis_w)), |d, label| { + d.child( + div() + .absolute() + .top_0() + .left(px(vis_x)) + .w(px(vis_w)) + .h(px(LABEL_H)) + .px(px(4.)) + .truncate() + .text_size(px(10.)) + .child(label), + ) + }) + // The way back off the lane, on the box itself: a + // caption is not in the clip selection's index + // space, so no stroke reaches it -- and a lane + // holding one cannot be removed either + // ([`Project::remove_lane`] refuses it), which + // would leave a placement nobody could undo but by + // undoing. Only where the box is wide enough to + // hold a target beside its name; narrower than that + // it is lifted after zooming in, exactly as it is + // trimmed after zooming in. + // + // Clear of the tail's own trim strip by that + // strip's width: both occlude and this one is drawn + // last, so hard against the right edge it swallowed + // every press meant for the edge and the tail could + // not be dragged at all (caught driving it). + .when(vis_w >= 2. * HIT_MIN + EDGE_W, |d| { + d.child( + div() + .id(("sub-lift", i)) + .absolute() + .top_0() + .left(px(vis_x + vis_w - HIT_MIN - EDGE_W)) + .w(px(HIT_MIN)) + .h(px(HIT_MIN)) + .flex() + .items_center() + .justify_center() + .occlude() + .rounded(px(3.)) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER()))) + .on_click(cx.listener( + move |this, _: &ClickEvent, _, cx| { + cx.stop_propagation(); + this.lift_sub(lane, i, cx); + }, + )) + .child("×"), + ) + }) + })) + // ...and where the words actually are inside those boxes: + // the cues this lane shows on *this* timeline, in a band + // along the bottom of the row. A placement is a window of a + // track, so a box is not full of speech -- and a lane whose + // marks are all in its first half is a caption dragged too + // far, which is exactly what this band shows. + .children(cues.into_iter().map(|(left, width)| { + div() + .absolute() + .bottom_0() + .h(px(4.)) + .left(px(left)) + .w(px(width)) + .rounded(px(2.)) + .bg(rgb(BG_SELECTED())) + })) // What the silence card found, over the clips it found them // in and over the waveform band that shows why: on the lane // the scan ran on and no other, because that is the only