diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index 60f76da..2cedaf1 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -63,6 +63,9 @@ pub enum ActionId { Color, Fit, Resolution, + ZoomIn, + ZoomOut, + ZoomFit, Undo, AddVideoLane, AddAudioLane, @@ -80,7 +83,7 @@ pub enum ActionId { impl ActionId { /// Display order everywhere -- the editor lists them in it and /// [`Keymap::defaults`] binds them in it. - pub const ALL: [ActionId; 35] = [ + pub const ALL: [ActionId; 38] = [ ActionId::Play, ActionId::StepBack, ActionId::StepForward, @@ -104,6 +107,9 @@ impl ActionId { ActionId::Color, ActionId::Fit, ActionId::Resolution, + ActionId::ZoomIn, + ActionId::ZoomOut, + ActionId::ZoomFit, ActionId::Undo, ActionId::AddVideoLane, ActionId::AddAudioLane, @@ -144,6 +150,9 @@ impl ActionId { ActionId::Color => "Colour…", ActionId::Fit => "Fit policy: fit → fill → stretch → centre", ActionId::Resolution => "Project resolution: source → 2160p → 1080p → 720p → 480p", + ActionId::ZoomIn => "Zoom in on the timeline (around the playhead)", + ActionId::ZoomOut => "Zoom out of the timeline", + ActionId::ZoomFit => "Fit the whole timeline on screen", ActionId::Undo => "Undo", ActionId::AddVideoLane => "Add a video track", ActionId::AddAudioLane => "Add an audio track", @@ -186,6 +195,9 @@ impl ActionId { ActionId::Color => "color", ActionId::Fit => "fit", ActionId::Resolution => "resolution", + ActionId::ZoomIn => "zoom-in", + ActionId::ZoomOut => "zoom-out", + ActionId::ZoomFit => "zoom-fit", ActionId::Undo => "undo", ActionId::AddVideoLane => "add-video-lane", ActionId::AddAudioLane => "add-audio-lane", @@ -236,7 +248,11 @@ impl ActionId { | ActionId::Silence => Category::Clips, // The project's own picture size is not a clip's business, and not // a file operation either: it is what the viewer is looking at. - ActionId::Resolution => Category::View, + // Neither is how much of the timeline the panel shows: a zoom edits + // nothing, it magnifies. + ActionId::Resolution | ActionId::ZoomIn | ActionId::ZoomOut | ActionId::ZoomFit => { + Category::View + } ActionId::Cut | ActionId::Regroup | ActionId::Detach @@ -307,7 +323,7 @@ pub const FIXED: [Fixed; 16] = [ // holding anything else still does what one press did. Fixed { chord: "hold ← → ↑ ↓", - label: "Run a card's slider, or the volume keys, while held", + label: "Run a card's slider, or the volume and zoom keys, while held", category: Category::View, }, Fixed { @@ -544,6 +560,14 @@ impl Keymap { // it changes what every clip is composed onto. b(ActionId::Fit, "p", false), b(ActionId::Resolution, "r", true), + // The zoom pair, on the chords every editor and every browser + // magnifies with. The bare "=" and "-" are the volume keys, so + // these take the ctrl versions of them -- and ctrl+0 is the + // "back to 100%" of the same family, which here is the whole + // timeline across the bed. + b(ActionId::ZoomIn, "=", true), + b(ActionId::ZoomOut, "-", true), + b(ActionId::ZoomFit, "0", true), b(ActionId::Undo, "z", false), b(ActionId::Undo, "z", true), // The unshifted initials of what they add. Both were free -- @@ -839,7 +863,7 @@ mod tests { #[test] fn every_default_stroke_reaches_its_action() { let k = Keymap::defaults(); - assert_eq!(k.entries().len(), 37); + assert_eq!(k.entries().len(), 40); assert_eq!(k.lookup("space", false), Some(ActionId::Play)); // The seek keys: bare arrows a frame, ctrl arrows a second, and the two // ends of the timeline. @@ -1015,7 +1039,8 @@ mod tests { // A bindable chord is one `rebind_action` may keep: what it writes is // what the next load reads, for every stroke that passes here. let mut k = Keymap::defaults(); - k.rebind_action(ActionId::Play, chord("=", true)).unwrap(); + // Any free chord will do here; ctrl+= is the zoom's. + k.rebind_action(ActionId::Play, chord("w", true)).unwrap(); assert_eq!(whole(&emit(&k)), k); } @@ -1072,7 +1097,8 @@ mod tests { assert_eq!(whole("edith-keys 1\n").display(ActionId::Cut), "unbound"); // The label is the editor's column, and never the file's word for it. assert_eq!(ActionId::CancelExport.label(), "Cancel export"); - assert_eq!(ActionId::ALL.len(), 35); + assert_eq!(ActionId::ALL.len(), 38); + assert_eq!(k.display(ActionId::ZoomIn), "ctrl+="); } #[test] diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 5ce2172..bbba1be 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -19,9 +19,9 @@ use engine::{Clip, ExportHandle, Frame, PlaybackSession}; use gpui::{ AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, - Point, RenderImage, SharedString, Size, Stateful, TextAlign, TitlebarOptions, Window, - WindowBounds, WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb, rgba, - size, + Point, RenderImage, ScrollDelta, ScrollWheelEvent, SharedString, Size, Stateful, TextAlign, + TitlebarOptions, Window, WindowBounds, WindowOptions, canvas, div, img, point, prelude::*, px, + relative, rgb, rgba, size, }; /// Editor chrome: three grays and one accent, all darker than the picture so the @@ -74,6 +74,11 @@ const LABEL_MIN_W: f32 = 36.; /// allocates one bucket per window, so a rate taken from anything the user can /// influence is an allocation bomb -- and 40 is already finer than the pixels a /// clip is ever given. +/// +/// ponytail: "finer than the pixels" stops being true once the timeline is +/// zoomed -- past ~25 ms per bucket the envelope reads as steps rather than as +/// a shape. Ceiling: [`View::max_zoom`]'s 8 frames across the bed. The upgrade +/// is a second, finer pass over the visible span only, cached like `waves` is. const WAVE_BPS: u32 = 40; /// Pixels per envelope column. Coarser than a pixel: the eye reads the shape, /// and a path with a point per pixel is a path per repaint. @@ -594,6 +599,10 @@ struct Player { /// The ruler's own box, recorded at prepaint: a mouse listener is handed /// the window position and nothing else. ruler: Rc>>, + /// How much of the timeline the ruler and the lanes are showing. Held here + /// and nowhere else: every frame-to-pixel answer in the panel comes out of + /// it, so the boxes, the playhead and the pointer cannot disagree. + view: View, /// Which clip the edit keys act on: the lane it is in and its index there. /// The *clicked* half, not the group -- a group is what gets marked on /// screen, but Lift has to know which half it was aimed at. Indices move @@ -916,6 +925,12 @@ impl Player { ActionId::Color => self.open_color(cx), ActionId::Fit => self.cycle_fit(cx), ActionId::Resolution => self.cycle_resolution(cx), + // The playhead is what a key zoom is aimed at: it is the one place + // on the timeline the user is certainly looking at, and keeping it + // still is what every editor does. + ActionId::ZoomIn => self.zoom(ZOOM_STEP, None, cx), + ActionId::ZoomOut => self.zoom(1. / ZOOM_STEP, None, cx), + ActionId::ZoomFit => self.zoom_fit(cx), ActionId::Undo => self.undo(cx), ActionId::AddVideoLane => self.add_lane(LaneKind::Video, cx), ActionId::AddAudioLane => self.add_lane(LaneKind::Audio, cx), @@ -1039,6 +1054,26 @@ impl Player { cx.notify(); } + /// Magnifies the timeline about a point that stays put: `anchor` is where + /// along the bed to hold still (a ctrl+wheel holds the pointer), and with + /// none it is the playhead -- so the frame being worked on is still the + /// frame on screen after the zoom. Clamped at both ends by [`View`]: out + /// stops at the whole timeline, in at a handful of frames. + fn zoom(&mut self, factor: f32, anchor: Option, cx: &mut Context) { + let duration = self.drawn_duration(); + let at = self.playhead(duration); + let anchor = anchor.unwrap_or_else(|| self.view.frac_at(at, duration).clamp(0., 1.)); + self.view = self.view.zoomed(factor, anchor, duration, self.fps); + cx.notify(); + } + + /// All the way back out: the whole timeline across the bed, which is what + /// the panel shows before anyone has zoomed at all. + fn zoom_fit(&mut self, cx: &mut Context) { + self.view = View::default(); + cx.notify(); + } + /// Cycles the *project's* resolution through [`RESOLUTIONS`], starting from /// the media's own -- the one size that must stay reachable, since a project /// moved off it has no other way back (the resolution is not an undo step). @@ -2108,14 +2143,16 @@ impl Player { /// pointer exactly. fn trim_to(&mut self, x: Pixels, cx: &mut Context) { let (duration, fps) = (self.drawn_duration(), self.fps); - let frac = frac_along(x, self.ruler.get()); + let at = self + .view + .time_at(frac_along(x, self.ruler.get()), duration); let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else { return; }; let Some((lo, hi)) = session.trim_room(trim.lane, trim.idx, trim.edge) else { return; }; - trim.to = frame_at(f64::from(frac) * duration, fps).clamp(lo, hi); + trim.to = frame_at(at, fps).clamp(lo, hi); cx.notify(); } @@ -2201,6 +2238,21 @@ impl Player { } } + /// Where the playhead is, as the panel draws it. The clock keeps running + /// after the last frame (wall time takes over at audio EOF) while the + /// picture is frozen, so what the UI shows is the clamped one, pinned to + /// the out-point once playback is done. + fn playhead(&self, duration: f64) -> f64 { + if self.done { + duration + } else { + self.session + .as_ref() + .map_or(0., PlaybackSession::now) + .clamp(0., duration) + } + } + /// The one way a library row reaches the timeline: the Add button and a row /// dragged onto a lane both come here, so there is a single answer to what /// "add this source" does. The whole source goes in at the playhead as one @@ -2657,7 +2709,9 @@ impl Player { let Some(session) = &self.session else { return; }; - let t = f64::from(frac_along(x, self.ruler.get())) * session.timeline_duration(); + let t = self + .view + .time_at(frac_along(x, self.ruler.get()), session.timeline_duration()); let target = (t * self.fps) as u32; if commit || scrub_due(target, self.last_target, self.last_scrub.elapsed()) { self.last_target = target; @@ -2927,17 +2981,12 @@ impl Render for Player { // timecode, the ruler and the clamp below all have to follow it -- and // so does the room a tail being dragged needs to grow into. let duration = self.drawn_duration(); - // The clock keeps running after the last frame (wall time takes over at - // audio EOF) while the picture is frozen, so the timeline the UI shows is - // the clamped one, pinned to the out-point once playback is done. - let position = if self.done { - duration - } else { - self.session - .as_ref() - .map_or(0., PlaybackSession::now) - .clamp(0., duration) - }; + let position = self.playhead(duration); + // Re-settled every frame against the duration this one is drawing: an + // edit that shortens the timeline moves the far end of the view, and a + // playhead that has run off the bed pulls the view after it -- which is + // what makes a zoomed-in timeline scroll while it plays. + self.view = self.view.following(position, duration, self.fps); div() .track_focus(&self.focus) @@ -3638,11 +3687,11 @@ impl Player { playing: bool, cx: &mut Context, ) -> impl IntoElement { - let filled = if duration > 0. { - (position / duration) as f32 - } else { - 0. - }; + // Where the playhead is *on the bed*, which at the fit is where along + // the timeline it is and zoomed in is where along the visible slice. + // Clamped 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. + let filled = self.view.frac_at(position, duration).clamp(0., 1.); // 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. @@ -3846,6 +3895,51 @@ impl Player { live, cx.listener(|this, _: &ClickEvent, _, cx| this.cycle_resolution(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 reads as the state (1.0x is the whole + // timeline) and is the way back to it. + .child(control( + "zoom-out", + None, + "−", + format!( + "{} — show more of the timeline; stops at the whole of it", + key(ActionId::ZoomOut) + ), + live, + cx.listener(|this, _: &ClickEvent, _, cx| { + this.zoom(1. / ZOOM_STEP, None, cx) + }), + )) + .child(control( + "zoom-fit", + None, + format!("{:.1}x", self.view.zoom), + format!( + "{} — fit the whole timeline; showing {} to {}", + key(ActionId::ZoomFit), + timecode(self.view.start, self.fps), + timecode( + (self.view.start + self.view.span(duration)).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)), + )) // 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. @@ -3958,7 +4052,32 @@ impl Player { .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".into())).into()) + .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 = frac_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| { @@ -5550,6 +5669,9 @@ impl Player { // one probe answers for both. Zero before the first paint, which only // costs the labels one frame. let bed_w = f32::from(self.ruler.get().size.width); + // The slice being shown, copied out once: every box in the row is + // placed through it, so all of them move together when it does. + let view = self.view; let clips = self .session .as_ref() @@ -5687,7 +5809,7 @@ impl Player { .and_then(|s| sources.iter().position(|o| o.path == s.path)) .unwrap_or(clip.source), ); - let width = width_frac(len, duration); + let width = view.width_frac(len, duration); let label = sources.get(clip.source).map(|s| file_name(&s.path)); let wave = sources .get(clip.source) @@ -5711,7 +5833,11 @@ impl Player { .absolute() .top_0() .h_full() - .left(relative(start_frac(start, duration))) + // 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(relative(view.frac_at(start, duration))) .w(relative(width)) .overflow_hidden() .rounded(px(3.)) @@ -5860,8 +5986,12 @@ impl Player { .absolute() .top_0() .h_full() - .left(relative(start_frac(f64::from(at) / self.fps, duration))) - .w(relative(width_frac(f64::from(len) / self.fps, duration))) + .left(relative( + view.frac_at(f64::from(at) / self.fps, duration), + )) + .w(relative( + view.width_frac(f64::from(len) / self.fps, duration), + )) .bg(rgba(0x4a9effaa)) }), ) @@ -6691,7 +6821,18 @@ enum Repeat { fn repeats(scope: Repeat, key: &str, action: Option) -> bool { match scope { Repeat::Card => matches!(key, "up" | "down" | "left" | "right"), - Repeat::Keymap => matches!(action, Some(ActionId::VolumeUp | ActionId::VolumeDown)), + Repeat::Keymap => matches!( + action, + Some( + ActionId::VolumeUp + | ActionId::VolumeDown + // A zoom is a value being moved as much as a level is: + // held, it runs from the whole timeline down to a handful + // of frames and stops there. The fit is one press. + | ActionId::ZoomIn + | ActionId::ZoomOut + ) + ), Repeat::Nothing => false, } } @@ -6789,14 +6930,127 @@ fn width_frac(len: f64, total: f64) -> f32 { if total > 0. { (len / total) as f32 } else { 1. } } -/// Where along the lane a clip starts, 0..1. Unlike [`width_frac`] a timeline -/// with no length pins this to the left edge -- a full-width offset would push -/// the box out of the lane it belongs to. -fn start_frac(start: f64, total: f64) -> f32 { - if total > 0. { - (start / total).clamp(0., 1.) as f32 - } else { - 0. +/// One press of a zoom key, or one notch of ctrl+wheel. +const ZOOM_STEP: f32 = 1.25; + +/// How few frames the bed may be narrowed down to. Past this there is nothing +/// left to aim at -- a single frame across a whole window is a wall of colour, +/// not an edit surface. +const ZOOM_MIN_FRAMES: f64 = 8.; + +/// Which slice of the timeline the ruler and the lanes are showing: `zoom` is +/// how many times the whole of it the bed is now worth, and `start` the moment +/// at the bed's left edge. The one place frames become pixels -- every box, the +/// playhead, a seek and a trim all go through it, so none of them can drift +/// away from the others when the view moves. +/// +/// [`View::default`] is the whole timeline across the bed, which is what the +/// panel drew before there was a zoom at all: at zoom 1 `start` is pinned to 0 +/// and every fraction here is the one [`width_frac`] and `start_frac` gave. +#[derive(Clone, Copy, Debug, PartialEq)] +struct View { + zoom: f32, + start: f64, +} + +impl Default for View { + fn default() -> Self { + View { + zoom: 1., + start: 0., + } + } +} + +impl View { + /// How much of the timeline is on the bed, in seconds. + fn span(self, duration: f64) -> f64 { + duration / f64::from(self.zoom) + } + + /// The tightest this timeline may be zoomed: [`ZOOM_MIN_FRAMES`] across the + /// bed. Never under 1 -- a timeline shorter than that is already at its + /// floor, and a zoom that cannot fit the whole of it is not a zoom. + fn max_zoom(duration: f64, fps: f64) -> f32 { + let frames = duration * fps; + if frames > ZOOM_MIN_FRAMES { + (frames / ZOOM_MIN_FRAMES) as f32 + } else { + 1. + } + } + + /// Where a moment sits along the bed, 0 at its left edge and 1 at its + /// right. Outside that range for a moment scrolled off the view, which is + /// exactly the negative offset a half-visible clip is drawn at. + fn frac_at(self, at: f64, duration: f64) -> f32 { + let span = self.span(duration); + if span > 0. { + ((at - self.start) / span) as f32 + } else { + 0. + } + } + + /// How wide a stretch of `len` seconds is on the bed. More than the whole + /// bed once zoomed in, which is the point of zooming in. + fn width_frac(self, len: f64, duration: f64) -> f32 { + width_frac(len, self.span(duration)) + } + + /// The moment a pointer at `frac` along the bed is pointing at: the inverse + /// of [`View::frac_at`], and what every seek and every trim reads. + fn time_at(self, frac: f32, duration: f64) -> f64 { + (self.start + f64::from(frac) * self.span(duration)).clamp(0., duration) + } + + /// Zoomed by `factor` about `anchor` (0..1 along the bed): whatever moment + /// was under that point stays under it, so a zoom magnifies what was being + /// looked at rather than throwing it off the edge. + fn zoomed(self, factor: f32, anchor: f32, duration: f64, fps: f64) -> Self { + let at = self.start + f64::from(anchor) * self.span(duration); + // Clamped *before* the offset is worked out, not after: a press that + // runs into either stop must still leave the anchor where it is, and a + // start measured against a zoom the stop then took away would slide it. + let zoom = (self.zoom * factor).clamp(1., Self::max_zoom(duration, fps)); + let start = at - f64::from(anchor) * View { zoom, start: 0. }.span(duration); + View { zoom, start }.settled(duration, fps) + } + + /// Clamped to the timeline it draws: never wider than the whole of it (the + /// zoom-out floor is the fit), never tighter than [`View::max_zoom`], and + /// never scrolled past either end. + fn settled(self, duration: f64, fps: f64) -> Self { + let zoom = if self.zoom.is_finite() { + self.zoom.clamp(1., Self::max_zoom(duration, fps)) + } else { + 1. + }; + let span = View { zoom, start: 0. }.span(duration); + let start = if self.start.is_finite() { + self.start.clamp(0., (duration - span).max(0.)) + } else { + 0. + }; + View { zoom, start } + } + + /// The view a playhead at `at` needs: the same one while it is on the bed, + /// and one centred on it once it has run off -- which is how a zoomed-in + /// timeline scrolls, during playback and after a seek alike. At the fit + /// this can never fire, so an unzoomed panel is untouched by it. + fn following(self, at: f64, duration: f64, fps: f64) -> Self { + let view = self.settled(duration, fps); + let span = view.span(duration); + if at < view.start || at > view.start + span { + View { + start: at - span / 2., + ..view + } + .settled(duration, fps) + } else { + view + } } } @@ -7465,10 +7719,13 @@ mod tests { export_settings, format_key, format_line, format_refusal, frac_along, frac_down, frame_at, histogram, is_bare_modifier, is_project, keymap, lanes_h, marked, menu_at, normalise, nothing_to_play, panel_h, project_path, push_digit, retarget, scrub_due, show_label, - silence_rate, source_tint, span_partner, speed_at, start_frac, timecode, unseen_paths, - unseen_sources, whole_take, width_frac, window_title, + silence_rate, source_tint, span_partner, speed_at, timecode, unseen_paths, unseen_sources, + whole_take, width_frac, window_title, + }; + use super::{ + LaneKind, Repeat, View, ZOOM_MIN_FRAMES, ZOOM_STEP, file_name, file_uri, library_rows, + repeats, unscannable, }; - use super::{LaneKind, Repeat, file_name, file_uri, library_rows, repeats, unscannable}; /// What the file manager is handed: the parts a path keeps as they are, and /// the ones the bus would otherwise read as something else. @@ -7856,6 +8113,10 @@ mod tests { ActionId::Save => element("save"), ActionId::Undo => element("undo"), ActionId::Resolution => element("resolution"), + // Three buttons beside it, and the ctrl+wheel on the bar. + ActionId::ZoomIn => element("zoom-in"), + ActionId::ZoomOut => element("zoom-out"), + ActionId::ZoomFit => element("zoom-fit"), ActionId::AddVideoLane => element("add-video-lane"), ActionId::AddAudioLane => element("add-audio-lane"), // The × in a lane's own header, which takes any track and @@ -8576,6 +8837,161 @@ mod tests { } } + /// The mapping the whole panel is drawn and clicked through: a moment goes + /// to a fraction of the bed and comes back the same moment, at every zoom. + /// The fit is the invariant that matters most -- it must be the arithmetic + /// the panel did before there was a zoom at all. + #[test] + fn a_moment_and_the_place_it_is_drawn_are_the_same_at_every_zoom() { + let duration = 20.; + // The fit: what `start_frac`/`width_frac` used to answer, exactly. + let fit = View::default(); + for t in [0., 5., 12.5, 20.] { + assert_eq!(fit.frac_at(t, duration), (t / duration) as f32, "fit at {t}"); + } + assert_eq!(fit.width_frac(5., duration), width_frac(5., duration)); + for view in [ + fit, + View { + zoom: 2., + start: 4., + }, + View { + zoom: 8., + start: 12.5, + }, + View { + zoom: 37.5, + start: 19., + }, + ] { + let view = view.settled(duration, 30.); + for frac in [0., 0.25, 0.5, 1.] { + let at = view.time_at(frac, duration); + assert!( + (f64::from(view.frac_at(at, duration)) - f64::from(frac)).abs() < 1e-6, + "{view:?} round trip at {frac}" + ); + } + // A stretch is as wide as the share of the visible slice it takes. + assert!( + (f64::from(view.width_frac(view.span(duration), duration)) - 1.).abs() < 1e-6, + "{view:?} spans the bed" + ); + } + } + + /// The rule that makes a zoom usable: whatever was under the anchor is + /// still under it afterwards -- the playhead for a key, the pointer for a + /// ctrl+wheel. + #[test] + fn a_zoom_leaves_the_anchor_where_it_was_on_screen() { + let (duration, fps) = (20., 30.); + let mut view = View::default(); + for anchor in [0.5f32, 0.25, 0.9] { + // Well past the zoom-in stop: the anchor holds at the clamp too, + // which is where it used to slide (the clamp came after the offset). + for _ in 0..30 { + let at = view.time_at(anchor, duration); + let zoomed = view.zoomed(ZOOM_STEP, anchor, duration, fps); + // Only where the anchor is not pinned by an edge of the + // timeline: a view already against an end cannot slide further. + let pinned = zoomed.start <= 0. || zoomed.start + zoomed.span(duration) >= duration; + if !pinned { + assert!( + (f64::from(zoomed.frac_at(at, duration)) - f64::from(anchor)).abs() < 1e-6, + "{at} moved: {view:?} -> {zoomed:?}" + ); + } + assert!(zoomed.zoom >= view.zoom, "and it did zoom in"); + view = zoomed; + } + } + } + + /// Both stops: out is the whole timeline (which is where the panel starts, + /// so nothing regressed for anyone who never zooms), in is a handful of + /// frames -- and neither can scroll off an end. + #[test] + fn zoom_stops_at_the_whole_timeline_and_at_a_handful_of_frames() { + let (duration, fps) = (20., 30.); + let mut view = View::default(); + for _ in 0..200 { + view = view.zoomed(1. / ZOOM_STEP, 0.5, duration, fps); + } + assert_eq!(view, View::default(), "zoomed out is the fit"); + for _ in 0..200 { + view = view.zoomed(ZOOM_STEP, 0.5, duration, fps); + } + assert_eq!( + (view.span(duration) * fps).round(), + ZOOM_MIN_FRAMES, + "tightest is a handful of frames" + ); + // Against the far end, the slice still ends at the last frame. + let end = View { + zoom: view.zoom, + start: 1e6, + } + .settled(duration, fps); + assert!((end.start + end.span(duration) - duration).abs() < 1e-9); + assert!( + View { + zoom: view.zoom, + start: -5. + } + .settled(duration, fps) + .start + == 0. + ); + // A timeline too short to zoom into, and one with no length at all, + // both stay at the fit rather than dividing by nothing. + assert_eq!(View::max_zoom(0.1, fps), 1.); + assert_eq!(View::default().settled(0., fps), View::default()); + assert_eq!(View::default().frac_at(3., 0.), 0.); + assert_eq!(View::default().time_at(0.5, 0.), 0.); + } + + /// What makes a zoomed timeline follow the playing head: off the bed at + /// either end pulls the view onto it, and on the bed it never moves -- a + /// view that jumped every frame would be unreadable. + #[test] + fn the_view_follows_a_playhead_that_runs_off_the_bed() { + let (duration, fps) = (20., 30.); + let view = View { + zoom: 4., + start: 5., + } + .settled(duration, fps); + assert_eq!(view.span(duration), 5.); + // Inside: untouched, whichever part of the slice it is in. + for at in [5., 7.5, 10.] { + assert_eq!(view.following(at, duration, fps), view, "{at} is on the bed"); + } + // Past the right edge, as playback does it: the head comes back on the + // bed, and the zoom is not changed by the scroll. + let moved = view.following(12., duration, fps); + assert_eq!(moved.zoom, view.zoom); + assert!(moved.start > view.start, "scrolled forward"); + assert!( + moved.frac_at(12., duration) > 0. && moved.frac_at(12., duration) < 1., + "and the playhead is on screen" + ); + // A seek back behind the slice does the same the other way. + let back = view.following(1., duration, fps); + assert!(back.start < view.start); + assert!(back.frac_at(1., duration) >= 0.); + // At the fit there is nothing to follow: the whole timeline is on the + // bed already, so no playhead can move it. + for at in [0., 10., 20.] { + assert_eq!( + View::default().following(at, duration, fps), + View::default(), + "the fit never scrolls" + ); + } + } + #[test] fn clip_boxes_split_the_lane_by_duration() { // 1 s + 3 s of a 4 s timeline: a quarter and three quarters. @@ -9158,11 +9574,20 @@ mod tests { // value being moved. assert!(repeats(Repeat::Keymap, "up", Some(ActionId::VolumeUp))); assert!(repeats(Repeat::Keymap, "down", Some(ActionId::VolumeDown))); + // ...and the zoom pair, which runs the view the way they run the level. + assert!(repeats(Repeat::Keymap, "=", Some(ActionId::ZoomIn))); + assert!(!repeats(Repeat::Keymap, "0", Some(ActionId::ZoomFit))); for action in ActionId::ALL { let held = repeats(Repeat::Keymap, "k", Some(action)); assert_eq!( held, - matches!(action, ActionId::VolumeUp | ActionId::VolumeDown), + matches!( + action, + ActionId::VolumeUp + | ActionId::VolumeDown + | ActionId::ZoomIn + | ActionId::ZoomOut + ), "{action:?} on a hold" ); } @@ -9386,10 +9811,9 @@ mod tests { assert!(show_label(400.)); assert!(!show_label(LABEL_MIN_W - 0.1)); // A timeline with no length must not put a box outside its lane. - assert_eq!(start_frac(3., 0.), 0.); - assert_eq!(start_frac(1., 4.), 0.25); - // Past the end clamps rather than running off the bed. - assert_eq!(start_frac(8., 4.), 1.); + let fit = View::default(); + assert_eq!(fit.frac_at(3., 0.), 0.); + assert_eq!(fit.frac_at(1., 4.), 0.25); } #[test] @@ -9754,6 +10178,9 @@ fn main() { eos: false, done: false, ruler: Rc::default(), + // The whole timeline across the bed, which is where a + // project opens: zooming is something the user asks for. + view: View::default(), selected: None, context_menu: None, library_menu: None,