diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 122d235..fe14af0 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -1,4 +1,8 @@ mod keymap; +mod ui; + +use ui::theme::*; +use ui::widgets::*; use keymap::{ActionId, Keymap}; @@ -28,43 +32,10 @@ use gpui::{ canvas, div, img, point, prelude::*, px, relative, rgb, rgba, size, }; -/// Editor chrome: three grays and one accent, all darker than the picture so the -/// frame is what the eye lands on. `LETTERBOX` stays the video's own bed. -const LETTERBOX: u32 = 0x101010; -const CHROME: u32 = 0x242424; -const SURFACE: u32 = 0x333333; -const INK: u32 = 0xc8c8c8; -const ACCENT: u32 = 0x4a9eff; -/// The accent at surface brightness: a selected clip is tinted, not lit up. -const SELECTED: u32 = 0x2a4a6b; -/// One per source, so a clip that came from an imported file reads as coming -/// from somewhere else. Same brightness as `SURFACE` and only the hue moves: -/// the lane stays in the dark family the rest of the chrome lives in -/// (ledger:187). The first entry is a colour like the rest rather than `SURFACE` -/// itself -- a first import whose swatch is the panel's own background is a -/// swatch nobody can see, and a file with one colour is what the whole -/// association is built on. -const SOURCE_TINTS: [u32; 4] = [0x29333b, 0x3b3329, 0x293b33, 0x33293b]; -/// The mirror of `SELECTED`: a drop the lane will not take, tinting the shadow -/// a drag draws ([`Ghost`]) so a refusal is seen before the release rather than -/// read afterwards. Same brightness as the rest of the chrome -- a warning, not -/// an alarm. -const REFUSE: u32 = 0x6b2a2a; -/// How solid that shadow is (`0xRRGGBBAA`): enough to read as a box, little -/// enough that the clip it is drawn over is still legible through it. -const GHOST_ALPHA: u32 = 0x66; /// ...and the narrowest it is drawn: a library row whose length the engine has /// not measured yet has a landing place but no width, and a head marker says /// where it goes where a zero-width box would say nothing. const GHOST_MIN: f32 = 2.; -/// One step lighter than whatever it sits on: the pointer's answer that this is -/// clickable. Two of them, because buttons stand on `SURFACE` and the scrub -/// strip stands on `CHROME`. -const HOVER: u32 = 0x3f3f3f; -const HOVER_DIM: u32 = 0x2c2c2c; -/// Secondary text -- shortcuts, dismissal hints. Dimmer than `INK` and still -/// past 4.5:1 on both `SURFACE` and `CHROME`. -const INK_DIM: u32 = 0xa0a0a0; /// Fixed so the video region takes every pixel the window gains and the controls /// never clip at 640x360. @@ -176,12 +147,6 @@ const MENU_W: f32 = 260.; const MENU_ROW_H: f32 = HIT_MIN; const MENU_PAD: f32 = 6.; -/// The subtitle over the picture: white on a black plate, because a cue is read -/// against whatever the film happens to be showing under it and the chrome's own -/// greys are not a contrast the picture agrees to. 21:1 against the plate, which -/// is the only pair here that is not a chrome-on-chrome one. -const SUB_INK: u32 = 0xffffff; -const SUB_SHADE: u32 = 0x000000cc; /// A cue's text, and the line it sits on. Fixed rather than a share of the /// picture: the video region is 108 px tall at the 640x360 floor and a /// proportional size there would be unreadable at exactly the size where it has @@ -990,9 +955,6 @@ const EQ_TICKS: [(f32, &str); 5] = [ /// named at the corners instead. const EQ_DB_GRID: [f32; 2] = [6., -6.]; -/// The grid's ink: above the card's background and below everything drawn on -/// it, so the lines are a ruling rather than a thing to look at. -const EQ_GRID: u32 = 0x3a3a3a; /// How many played samples one spectrum frame is transformed from. A power of /// two ([`fft`] is radix-2) and the whole of the engine's tap: 1024 at 48 kHz @@ -1006,18 +968,8 @@ const EQ_FFT: usize = 1024; /// the numbers on the axis are the curve's dB, never the analyser's. const EQ_SPECTRUM_DB: (f32, f32) = (-96., -12.); -/// The analyser's fill, behind the curve: a dim blue-grey with enough alpha to -/// read as a haze the accent line sits on top of. -const EQ_SPECTRUM_INK: u32 = 0x7f95ad66; -/// The area under the response curve, same accent as the line at a tenth of -/// its weight: it is what makes a boost read as a hill rather than as a wire. -const EQ_FILL_INK: u32 = 0x4a9eff26; -/// One band's own response, drawn under the sum: a dim thread per band, so a -/// boost pushed against a cut can be *seen* as two bands rather than as the -/// flat line their total makes. -const EQ_BELL_INK: u32 = 0x4a9eff66; /// The colour card's four controls, in the order it lists them: what each is /// called and the range it moves in. The order is `ColorParams`' own, which is @@ -1057,9 +1009,6 @@ const HIST_SAMPLES: usize = 8_192; /// rows stand under it and the card still has to fit a 360 px window. const HIST_H: f32 = 96.; -/// What each channel's line is drawn in, in `[r, g, b]` order -- the channel it -/// counts, lightened enough to read on the dark box. -const HIST_INK: [u32; 3] = [0xE0_5A_5A, 0x5A_D0_7A, 0x5A_9A_E0]; /// Where the transport is. The one answer the button's glyph, its label, its /// enablement, the play key and the repaint loop all read -- there is no play @@ -2892,7 +2841,7 @@ impl Player { let refusal = match (self.selected, &self.session) { (_, None) => Some("NO TIMELINE — open a file first".to_string()), (None, _) => Some(format!( - "NOTHING SELECTED — click an audio clip or press {}, then ask again", + "NOTHING BG_SELECTED — click an audio clip or press {}, then ask again", self.keymap.display(ActionId::Select) )), (Some((lane, _)), _) if lane.kind != LaneKind::Audio => Some( @@ -3620,7 +3569,7 @@ impl Player { .map_or(0, |session| session.file_frames(path)), // A path with no source entry has no colour of its own, and the // shadow wears the lane's own instead of borrowing another file's. - tint: file_tint(self.sources(), path).unwrap_or(SURFACE), + tint: file_tint(self.sources(), path).unwrap_or(BG_RAISED), refused: lane_refuses(path, to).is_some(), }; self.set_ghost(Some(ghost), cx); @@ -5765,8 +5714,8 @@ impl Render for Player { .size_full() .flex() .flex_col() - .bg(rgb(LETTERBOX)) - .text_color(rgb(INK)) + .bg(rgb(BG_CANVAS)) + .text_color(rgb(FG_PRIMARY)) .text_size(px(13.)) .child( div() @@ -5775,7 +5724,7 @@ impl Render for Player { .flex() .items_center() .px(px(12.)) - .bg(rgb(CHROME)) + .bg(rgb(BG_PANEL)) .child(self.name.clone()), ) // The library beside the picture rather than under it: a media pool @@ -5861,4771 +5810,81 @@ impl Render for Player { } } -impl Player { - /// The media library: a row per source the timeline knows, in the order - /// they arrived, each wearing the tint its clips wear in the lanes -- the - /// swatch *is* what says which boxes down there came from this file. A - /// click picks a row, the button under the list drops that source in at the - /// playhead, and a row dragged onto either lane does the same thing through - /// the same call. - /// - /// Import lives here, because this is the list it adds to. Plain divs like - /// the rest of this window: nothing in it takes focus, so the root keeps - /// the keyboard and the play key still works after a row is clicked - /// (ledger:182). - fn library(&self, width: f32, viewport_h: f32, cx: &mut Context) -> impl IntoElement { - let exporting = self.exporting().is_some(); - let sources = self - .session - .as_ref() - .map_or(&[][..], PlaybackSession::sources); - // Every source matches the first in size and rate or it was refused at - // the door (the import policy, ledger:436), so the session's own meta - // describes every row and nothing has to be probed to say so. - let meta = self.session.as_ref().map(PlaybackSession::meta); - // Its own length, not one derived from what is on the lanes: a row - // imported and never placed is a row with a length, and it is the - // length a drag would put down. - let rows: Vec<_> = library_rows( - sources, - &self.streams, - &self.decoders, - self.timeline_audio(), - |path| { - self.session - .as_ref() - .map_or(0, |session| session.file_frames(path)) - }, - ) - .into_iter() - .enumerate() - .map(|(i, row)| { - let picked = self - .selected_asset - .as_ref() - .is_some_and(|p| *p == (row.path.clone(), row.stream)); - let name: SharedString = row.name.clone().into(); - let says: String = match (&row.unusable, meta) { - // A greyed row says why in full, where its length would be: - // the list is the one place the file's own tracks are named. - (Some(why), _) => format!("{} — {why}", row.path.display()), - // A file with no picture has no size and no frame rate to - // report, and only one lane it can go on: saying so is the - // difference between a hint and a lie. - (None, _) if engine::is_audio(&row.path) => format!( - "{} — audio only · drag onto the audio lane, or Add at playhead", - row.path.display() - ), - // A still is the mirror: its own size (the timeline's meta - // describes video, and a picture placed on that canvas is not - // the same shape), no frame rate, and one kind of lane. - (None, _) if engine::is_image(&row.path) => format!( - "{} — still image{} · drag onto a video lane, or Add at playhead", - row.path.display(), - match self.sizes.get(&row.path).copied().flatten() { - Some((w, h)) => format!(" · {w}x{h}"), - None => String::new(), - } - ), - // The file's *own* frame rate, not the timeline's: a clip shot - // at another rate plays at the speed it was shot at, and the - // row that says where it came from has to say which rate that - // was. - (None, Some(meta)) => format!( - "{} — {}x{} @ {:.2} fps · drag it where you want it, or Add at playhead", - row.path.display(), - meta.width, - meta.height, - self.session - .as_ref() - .map_or(meta.frame_rate, |session| session.file_fps(&row.path)) - ), - (None, None) => row.path.display().to_string(), - }; - // The menu is the third way into a row, after the click and the - // drag, and a right-click nothing advertises is one nobody finds. - let tip: SharedString = format!("{says} · right-click for more").into(); - let ghost = name.clone(); - // What the second line says: the stream, then either its length or - // the reason it cannot be used. - let under = match &row.unusable { - Some(why) => join_detail(&row.detail, why), - // A still has no length to report -- the ten minutes it is - // *held* to is a wall, not a duration -- so the line says what - // it is and how big it is instead. - None if engine::is_image(&row.path) => join_detail( - &row.detail, - &match self.sizes.get(&row.path).copied().flatten() { - Some((w, h)) => format!("still image · {w}x{h}"), - None => "still image".to_string(), - }, - ), - None => join_detail( - &row.detail, - &timecode(f64::from(row.frames) / self.fps, self.fps), - ), - }; - let usable = row.unusable.is_none(); - let (path, stream) = (row.path.clone(), row.stream); - let dragged = (path.clone(), stream); - let menu_path = path.clone(); - div() - .id(("asset", i)) - .flex_none() - .h(px(ROW_H)) - .flex() - .items_center() - .gap(px(6.)) - .pr(px(6.)) - .rounded(px(3.)) - // A row that cannot be placed takes no click and no drag, and - // reads as unavailable rather than merely unlucky. - .when(!usable, |d| d.text_color(rgb(INK_DIM)).opacity(0.55)) - .when(usable, |d| { - d.cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.selected_asset = Some((path.clone(), stream)); - cx.notify(); - })) - // The drag carries the row's file and stream and the - // row's name: one for the drop to insert, one for the - // pointer to carry, so what is being dragged is legible - // on the way down. - .on_drag(AssetDrag(dragged.0, dragged.1), move |_, _, _, cx| { - cx.new(|_| Tip(ghost.clone())) - }) - }) - // The right button hangs the row's own menu at the pointer. - // Every row takes it, greyed ones included: a file that cannot - // join this timeline can still be revealed, described and taken - // out of the list, and Add is the one item that then refuses -- - // in the engine's words, where the row's grey already says why. - .on_mouse_down( - MouseButton::Right, - cx.listener(move |this, event: &MouseDownEvent, _, cx| { - if this.modal() { - return; - } - // Picked as a left-click would pick it, so the row the - // menu is about is the row that reads as chosen -- but - // only a row that *can* be picked, which is what keeps - // the Add button under the list honest. - if usable { - this.selected_asset = Some((menu_path.clone(), stream)); - } - this.library_menu = Some(LibraryMenu { - path: menu_path.clone(), - stream, - at: event.position, - details: false, - }); - cx.notify(); - }), - ) - .when(picked, |d| d.bg(rgb(SELECTED)).border_1()) - .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into()) - // Full height and hard against the edge: the tint reads as - // the lane's colour continuing into the list, not as a chip - // that happens to be near it. - .child( - div() - .flex_none() - .w(px(SWATCH_W)) - .h_full() - .rounded(px(2.)) - .bg(rgb(source_tint(row.tint))), - ) - .child( - div() - .flex_1() - .min_w(px(0.)) - .flex() - .flex_col() - // Two lines rather than two columns: at the width - // this panel yields to, a name and a timecode side - // by side leave room for neither. - // Cut out of the middle, not the end: two episodes off - // one release are the same words up to the number, and - // the number is at the end. - .child( - div() - .truncate() - .text_size(px(11.)) - .child(clip_middle(&name, row_text_w(width))), - ) - .child( - div() - .truncate() - .text_size(px(10.)) - .text_color(rgb(INK_DIM)) - .child(under), - ), - ) - }) - .collect(); - div() - .flex_none() - .w(px(width)) - .h_full() - .flex() - .flex_col() - .gap(px(6.)) - .p(px(8.)) - .bg(rgb(CHROME)) - .child( - div() - .flex_none() - .flex() - .items_center() - .gap(px(6.)) - .child( - div() - .flex_1() - .min_w(px(0.)) - .truncate() - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child("Media"), - ) - .child(control( - "import", - None, - "Import", - "adds a file to this list — or drop one on the window".to_string(), - !exporting, - cx.listener(|this, _: &ClickEvent, _, cx| this.pick_and_import(cx)), - )), - ) - .child( - div() - .id("library-rows") - .flex_1() - .min_h(px(0.)) - .flex() - .flex_col() - .gap(px(2.)) - .overflow_y_scroll() - // Never a blank column: with nothing imported the list is - // where the way in is said. - .when(rows.is_empty(), |d| { - d.child( - div() - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child("No media yet — Import, or drop a file on the window"), - ) - }) - .children(rows), - ) - // Under the media it belongs to: a subtitle track is not a source -- - // it goes on no lane and is dragged nowhere -- but it is a thing the - // timeline holds, and this is the list of those. - .children(self.subtitle_section(width, viewport_h, cx)) - .child(control( - "add-asset", - None, - "Add at playhead", - match self.selected_asset { - Some(_) => "inserts the picked file at the playhead".to_string(), - None => "click a file above first — or drag one where you want it".to_string(), - }, - can_add( - self.selected_asset.as_ref(), - self.session.is_some(), - exporting, - ), - cx.listener(|this, _: &ClickEvent, _, cx| { - if let Some((path, stream)) = this.selected_asset.clone() { - // No lane: the button means "wherever this belongs", - // which for a file with no picture is the audio lane. - this.insert_source(&path, stream, None, None, cx); - } - }), - )) - } - /// The subtitle tracks this timeline holds, under the media list: one row - /// each, the picked one marked, and a click makes another one the picked one - /// -- which is the whole of choosing between the two tracks of a film. A row - /// per track and no cycle: three of them is an ordinary number for a remux, - /// and a key that steps through three is a key nobody can aim. - /// - /// A track that could not be read is *here*, greyed and saying why, exactly - /// as a media row the timeline cannot take is: PGS subtitles are pictures, - /// and a film carrying four of them says so instead of listing nothing. - /// - /// Every row names the file it came out of itself, in words and in the tint - /// that file's clips wear on the lanes -- but only where there is more than - /// one file to tell apart, the way [`row_name`] numbers audio streams only - /// where a file gave several. Where the window is tall enough for it - /// ([`sub_headers_fit`]) each file's block is headed by its name as well: a - /// label and nothing more, no click and nothing to fold, so the rows under - /// it are the only things anybody has to aim at. At the 640x360 floor the - /// headers are gone and the rows still say whose they are. - /// - /// `None` when there are none -- an empty heading is a section about - /// nothing. - fn subtitle_section( - &self, - width: f32, - viewport_h: f32, - cx: &mut Context, - ) -> Option { - let tracks = self.session.as_ref()?.subtitles(); - if tracks.is_empty() { - return None; - } - let groups = subtitle_rows(tracks); - // One file's tracks need no prefix saying which file: it is the only - // one, and every row would carry the same word. - let several_files = groups.len() > 1; - let headed = several_files && sub_headers_fit(viewport_h); - let text_w = row_text_w(width); - let rows: Vec<_> = groups - .into_iter() - .map(|SubGroup { name, path, rows }| { - // The file's own colour, the one its media rows and its clips - // wear -- and none at all for a standalone `.srt`, which came - // off no file on this timeline. - let tint = file_tint(self.sources(), &path); - let numbered = rows.len() > 1; - // The name twice over: all of it the header can hold, and the - // share of a row a prefix may take in front of the label. - let head = clip_middle(&name, text_w); - let prefix = clip_middle(&name, text_w * SUB_STEM_SHARE); - let rows: Vec<_> = rows - .into_iter() - .map(|row| { - let track = row.track; - let picked = track == self.sub_track; - let usable = row.refused.is_none(); - // Two tracks off one remux that both say "eng" are told - // apart by their number and by nothing else -- the same - // count [`sub_pick_name`] echoes. - let title = match numbered { - true => format!("{} {}", row.label, row.number), - false => row.label, - }; - // A standalone `.srt` is named after its own file, so - // the file in front of it says the same word twice - // ("Legend.of.… · Legend.of.…"). [`sub_pick_name`]'s - // rule, on the row it is about. - let owned = several_files && !title.starts_with(name.as_str()); - // The whole path, never clipped: the row says which - // file, and the tooltip says which one on disk. - let tip: SharedString = match &row.refused { - Some(why) => format!("{} — {why}", path.display()), - None => format!( - "{} — click to show this track over the picture", - path.display() - ), - } - .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 = - format!("Remove {title} — importing the file again brings it back") - .into(); - div() - // The *flat* index into the session's add-order - // list, which is what a pick is and what a save - // writes: the grouping moved the row on screen and - // never the track it stands for. - .id(("subtitle-track", track)) - .flex_none() - .h(px(ROW_H)) - .flex() - .items_center() - .gap(px(6.)) - .pr(px(6.)) - .rounded(px(3.)) - .when(!usable, |d| d.text_color(rgb(INK_DIM)).opacity(0.55)) - .when(usable, |d| { - d.cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.sub_track = track; - // Picking a track is asking to see it: a - // click that changed nothing on screen - // because the toggle was off would read - // as a dead row. - this.subs_on = true; - cx.notify(); - })) - }) - .when(picked, |d| d.bg(rgb(SELECTED))) - .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into()) - // The media rows' bar, same width and hard against - // the same edge: one association across the panel - // and the lanes. Kept as room rather than dropped - // where there is no tint, so a standalone `.srt` - // still lines its words up with the rest. - .child( - div() - .flex_none() - .w(px(SWATCH_W)) - .h_full() - .rounded(px(2.)) - .when_some(tint, |d, tint| d.bg(rgb(tint))), - ) - .child( - div() - .flex_1() - .min_w(px(0.)) - .flex() - .flex_col() - .child( - div() - .flex() - .text_size(px(11.)) - // In front, because the column - // truncates from the right: an - // ownership word at the end is a - // word the floor never shows. - .when(owned, |d| { - d.child( - div() - .flex_none() - // Said twice where a - // header says it above: - // still there, out of - // the way. - .when(headed, |d| { - d.text_color(rgb(INK_DIM)) - }) - .child(format!("{prefix} · ")), - ) - }) - .child( - div() - .flex_1() - .min_w(px(0.)) - .truncate() - .child(title), - ), - ) - .child( - div() - .truncate() - .text_size(px(10.)) - .text_color(rgb(INK_DIM)) - .child(row.detail), - ), - ) - // The way back off the timeline, on every row and on - // the last one too -- a list of subtitles is allowed - // to be empty, unlike a lane. A `HIT_MIN` target and - // never hidden, the lane header's ×, and it stops - // the click there: the row under it picks a track, - // and picking the track that has just gone would - // leave the pick naming nothing. - .child( - div() - .id(("subtitle-remove", track)) - .flex_none() - .w(px(HIT_MIN)) - .h_full() - .flex() - .items_center() - .justify_center() - .rounded(px(3.)) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .tooltip(move |_, cx| cx.new(|_| Tip(remove_tip.clone())).into()) - .on_click(cx.listener( - move |this, _: &ClickEvent, _, cx| { - cx.stop_propagation(); - this.remove_subtitle_track(track, cx); - }, - )) - .child("×"), - ) - }) - .collect(); - div() - .flex_none() - .flex() - .flex_col() - .gap(px(2.)) - // The header: which film these came out of, in words and not - // in colour alone. No id, no click, nothing to fold -- a - // label, which is why it is allowed under `HIT_MIN`. - .when(headed, |d| { - d.child( - div() - .flex_none() - .h(px(SUB_HEAD_H)) - .flex() - .items_center() - .gap(px(6.)) - .text_size(px(10.)) - .text_color(rgb(INK_DIM)) - .when_some(tint, |d, tint| { - d.child( - div() - .flex_none() - .w(px(SWATCH_W)) - .h_full() - .rounded(px(2.)) - .bg(rgb(tint)), - ) - }) - .child(div().flex_1().min_w(px(0.)).truncate().child(head)), - ) - }) - .children(rows) - }) - .collect(); - Some( - div() - .flex_none() - .flex() - .flex_col() - .gap(px(2.)) - .child( - div() - .truncate() - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child(match (self.subs_on, sub_pick_name(tracks, self.sub_track)) { - // Which of them is on screen, named by its film: - // the heading over a list of five is where the one - // being shown is worth saying out loud. - (true, Some(pick)) => format!("Subtitles — {pick}"), - (true, None) => "Subtitles".to_string(), - // The toggle's state where the tracks are listed: a - // list of subtitles nothing on screen is showing has - // to say that it is showing none. - (false, _) => "Subtitles — hidden".to_string(), - }), - ) - .child( - div() - .id("subtitle-rows") - .flex() - .flex_col() - .gap(px(2.)) - .max_h(px(SUB_ROWS_H)) - .overflow_y_scroll() - .children(rows), - ), - ) - } +/// Rate limit for scrub seeks: a video worker reopen costs 72-87 ms on the +/// hardware path for the small files it was measured on (215 ms in software), so +/// one seek per mouse move would only queue workers that are cancelled before +/// they decode anything. +/// +/// It is a *floor*, not a bound: the reopen is a demux open +/// ([`engine::decode::open_worker`]), and on a 25 GB film that is 550-750 ms -- +/// five to seven times this gap, which therefore gates nothing there. Where the +/// cost had to be bounded rather than thinned -- the colour and speed drags -- +/// the gate is the frame the worker delivers ([`Player::flush_drag`]) and no +/// timer at all. The ruler keeps this one: a scrub has no value to hold back, +/// only a position that the next mouse move replaces anyway. +const SCRUB_GAP: Duration = Duration::from_millis(100); - /// The cues of the picked track that are on screen at `at`, over the picture - /// and nothing else: bottom-centred where every player puts them, white on a - /// plate so the film underneath cannot swallow them, and each cue its own - /// plate so two at one moment stack rather than run together. - /// - /// `None` -- no element at all -- while the toggle is off, with no track - /// picked, and between cues: the picture is what this window is for, and a - /// permanent empty band across it would be in the way of exactly that. - /// - /// The cues are the *timeline's* ([`PlaybackSession::timeline_cues`]) and - /// not the track's own: on a cut timeline an embedded track's cues ride the - /// pictures they belong to, and this is the same map the export writes the - /// file with -- so what is read here is what the file says. - /// - /// A cue off a PGS track is a *picture* and not a line - /// ([`engine::subtitle::CueImage`]), and is drawn as one: the disc's whole - /// canvas fitted over the picture region exactly as the picture itself is, - /// which puts every cue where the disc put it relative to its own frame. - /// - /// ponytail: exact only while the canvas and the encode are the same shape - /// -- a 16:9 canvas over a 2.39:1 encode fits to the region's height and - /// the film to its width, so a cue sits a little low on a scope film. The - /// upgrade path is the picture's own rect, which wants `VideoMeta`'s aspect - /// and the measured bounds rather than the shared `Contain`. - fn subtitle_overlay( - &mut self, - at: f64, - window: &mut Window, - ) -> Option> { - // One way out, and it lets the drawn picture go on the way: the toggle - // going off, the file closing and the gap between two cues are the same - // "nothing on screen", and an 8 MB atlas tile may not survive any of - // them (an early return above this leaked one per toggle-off). - let mapped = match self.session.as_ref().filter(|_| self.subs_on) { - Some(session) => session.timeline_cues(self.sub_track), - None => Vec::new(), - }; - let cues = cues_at(&mapped, at); - if cues.is_empty() { - self.drop_sub_image(window); - return None; +fn scrub_due(target: u32, last_target: u32, since: Duration) -> bool { + target != last_target && since >= SCRUB_GAP +} + +/// The gate a live drag sample goes through. With the worker still owing a +/// frame (`busy`), writing now would only cancel the open the picture is already +/// waiting for -- the sample is held in `stash` instead, and the frame that +/// lands writes it ([`Player::flush_drag`]). Returns what to write, if anything. +/// +/// The press (`first`) never waits: it is the undo step the whole gesture rolls +/// back to, so it has to be taken against the state the hand picked up. +fn stash_or_write(stash: &mut Option, value: T, first: bool, busy: bool) -> Option { + match busy && !first { + true => { + *stash = Some(value); + None } - // The first picture cue up, decoded once and kept: two bitmap cues at - // one moment is a thing PGS composes into one display set, so there is - // never a second picture to stack under the first. - let picture = cues - .iter() - .find_map(|cue| Some((cue.start_us, cue.image.as_ref()?))) - .and_then(|(start_us, image)| self.sub_picture(start_us, image, window)); - // A picture is fitted onto the whole region and a plate hangs off the - // bottom of it, and a track is one or the other -- so they are two - // shapes and not one with the parts switched off. - if let Some(image) = picture { - // A *flex* box with the canvas as its one growing item: a percentage - // size (`size_full`) inside an absolutely placed box has nothing to - // be a percentage of and lays the picture out to nothing, while a - // flex item is sized by the box itself. Fitted the way the picture - // above it is -- `Contain` over the same box -- so a canvas of the - // picture's own shape lands exactly on it. - return Some(div().absolute().inset_0().flex().child( - img(image).flex_1().h_full().object_fit(gpui::ObjectFit::Contain), - )); - } - Some( - div() - .absolute() - .left_0() - .right_0() - .bottom(px(SUB_BOTTOM)) - .flex() - .flex_col() - .items_center() - .gap(px(2.)) - // The plate takes no click: the picture behind it is still the - // drop target the whole window is. - .children(cues.into_iter().filter(|c| c.image.is_none()).map(|cue| { - div() - .max_w(relative(0.9)) - .px(px(6.)) - .rounded(px(3.)) - .bg(rgba(SUB_SHADE)) - .text_size(px(SUB_TEXT)) - .text_color(rgb(SUB_INK)) - .text_align(TextAlign::Center) - // A line of the cue is a line on screen: the break the - // parser kept is not whitespace to be re-flowed. What a - // *long* line does is wrap inside its own div, which is - // what the width cap above is for. - .children( - cue.text - .split('\n') - .map(|line| div().min_h(px(SUB_LINE_H)).child(line.to_string())), - ) - })), - ) + false => Some(value), } +} - /// The cue starting at `start_us` as a drawable picture, decoded on the - /// first repaint it is up for and kept until another cue takes its place - /// ([`Player::sub_image`]). `None` for a display set the decoder refuses, - /// which draws nothing rather than failing the frame. - /// - /// Its atlas tile is released as the video's is: every [`RenderImage`] gets - /// a fresh id and its own tile, so a film's worth of cues would grow the - /// sprite atlas by the whole film. - fn sub_picture( - &mut self, - start_us: i64, - image: &engine::subtitle::CueImage, - window: &mut Window, - ) -> Option> { - let key = (self.sub_track, start_us); - if let Some((up, ready)) = &self.sub_image - && *up == key - { - return Some(ready.clone()); - } - let mut rgba = image.rgba()?; - // gpui's atlas is BGRA with straight alpha; PGS decodes to RGBA with - // straight alpha. The same swap the video frames get. - for pixel in rgba.chunks_exact_mut(4) { - pixel.swap(0, 2); - } - let buf = image::RgbaImage::from_raw(image.width, image.height, rgba)?; - let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)])); - self.drop_sub_image(window); - self.sub_image = Some((key, next.clone())); - Some(next) - } - - /// Lets go of the drawn cue and its atlas tile. Called where the cue stops - /// being on screen, which is every gap between two of them: an 8 MB tile - /// per cue is not a thing to leave behind a film. - fn drop_sub_image(&mut self, window: &mut Window) { - if let Some((_, old)) = self.sub_image.take() { - let _ = window.drop_image(old); - } - } - - /// What is decoding the picture right now, for the transport line: the - /// backend is the running worker's own (it is written where a hardware - /// session falls back to software, so this follows reality), and the codec - /// comes from the clip under the playhead. Empty when nothing is playing -- - /// the question is about what is happening, not about what would. - fn live_decode(&self, position: f64, playing: bool) -> String { - let Some(session) = self.session.as_ref().filter(|_| playing) else { - return String::new(); - }; - let backend = session.decode_backend(); - let codec = session - .video_clip_at(position) - .and_then(|(lane, idx)| session.lane_clips(lane).get(idx).map(|clip| clip.source)) - .and_then(|source| session.sources().get(source)) - .and_then(|source| self.decoders.get(&source.path).copied().flatten()) - .and_then(|(codec, _)| codec); - match backend { - // Neither is a decode, and saying "SW" of them would be a lie. - Backend::Gap => "gap · nothing to decode".to_string(), - Backend::Still => "still · one decode, held".to_string(), - _ => format!("{} decode", decode_label(codec, backend)), - } - } - - /// Transport, edit and file buttons, timecode, playhead, clips lane. - fn panel( - &self, - position: f64, - duration: f64, - state: Transport, - cx: &mut Context, - ) -> impl IntoElement { - // Where the playhead is *on the bed*, in pixels from its left edge. - // Clamped to the bed because it is drawn as a width as well as an - // offset, and the view follows the playhead anyway, so it is never off - // the bed for long. - let bed_w = f32::from(self.ruler.get().size.width); - let filled = self.scale.px_at(position).clamp(0., bed_w); - // An export owns the hint slot and the ruler while it runs: the - // percentage and the accent bar are the same number, so the playhead - // fill doubles as the progress bar for free. - let exporting = self.exporting().is_some(); - // Everything but Import and Keys needs a timeline to act on: with none - // open they are dimmed rather than silently doing nothing. - let live = state != Transport::Stopped && !exporting; - // The project's own picture size, for the button that cycles it: read - // per render like everything else here, so a cycle shows on the button - // that made it. - let resolution = self.session.as_ref().map(PlaybackSession::resolution); - let key = |action| self.keymap.display(action); - // The lanes the project has, or the pair a fresh one starts with so the - // panel reads the same before a file is open as after. - let lanes = self - .session - .as_ref() - .map_or_else(|| vec![Lane::V1, Lane::A1], PlaybackSession::lanes); - // A loop rather than a `map`: each row takes `cx` in turn, where a - // closure would hold it for as long as the iterator lives. - let mut rows = Vec::new(); - 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); - 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 - .export_started - .map_or(0., |t| t.elapsed().as_secs_f32()); - // Two numbers that must both be honest: the one that counts up is - // measured, the one that counts down is a guess and says so. - let left = eta_secs(&self.export_marks, elapsed, progress).map_or_else( - || "estimating…".to_owned(), - |s| format!("~{} left", clock(s)), - ); - ( - format!( - // Clocks, then the way out, then what is encoding: at the - // 640 px floor the tail is what truncation eats, and the - // codec pair is the one part of this line the card already - // said. The escape must not be what goes missing. - "EXPORTING {}% · {} elapsed · {left} — {} cancels · {} · {}", - (progress * 100.) as u32, - clock(elapsed), - key(ActionId::CancelExport), - // The row that was picked; the engine's line below names the - // seats alone, since the library is what identifies a codec. - format_label(self.format), - // What the worker actually opened, so a fallback to the - // software encoder shows here rather than being invisible. - export - .encoders() - .unwrap_or_else(|| "opening the encoder".to_string()), - ), - progress, - ) - } else { - // The strokes no button carries; the rest ride on the buttons' - // tooltips. Keys first: at a 640 px window the tail is what a - // truncation eats, and the two hints at the end are also on the - // ruler's and Import's tooltips. - // While it plays, what is decoding it goes first: it is the - // answer that changes as the playhead crosses a cut, and the tail - // of this line is what a narrow window truncates. - ( - join_detail( - &self.live_decode(position, state.is_playing()), - &format!( - "{} copy · {} paste · {} undo · click the bar to seek · drop a file to \ - import", - key(ActionId::Copy), - key(ActionId::Paste), - key(ActionId::Undo) - ), - ), - filled, - ) - }; - div() - .flex_none() - .h(px(panel_h(lanes.len()) + strip_h)) - .flex() - .flex_col() - .gap(px(8.)) - .px(px(12.)) - .py(px(8.)) - .bg(rgb(CHROME)) - // Transport | edit | file: three groups, so the eye can skip two of - // them. Every button says what it does; the tooltip adds its key. - // - // The row scrolls rather than losing its tail: at the 640 px floor - // this window is sized for it is wider than the panel, and a button - // off the right edge is a button a pointer cannot press. A plain - // wheel moves it -- gpui puts a vertical delta on the x axis when - // that is the only one scrolling (div.rs:2424). - // - // ...and "it scrolls" is not "it can be found": the button beside - // the row is pinned outside it and never scrolls away, so Export, - // Save and the rest are one press from the smallest window even - // when the row's tail is off the edge. - // `toolbar_fits_the_smallest_window` is the guard. - .child( - div() - .flex_none() - .flex() - .items_center() - .gap(px(8.)) - .child( - div() - .id("controls") - .flex_1() - .min_w(px(0.)) - .flex() - .items_center() - .gap(px(8.)) - .overflow_x_scroll() - .child(control( - "transport", - Some(transport_glyph(state).into_any_element()), - if state.is_playing() { "Pause" } else { "Play" }, - if nothing_to_play(self.session.as_ref()) && !state.is_playing() { - format!("{} — put a clip on a lane first", key(ActionId::Play)) - } else { - key(ActionId::Play) - }, - // An empty timeline has nothing to play, so the button - // says so by being dim rather than by starting a clock - // against nothing (the key press answers with the - // notice). Still live while it *is* playing: a delete - // can empty the timeline mid-play and that has to stop. - live && (state.is_playing() || !nothing_to_play(self.session.as_ref())), - cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_or_restart(cx)), - )) - .child(separator()) - .child(control( - "cut", - Some(cut_glyph().into_any_element()), - "Cut", - format!( - "{} — splits the clip under the playhead", - key(ActionId::Cut) - ), - live, - cx.listener(|this, _: &ClickEvent, _, cx| this.cut(cx)), - )) - .child(control( - "delete", - Some(delete_glyph().into_any_element()), - "Delete", - if self.selected.is_some() { - key(ActionId::Delete) - } else { - format!("{} — click a clip below first", key(ActionId::Delete)) - }, - live && self.selected.is_some(), - cx.listener(|this, _: &ClickEvent, _, cx| this.delete_selected(cx)), - )) - // The way back from every one of them. It was a stroke and - // nothing else, which made the whole edit group a one-way - // door for anyone working with a pointer. - .child(control( - "undo", - None, - "Undo", - format!("{} — takes the last edit back", key(ActionId::Undo)), - live, - cx.listener(|this, _: &ClickEvent, _, cx| this.undo(cx)), - )) - // With the edit group, beside the buttons that change the - // edit list: a track is a row of it, and adding one is an - // undoable edit like the rest. Two buttons rather than one - // with a choice, because the choice is the whole action. - .child(control( - "add-video-lane", - None, - "+ V", - format!( - "{} — adds a video track under the ones there", - key(ActionId::AddVideoLane) - ), - live, - cx.listener(|this, _: &ClickEvent, _, cx| { - this.add_lane(LaneKind::Video, cx) - }), - )) - .child(control( - "add-audio-lane", - None, - "+ A", - format!( - "{} — adds an audio track under the ones there", - key(ActionId::AddAudioLane) - ), - live, - cx.listener(|this, _: &ClickEvent, _, cx| { - this.add_lane(LaneKind::Audio, cx) - }), - )) - // The third kind of track this timeline carries, and - // the only one that arrived through a drop alone: a - // subtitle file nobody thought to drag was a track - // the editor could not be asked for. What it opens is - // a chooser rather than an empty row -- a subtitle - // track is its file, and there is nothing to add - // before one is named. - .child(control( - "add-subtitle-track", - None, - "+ S", - // Dim, and saying why it is dim, out of the one - // oracle -- the very words the key answers with - // (`Player::pick_and_add_subtitles`), so the - // tooltip and the notice cannot come to differ. - match self.enable(ActionId::AddSubtitleTrack, None).why() { - Some(why) => { - format!("{} — {why}", key(ActionId::AddSubtitleTrack)) - } - None => format!( - "{} — adds every subtitle track in a file you pick", - key(ActionId::AddSubtitleTrack) - ), - }, - live, - cx.listener(|this, _: &ClickEvent, _, cx| { - this.pick_and_add_subtitles(cx) - }), - )) - // With the transport, not the edit group: it changes what - // the file sounds like, never what it is. Reads as its own - // state, so muted is legible without a tooltip. - .child(control( - "volume", - None, - self.volume.label(), - format!( - "{} mutes · {} louder · {} quieter", - key(ActionId::ToggleMute), - key(ActionId::VolumeUp), - key(ActionId::VolumeDown) - ), - live, - cx.listener(|this, _: &ClickEvent, _, cx| { - this.set_volume(|volume| volume.muted = !volume.muted, cx) - }), - )) - // The level itself, to drag. The button beside it stays the - // mute -- one gesture each -- and the label above is what - // this writes, live, so the number follows the hand. - .child(volume_slider( - self.volume, - self.volume_bar.clone(), - live, - cx, - )) - .child(separator()) - // The size every clip is composed onto, which is also the - // size the export comes out at. Five sizes, so a click opens - // the list of them with this one marked and picks whichever - // was meant: a button that stepped one on per press made the - // user click round the ladder to get back to where they - // were. The stroke still steps, for the hand already on it. - .child(control( - "resolution", - None, - resolution.map_or_else(|| "Size".to_string(), |(_, h)| format!("{h}p")), - match resolution { - Some((w, h)) => format!( - "click to pick a size — the project is {w}x{h}; {} steps to the next", - key(ActionId::Resolution) - ), - None => format!("{} — open a file first", key(ActionId::Resolution)), - }, - live, - cx.listener(|this, event: &ClickEvent, _, cx| { - this.open_picker(Pick::Resolution, event.position(), cx) - }), - )) - // The rate every clip is counted in, which is also the rate - // the export is written at -- the other half of "the project - // is not the media", and the one the panel could only ever - // read out before. A click opens the rates with this one - // marked; picking one conforms the whole timeline to it. - .child(control( - "fps", - None, - match self.session.is_some() { - true => format!("{} fps", fps_label(self.fps)), - false => "Rate".to_string(), - }, - match self.session.is_some() { - true => format!( - "click to pick a frame rate — the project is cut at {} fps", - fps_label(self.fps) - ), - false => "the project's frame rate — open a file first".to_string(), - }, - live, - cx.listener(|this, event: &ClickEvent, _, cx| { - this.open_picker(Pick::Fps, event.position(), cx) - }), - )) - // ...and which rendition its HDR media is watched in, the - // third thing that is the project's rather than the media's. - // Listed whatever is on the timeline, and the tooltip says - // who it acts on: a control that came and went with the - // media would be one nobody could find when they wanted it. - .child(control( - "tonemap", - None, - match &self.session { - Some(session) => format!("HDR {}", tone_label(session.tone())), - None => "HDR".to_string(), - }, - match &self.session { - Some(session) => format!( - "click to pick the HDR rendition — the project is {}; SDR media is untouched", - tone_label(session.tone()) - ), - None => "the HDR rendition — open a file first".to_string(), - }, - live, - cx.listener(|this, event: &ClickEvent, _, cx| { - this.open_picker(Pick::Tone, event.position(), cx) - }), - )) - // How much of the timeline the panel below is showing -- - // beside the resolution, since neither of them edits - // anything: they are both what is being looked at. The - // middle one says how much of it is on the bed, and is the - // way back to the whole of it. - .child(control( - "zoom-out", - None, - "−", - format!( - "{} — show more of the timeline; stops with all of it on the bed", - key(ActionId::ZoomOut) - ), - live, - cx.listener(|this, _: &ClickEvent, _, cx| { - this.zoom(1. / ZOOM_STEP, None, cx) - }), - )) - .child(control( - "zoom-fit", - None, - // How much timeline is on the bed, not a multiple of - // "the whole of it": the scale no longer knows what the - // whole of it is, and a number that changed on every - // import was a number that lied. - span_label(self.view().span()), - format!( - "{} — fit the whole timeline; showing {} to {}", - key(ActionId::ZoomFit), - timecode(self.scale.start, self.fps), - timecode( - (self.scale.start + self.view().span()).min(duration), - self.fps - ) - ), - live, - cx.listener(|this, _: &ClickEvent, _, cx| this.zoom_fit(cx)), - )) - .child(control( - "zoom-in", - None, - "+", - format!( - "{} — magnify around the playhead; ctrl+wheel on the bar zooms at the pointer", - key(ActionId::ZoomIn) - ), - live, - cx.listener(|this, _: &ClickEvent, _, cx| this.zoom(ZOOM_STEP, None, cx)), - )) - // The magnet, beside the zoom for the zoom's own reason: it - // changes nothing on the timeline, it changes how the hand - // meets it. The label is the state, as the volume's is -- - // a toggle that looks the same either way says nothing. - .child(control( - "snap", - None, - if self.snap { "Snap" } else { "No snap" }, - format!( - "{} — {}", - key(ActionId::ToggleSnap), - match self.snap { - true => "drags and trims land on clip edges, the playhead and the start", - false => "drags and trims land exactly where the hand leaves them", - } - ), - live, - cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_snap(cx)), - )) - // The cues over the picture, off and on -- beside the zoom - // and the snap, since like both of them it changes what is - // being looked at and nothing about the edit. The label is - // the state, as the snap's is, and it says what there is to - // toggle when there is nothing. - .child(control( - "subs", - None, - match (self.subtitle_track().is_some(), self.subs_on) { - (false, _) => "No subs", - (true, true) => "Subs", - (true, false) => "Subs off", - }, - match self.enable(ActionId::ToggleSubtitles, None).why() { - Some(why) => format!( - "{} — {why}; drop a .srt on the window, or open an mkv that carries them", - key(ActionId::ToggleSubtitles) - ), - None => format!( - "{} — {}", - key(ActionId::ToggleSubtitles), - match self.subs_on { - true => "the cue under the playhead is drawn over the picture", - false => "the cues are on the timeline and off the picture", - } - ), - }, - live && self.enable(ActionId::ToggleSubtitles, None).yes(), - cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_subtitles(cx)), - )) - // Import is not here: it belongs to the media list it adds - // to, and two doors into one action is a question about - // which one is the real one. - // - // While one runs, this button is the way out of it: the - // progress line promised esc and nothing else, which left a - // pointer no way to stop an export it had started. - .child(control( - "export", - None, - if exporting { "Cancel" } else { "Export" }, - if exporting { - format!( - "{} — stops the export; the part-written file goes", - key(ActionId::CancelExport) - ) - } else { - format!( - "{} — quality and destination, then writes the timeline out", - key(ActionId::Export) - ) - }, - if exporting { - true - } else { - live && self.export.is_none() - }, - cx.listener(|this, _: &ClickEvent, _, cx| { - if this.exporting().is_some() { - this.cancel_export(); - cx.notify(); - } else { - this.open_export(cx); - } - }), - )) - .child(control( - "save", - None, - "Save", - format!("{} — writes the project file", key(ActionId::Save)), - live, - cx.listener(|this, _: &ClickEvent, _, cx| this.save_project(cx)), - )) - // Closed while an export runs, which is what keeps a waiting - // row from swallowing the escape the progress line promises - // cancels the export. - .child(control( - "keys", - None, - "Actions", - // The pointer's way to every action there is, including - // the ones no button here has room for. - format!( - "{} — do any action, or change the key that does it", - key(ActionId::ShowActions) - ), - !exporting, - cx.listener(|this, _: &ClickEvent, _, cx| match this.keys_open { - true => { - this.keys_open = false; - this.rebinding = None; - cx.notify(); - } - false => this.show_actions(cx), - }), - )) - ) - // The door to everything the row cannot show at this - // window: the same card the Actions button opens, by the - // same call, pinned where a scroll cannot take it. - .child(control( - "controls-more", - None, - "⋯", - format!( - "{} — every action, including the ones scrolled off this row", - key(ActionId::ShowActions) - ), - !exporting, - cx.listener(|this, _: &ClickEvent, _, cx| match this.keys_open { - true => { - this.keys_open = false; - this.rebinding = None; - cx.notify(); - } - false => this.show_actions(cx), - }), - )), - ) - .child( - div() - .flex_none() - .flex() - .items_center() - .gap(px(12.)) - // Fixed width and one line: changing digits must not push - // the row around, nor wrap and change its height. - // The timeline's own length, never the drawn one: a tail - // being dragged inflates the bed to the room that edge has - // ([`Player::drawn_duration`]), and for a still that room is - // ten minutes -- a total that jumped to 10:00:00 the moment - // a picture's edge was pressed, and back on release. - .child(div().flex_none().w(px(TIME_W)).truncate().child(format!( - "{} / {}", - timecode(position, self.fps), - timecode( - self.session - .as_ref() - .map_or(0., PlaybackSession::timeline_duration), - self.fps - ) - ))) - .child( - div() - .flex_1() - .min_w(px(0.)) - .truncate() - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child(hint), - ), - ) - // Press to seek, drag to scrub: the move and release halves live on - // the root, since the pointer leaves the bar immediately. The bar - // stays 6 px to look at; the strip that takes the click is 24, so - // it can be hit without aiming (WCAG 2.5.8). - .child( - div() - .flex_none() - .flex() - .gap(px(HEADER_GAP)) - // The lanes' header column, empty here: the ruler's own bar - // has to start where their beds start, or the playhead - // would point at a different moment in each row. - .child(div().flex_none().w(px(HEADER_W))) - .child( - div() - .id("ruler") - .flex_1() - .min_w(px(0.)) - .h(px(RULER_HIT_H)) - .flex() - .flex_col() - .justify_center() - .rounded(px(3.)) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER_DIM))) - // The strip carries no text, so the tooltip is the only - // place it can say what it is. - .tooltip(|_, cx| { - cx.new(|_| Tip("Seek — click or drag; ctrl+wheel zooms".into())) - .into() - }) - // Ctrl+wheel is what every timeline zooms with, and - // the point held still is the one under the pointer - // rather than the playhead. Only with ctrl: a bare - // wheel here is the window's to scroll, and the - // controls row above scrolls on exactly that. - .on_scroll_wheel(cx.listener( - |this, event: &ScrollWheelEvent, _, cx| { - if !event.modifiers.control { - return; - } - let dy = match event.delta { - ScrollDelta::Lines(d) => d.y, - ScrollDelta::Pixels(d) => f32::from(d.y), - }; - if dy == 0. { - return; - } - let anchor = px_along(event.position.x, this.ruler.get()); - let factor = if dy > 0. { ZOOM_STEP } else { 1. / ZOOM_STEP }; - this.zoom(factor, Some(anchor), cx); - }, - )) - .on_mouse_down( - MouseButton::Left, - cx.listener(|this, event: &MouseDownEvent, _, cx| { - this.scrubbing = true; - this.scrub_to(event.position.x, true, cx); - }), - ) - .child( - div() - .w_full() - .h(px(6.)) - .rounded(px(3.)) - .bg(rgb(SURFACE)) - .child(bounds_probe(self.ruler.clone())) - .child( - div() - .h_full() - .w(px(filled)) - .rounded(px(3.)) - .bg(rgb(ACCENT)), - ), - ), - ), - ) - // Every lane the project has, in its own order -- and its own - // column, so a project with more lanes than the panel is tall - // scrolls its tracks instead of pushing the picture off the window. - // The gap is the panel's own, so two lanes lay out exactly as they - // did when they were two children of it. - .child( - div() - .id("lanes") - .flex_none() - .flex() - .flex_col() - .gap(px(8.)) - .max_h(px(lanes_h(LANES_MAX))) - .overflow_y_scroll() - .children(rows), - ) - // 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) - } +/// How long an open may stand before the window says so in words. Well past an +/// ordinary seek (a warm reopen is under a tenth of this) and well under what a +/// cold read of a big film takes, which is the only case worth a line. +const SEEK_STALL: Duration = Duration::from_secs(2); - /// The running import holds its own bar above the notice's, for the notice - /// bar's reason: the message is the point. Not a notice, though -- nothing - /// dismisses it, because it is about work still going on, and it leaves by - /// itself when the file lands. - /// - /// The bar under the words is a *sweep*, not a fill: neither read reports - /// where in the file it is, so a fill would have to invent the one number - /// this cannot know. What it does say truthfully is "something is still - /// running", which is exactly the question a frozen-looking window raises. - /// - /// ...and beside them the way out. A read that may be twenty seconds of a - /// cold 24 GB film needs one, and the only honest place for it is the line - /// that says the read is happening ([`Player::cancel_import`]). - fn import_bar(&self, cx: &mut Context) -> Option { - let import = self.importing.as_ref()?; - let elapsed = import.started.elapsed().as_secs_f32(); - let line = import_line( - &file_name(&import.path), - import.seen, - elapsed, - import.since.elapsed().as_secs_f32(), - self.imports.len(), - arrival(self.opening.as_deref(), &import.path) != Landing::Import, - ); - // A quarter of the bar, crossing it every three seconds and wrapping. - // Tied to the elapsed clock, so it moves for as long as the read does - // and stops dead the instant the file lands. - const SWEEP: f32 = 0.25; - let at = (elapsed / 3.).fract() * (1. + SWEEP) - SWEEP; - Some( - div() - .flex_none() - .flex() - .flex_col() - .gap(px(4.)) - .px(px(12.)) - .py(px(6.)) - .bg(rgb(SURFACE)) - .child( - div() - .flex() - .items_center() - .gap(px(8.)) - .child(div().flex_1().min_w(px(0.)).child(line)) - .child(control( - "cancel-import", - None, - "Cancel", - "stops this file and anything queued behind it; the read already \ - running finishes unheeded" - .to_string(), - true, - cx.listener(|this, _: &ClickEvent, _, cx| this.cancel_import(cx)), - )), - ) - .child( - div() - .relative() - .w_full() - .h(px(2.)) - .bg(rgb(HOVER)) - .child( - div() - .absolute() - .top_0() - .left(relative(at.max(0.))) - // Clipped at both ends by hand: the segment - // enters from the left edge and leaves past the - // right one, and a width that overhung would - // paint outside the track. - .w(relative((at + SWEEP).min(1.) - at.max(0.))) - .h(px(2.)) - .bg(rgb(ACCENT)), - ), - ), - ) - } +/// What a seek that has stood past [`SEEK_STALL`] says, and nothing at all +/// before that: a line on every click of the ruler would be a flicker, and the +/// picture holding still for a tenth of a second is not something to explain. +/// The import bar's words, for the import bar's reason -- a window that cannot +/// move and a window that has hung look identical, so this one says which. +fn seek_line(standing: Option) -> Option { + let since = standing.filter(|d| *d >= SEEK_STALL)?; + Some(format!( + "still opening the picture — a cold read of a big file is seconds of it, and the window \ + is not frozen · {} elapsed", + clock(since.as_secs_f32()) + )) +} - /// The line a long-standing seek shows, in the import bar's place and by the - /// import bar's rules: nothing dismisses it, and it leaves by itself the - /// moment the frame lands. No sweep under it -- an open reports nothing about - /// where it has got to, and the clock is the honest half of that bar anyway. - fn seek_bar(&self) -> Option { - let line = seek_line(self.seek_since.map(|t| t.elapsed()))?; - Some( - div() - .flex_none() - .px(px(12.)) - .py(px(6.)) - .bg(rgb(SURFACE)) - .child(line), - ) - } +/// How a finished export announces itself. Written by `poll_export` and read +/// by the notice bar, which is what makes that one line clickable. +const EXPORT_DONE: &str = "EXPORT DONE → "; - /// A notice holds its own bar, full width, until it is answered: any key - /// retires it (the key handler) and so does a click on it. Its own surface - /// because the message is the point -- a failure cut to the timecode's slot - /// is a failure nobody read. - /// - /// The export's own line is more than a message: it names a file that is - /// now on disk, so the same click that retires it shows that file in the - /// desktop's file manager. - fn notice_bar(&self, cx: &mut Context) -> Option { - let notice = self.notice.clone()?; - // The path travels with the text it was written for: a later notice - // holds the bar and the click is a plain dismissal again. - let exported = self - .exported - .clone() - .filter(|_| notice.starts_with(EXPORT_DONE)); - let hint = match exported { - Some(_) => "click — open file location", - None => "click or press any key to dismiss", - }; - Some( - div() - .id("notice") - .when(exported.is_some(), |d| { - d.tooltip(|_, cx| { - cx.new(|_| { - Tip("Open file location — shows the export in the file manager".into()) - }) - .into() - }) - }) - .flex_none() - .flex() - .items_start() - .gap(px(12.)) - .px(px(12.)) - .py(px(6.)) - .bg(rgb(SURFACE)) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - // Another process starting: off the UI thread, and it - // outlives the notice it was asked from. - if let Some(path) = exported.clone() { - cx.background_executor() - .spawn(async move { show_in_file_manager(&path) }) - .detach(); - } - this.notice = None; - cx.notify(); - })) - .child(div().flex_1().min_w(px(0.)).child(notice)) - .child( - div() - .flex_none() - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child(hint), - ), - ) +/// The path as a URI the bus will take: percent-encoded, because an export +/// lands wherever its source lives and those directories have spaces in them. +/// Bytes, not chars -- a path is not required to be UTF-8. +fn file_uri(path: &std::path::Path) -> String { + use std::os::unix::ffi::OsStrExt; + let mut uri = String::from("file://"); + for &b in path.as_os_str().as_bytes() { + match b { + b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => { + uri.push(b as char) + } + _ => uri.push_str(&format!("%{b:02X}")), + } } - - /// Every binding, and the way to change one: a row per entry, click it and - /// the next stroke becomes its chord. Over the whole window, because while - /// it is up nothing under it may answer -- the scrim stops the clicks - /// (gpui dispatches mouse listeners topmost-first, window.rs:3705) and the - /// key handler's own branch stops the strokes. - /// - /// Plain divs, like every control here: nothing in it takes focus, so the - /// root is still the one reading the keyboard -- which is exactly what a - /// waiting row depends on. - fn keys_overlay(&self, cx: &mut Context) -> Option { - if !self.keys_open { - return None; - } - // The way out, spelled the way the rows spell a chord. - let out = keymap::Chord { - key: ESCAPE.to_string(), - ctrl: false, - } - .pretty(); - // Every action there is, under its heading, and the strokes the modal - // cards answer to beside them -- `keys_rows` is the whole of the order - // and every word in it comes off the registry. - // - // A row is two targets, not one: its label *does* the action, which is - // the pointer's way to the ones no button carries, and its stroke - // changes that stroke. An action with two strokes reads as one line - // ("x or delete") and a rebind replaces that whole set. - let mut rows: Vec = Vec::new(); - let row = || { - div() - .flex() - // The floor, not the height: a row that needed two lines - // would otherwise paint over the one under it -- which it did - // anyway until this said `flex_none`, a row inside a capped - // scrolling list being shrunk to fit by default (the export - // card's rows had the same shape and the same overlap). - .flex_none() - .min_h(px(KEYS_ROW_H)) - .items_center() - .justify_between() - .gap(px(12.)) - .px(px(6.)) - .rounded(px(3.)) - }; - let found = keys_filter(&self.keys_search, &self.keymap); - // What the search box says: the typed text, and how much of the list is - // left under it -- a filter that found nothing has to say so, or the - // card reads as a list that lost its rows. - let search = if self.keys_search.is_empty() { - "search: type to filter · ↑ ↓ scroll the list · a click away closes".to_string() - } else { - let rows = found - .iter() - .filter(|(_, r)| !matches!(r, KeyRow::Head(_))) - .count(); - match rows { - 0 => format!( - "search: {} — nothing matches · {out} clears", - self.keys_search - ), - n => format!("search: {} — {n} shown · {out} clears", self.keys_search), - } - }; - for (i, key_row) in found { - rows.push(match key_row { - KeyRow::Head(category) => div() - .flex_none() - .px(px(6.)) - .pt(px(4.)) - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child(category.label()) - .into_any_element(), - KeyRow::Act(action) => { - let capturing = self.rebinding == Some(action); - // Why the label half will not answer, if it will not: the - // registry's one answer, the same the clip menu dims by. - let refusal = self.enable(action, None); - let out = out.clone(); - row() - .when(capturing, |d| d.bg(rgb(SELECTED))) - .child( - div() - .id(("do", i)) - .flex_1() - .min_w(px(0.)) - .flex() - .min_h(px(KEYS_ROW_H)) - .items_center() - // One line, cut where the stroke's column - // starts: a label longer than the room it has - // printed straight over the stroke beside it, - // and two overprinted words are less readable - // than one truncated one. - .truncate() - .child(action.label()) - // The reason rides on the label rather than in - // the stroke column, which the rebind half - // needs whatever the editor's state is: an - // action nobody can ask for right now is still - // one whose key may be changed. - .when_some(refusal.why(), |d, why| { - let why: SharedString = why.into(); - d.tooltip(move |_, cx| cx.new(|_| Tip(why.clone())).into()) - }) - .when(!refusal.yes(), |d| d.opacity(0.4).cursor_not_allowed()) - .when(refusal.yes(), |d| { - d.cursor_pointer().hover(|s| s.bg(rgb(HOVER))).on_click( - cx.listener(move |this, _: &ClickEvent, _, cx| { - // The card goes first: several of - // these open a card of their own, - // and every edit moves the indices - // the menus are holding. - this.keys_open = false; - this.rebinding = None; - this.act(action, cx); - cx.notify(); - }), - ) - }), - ) - .child( - // ponytail: the column is as wide as the stroke it - // prints, so a one-character chord gives this half a - // hit area under the 24px WCAG 2.5.8 floor -- tall - // enough, narrow. Upgrade: a min_w of HIT_MIN here. - div() - .id(("bind", i)) - .flex_none() - .flex() - .min_h(px(KEYS_ROW_H)) - .items_center() - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.rebinding = Some(action); - cx.notify(); - })) - .child(if capturing { - div() - .text_color(rgb(INK_DIM)) - .child(format!("press a key — {out} cancels")) - } else { - div().child(self.keymap.display(action)) - }), - ) - .into_any_element() - } - KeyRow::Fixed(f) => { - let f = &keymap::FIXED[f]; - row() - .child(f.label) - // Dim, and no hover: this one is not a row you can click. - .child(div().text_color(rgb(INK_DIM)).child(f.chord.clone())) - .into_any_element() - } - }); - } - Some( - scrim() - .flex() - .justify_center() - .items_center() - // The picture behind is out of reach, and looks it. The press is - // swallowed here so a button under the scrim cannot take it -- - // and it closes the card on the way, which is the pointer's exit - // from every card here ([`Player::close_card`]). - .bg(rgba(0x101010cc)) - .on_mouse_down( - MouseButton::Left, - cx.listener(|this, _: &MouseDownEvent, _, cx| { - this.close_card(); - cx.notify(); - cx.stop_propagation(); - }), - ) - .child( - div() - .w(px(KEYS_W)) - .on_mouse_down(MouseButton::Left, swallow) - .flex() - .flex_col() - .gap(px(2.)) - .p(px(12.)) - .rounded(px(6.)) - .bg(rgb(SURFACE)) - // Title and instruction are two children, never one - // wrapping line: a fixed-height slot whose text wrapped - // painted its second line over the first row. - .child(div().flex_none().px(px(6.)).child("Actions & keys")) - // One status line, under the title where the eye starts. - // A refusal takes it over -- it is the more urgent of the - // two, and the notice bar it would otherwise appear in is - // under the scrim. - // - // The row list below is capped and scrolls, so neither a - // wrapped refusal here nor another action added to `ALL` - // can push the card past a 360 px window any more. - .child( - div() - .flex_none() - .px(px(6.)) - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child( - self.notice - .clone() - .unwrap_or_else(|| { - "click an action to do it · click its key to change it" - .into() - }), - ), - ) - // The search box: no focus and no text field -- the - // card's key handler is the field, exactly as the - // export card's bitrate is typed into it. Its own line - // above the list, so the rows below it are always the - // answer to what it says. - .child( - div() - .flex_none() - .px(px(6.)) - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child(search), - ) - // Capped and scrolling rather than as tall as the action - // list happens to be: the list grows with the editor, - // the smallest window does not. - .child( - div() - .id("keys-rows") - .flex() - .flex_col() - .gap(px(2.)) - .max_h(px(KEYS_ROWS_H)) - // The line the list scrolls under: a row half - // out of the viewport sat against the search - // line with nothing between them, and read as a - // row painted over the heading rather than as a - // list with more above it. - .mt(px(4.)) - .border_t_1() - .border_color(rgb(CHROME)) - .pt(px(4.)) - .overflow_y_scroll() - // The wheel's offset and the arrow keys' are - // the same one, so the two cannot disagree - // about where the list is. - .track_scroll(&self.keys_scroll) - .children(rows), - ), - ), - ) - } - - /// What an export is going to be, before there is one: the codec, the box - /// it goes into, the bitrate, where it lands -- and, above the button, the - /// two lines that state the file all of that adds up to. The same scrim and - /// row shape as the keybindings overlay (two cards of different builds over - /// one window read as two different programs) and the same plain divs, so - /// the root keeps the keyboard and the custom row's field is typed into - /// through it ([`NumberEdit`]). - /// - /// Every row carries the key that picks it, so the card is drivable end to - /// end without a pointer *and* without a legend to memorise -- and every - /// row is clickable, the bitrate's steppers included, so it is drivable end - /// to end without a keyboard as well. - /// - /// Two shapes of it, behind `g` and `r`: sections against one flat list, - /// and the codecs with no encoder collapsed into a footer against a dimmed - /// row each. Grouped and collapsed is what opens. - fn export_card( - &self, - viewport: Size, - cx: &mut Context, - ) -> Option { - if !self.export_open { - return None; - } - // The cap is what keeps the card inside the smallest window; a taller - // one gets a taller list rather than a scroll past empty space, and the - // card is still only as tall as the rows it has. - let rows_h = (f32::from(viewport.height) - EXPORT_FIXED_H - 24.).max(EXPORT_ROWS_H); - let row = |id: (&'static str, usize)| { - div() - .id(id) - .flex() - // The floor, not the height: the destination's path wraps on a - // long name and must not paint over the row under it. Which it - // did: inside a capped, scrolling list a row shrinks to fit by - // default, so a wrapped detail was drawn over the row beneath - // it (the Sound row's "the source's own packets are copied…" - // over Subtitles). The list scrolls -- a row is as tall as what - // it has to say. - .flex_none() - .min_h(px(KEYS_ROW_H)) - .items_center() - .justify_between() - .gap(px(12.)) - .px(px(6.)) - .rounded(px(3.)) - }; - // A row that cannot be picked is dimmed and takes no click, exactly as - // an inapplicable item in the clip menu is: it still says its piece. - let live = |d: Stateful
, enabled: bool| { - d.when(!enabled, |d| { - d.cursor_not_allowed().text_color(rgb(INK_DIM)) - }) - .when(enabled, |d| d.cursor_pointer().hover(|s| s.bg(rgb(HOVER)))) - }; - // A row as this card writes them: the mark saying which one is picked, - // the key that picks it, its name, and what the choice means. The mark - // is a glyph and not only a colour -- a background alone is gone the - // moment a hover lands on the row, and invisible to anyone who cannot - // tell the two greys apart (WCAG 1.4.1). - let entry = |id: (&'static str, usize), - key: &str, - label: SharedString, - detail: SharedString, - picked: bool, - enabled: bool| { - // The small print of a picked row sits on the highlight, where the - // dim ink is only 3.3:1 -- the row it lands on lifts it (WCAG - // 1.4.3, and the fit test pins both numbers). - let ink = match picked { - true => INK, - false => INK_DIM, - }; - live(row(id), enabled) - .when(picked, |d| d.bg(rgb(SELECTED))) - .child( - div() - .flex() - .flex_none() - .items_center() - .gap(px(8.)) - .child(div().w(px(10.)).child(match picked { - true => "✓", - false => " ", - })) - .child( - div() - .w(px(EXPORT_KEY_W)) - .text_size(px(11.)) - .text_color(rgb(ink)) - .child(SharedString::from(key.to_string())), - ) - .child(label), - ) - // Wraps rather than runs off the row: a refusal is the longest - // thing in this column and the half of it past the edge is the - // half that says what to do instead. - .child( - div() - .min_w(px(0.)) - .flex_shrink() - .text_size(px(11.)) - .text_color(rgb(ink)) - .child(detail), - ) - }; - let header = |text: &'static str| { - div() - .flex_none() - .px(px(6.)) - .pt(px(4.)) - .text_size(px(10.)) - .text_color(rgb(INK_DIM)) - .child(text) - .into_any_element() - }; - let mut list: Vec = Vec::new(); - if self.export_grouped { - list.push(header("FORMAT")); - } - // The codecs first: which one is being written decides whether every - // row under it means anything. One a *this* timeline cannot be written - // as (an audio-only edit, for a picture codec) reads exactly like one - // there is no encoder for -- dimmed, unclickable, and carrying its own - // reason where its detail was, with nothing to click to find that out. - let mut refusals: Vec = Vec::new(); - for (i, (boxes, key, label, detail)) in FORMATS.into_iter().enumerate() { - let format = same_box(boxes, self.format); - let refused = format - .zip(self.session.as_ref()) - .and_then(|(f, s)| format_refusal(s, f)); - // A codec with no encoder here at all is the other kind of refusal, - // and the one the footer collects: it can never become pickable, so - // a row each is dead rows above the fold. - if format.is_none() { - refusals.push(format!("{label} — {detail}")); - if !self.export_refusals_inline { - continue; - } - } - let detail: SharedString = match &refused { - Some(why) => why.clone().into(), - None => detail.into(), - }; - let format = format.filter(|_| refused.is_none()); - let mut r = entry( - ("format", i), - key, - label.into(), - detail, - boxes.contains(&self.format), - format.is_some(), - ); - if let Some(format) = format { - r = r.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.set_format(format); - cx.notify(); - })); - } - list.push(r.into_any_element()); - } - if self.export_grouped { - list.push(header("DETAILS")); - } - // The container, and only where the picked codec has more than one box: - // a row offering a single choice reads as a choice. - let boxes = containers(self.format); - if boxes.len() > 1 { - let next = next_container(self.format); - list.push( - entry( - ("container", 0), - "c", - "Container".into(), - format!( - "{} — c for {}", - self.format.ext().to_uppercase(), - next.ext().to_uppercase() - ) - .into(), - false, - true, - ) - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.cycle_container(); - cx.notify(); - })) - .into_any_element(), - ); - } - match bitrate_refusal(self.format) { - // One dimmed row carrying the reason, rather than five rows of a - // figure that will not be written: the quality rows are the - // *picture's* bitrate, and this file has no picture in it. - Some(why) => list.push( - entry( - ("quality", 0), - "q", - "Quality".into(), - why.into(), - false, - false, - ) - .into_any_element(), - ), - None => { - for (i, quality) in Quality::ALL.into_iter().enumerate() { - // The custom row is a field: `n` opens it, a click in it - // opens it too, and while it is open the row shows what is - // being typed with a caret in it rather than the number in - // force. The other four are picked whole. - let field = self.mbps_edit.as_ref().filter(|_| quality == Quality::Custom); - let mut r = entry( - ("quality", i), - match quality { - Quality::Custom => "n", - _ => "q", - }, - quality.label().into(), - match field { - Some(edit) => edit.detail().into(), - None => quality.detail(self.custom_mbps).into(), - }, - self.quality == quality, - true, - ) - .on_click(cx.listener( - move |this, _: &ClickEvent, _, cx| { - match quality { - Quality::Custom => this.edit_mbps(), - _ => this.quality = quality, - } - cx.notify(); - }, - )); - if quality == Quality::Custom { - r = r.child(self.mbps_steppers(cx)); - } - list.push(r.into_any_element()); - } - } - } - // The other half of the file, and the one this card used to write at a - // fixed rate without saying so: what the *sound* is coded at, for every - // format that codes it -- the AAC inside a video export as much as an - // MP3. Four rates, so the pointer gets the *list* of them - // ([`Pick::AudioRate`]) rather than a button clicked round -- the - // resolution row's rule, and the key still steps as `ctrl+r` still - // does. Dimmed with the reason where this timeline has no rate to pick, - // like the quality rows are. - let sound = self.audio_rate_refusal(); - let mut r = entry( - ("sound", 0), - "b", - "Sound".into(), - match sound { - Some(why) => why.into(), - None => format!("{} kbps — b steps", self.audio_kbps).into(), - }, - false, - sound.is_none(), - ); - if sound.is_none() { - r = r.on_click(cx.listener(|this, event: &ClickEvent, _, cx| { - this.open_picker(Pick::AudioRate, event.position(), cx) - })); - } - list.push(r.into_any_element()); - // What happens to the subtitles on this timeline, in one line: how many - // are written into the file and under what names, or the reason each one - // is not. Which tracks travel is not a pick -- everything with a cue on - // the timeline goes ([`Player::export_subs`]) -- so the row says rather - // than offers, like the machine lines below. - // ...and the ones that do not travel are named here too, which they were - // not: `export_subs` had already filtered a track with no cue on *this* - // timeline out of the engine's sight, so the card said nothing about a - // row the list was still showing ([`subtitle_plan`]). - let plan = self.subtitle_line(); - // The row used to end in "click for in MKV" whenever the picture - // was going into an mp4, on the grounds that only Matroska carries a - // text track. An mp4 carries one now (`Mp4Muxer::write_subtitles` writes - // `tx3g`), so that was a refusal offering a way out of nothing: the - // container the card is already set to embeds them. The refusals left in - // `planned_subtitles` are the true ones -- a sound-only format has - // nowhere to put a track, and a PGS track is pictures whatever the box. - list.push( - entry( - ("subtitles", 0), - "", - "Subtitles".into(), - plan.into(), - false, - false, - ) - .into_any_element(), - ); - let destination = entry( - ("destination", 0), - "d", - "Destination".into(), - file_name(&self.export_path).into(), - false, - true, - ) - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| this.pick_destination(cx))) - .into_any_element(); - // The card's own two layout switches. They were `g` and `r` and nothing - // else, while the status line under the title advertised both of them: - // a hand on the mouse read what they do and had nothing to press. - list.push( - entry( - ("export-layout", 0), - "g", - "Layout".into(), - match self.export_grouped { - true => "sections — g for one flat list".into(), - false => "one flat list — g for sections".into(), - }, - self.export_grouped, - true, - ) - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.export_grouped = !this.export_grouped; - cx.notify(); - })) - .into_any_element(), - ); - list.push( - entry( - ("export-refusals", 0), - "r", - "Codecs with no encoder".into(), - match self.export_refusals_inline { - true => "a dimmed row each — r collapses them".into(), - false => "one line at the foot — r shows a row each".into(), - }, - self.export_refusals_inline, - true, - ) - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.export_refusals_inline = !this.export_refusals_inline; - cx.notify(); - })) - .into_any_element(), - ); - match self.export_grouped { - true => list.push(destination), - // Flat: the same rows with no headers over them, and the - // destination back at the top where the card used to open with it. - false => list.insert(0, destination), - } - if !self.export_refusals_inline && !refusals.is_empty() { - // Last, and one line: the reason travels with the name (a footer - // that only listed them would be the "why not?" the rows exist to - // answer), but nothing here can ever be picked, so it sits under - // every row that can rather than above them. - list.push( - div() - .flex_none() - .px(px(6.)) - .py(px(2.)) - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child(format!("cannot write: {}", refusals.join(" · "))) - .into_any_element(), - ); - } - // What is doing the work, on this machine and in this build: the GPU - // half is asked of the driver through the plugin (a different answer on - // every machine, and "none" where there is no plugin at all), the build - // half is the crates that were compiled in. Last in the list, because it - // is what a user checks rather than what they pick -- and a listing - // rather than rows, since none of it can be clicked. - if self.export_grouped { - list.push(header("THIS MACHINE")); - } - let note = |text: String| { - div() - .flex_none() - .px(px(6.)) - .py(px(2.)) - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child(text) - .into_any_element() - }; - list.push(note(format!( - "GPU: {}", - self.hw_caps.clone().unwrap_or_else(|| "asking…".into()) - ))); - list.push(note(format!("Built in: {}", engine::caps::software()))); - // What the rows add up to, which is the one thing that has to be right: - // codec, box, size, rate, sound, where it goes and about how big. Two - // lines, outside the scrolling list, so it is on screen whatever the - // list is scrolled to and whatever is picked. - let picture = self - .session - .as_ref() - .map(|s| (s.resolution(), s.meta().frame_rate)); - let audio = self - .session - .as_ref() - .map_or("", |s| s.planned_audio(self.format)); - let settings = - export_settings(self.quality, self.custom_mbps, self.format, self.audio_kbps); - let size = estimated_bytes( - settings.bitrate.filter(|_| self.format.has_video()), - self.session - .as_ref() - .map_or(0., PlaybackSession::timeline_duration), - ); - let head = summary_head(self.format, picture, audio); - let tail = summary_tail( - &self.export_path, - size, - self.export_seat.as_ref().and_then(|(.., seat)| *seat), - self.format.has_video(), - ); - // The button says the refusal *before* it is pressed: the picked codec - // can go invalid one edit after it was picked (a cleared video lane), - // and a button that looks ready until it is pressed is the lie the - // dimmed rows above it are there to avoid. - let blocked = self - .session - .as_ref() - .and_then(|s| format_refusal(s, self.format)); - let action: SharedString = match &blocked { - Some(why) => { - format!("Cannot export — {}", why.split(" — ").next().unwrap_or(why)).into() - } - None => "Export".into(), - }; - Some( - scrim() - .flex() - .justify_center() - .items_center() - .bg(rgba(0x101010cc)) - // Click away closes it, as on every card here. - .on_mouse_down( - MouseButton::Left, - cx.listener(|this, _: &MouseDownEvent, _, cx| { - this.close_card(); - cx.notify(); - cx.stop_propagation(); - }), - ) - .child( - div() - .w(px(EXPORT_W)) - .on_mouse_down(MouseButton::Left, swallow) - .flex() - .flex_col() - .gap(px(2.)) - .p(px(12.)) - .rounded(px(6.)) - .bg(rgb(SURFACE)) - .child(div().flex_none().px(px(6.)).child("Export")) - // The status line, where a refusal from the save dialog - // lands: the notice bar it would otherwise take is under - // the scrim. The keys are on the rows, so this says how - // the card as a whole is answered rather than listing - // them a second time. - .child( - div() - .flex_none() - .px(px(6.)) - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child(match (&self.mbps_edit, &self.notice) { - // A field being typed into says so here as - // well as in its row: this line is outside - // the scrolling list and on screen at every - // window size, and at 360 px the custom row - // itself can be below the fold -- a number - // typed where it cannot be seen is the - // blind capture this field replaced. - (Some(edit), _) => { - SharedString::from(format!("Custom bitrate {}", edit.detail())) - } - (None, Some(notice)) => notice.clone(), - (None, None) => "the keys are on the rows · enter exports · \ - a click away or esc closes · g/r change the layout" - .into(), - }), - ) - // Capped and scrolling like the keybindings list: the - // rows are more than a 360 px window has room for, and - // it is the list that scrolls, never the card that - // grows -- the summary and the button below stay put. - .child( - div() - .id("export-rows") - .flex() - .flex_col() - .gap(px(2.)) - .max_h(px(rows_h)) - .overflow_y_scroll() - .children(list), - ) - .child(div().flex_none().px(px(6.)).text_size(px(11.)).child(head)) - .child( - div() - .flex_none() - .px(px(6.)) - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child(tail), - ) - .child( - div() - .id("export-confirm") - .mt(px(4.)) - .flex() - .h(px(CONTROL_H)) - .items_center() - .justify_center() - .rounded(px(3.)) - .bg(rgb(match blocked.is_some() { - true => CHROME, - false => SELECTED, - })) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click( - cx.listener(|this, _: &ClickEvent, _, cx| { - this.start_export(cx) - }), - ) - .child(action), - ), - ), - ) - } - - /// The custom bitrate's two pointer buttons. The typed digits were the last - /// control in this card a mouse could not reach at all -- and a number that - /// can only be typed is a number a hand on the pointer has to leave the - /// card to change. `HIT_MIN` square, like every other target here. - fn mbps_steppers(&self, cx: &mut Context) -> impl IntoElement { - let step = |id: &'static str, label: &'static str, by: i32, cx: &mut Context| { - div() - .id(id) - .flex() - .w(px(HIT_MIN)) - .h(px(HIT_MIN)) - .items_center() - .justify_center() - .rounded(px(3.)) - .bg(rgb(CHROME)) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.nudge_mbps(by); - cx.notify(); - })) - .child(label) - }; - div() - .flex() - .gap(px(4.)) - .child(step("mbps-down", "−", -1, cx)) - .child(step("mbps-up", "+", 1, cx)) - } - - /// The equalizer of one audio clip: its frequency response drawn as a - /// curve, a handle per band sitting on it, each band's own bell under the - /// sum, and a row that reads and moves the picked band's three numbers. The - /// curve is the clip's actual filter (`EqParams::response_db` reads the - /// coefficients the samples go through), and it is redrawn on every pointer - /// sample of a drag, so the shape bends under the hand. - /// - /// Wider than the other cards and wider still on a bigger window - /// ([`eq_card_w`]): every pixel across is frequency resolution, which none - /// of the row-shaped cards have any use for. The same scrim and the same - /// plain divs -- nothing here takes focus, so the root keeps the keyboard - /// and the card's own strokes (a digit, the arrows, `a`, `x`, `f`, `r`, - /// `s`) reach it. - /// - /// Every change is written at the clip as it is made - /// ([`Player::commit_eq`]), so what the card shows is always what is - /// playing: there is no OK button to forget, and closing it changes - /// nothing. What takes a curve back off is undo, like every other edit. - fn eq_card( - &self, - viewport: Size, - cx: &mut Context, - ) -> Option { - let (lane, idx) = self.eq_open?; - // The rate the engine filters this timeline at, so the drawn curve is - // the one those coefficients make -- near the top of the axis a 44.1 kHz - // clip and a 48 kHz one are not the same shape. - let sample_rate = self.timeline_audio().map_or(48_000, |(rate, _)| rate); - let picked = self.eq_params.bands.get(self.eq_band); - // What is playing, drawn behind the curve -- and only while something - // *is* playing: the tap freezes with the device, and a still spectrum - // under a paused timeline would look like sound that is not there. - let spectrum = self - .eq_spectrum - .then_some(self.session.as_ref()) - .flatten() - .filter(|session| session.is_playing()) - .and_then(PlaybackSession::audio_tap) - .map(|(samples, rate)| eq_spectrum(&samples, rate)) - .filter(|levels| !levels.is_empty()) - .map(eq_spectrum_curve); - let handles: Vec<_> = self - .eq_params - .bands - .iter() - .enumerate() - .map(|(i, band)| { - div() - .absolute() - .left(relative(eq_x(band.freq_hz))) - .top(relative(eq_y(band.gain_db))) - // Centred on its own point: it hangs off the graph's corner, - // so it is pulled back by half of itself both ways. - .ml(px(-EQ_HANDLE / 2.)) - .mt(px(-EQ_HANDLE / 2.)) - .w(px(EQ_HANDLE)) - .h(px(EQ_HANDLE)) - .rounded(px(EQ_HANDLE / 2.)) - .bg(rgb(match i == self.eq_band { - true => ACCENT, - false => INK_DIM, - })) - }) - .collect(); - let graph = div() - // Ided like the band rows it replaces: what the pointer presses on - // is one element with its own hitbox, which is what a drag is - // tracked from. - .id("eq-graph") - .relative() - .flex_none() - .h(px(EQ_GRAPH_H)) - .rounded(px(3.)) - .bg(rgb(HOVER_DIM)) - .cursor_pointer() - // The press picks the band under it *and* is already the first - // sample of the drag, so a plain click sets a value. A second click - // takes that band back to flat instead: the gesture that undoes one - // handle, with no modifier to remember. - .on_mouse_down( - MouseButton::Left, - cx.listener(|this, event: &MouseDownEvent, _, cx| { - this.eq_band = this.nearest_band(event.position.x); - if event.click_count >= 2 { - this.eq_dragging = false; - this.nudge_band(|b| b.gain_db = 0., cx); - return; - } - this.eq_dragging = true; - this.drag_band(event.position, cx); - }), - ) - .child(bounds_probe(self.eq_graph.clone())) - // The analyser first, so everything else is drawn on top of it. - .children(spectrum) - // The decades, so a hump can be read as "around 200 Hz" without - // dropping the eye to the labels along the bottom. The two ends - // are the box's own edges and rule nothing. - .children( - EQ_TICKS - .iter() - .filter(|(freq, _)| *freq > EQ_FREQ_LOW && *freq < EQ_FREQ_HIGH) - .map(|(freq, _)| { - div() - .absolute() - .left(relative(eq_x(*freq))) - .w(px(1.)) - .h_full() - .bg(rgb(EQ_GRID)) - }) - .collect::>(), - ) - // Half way to each limit, each carrying its own number: the curve - // is a curve of decibels, and until now only one of them was drawn. - .children(EQ_DB_GRID.map(|db| { - div() - .absolute() - .top(relative(eq_y(db))) - .w_full() - .h(px(1.)) - .bg(rgb(EQ_GRID)) - .child( - div() - .absolute() - .left(px(4.)) - .top(px(-11.)) - .text_size(px(9.)) - .text_color(rgb(INK_DIM)) - .child(format!("{db:+.0}")), - ) - })) - // 0 dB: the line a boost is a boost *from*. - .child( - div() - .absolute() - .top(relative(0.5)) - .w_full() - .h(px(1.)) - .bg(rgb(HOVER)), - ) - .child(eq_curve(self.eq_params.clone(), sample_rate)) - .children(handles) - .children(EQ_TICKS.map(|(freq, label)| { - div() - .absolute() - .left(relative(eq_x(freq))) - // Pulled back so the mark reads as sitting *at* its - // frequency; the two ends then hug the corners. - .ml(px(-12.)) - .bottom(px(1.)) - .w(px(24.)) - .text_align(TextAlign::Center) - .text_size(px(9.)) - .text_color(rgb(INK_DIM)) - .child(label) - })) - .child( - div() - .absolute() - .top(px(2.)) - .left(px(4.)) - .text_size(px(9.)) - .text_color(rgb(INK_DIM)) - .child(format!("+{EQ_GAIN_LIMIT:.0} dB")), - ); - // The bottom of the axis is not named: -12 dB would land in the same - // corner as the 20 Hz tick, and the two lines above it (+6 and -6) - // already say what the box is worth per pixel. - Some( - scrim() - .flex() - .justify_center() - .items_center() - .bg(rgba(0x101010cc)) - // Click away closes it, as on every card here. - .on_mouse_down( - MouseButton::Left, - cx.listener(|this, _: &MouseDownEvent, _, cx| { - this.close_card(); - cx.notify(); - cx.stop_propagation(); - }), - ) - .child( - div() - .w(px(eq_card_w(f32::from(viewport.width)))) - .on_mouse_down(MouseButton::Left, swallow) - .flex() - .flex_col() - .gap(px(2.)) - .p(px(12.)) - .rounded(px(6.)) - .bg(rgb(SURFACE)) - // Which clip, because the card is modal and the lane it - // was opened from is behind a scrim by the time it is up. - .child(div().flex_none().px(px(6.)).child(format!( - "Equalizer — {} clip {}", - lane.label(), - idx + 1 - ))) - .child( - div() - .flex_none() - .px(px(6.)) - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child(self.notice.clone().unwrap_or_else(|| { - "drag a handle, or a digit picks a band — ←→ moves it, ↑↓ its gain, shift+←→ its width; a adds, x removes, f flattens it, r all, s spectrum; a click away or esc closes".into() - })), - ) - .child(graph) - // Which band the keyboard is holding and every number it - // is set to, each with the pair of buttons that moves it: - // the curve shows the sum, and a band pushed against one - // pulling the other way is not readable off it. - .child(self.eq_numbers(picked, cx)) - .child( - div() - .mt(px(4.)) - .flex() - .gap(px(4.)) - .child( - div() - .id("eq-reset") - .flex() - .flex_1() - .h(px(CONTROL_H)) - .items_center() - .justify_center() - .rounded(px(3.)) - .bg(rgb(SELECTED)) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - for band in &mut this.eq_params.bands { - band.gain_db = 0.; - } - this.commit_eq(cx); - })) - .child("Flatten all"), - ) - // The two that change how many bands there are. - // The engine takes any cascade -- the count was - // only ever fixed because this card had no way - // to say otherwise. - .child( - div() - .id("eq-add") - .flex() - .flex_1() - .h(px(CONTROL_H)) - .items_center() - .justify_center() - .rounded(px(3.)) - .bg(rgb(CHROME)) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.add_band(cx) - })) - .child("Add band"), - ) - .child( - div() - .id("eq-remove") - .flex() - .flex_1() - .h(px(CONTROL_H)) - .items_center() - .justify_center() - .rounded(px(3.)) - .bg(rgb(CHROME)) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.remove_band(cx) - })) - .child("Remove band"), - ) - // The analyser's switch, next to the one other - // button the card has: `s` does the same, and a - // toggle only a keystroke can reach is one most - // people never find. - .child( - div() - .id("eq-spectrum") - .flex() - .flex_1() - .h(px(CONTROL_H)) - .items_center() - .justify_center() - .rounded(px(3.)) - .bg(rgb(match self.eq_spectrum { - true => SELECTED, - false => HOVER_DIM, - })) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.eq_spectrum = !this.eq_spectrum; - cx.notify(); - })) - .child(match self.eq_spectrum { - true => "Spectrum on", - false => "Spectrum off", - }), - ), - ), - ), - ) - } - - /// The picked band's three numbers -- where it sits, how far it pushes and - /// how wide it is -- each beside the pair of buttons that moves it. The - /// arrows do the same three things, but a value only a key can change is a - /// value a hand on the pointer cannot reach at all, which is the same reason - /// [`Player::mbps_steppers`] exists. - fn eq_numbers(&self, picked: Option<&Band>, cx: &mut Context) -> impl IntoElement { - let row = div() - .flex_none() - .flex() - .items_center() - .gap(px(10.)) - .px(px(6.)) - .text_size(px(11.)); - let Some(band) = picked.copied() else { - return row.child("no bands — a adds one"); - }; - let step = |id: &'static str, - label: &'static str, - change: fn(&mut Band), - cx: &mut Context| { - div() - .id(id) - .flex() - .w(px(HIT_MIN)) - .h(px(HIT_MIN)) - .items_center() - .justify_center() - .rounded(px(3.)) - .bg(rgb(CHROME)) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.nudge_band(change, cx) - })) - .child(label) - }; - let number = |value: String, - ids: (&'static str, &'static str), - by: (fn(&mut Band), fn(&mut Band)), - cx: &mut Context| { - div() - .flex() - .items_center() - .gap(px(4.)) - .child(div().child(value)) - .child(step(ids.0, "−", by.0, cx)) - .child(step(ids.1, "+", by.1, cx)) - }; - row.child(format!( - "Band {} of {}", - self.eq_band + 1, - self.eq_params.bands.len() - )) - .child(number( - band_label(&band), - ("eq-freq-down", "eq-freq-up"), - ( - |b| b.freq_hz /= EQ_FREQ_STEP, - |b| b.freq_hz *= EQ_FREQ_STEP, - ), - cx, - )) - .child(number( - format!("{:+.1} dB", band.gain_db), - ("eq-gain-down", "eq-gain-up"), - (|b| b.gain_db -= EQ_STEP, |b| b.gain_db += EQ_STEP), - cx, - )) - // Q is width, so its buttons are labelled by what they *do* to the - // hump rather than by which way the number goes: a wider band is a - // smaller Q, and nobody should have to know that to use the card. - .child(number( - format!("Q {:.2}", band.q), - ("eq-q-wider", "eq-q-narrower"), - (|b| b.q /= EQ_Q_STEP, |b| b.q *= EQ_Q_STEP), - cx, - )) - .child( - div() - .id("eq-flat-band") - .flex() - .h(px(HIT_MIN)) - .px(px(8.)) - .items_center() - .rounded(px(3.)) - .bg(rgb(CHROME)) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click( - cx.listener(|this, _: &ClickEvent, _, cx| { - this.nudge_band(|b| b.gain_db = 0., cx) - }), - ) - .child("Flatten this"), - ) - } - - /// The colour card: the graded frame's histogram over a row per control, - /// each row a bar the pointer drags straight to a value -- no stepper - /// buttons, because a slider is a thing to pull, and the arrow keys still - /// move the same value for anyone not using a pointer. Same scrim, surface - /// and row shape as the other two cards, and the same plain divs, so the - /// root keeps the keyboard. - /// - /// The values are read from the project every render: what is drawn is what - /// the decoder is grading with, never a copy that could drift from it. The - /// graph above them is counted off the frame that came *back* through that - /// grade ([`histogram`]), so pulling exposure tilts it while the hand moves. - fn color_card(&self, cx: &mut Context) -> Option { - let (lane, idx) = self.color_open?; - let params = self.color_params(); - let rows: Vec<_> = COLOR_BANDS - .iter() - .enumerate() - .map(|(i, &(label, low, high))| { - let mut read = params; - let value = *band_mut(&mut read, i); - let frac = ((value - low) / (high - low)).clamp(0., 1.); - let picked = i == self.color_band; - div() - .id(("color-row", i)) - .flex() - .min_h(px(KEYS_ROW_H)) - .items_center() - .gap(px(8.)) - .px(px(6.)) - .rounded(px(3.)) - .cursor_pointer() - .when(picked, |d| d.bg(rgb(SELECTED))) - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.color_band = i; - cx.notify(); - })) - .child(div().flex_1().min_w(px(0.)).truncate().child(label)) - .child( - // The bar is 4 px to look at and a whole row to hit - // (WCAG 2.5.8), the same split the ruler makes between - // what is drawn and what is grabbed. The press is - // already the first sample of the drag, so a plain click - // sets the value it landed on. - div() - .id(("color-bar", i)) - .relative() - .w(px(COLOR_BAR_W)) - .h(px(KEYS_ROW_H)) - .flex() - .items_center() - .on_mouse_down( - MouseButton::Left, - cx.listener(move |this, event: &MouseDownEvent, _, cx| { - this.color_band = i; - this.color_dragging = true; - this.drag_color(event.position.x, true, cx); - }), - ) - .child(bounds_probe(self.color_bars[i].clone())) - .child( - div() - .w_full() - .h(px(4.)) - .rounded(px(2.)) - .bg(rgb(CHROME)) - .child( - div() - .h_full() - .w(relative(frac)) - .rounded(px(2.)) - .bg(rgb(ACCENT)), - ), - ), - ) - .child( - div() - .w(px(44.)) - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child(format!("{value:.2}")), - ) - }) - .collect(); - Some( - scrim() - .flex() - .justify_center() - .items_center() - .bg(rgba(0x101010cc)) - // Click away closes it, as on every card here. - .on_mouse_down( - MouseButton::Left, - cx.listener(|this, _: &MouseDownEvent, _, cx| { - this.close_card(); - cx.notify(); - cx.stop_propagation(); - }), - ) - .child( - div() - .w(px(COLOR_W)) - .on_mouse_down(MouseButton::Left, swallow) - .flex() - .flex_col() - .gap(px(2.)) - .p(px(12.)) - .rounded(px(6.)) - .bg(rgb(SURFACE)) - .child(div().flex_none().px(px(6.)).child(format!( - "Colour — {} clip {}", - lane.label(), - idx + 1 - ))) - .child( - div() - .flex_none() - .px(px(6.)) - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child( - "drag a bar, or ↑↓ picks one and ←→ moves it, r resets — a click away or esc closes", - ), - ) - // The frame as it is being graded, over the controls - // grading it: the three lines are what the picture is - // made of, and every sample of a drag reseeks, so they - // move with the bar under the hand. - .child( - div() - .flex_none() - .h(px(HIST_H)) - .rounded(px(3.)) - .bg(rgb(HOVER_DIM)) - .relative() - .child(hist_curves(self.histogram)), - ) - .children(rows) - .child( - div() - .id("color-reset") - .mt(px(4.)) - .flex() - .h(px(CONTROL_H)) - .items_center() - .justify_center() - .rounded(px(3.)) - .bg(rgb(SELECTED)) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - this.set_color(ColorParams::default(), cx); - })) - .child("Reset"), - ), - ), - ) - } - - /// The speed card: one bar from a quarter speed to four times it, the rates - /// people name as buttons under it, and the clip's new length in frames -- - /// which is the number a person is actually choosing. Built like the colour - /// card down to the scrim and the bar's own hit height, because it is the - /// same kind of card: one continuous value on one clip, live at the clip as - /// it moves. - /// - /// Honest about what it does: the sound is *resampled*, so the pitch goes up - /// with the rate, which is what the tape in the title means. - fn speed_card(&self, cx: &mut Context) -> Option { - let (lane, idx) = self.speed_open?; - let speed = self.card_speed(); - let session = self.session.as_ref()?; - let clip = session.lane_clips(lane).get(idx).copied()?; - let lo = f32::from(Speed::MIN.permille()); - let hi = f32::from(Speed::MAX.permille()); - let frac = ((f32::from(speed.permille()) - lo) / (hi - lo)).clamp(0., 1.); - let presets: Vec<_> = SPEED_PRESETS - .into_iter() - .map(|permille| { - let at = Speed::from_permille(permille); - div() - .id(("speed-preset", usize::from(permille))) - .flex_1() - .flex() - .h(px(CONTROL_H)) - .items_center() - .justify_center() - .rounded(px(3.)) - .bg(rgb(match at == speed { - true => SELECTED, - false => CHROME, - })) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.set_speed(at, cx); - })) - .child(format!("{at}")) - }) - .collect(); - Some( - scrim() - .flex() - .justify_center() - .items_center() - .bg(rgba(0x101010cc)) - // Click away closes it, as on every card here. - .on_mouse_down( - MouseButton::Left, - cx.listener(|this, _: &MouseDownEvent, _, cx| { - this.close_card(); - cx.notify(); - cx.stop_propagation(); - }), - ) - .child( - div() - .w(px(COLOR_W)) - .on_mouse_down(MouseButton::Left, swallow) - .flex() - .flex_col() - .gap(px(6.)) - .p(px(12.)) - .rounded(px(6.)) - .bg(rgb(SURFACE)) - .child(div().flex_none().px(px(6.)).child(format!( - "Speed (tape) — {} clip {}", - lane.label(), - idx + 1 - ))) - .child( - div() - .flex_none() - .px(px(6.)) - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child( - "drag the bar or ←→ moves it, r is 1.00x — the pitch moves with the rate; a click away or esc closes", - ), - ) - .child( - // 4 px to look at and a whole row to hit (WCAG - // 2.5.8), the split the colour sliders and the ruler - // both make. - div() - .id("speed-bar") - .relative() - .w_full() - .h(px(KEYS_ROW_H)) - .flex() - .items_center() - .cursor_pointer() - .on_mouse_down( - MouseButton::Left, - cx.listener(move |this, event: &MouseDownEvent, _, cx| { - this.speed_dragging = true; - this.drag_speed(event.position.x, true, cx); - }), - ) - .child(bounds_probe(self.speed_bar.clone())) - .child( - div() - .w_full() - .h(px(4.)) - .rounded(px(2.)) - .bg(rgb(CHROME)) - .child( - div() - .h_full() - .w(relative(frac)) - .rounded(px(2.)) - .bg(rgb(ACCENT)), - ), - ), - ) - .child(div().flex().gap(px(4.)).children(presets)) - .child( - div() - .flex_none() - .px(px(6.)) - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - // What the choice *is*, in the numbers the - // timeline is measured in: the source range - // never moves, the room it takes does. - .child(format!( - "{speed} — {} source frames over {} on the timeline ({})", - clip.len(), - clip.frames(), - timecode(f64::from(clip.frames()) / self.fps, self.fps) - )), - ), - ), - ) - } - - /// The mix card: one fader per audio track and the master limiter under - /// them -- the two settings that belong to the *sound of the whole - /// timeline* rather than to any clip on it. - /// - /// A track's fader moves everything on that track by the same amount, - /// every frequency of it: it is not the equalizer (one take, one band) and - /// it is not the volume in the panel, which is what this machine monitors - /// at and is written to no file. The limiter is over the sum of them all, - /// which is where a mix can pass full scale and where a clamp used to - /// square it off. - /// - /// The silence card's shape, down to the steppers: a row is a label, a - /// value and the two presses that move it, and the arrows pick a row and - /// move it too. The rows scroll rather than the card growing past the - /// window -- a timeline may hold more tracks than a 360 px window has room - /// for faders. - fn mix_card(&self, cx: &mut Context) -> Option { - if !self.mix_open { - return None; - } - let session = self.session.as_ref(); - let lanes = self.mix_lanes(); - let limiter = session.map_or_else(Limiter::default, PlaybackSession::limiter); - let mut rows: Vec<(String, String)> = lanes - .iter() - .map(|&lane| { - let db = session.map_or(0., |s| s.lane_gain_db(lane)); - (format!("{} plays at", lane.label()), format!("{db:+.0} dB")) - }) - .collect(); - // The ceiling in dBFS and the faders in dB, the silence card's rule: - // a ceiling is a level below full scale, a fader is a change. - rows.push(( - "Limiter ceiling".into(), - format!("{:+.0} dBFS", limiter.ceiling_db), - )); - rows.push(( - "Limiter".into(), - match limiter.on { - true => "on".into(), - false => "off".into(), - }, - )); - let rows: Vec<_> = rows - .into_iter() - .enumerate() - .map(|(n, (label, value))| { - div() - .id(("mix-row", n)) - .flex() - .flex_none() - .min_h(px(KEYS_ROW_H)) - .items_center() - .justify_between() - .px(px(6.)) - .rounded(px(3.)) - .bg(rgb(match n == self.mix_field { - true => SELECTED, - false => CHROME, - })) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.mix_field = n; - cx.notify(); - })) - .child(div().text_color(rgb(INK_DIM)).child(label)) - .child( - div() - .flex() - .items_center() - .gap(px(4.)) - .child(value) - .children([-1, 1].map(|steps: i32| { - div() - .id(("mix-step", n * 2 + usize::from(steps > 0))) - .flex_none() - .w(px(HIT_MIN)) - .h(px(KEYS_ROW_H)) - .flex() - .items_center() - .justify_center() - .rounded(px(3.)) - .bg(rgb(CHROME)) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - // Picked as well as moved, the silence - // card's rule: the row a press lands on - // is the row the arrows carry on from. - this.mix_field = n; - this.nudge_mix(steps, cx); - })) - .child(match steps > 0 { - true => "+", - false => "−", - }) - })), - ) - }) - .collect(); - Some( - scrim() - .flex() - .justify_center() - .items_center() - .bg(rgba(0x101010cc)) - // Click away closes it, as on every card here. - .on_mouse_down( - MouseButton::Left, - cx.listener(|this, _: &MouseDownEvent, _, cx| { - this.close_card(); - cx.notify(); - cx.stop_propagation(); - }), - ) - .child( - div() - .w(px(COLOR_W)) - .on_mouse_down(MouseButton::Left, swallow) - .max_h(px(360. - 24.)) - .flex() - .flex_col() - .gap(px(6.)) - .p(px(12.)) - .rounded(px(6.)) - .bg(rgb(SURFACE)) - .child( - div() - .flex_none() - .px(px(6.)) - .child("Mix — track volumes and the master limiter"), - ) - .child( - div() - .flex_none() - .px(px(6.)) - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child( - "− and + move a setting, or ↑↓ picks one and ←→ moves it (hold to run it) — a track fader moves everything on that track; a click away or esc closes", - ), - ) - .child( - div() - .id("mix-rows") - .flex() - .flex_col() - .gap(px(6.)) - .overflow_y_scroll() - .children(rows), - ) - .child( - div() - .flex_none() - .px(px(6.)) - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - // What the choice *is*: the limiter's own line, - // because "on" alone says nothing about what it - // does to a mix that never reaches the ceiling. - .child(match limiter.on { - true => format!( - "the mix is held under {:+.0} dBFS — quieter passages are untouched", - limiter.ceiling_db - ), - false => "the limiter is out of circuit — a hot mix clips at full scale".to_string(), - }), - ), - ), - ) - } - - /// The silence card: what the scan is looking for, what it found, and the - /// two things that can be done about it. - /// - /// Its scrim is the lightest of the cards' on purpose. Every other card is - /// about the clip it names and can black the timeline out; this one is - /// *about* the timeline -- the marks under it are the whole preview -- so - /// the bed stays readable and the card sits up in the picture area rather - /// than over the lanes. - fn silence_card(&self, cx: &mut Context) -> Option { - let (lane, idx) = self.silence_open?; - let cfg = self.silence; - // The unit is a label, never a conversion: the threshold is a level - // below full scale whichever of the two the row says (`silence_dbfs`). - let unit = match self.silence_dbfs { - true => "dBFS", - false => "dB", - }; - let rows = [ - ("Apply to", self.silence_scope.label(&self.silence_lanes())), - ( - "Silence is under", - format!("{:.0} {unit}", cfg.threshold_db), - ), - ("Level read in", format!("{unit} (0 = full scale)")), - ( - "Forgive quiet shorter than", - format!("{:.2} s", cfg.min_silence), - ), - ( - "Keep either side of speech", - format!("{:.2} s", cfg.padding), - ), - ( - "Swallow kept slivers under", - format!("{:.2} s", cfg.min_keep), - ), - ("Speed-up plays at", format!("{}", self.silence_factor)), - ]; - let found = self.silence_marks.len(); - let secs = - f64::from(self.silence_marks.iter().map(|&(_, len)| len).sum::()) / self.fps; - // The line under the rows: where a scan still running has got to -- a - // card is up from the frame it is asked for, numbers or no numbers -- - // or what the settings found in levels already read. - let status = match &self.silence_scan { - Some(scan) => silence_line( - scan.seen as f32 / 10., - scan.progress.total.load(std::sync::atomic::Ordering::Relaxed) as f32 / 10., - scan.started.elapsed().as_secs_f32(), - scan.since.elapsed().as_secs_f32(), - ), - None => match found { - 0 => "nothing quiet enough for long enough".to_string(), - 1 => format!("1 silence, {}", secs_label(secs)), - n => format!("{n} silences, {}", secs_label(secs)), - }, - }; - let rows: Vec<_> = rows - .into_iter() - .enumerate() - .map(|(n, (label, value))| { - div() - .id(("silence-row", n)) - .flex() - .min_h(px(KEYS_ROW_H)) - .items_center() - .justify_between() - .px(px(6.)) - .rounded(px(3.)) - .bg(rgb(match n == self.silence_field { - true => SELECTED, - false => CHROME, - })) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.silence_field = n; - cx.notify(); - })) - .child(div().text_color(rgb(INK_DIM)).child(label)) - // The value and the two steps that move it. Every other - // card has something to drag or press; this one had the - // arrow keys and nothing else, so a row was a setting a - // pointer could pick but never change. One press each, the - // same call the arrows make -- the hold-to-run is the - // keyboard's own and is not a thing a button has. - .child( - div() - .flex() - .items_center() - .gap(px(4.)) - .child(value) - .children([-1, 1].map(|steps: i32| { - div() - .id(("silence-step", n * 2 + usize::from(steps > 0))) - .flex_none() - .w(px(HIT_MIN)) - .h(px(KEYS_ROW_H)) - .flex() - .items_center() - .justify_center() - .rounded(px(3.)) - .bg(rgb(CHROME)) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - // Picked as well as moved: the row a - // press lands on is the row the arrows - // carry on from. - this.silence_field = n; - this.nudge_silence(steps); - cx.notify(); - })) - .child(match steps > 0 { - true => "+", - false => "−", - }) - })), - ) - }) - .collect(); - // The two buttons the ask names, side by side: a mode toggle would hide - // one of them behind the other, and there are only two. - let button = |n: usize, text: String, act: fn(&mut Self, &mut Context)| { - div() - .id(("silence-apply", n)) - .flex_1() - .flex() - .min_h(px(KEYS_ROW_H)) - .items_center() - .justify_center() - .rounded(px(3.)) - .bg(rgb(match found { - 0 => CHROME, - _ => SELECTED, - })) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| act(this, cx))) - .child(text) - }; - Some( - scrim() - .flex() - .justify_center() - .items_start() - .pt(px(HEADER_H + 8.)) - // Light enough to read the lanes and the marks on them through: - // the preview is the point of this card. - .bg(rgba(0x10101055)) - // Click away closes it, as on every card here -- and the marks - // go with it, which is what makes this one a call and not a flag. - .on_mouse_down( - MouseButton::Left, - cx.listener(|this, _: &MouseDownEvent, _, cx| { - this.close_card(); - cx.notify(); - cx.stop_propagation(); - }), - ) - .child( - div() - .w(px(COLOR_W)) - .on_mouse_down(MouseButton::Left, swallow) - .flex() - .flex_col() - .gap(px(6.)) - .p(px(12.)) - .rounded(px(6.)) - .bg(rgb(SURFACE)) - .child(div().flex_none().px(px(6.)).child(format!( - "Silences — {} clip {}", - lane.label(), - idx + 1 - ))) - .child( - div() - .flex_none() - .px(px(6.)) - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child( - "− and + move a setting, or ↑↓ picks one and ←→ moves it (hold to run it) — the marks on the lane are what would go; a click away or esc closes", - ), - ) - .children(rows) - .child( - div() - .flex_none() - .px(px(6.)) - .text_color(rgb(match (&self.silence_scan, found) { - (None, 1..) => ACCENT, - _ => INK_DIM, - })) - .child(status), - ) - .child(div().flex().gap(px(4.)).children([ - button(0, "Cut them out (enter)".into(), Self::cut_silences), - button( - 1, - format!("Play them at {} (f)", self.silence_factor), - Self::speed_silences, - ), - ])), - ), - ) - } - - /// The menu a right-click on a library row opens: what can be done with the - /// *file* rather than with a clip of it, and a turn-over side saying what - /// that file is. Built like [`Player::context_card`] down to the scrim, the - /// row height and the clamp, because it is the same menu on the other panel - /// -- a click away or any stroke closes it. - fn library_card( - &self, - viewport: Size, - cx: &mut Context, - ) -> Option { - let menu = self.library_menu.clone()?; - let path = menu.path.clone(); - let row = |n: usize| { - div() - .id(("library-menu", n)) - .flex() - .min_h(px(MENU_ROW_H)) - .items_center() - .justify_between() - .gap(px(12.)) - .px(px(6.)) - .rounded(px(3.)) - }; - let mut rows: Vec = Vec::new(); - // What every item of this menu is answered from, read once. - let ctx = self.row_ctx(&path, menu.stream); - if menu.details { - // What the library knows about this row and nothing probed for the - // card: the streams table is filled once per file at import. - let info = self - .streams - .get(&path) - .and_then(|of_file| of_file.iter().find(|s| s.index == menu.stream)); - let frames = self - .session - .as_ref() - .map_or(0, |session| session.file_frames(&path)); - // How many clips play from this exact row -- the number that - // decides whether Remove is refused, so the card answers the - // question the refusal would otherwise raise. - let placed = ctx.placed; - // A still is described by what it has -- a picture, a size, and a - // longest it may be held for -- where a media file is described by - // its streams and its length. Same card, the rows that mean - // something for this kind of source. - let image = engine::is_image(&path); - let kind = match self.sizes.get(&path).copied().flatten() { - Some((w, h)) => format!("still image · {w}x{h}"), - None => "still image".to_string(), - }; - for (label, value) in [ - ("File", file_name(&path)), - ("Path", path.display().to_string()), - match image { - true => ("Picture", kind), - false => ( - "Audio", - info.map_or_else(|| "no track of its own".to_string(), stream_detail), - ), - }, - ( - "Bitrate", - bitrate_detail( - self.bitrates.get(&path).copied().flatten(), - self.streams.get(&path).map_or(0, Vec::len), - ), - ), - match image { - true => ( - "Longest hold", - timecode(f64::from(frames) / self.fps, self.fps), - ), - false => ("Length", timecode(f64::from(frames) / self.fps, self.fps)), - }, - ("On the timeline", format!("{placed} clips")), - ] { - rows.push( - row(rows.len()) - .child(label) - .child( - div() - .min_w(px(0.)) - .truncate() - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child(value), - ) - .into_any_element(), - ); - } - } else { - // The oracle's list, exactly as the clip menu takes its rows from - // `menu_items`: an item that means nothing for the file that was - // right-clicked is not a row, and one this moment refuses is drawn - // dimmed and says why in place of its hint. - for item in row_items(ctx) { - let refusal = row_enable(item, ctx); - let enabled = refusal.yes(); - rows.push( - row(rows.len()) - .child(item.label()) - .child( - div() - .min_w(px(0.)) - .truncate() - .text_color(rgb(INK_DIM)) - .child(refusal.why().unwrap_or_else(|| item.hint())), - ) - .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) - .when(enabled, |d| { - d.cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.act_on_row(item, cx); - })) - }) - .into_any_element(), - ); - } - } - // Placed by the height it is drawn to, and drawn to what the window has - // room for -- the clip menu's rule, one function for all three. - let list_h = menu_rows_h(rows.len(), viewport); - let (x, y) = menu_at(menu.at, viewport, MENU_PAD * 2. + list_h); - let full: SharedString = path.display().to_string().into(); - Some( - scrim() - .on_mouse_down( - MouseButton::Left, - cx.listener(|this, _: &MouseDownEvent, _, cx| { - this.library_menu = None; - cx.notify(); - cx.stop_propagation(); - }), - ) - .on_mouse_down( - MouseButton::Right, - cx.listener(|this, _: &MouseDownEvent, _, cx| { - this.library_menu = None; - cx.notify(); - cx.stop_propagation(); - }), - ) - .child( - div() - .id("library-menu-card") - .absolute() - .left(px(x)) - .top(px(y)) - .w(px(MENU_W)) - .flex() - .flex_col() - .p(px(MENU_PAD)) - .rounded(px(6.)) - .bg(rgb(SURFACE)) - // Painted after the scrim, so this listener runs first - // and a press meant for an item never closes the menu - // out from under its own click (`context_card`). - .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| { - cx.stop_propagation() - }) - .on_mouse_down(MouseButton::Right, |_: &MouseDownEvent, _, cx| { - cx.stop_propagation() - }) - .when(menu.details, |d| { - d.tooltip(move |_, cx| cx.new(|_| Tip(full.clone())).into()) - }) - // Scrolls where the window has no room for the list, - // like the clip menu's -- an item hanging off the bottom - // edge is an item nobody can click. - .child( - div() - .id("library-menu-rows") - .flex() - .flex_col() - .max_h(px(list_h)) - .overflow_y_scroll() - .children(rows), - ), - ), - ) - } - - /// The menu a right-click on a clip opens: what that clip can be given, - /// each item beside the stroke that does the very same thing, and a - /// turn-over side that says what the clip *is*. An item that would do - /// nothing where the playhead is standing is dimmed and takes no click - /// rather than disappearing, so the menu reads the same every time. - /// - /// Every item goes through [`Player::act`], the table the key handler uses: - /// an item is its stroke, asked for with the mouse. Plain divs like the - /// rest of this window, so the root keeps the keyboard and escape still - /// reaches the handler that closes this. - fn context_card( - &self, - viewport: Size, - cx: &mut Context, - ) -> Option { - let menu = self.context_menu?; - let session = self.session.as_ref()?; - let clip = *session.lane_clips(menu.lane).get(menu.idx)?; - let source = session.sources().get(clip.source).cloned()?; - let secs = |frames: u32| timecode(f64::from(frames) / self.fps, self.fps); - let row = |n: usize| { - div() - .id(("menu", n)) - .flex() - // The floor, not the height: a long label wrapping must not - // paint over the item under it. - .min_h(px(MENU_ROW_H)) - .items_center() - .justify_between() - .gap(px(12.)) - .px(px(6.)) - .rounded(px(3.)) - }; - let mut rows: Vec = Vec::new(); - if menu.details { - // Read-only, so no ids and no hover: this side is a card, not a - // list of things to click. Each value is one truncated line, which - // is what keeps the height below the one the clamp was given. - for (label, value) in [ - ("File", file_name(&source.path)), - ("Path", source.path.display().to_string()), - ( - "Source range", - format!("{} – {}", secs(clip.in_frame), secs(clip.out_frame)), - ), - // How long it is *where it sits*, which its rate decides -- and - // the rate itself beside it, because a clip half its source's - // length could be either a trim or a 2x. - ("This clip", secs(clip.frames())), - ("Speed", format!("{} (tape)", clip.speed)), - ("Source duration", secs(session.file_frames(&source.path))), - ( - "Bitrate", - bitrate_detail( - self.bitrates.get(&source.path).copied().flatten(), - self.streams.get(&source.path).map_or(0, Vec::len), - ), - ), - ] { - rows.push( - row(rows.len()) - .child(label) - .child( - div() - .min_w(px(0.)) - .truncate() - // A size smaller than the labels: a timecode - // pair is 25 characters and has to fit beside - // its label inside `MENU_W`. - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child(value), - ) - .into_any_element(), - ); - } - } else { - // A grade on a waveform, an equalizer on a picture, a silence scan - // on a still: things that do not exist for what was right-clicked, - // so the menu is the list of what this clip can do rather than the - // registry with most of it struck through. One filter, in - // `menu_items`, so there is no second answer to keep in step. The - // state refusals below stay, dimmed and saying why -- the next - // click of the playhead lights them. - let ctx = self.ctx(Some((menu.lane, menu.idx))); - for action in menu_items(ctx) { - // The registry's own answer, the same one the actions card - // dims a row with -- and a row that takes no click says *why* - // rather than printing a stroke that would do nothing. - let refusal = enable(action, ctx); - let enabled = refusal.yes(); - // The one item that is not about this clip says so, and says it - // here rather than in the registry: the stroke is global too, - // but its row in the keys menu is not sitting on a clip. - let label = if matches!(action, ActionId::ToggleMute | ActionId::Paste) { - format!("{} (global)", action.label()) - } else { - action.label().to_string() - }; - rows.push( - row(rows.len()) - .child(label) - .child(match refusal.why() { - // One truncated line, like the details side: a - // reason that wrapped would make the card taller - // than the height `menu_at` placed it by. - Some(why) => div() - .min_w(px(0.)) - .truncate() - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child(why), - None => div() - .text_color(rgb(INK_DIM)) - .child(self.keymap.display(action)), - }) - .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) - .when(enabled, |d| { - d.cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(move |this, event: &ClickEvent, _, cx| { - // Closed first: the action moves the very - // indices this menu is holding. - this.context_menu = None; - // The one item that is a *choice* and not a - // doing: four policies, so the pointer gets - // the list of them on this clip rather than - // the next one stepped to behind the click. - // The stroke still steps -- same door. - if action == ActionId::Fit { - this.open_picker( - Pick::Fit(menu.lane, menu.idx), - event.position(), - cx, - ); - } else { - this.act(action, cx); - } - })) - }) - .into_any_element(), - ); - } - rows.push( - row(rows.len()) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { - if let Some(menu) = &mut this.context_menu { - menu.details = true; - } - cx.notify(); - })) - .child("Properties") - // No stroke reaches this one, and a blank column would read - // as one that was forgotten. - .child(div().text_color(rgb(INK_DIM)).child("…")) - .into_any_element(), - ); - } - // The height the card is *placed* by and the height its list is drawn - // to are one number: placed by a taller one, the card would hang off the - // window's floor -- the very thing the clamp is for. - let list_h = menu_rows_h(rows.len(), viewport); - let (x, y) = menu_at(menu.at, viewport, MENU_PAD * 2. + list_h); - let full: SharedString = source.path.display().to_string().into(); - Some( - scrim() - // Click away closes it, either button, and the press is - // swallowed so nothing under the menu also takes it. No tint, - // unlike the modal cards: the timeline this menu is about has - // to stay readable behind it. - .on_mouse_down( - MouseButton::Left, - cx.listener(|this, _: &MouseDownEvent, _, cx| { - this.context_menu = None; - cx.notify(); - cx.stop_propagation(); - }), - ) - .on_mouse_down( - MouseButton::Right, - cx.listener(|this, _: &MouseDownEvent, _, cx| { - this.context_menu = None; - cx.notify(); - cx.stop_propagation(); - }), - ) - .child( - div() - // Only so the details side can carry a tooltip, which - // gpui gives to identified elements alone. - .id("menu-card") - .absolute() - .left(px(x)) - .top(px(y)) - .w(px(MENU_W)) - .flex() - .flex_col() - .p(px(MENU_PAD)) - .rounded(px(6.)) - .bg(rgb(SURFACE)) - // Painted after the scrim, so this listener runs first - // (gpui bubbles mouse events in reverse, window.rs:3705) - // and a press meant for an item never closes the menu - // out from under its own click. - .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| { - cx.stop_propagation() - }) - .on_mouse_down(MouseButton::Right, |_: &MouseDownEvent, _, cx| { - cx.stop_propagation() - }) - // The one value the details side has to truncate. - .when(menu.details, |d| { - d.tooltip(move |_, cx| cx.new(|_| Tip(full.clone())).into()) - }) - // The list scrolls where the card would otherwise grow - // past the window's floor -- an item hanging off the - // bottom edge is an item nobody can click. - .child( - div() - .id("menu-rows") - .flex() - .flex_col() - .max_h(px(list_h)) - .overflow_y_scroll() - .children(rows), - ), - ), - ) - } - - /// The open choice list: every value of one enumerated setting at once, the - /// one in force marked, and a click on any of them picks *that* one -- what - /// a button stepping one value on per click could never say. Built on the - /// clip menu's machinery down to the scrim, the placement and the scroll - /// cap, so it hangs and closes exactly as the menus do and fits the same - /// 640x360 floor. The stroke for the setting is untouched: this is the - /// pointer's door to it, not a second setting. - fn picker_card( - &self, - viewport: Size, - cx: &mut Context, - ) -> Option { - let picker = self.picker?; - let rows: Vec = self - .choices(picker.of) - .into_iter() - .enumerate() - .map(|(n, (choice, label, detail, picked))| { - div() - .id(("picker-row", n)) - .flex() - // The floor, not the height, and `HIT_MIN` of it: a row of a - // list is a click target like every other one here (WCAG - // 2.5.8). - .min_h(px(MENU_ROW_H)) - .items_center() - .justify_between() - .gap(px(12.)) - .px(px(6.)) - .rounded(px(3.)) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - // The mark is a glyph as well as a highlight, like the - // export card's rows: a background alone is gone under a - // hover and invisible to anyone who cannot tell the two - // greys apart (WCAG 1.4.1). - .when(picked, |d| d.bg(rgb(SELECTED))) - .child( - div() - .flex() - .flex_none() - .items_center() - .gap(px(8.)) - .child(div().w(px(10.)).child(match picked { - true => "✓", - false => " ", - })) - .child(label), - ) - .child( - div() - .min_w(px(0.)) - .truncate() - .text_size(px(11.)) - // On the picked row the dim ink sits on the - // highlight, where it is only 3.3:1 (WCAG 1.4.3). - .text_color(rgb(match picked { - true => INK, - false => INK_DIM, - })) - .child(detail), - ) - .on_click( - cx.listener(move |this, _: &ClickEvent, _, cx| this.choose(choice, cx)), - ) - .into_any_element() - }) - .collect(); - // The window's own room, and the list scrolls only where the window has - // none -- the clip menu's rule, one function for both. - let list_h = menu_rows_h(rows.len(), viewport); - let (x, y) = menu_at(picker.at, viewport, MENU_PAD * 2. + list_h); - Some( - scrim() - // Click away closes it, either button, swallowed so nothing - // under the list also takes the press -- the clip menu's rule. - .on_mouse_down( - MouseButton::Left, - cx.listener(|this, _: &MouseDownEvent, _, cx| { - this.picker = None; - cx.notify(); - cx.stop_propagation(); - }), - ) - .on_mouse_down( - MouseButton::Right, - cx.listener(|this, _: &MouseDownEvent, _, cx| { - this.picker = None; - cx.notify(); - cx.stop_propagation(); - }), - ) - .child( - div() - .id("picker-card") - .absolute() - .left(px(x)) - .top(px(y)) - .w(px(MENU_W)) - .flex() - .flex_col() - .p(px(MENU_PAD)) - .rounded(px(6.)) - .bg(rgb(SURFACE)) - // Painted after the scrim, so this listener runs first - // and a press meant for a row never closes the list out - // from under its own click (`context_card`). - .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| { - cx.stop_propagation() - }) - .on_mouse_down(MouseButton::Right, |_: &MouseDownEvent, _, cx| { - cx.stop_propagation() - }) - .child( - div() - .id("picker-rows") - .flex() - .flex_col() - .max_h(px(list_h)) - .overflow_y_scroll() - .children(rows), - ), - ), - ) - } - - /// One lane of the edit list made visible: a fixed header saying which lane - /// it is, then a bed with a box per clip, placed and sized by its share of - /// the timeline. A cut adds a box without moving anything, a delete closes - /// the hole, a lift leaves one. A clip too narrow for its name says what it - /// 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. - fn subtitle_strip(&self, filled: f32) -> 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(SURFACE); - // 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(INK_DIM)) - .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(LETTERBOX)) - .overflow_hidden() - .children(cues.into_iter().map(|(left, width)| { - div() - .absolute() - .top_0() - .h_full() - .left(px(left)) - .w(px(width)) - .rounded(px(2.)) - .bg(rgb(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(1.)) - .bg(rgb(ACCENT)), - ), - ), - ) - } - - fn lane_row( - &self, - lane: Lane, - // Where the playhead is on the bed, in pixels: worked out once by the - // panel so the ruler's line and every lane's draw the same one. - filled: f32, - cx: &mut Context, - // Borrows nothing it was given (`use<>`): the rows are built one after - // another into a list, and a row still holding `cx` would be the only - // one that could be built. - ) -> impl IntoElement + use<> { - // The mapping, copied out once: every box in the row is placed through - // it, so all of them move together when it does. No bed width is needed - // to place them any more -- a second is so many pixels wherever it is. - let scale = self.scale; - // How much bed there is to be seen on, measured off the ruler's own - // probe like every other question about it: what a box draws *inside* - // itself is clipped to this ([`visible_slice`]), because a box at a deep - // zoom is far wider than the strip it is being watched through. - let bed = f32::from(self.ruler.get().size.width); - // Where the snap line stands, in the same pixels every box is placed - // through -- and only while a gesture is actually live: gpui drops a - // drag without telling anyone, so this asks whether one is in flight - // (`App::has_active_drag`) rather than remembering that one was. - let cue = self - .snap_cue - .filter(|_| self.trim.is_some() || cx.has_active_drag()) - .map(|frame| scale.px_at(f64::from(frame) / self.fps)); - // The shadow, on the one lane the pointer is over -- and, like the line, - // only while the drag that asked for it is still in flight. - let ghost = self - .ghost - .filter(|g| g.lane == lane && cx.has_active_drag()); - let clips = self - .session - .as_ref() - .map_or(&[][..], |session| session.lane_clips(lane)); - // The group ids some *other* lane carries: a clip whose id is in here - // has a half elsewhere, and one whose is not is a detached half however - // many lanes there are. - let others: Vec = self.session.as_ref().map_or_else(Vec::new, |session| { - session - .lanes() - .into_iter() - .filter(|&other| other != lane) - .flat_map(|other| session.lane_clips(other)) - .filter_map(|clip| clip.link) - .collect() - }); - let name = lane.label(); - let row_id: SharedString = format!("{name}-clip").into(); - let remove_id: SharedString = format!("{name}-remove").into(); - let remove_tip: SharedString = format!( - "Remove {name} — it must be empty first, and {} brings it back", - self.keymap.display(ActionId::Undo) - ) - .into(); - let sources = self - .session - .as_ref() - .map_or(&[][..], PlaybackSession::sources); - let (sel, sel_link) = (self.selected, self.selected_link()); - let audio = lane.kind == LaneKind::Audio; - // 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 - // press opens the mix card on this very track. - let gain_db = self - .session - .as_ref() - .map_or(0., |session| session.lane_gain_db(lane)); - let gain_tip: SharedString = format!( - "{name} plays at {gain_db:+.0} dB — opens the mix ({}); the whole track, every frequency, unlike the equalizer", - self.keymap.display(ActionId::Mix) - ) - .into(); - let tip: SharedString = format!( - "Select (or {} under the playhead, {}/{} along the lane) — drag it to move it, an end to trim, {} removes the take, {} leaves a gap, {} rejoins a cut", - self.keymap.display(ActionId::Select), - self.keymap.display(ActionId::SelectPrev), - self.keymap.display(ActionId::SelectNext), - self.keymap.display(ActionId::Delete), - self.keymap.display(ActionId::Lift), - self.keymap.display(ActionId::Regroup) - ) - .into(); - div() - .flex_none() - .h(px(LANE_H)) - .flex() - .gap(px(HEADER_GAP)) - // The fixed column the ruler above is offset by as well. Full lane - // height, so it reads as the bed continuing rather than as a chip. - .child( - div() - .flex_none() - .w(px(HEADER_W)) - .h_full() - .flex() - .flex_col() - .items_center() - .justify_center() - .rounded(px(3.)) - .bg(rgb(SURFACE)) - .text_size(px(11.)) - .text_color(rgb(INK_DIM)) - .child(match audio { - // A button, not a label: the one setting a track has of - // its own used to be reachable from nowhere. - true => div() - .id(("mix-lane", lane.ord)) - .flex_1() - .w_full() - .flex() - .items_center() - .justify_center() - .rounded(px(3.)) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .tooltip(move |_, cx| cx.new(|_| Tip(gain_tip.clone())).into()) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.open_mix(Some(lane), cx) - })) - .child(match gain_db == 0. { - true => name.clone(), - false => format!("{name} {gain_db:+.0}"), - }) - .into_any_element(), - false => div() - .flex_1() - .flex() - .items_center() - .child(name.clone()) - .into_any_element(), - }) - // The one thing a header does: take this track away again. - // A `HIT_MIN` target rather than a glyph-sized one, and it - // stays put on a track holding clips instead of hiding -- - // the refusal names them, and a control that vanishes - // teaches nothing. - .child( - div() - .id(remove_id) - .flex_none() - .w_full() - .h(px(HIT_MIN)) - .flex() - .items_center() - .justify_center() - .rounded(px(3.)) - .cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .tooltip(move |_, cx| cx.new(|_| Tip(remove_tip.clone())).into()) - .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { - this.remove_lane(lane, cx) - })) - .child("×"), - ), - ) - .child( - // Clips are placed at their own start rather than queued edge - // to edge: a lift leaves a hole in the lane, and the bare bed - // showing through it *is* how a gap looks. - div() - .relative() - .flex_1() - .min_w(px(0.)) - .h_full() - .rounded(px(3.)) - .bg(rgb(LETTERBOX)) - .overflow_hidden() - // A library row let go over a lane is the same insert the - // Add button makes, through the same call -- but where the - // pointer let it go, not at the playhead: a hand that - // carried a file to a place on the bed named that place. - // gpui hands a drop no event, so the pointer is read off - // the window, which took it from the release that fired - // this (gpui window.rs:3602). - .on_drop(cx.listener(move |this, drag: &AssetDrag, window, cx| { - // Onto the edges near it, exactly as a clip carried by - // hand lands: the line drawn while it was in flight is - // the frame it goes down on. - let at = this.place_frame(window.mouse_position().x).0; - this.insert_source(&drag.0.clone(), drag.1, Some(lane), Some(at), cx) - })) - .drag_over::(|s, _, _, _| s.bg(rgb(HOVER_DIM))) - // The shadow of the row in flight, drawn by the lane the - // pointer is inside: `on_drag_move` fires on every painted - // element while a drag of its type is live, wherever the - // pointer is, and hands each one its own box -- which is how - // a lane knows the pointer is over *it* (gpui div.rs:282). - // The root cleared it a moment ago, so exactly one lane - // draws one. - .on_drag_move(cx.listener( - move |this, event: &DragMoveEvent, _, cx| { - if !event.bounds.contains(&event.event.position) { - return; - } - let path = event.drag(cx).0.clone(); - this.preview_ghost_asset(&path, lane, event.event.position.x, cx); - }, - )) - // ...and a clip let go over a lane lands the same way: on - // the track it was dropped on, at the frame it was carried - // to -- its own included, which is the drag that moves a - // take along its track. - .on_drop(cx.listener(move |this, drag: &ClipDrag, window, cx| { - // Against the lane as it is *now* ([`Player::dragged`]), - // and then snapped by `move_clip` like any other drop: - // which clip is being moved and where it lands are two - // questions, and this is the first one. - let Some(idx) = this.dragged(drag) else { - return; - }; - this.move_clip(drag.lane, idx, lane, window.mouse_position().x, cx) - })) - .drag_over::(|s, _, _, _| s.bg(rgb(HOVER_DIM))) - // ...and the same shadow for the clip in the hand, seated on - // this lane when the pointer is inside it. - .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(&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 - // clip, never the preview an edge drag is drawing. - let placed = *clip; - // What a drag on an edge is showing, which is the clip - // itself while nothing is being dragged. - let clip = &self.trimmed(lane, i, *clip); - // Its *timeline* length, which a speed halves or - // quadruples: the box is as wide as the clip is long - // where it sits, not as long as the source it reads. - let (start, len) = ( - f64::from(clip.start) / self.fps, - f64::from(clip.frames()) / self.fps, - ); - let on = marked((lane, i), clip.link, sel, sel_link); - // A group with a half in the other lane wears its tint; - // one without is outlined, so a detached half is visible - // as detached before anyone clicks it. - let grouped = clip.link.is_some_and(|link| others.contains(&link)); - // Tinted by *file*, not by source entry: two audio - // streams of one file are two sources, and the library - // gives them one swatch because they are one file. - let tint = self.clip_tint(clip.source); - // What the clip is worth in pixels, and how wide its box - // is drawn -- the two part company on a take too short - // to be hit at this zoom ([`clip_width`]). - let span = scale.width_px(len); - let width = clip_width(span); - let left = scale.px_at(start); - // The slice of this box that is on the bed: where its - // name, its badge and its waveform go, so none of the - // three is drawn out at a zoomed-in box's own edges. - let (vis_x, vis_w) = visible_slice(left, width, bed); - let label = sources.get(clip.source).map(|s| file_name(&s.path)); - let wave = sources - .get(clip.source) - .and_then(|s| self.waves.get(&(s.path.clone(), s.audio_stream))) - .cloned(); - // The source seconds that slice plays -- not the clip's - // whole range: the envelope is drawn for the part of the - // box that can be seen, at the resolution of the pixels - // it actually has, and never one column per two pixels - // of a box millions of pixels wide. - let along = |x: f32| match width > 0. { - true => { - f64::from(clip.in_frame) - + f64::from(clip.out_frame - clip.in_frame) - * f64::from(x / width) - } - false => f64::from(clip.in_frame), - }; - let (from, to) = (along(vis_x) / self.fps, along(vis_x + vis_w) / self.fps); - let tip = tip.clone(); - // What the pointer carries on the way to another lane: - // the file the box is showing, the same ghost a library - // row makes. A box too narrow for its own label still - // says what is moving. - let ghost: SharedString = - label.clone().unwrap_or_else(|| lane.label()).into(); - // Its head in frames, for the press below: the `start` - // above is the same moment in seconds, which is what - // the box is *drawn* from. - let head = clip.start; - div() - // Named per lane: two rows numbering their clips - // from zero would hand gpui the same id twice. - .id((row_id.clone(), i)) - .absolute() - .top_0() - .h_full() - // Negative once the clip's head has been scrolled - // off the left edge: the bed clips what hangs out - // of it, so a half-visible clip is drawn as the - // half of itself that is on screen. - .left(px(left)) - .w(px(width)) - .overflow_hidden() - .rounded(px(3.)) - .border_1() - .border_color(rgb(if on { - ACCENT - } else if grouped { - tint - } else { - INK_DIM - })) - .bg(rgb(if on { SELECTED } else { tint })) - .cursor_pointer() - .hover(|s| s.border_color(rgb(ACCENT))) - .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into()) - // Dragged, it *moves*: to the frame it was let go on - // and to the lane it was let go over. The click that - // starts the drag still selects, so picking a clip - // up and putting it back down where it was is - // exactly a click. - .on_drag( - ClipDrag { - lane, - idx: i, - clip: 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 of it, - // for the drag this press may become: the - // clip has to move with the pointer rather - // than jump its head under it. - this.grab = - this.frame_under(event.position.x).saturating_sub(head); - this.select((lane, i), cx); - }), - ) - // The right button selects exactly as the left one - // does -- the menu acts on the clip it names, so - // opening one has to pick it -- and then hangs the - // menu at the pointer. - .on_mouse_down( - MouseButton::Right, - cx.listener(move |this, event: &MouseDownEvent, _, cx| { - this.open_menu(lane, i, event.position, cx); - }), - ) - // The two strips a drag *lengthens* the clip by, - // one at each end. They occlude the box behind - // them, which is what keeps one gesture one thing: - // a press here trims, a press anywhere else on the - // box still starts the move to another lane. - // - // Asked of the clip's own width and not of the box's - // floor: a take drawn at `HIT_MIN` because it is - // shorter than that has no *pixels* to trim by -- one - // would move it by seconds -- so it keeps all of its - // padded box as a body to select and drag by, and is - // trimmed after zooming in, exactly as [`trims`] says. - .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))) - .on_mouse_down( - MouseButton::Left, - cx.listener( - move |this, _: &MouseDownEvent, _, cx| { - this.start_trim(lane, i, edge, cx); - }, - ), - ) - // Occluded, so the box's own right-button - // listener never fires here: the menu is - // the same menu, opened by the same call. - .on_mouse_down( - MouseButton::Right, - cx.listener( - move |this, event: &MouseDownEvent, _, cx| { - this.open_menu(lane, i, event.position, cx); - }, - ), - ); - zone = match edge { - Edge::Start => zone.left_0(), - Edge::End => zone.right_0(), - }; - zone - }), - ) - // Under the label row, never through it. - .children(wave.filter(|_| audio && vis_w > 0.).and_then(|wave| { - let inner: AnyElement = match wave { - Wave::Peaks(peaks) => { - waveform(peaks, from, to).into_any_element() - } - // A bed while the decode runs, and dimmer - // than any waveform is drawn: a flat - // `INK_DIM` line here would be the shape a - // silent file makes, which this file is not - // known to be yet. - Wave::Loading => div() - .h_full() - .flex() - .items_center() - .child(div().w_full().h(px(1.)).bg(rgb(HOVER))) - .into_any_element(), - // No audio track: nothing, never a fake. - Wave::Silent => return None, - // Could not be read: a band that says so in - // words, because the empty band a silent - // file draws would claim this file has no - // sound. The reason itself went to the log. - Wave::Failed => div() - .h_full() - .flex() - .items_center() - .justify_center() - .truncate() - .text_size(px(9.)) - .text_color(rgb(INK_DIM)) - .child("audio unreadable") - .into_any_element(), - }; - Some( - div() - .absolute() - .left(px(vis_x)) - .w(px(vis_w)) - .top(px(LABEL_H)) - .bottom_0() - .child(inner), - ) - })) - // A speeded clip says so on the box, in the corner - // the label does not reach: the box's width alone - // cannot say whether a short clip is a trim or a - // clip at 4x, and that is the difference between a - // cut and a re-time. - // Against the right edge of what is *visible* of the - // box, not of the box: zoomed in, the box's own - // right edge is off the screen and the badge with - // it, which is a clip that stops saying it is - // speeded exactly when it is being looked at - // closely. - .when(!clip.speed.is_normal() && vis_w > 0., |d| { - d.child( - div() - .absolute() - .top_0() - .left(px(vis_x)) - .w(px(vis_w)) - .flex() - .justify_end() - .overflow_hidden() - .child( - div() - .flex_none() - .px(px(3.)) - .rounded(px(3.)) - .bg(rgb(ACCENT)) - .text_size(px(9.)) - .text_color(rgb(SURFACE)) - .child(format!("{}", clip.speed)), - ), - ) - }) - // ...and the name sits at the left edge of the same - // slice, for the same reason: a box scrolled half - // off names itself on the half that is on screen. - .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), - ) - }) - })) - // 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 - // lane whose sound was read. Drawn before anything is cut, - // and replaced -- never stacked -- by every re-run. - .children( - self.silence_marks - .iter() - .filter(|_| self.silence_open.is_some_and(|(on, _)| on == lane)) - .map(|&(at, len)| { - div() - .absolute() - .top_0() - .h_full() - .left(px(scale.px_at(f64::from(at) / self.fps))) - // Floored like a cue's mark and for the same - // reason: a half-second silence on a zoomed- - // out bed rounds to nothing, and a preview - // that draws nothing reads as a scan that - // found nothing. - .w(px(scale - .width_px(f64::from(len) / self.fps) - .max(SUB_CUE_MIN_W))) - .bg(rgba(0x4a9effaa)) - }), - ) - // Where the thing in the hand would come to rest, at the size - // it would come to rest at: the shadow a proper editor draws - // under a drag. Over the clips (it is translucent, so what - // it would cover shows through) and under the line, which - // marks the frame this box merely fills. - .children(ghost.map(|g| { - div() - .absolute() - .top_0() - .h_full() - .left(px(scale.px_at(f64::from(g.start) / self.fps))) - // A row whose length the engine has not measured - // draws a head marker rather than nothing: where it - // lands is known, how long it is is not. - .w(px(scale - .width_px(f64::from(g.frames) / self.fps) - .max(GHOST_MIN))) - .rounded(px(3.)) - .border_1() - .border_color(rgb(if g.refused { REFUSE } else { INK })) - // The file's own swatch at a third of its weight, so - // the box beneath is still legible through it -- and - // the refusal red instead, for a lane that will not - // take this drop at all. - .bg(rgba( - ((if g.refused { REFUSE } else { g.tint }) << 8) | GHOST_ALPHA, - )) - })) - // What the gesture in flight is about to land on, drawn on - // every lane so a clip lining up with a take one track over - // can be seen to line up with it. Under the playhead's line - // and in another colour, since the two mean different - // things and often stand on the same pixel. - .children(cue.map(|x| { - div() - .absolute() - .top_0() - .h_full() - .left(px(x)) - .w(px(1.)) - .bg(rgb(INK)) - })) - // Last, so it is over the clips: the same fraction in both - // lanes, which is the playhead being one line. - .child( - div() - .absolute() - .top_0() - .h_full() - .left(px(filled)) - .w(px(1.)) - .bg(rgb(ACCENT)), - ), - ) - } -} - -/// Rate limit for scrub seeks: a video worker reopen costs 72-87 ms on the -/// hardware path for the small files it was measured on (215 ms in software), so -/// one seek per mouse move would only queue workers that are cancelled before -/// they decode anything. -/// -/// It is a *floor*, not a bound: the reopen is a demux open -/// ([`engine::decode::open_worker`]), and on a 25 GB film that is 550-750 ms -- -/// five to seven times this gap, which therefore gates nothing there. Where the -/// cost had to be bounded rather than thinned -- the colour and speed drags -- -/// the gate is the frame the worker delivers ([`Player::flush_drag`]) and no -/// timer at all. The ruler keeps this one: a scrub has no value to hold back, -/// only a position that the next mouse move replaces anyway. -const SCRUB_GAP: Duration = Duration::from_millis(100); - -fn scrub_due(target: u32, last_target: u32, since: Duration) -> bool { - target != last_target && since >= SCRUB_GAP -} - -/// The gate a live drag sample goes through. With the worker still owing a -/// frame (`busy`), writing now would only cancel the open the picture is already -/// waiting for -- the sample is held in `stash` instead, and the frame that -/// lands writes it ([`Player::flush_drag`]). Returns what to write, if anything. -/// -/// The press (`first`) never waits: it is the undo step the whole gesture rolls -/// back to, so it has to be taken against the state the hand picked up. -fn stash_or_write(stash: &mut Option, value: T, first: bool, busy: bool) -> Option { - match busy && !first { - true => { - *stash = Some(value); - None - } - false => Some(value), - } -} - -/// How long an open may stand before the window says so in words. Well past an -/// ordinary seek (a warm reopen is under a tenth of this) and well under what a -/// cold read of a big film takes, which is the only case worth a line. -const SEEK_STALL: Duration = Duration::from_secs(2); - -/// What a seek that has stood past [`SEEK_STALL`] says, and nothing at all -/// before that: a line on every click of the ruler would be a flicker, and the -/// picture holding still for a tenth of a second is not something to explain. -/// The import bar's words, for the import bar's reason -- a window that cannot -/// move and a window that has hung look identical, so this one says which. -fn seek_line(standing: Option) -> Option { - let since = standing.filter(|d| *d >= SEEK_STALL)?; - Some(format!( - "still opening the picture — a cold read of a big file is seconds of it, and the window \ - is not frozen · {} elapsed", - clock(since.as_secs_f32()) - )) -} - -/// How a finished export announces itself. Written by `poll_export` and read -/// by the notice bar, which is what makes that one line clickable. -const EXPORT_DONE: &str = "EXPORT DONE → "; - -/// The path as a URI the bus will take: percent-encoded, because an export -/// lands wherever its source lives and those directories have spaces in them. -/// Bytes, not chars -- a path is not required to be UTF-8. -fn file_uri(path: &std::path::Path) -> String { - use std::os::unix::ffi::OsStrExt; - let mut uri = String::from("file://"); - for &b in path.as_os_str().as_bytes() { - match b { - b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => { - uri.push(b as char) - } - _ => uri.push_str(&format!("%{b:02X}")), - } - } - uri -} + uri +} /// Shows a file in the desktop's file manager, selected: the freedesktop /// interface every major one answers, asked for over the session bus. With no @@ -13410,211 +8669,12 @@ fn envelope(peaks: &[(f32, f32)], from: f64, to: f64, w: f32, h: f32) -> Vec<(f3 .collect() } -/// One clip's audio, drawn as a filled min/max envelope inside whatever box it -/// is given. Peaks are the source's whole envelope; `from`/`to` are the source -/// seconds this clip plays, so a cut clip shows its own stretch of the file. -fn waveform(peaks: Arc>, from: f64, to: f64) -> impl IntoElement { - canvas( - |_, _, _| (), - move |bounds, _, window, _| { - let (o, s) = (bounds.origin, bounds.size); - let cols = envelope(&peaks, from, to, f32::from(s.width), f32::from(s.height)); - if cols.len() < 2 { - return; - } - // Down the tops and back along the bottoms: one closed outline of - // the whole envelope, which is one path rather than a path a column. - let mut points: Vec> = cols - .iter() - .map(|&(x, top, _)| point(o.x + px(x), o.y + px(top))) - .collect(); - points.extend( - cols.iter() - .rev() - .map(|&(x, _, bottom)| point(o.x + px(x), o.y + px(bottom))), - ); - let mut path = PathBuilder::fill(); - path.add_polygon(&points, true); - if let Ok(path) = path.build() { - window.paint_path(path, rgb(INK_DIM)); - } - }, - ) - .size_full() -} -/// A toolbar button: its glyph, its name, and its key on hover. `id` only buys -/// `on_click` and the tooltip -- it is still not focusable, so the root's own -/// key listener keeps working after a press, and the click lands on mouse-up -/// inside the button (a press that slides off does nothing). -/// -/// A button that would do nothing says so: dimmed, no pointer, no listener. -fn control( - id: &'static str, - glyph: Option, - // Not `&'static str`: the volume button's label is its state. - label: impl Into, - shortcut: String, - enabled: bool, - on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, -) -> impl IntoElement { - let label = label.into(); - let tip: SharedString = format!("{label} — {shortcut}").into(); - div() - .id(id) - .flex_none() - .h(px(CONTROL_H)) - .flex() - .items_center() - .gap(px(6.)) - .px(px(8.)) - .rounded(px(3.)) - .bg(rgb(SURFACE)) - .children(glyph) - .child(label) - .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into()) - .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) - .when(enabled, |d| { - d.cursor_pointer() - .hover(|s| s.bg(rgb(HOVER))) - .on_click(on_click) - }) -} -/// The monitoring level as something to drag: 4 px of bar to look at and the -/// whole control's height to hit (WCAG 2.5.8), the split the speed bar and the -/// colour sliders both make. Only the level -- mute is the button beside it, so -/// a muted slider still shows what unmuting comes back to, drawn dim. -/// -/// Dimmed and inert without a timeline, like every other control that would -/// have nothing to act on. -fn volume_slider( - volume: Volume, - bar: Rc>>, - enabled: bool, - cx: &mut Context, -) -> impl IntoElement { - div() - .id("volume-bar") - .relative() - .flex_none() - .w(px(VOLUME_W)) - .h(px(CONTROL_H)) - .flex() - .items_center() - .tooltip(|_, cx| { - cx.new(|_| Tip("Volume — drag to set the level; the button mutes".into())) - .into() - }) - .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) - .when(enabled, |d| { - d.cursor_pointer() - .on_mouse_down( - MouseButton::Left, - cx.listener(|this, event: &MouseDownEvent, _, cx| { - this.volume_dragging = true; - this.drag_volume(event.position.x, cx); - }), - ) - .child(bounds_probe(bar)) - }) - .child( - div() - .w_full() - .h(px(4.)) - .rounded(px(2.)) - .bg(rgb(SURFACE)) - .child( - div() - .h_full() - .w(relative(volume.along())) - .rounded(px(2.)) - .bg(rgb(if volume.muted { INK_DIM } else { ACCENT })), - ), - ) -} -/// The line between two groups of buttons. -fn separator() -> impl IntoElement { - div() - .flex_none() - .mx(px(4.)) - .w(px(1.)) - .h(px(18.)) - .bg(rgb(HOVER)) -} -/// Whether a card or a menu is drawn over the window, as the hover labels see -/// it: written once a frame by [`Player::render`], read by every [`Tip`] before -/// it paints. -/// -/// A tooltip already on screen when an overlay opens *stays* on screen in gpui: -/// occluding the surface under it does not take it back, because the check that -/// keeps it visible works off the element's absolute bounds and knows nothing -/// about what was painted over it (`div.rs::handle_tooltip_mouse_move`, its own -/// TODO). So the tip is what has to stand aside -- here, once, for every hover -/// label in this window, rather than at fifteen call sites of which the -/// sixteenth would be forgotten. -static OVERLAID: AtomicBool = AtomicBool::new(false); - -/// A tooltip is a view in gpui and nothing smaller, so this is the smallest one -/// that carries a line of text. It paints outside the window's element tree and -/// therefore owns its colours. -struct Tip(SharedString); - -impl Render for Tip { - fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { - // A card or a menu is up: nothing. A line of text over the items of the - // menu that just opened under the pointer is the card being painted - // over by the window it covers. - if OVERLAID.load(Ordering::Relaxed) { - return div(); - } - div() - .px(px(6.)) - .py(px(3.)) - .rounded(px(3.)) - .border_1() - .border_color(rgb(SURFACE)) - .bg(rgb(CHROME)) - .text_color(rgb(INK)) - .text_size(px(12.)) - .child(self.0.clone()) - } -} -/// Scissors: two blades crossed. Drawn this way and not as a split clip because -/// two bars is what the transport wears when it is playing -- the one glyph a -/// cut must never be mistaken for. -fn cut_glyph() -> impl IntoElement { - canvas( - |_, _, _| (), - |bounds, _, window, _| { - let (o, s) = (bounds.origin, bounds.size); - let mut path = PathBuilder::stroke(px(1.5)); - path.move_to(point(o.x + s.width * 0.15, o.y + s.height)); - path.line_to(point(o.x + s.width * 0.9, o.y + s.height * 0.1)); - path.move_to(point(o.x + s.width * 0.85, o.y + s.height)); - path.line_to(point(o.x + s.width * 0.1, o.y + s.height * 0.1)); - if let Ok(path) = path.build() { - window.paint_path(path, rgb(INK)); - } - }, - ) - .w(px(13.)) - .h(px(13.)) -} -/// A lid over a bin. -fn delete_glyph() -> impl IntoElement { - div() - .flex() - .flex_col() - .items_center() - .gap(px(2.)) - .child(div().w(px(13.)).h(px(2.)).bg(rgb(INK))) - .child(div().w(px(9.)).h(px(9.)).bg(rgb(INK))) -} /// Records its parent's laid-out box: gpui hands a mouse listener the window /// position only, and the ruler sits behind the panel's padding. Paints @@ -14026,7 +9086,7 @@ fn eq_curve(params: EqParams, sample_rate: u32) -> impl IntoElement { } } if let Ok(path) = path.build() { - window.paint_path(path, rgb(ACCENT)); + window.paint_path(path, rgb(ACCENT_PRIMARY)); } }, ) @@ -14034,59 +9094,7 @@ fn eq_curve(params: EqParams, sample_rate: u32) -> impl IntoElement { .size_full() } -/// What a window with no file open is waiting for. Both ways in are already -/// built -- the whole window is the drop target and the Import chooser takes a -/// project as readily as media -- so this only has to say so. -fn empty_hint() -> impl IntoElement { - div() - .flex() - .flex_col() - .items_center() - .gap(px(6.)) - .text_color(rgb(INK_DIM)) - .child("Drop a video or an .edith project here") - .child( - div() - .text_size(px(11.)) - .child("or click Import in the media list"), - ) -} -/// Two bars while playing, a triangle in every other state -- paused, nothing -/// open, and played out, where the button's next act is to start over rather -/// than to stop something. Drawn, so there is no icon font and no glyph -/// coverage to depend on. -fn transport_glyph(state: Transport) -> impl IntoElement { - let playing = state.is_playing(); - div() - .flex() - .items_center() - .gap(px(4.)) - .when(playing, |d| { - d.child(div().w(px(3.)).h(px(12.)).bg(rgb(INK))) - .child(div().w(px(3.)).h(px(12.)).bg(rgb(INK))) - }) - .when(!playing, |d| { - d.child( - canvas( - |_, _, _| (), - |bounds, _, window, _| { - let (o, s) = (bounds.origin, bounds.size); - let mut path = PathBuilder::fill(); - path.move_to(o); - path.line_to(point(o.x + s.width, o.y + s.height / 2.)); - path.line_to(point(o.x, o.y + s.height)); - path.close(); - if let Ok(path) = path.build() { - window.paint_path(path, rgb(INK)); - } - }, - ) - .w(px(11.)) - .h(px(13.)), - ) - }) -} /// NLE timecode: `HH:MM:SS:FF`, the frame counted inside its own second. fn timecode(t: f64, fps: f64) -> String { @@ -14328,16 +9336,16 @@ fn eta_secs(marks: &[(f32, f32)], elapsed: f32, progress: f32) -> Option { #[cfg(test)] mod tests { use super::{ - ACCENT, AUDIO_KBPS, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, Ctx, DEFAULT_AUDIO_KBPS, EQ_BANDS_MAX, + ACCENT_PRIMARY, AUDIO_KBPS, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, Ctx, DEFAULT_AUDIO_KBPS, EQ_BANDS_MAX, EQ_CURVE_STEPS, EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_FREQ_STEP, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_Q_HIGH, EQ_Q_LOW, EQ_Q_STEP, EQ_SPECTRUM_DB, EQ_TICKS, EQ_W_MAX, ESCAPE, EXPORT_FIXED_H, EXPORT_ROWS_H, EXPORT_W, Enable, FORMATS, - Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, - INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, KeyRow, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, - LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H, + Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, FG_PRIMARY, + FG_SECONDARY, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, KeyRow, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, + BG_CANVAS, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H, MBPS_DIGITS, MBPS_MAX, MBPS_MIN, MB_FLOOR, MENU_W, NO_FILE, NumberEdit, PANEL_H, ROW_ITEMS, RowCtx, RowItem, - Quality, ROW_H, RULER_HIT_H, SELECTED, SILENCE_ROWS, - SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, SURFACE, SWATCH_W, Source, Speed, StreamInfo, + Quality, ROW_H, RULER_HIT_H, BG_SELECTED, SILENCE_ROWS, + SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, BG_RAISED, SWATCH_W, Source, Speed, StreamInfo, Transport, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, WAVE_COLS_MAX, Wave, band_label, bitrate_detail, bitrate_refusal, can_add, cancels_export, clipboard_after_remove, color_snap, commit_mbps, containers, @@ -14366,7 +9374,7 @@ mod tests { visible_slice, }; use super::{ - SUB_BOTTOM, SUB_CUE_MIN_W, SUB_HEAD_H, SUB_INK, SUB_LANE_H, SUB_LINE_H, SUB_ROWS_H, + SUB_BOTTOM, SUB_CUE_MIN_W, SUB_HEAD_H, SUB_FG, SUB_LANE_H, SUB_LINE_H, SUB_ROWS_H, SUB_STEM_SHARE, SUB_TEXT, clip_middle, cue_box, carries_subtitles, cues_at, file_tint, is_subtitle, lang_human, row_text_w, sub_headers_fit, Subs, subtitle_detail, subtitle_notice, subtitle_tail, @@ -17900,19 +12908,19 @@ mod tests { assert!(KEYS_ROW_H >= HIT_MIN); assert!(CONTROL_H >= HIT_MIN); // The dimmed text on the card -- every refusal, every detail, every key - // in its column -- is body text on `SURFACE` and WCAG 1.4.3 binds it. + // in its column -- is body text on `BG_RAISED` and WCAG 1.4.3 binds it. // A dimmed row is drawn in this ink rather than at an opacity, which is // what a refusal used to be readable through. assert!( - contrast(INK_DIM, SURFACE) >= 4.5, + contrast(FG_SECONDARY, BG_RAISED) >= 4.5, "refusal ink {:.2}", - contrast(INK_DIM, SURFACE) + contrast(FG_SECONDARY, BG_RAISED) ); // On the picked row that ink would only be 3.3:1 against the highlight, - // so the row it lands on lifts its key and detail to `INK`. - assert!(contrast(INK, SELECTED) >= 4.5); + // so the row it lands on lifts its key and detail to `FG_PRIMARY`. + assert!(contrast(FG_PRIMARY, BG_SELECTED) >= 4.5); assert!( - contrast(INK_DIM, SELECTED) < 4.5, + contrast(FG_SECONDARY, BG_SELECTED) < 4.5, "the lift is still needed" ); } @@ -18781,7 +13789,7 @@ mod tests { assert!(SUB_LINE_H >= SUB_TEXT); // White on the plate, not chrome on chrome: a cue is read against the // film, and this is the one pair here that has to survive any picture. - assert!(contrast(SUB_INK, 0x000000) >= 7.); + assert!(contrast(SUB_FG, 0x000000) >= 7.); // 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.); @@ -19387,34 +14395,34 @@ mod tests { for (i, tint) in SOURCE_TINTS.iter().enumerate() { // WCAG 1.4.3: the clip's name is body text on its tint. assert!( - contrast(INK, *tint) >= 4.5, + contrast(FG_PRIMARY, *tint) >= 4.5, "source {i}: label contrast {:.2}", - contrast(INK, *tint) + contrast(FG_PRIMARY, *tint) ); // WCAG 1.4.11: the waveform is a non-text graphic on it. assert!( - contrast(INK_DIM, *tint) >= 3., + contrast(FG_SECONDARY, *tint) >= 3., "source {i}: waveform contrast {:.2}", - contrast(INK_DIM, *tint) + contrast(FG_SECONDARY, *tint) ); } // A selected clip's bed is the same two marks on a different colour. - assert!(contrast(INK, SELECTED) >= 4.5); - assert!(contrast(INK_DIM, SELECTED) >= 3.); + assert!(contrast(FG_PRIMARY, BG_SELECTED) >= 4.5); + assert!(contrast(FG_SECONDARY, BG_SELECTED) >= 3.); // The bed a gap shows through has to read as a hole in the lane, and // the accent playhead has to be findable on it. - assert!(contrast(LETTERBOX, SURFACE) >= 1.5); - assert!(contrast(ACCENT, LETTERBOX) >= 3.); + assert!(contrast(BG_CANVAS, BG_RAISED) >= 1.5); + assert!(contrast(ACCENT_PRIMARY, BG_CANVAS) >= 3.); // The sanity check on the ratio itself: black on white is 21:1. assert!((contrast(0xffffff, 0x000000) - 21.).abs() < 0.01); } #[test] fn source_tints_differ_per_source_and_cycle() { - // The bug: the first entry *was* `SURFACE`, so the first file imported + // The bug: the first entry *was* `BG_RAISED`, so the first file imported // -- the one every session has -- wore the panel's own background and // had no visible swatch at all. - assert_ne!(source_tint(0), SURFACE); + assert_ne!(source_tint(0), BG_RAISED); // Neighbouring sources must not share one, or an import is invisible. assert_ne!(source_tint(0), source_tint(1)); assert_ne!(source_tint(1), source_tint(2)); @@ -19431,7 +14439,7 @@ mod tests { /// tint picked by eye can land inside it without anyone noticing. #[test] fn source_tints_are_all_discernible() { - // Summed channel distance: `SURFACE` to the warm tint is 18, and that + // Summed channel distance: `BG_RAISED` to the warm tint is 18, and that // step is the one already accepted as readable on a lane. let apart = |a: u32, b: u32| { (0..3) @@ -19443,9 +14451,9 @@ mod tests { }; for (i, &tint) in SOURCE_TINTS.iter().enumerate() { assert!( - apart(tint, SURFACE) >= 16, + apart(tint, BG_RAISED) >= 16, "tint {i} is {} from the panel it sits on", - apart(tint, SURFACE) + apart(tint, BG_RAISED) ); for (j, &other) in SOURCE_TINTS.iter().enumerate().skip(i + 1) { assert!( diff --git a/crates/app/src/ui/cards.rs b/crates/app/src/ui/cards.rs new file mode 100644 index 0000000..e7dd933 --- /dev/null +++ b/crates/app/src/ui/cards.rs @@ -0,0 +1,1657 @@ +//! The property cards -- docked into the inspector, or floated when modal. + +use crate::*; +use crate::ui::widgets::*; + +impl Player { + /// What an export is going to be, before there is one: the codec, the box + /// it goes into, the bitrate, where it lands -- and, above the button, the + /// two lines that state the file all of that adds up to. The same scrim and + /// row shape as the keybindings overlay (two cards of different builds over + /// one window read as two different programs) and the same plain divs, so + /// the root keeps the keyboard and the custom row's field is typed into + /// through it ([`NumberEdit`]). + /// + /// Every row carries the key that picks it, so the card is drivable end to + /// end without a pointer *and* without a legend to memorise -- and every + /// row is clickable, the bitrate's steppers included, so it is drivable end + /// to end without a keyboard as well. + /// + /// Two shapes of it, behind `g` and `r`: sections against one flat list, + /// and the codecs with no encoder collapsed into a footer against a dimmed + /// row each. Grouped and collapsed is what opens. + pub(crate) fn export_card( + &self, + viewport: Size, + cx: &mut Context, + ) -> Option { + if !self.export_open { + return None; + } + // The cap is what keeps the card inside the smallest window; a taller + // one gets a taller list rather than a scroll past empty space, and the + // card is still only as tall as the rows it has. + let rows_h = (f32::from(viewport.height) - EXPORT_FIXED_H - 24.).max(EXPORT_ROWS_H); + let row = |id: (&'static str, usize)| { + div() + .id(id) + .flex() + // The floor, not the height: the destination's path wraps on a + // long name and must not paint over the row under it. Which it + // did: inside a capped, scrolling list a row shrinks to fit by + // default, so a wrapped detail was drawn over the row beneath + // it (the Sound row's "the source's own packets are copied…" + // over Subtitles). The list scrolls -- a row is as tall as what + // it has to say. + .flex_none() + .min_h(px(KEYS_ROW_H)) + .items_center() + .justify_between() + .gap(px(12.)) + .px(px(6.)) + .rounded(px(3.)) + }; + // A row that cannot be picked is dimmed and takes no click, exactly as + // an inapplicable item in the clip menu is: it still says its piece. + let live = |d: Stateful
, enabled: bool| { + d.when(!enabled, |d| { + d.cursor_not_allowed().text_color(rgb(FG_SECONDARY)) + }) + .when(enabled, |d| d.cursor_pointer().hover(|s| s.bg(rgb(BG_HOVER)))) + }; + // A row as this card writes them: the mark saying which one is picked, + // the key that picks it, its name, and what the choice means. The mark + // is a glyph and not only a colour -- a background alone is gone the + // moment a hover lands on the row, and invisible to anyone who cannot + // tell the two greys apart (WCAG 1.4.1). + let entry = |id: (&'static str, usize), + key: &str, + label: SharedString, + detail: SharedString, + picked: bool, + enabled: bool| { + // The small print of a picked row sits on the highlight, where the + // dim ink is only 3.3:1 -- the row it lands on lifts it (WCAG + // 1.4.3, and the fit test pins both numbers). + let ink = match picked { + true => FG_PRIMARY, + false => FG_SECONDARY, + }; + live(row(id), enabled) + .when(picked, |d| d.bg(rgb(BG_SELECTED))) + .child( + div() + .flex() + .flex_none() + .items_center() + .gap(px(8.)) + .child(div().w(px(10.)).child(match picked { + true => "✓", + false => " ", + })) + .child( + div() + .w(px(EXPORT_KEY_W)) + .text_size(px(11.)) + .text_color(rgb(ink)) + .child(SharedString::from(key.to_string())), + ) + .child(label), + ) + // Wraps rather than runs off the row: a refusal is the longest + // thing in this column and the half of it past the edge is the + // half that says what to do instead. + .child( + div() + .min_w(px(0.)) + .flex_shrink() + .text_size(px(11.)) + .text_color(rgb(ink)) + .child(detail), + ) + }; + let header = |text: &'static str| { + div() + .flex_none() + .px(px(6.)) + .pt(px(4.)) + .text_size(px(10.)) + .text_color(rgb(FG_SECONDARY)) + .child(text) + .into_any_element() + }; + let mut list: Vec = Vec::new(); + if self.export_grouped { + list.push(header("FORMAT")); + } + // The codecs first: which one is being written decides whether every + // row under it means anything. One a *this* timeline cannot be written + // as (an audio-only edit, for a picture codec) reads exactly like one + // there is no encoder for -- dimmed, unclickable, and carrying its own + // reason where its detail was, with nothing to click to find that out. + let mut refusals: Vec = Vec::new(); + for (i, (boxes, key, label, detail)) in FORMATS.into_iter().enumerate() { + let format = same_box(boxes, self.format); + let refused = format + .zip(self.session.as_ref()) + .and_then(|(f, s)| format_refusal(s, f)); + // A codec with no encoder here at all is the other kind of refusal, + // and the one the footer collects: it can never become pickable, so + // a row each is dead rows above the fold. + if format.is_none() { + refusals.push(format!("{label} — {detail}")); + if !self.export_refusals_inline { + continue; + } + } + let detail: SharedString = match &refused { + Some(why) => why.clone().into(), + None => detail.into(), + }; + let format = format.filter(|_| refused.is_none()); + let mut r = entry( + ("format", i), + key, + label.into(), + detail, + boxes.contains(&self.format), + format.is_some(), + ); + if let Some(format) = format { + r = r.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.set_format(format); + cx.notify(); + })); + } + list.push(r.into_any_element()); + } + if self.export_grouped { + list.push(header("DETAILS")); + } + // The container, and only where the picked codec has more than one box: + // a row offering a single choice reads as a choice. + let boxes = containers(self.format); + if boxes.len() > 1 { + let next = next_container(self.format); + list.push( + entry( + ("container", 0), + "c", + "Container".into(), + format!( + "{} — c for {}", + self.format.ext().to_uppercase(), + next.ext().to_uppercase() + ) + .into(), + false, + true, + ) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.cycle_container(); + cx.notify(); + })) + .into_any_element(), + ); + } + match bitrate_refusal(self.format) { + // One dimmed row carrying the reason, rather than five rows of a + // figure that will not be written: the quality rows are the + // *picture's* bitrate, and this file has no picture in it. + Some(why) => list.push( + entry( + ("quality", 0), + "q", + "Quality".into(), + why.into(), + false, + false, + ) + .into_any_element(), + ), + None => { + for (i, quality) in Quality::ALL.into_iter().enumerate() { + // The custom row is a field: `n` opens it, a click in it + // opens it too, and while it is open the row shows what is + // being typed with a caret in it rather than the number in + // force. The other four are picked whole. + let field = self.mbps_edit.as_ref().filter(|_| quality == Quality::Custom); + let mut r = entry( + ("quality", i), + match quality { + Quality::Custom => "n", + _ => "q", + }, + quality.label().into(), + match field { + Some(edit) => edit.detail().into(), + None => quality.detail(self.custom_mbps).into(), + }, + self.quality == quality, + true, + ) + .on_click(cx.listener( + move |this, _: &ClickEvent, _, cx| { + match quality { + Quality::Custom => this.edit_mbps(), + _ => this.quality = quality, + } + cx.notify(); + }, + )); + if quality == Quality::Custom { + r = r.child(self.mbps_steppers(cx)); + } + list.push(r.into_any_element()); + } + } + } + // The other half of the file, and the one this card used to write at a + // fixed rate without saying so: what the *sound* is coded at, for every + // format that codes it -- the AAC inside a video export as much as an + // MP3. Four rates, so the pointer gets the *list* of them + // ([`Pick::AudioRate`]) rather than a button clicked round -- the + // resolution row's rule, and the key still steps as `ctrl+r` still + // does. Dimmed with the reason where this timeline has no rate to pick, + // like the quality rows are. + let sound = self.audio_rate_refusal(); + let mut r = entry( + ("sound", 0), + "b", + "Sound".into(), + match sound { + Some(why) => why.into(), + None => format!("{} kbps — b steps", self.audio_kbps).into(), + }, + false, + sound.is_none(), + ); + if sound.is_none() { + r = r.on_click(cx.listener(|this, event: &ClickEvent, _, cx| { + this.open_picker(Pick::AudioRate, event.position(), cx) + })); + } + list.push(r.into_any_element()); + // What happens to the subtitles on this timeline, in one line: how many + // are written into the file and under what names, or the reason each one + // is not. Which tracks travel is not a pick -- everything with a cue on + // the timeline goes ([`Player::export_subs`]) -- so the row says rather + // than offers, like the machine lines below. + // ...and the ones that do not travel are named here too, which they were + // not: `export_subs` had already filtered a track with no cue on *this* + // timeline out of the engine's sight, so the card said nothing about a + // row the list was still showing ([`subtitle_plan`]). + let plan = self.subtitle_line(); + // The row used to end in "click for in MKV" whenever the picture + // was going into an mp4, on the grounds that only Matroska carries a + // text track. An mp4 carries one now (`Mp4Muxer::write_subtitles` writes + // `tx3g`), so that was a refusal offering a way out of nothing: the + // container the card is already set to embeds them. The refusals left in + // `planned_subtitles` are the true ones -- a sound-only format has + // nowhere to put a track, and a PGS track is pictures whatever the box. + list.push( + entry( + ("subtitles", 0), + "", + "Subtitles".into(), + plan.into(), + false, + false, + ) + .into_any_element(), + ); + let destination = entry( + ("destination", 0), + "d", + "Destination".into(), + file_name(&self.export_path).into(), + false, + true, + ) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| this.pick_destination(cx))) + .into_any_element(); + // The card's own two layout switches. They were `g` and `r` and nothing + // else, while the status line under the title advertised both of them: + // a hand on the mouse read what they do and had nothing to press. + list.push( + entry( + ("export-layout", 0), + "g", + "Layout".into(), + match self.export_grouped { + true => "sections — g for one flat list".into(), + false => "one flat list — g for sections".into(), + }, + self.export_grouped, + true, + ) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.export_grouped = !this.export_grouped; + cx.notify(); + })) + .into_any_element(), + ); + list.push( + entry( + ("export-refusals", 0), + "r", + "Codecs with no encoder".into(), + match self.export_refusals_inline { + true => "a dimmed row each — r collapses them".into(), + false => "one line at the foot — r shows a row each".into(), + }, + self.export_refusals_inline, + true, + ) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.export_refusals_inline = !this.export_refusals_inline; + cx.notify(); + })) + .into_any_element(), + ); + match self.export_grouped { + true => list.push(destination), + // Flat: the same rows with no headers over them, and the + // destination back at the top where the card used to open with it. + false => list.insert(0, destination), + } + if !self.export_refusals_inline && !refusals.is_empty() { + // Last, and one line: the reason travels with the name (a footer + // that only listed them would be the "why not?" the rows exist to + // answer), but nothing here can ever be picked, so it sits under + // every row that can rather than above them. + list.push( + div() + .flex_none() + .px(px(6.)) + .py(px(2.)) + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child(format!("cannot write: {}", refusals.join(" · "))) + .into_any_element(), + ); + } + // What is doing the work, on this machine and in this build: the GPU + // half is asked of the driver through the plugin (a different answer on + // every machine, and "none" where there is no plugin at all), the build + // half is the crates that were compiled in. Last in the list, because it + // is what a user checks rather than what they pick -- and a listing + // rather than rows, since none of it can be clicked. + if self.export_grouped { + list.push(header("THIS MACHINE")); + } + let note = |text: String| { + div() + .flex_none() + .px(px(6.)) + .py(px(2.)) + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child(text) + .into_any_element() + }; + list.push(note(format!( + "GPU: {}", + self.hw_caps.clone().unwrap_or_else(|| "asking…".into()) + ))); + list.push(note(format!("Built in: {}", engine::caps::software()))); + // What the rows add up to, which is the one thing that has to be right: + // codec, box, size, rate, sound, where it goes and about how big. Two + // lines, outside the scrolling list, so it is on screen whatever the + // list is scrolled to and whatever is picked. + let picture = self + .session + .as_ref() + .map(|s| (s.resolution(), s.meta().frame_rate)); + let audio = self + .session + .as_ref() + .map_or("", |s| s.planned_audio(self.format)); + let settings = + export_settings(self.quality, self.custom_mbps, self.format, self.audio_kbps); + let size = estimated_bytes( + settings.bitrate.filter(|_| self.format.has_video()), + self.session + .as_ref() + .map_or(0., PlaybackSession::timeline_duration), + ); + let head = summary_head(self.format, picture, audio); + let tail = summary_tail( + &self.export_path, + size, + self.export_seat.as_ref().and_then(|(.., seat)| *seat), + self.format.has_video(), + ); + // The button says the refusal *before* it is pressed: the picked codec + // can go invalid one edit after it was picked (a cleared video lane), + // and a button that looks ready until it is pressed is the lie the + // dimmed rows above it are there to avoid. + let blocked = self + .session + .as_ref() + .and_then(|s| format_refusal(s, self.format)); + let action: SharedString = match &blocked { + Some(why) => { + format!("Cannot export — {}", why.split(" — ").next().unwrap_or(why)).into() + } + None => "Export".into(), + }; + Some( + scrim() + .flex() + .justify_center() + .items_center() + .bg(rgba(SCRIM)) + // Click away closes it, as on every card here. + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _: &MouseDownEvent, _, cx| { + this.close_card(); + cx.notify(); + cx.stop_propagation(); + }), + ) + .child( + div() + .w(px(EXPORT_W)) + .on_mouse_down(MouseButton::Left, swallow) + .flex() + .flex_col() + .gap(px(2.)) + .p(px(12.)) + .rounded(px(6.)) + .bg(rgb(BG_RAISED)) + .child(div().flex_none().px(px(6.)).child("Export")) + // The status line, where a refusal from the save dialog + // lands: the notice bar it would otherwise take is under + // the scrim. The keys are on the rows, so this says how + // the card as a whole is answered rather than listing + // them a second time. + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child(match (&self.mbps_edit, &self.notice) { + // A field being typed into says so here as + // well as in its row: this line is outside + // the scrolling list and on screen at every + // window size, and at 360 px the custom row + // itself can be below the fold -- a number + // typed where it cannot be seen is the + // blind capture this field replaced. + (Some(edit), _) => { + SharedString::from(format!("Custom bitrate {}", edit.detail())) + } + (None, Some(notice)) => notice.clone(), + (None, None) => "the keys are on the rows · enter exports · \ + a click away or esc closes · g/r change the layout" + .into(), + }), + ) + // Capped and scrolling like the keybindings list: the + // rows are more than a 360 px window has room for, and + // it is the list that scrolls, never the card that + // grows -- the summary and the button below stay put. + .child( + div() + .id("export-rows") + .flex() + .flex_col() + .gap(px(2.)) + .max_h(px(rows_h)) + .overflow_y_scroll() + .children(list), + ) + .child(div().flex_none().px(px(6.)).text_size(px(11.)).child(head)) + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child(tail), + ) + .child( + div() + .id("export-confirm") + .mt(px(4.)) + .flex() + .h(px(CONTROL_H)) + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(match blocked.is_some() { + true => BG_PANEL, + false => BG_SELECTED, + })) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click( + cx.listener(|this, _: &ClickEvent, _, cx| { + this.start_export(cx) + }), + ) + .child(action), + ), + ), + ) + } + + /// The custom bitrate's two pointer buttons. The typed digits were the last + /// control in this card a mouse could not reach at all -- and a number that + /// can only be typed is a number a hand on the pointer has to leave the + /// card to change. `HIT_MIN` square, like every other target here. + pub(crate) fn mbps_steppers(&self, cx: &mut Context) -> impl IntoElement { + let step = |id: &'static str, label: &'static str, by: i32, cx: &mut Context| { + div() + .id(id) + .flex() + .w(px(HIT_MIN)) + .h(px(HIT_MIN)) + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(BG_PANEL)) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.nudge_mbps(by); + cx.notify(); + })) + .child(label) + }; + div() + .flex() + .gap(px(4.)) + .child(step("mbps-down", "−", -1, cx)) + .child(step("mbps-up", "+", 1, cx)) + } + + /// The equalizer of one audio clip: its frequency response drawn as a + /// curve, a handle per band sitting on it, each band's own bell under the + /// sum, and a row that reads and moves the picked band's three numbers. The + /// curve is the clip's actual filter (`EqParams::response_db` reads the + /// coefficients the samples go through), and it is redrawn on every pointer + /// sample of a drag, so the shape bends under the hand. + /// + /// Wider than the other cards and wider still on a bigger window + /// ([`eq_card_w`]): every pixel across is frequency resolution, which none + /// of the row-shaped cards have any use for. The same scrim and the same + /// plain divs -- nothing here takes focus, so the root keeps the keyboard + /// and the card's own strokes (a digit, the arrows, `a`, `x`, `f`, `r`, + /// `s`) reach it. + /// + /// Every change is written at the clip as it is made + /// ([`Player::commit_eq`]), so what the card shows is always what is + /// playing: there is no OK button to forget, and closing it changes + /// nothing. What takes a curve back off is undo, like every other edit. + pub(crate) fn eq_card( + &self, + viewport: Size, + cx: &mut Context, + ) -> Option { + let (lane, idx) = self.eq_open?; + // The rate the engine filters this timeline at, so the drawn curve is + // the one those coefficients make -- near the top of the axis a 44.1 kHz + // clip and a 48 kHz one are not the same shape. + let sample_rate = self.timeline_audio().map_or(48_000, |(rate, _)| rate); + let picked = self.eq_params.bands.get(self.eq_band); + // What is playing, drawn behind the curve -- and only while something + // *is* playing: the tap freezes with the device, and a still spectrum + // under a paused timeline would look like sound that is not there. + let spectrum = self + .eq_spectrum + .then_some(self.session.as_ref()) + .flatten() + .filter(|session| session.is_playing()) + .and_then(PlaybackSession::audio_tap) + .map(|(samples, rate)| eq_spectrum(&samples, rate)) + .filter(|levels| !levels.is_empty()) + .map(eq_spectrum_curve); + let handles: Vec<_> = self + .eq_params + .bands + .iter() + .enumerate() + .map(|(i, band)| { + div() + .absolute() + .left(relative(eq_x(band.freq_hz))) + .top(relative(eq_y(band.gain_db))) + // Centred on its own point: it hangs off the graph's corner, + // so it is pulled back by half of itself both ways. + .ml(px(-EQ_HANDLE / 2.)) + .mt(px(-EQ_HANDLE / 2.)) + .w(px(EQ_HANDLE)) + .h(px(EQ_HANDLE)) + .rounded(px(EQ_HANDLE / 2.)) + .bg(rgb(match i == self.eq_band { + true => ACCENT_PRIMARY, + false => FG_SECONDARY, + })) + }) + .collect(); + let graph = div() + // Ided like the band rows it replaces: what the pointer presses on + // is one element with its own hitbox, which is what a drag is + // tracked from. + .id("eq-graph") + .relative() + .flex_none() + .h(px(EQ_GRAPH_H)) + .rounded(px(3.)) + .bg(rgb(BG_HOVER_DIM)) + .cursor_pointer() + // The press picks the band under it *and* is already the first + // sample of the drag, so a plain click sets a value. A second click + // takes that band back to flat instead: the gesture that undoes one + // handle, with no modifier to remember. + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, event: &MouseDownEvent, _, cx| { + this.eq_band = this.nearest_band(event.position.x); + if event.click_count >= 2 { + this.eq_dragging = false; + this.nudge_band(|b| b.gain_db = 0., cx); + return; + } + this.eq_dragging = true; + this.drag_band(event.position, cx); + }), + ) + .child(bounds_probe(self.eq_graph.clone())) + // The analyser first, so everything else is drawn on top of it. + .children(spectrum) + // The decades, so a hump can be read as "around 200 Hz" without + // dropping the eye to the labels along the bottom. The two ends + // are the box's own edges and rule nothing. + .children( + EQ_TICKS + .iter() + .filter(|(freq, _)| *freq > EQ_FREQ_LOW && *freq < EQ_FREQ_HIGH) + .map(|(freq, _)| { + div() + .absolute() + .left(relative(eq_x(*freq))) + .w(px(1.)) + .h_full() + .bg(rgb(EQ_GRID)) + }) + .collect::>(), + ) + // Half way to each limit, each carrying its own number: the curve + // is a curve of decibels, and until now only one of them was drawn. + .children(EQ_DB_GRID.map(|db| { + div() + .absolute() + .top(relative(eq_y(db))) + .w_full() + .h(px(1.)) + .bg(rgb(EQ_GRID)) + .child( + div() + .absolute() + .left(px(4.)) + .top(px(-11.)) + .text_size(px(9.)) + .text_color(rgb(FG_SECONDARY)) + .child(format!("{db:+.0}")), + ) + })) + // 0 dB: the line a boost is a boost *from*. + .child( + div() + .absolute() + .top(relative(0.5)) + .w_full() + .h(px(1.)) + .bg(rgb(BG_HOVER)), + ) + .child(eq_curve(self.eq_params.clone(), sample_rate)) + .children(handles) + .children(EQ_TICKS.map(|(freq, label)| { + div() + .absolute() + .left(relative(eq_x(freq))) + // Pulled back so the mark reads as sitting *at* its + // frequency; the two ends then hug the corners. + .ml(px(-12.)) + .bottom(px(1.)) + .w(px(24.)) + .text_align(TextAlign::Center) + .text_size(px(9.)) + .text_color(rgb(FG_SECONDARY)) + .child(label) + })) + .child( + div() + .absolute() + .top(px(2.)) + .left(px(4.)) + .text_size(px(9.)) + .text_color(rgb(FG_SECONDARY)) + .child(format!("+{EQ_GAIN_LIMIT:.0} dB")), + ); + // The bottom of the axis is not named: -12 dB would land in the same + // corner as the 20 Hz tick, and the two lines above it (+6 and -6) + // already say what the box is worth per pixel. + Some( + scrim() + .flex() + .justify_center() + .items_center() + .bg(rgba(SCRIM)) + // Click away closes it, as on every card here. + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _: &MouseDownEvent, _, cx| { + this.close_card(); + cx.notify(); + cx.stop_propagation(); + }), + ) + .child( + div() + .w(px(eq_card_w(f32::from(viewport.width)))) + .on_mouse_down(MouseButton::Left, swallow) + .flex() + .flex_col() + .gap(px(2.)) + .p(px(12.)) + .rounded(px(6.)) + .bg(rgb(BG_RAISED)) + // Which clip, because the card is modal and the lane it + // was opened from is behind a scrim by the time it is up. + .child(div().flex_none().px(px(6.)).child(format!( + "Equalizer — {} clip {}", + lane.label(), + idx + 1 + ))) + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child(self.notice.clone().unwrap_or_else(|| { + "drag a handle, or a digit picks a band — ←→ moves it, ↑↓ its gain, shift+←→ its width; a adds, x removes, f flattens it, r all, s spectrum; a click away or esc closes".into() + })), + ) + .child(graph) + // Which band the keyboard is holding and every number it + // is set to, each with the pair of buttons that moves it: + // the curve shows the sum, and a band pushed against one + // pulling the other way is not readable off it. + .child(self.eq_numbers(picked, cx)) + .child( + div() + .mt(px(4.)) + .flex() + .gap(px(4.)) + .child( + div() + .id("eq-reset") + .flex() + .flex_1() + .h(px(CONTROL_H)) + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(BG_SELECTED)) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + for band in &mut this.eq_params.bands { + band.gain_db = 0.; + } + this.commit_eq(cx); + })) + .child("Flatten all"), + ) + // The two that change how many bands there are. + // The engine takes any cascade -- the count was + // only ever fixed because this card had no way + // to say otherwise. + .child( + div() + .id("eq-add") + .flex() + .flex_1() + .h(px(CONTROL_H)) + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(BG_PANEL)) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.add_band(cx) + })) + .child("Add band"), + ) + .child( + div() + .id("eq-remove") + .flex() + .flex_1() + .h(px(CONTROL_H)) + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(BG_PANEL)) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.remove_band(cx) + })) + .child("Remove band"), + ) + // The analyser's switch, next to the one other + // button the card has: `s` does the same, and a + // toggle only a keystroke can reach is one most + // people never find. + .child( + div() + .id("eq-spectrum") + .flex() + .flex_1() + .h(px(CONTROL_H)) + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(match self.eq_spectrum { + true => BG_SELECTED, + false => BG_HOVER_DIM, + })) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.eq_spectrum = !this.eq_spectrum; + cx.notify(); + })) + .child(match self.eq_spectrum { + true => "Spectrum on", + false => "Spectrum off", + }), + ), + ), + ), + ) + } + + /// The picked band's three numbers -- where it sits, how far it pushes and + /// how wide it is -- each beside the pair of buttons that moves it. The + /// arrows do the same three things, but a value only a key can change is a + /// value a hand on the pointer cannot reach at all, which is the same reason + /// [`Player::mbps_steppers`] exists. + pub(crate) fn eq_numbers(&self, picked: Option<&Band>, cx: &mut Context) -> impl IntoElement { + let row = div() + .flex_none() + .flex() + .items_center() + .gap(px(10.)) + .px(px(6.)) + .text_size(px(11.)); + let Some(band) = picked.copied() else { + return row.child("no bands — a adds one"); + }; + let step = |id: &'static str, + label: &'static str, + change: fn(&mut Band), + cx: &mut Context| { + div() + .id(id) + .flex() + .w(px(HIT_MIN)) + .h(px(HIT_MIN)) + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(BG_PANEL)) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.nudge_band(change, cx) + })) + .child(label) + }; + let number = |value: String, + ids: (&'static str, &'static str), + by: (fn(&mut Band), fn(&mut Band)), + cx: &mut Context| { + div() + .flex() + .items_center() + .gap(px(4.)) + .child(div().child(value)) + .child(step(ids.0, "−", by.0, cx)) + .child(step(ids.1, "+", by.1, cx)) + }; + row.child(format!( + "Band {} of {}", + self.eq_band + 1, + self.eq_params.bands.len() + )) + .child(number( + band_label(&band), + ("eq-freq-down", "eq-freq-up"), + ( + |b| b.freq_hz /= EQ_FREQ_STEP, + |b| b.freq_hz *= EQ_FREQ_STEP, + ), + cx, + )) + .child(number( + format!("{:+.1} dB", band.gain_db), + ("eq-gain-down", "eq-gain-up"), + (|b| b.gain_db -= EQ_STEP, |b| b.gain_db += EQ_STEP), + cx, + )) + // Q is width, so its buttons are labelled by what they *do* to the + // hump rather than by which way the number goes: a wider band is a + // smaller Q, and nobody should have to know that to use the card. + .child(number( + format!("Q {:.2}", band.q), + ("eq-q-wider", "eq-q-narrower"), + (|b| b.q /= EQ_Q_STEP, |b| b.q *= EQ_Q_STEP), + cx, + )) + .child( + div() + .id("eq-flat-band") + .flex() + .h(px(HIT_MIN)) + .px(px(8.)) + .items_center() + .rounded(px(3.)) + .bg(rgb(BG_PANEL)) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click( + cx.listener(|this, _: &ClickEvent, _, cx| { + this.nudge_band(|b| b.gain_db = 0., cx) + }), + ) + .child("Flatten this"), + ) + } + + /// The colour card: the graded frame's histogram over a row per control, + /// each row a bar the pointer drags straight to a value -- no stepper + /// buttons, because a slider is a thing to pull, and the arrow keys still + /// move the same value for anyone not using a pointer. Same scrim, surface + /// and row shape as the other two cards, and the same plain divs, so the + /// root keeps the keyboard. + /// + /// The values are read from the project every render: what is drawn is what + /// the decoder is grading with, never a copy that could drift from it. The + /// graph above them is counted off the frame that came *back* through that + /// grade ([`histogram`]), so pulling exposure tilts it while the hand moves. + pub(crate) fn color_card(&self, cx: &mut Context) -> Option { + let (lane, idx) = self.color_open?; + let params = self.color_params(); + let rows: Vec<_> = COLOR_BANDS + .iter() + .enumerate() + .map(|(i, &(label, low, high))| { + let mut read = params; + let value = *band_mut(&mut read, i); + let frac = ((value - low) / (high - low)).clamp(0., 1.); + let picked = i == self.color_band; + div() + .id(("color-row", i)) + .flex() + .min_h(px(KEYS_ROW_H)) + .items_center() + .gap(px(8.)) + .px(px(6.)) + .rounded(px(3.)) + .cursor_pointer() + .when(picked, |d| d.bg(rgb(BG_SELECTED))) + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.color_band = i; + cx.notify(); + })) + .child(div().flex_1().min_w(px(0.)).truncate().child(label)) + .child( + // The bar is 4 px to look at and a whole row to hit + // (WCAG 2.5.8), the same split the ruler makes between + // what is drawn and what is grabbed. The press is + // already the first sample of the drag, so a plain click + // sets the value it landed on. + div() + .id(("color-bar", i)) + .relative() + .w(px(COLOR_BAR_W)) + .h(px(KEYS_ROW_H)) + .flex() + .items_center() + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, event: &MouseDownEvent, _, cx| { + this.color_band = i; + this.color_dragging = true; + this.drag_color(event.position.x, true, cx); + }), + ) + .child(bounds_probe(self.color_bars[i].clone())) + .child( + div() + .w_full() + .h(px(4.)) + .rounded(px(2.)) + .bg(rgb(BG_PANEL)) + .child( + div() + .h_full() + .w(relative(frac)) + .rounded(px(2.)) + .bg(rgb(ACCENT_PRIMARY)), + ), + ), + ) + .child( + div() + .w(px(44.)) + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child(format!("{value:.2}")), + ) + }) + .collect(); + Some( + scrim() + .flex() + .justify_center() + .items_center() + .bg(rgba(SCRIM)) + // Click away closes it, as on every card here. + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _: &MouseDownEvent, _, cx| { + this.close_card(); + cx.notify(); + cx.stop_propagation(); + }), + ) + .child( + div() + .w(px(COLOR_W)) + .on_mouse_down(MouseButton::Left, swallow) + .flex() + .flex_col() + .gap(px(2.)) + .p(px(12.)) + .rounded(px(6.)) + .bg(rgb(BG_RAISED)) + .child(div().flex_none().px(px(6.)).child(format!( + "Colour — {} clip {}", + lane.label(), + idx + 1 + ))) + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child( + "drag a bar, or ↑↓ picks one and ←→ moves it, r resets — a click away or esc closes", + ), + ) + // The frame as it is being graded, over the controls + // grading it: the three lines are what the picture is + // made of, and every sample of a drag reseeks, so they + // move with the bar under the hand. + .child( + div() + .flex_none() + .h(px(HIST_H)) + .rounded(px(3.)) + .bg(rgb(BG_HOVER_DIM)) + .relative() + .child(hist_curves(self.histogram)), + ) + .children(rows) + .child( + div() + .id("color-reset") + .mt(px(4.)) + .flex() + .h(px(CONTROL_H)) + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(BG_SELECTED)) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + this.set_color(ColorParams::default(), cx); + })) + .child("Reset"), + ), + ), + ) + } + + /// The speed card: one bar from a quarter speed to four times it, the rates + /// people name as buttons under it, and the clip's new length in frames -- + /// which is the number a person is actually choosing. Built like the colour + /// card down to the scrim and the bar's own hit height, because it is the + /// same kind of card: one continuous value on one clip, live at the clip as + /// it moves. + /// + /// Honest about what it does: the sound is *resampled*, so the pitch goes up + /// with the rate, which is what the tape in the title means. + pub(crate) fn speed_card(&self, cx: &mut Context) -> Option { + let (lane, idx) = self.speed_open?; + let speed = self.card_speed(); + let session = self.session.as_ref()?; + let clip = session.lane_clips(lane).get(idx).copied()?; + let lo = f32::from(Speed::MIN.permille()); + let hi = f32::from(Speed::MAX.permille()); + let frac = ((f32::from(speed.permille()) - lo) / (hi - lo)).clamp(0., 1.); + let presets: Vec<_> = SPEED_PRESETS + .into_iter() + .map(|permille| { + let at = Speed::from_permille(permille); + div() + .id(("speed-preset", usize::from(permille))) + .flex_1() + .flex() + .h(px(CONTROL_H)) + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(match at == speed { + true => BG_SELECTED, + false => BG_PANEL, + })) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.set_speed(at, cx); + })) + .child(format!("{at}")) + }) + .collect(); + Some( + scrim() + .flex() + .justify_center() + .items_center() + .bg(rgba(SCRIM)) + // Click away closes it, as on every card here. + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _: &MouseDownEvent, _, cx| { + this.close_card(); + cx.notify(); + cx.stop_propagation(); + }), + ) + .child( + div() + .w(px(COLOR_W)) + .on_mouse_down(MouseButton::Left, swallow) + .flex() + .flex_col() + .gap(px(6.)) + .p(px(12.)) + .rounded(px(6.)) + .bg(rgb(BG_RAISED)) + .child(div().flex_none().px(px(6.)).child(format!( + "Speed (tape) — {} clip {}", + lane.label(), + idx + 1 + ))) + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child( + "drag the bar or ←→ moves it, r is 1.00x — the pitch moves with the rate; a click away or esc closes", + ), + ) + .child( + // 4 px to look at and a whole row to hit (WCAG + // 2.5.8), the split the colour sliders and the ruler + // both make. + div() + .id("speed-bar") + .relative() + .w_full() + .h(px(KEYS_ROW_H)) + .flex() + .items_center() + .cursor_pointer() + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, event: &MouseDownEvent, _, cx| { + this.speed_dragging = true; + this.drag_speed(event.position.x, true, cx); + }), + ) + .child(bounds_probe(self.speed_bar.clone())) + .child( + div() + .w_full() + .h(px(4.)) + .rounded(px(2.)) + .bg(rgb(BG_PANEL)) + .child( + div() + .h_full() + .w(relative(frac)) + .rounded(px(2.)) + .bg(rgb(ACCENT_PRIMARY)), + ), + ), + ) + .child(div().flex().gap(px(4.)).children(presets)) + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + // What the choice *is*, in the numbers the + // timeline is measured in: the source range + // never moves, the room it takes does. + .child(format!( + "{speed} — {} source frames over {} on the timeline ({})", + clip.len(), + clip.frames(), + timecode(f64::from(clip.frames()) / self.fps, self.fps) + )), + ), + ), + ) + } + + /// The mix card: one fader per audio track and the master limiter under + /// them -- the two settings that belong to the *sound of the whole + /// timeline* rather than to any clip on it. + /// + /// A track's fader moves everything on that track by the same amount, + /// every frequency of it: it is not the equalizer (one take, one band) and + /// it is not the volume in the panel, which is what this machine monitors + /// at and is written to no file. The limiter is over the sum of them all, + /// which is where a mix can pass full scale and where a clamp used to + /// square it off. + /// + /// The silence card's shape, down to the steppers: a row is a label, a + /// value and the two presses that move it, and the arrows pick a row and + /// move it too. The rows scroll rather than the card growing past the + /// window -- a timeline may hold more tracks than a 360 px window has room + /// for faders. + pub(crate) fn mix_card(&self, cx: &mut Context) -> Option { + if !self.mix_open { + return None; + } + let session = self.session.as_ref(); + let lanes = self.mix_lanes(); + let limiter = session.map_or_else(Limiter::default, PlaybackSession::limiter); + let mut rows: Vec<(String, String)> = lanes + .iter() + .map(|&lane| { + let db = session.map_or(0., |s| s.lane_gain_db(lane)); + (format!("{} plays at", lane.label()), format!("{db:+.0} dB")) + }) + .collect(); + // The ceiling in dBFS and the faders in dB, the silence card's rule: + // a ceiling is a level below full scale, a fader is a change. + rows.push(( + "Limiter ceiling".into(), + format!("{:+.0} dBFS", limiter.ceiling_db), + )); + rows.push(( + "Limiter".into(), + match limiter.on { + true => "on".into(), + false => "off".into(), + }, + )); + let rows: Vec<_> = rows + .into_iter() + .enumerate() + .map(|(n, (label, value))| { + div() + .id(("mix-row", n)) + .flex() + .flex_none() + .min_h(px(KEYS_ROW_H)) + .items_center() + .justify_between() + .px(px(6.)) + .rounded(px(3.)) + .bg(rgb(match n == self.mix_field { + true => BG_SELECTED, + false => BG_PANEL, + })) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.mix_field = n; + cx.notify(); + })) + .child(div().text_color(rgb(FG_SECONDARY)).child(label)) + .child( + div() + .flex() + .items_center() + .gap(px(4.)) + .child(value) + .children([-1, 1].map(|steps: i32| { + div() + .id(("mix-step", n * 2 + usize::from(steps > 0))) + .flex_none() + .w(px(HIT_MIN)) + .h(px(KEYS_ROW_H)) + .flex() + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(BG_PANEL)) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + // Picked as well as moved, the silence + // card's rule: the row a press lands on + // is the row the arrows carry on from. + this.mix_field = n; + this.nudge_mix(steps, cx); + })) + .child(match steps > 0 { + true => "+", + false => "−", + }) + })), + ) + }) + .collect(); + Some( + scrim() + .flex() + .justify_center() + .items_center() + .bg(rgba(SCRIM)) + // Click away closes it, as on every card here. + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _: &MouseDownEvent, _, cx| { + this.close_card(); + cx.notify(); + cx.stop_propagation(); + }), + ) + .child( + div() + .w(px(COLOR_W)) + .on_mouse_down(MouseButton::Left, swallow) + .max_h(px(360. - 24.)) + .flex() + .flex_col() + .gap(px(6.)) + .p(px(12.)) + .rounded(px(6.)) + .bg(rgb(BG_RAISED)) + .child( + div() + .flex_none() + .px(px(6.)) + .child("Mix — track volumes and the master limiter"), + ) + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child( + "− and + move a setting, or ↑↓ picks one and ←→ moves it (hold to run it) — a track fader moves everything on that track; a click away or esc closes", + ), + ) + .child( + div() + .id("mix-rows") + .flex() + .flex_col() + .gap(px(6.)) + .overflow_y_scroll() + .children(rows), + ) + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + // What the choice *is*: the limiter's own line, + // because "on" alone says nothing about what it + // does to a mix that never reaches the ceiling. + .child(match limiter.on { + true => format!( + "the mix is held under {:+.0} dBFS — quieter passages are untouched", + limiter.ceiling_db + ), + false => "the limiter is out of circuit — a hot mix clips at full scale".to_string(), + }), + ), + ), + ) + } + + /// The silence card: what the scan is looking for, what it found, and the + /// two things that can be done about it. + /// + /// Its scrim is the lightest of the cards' on purpose. Every other card is + /// about the clip it names and can black the timeline out; this one is + /// *about* the timeline -- the marks under it are the whole preview -- so + /// the bed stays readable and the card sits up in the picture area rather + /// than over the lanes. + pub(crate) fn silence_card(&self, cx: &mut Context) -> Option { + let (lane, idx) = self.silence_open?; + let cfg = self.silence; + // The unit is a label, never a conversion: the threshold is a level + // below full scale whichever of the two the row says (`silence_dbfs`). + let unit = match self.silence_dbfs { + true => "dBFS", + false => "dB", + }; + let rows = [ + ("Apply to", self.silence_scope.label(&self.silence_lanes())), + ( + "Silence is under", + format!("{:.0} {unit}", cfg.threshold_db), + ), + ("Level read in", format!("{unit} (0 = full scale)")), + ( + "Forgive quiet shorter than", + format!("{:.2} s", cfg.min_silence), + ), + ( + "Keep either side of speech", + format!("{:.2} s", cfg.padding), + ), + ( + "Swallow kept slivers under", + format!("{:.2} s", cfg.min_keep), + ), + ("Speed-up plays at", format!("{}", self.silence_factor)), + ]; + let found = self.silence_marks.len(); + let secs = + f64::from(self.silence_marks.iter().map(|&(_, len)| len).sum::()) / self.fps; + // The line under the rows: where a scan still running has got to -- a + // card is up from the frame it is asked for, numbers or no numbers -- + // or what the settings found in levels already read. + let status = match &self.silence_scan { + Some(scan) => silence_line( + scan.seen as f32 / 10., + scan.progress.total.load(std::sync::atomic::Ordering::Relaxed) as f32 / 10., + scan.started.elapsed().as_secs_f32(), + scan.since.elapsed().as_secs_f32(), + ), + None => match found { + 0 => "nothing quiet enough for long enough".to_string(), + 1 => format!("1 silence, {}", secs_label(secs)), + n => format!("{n} silences, {}", secs_label(secs)), + }, + }; + let rows: Vec<_> = rows + .into_iter() + .enumerate() + .map(|(n, (label, value))| { + div() + .id(("silence-row", n)) + .flex() + .min_h(px(KEYS_ROW_H)) + .items_center() + .justify_between() + .px(px(6.)) + .rounded(px(3.)) + .bg(rgb(match n == self.silence_field { + true => BG_SELECTED, + false => BG_PANEL, + })) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.silence_field = n; + cx.notify(); + })) + .child(div().text_color(rgb(FG_SECONDARY)).child(label)) + // The value and the two steps that move it. Every other + // card has something to drag or press; this one had the + // arrow keys and nothing else, so a row was a setting a + // pointer could pick but never change. One press each, the + // same call the arrows make -- the hold-to-run is the + // keyboard's own and is not a thing a button has. + .child( + div() + .flex() + .items_center() + .gap(px(4.)) + .child(value) + .children([-1, 1].map(|steps: i32| { + div() + .id(("silence-step", n * 2 + usize::from(steps > 0))) + .flex_none() + .w(px(HIT_MIN)) + .h(px(KEYS_ROW_H)) + .flex() + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(BG_PANEL)) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + // Picked as well as moved: the row a + // press lands on is the row the arrows + // carry on from. + this.silence_field = n; + this.nudge_silence(steps); + cx.notify(); + })) + .child(match steps > 0 { + true => "+", + false => "−", + }) + })), + ) + }) + .collect(); + // The two buttons the ask names, side by side: a mode toggle would hide + // one of them behind the other, and there are only two. + let button = |n: usize, text: String, act: fn(&mut Self, &mut Context)| { + div() + .id(("silence-apply", n)) + .flex_1() + .flex() + .min_h(px(KEYS_ROW_H)) + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(match found { + 0 => BG_PANEL, + _ => BG_SELECTED, + })) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| act(this, cx))) + .child(text) + }; + Some( + scrim() + .flex() + .justify_center() + .items_start() + .pt(px(HEADER_H + 8.)) + // Light enough to read the lanes and the marks on them through: + // the preview is the point of this card. + .bg(rgba(SCRIM_LIGHT)) + // Click away closes it, as on every card here -- and the marks + // go with it, which is what makes this one a call and not a flag. + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _: &MouseDownEvent, _, cx| { + this.close_card(); + cx.notify(); + cx.stop_propagation(); + }), + ) + .child( + div() + .w(px(COLOR_W)) + .on_mouse_down(MouseButton::Left, swallow) + .flex() + .flex_col() + .gap(px(6.)) + .p(px(12.)) + .rounded(px(6.)) + .bg(rgb(BG_RAISED)) + .child(div().flex_none().px(px(6.)).child(format!( + "Silences — {} clip {}", + lane.label(), + idx + 1 + ))) + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child( + "− and + move a setting, or ↑↓ picks one and ←→ moves it (hold to run it) — the marks on the lane are what would go; a click away or esc closes", + ), + ) + .children(rows) + .child( + div() + .flex_none() + .px(px(6.)) + .text_color(rgb(match (&self.silence_scan, found) { + (None, 1..) => ACCENT_PRIMARY, + _ => FG_SECONDARY, + })) + .child(status), + ) + .child(div().flex().gap(px(4.)).children([ + button(0, "Cut them out (enter)".into(), Self::cut_silences), + button( + 1, + format!("Play them at {} (f)", self.silence_factor), + Self::speed_silences, + ), + ])), + ), + ) + } +} diff --git a/crates/app/src/ui/inspector.rs b/crates/app/src/ui/inspector.rs new file mode 100644 index 0000000..e69de29 diff --git a/crates/app/src/ui/library.rs b/crates/app/src/ui/library.rs new file mode 100644 index 0000000..4c569f4 --- /dev/null +++ b/crates/app/src/ui/library.rs @@ -0,0 +1,472 @@ +//! The media library: the left panel's rows and the menu over them. + +use crate::*; +use crate::ui::widgets::*; + +impl Player { + /// The media library: a row per source the timeline knows, in the order + /// they arrived, each wearing the tint its clips wear in the lanes -- the + /// swatch *is* what says which boxes down there came from this file. A + /// click picks a row, the button under the list drops that source in at the + /// playhead, and a row dragged onto either lane does the same thing through + /// the same call. + /// + /// Import lives here, because this is the list it adds to. Plain divs like + /// the rest of this window: nothing in it takes focus, so the root keeps + /// the keyboard and the play key still works after a row is clicked + /// (ledger:182). + pub(crate) fn library(&self, width: f32, viewport_h: f32, cx: &mut Context) -> impl IntoElement { + let exporting = self.exporting().is_some(); + let sources = self + .session + .as_ref() + .map_or(&[][..], PlaybackSession::sources); + // Every source matches the first in size and rate or it was refused at + // the door (the import policy, ledger:436), so the session's own meta + // describes every row and nothing has to be probed to say so. + let meta = self.session.as_ref().map(PlaybackSession::meta); + // Its own length, not one derived from what is on the lanes: a row + // imported and never placed is a row with a length, and it is the + // length a drag would put down. + let rows: Vec<_> = library_rows( + sources, + &self.streams, + &self.decoders, + self.timeline_audio(), + |path| { + self.session + .as_ref() + .map_or(0, |session| session.file_frames(path)) + }, + ) + .into_iter() + .enumerate() + .map(|(i, row)| { + let picked = self + .selected_asset + .as_ref() + .is_some_and(|p| *p == (row.path.clone(), row.stream)); + let name: SharedString = row.name.clone().into(); + let says: String = match (&row.unusable, meta) { + // A greyed row says why in full, where its length would be: + // the list is the one place the file's own tracks are named. + (Some(why), _) => format!("{} — {why}", row.path.display()), + // A file with no picture has no size and no frame rate to + // report, and only one lane it can go on: saying so is the + // difference between a hint and a lie. + (None, _) if engine::is_audio(&row.path) => format!( + "{} — audio only · drag onto the audio lane, or Add at playhead", + row.path.display() + ), + // A still is the mirror: its own size (the timeline's meta + // describes video, and a picture placed on that canvas is not + // the same shape), no frame rate, and one kind of lane. + (None, _) if engine::is_image(&row.path) => format!( + "{} — still image{} · drag onto a video lane, or Add at playhead", + row.path.display(), + match self.sizes.get(&row.path).copied().flatten() { + Some((w, h)) => format!(" · {w}x{h}"), + None => String::new(), + } + ), + // The file's *own* frame rate, not the timeline's: a clip shot + // at another rate plays at the speed it was shot at, and the + // row that says where it came from has to say which rate that + // was. + (None, Some(meta)) => format!( + "{} — {}x{} @ {:.2} fps · drag it where you want it, or Add at playhead", + row.path.display(), + meta.width, + meta.height, + self.session + .as_ref() + .map_or(meta.frame_rate, |session| session.file_fps(&row.path)) + ), + (None, None) => row.path.display().to_string(), + }; + // The menu is the third way into a row, after the click and the + // drag, and a right-click nothing advertises is one nobody finds. + let tip: SharedString = format!("{says} · right-click for more").into(); + let ghost = name.clone(); + // What the second line says: the stream, then either its length or + // the reason it cannot be used. + let under = match &row.unusable { + Some(why) => join_detail(&row.detail, why), + // A still has no length to report -- the ten minutes it is + // *held* to is a wall, not a duration -- so the line says what + // it is and how big it is instead. + None if engine::is_image(&row.path) => join_detail( + &row.detail, + &match self.sizes.get(&row.path).copied().flatten() { + Some((w, h)) => format!("still image · {w}x{h}"), + None => "still image".to_string(), + }, + ), + None => join_detail( + &row.detail, + &timecode(f64::from(row.frames) / self.fps, self.fps), + ), + }; + let usable = row.unusable.is_none(); + let (path, stream) = (row.path.clone(), row.stream); + let dragged = (path.clone(), stream); + let menu_path = path.clone(); + div() + .id(("asset", i)) + .flex_none() + .h(px(ROW_H)) + .flex() + .items_center() + .gap(px(6.)) + .pr(px(6.)) + .rounded(px(3.)) + // A row that cannot be placed takes no click and no drag, and + // reads as unavailable rather than merely unlucky. + .when(!usable, |d| d.text_color(rgb(FG_SECONDARY)).opacity(0.55)) + .when(usable, |d| { + d.cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.selected_asset = Some((path.clone(), stream)); + cx.notify(); + })) + // The drag carries the row's file and stream and the + // row's name: one for the drop to insert, one for the + // pointer to carry, so what is being dragged is legible + // on the way down. + .on_drag(AssetDrag(dragged.0, dragged.1), move |_, _, _, cx| { + cx.new(|_| Tip(ghost.clone())) + }) + }) + // The right button hangs the row's own menu at the pointer. + // Every row takes it, greyed ones included: a file that cannot + // join this timeline can still be revealed, described and taken + // out of the list, and Add is the one item that then refuses -- + // in the engine's words, where the row's grey already says why. + .on_mouse_down( + MouseButton::Right, + cx.listener(move |this, event: &MouseDownEvent, _, cx| { + if this.modal() { + return; + } + // Picked as a left-click would pick it, so the row the + // menu is about is the row that reads as chosen -- but + // only a row that *can* be picked, which is what keeps + // the Add button under the list honest. + if usable { + this.selected_asset = Some((menu_path.clone(), stream)); + } + this.library_menu = Some(LibraryMenu { + path: menu_path.clone(), + stream, + at: event.position, + details: false, + }); + cx.notify(); + }), + ) + .when(picked, |d| d.bg(rgb(BG_SELECTED)).border_1()) + .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into()) + // Full height and hard against the edge: the tint reads as + // the lane's colour continuing into the list, not as a chip + // that happens to be near it. + .child( + div() + .flex_none() + .w(px(SWATCH_W)) + .h_full() + .rounded(px(2.)) + .bg(rgb(source_tint(row.tint))), + ) + .child( + div() + .flex_1() + .min_w(px(0.)) + .flex() + .flex_col() + // Two lines rather than two columns: at the width + // this panel yields to, a name and a timecode side + // by side leave room for neither. + // Cut out of the middle, not the end: two episodes off + // one release are the same words up to the number, and + // the number is at the end. + .child( + div() + .truncate() + .text_size(px(11.)) + .child(clip_middle(&name, row_text_w(width))), + ) + .child( + div() + .truncate() + .text_size(px(10.)) + .text_color(rgb(FG_SECONDARY)) + .child(under), + ), + ) + }) + .collect(); + div() + .flex_none() + .w(px(width)) + .h_full() + .flex() + .flex_col() + .gap(px(6.)) + .p(px(8.)) + .bg(rgb(BG_PANEL)) + .child( + div() + .flex_none() + .flex() + .items_center() + .gap(px(6.)) + .child( + div() + .flex_1() + .min_w(px(0.)) + .truncate() + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child("Media"), + ) + .child(control( + "import", + None, + "Import", + "adds a file to this list — or drop one on the window".to_string(), + !exporting, + cx.listener(|this, _: &ClickEvent, _, cx| this.pick_and_import(cx)), + )), + ) + .child( + div() + .id("library-rows") + .flex_1() + .min_h(px(0.)) + .flex() + .flex_col() + .gap(px(2.)) + .overflow_y_scroll() + // Never a blank column: with nothing imported the list is + // where the way in is said. + .when(rows.is_empty(), |d| { + d.child( + div() + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child("No media yet — Import, or drop a file on the window"), + ) + }) + .children(rows), + ) + // Under the media it belongs to: a subtitle track is not a source -- + // it goes on no lane and is dragged nowhere -- but it is a thing the + // timeline holds, and this is the list of those. + .children(self.subtitle_section(width, viewport_h, cx)) + .child(control( + "add-asset", + None, + "Add at playhead", + match self.selected_asset { + Some(_) => "inserts the picked file at the playhead".to_string(), + None => "click a file above first — or drag one where you want it".to_string(), + }, + can_add( + self.selected_asset.as_ref(), + self.session.is_some(), + exporting, + ), + cx.listener(|this, _: &ClickEvent, _, cx| { + if let Some((path, stream)) = this.selected_asset.clone() { + // No lane: the button means "wherever this belongs", + // which for a file with no picture is the audio lane. + this.insert_source(&path, stream, None, None, cx); + } + }), + )) + } + + /// The menu a right-click on a library row opens: what can be done with the + /// *file* rather than with a clip of it, and a turn-over side saying what + /// that file is. Built like [`Player::context_card`] down to the scrim, the + /// row height and the clamp, because it is the same menu on the other panel + /// -- a click away or any stroke closes it. + pub(crate) fn library_card( + &self, + viewport: Size, + cx: &mut Context, + ) -> Option { + let menu = self.library_menu.clone()?; + let path = menu.path.clone(); + let row = |n: usize| { + div() + .id(("library-menu", n)) + .flex() + .min_h(px(MENU_ROW_H)) + .items_center() + .justify_between() + .gap(px(12.)) + .px(px(6.)) + .rounded(px(3.)) + }; + let mut rows: Vec = Vec::new(); + // What every item of this menu is answered from, read once. + let ctx = self.row_ctx(&path, menu.stream); + if menu.details { + // What the library knows about this row and nothing probed for the + // card: the streams table is filled once per file at import. + let info = self + .streams + .get(&path) + .and_then(|of_file| of_file.iter().find(|s| s.index == menu.stream)); + let frames = self + .session + .as_ref() + .map_or(0, |session| session.file_frames(&path)); + // How many clips play from this exact row -- the number that + // decides whether Remove is refused, so the card answers the + // question the refusal would otherwise raise. + let placed = ctx.placed; + // A still is described by what it has -- a picture, a size, and a + // longest it may be held for -- where a media file is described by + // its streams and its length. Same card, the rows that mean + // something for this kind of source. + let image = engine::is_image(&path); + let kind = match self.sizes.get(&path).copied().flatten() { + Some((w, h)) => format!("still image · {w}x{h}"), + None => "still image".to_string(), + }; + for (label, value) in [ + ("File", file_name(&path)), + ("Path", path.display().to_string()), + match image { + true => ("Picture", kind), + false => ( + "Audio", + info.map_or_else(|| "no track of its own".to_string(), stream_detail), + ), + }, + ( + "Bitrate", + bitrate_detail( + self.bitrates.get(&path).copied().flatten(), + self.streams.get(&path).map_or(0, Vec::len), + ), + ), + match image { + true => ( + "Longest hold", + timecode(f64::from(frames) / self.fps, self.fps), + ), + false => ("Length", timecode(f64::from(frames) / self.fps, self.fps)), + }, + ("On the timeline", format!("{placed} clips")), + ] { + rows.push( + row(rows.len()) + .child(label) + .child( + div() + .min_w(px(0.)) + .truncate() + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child(value), + ) + .into_any_element(), + ); + } + } else { + // The oracle's list, exactly as the clip menu takes its rows from + // `menu_items`: an item that means nothing for the file that was + // right-clicked is not a row, and one this moment refuses is drawn + // dimmed and says why in place of its hint. + for item in row_items(ctx) { + let refusal = row_enable(item, ctx); + let enabled = refusal.yes(); + rows.push( + row(rows.len()) + .child(item.label()) + .child( + div() + .min_w(px(0.)) + .truncate() + .text_color(rgb(FG_SECONDARY)) + .child(refusal.why().unwrap_or_else(|| item.hint())), + ) + .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) + .when(enabled, |d| { + d.cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.act_on_row(item, cx); + })) + }) + .into_any_element(), + ); + } + } + // Placed by the height it is drawn to, and drawn to what the window has + // room for -- the clip menu's rule, one function for all three. + let list_h = menu_rows_h(rows.len(), viewport); + let (x, y) = menu_at(menu.at, viewport, MENU_PAD * 2. + list_h); + let full: SharedString = path.display().to_string().into(); + Some( + scrim() + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _: &MouseDownEvent, _, cx| { + this.library_menu = None; + cx.notify(); + cx.stop_propagation(); + }), + ) + .on_mouse_down( + MouseButton::Right, + cx.listener(|this, _: &MouseDownEvent, _, cx| { + this.library_menu = None; + cx.notify(); + cx.stop_propagation(); + }), + ) + .child( + div() + .id("library-menu-card") + .absolute() + .left(px(x)) + .top(px(y)) + .w(px(MENU_W)) + .flex() + .flex_col() + .p(px(MENU_PAD)) + .rounded(px(6.)) + .bg(rgb(BG_RAISED)) + // Painted after the scrim, so this listener runs first + // and a press meant for an item never closes the menu + // out from under its own click (`context_card`). + .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| { + cx.stop_propagation() + }) + .on_mouse_down(MouseButton::Right, |_: &MouseDownEvent, _, cx| { + cx.stop_propagation() + }) + .when(menu.details, |d| { + d.tooltip(move |_, cx| cx.new(|_| Tip(full.clone())).into()) + }) + // Scrolls where the window has no room for the list, + // like the clip menu's -- an item hanging off the bottom + // edge is an item nobody can click. + .child( + div() + .id("library-menu-rows") + .flex() + .flex_col() + .max_h(px(list_h)) + .overflow_y_scroll() + .children(rows), + ), + ), + ) + } +} diff --git a/crates/app/src/ui/mod.rs b/crates/app/src/ui/mod.rs new file mode 100644 index 0000000..4d268c1 --- /dev/null +++ b/crates/app/src/ui/mod.rs @@ -0,0 +1,14 @@ +//! Every pixel this editor draws, one module per region of the window. +//! +//! The whole UI used to be one 19,916-line file with one `Render` impl in it, +//! which is why a colour or a rule fixed in one place kept surviving in the +//! next: there was no seam to sweep. The seams are the regions themselves. +pub mod cards; +pub mod inspector; +pub mod library; +pub mod overlays; +pub mod preview; +pub mod theme; +pub mod timeline; +pub mod toolbar; +pub mod widgets; diff --git a/crates/app/src/ui/overlays.rs b/crates/app/src/ui/overlays.rs new file mode 100644 index 0000000..deeeed8 --- /dev/null +++ b/crates/app/src/ui/overlays.rs @@ -0,0 +1,776 @@ +//! The bars and the floating cards that are not inspector sections. + +use crate::*; +use crate::ui::widgets::*; + +impl Player { + /// The running import holds its own bar above the notice's, for the notice + /// bar's reason: the message is the point. Not a notice, though -- nothing + /// dismisses it, because it is about work still going on, and it leaves by + /// itself when the file lands. + /// + /// The bar under the words is a *sweep*, not a fill: neither read reports + /// where in the file it is, so a fill would have to invent the one number + /// this cannot know. What it does say truthfully is "something is still + /// running", which is exactly the question a frozen-looking window raises. + /// + /// ...and beside them the way out. A read that may be twenty seconds of a + /// cold 24 GB film needs one, and the only honest place for it is the line + /// that says the read is happening ([`Player::cancel_import`]). + pub(crate) fn import_bar(&self, cx: &mut Context) -> Option { + let import = self.importing.as_ref()?; + let elapsed = import.started.elapsed().as_secs_f32(); + let line = import_line( + &file_name(&import.path), + import.seen, + elapsed, + import.since.elapsed().as_secs_f32(), + self.imports.len(), + arrival(self.opening.as_deref(), &import.path) != Landing::Import, + ); + // A quarter of the bar, crossing it every three seconds and wrapping. + // Tied to the elapsed clock, so it moves for as long as the read does + // and stops dead the instant the file lands. + const SWEEP: f32 = 0.25; + let at = (elapsed / 3.).fract() * (1. + SWEEP) - SWEEP; + Some( + div() + .flex_none() + .flex() + .flex_col() + .gap(px(4.)) + .px(px(12.)) + .py(px(6.)) + .bg(rgb(BG_RAISED)) + .child( + div() + .flex() + .items_center() + .gap(px(8.)) + .child(div().flex_1().min_w(px(0.)).child(line)) + .child(control( + "cancel-import", + None, + "Cancel", + "stops this file and anything queued behind it; the read already \ + running finishes unheeded" + .to_string(), + true, + cx.listener(|this, _: &ClickEvent, _, cx| this.cancel_import(cx)), + )), + ) + .child( + div() + .relative() + .w_full() + .h(px(2.)) + .bg(rgb(BG_HOVER)) + .child( + div() + .absolute() + .top_0() + .left(relative(at.max(0.))) + // Clipped at both ends by hand: the segment + // enters from the left edge and leaves past the + // right one, and a width that overhung would + // paint outside the track. + .w(relative((at + SWEEP).min(1.) - at.max(0.))) + .h(px(2.)) + .bg(rgb(ACCENT_PRIMARY)), + ), + ), + ) + } + + /// The line a long-standing seek shows, in the import bar's place and by the + /// import bar's rules: nothing dismisses it, and it leaves by itself the + /// moment the frame lands. No sweep under it -- an open reports nothing about + /// where it has got to, and the clock is the honest half of that bar anyway. + pub(crate) fn seek_bar(&self) -> Option { + let line = seek_line(self.seek_since.map(|t| t.elapsed()))?; + Some( + div() + .flex_none() + .px(px(12.)) + .py(px(6.)) + .bg(rgb(BG_RAISED)) + .child(line), + ) + } + + /// A notice holds its own bar, full width, until it is answered: any key + /// retires it (the key handler) and so does a click on it. Its own surface + /// because the message is the point -- a failure cut to the timecode's slot + /// is a failure nobody read. + /// + /// The export's own line is more than a message: it names a file that is + /// now on disk, so the same click that retires it shows that file in the + /// desktop's file manager. + pub(crate) fn notice_bar(&self, cx: &mut Context) -> Option { + let notice = self.notice.clone()?; + // The path travels with the text it was written for: a later notice + // holds the bar and the click is a plain dismissal again. + let exported = self + .exported + .clone() + .filter(|_| notice.starts_with(EXPORT_DONE)); + let hint = match exported { + Some(_) => "click — open file location", + None => "click or press any key to dismiss", + }; + Some( + div() + .id("notice") + .when(exported.is_some(), |d| { + d.tooltip(|_, cx| { + cx.new(|_| { + Tip("Open file location — shows the export in the file manager".into()) + }) + .into() + }) + }) + .flex_none() + .flex() + .items_start() + .gap(px(12.)) + .px(px(12.)) + .py(px(6.)) + .bg(rgb(BG_RAISED)) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + // Another process starting: off the UI thread, and it + // outlives the notice it was asked from. + if let Some(path) = exported.clone() { + cx.background_executor() + .spawn(async move { show_in_file_manager(&path) }) + .detach(); + } + this.notice = None; + cx.notify(); + })) + .child(div().flex_1().min_w(px(0.)).child(notice)) + .child( + div() + .flex_none() + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child(hint), + ), + ) + } + + /// Every binding, and the way to change one: a row per entry, click it and + /// the next stroke becomes its chord. Over the whole window, because while + /// it is up nothing under it may answer -- the scrim stops the clicks + /// (gpui dispatches mouse listeners topmost-first, window.rs:3705) and the + /// key handler's own branch stops the strokes. + /// + /// Plain divs, like every control here: nothing in it takes focus, so the + /// root is still the one reading the keyboard -- which is exactly what a + /// waiting row depends on. + pub(crate) fn keys_overlay(&self, cx: &mut Context) -> Option { + if !self.keys_open { + return None; + } + // The way out, spelled the way the rows spell a chord. + let out = keymap::Chord { + key: ESCAPE.to_string(), + ctrl: false, + } + .pretty(); + // Every action there is, under its heading, and the strokes the modal + // cards answer to beside them -- `keys_rows` is the whole of the order + // and every word in it comes off the registry. + // + // A row is two targets, not one: its label *does* the action, which is + // the pointer's way to the ones no button carries, and its stroke + // changes that stroke. An action with two strokes reads as one line + // ("x or delete") and a rebind replaces that whole set. + let mut rows: Vec = Vec::new(); + let row = || { + div() + .flex() + // The floor, not the height: a row that needed two lines + // would otherwise paint over the one under it -- which it did + // anyway until this said `flex_none`, a row inside a capped + // scrolling list being shrunk to fit by default (the export + // card's rows had the same shape and the same overlap). + .flex_none() + .min_h(px(KEYS_ROW_H)) + .items_center() + .justify_between() + .gap(px(12.)) + .px(px(6.)) + .rounded(px(3.)) + }; + let found = keys_filter(&self.keys_search, &self.keymap); + // What the search box says: the typed text, and how much of the list is + // left under it -- a filter that found nothing has to say so, or the + // card reads as a list that lost its rows. + let search = if self.keys_search.is_empty() { + "search: type to filter · ↑ ↓ scroll the list · a click away closes".to_string() + } else { + let rows = found + .iter() + .filter(|(_, r)| !matches!(r, KeyRow::Head(_))) + .count(); + match rows { + 0 => format!( + "search: {} — nothing matches · {out} clears", + self.keys_search + ), + n => format!("search: {} — {n} shown · {out} clears", self.keys_search), + } + }; + for (i, key_row) in found { + rows.push(match key_row { + KeyRow::Head(category) => div() + .flex_none() + .px(px(6.)) + .pt(px(4.)) + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child(category.label()) + .into_any_element(), + KeyRow::Act(action) => { + let capturing = self.rebinding == Some(action); + // Why the label half will not answer, if it will not: the + // registry's one answer, the same the clip menu dims by. + let refusal = self.enable(action, None); + let out = out.clone(); + row() + .when(capturing, |d| d.bg(rgb(BG_SELECTED))) + .child( + div() + .id(("do", i)) + .flex_1() + .min_w(px(0.)) + .flex() + .min_h(px(KEYS_ROW_H)) + .items_center() + // One line, cut where the stroke's column + // starts: a label longer than the room it has + // printed straight over the stroke beside it, + // and two overprinted words are less readable + // than one truncated one. + .truncate() + .child(action.label()) + // The reason rides on the label rather than in + // the stroke column, which the rebind half + // needs whatever the editor's state is: an + // action nobody can ask for right now is still + // one whose key may be changed. + .when_some(refusal.why(), |d, why| { + let why: SharedString = why.into(); + d.tooltip(move |_, cx| cx.new(|_| Tip(why.clone())).into()) + }) + .when(!refusal.yes(), |d| d.opacity(0.4).cursor_not_allowed()) + .when(refusal.yes(), |d| { + d.cursor_pointer().hover(|s| s.bg(rgb(BG_HOVER))).on_click( + cx.listener(move |this, _: &ClickEvent, _, cx| { + // The card goes first: several of + // these open a card of their own, + // and every edit moves the indices + // the menus are holding. + this.keys_open = false; + this.rebinding = None; + this.act(action, cx); + cx.notify(); + }), + ) + }), + ) + .child( + // ponytail: the column is as wide as the stroke it + // prints, so a one-character chord gives this half a + // hit area under the 24px WCAG 2.5.8 floor -- tall + // enough, narrow. Upgrade: a min_w of HIT_MIN here. + div() + .id(("bind", i)) + .flex_none() + .flex() + .min_h(px(KEYS_ROW_H)) + .items_center() + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.rebinding = Some(action); + cx.notify(); + })) + .child(if capturing { + div() + .text_color(rgb(FG_SECONDARY)) + .child(format!("press a key — {out} cancels")) + } else { + div().child(self.keymap.display(action)) + }), + ) + .into_any_element() + } + KeyRow::Fixed(f) => { + let f = &keymap::FIXED[f]; + row() + .child(f.label) + // Dim, and no hover: this one is not a row you can click. + .child(div().text_color(rgb(FG_SECONDARY)).child(f.chord.clone())) + .into_any_element() + } + }); + } + Some( + scrim() + .flex() + .justify_center() + .items_center() + // The picture behind is out of reach, and looks it. The press is + // swallowed here so a button under the scrim cannot take it -- + // and it closes the card on the way, which is the pointer's exit + // from every card here ([`Player::close_card`]). + .bg(rgba(SCRIM)) + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _: &MouseDownEvent, _, cx| { + this.close_card(); + cx.notify(); + cx.stop_propagation(); + }), + ) + .child( + div() + .w(px(KEYS_W)) + .on_mouse_down(MouseButton::Left, swallow) + .flex() + .flex_col() + .gap(px(2.)) + .p(px(12.)) + .rounded(px(6.)) + .bg(rgb(BG_RAISED)) + // Title and instruction are two children, never one + // wrapping line: a fixed-height slot whose text wrapped + // painted its second line over the first row. + .child(div().flex_none().px(px(6.)).child("Actions & keys")) + // One status line, under the title where the eye starts. + // A refusal takes it over -- it is the more urgent of the + // two, and the notice bar it would otherwise appear in is + // under the scrim. + // + // The row list below is capped and scrolls, so neither a + // wrapped refusal here nor another action added to `ALL` + // can push the card past a 360 px window any more. + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child( + self.notice + .clone() + .unwrap_or_else(|| { + "click an action to do it · click its key to change it" + .into() + }), + ), + ) + // The search box: no focus and no text field -- the + // card's key handler is the field, exactly as the + // export card's bitrate is typed into it. Its own line + // above the list, so the rows below it are always the + // answer to what it says. + .child( + div() + .flex_none() + .px(px(6.)) + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child(search), + ) + // Capped and scrolling rather than as tall as the action + // list happens to be: the list grows with the editor, + // the smallest window does not. + .child( + div() + .id("keys-rows") + .flex() + .flex_col() + .gap(px(2.)) + .max_h(px(KEYS_ROWS_H)) + // The line the list scrolls under: a row half + // out of the viewport sat against the search + // line with nothing between them, and read as a + // row painted over the heading rather than as a + // list with more above it. + .mt(px(4.)) + .border_t_1() + .border_color(rgb(BG_PANEL)) + .pt(px(4.)) + .overflow_y_scroll() + // The wheel's offset and the arrow keys' are + // the same one, so the two cannot disagree + // about where the list is. + .track_scroll(&self.keys_scroll) + .children(rows), + ), + ), + ) + } + + /// The menu a right-click on a clip opens: what that clip can be given, + /// each item beside the stroke that does the very same thing, and a + /// turn-over side that says what the clip *is*. An item that would do + /// nothing where the playhead is standing is dimmed and takes no click + /// rather than disappearing, so the menu reads the same every time. + /// + /// Every item goes through [`Player::act`], the table the key handler uses: + /// an item is its stroke, asked for with the mouse. Plain divs like the + /// rest of this window, so the root keeps the keyboard and escape still + /// reaches the handler that closes this. + pub(crate) fn context_card( + &self, + viewport: Size, + cx: &mut Context, + ) -> Option { + let menu = self.context_menu?; + let session = self.session.as_ref()?; + let clip = *session.lane_clips(menu.lane).get(menu.idx)?; + let source = session.sources().get(clip.source).cloned()?; + let secs = |frames: u32| timecode(f64::from(frames) / self.fps, self.fps); + let row = |n: usize| { + div() + .id(("menu", n)) + .flex() + // The floor, not the height: a long label wrapping must not + // paint over the item under it. + .min_h(px(MENU_ROW_H)) + .items_center() + .justify_between() + .gap(px(12.)) + .px(px(6.)) + .rounded(px(3.)) + }; + let mut rows: Vec = Vec::new(); + if menu.details { + // Read-only, so no ids and no hover: this side is a card, not a + // list of things to click. Each value is one truncated line, which + // is what keeps the height below the one the clamp was given. + for (label, value) in [ + ("File", file_name(&source.path)), + ("Path", source.path.display().to_string()), + ( + "Source range", + format!("{} – {}", secs(clip.in_frame), secs(clip.out_frame)), + ), + // How long it is *where it sits*, which its rate decides -- and + // the rate itself beside it, because a clip half its source's + // length could be either a trim or a 2x. + ("This clip", secs(clip.frames())), + ("Speed", format!("{} (tape)", clip.speed)), + ("Source duration", secs(session.file_frames(&source.path))), + ( + "Bitrate", + bitrate_detail( + self.bitrates.get(&source.path).copied().flatten(), + self.streams.get(&source.path).map_or(0, Vec::len), + ), + ), + ] { + rows.push( + row(rows.len()) + .child(label) + .child( + div() + .min_w(px(0.)) + .truncate() + // A size smaller than the labels: a timecode + // pair is 25 characters and has to fit beside + // its label inside `MENU_W`. + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child(value), + ) + .into_any_element(), + ); + } + } else { + // A grade on a waveform, an equalizer on a picture, a silence scan + // on a still: things that do not exist for what was right-clicked, + // so the menu is the list of what this clip can do rather than the + // registry with most of it struck through. One filter, in + // `menu_items`, so there is no second answer to keep in step. The + // state refusals below stay, dimmed and saying why -- the next + // click of the playhead lights them. + let ctx = self.ctx(Some((menu.lane, menu.idx))); + for action in menu_items(ctx) { + // The registry's own answer, the same one the actions card + // dims a row with -- and a row that takes no click says *why* + // rather than printing a stroke that would do nothing. + let refusal = enable(action, ctx); + let enabled = refusal.yes(); + // The one item that is not about this clip says so, and says it + // here rather than in the registry: the stroke is global too, + // but its row in the keys menu is not sitting on a clip. + let label = if matches!(action, ActionId::ToggleMute | ActionId::Paste) { + format!("{} (global)", action.label()) + } else { + action.label().to_string() + }; + rows.push( + row(rows.len()) + .child(label) + .child(match refusal.why() { + // One truncated line, like the details side: a + // reason that wrapped would make the card taller + // than the height `menu_at` placed it by. + Some(why) => div() + .min_w(px(0.)) + .truncate() + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child(why), + None => div() + .text_color(rgb(FG_SECONDARY)) + .child(self.keymap.display(action)), + }) + .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) + .when(enabled, |d| { + d.cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(move |this, event: &ClickEvent, _, cx| { + // Closed first: the action moves the very + // indices this menu is holding. + this.context_menu = None; + // The one item that is a *choice* and not a + // doing: four policies, so the pointer gets + // the list of them on this clip rather than + // the next one stepped to behind the click. + // The stroke still steps -- same door. + if action == ActionId::Fit { + this.open_picker( + Pick::Fit(menu.lane, menu.idx), + event.position(), + cx, + ); + } else { + this.act(action, cx); + } + })) + }) + .into_any_element(), + ); + } + rows.push( + row(rows.len()) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| { + if let Some(menu) = &mut this.context_menu { + menu.details = true; + } + cx.notify(); + })) + .child("Properties") + // No stroke reaches this one, and a blank column would read + // as one that was forgotten. + .child(div().text_color(rgb(FG_SECONDARY)).child("…")) + .into_any_element(), + ); + } + // The height the card is *placed* by and the height its list is drawn + // to are one number: placed by a taller one, the card would hang off the + // window's floor -- the very thing the clamp is for. + let list_h = menu_rows_h(rows.len(), viewport); + let (x, y) = menu_at(menu.at, viewport, MENU_PAD * 2. + list_h); + let full: SharedString = source.path.display().to_string().into(); + Some( + scrim() + // Click away closes it, either button, and the press is + // swallowed so nothing under the menu also takes it. No tint, + // unlike the modal cards: the timeline this menu is about has + // to stay readable behind it. + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _: &MouseDownEvent, _, cx| { + this.context_menu = None; + cx.notify(); + cx.stop_propagation(); + }), + ) + .on_mouse_down( + MouseButton::Right, + cx.listener(|this, _: &MouseDownEvent, _, cx| { + this.context_menu = None; + cx.notify(); + cx.stop_propagation(); + }), + ) + .child( + div() + // Only so the details side can carry a tooltip, which + // gpui gives to identified elements alone. + .id("menu-card") + .absolute() + .left(px(x)) + .top(px(y)) + .w(px(MENU_W)) + .flex() + .flex_col() + .p(px(MENU_PAD)) + .rounded(px(6.)) + .bg(rgb(BG_RAISED)) + // Painted after the scrim, so this listener runs first + // (gpui bubbles mouse events in reverse, window.rs:3705) + // and a press meant for an item never closes the menu + // out from under its own click. + .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| { + cx.stop_propagation() + }) + .on_mouse_down(MouseButton::Right, |_: &MouseDownEvent, _, cx| { + cx.stop_propagation() + }) + // The one value the details side has to truncate. + .when(menu.details, |d| { + d.tooltip(move |_, cx| cx.new(|_| Tip(full.clone())).into()) + }) + // The list scrolls where the card would otherwise grow + // past the window's floor -- an item hanging off the + // bottom edge is an item nobody can click. + .child( + div() + .id("menu-rows") + .flex() + .flex_col() + .max_h(px(list_h)) + .overflow_y_scroll() + .children(rows), + ), + ), + ) + } + + /// The open choice list: every value of one enumerated setting at once, the + /// one in force marked, and a click on any of them picks *that* one -- what + /// a button stepping one value on per click could never say. Built on the + /// clip menu's machinery down to the scrim, the placement and the scroll + /// cap, so it hangs and closes exactly as the menus do and fits the same + /// 640x360 floor. The stroke for the setting is untouched: this is the + /// pointer's door to it, not a second setting. + pub(crate) fn picker_card( + &self, + viewport: Size, + cx: &mut Context, + ) -> Option { + let picker = self.picker?; + let rows: Vec = self + .choices(picker.of) + .into_iter() + .enumerate() + .map(|(n, (choice, label, detail, picked))| { + div() + .id(("picker-row", n)) + .flex() + // The floor, not the height, and `HIT_MIN` of it: a row of a + // list is a click target like every other one here (WCAG + // 2.5.8). + .min_h(px(MENU_ROW_H)) + .items_center() + .justify_between() + .gap(px(12.)) + .px(px(6.)) + .rounded(px(3.)) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + // The mark is a glyph as well as a highlight, like the + // export card's rows: a background alone is gone under a + // hover and invisible to anyone who cannot tell the two + // greys apart (WCAG 1.4.1). + .when(picked, |d| d.bg(rgb(BG_SELECTED))) + .child( + div() + .flex() + .flex_none() + .items_center() + .gap(px(8.)) + .child(div().w(px(10.)).child(match picked { + true => "✓", + false => " ", + })) + .child(label), + ) + .child( + div() + .min_w(px(0.)) + .truncate() + .text_size(px(11.)) + // On the picked row the dim ink sits on the + // highlight, where it is only 3.3:1 (WCAG 1.4.3). + .text_color(rgb(match picked { + true => FG_PRIMARY, + false => FG_SECONDARY, + })) + .child(detail), + ) + .on_click( + cx.listener(move |this, _: &ClickEvent, _, cx| this.choose(choice, cx)), + ) + .into_any_element() + }) + .collect(); + // The window's own room, and the list scrolls only where the window has + // none -- the clip menu's rule, one function for both. + let list_h = menu_rows_h(rows.len(), viewport); + let (x, y) = menu_at(picker.at, viewport, MENU_PAD * 2. + list_h); + Some( + scrim() + // Click away closes it, either button, swallowed so nothing + // under the list also takes the press -- the clip menu's rule. + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _: &MouseDownEvent, _, cx| { + this.picker = None; + cx.notify(); + cx.stop_propagation(); + }), + ) + .on_mouse_down( + MouseButton::Right, + cx.listener(|this, _: &MouseDownEvent, _, cx| { + this.picker = None; + cx.notify(); + cx.stop_propagation(); + }), + ) + .child( + div() + .id("picker-card") + .absolute() + .left(px(x)) + .top(px(y)) + .w(px(MENU_W)) + .flex() + .flex_col() + .p(px(MENU_PAD)) + .rounded(px(6.)) + .bg(rgb(BG_RAISED)) + // Painted after the scrim, so this listener runs first + // and a press meant for a row never closes the list out + // from under its own click (`context_card`). + .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| { + cx.stop_propagation() + }) + .on_mouse_down(MouseButton::Right, |_: &MouseDownEvent, _, cx| { + cx.stop_propagation() + }) + .child( + div() + .id("picker-rows") + .flex() + .flex_col() + .max_h(px(list_h)) + .overflow_y_scroll() + .children(rows), + ), + ), + ) + } +} diff --git a/crates/app/src/ui/preview.rs b/crates/app/src/ui/preview.rs new file mode 100644 index 0000000..b775555 --- /dev/null +++ b/crates/app/src/ui/preview.rs @@ -0,0 +1,169 @@ +//! The picture: what is drawn over it and what is read off it. + +use crate::*; +use crate::ui::widgets::*; + +impl Player { + /// The cues of the picked track that are on screen at `at`, over the picture + /// and nothing else: bottom-centred where every player puts them, white on a + /// plate so the film underneath cannot swallow them, and each cue its own + /// plate so two at one moment stack rather than run together. + /// + /// `None` -- no element at all -- while the toggle is off, with no track + /// picked, and between cues: the picture is what this window is for, and a + /// permanent empty band across it would be in the way of exactly that. + /// + /// The cues are the *timeline's* ([`PlaybackSession::timeline_cues`]) and + /// not the track's own: on a cut timeline an embedded track's cues ride the + /// pictures they belong to, and this is the same map the export writes the + /// file with -- so what is read here is what the file says. + /// + /// A cue off a PGS track is a *picture* and not a line + /// ([`engine::subtitle::CueImage`]), and is drawn as one: the disc's whole + /// canvas fitted over the picture region exactly as the picture itself is, + /// which puts every cue where the disc put it relative to its own frame. + /// + /// ponytail: exact only while the canvas and the encode are the same shape + /// -- a 16:9 canvas over a 2.39:1 encode fits to the region's height and + /// the film to its width, so a cue sits a little low on a scope film. The + /// upgrade path is the picture's own rect, which wants `VideoMeta`'s aspect + /// and the measured bounds rather than the shared `Contain`. + pub(crate) fn subtitle_overlay( + &mut self, + at: f64, + window: &mut Window, + ) -> Option> { + // One way out, and it lets the drawn picture go on the way: the toggle + // going off, the file closing and the gap between two cues are the same + // "nothing on screen", and an 8 MB atlas tile may not survive any of + // them (an early return above this leaked one per toggle-off). + let mapped = match self.session.as_ref().filter(|_| self.subs_on) { + Some(session) => session.timeline_cues(self.sub_track), + None => Vec::new(), + }; + let cues = cues_at(&mapped, at); + if cues.is_empty() { + self.drop_sub_image(window); + return None; + } + // The first picture cue up, decoded once and kept: two bitmap cues at + // one moment is a thing PGS composes into one display set, so there is + // never a second picture to stack under the first. + let picture = cues + .iter() + .find_map(|cue| Some((cue.start_us, cue.image.as_ref()?))) + .and_then(|(start_us, image)| self.sub_picture(start_us, image, window)); + // A picture is fitted onto the whole region and a plate hangs off the + // bottom of it, and a track is one or the other -- so they are two + // shapes and not one with the parts switched off. + if let Some(image) = picture { + // A *flex* box with the canvas as its one growing item: a percentage + // size (`size_full`) inside an absolutely placed box has nothing to + // be a percentage of and lays the picture out to nothing, while a + // flex item is sized by the box itself. Fitted the way the picture + // above it is -- `Contain` over the same box -- so a canvas of the + // picture's own shape lands exactly on it. + return Some(div().absolute().inset_0().flex().child( + img(image).flex_1().h_full().object_fit(gpui::ObjectFit::Contain), + )); + } + Some( + div() + .absolute() + .left_0() + .right_0() + .bottom(px(SUB_BOTTOM)) + .flex() + .flex_col() + .items_center() + .gap(px(2.)) + // The plate takes no click: the picture behind it is still the + // drop target the whole window is. + .children(cues.into_iter().filter(|c| c.image.is_none()).map(|cue| { + div() + .max_w(relative(0.9)) + .px(px(6.)) + .rounded(px(3.)) + .bg(rgba(SUB_SHADE)) + .text_size(px(SUB_TEXT)) + .text_color(rgb(SUB_FG)) + .text_align(TextAlign::Center) + // A line of the cue is a line on screen: the break the + // parser kept is not whitespace to be re-flowed. What a + // *long* line does is wrap inside its own div, which is + // what the width cap above is for. + .children( + cue.text + .split('\n') + .map(|line| div().min_h(px(SUB_LINE_H)).child(line.to_string())), + ) + })), + ) + } + + /// The cue starting at `start_us` as a drawable picture, decoded on the + /// first repaint it is up for and kept until another cue takes its place + /// ([`Player::sub_image`]). `None` for a display set the decoder refuses, + /// which draws nothing rather than failing the frame. + /// + /// Its atlas tile is released as the video's is: every [`RenderImage`] gets + /// a fresh id and its own tile, so a film's worth of cues would grow the + /// sprite atlas by the whole film. + pub(crate) fn sub_picture( + &mut self, + start_us: i64, + image: &engine::subtitle::CueImage, + window: &mut Window, + ) -> Option> { + let key = (self.sub_track, start_us); + if let Some((up, ready)) = &self.sub_image + && *up == key + { + return Some(ready.clone()); + } + let mut rgba = image.rgba()?; + // gpui's atlas is BGRA with straight alpha; PGS decodes to RGBA with + // straight alpha. The same swap the video frames get. + for pixel in rgba.chunks_exact_mut(4) { + pixel.swap(0, 2); + } + let buf = image::RgbaImage::from_raw(image.width, image.height, rgba)?; + let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)])); + self.drop_sub_image(window); + self.sub_image = Some((key, next.clone())); + Some(next) + } + + /// Lets go of the drawn cue and its atlas tile. Called where the cue stops + /// being on screen, which is every gap between two of them: an 8 MB tile + /// per cue is not a thing to leave behind a film. + pub(crate) fn drop_sub_image(&mut self, window: &mut Window) { + if let Some((_, old)) = self.sub_image.take() { + let _ = window.drop_image(old); + } + } + + /// What is decoding the picture right now, for the transport line: the + /// backend is the running worker's own (it is written where a hardware + /// session falls back to software, so this follows reality), and the codec + /// comes from the clip under the playhead. Empty when nothing is playing -- + /// the question is about what is happening, not about what would. + pub(crate) fn live_decode(&self, position: f64, playing: bool) -> String { + let Some(session) = self.session.as_ref().filter(|_| playing) else { + return String::new(); + }; + let backend = session.decode_backend(); + let codec = session + .video_clip_at(position) + .and_then(|(lane, idx)| session.lane_clips(lane).get(idx).map(|clip| clip.source)) + .and_then(|source| session.sources().get(source)) + .and_then(|source| self.decoders.get(&source.path).copied().flatten()) + .and_then(|(codec, _)| codec); + match backend { + // Neither is a decode, and saying "SW" of them would be a lie. + Backend::Gap => "gap · nothing to decode".to_string(), + Backend::Still => "still · one decode, held".to_string(), + _ => format!("{} decode", decode_label(codec, backend)), + } + } +} diff --git a/crates/app/src/ui/theme.rs b/crates/app/src/ui/theme.rs new file mode 100644 index 0000000..087e60a --- /dev/null +++ b/crates/app/src/ui/theme.rs @@ -0,0 +1,119 @@ +//! The one place this editor knows a colour. +//! +//! Every paint in every region reads a token from this table and nothing else: +//! a `0x` literal anywhere but this file is the bug the whole redesign is about +//! (`no_colour_is_written_outside_the_theme` is the guard). Names say the +//! *role*, never the shade -- `bg/panel`, not "the dark grey" -- so the palette +//! can be swapped whole without touching a single element. +//! +//! Family B: near-black ground, cool neutral chrome, one cyan accent, with the +//! clip bodies carrying the cross-NLE kind convention (video blue, audio green, +//! image teal, text purple) instead of four greys that differ by a hair. + +use engine::project::LaneKind; + +// -- surfaces ----------------------------------------------------------------- +/// The app's base, and the bed a picture is letterboxed against: darker than +/// every panel, so the picture is what the eye lands on. +pub const BG_CANVAS: u32 = 0x0b0d10; +/// The library, the inspector, the toolbar: the chrome the work sits between. +pub const BG_PANEL: u32 = 0x151a21; +/// Buttons, menu bodies, cards -- one plane up from the panel. Flat: the +/// separation is colour, never a shadow. +pub const BG_RAISED: u32 = 0x212936; +/// The lane bed, darker than the panel so a clip reads as an object on it. +pub const BG_TIMELINE: u32 = 0x0e1218; +/// One step lighter than whatever it sits on: the pointer's answer that this is +/// clickable. +pub const BG_HOVER: u32 = 0x2f3a4a; +/// The same answer for the things that stand on the panel rather than on a +/// button. +pub const BG_HOVER_DIM: u32 = 0x1d2531; +/// A picked row, a picked clip: the accent at surface brightness, so a +/// selection is tinted rather than lit up. +pub const BG_SELECTED: u32 = 0x0d4b5c; +/// What a card is floated over when it is genuinely modal (the export, the +/// actions list). Inspector sections never draw one -- they occlude nothing. +pub const SCRIM: u32 = 0x0b0d10cc; + +// -- strokes ------------------------------------------------------------------ +pub const STROKE_DIVIDER: u32 = 0x2a3442; +/// The keyboard's own ring, distinct from selection on purpose: focus is where +/// the next stroke lands, selection is what an edit acts on. +pub const STROKE_FOCUS: u32 = 0xffd166; +pub const STROKE_SELECTED: u32 = 0x22d3ee; + +// -- text --------------------------------------------------------------------- +pub const FG_PRIMARY: u32 = 0xe9eff7; +/// Shortcuts, dismissal hints, detail lines. Past 4.5:1 on every surface above. +pub const FG_SECONDARY: u32 = 0xa7b6c9; +pub const FG_DISABLED: u32 = 0x6c7a8b; + +// -- interaction -------------------------------------------------------------- +pub const ACCENT_PRIMARY: u32 = 0x22d3ee; +/// Not the accent: the playhead crosses every clip colour there is and has to +/// stay the one line that is none of them. +pub const ACCENT_PLAYHEAD: u32 = 0xff4d6d; +/// The accent as a translucent wash, for the marks drawn over a clip body. +pub const ACCENT_WASH: u32 = 0x22d3eeaa; + +// -- clip kinds (cross-NLE convention) ---------------------------------------- +pub const CLIP_VIDEO: u32 = 0x2b5fa8; +pub const CLIP_AUDIO: u32 = 0x276b43; +pub const CLIP_IMAGE: u32 = 0x1a6a6a; +pub const CLIP_TEXT: u32 = 0x6b46c1; + +/// What a clip on `kind` is painted: the timeline's whole colour language in +/// one call, so a lane added later cannot invent a shade of its own. +pub const fn clip_kind(kind: LaneKind, image: bool) -> u32 { + match kind { + LaneKind::Audio => CLIP_AUDIO, + LaneKind::Video if image => CLIP_IMAGE, + LaneKind::Video => CLIP_VIDEO, + } +} + +/// One per source, so a clip that came from an imported file reads as coming +/// from somewhere else than its neighbour. The *kind* is the body colour now +/// ([`clip_kind`]); this is the identity stripe and the library swatch, and it +/// only has to be four things telling each other apart. +pub const SOURCE_TINTS: [u32; 4] = [0x4f8fd6, 0xd69a4f, 0x4fd6a8, 0xb14fd6]; + +// -- feedback ----------------------------------------------------------------- +pub const STATUS_ERROR: u32 = 0xef4444; +pub const STATUS_WARNING: u32 = 0xf59e0b; +pub const STATUS_SUCCESS: u32 = 0x34d399; +pub const STATUS_PROGRESS: u32 = ACCENT_PRIMARY; +/// The mirror of [`BG_SELECTED`]: a drop the lane will not take, tinting the +/// shadow the drag draws so a refusal is seen before the release. +pub const DROP_REFUSE: u32 = 0x8f2740; +/// How solid that shadow is (`0xRRGGBBAA`): enough to read as a box, little +/// enough that the clip under it is still legible. +pub const GHOST_ALPHA: u32 = 0x66; + +// -- subtitles (drawn over the picture, so they own their own contrast) -------- +pub const SUB_FG: u32 = 0xffffff; +pub const SUB_SHADE: u32 = 0x000000cc; + +// -- the equalizer graph and the histogram ------------------------------------ +pub const EQ_GRID: u32 = 0x2a3442; +pub const EQ_SPECTRUM_INK: u32 = 0x7f95ad66; +pub const EQ_FILL_INK: u32 = 0x22d3ee26; +pub const EQ_BELL_INK: u32 = 0x22d3ee66; +pub const HIST_INK: [u32; 3] = [0xE0_5A_5A, 0x5A_D0_7A, 0x5A_9A_E0]; + +// -- geometry the four regions are laid out on -------------------------------- +/// Compact density: 11-13 px text, 28 px controls, 8 px gutters. The floor the +/// whole window is measured at is 640x360, and airy spacing loses a region. +pub const INSPECTOR_MIN_W: f32 = 208.; +pub const INSPECTOR_MAX_W: f32 = 320.; +pub const INSPECTOR_FRAC: f32 = 0.24; + +/// The inspector's width at this window width, on the library's own rule: a +/// share of the window, clamped so the picture keeps the middle at every size. +pub fn inspector_w(window_w: f32) -> f32 { + (window_w * INSPECTOR_FRAC).clamp(INSPECTOR_MIN_W, INSPECTOR_MAX_W) +} +/// The lighter scrim: the picker list floats over a card that is still being +/// read, so it dims rather than hides. +pub const SCRIM_LIGHT: u32 = 0x0b0d1055; diff --git a/crates/app/src/ui/timeline.rs b/crates/app/src/ui/timeline.rs new file mode 100644 index 0000000..990bb9d --- /dev/null +++ b/crates/app/src/ui/timeline.rs @@ -0,0 +1,1645 @@ +//! The bottom region: the ruler, the lanes and the subtitle strip. + +use crate::*; +use crate::ui::widgets::*; + +impl Player { + /// Transport, edit and file buttons, timecode, playhead, clips lane. + pub(crate) fn panel( + &self, + position: f64, + duration: f64, + state: Transport, + cx: &mut Context, + ) -> impl IntoElement { + // Where the playhead is *on the bed*, in pixels from its left edge. + // Clamped to the bed because it is drawn as a width as well as an + // offset, and the view follows the playhead anyway, so it is never off + // the bed for long. + let bed_w = f32::from(self.ruler.get().size.width); + let filled = self.scale.px_at(position).clamp(0., bed_w); + // An export owns the hint slot and the ruler while it runs: the + // percentage and the accent bar are the same number, so the playhead + // fill doubles as the progress bar for free. + let exporting = self.exporting().is_some(); + // Everything but Import and Keys needs a timeline to act on: with none + // open they are dimmed rather than silently doing nothing. + let live = state != Transport::Stopped && !exporting; + // The project's own picture size, for the button that cycles it: read + // per render like everything else here, so a cycle shows on the button + // that made it. + let resolution = self.session.as_ref().map(PlaybackSession::resolution); + let key = |action| self.keymap.display(action); + // The lanes the project has, or the pair a fresh one starts with so the + // panel reads the same before a file is open as after. + let lanes = self + .session + .as_ref() + .map_or_else(|| vec![Lane::V1, Lane::A1], PlaybackSession::lanes); + // A loop rather than a `map`: each row takes `cx` in turn, where a + // closure would hold it for as long as the iterator lives. + let mut rows = Vec::new(); + 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); + 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 + .export_started + .map_or(0., |t| t.elapsed().as_secs_f32()); + // Two numbers that must both be honest: the one that counts up is + // measured, the one that counts down is a guess and says so. + let left = eta_secs(&self.export_marks, elapsed, progress).map_or_else( + || "estimating…".to_owned(), + |s| format!("~{} left", clock(s)), + ); + ( + format!( + // Clocks, then the way out, then what is encoding: at the + // 640 px floor the tail is what truncation eats, and the + // codec pair is the one part of this line the card already + // said. The escape must not be what goes missing. + "EXPORTING {}% · {} elapsed · {left} — {} cancels · {} · {}", + (progress * 100.) as u32, + clock(elapsed), + key(ActionId::CancelExport), + // The row that was picked; the engine's line below names the + // seats alone, since the library is what identifies a codec. + format_label(self.format), + // What the worker actually opened, so a fallback to the + // software encoder shows here rather than being invisible. + export + .encoders() + .unwrap_or_else(|| "opening the encoder".to_string()), + ), + progress, + ) + } else { + // The strokes no button carries; the rest ride on the buttons' + // tooltips. Keys first: at a 640 px window the tail is what a + // truncation eats, and the two hints at the end are also on the + // ruler's and Import's tooltips. + // While it plays, what is decoding it goes first: it is the + // answer that changes as the playhead crosses a cut, and the tail + // of this line is what a narrow window truncates. + ( + join_detail( + &self.live_decode(position, state.is_playing()), + &format!( + "{} copy · {} paste · {} undo · click the bar to seek · drop a file to \ + import", + key(ActionId::Copy), + key(ActionId::Paste), + key(ActionId::Undo) + ), + ), + filled, + ) + }; + div() + .flex_none() + .h(px(panel_h(lanes.len()) + strip_h)) + .flex() + .flex_col() + .gap(px(8.)) + .px(px(12.)) + .py(px(8.)) + .bg(rgb(BG_PANEL)) + // Transport | edit | file: three groups, so the eye can skip two of + // them. Every button says what it does; the tooltip adds its key. + // + // The row scrolls rather than losing its tail: at the 640 px floor + // this window is sized for it is wider than the panel, and a button + // off the right edge is a button a pointer cannot press. A plain + // wheel moves it -- gpui puts a vertical delta on the x axis when + // that is the only one scrolling (div.rs:2424). + // + // ...and "it scrolls" is not "it can be found": the button beside + // the row is pinned outside it and never scrolls away, so Export, + // Save and the rest are one press from the smallest window even + // when the row's tail is off the edge. + // `toolbar_fits_the_smallest_window` is the guard. + .child( + div() + .flex_none() + .flex() + .items_center() + .gap(px(8.)) + .child( + div() + .id("controls") + .flex_1() + .min_w(px(0.)) + .flex() + .items_center() + .gap(px(8.)) + .overflow_x_scroll() + .child(control( + "transport", + Some(transport_glyph(state).into_any_element()), + if state.is_playing() { "Pause" } else { "Play" }, + if nothing_to_play(self.session.as_ref()) && !state.is_playing() { + format!("{} — put a clip on a lane first", key(ActionId::Play)) + } else { + key(ActionId::Play) + }, + // An empty timeline has nothing to play, so the button + // says so by being dim rather than by starting a clock + // against nothing (the key press answers with the + // notice). Still live while it *is* playing: a delete + // can empty the timeline mid-play and that has to stop. + live && (state.is_playing() || !nothing_to_play(self.session.as_ref())), + cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_or_restart(cx)), + )) + .child(separator()) + .child(control( + "cut", + Some(cut_glyph().into_any_element()), + "Cut", + format!( + "{} — splits the clip under the playhead", + key(ActionId::Cut) + ), + live, + cx.listener(|this, _: &ClickEvent, _, cx| this.cut(cx)), + )) + .child(control( + "delete", + Some(delete_glyph().into_any_element()), + "Delete", + if self.selected.is_some() { + key(ActionId::Delete) + } else { + format!("{} — click a clip below first", key(ActionId::Delete)) + }, + live && self.selected.is_some(), + cx.listener(|this, _: &ClickEvent, _, cx| this.delete_selected(cx)), + )) + // The way back from every one of them. It was a stroke and + // nothing else, which made the whole edit group a one-way + // door for anyone working with a pointer. + .child(control( + "undo", + None, + "Undo", + format!("{} — takes the last edit back", key(ActionId::Undo)), + live, + cx.listener(|this, _: &ClickEvent, _, cx| this.undo(cx)), + )) + // With the edit group, beside the buttons that change the + // edit list: a track is a row of it, and adding one is an + // undoable edit like the rest. Two buttons rather than one + // with a choice, because the choice is the whole action. + .child(control( + "add-video-lane", + None, + "+ V", + format!( + "{} — adds a video track under the ones there", + key(ActionId::AddVideoLane) + ), + live, + cx.listener(|this, _: &ClickEvent, _, cx| { + this.add_lane(LaneKind::Video, cx) + }), + )) + .child(control( + "add-audio-lane", + None, + "+ A", + format!( + "{} — adds an audio track under the ones there", + key(ActionId::AddAudioLane) + ), + live, + cx.listener(|this, _: &ClickEvent, _, cx| { + this.add_lane(LaneKind::Audio, cx) + }), + )) + // The third kind of track this timeline carries, and + // the only one that arrived through a drop alone: a + // subtitle file nobody thought to drag was a track + // the editor could not be asked for. What it opens is + // a chooser rather than an empty row -- a subtitle + // track is its file, and there is nothing to add + // before one is named. + .child(control( + "add-subtitle-track", + None, + "+ S", + // Dim, and saying why it is dim, out of the one + // oracle -- the very words the key answers with + // (`Player::pick_and_add_subtitles`), so the + // tooltip and the notice cannot come to differ. + match self.enable(ActionId::AddSubtitleTrack, None).why() { + Some(why) => { + format!("{} — {why}", key(ActionId::AddSubtitleTrack)) + } + None => format!( + "{} — adds every subtitle track in a file you pick", + key(ActionId::AddSubtitleTrack) + ), + }, + live, + cx.listener(|this, _: &ClickEvent, _, cx| { + this.pick_and_add_subtitles(cx) + }), + )) + // With the transport, not the edit group: it changes what + // the file sounds like, never what it is. Reads as its own + // state, so muted is legible without a tooltip. + .child(control( + "volume", + None, + self.volume.label(), + format!( + "{} mutes · {} louder · {} quieter", + key(ActionId::ToggleMute), + key(ActionId::VolumeUp), + key(ActionId::VolumeDown) + ), + live, + cx.listener(|this, _: &ClickEvent, _, cx| { + this.set_volume(|volume| volume.muted = !volume.muted, cx) + }), + )) + // The level itself, to drag. The button beside it stays the + // mute -- one gesture each -- and the label above is what + // this writes, live, so the number follows the hand. + .child(volume_slider( + self.volume, + self.volume_bar.clone(), + live, + cx, + )) + .child(separator()) + // The size every clip is composed onto, which is also the + // size the export comes out at. Five sizes, so a click opens + // the list of them with this one marked and picks whichever + // was meant: a button that stepped one on per press made the + // user click round the ladder to get back to where they + // were. The stroke still steps, for the hand already on it. + .child(control( + "resolution", + None, + resolution.map_or_else(|| "Size".to_string(), |(_, h)| format!("{h}p")), + match resolution { + Some((w, h)) => format!( + "click to pick a size — the project is {w}x{h}; {} steps to the next", + key(ActionId::Resolution) + ), + None => format!("{} — open a file first", key(ActionId::Resolution)), + }, + live, + cx.listener(|this, event: &ClickEvent, _, cx| { + this.open_picker(Pick::Resolution, event.position(), cx) + }), + )) + // The rate every clip is counted in, which is also the rate + // the export is written at -- the other half of "the project + // is not the media", and the one the panel could only ever + // read out before. A click opens the rates with this one + // marked; picking one conforms the whole timeline to it. + .child(control( + "fps", + None, + match self.session.is_some() { + true => format!("{} fps", fps_label(self.fps)), + false => "Rate".to_string(), + }, + match self.session.is_some() { + true => format!( + "click to pick a frame rate — the project is cut at {} fps", + fps_label(self.fps) + ), + false => "the project's frame rate — open a file first".to_string(), + }, + live, + cx.listener(|this, event: &ClickEvent, _, cx| { + this.open_picker(Pick::Fps, event.position(), cx) + }), + )) + // ...and which rendition its HDR media is watched in, the + // third thing that is the project's rather than the media's. + // Listed whatever is on the timeline, and the tooltip says + // who it acts on: a control that came and went with the + // media would be one nobody could find when they wanted it. + .child(control( + "tonemap", + None, + match &self.session { + Some(session) => format!("HDR {}", tone_label(session.tone())), + None => "HDR".to_string(), + }, + match &self.session { + Some(session) => format!( + "click to pick the HDR rendition — the project is {}; SDR media is untouched", + tone_label(session.tone()) + ), + None => "the HDR rendition — open a file first".to_string(), + }, + live, + cx.listener(|this, event: &ClickEvent, _, cx| { + this.open_picker(Pick::Tone, event.position(), cx) + }), + )) + // How much of the timeline the panel below is showing -- + // beside the resolution, since neither of them edits + // anything: they are both what is being looked at. The + // middle one says how much of it is on the bed, and is the + // way back to the whole of it. + .child(control( + "zoom-out", + None, + "−", + format!( + "{} — show more of the timeline; stops with all of it on the bed", + key(ActionId::ZoomOut) + ), + live, + cx.listener(|this, _: &ClickEvent, _, cx| { + this.zoom(1. / ZOOM_STEP, None, cx) + }), + )) + .child(control( + "zoom-fit", + None, + // How much timeline is on the bed, not a multiple of + // "the whole of it": the scale no longer knows what the + // whole of it is, and a number that changed on every + // import was a number that lied. + span_label(self.view().span()), + format!( + "{} — fit the whole timeline; showing {} to {}", + key(ActionId::ZoomFit), + timecode(self.scale.start, self.fps), + timecode( + (self.scale.start + self.view().span()).min(duration), + self.fps + ) + ), + live, + cx.listener(|this, _: &ClickEvent, _, cx| this.zoom_fit(cx)), + )) + .child(control( + "zoom-in", + None, + "+", + format!( + "{} — magnify around the playhead; ctrl+wheel on the bar zooms at the pointer", + key(ActionId::ZoomIn) + ), + live, + cx.listener(|this, _: &ClickEvent, _, cx| this.zoom(ZOOM_STEP, None, cx)), + )) + // The magnet, beside the zoom for the zoom's own reason: it + // changes nothing on the timeline, it changes how the hand + // meets it. The label is the state, as the volume's is -- + // a toggle that looks the same either way says nothing. + .child(control( + "snap", + None, + if self.snap { "Snap" } else { "No snap" }, + format!( + "{} — {}", + key(ActionId::ToggleSnap), + match self.snap { + true => "drags and trims land on clip edges, the playhead and the start", + false => "drags and trims land exactly where the hand leaves them", + } + ), + live, + cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_snap(cx)), + )) + // The cues over the picture, off and on -- beside the zoom + // and the snap, since like both of them it changes what is + // being looked at and nothing about the edit. The label is + // the state, as the snap's is, and it says what there is to + // toggle when there is nothing. + .child(control( + "subs", + None, + match (self.subtitle_track().is_some(), self.subs_on) { + (false, _) => "No subs", + (true, true) => "Subs", + (true, false) => "Subs off", + }, + match self.enable(ActionId::ToggleSubtitles, None).why() { + Some(why) => format!( + "{} — {why}; drop a .srt on the window, or open an mkv that carries them", + key(ActionId::ToggleSubtitles) + ), + None => format!( + "{} — {}", + key(ActionId::ToggleSubtitles), + match self.subs_on { + true => "the cue under the playhead is drawn over the picture", + false => "the cues are on the timeline and off the picture", + } + ), + }, + live && self.enable(ActionId::ToggleSubtitles, None).yes(), + cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_subtitles(cx)), + )) + // Import is not here: it belongs to the media list it adds + // to, and two doors into one action is a question about + // which one is the real one. + // + // While one runs, this button is the way out of it: the + // progress line promised esc and nothing else, which left a + // pointer no way to stop an export it had started. + .child(control( + "export", + None, + if exporting { "Cancel" } else { "Export" }, + if exporting { + format!( + "{} — stops the export; the part-written file goes", + key(ActionId::CancelExport) + ) + } else { + format!( + "{} — quality and destination, then writes the timeline out", + key(ActionId::Export) + ) + }, + if exporting { + true + } else { + live && self.export.is_none() + }, + cx.listener(|this, _: &ClickEvent, _, cx| { + if this.exporting().is_some() { + this.cancel_export(); + cx.notify(); + } else { + this.open_export(cx); + } + }), + )) + .child(control( + "save", + None, + "Save", + format!("{} — writes the project file", key(ActionId::Save)), + live, + cx.listener(|this, _: &ClickEvent, _, cx| this.save_project(cx)), + )) + // Closed while an export runs, which is what keeps a waiting + // row from swallowing the escape the progress line promises + // cancels the export. + .child(control( + "keys", + None, + "Actions", + // The pointer's way to every action there is, including + // the ones no button here has room for. + format!( + "{} — do any action, or change the key that does it", + key(ActionId::ShowActions) + ), + !exporting, + cx.listener(|this, _: &ClickEvent, _, cx| match this.keys_open { + true => { + this.keys_open = false; + this.rebinding = None; + cx.notify(); + } + false => this.show_actions(cx), + }), + )) + ) + // The door to everything the row cannot show at this + // window: the same card the Actions button opens, by the + // same call, pinned where a scroll cannot take it. + .child(control( + "controls-more", + None, + "⋯", + format!( + "{} — every action, including the ones scrolled off this row", + key(ActionId::ShowActions) + ), + !exporting, + cx.listener(|this, _: &ClickEvent, _, cx| match this.keys_open { + true => { + this.keys_open = false; + this.rebinding = None; + cx.notify(); + } + false => this.show_actions(cx), + }), + )), + ) + .child( + div() + .flex_none() + .flex() + .items_center() + .gap(px(12.)) + // Fixed width and one line: changing digits must not push + // the row around, nor wrap and change its height. + // The timeline's own length, never the drawn one: a tail + // being dragged inflates the bed to the room that edge has + // ([`Player::drawn_duration`]), and for a still that room is + // ten minutes -- a total that jumped to 10:00:00 the moment + // a picture's edge was pressed, and back on release. + .child(div().flex_none().w(px(TIME_W)).truncate().child(format!( + "{} / {}", + timecode(position, self.fps), + timecode( + self.session + .as_ref() + .map_or(0., PlaybackSession::timeline_duration), + self.fps + ) + ))) + .child( + div() + .flex_1() + .min_w(px(0.)) + .truncate() + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child(hint), + ), + ) + // Press to seek, drag to scrub: the move and release halves live on + // the root, since the pointer leaves the bar immediately. The bar + // stays 6 px to look at; the strip that takes the click is 24, so + // it can be hit without aiming (WCAG 2.5.8). + .child( + div() + .flex_none() + .flex() + .gap(px(HEADER_GAP)) + // The lanes' header column, empty here: the ruler's own bar + // has to start where their beds start, or the playhead + // would point at a different moment in each row. + .child(div().flex_none().w(px(HEADER_W))) + .child( + div() + .id("ruler") + .flex_1() + .min_w(px(0.)) + .h(px(RULER_HIT_H)) + .flex() + .flex_col() + .justify_center() + .rounded(px(3.)) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER_DIM))) + // The strip carries no text, so the tooltip is the only + // place it can say what it is. + .tooltip(|_, cx| { + cx.new(|_| Tip("Seek — click or drag; ctrl+wheel zooms".into())) + .into() + }) + // Ctrl+wheel is what every timeline zooms with, and + // the point held still is the one under the pointer + // rather than the playhead. Only with ctrl: a bare + // wheel here is the window's to scroll, and the + // controls row above scrolls on exactly that. + .on_scroll_wheel(cx.listener( + |this, event: &ScrollWheelEvent, _, cx| { + if !event.modifiers.control { + return; + } + let dy = match event.delta { + ScrollDelta::Lines(d) => d.y, + ScrollDelta::Pixels(d) => f32::from(d.y), + }; + if dy == 0. { + return; + } + let anchor = px_along(event.position.x, this.ruler.get()); + let factor = if dy > 0. { ZOOM_STEP } else { 1. / ZOOM_STEP }; + this.zoom(factor, Some(anchor), cx); + }, + )) + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, event: &MouseDownEvent, _, cx| { + this.scrubbing = true; + this.scrub_to(event.position.x, true, cx); + }), + ) + .child( + div() + .w_full() + .h(px(6.)) + .rounded(px(3.)) + .bg(rgb(BG_RAISED)) + .child(bounds_probe(self.ruler.clone())) + .child( + div() + .h_full() + .w(px(filled)) + .rounded(px(3.)) + .bg(rgb(ACCENT_PRIMARY)), + ), + ), + ), + ) + // Every lane the project has, in its own order -- and its own + // column, so a project with more lanes than the panel is tall + // scrolls its tracks instead of pushing the picture off the window. + // The gap is the panel's own, so two lanes lay out exactly as they + // did when they were two children of it. + .child( + div() + .id("lanes") + .flex_none() + .flex() + .flex_col() + .gap(px(8.)) + .max_h(px(lanes_h(LANES_MAX))) + .overflow_y_scroll() + .children(rows), + ) + // 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 + /// each, the picked one marked, and a click makes another one the picked one + /// -- which is the whole of choosing between the two tracks of a film. A row + /// per track and no cycle: three of them is an ordinary number for a remux, + /// and a key that steps through three is a key nobody can aim. + /// + /// A track that could not be read is *here*, greyed and saying why, exactly + /// as a media row the timeline cannot take is: PGS subtitles are pictures, + /// and a film carrying four of them says so instead of listing nothing. + /// + /// Every row names the file it came out of itself, in words and in the tint + /// that file's clips wear on the lanes -- but only where there is more than + /// one file to tell apart, the way [`row_name`] numbers audio streams only + /// where a file gave several. Where the window is tall enough for it + /// ([`sub_headers_fit`]) each file's block is headed by its name as well: a + /// label and nothing more, no click and nothing to fold, so the rows under + /// it are the only things anybody has to aim at. At the 640x360 floor the + /// headers are gone and the rows still say whose they are. + /// + /// `None` when there are none -- an empty heading is a section about + /// nothing. + pub(crate) fn subtitle_section( + &self, + width: f32, + viewport_h: f32, + cx: &mut Context, + ) -> Option { + let tracks = self.session.as_ref()?.subtitles(); + if tracks.is_empty() { + return None; + } + let groups = subtitle_rows(tracks); + // One file's tracks need no prefix saying which file: it is the only + // one, and every row would carry the same word. + let several_files = groups.len() > 1; + let headed = several_files && sub_headers_fit(viewport_h); + let text_w = row_text_w(width); + let rows: Vec<_> = groups + .into_iter() + .map(|SubGroup { name, path, rows }| { + // The file's own colour, the one its media rows and its clips + // wear -- and none at all for a standalone `.srt`, which came + // off no file on this timeline. + let tint = file_tint(self.sources(), &path); + let numbered = rows.len() > 1; + // The name twice over: all of it the header can hold, and the + // share of a row a prefix may take in front of the label. + let head = clip_middle(&name, text_w); + let prefix = clip_middle(&name, text_w * SUB_STEM_SHARE); + let rows: Vec<_> = rows + .into_iter() + .map(|row| { + let track = row.track; + let picked = track == self.sub_track; + let usable = row.refused.is_none(); + // Two tracks off one remux that both say "eng" are told + // apart by their number and by nothing else -- the same + // count [`sub_pick_name`] echoes. + let title = match numbered { + true => format!("{} {}", row.label, row.number), + false => row.label, + }; + // A standalone `.srt` is named after its own file, so + // the file in front of it says the same word twice + // ("Legend.of.… · Legend.of.…"). [`sub_pick_name`]'s + // rule, on the row it is about. + let owned = several_files && !title.starts_with(name.as_str()); + // The whole path, never clipped: the row says which + // file, and the tooltip says which one on disk. + let tip: SharedString = match &row.refused { + Some(why) => format!("{} — {why}", path.display()), + None => format!( + "{} — click to show this track over the picture", + path.display() + ), + } + .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 = + format!("Remove {title} — importing the file again brings it back") + .into(); + div() + // The *flat* index into the session's add-order + // list, which is what a pick is and what a save + // writes: the grouping moved the row on screen and + // never the track it stands for. + .id(("subtitle-track", track)) + .flex_none() + .h(px(ROW_H)) + .flex() + .items_center() + .gap(px(6.)) + .pr(px(6.)) + .rounded(px(3.)) + .when(!usable, |d| d.text_color(rgb(FG_SECONDARY)).opacity(0.55)) + .when(usable, |d| { + d.cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.sub_track = track; + // Picking a track is asking to see it: a + // click that changed nothing on screen + // because the toggle was off would read + // as a dead row. + this.subs_on = true; + cx.notify(); + })) + }) + .when(picked, |d| d.bg(rgb(BG_SELECTED))) + .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into()) + // The media rows' bar, same width and hard against + // the same edge: one association across the panel + // and the lanes. Kept as room rather than dropped + // where there is no tint, so a standalone `.srt` + // still lines its words up with the rest. + .child( + div() + .flex_none() + .w(px(SWATCH_W)) + .h_full() + .rounded(px(2.)) + .when_some(tint, |d, tint| d.bg(rgb(tint))), + ) + .child( + div() + .flex_1() + .min_w(px(0.)) + .flex() + .flex_col() + .child( + div() + .flex() + .text_size(px(11.)) + // In front, because the column + // truncates from the right: an + // ownership word at the end is a + // word the floor never shows. + .when(owned, |d| { + d.child( + div() + .flex_none() + // Said twice where a + // header says it above: + // still there, out of + // the way. + .when(headed, |d| { + d.text_color(rgb(FG_SECONDARY)) + }) + .child(format!("{prefix} · ")), + ) + }) + .child( + div() + .flex_1() + .min_w(px(0.)) + .truncate() + .child(title), + ), + ) + .child( + div() + .truncate() + .text_size(px(10.)) + .text_color(rgb(FG_SECONDARY)) + .child(row.detail), + ), + ) + // The way back off the timeline, on every row and on + // the last one too -- a list of subtitles is allowed + // to be empty, unlike a lane. A `HIT_MIN` target and + // never hidden, the lane header's ×, and it stops + // the click there: the row under it picks a track, + // and picking the track that has just gone would + // leave the pick naming nothing. + .child( + div() + .id(("subtitle-remove", track)) + .flex_none() + .w(px(HIT_MIN)) + .h_full() + .flex() + .items_center() + .justify_center() + .rounded(px(3.)) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .tooltip(move |_, cx| cx.new(|_| Tip(remove_tip.clone())).into()) + .on_click(cx.listener( + move |this, _: &ClickEvent, _, cx| { + cx.stop_propagation(); + this.remove_subtitle_track(track, cx); + }, + )) + .child("×"), + ) + }) + .collect(); + div() + .flex_none() + .flex() + .flex_col() + .gap(px(2.)) + // The header: which film these came out of, in words and not + // in colour alone. No id, no click, nothing to fold -- a + // label, which is why it is allowed under `HIT_MIN`. + .when(headed, |d| { + d.child( + div() + .flex_none() + .h(px(SUB_HEAD_H)) + .flex() + .items_center() + .gap(px(6.)) + .text_size(px(10.)) + .text_color(rgb(FG_SECONDARY)) + .when_some(tint, |d, tint| { + d.child( + div() + .flex_none() + .w(px(SWATCH_W)) + .h_full() + .rounded(px(2.)) + .bg(rgb(tint)), + ) + }) + .child(div().flex_1().min_w(px(0.)).truncate().child(head)), + ) + }) + .children(rows) + }) + .collect(); + Some( + div() + .flex_none() + .flex() + .flex_col() + .gap(px(2.)) + .child( + div() + .truncate() + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child(match (self.subs_on, sub_pick_name(tracks, self.sub_track)) { + // Which of them is on screen, named by its film: + // the heading over a list of five is where the one + // being shown is worth saying out loud. + (true, Some(pick)) => format!("Subtitles — {pick}"), + (true, None) => "Subtitles".to_string(), + // The toggle's state where the tracks are listed: a + // list of subtitles nothing on screen is showing has + // to say that it is showing none. + (false, _) => "Subtitles — hidden".to_string(), + }), + ) + .child( + div() + .id("subtitle-rows") + .flex() + .flex_col() + .gap(px(2.)) + .max_h(px(SUB_ROWS_H)) + .overflow_y_scroll() + .children(rows), + ), + ) + } + + /// One lane of the edit list made visible: a fixed header saying which lane + /// it is, then a bed with a box per clip, placed and sized by its share of + /// the timeline. A cut adds a box without moving anything, a delete closes + /// the hole, a lift leaves one. A clip too narrow for its name says what it + /// 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) -> 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_CANVAS)) + .overflow_hidden() + .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(1.)) + .bg(rgb(ACCENT_PRIMARY)), + ), + ), + ) + } + + pub(crate) fn lane_row( + &self, + lane: Lane, + // Where the playhead is on the bed, in pixels: worked out once by the + // panel so the ruler's line and every lane's draw the same one. + filled: f32, + cx: &mut Context, + // Borrows nothing it was given (`use<>`): the rows are built one after + // another into a list, and a row still holding `cx` would be the only + // one that could be built. + ) -> impl IntoElement + use<> { + // The mapping, copied out once: every box in the row is placed through + // it, so all of them move together when it does. No bed width is needed + // to place them any more -- a second is so many pixels wherever it is. + let scale = self.scale; + // How much bed there is to be seen on, measured off the ruler's own + // probe like every other question about it: what a box draws *inside* + // itself is clipped to this ([`visible_slice`]), because a box at a deep + // zoom is far wider than the strip it is being watched through. + let bed = f32::from(self.ruler.get().size.width); + // Where the snap line stands, in the same pixels every box is placed + // through -- and only while a gesture is actually live: gpui drops a + // drag without telling anyone, so this asks whether one is in flight + // (`App::has_active_drag`) rather than remembering that one was. + let cue = self + .snap_cue + .filter(|_| self.trim.is_some() || cx.has_active_drag()) + .map(|frame| scale.px_at(f64::from(frame) / self.fps)); + // The shadow, on the one lane the pointer is over -- and, like the line, + // only while the drag that asked for it is still in flight. + let ghost = self + .ghost + .filter(|g| g.lane == lane && cx.has_active_drag()); + let clips = self + .session + .as_ref() + .map_or(&[][..], |session| session.lane_clips(lane)); + // The group ids some *other* lane carries: a clip whose id is in here + // has a half elsewhere, and one whose is not is a detached half however + // many lanes there are. + let others: Vec = self.session.as_ref().map_or_else(Vec::new, |session| { + session + .lanes() + .into_iter() + .filter(|&other| other != lane) + .flat_map(|other| session.lane_clips(other)) + .filter_map(|clip| clip.link) + .collect() + }); + let name = lane.label(); + let row_id: SharedString = format!("{name}-clip").into(); + let remove_id: SharedString = format!("{name}-remove").into(); + let remove_tip: SharedString = format!( + "Remove {name} — it must be empty first, and {} brings it back", + self.keymap.display(ActionId::Undo) + ) + .into(); + let sources = self + .session + .as_ref() + .map_or(&[][..], PlaybackSession::sources); + let (sel, sel_link) = (self.selected, self.selected_link()); + let audio = lane.kind == LaneKind::Audio; + // 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 + // press opens the mix card on this very track. + let gain_db = self + .session + .as_ref() + .map_or(0., |session| session.lane_gain_db(lane)); + let gain_tip: SharedString = format!( + "{name} plays at {gain_db:+.0} dB — opens the mix ({}); the whole track, every frequency, unlike the equalizer", + self.keymap.display(ActionId::Mix) + ) + .into(); + let tip: SharedString = format!( + "Select (or {} under the playhead, {}/{} along the lane) — drag it to move it, an end to trim, {} removes the take, {} leaves a gap, {} rejoins a cut", + self.keymap.display(ActionId::Select), + self.keymap.display(ActionId::SelectPrev), + self.keymap.display(ActionId::SelectNext), + self.keymap.display(ActionId::Delete), + self.keymap.display(ActionId::Lift), + self.keymap.display(ActionId::Regroup) + ) + .into(); + div() + .flex_none() + .h(px(LANE_H)) + .flex() + .gap(px(HEADER_GAP)) + // The fixed column the ruler above is offset by as well. Full lane + // height, so it reads as the bed continuing rather than as a chip. + .child( + div() + .flex_none() + .w(px(HEADER_W)) + .h_full() + .flex() + .flex_col() + .items_center() + .justify_center() + .rounded(px(3.)) + .bg(rgb(BG_RAISED)) + .text_size(px(11.)) + .text_color(rgb(FG_SECONDARY)) + .child(match audio { + // A button, not a label: the one setting a track has of + // its own used to be reachable from nowhere. + true => div() + .id(("mix-lane", lane.ord)) + .flex_1() + .w_full() + .flex() + .items_center() + .justify_center() + .rounded(px(3.)) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .tooltip(move |_, cx| cx.new(|_| Tip(gain_tip.clone())).into()) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.open_mix(Some(lane), cx) + })) + .child(match gain_db == 0. { + true => name.clone(), + false => format!("{name} {gain_db:+.0}"), + }) + .into_any_element(), + false => div() + .flex_1() + .flex() + .items_center() + .child(name.clone()) + .into_any_element(), + }) + // The one thing a header does: take this track away again. + // A `HIT_MIN` target rather than a glyph-sized one, and it + // stays put on a track holding clips instead of hiding -- + // the refusal names them, and a control that vanishes + // teaches nothing. + .child( + div() + .id(remove_id) + .flex_none() + .w_full() + .h(px(HIT_MIN)) + .flex() + .items_center() + .justify_center() + .rounded(px(3.)) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .tooltip(move |_, cx| cx.new(|_| Tip(remove_tip.clone())).into()) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + this.remove_lane(lane, cx) + })) + .child("×"), + ), + ) + .child( + // Clips are placed at their own start rather than queued edge + // to edge: a lift leaves a hole in the lane, and the bare bed + // showing through it *is* how a gap looks. + div() + .relative() + .flex_1() + .min_w(px(0.)) + .h_full() + .rounded(px(3.)) + .bg(rgb(BG_CANVAS)) + .overflow_hidden() + // A library row let go over a lane is the same insert the + // Add button makes, through the same call -- but where the + // pointer let it go, not at the playhead: a hand that + // carried a file to a place on the bed named that place. + // gpui hands a drop no event, so the pointer is read off + // the window, which took it from the release that fired + // this (gpui window.rs:3602). + .on_drop(cx.listener(move |this, drag: &AssetDrag, window, cx| { + // Onto the edges near it, exactly as a clip carried by + // hand lands: the line drawn while it was in flight is + // the frame it goes down on. + let at = this.place_frame(window.mouse_position().x).0; + this.insert_source(&drag.0.clone(), drag.1, Some(lane), Some(at), cx) + })) + .drag_over::(|s, _, _, _| s.bg(rgb(BG_HOVER_DIM))) + // The shadow of the row in flight, drawn by the lane the + // pointer is inside: `on_drag_move` fires on every painted + // element while a drag of its type is live, wherever the + // pointer is, and hands each one its own box -- which is how + // a lane knows the pointer is over *it* (gpui div.rs:282). + // The root cleared it a moment ago, so exactly one lane + // draws one. + .on_drag_move(cx.listener( + move |this, event: &DragMoveEvent, _, cx| { + if !event.bounds.contains(&event.event.position) { + return; + } + let path = event.drag(cx).0.clone(); + this.preview_ghost_asset(&path, lane, event.event.position.x, cx); + }, + )) + // ...and a clip let go over a lane lands the same way: on + // the track it was dropped on, at the frame it was carried + // to -- its own included, which is the drag that moves a + // take along its track. + .on_drop(cx.listener(move |this, drag: &ClipDrag, window, cx| { + // Against the lane as it is *now* ([`Player::dragged`]), + // and then snapped by `move_clip` like any other drop: + // which clip is being moved and where it lands are two + // questions, and this is the first one. + let Some(idx) = this.dragged(drag) else { + return; + }; + this.move_clip(drag.lane, idx, lane, window.mouse_position().x, cx) + })) + .drag_over::(|s, _, _, _| s.bg(rgb(BG_HOVER_DIM))) + // ...and the same shadow for the clip in the hand, seated on + // this lane when the pointer is inside it. + .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(&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 + // clip, never the preview an edge drag is drawing. + let placed = *clip; + // What a drag on an edge is showing, which is the clip + // itself while nothing is being dragged. + let clip = &self.trimmed(lane, i, *clip); + // Its *timeline* length, which a speed halves or + // quadruples: the box is as wide as the clip is long + // where it sits, not as long as the source it reads. + let (start, len) = ( + f64::from(clip.start) / self.fps, + f64::from(clip.frames()) / self.fps, + ); + let on = marked((lane, i), clip.link, sel, sel_link); + // A group with a half in the other lane wears its tint; + // one without is outlined, so a detached half is visible + // as detached before anyone clicks it. + let grouped = clip.link.is_some_and(|link| others.contains(&link)); + // Tinted by *file*, not by source entry: two audio + // streams of one file are two sources, and the library + // gives them one swatch because they are one file. + let tint = self.clip_tint(clip.source); + // What the clip is worth in pixels, and how wide its box + // is drawn -- the two part company on a take too short + // to be hit at this zoom ([`clip_width`]). + let span = scale.width_px(len); + let width = clip_width(span); + let left = scale.px_at(start); + // The slice of this box that is on the bed: where its + // name, its badge and its waveform go, so none of the + // three is drawn out at a zoomed-in box's own edges. + let (vis_x, vis_w) = visible_slice(left, width, bed); + let label = sources.get(clip.source).map(|s| file_name(&s.path)); + let wave = sources + .get(clip.source) + .and_then(|s| self.waves.get(&(s.path.clone(), s.audio_stream))) + .cloned(); + // The source seconds that slice plays -- not the clip's + // whole range: the envelope is drawn for the part of the + // box that can be seen, at the resolution of the pixels + // it actually has, and never one column per two pixels + // of a box millions of pixels wide. + let along = |x: f32| match width > 0. { + true => { + f64::from(clip.in_frame) + + f64::from(clip.out_frame - clip.in_frame) + * f64::from(x / width) + } + false => f64::from(clip.in_frame), + }; + let (from, to) = (along(vis_x) / self.fps, along(vis_x + vis_w) / self.fps); + let tip = tip.clone(); + // What the pointer carries on the way to another lane: + // the file the box is showing, the same ghost a library + // row makes. A box too narrow for its own label still + // says what is moving. + let ghost: SharedString = + label.clone().unwrap_or_else(|| lane.label()).into(); + // Its head in frames, for the press below: the `start` + // above is the same moment in seconds, which is what + // the box is *drawn* from. + let head = clip.start; + div() + // Named per lane: two rows numbering their clips + // from zero would hand gpui the same id twice. + .id((row_id.clone(), i)) + .absolute() + .top_0() + .h_full() + // Negative once the clip's head has been scrolled + // off the left edge: the bed clips what hangs out + // of it, so a half-visible clip is drawn as the + // half of itself that is on screen. + .left(px(left)) + .w(px(width)) + .overflow_hidden() + .rounded(px(3.)) + .border_1() + .border_color(rgb(if on { + ACCENT_PRIMARY + } else if grouped { + tint + } else { + FG_SECONDARY + })) + .bg(rgb(if on { BG_SELECTED } else { tint })) + .cursor_pointer() + .hover(|s| s.border_color(rgb(ACCENT_PRIMARY))) + .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into()) + // Dragged, it *moves*: to the frame it was let go on + // and to the lane it was let go over. The click that + // starts the drag still selects, so picking a clip + // up and putting it back down where it was is + // exactly a click. + .on_drag( + ClipDrag { + lane, + idx: i, + clip: 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 of it, + // for the drag this press may become: the + // clip has to move with the pointer rather + // than jump its head under it. + this.grab = + this.frame_under(event.position.x).saturating_sub(head); + this.select((lane, i), cx); + }), + ) + // The right button selects exactly as the left one + // does -- the menu acts on the clip it names, so + // opening one has to pick it -- and then hangs the + // menu at the pointer. + .on_mouse_down( + MouseButton::Right, + cx.listener(move |this, event: &MouseDownEvent, _, cx| { + this.open_menu(lane, i, event.position, cx); + }), + ) + // The two strips a drag *lengthens* the clip by, + // one at each end. They occlude the box behind + // them, which is what keeps one gesture one thing: + // a press here trims, a press anywhere else on the + // box still starts the move to another lane. + // + // Asked of the clip's own width and not of the box's + // floor: a take drawn at `HIT_MIN` because it is + // shorter than that has no *pixels* to trim by -- one + // would move it by seconds -- so it keeps all of its + // padded box as a body to select and drag by, and is + // trimmed after zooming in, exactly as [`trims`] says. + .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); + }, + ), + ) + // Occluded, so the box's own right-button + // listener never fires here: the menu is + // the same menu, opened by the same call. + .on_mouse_down( + MouseButton::Right, + cx.listener( + move |this, event: &MouseDownEvent, _, cx| { + this.open_menu(lane, i, event.position, cx); + }, + ), + ); + zone = match edge { + Edge::Start => zone.left_0(), + Edge::End => zone.right_0(), + }; + zone + }), + ) + // Under the label row, never through it. + .children(wave.filter(|_| audio && vis_w > 0.).and_then(|wave| { + let inner: AnyElement = match wave { + Wave::Peaks(peaks) => { + waveform(peaks, from, to).into_any_element() + } + // A bed while the decode runs, and dimmer + // than any waveform is drawn: a flat + // `FG_SECONDARY` line here would be the shape a + // silent file makes, which this file is not + // known to be yet. + Wave::Loading => div() + .h_full() + .flex() + .items_center() + .child(div().w_full().h(px(1.)).bg(rgb(BG_HOVER))) + .into_any_element(), + // No audio track: nothing, never a fake. + Wave::Silent => return None, + // Could not be read: a band that says so in + // words, because the empty band a silent + // file draws would claim this file has no + // sound. The reason itself went to the log. + Wave::Failed => div() + .h_full() + .flex() + .items_center() + .justify_center() + .truncate() + .text_size(px(9.)) + .text_color(rgb(FG_SECONDARY)) + .child("audio unreadable") + .into_any_element(), + }; + Some( + div() + .absolute() + .left(px(vis_x)) + .w(px(vis_w)) + .top(px(LABEL_H)) + .bottom_0() + .child(inner), + ) + })) + // A speeded clip says so on the box, in the corner + // the label does not reach: the box's width alone + // cannot say whether a short clip is a trim or a + // clip at 4x, and that is the difference between a + // cut and a re-time. + // Against the right edge of what is *visible* of the + // box, not of the box: zoomed in, the box's own + // right edge is off the screen and the badge with + // it, which is a clip that stops saying it is + // speeded exactly when it is being looked at + // closely. + .when(!clip.speed.is_normal() && vis_w > 0., |d| { + d.child( + div() + .absolute() + .top_0() + .left(px(vis_x)) + .w(px(vis_w)) + .flex() + .justify_end() + .overflow_hidden() + .child( + div() + .flex_none() + .px(px(3.)) + .rounded(px(3.)) + .bg(rgb(ACCENT_PRIMARY)) + .text_size(px(9.)) + .text_color(rgb(BG_RAISED)) + .child(format!("{}", clip.speed)), + ), + ) + }) + // ...and the name sits at the left edge of the same + // slice, for the same reason: a box scrolled half + // off names itself on the half that is on screen. + .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), + ) + }) + })) + // 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 + // lane whose sound was read. Drawn before anything is cut, + // and replaced -- never stacked -- by every re-run. + .children( + self.silence_marks + .iter() + .filter(|_| self.silence_open.is_some_and(|(on, _)| on == lane)) + .map(|&(at, len)| { + div() + .absolute() + .top_0() + .h_full() + .left(px(scale.px_at(f64::from(at) / self.fps))) + // Floored like a cue's mark and for the same + // reason: a half-second silence on a zoomed- + // out bed rounds to nothing, and a preview + // that draws nothing reads as a scan that + // found nothing. + .w(px(scale + .width_px(f64::from(len) / self.fps) + .max(SUB_CUE_MIN_W))) + .bg(rgba(ACCENT_WASH)) + }), + ) + // Where the thing in the hand would come to rest, at the size + // it would come to rest at: the shadow a proper editor draws + // under a drag. Over the clips (it is translucent, so what + // it would cover shows through) and under the line, which + // marks the frame this box merely fills. + .children(ghost.map(|g| { + div() + .absolute() + .top_0() + .h_full() + .left(px(scale.px_at(f64::from(g.start) / self.fps))) + // A row whose length the engine has not measured + // draws a head marker rather than nothing: where it + // lands is known, how long it is is not. + .w(px(scale + .width_px(f64::from(g.frames) / self.fps) + .max(GHOST_MIN))) + .rounded(px(3.)) + .border_1() + .border_color(rgb(if g.refused { DROP_REFUSE } else { FG_PRIMARY })) + // The file's own swatch at a third of its weight, so + // the box beneath is still legible through it -- and + // the refusal red instead, for a lane that will not + // take this drop at all. + .bg(rgba( + ((if g.refused { DROP_REFUSE } else { g.tint }) << 8) | GHOST_ALPHA, + )) + })) + // What the gesture in flight is about to land on, drawn on + // every lane so a clip lining up with a take one track over + // can be seen to line up with it. Under the playhead's line + // and in another colour, since the two mean different + // things and often stand on the same pixel. + .children(cue.map(|x| { + div() + .absolute() + .top_0() + .h_full() + .left(px(x)) + .w(px(1.)) + .bg(rgb(FG_PRIMARY)) + })) + // Last, so it is over the clips: the same fraction in both + // lanes, which is the playhead being one line. + .child( + div() + .absolute() + .top_0() + .h_full() + .left(px(filled)) + .w(px(1.)) + .bg(rgb(ACCENT_PRIMARY)), + ), + ) + } +} diff --git a/crates/app/src/ui/toolbar.rs b/crates/app/src/ui/toolbar.rs new file mode 100644 index 0000000..e69de29 diff --git a/crates/app/src/ui/widgets.rs b/crates/app/src/ui/widgets.rs new file mode 100644 index 0000000..8735c51 --- /dev/null +++ b/crates/app/src/ui/widgets.rs @@ -0,0 +1,263 @@ +//! The small elements every region is built out of. + +use crate::*; + +/// One clip's audio, drawn as a filled min/max envelope inside whatever box it +/// is given. Peaks are the source's whole envelope; `from`/`to` are the source +/// seconds this clip plays, so a cut clip shows its own stretch of the file. +pub(crate) fn waveform(peaks: Arc>, from: f64, to: f64) -> impl IntoElement { + canvas( + |_, _, _| (), + move |bounds, _, window, _| { + let (o, s) = (bounds.origin, bounds.size); + let cols = envelope(&peaks, from, to, f32::from(s.width), f32::from(s.height)); + if cols.len() < 2 { + return; + } + // Down the tops and back along the bottoms: one closed outline of + // the whole envelope, which is one path rather than a path a column. + let mut points: Vec> = cols + .iter() + .map(|&(x, top, _)| point(o.x + px(x), o.y + px(top))) + .collect(); + points.extend( + cols.iter() + .rev() + .map(|&(x, _, bottom)| point(o.x + px(x), o.y + px(bottom))), + ); + let mut path = PathBuilder::fill(); + path.add_polygon(&points, true); + if let Ok(path) = path.build() { + window.paint_path(path, rgb(FG_SECONDARY)); + } + }, + ) + .size_full() +} + +/// A toolbar button: its glyph, its name, and its key on hover. `id` only buys +/// `on_click` and the tooltip -- it is still not focusable, so the root's own +/// key listener keeps working after a press, and the click lands on mouse-up +/// inside the button (a press that slides off does nothing). +/// +/// A button that would do nothing says so: dimmed, no pointer, no listener. +pub(crate) fn control( + id: &'static str, + glyph: Option, + // Not `&'static str`: the volume button's label is its state. + label: impl Into, + shortcut: String, + enabled: bool, + on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static, +) -> impl IntoElement { + let label = label.into(); + let tip: SharedString = format!("{label} — {shortcut}").into(); + div() + .id(id) + .flex_none() + .h(px(CONTROL_H)) + .flex() + .items_center() + .gap(px(6.)) + .px(px(8.)) + .rounded(px(3.)) + .bg(rgb(BG_RAISED)) + .children(glyph) + .child(label) + .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into()) + .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) + .when(enabled, |d| { + d.cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER))) + .on_click(on_click) + }) +} + +/// The monitoring level as something to drag: 4 px of bar to look at and the +/// whole control's height to hit (WCAG 2.5.8), the split the speed bar and the +/// colour sliders both make. Only the level -- mute is the button beside it, so +/// a muted slider still shows what unmuting comes back to, drawn dim. +/// +/// Dimmed and inert without a timeline, like every other control that would +/// have nothing to act on. +pub(crate) fn volume_slider( + volume: Volume, + bar: Rc>>, + enabled: bool, + cx: &mut Context, +) -> impl IntoElement { + div() + .id("volume-bar") + .relative() + .flex_none() + .w(px(VOLUME_W)) + .h(px(CONTROL_H)) + .flex() + .items_center() + .tooltip(|_, cx| { + cx.new(|_| Tip("Volume — drag to set the level; the button mutes".into())) + .into() + }) + .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed()) + .when(enabled, |d| { + d.cursor_pointer() + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, event: &MouseDownEvent, _, cx| { + this.volume_dragging = true; + this.drag_volume(event.position.x, cx); + }), + ) + .child(bounds_probe(bar)) + }) + .child( + div() + .w_full() + .h(px(4.)) + .rounded(px(2.)) + .bg(rgb(BG_RAISED)) + .child( + div() + .h_full() + .w(relative(volume.along())) + .rounded(px(2.)) + .bg(rgb(if volume.muted { FG_SECONDARY } else { ACCENT_PRIMARY })), + ), + ) +} + +/// The line between two groups of buttons. +pub(crate) fn separator() -> impl IntoElement { + div() + .flex_none() + .mx(px(4.)) + .w(px(1.)) + .h(px(18.)) + .bg(rgb(BG_HOVER)) +} + +/// Whether a card or a menu is drawn over the window, as the hover labels see +/// it: written once a frame by [`Player::render`], read by every [`Tip`] before +/// it paints. +/// +/// A tooltip already on screen when an overlay opens *stays* on screen in gpui: +/// occluding the surface under it does not take it back, because the check that +/// keeps it visible works off the element's absolute bounds and knows nothing +/// about what was painted over it (`div.rs::handle_tooltip_mouse_move`, its own +/// TODO). So the tip is what has to stand aside -- here, once, for every hover +/// label in this window, rather than at fifteen call sites of which the +/// sixteenth would be forgotten. +pub(crate) static OVERLAID: AtomicBool = AtomicBool::new(false); + +/// A tooltip is a view in gpui and nothing smaller, so this is the smallest one +/// that carries a line of text. It paints outside the window's element tree and +/// therefore owns its colours. +pub(crate) struct Tip(pub(crate) SharedString); + +impl Render for Tip { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + // A card or a menu is up: nothing. A line of text over the items of the + // menu that just opened under the pointer is the card being painted + // over by the window it covers. + if OVERLAID.load(Ordering::Relaxed) { + return div(); + } + div() + .px(px(6.)) + .py(px(3.)) + .rounded(px(3.)) + .border_1() + .border_color(rgb(BG_RAISED)) + .bg(rgb(BG_PANEL)) + .text_color(rgb(FG_PRIMARY)) + .text_size(px(12.)) + .child(self.0.clone()) + } +} + +/// Scissors: two blades crossed. Drawn this way and not as a split clip because +/// two bars is what the transport wears when it is playing -- the one glyph a +/// cut must never be mistaken for. +pub(crate) fn cut_glyph() -> impl IntoElement { + canvas( + |_, _, _| (), + |bounds, _, window, _| { + let (o, s) = (bounds.origin, bounds.size); + let mut path = PathBuilder::stroke(px(1.5)); + path.move_to(point(o.x + s.width * 0.15, o.y + s.height)); + path.line_to(point(o.x + s.width * 0.9, o.y + s.height * 0.1)); + path.move_to(point(o.x + s.width * 0.85, o.y + s.height)); + path.line_to(point(o.x + s.width * 0.1, o.y + s.height * 0.1)); + if let Ok(path) = path.build() { + window.paint_path(path, rgb(FG_PRIMARY)); + } + }, + ) + .w(px(13.)) + .h(px(13.)) +} + +/// A lid over a bin. +pub(crate) fn delete_glyph() -> impl IntoElement { + div() + .flex() + .flex_col() + .items_center() + .gap(px(2.)) + .child(div().w(px(13.)).h(px(2.)).bg(rgb(FG_PRIMARY))) + .child(div().w(px(9.)).h(px(9.)).bg(rgb(FG_PRIMARY))) +} + +/// What a window with no file open is waiting for. Both ways in are already +/// built -- the whole window is the drop target and the Import chooser takes a +/// project as readily as media -- so this only has to say so. +pub(crate) fn empty_hint() -> impl IntoElement { + div() + .flex() + .flex_col() + .items_center() + .gap(px(6.)) + .text_color(rgb(FG_SECONDARY)) + .child("Drop a video or an .edith project here") + .child( + div() + .text_size(px(11.)) + .child("or click Import in the media list"), + ) +} + +/// Two bars while playing, a triangle in every other state -- paused, nothing +/// open, and played out, where the button's next act is to start over rather +/// than to stop something. Drawn, so there is no icon font and no glyph +/// coverage to depend on. +pub(crate) fn transport_glyph(state: Transport) -> impl IntoElement { + let playing = state.is_playing(); + div() + .flex() + .items_center() + .gap(px(4.)) + .when(playing, |d| { + d.child(div().w(px(3.)).h(px(12.)).bg(rgb(FG_PRIMARY))) + .child(div().w(px(3.)).h(px(12.)).bg(rgb(FG_PRIMARY))) + }) + .when(!playing, |d| { + d.child( + canvas( + |_, _, _| (), + |bounds, _, window, _| { + let (o, s) = (bounds.origin, bounds.size); + let mut path = PathBuilder::fill(); + path.move_to(o); + path.line_to(point(o.x + s.width, o.y + s.height / 2.)); + path.line_to(point(o.x, o.y + s.height)); + path.close(); + if let Ok(path) = path.build() { + window.paint_path(path, rgb(FG_PRIMARY)); + } + }, + ) + .w(px(11.)) + .h(px(13.)), + ) + }) +}