From 5372bfda87ac86a9bd6f9ed1e72d67217730c75e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 9 Aug 2026 17:32:44 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(app):=20clips=20lane=20?= =?UTF-8?q?=E2=80=94=20cut/delete/undo,=20drag-scrub?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - clips lane: one box per clip, proportional widths, click-select, ACCENT-tinted selection; plain divs keep spacebar focus - keys c (cut at playhead) / x or delete / z (undo) + drawn buttons; is_held guards all four against auto-repeat editing - drag-scrub on the root div (gpui has no mouse capture — release outside the window is caught by clearing scrub on a moved event with no left button); throttle: seek only on frame change + 100ms, always commit on release - cached duration deleted — timeline_duration() dynamic, so delete shrinks ruler and timecode immediately --- crates/app/src/main.rs | 322 ++++++++++++++++++++++++++++++++++------- 1 file changed, 267 insertions(+), 55 deletions(-) diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index db47ea3..c4bba84 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -1,14 +1,14 @@ use std::cell::Cell; use std::rc::Rc; use std::sync::Arc; -use std::sync::mpsc::TryRecvError; -use std::time::Instant; +use std::time::{Duration, Instant}; use engine::{Frame, PlaybackSession}; use gpui::{ App, Application, Bounds, Context, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent, - PathBuilder, Pixels, RenderImage, SharedString, TitlebarOptions, Window, WindowBounds, - WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb, size, + MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, RenderImage, SharedString, TitlebarOptions, + Window, WindowBounds, WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb, + size, }; /// Editor chrome: three grays and one accent, all darker than the picture so the @@ -18,6 +18,8 @@ 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; /// Fixed so the video region takes every pixel the window gains and the controls /// never clip at 640x360. @@ -33,9 +35,6 @@ struct Player { /// Timeline seconds -> frame index, so the clock can be compared to what /// the decoder hands over. fps: f64, - /// `frame_count / frame_rate`: the timeline's end, and the clamp for a clock - /// that keeps running past it. - duration: f64, name: SharedString, image: Option>, /// A frame that arrived before its time; shown on the tick it comes due. @@ -50,6 +49,14 @@ struct Player { /// The ruler's own box, recorded at prepaint: a mouse listener is handed /// the window position and nothing else. ruler: Rc>>, + /// Which clip the edit keys act on. Indices move under every edit, so this + /// is cleared by all of them. + selected: Option, + /// A drag that started on the ruler. Moves anywhere in the window scrub + /// while it is set; the release commits the exact position. + scrubbing: bool, + last_scrub: Instant, + last_target: u32, /// Playback was started once, on the first render. Space owns it after that. launched: bool, displayed: u32, @@ -69,11 +76,13 @@ impl Player { loop { let frame = match self.held.take() { Some(frame) => frame, - None => match self.session.frames().try_recv() { - Ok(frame) => frame, - Err(TryRecvError::Empty) => break, - Err(TryRecvError::Disconnected) => { - self.eos = true; + // Nothing waiting means either a clip boundary being rebuilt or + // the real end of the timeline, and only the engine can tell + // them apart -- `frame.index` is already a timeline index. + None => match self.session.try_frame() { + Some(frame) => frame, + None => { + self.eos = self.session.is_eos(); break; } }, @@ -119,18 +128,66 @@ impl Player { } } - /// Jumps the timeline. Every end-of-stream flag is app state and the - /// engine knows nothing about it, so clearing them here is what stops the - /// picture from staying frozen on the old last frame. - fn seek(&mut self, t: f64, cx: &mut Context) { - self.session.seek(t); + /// Every end-of-stream flag is app state and the engine knows nothing about + /// it, so clearing them after a reseek is what stops the picture from + /// staying frozen on the old last frame. Edits reseek inside the engine and + /// still owe this. + fn reset_after_reseek(&mut self) { self.held = None; self.eos = false; self.done = false; self.pending_seek = true; + } + + /// Jumps the timeline. + fn seek(&mut self, t: f64, cx: &mut Context) { + self.session.seek(t); + self.reset_after_reseek(); + cx.notify(); + } + + /// Splits the clip under the playhead. Metadata only: the timeline->source + /// mapping is unchanged, so nothing reseeks and no flag is touched. + fn cut(&mut self, cx: &mut Context) { + self.session.cut_at(self.session.now()); + self.selected = None; + cx.notify(); + } + + /// Drops the selected clip. The engine reseeks itself, so all this owes is + /// the flag reset. + fn delete_selected(&mut self, cx: &mut Context) { + if self + .selected + .take() + .is_some_and(|i| self.session.delete_clip(i)) + { + self.reset_after_reseek(); + } + cx.notify(); + } + + fn undo(&mut self, cx: &mut Context) { + if self.session.undo() { + self.reset_after_reseek(); + } + self.selected = None; cx.notify(); } + /// Seeks to where the pointer sits along the ruler. `commit` is the press + /// and the release, which must land exactly even when the throttle below + /// would have skipped them. + fn scrub_to(&mut self, x: Pixels, commit: bool, cx: &mut Context) { + let t = f64::from(frac_along(x, self.ruler.get())) * self.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; + self.last_scrub = Instant::now(); + self.seek(t, cx); + } + } + /// Space and the transport button share it: once the timeline is finished /// the only sensible "play" is from the top. fn toggle_or_restart(&mut self, cx: &mut Context) { @@ -164,24 +221,58 @@ impl Render for Player { window.request_animation_frame(); } + // Read per render, never cached: a delete shortens the timeline and the + // timecode, the ruler and the clamp below all have to follow it. + let duration = self.session.timeline_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 { - self.duration + duration } else { - self.session.now().clamp(0., self.duration) + self.session.now().clamp(0., duration) }; div() .track_focus(&self.focus) .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| { // `is_held` filters auto-repeat, which would otherwise toggle - // playback many times a second. - if event.keystroke.key == "space" && !event.is_held { - this.toggle_or_restart(cx); + // playback -- or cut the timeline -- many times a second. + if event.is_held { + return; + } + match event.keystroke.key.as_str() { + "space" => this.toggle_or_restart(cx), + "c" => this.cut(cx), + "x" | "delete" => this.delete_selected(cx), + "z" => this.undo(cx), + _ => {} } })) + // Scrubbing is tracked on the root because the pointer leaves the + // 6 px ruler on the first drag and its own listeners then stop + // firing; the root's hitbox is the whole window. + .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _, cx| { + if !this.scrubbing { + return; + } + if event.pressed_button == Some(MouseButton::Left) { + this.scrub_to(event.position.x, false, cx); + } else { + // A release outside the window never reaches the handler + // below, so the first button-up move is when we learn the + // drag is over. Without this the next hover would scrub. + this.scrubbing = false; + } + })) + .on_mouse_up( + MouseButton::Left, + cx.listener(|this, event: &MouseUpEvent, _, cx| { + if std::mem::take(&mut this.scrubbing) { + this.scrub_to(event.position.x, true, cx); + } + }), + ) .size_full() .flex() .flex_col() @@ -212,15 +303,21 @@ impl Render for Player { .map(|i| img(i).size_full().object_fit(gpui::ObjectFit::Contain)), ), ) - .child(self.panel(position, playing, cx)) + .child(self.panel(position, duration, playing, cx)) } } impl Player { - /// Transport, timecode, playhead and the (still empty) track lanes. - fn panel(&self, position: f64, playing: bool, cx: &mut Context) -> impl IntoElement { - let filled = if self.duration > 0. { - (position / self.duration) as f32 + /// Transport, timecode, playhead, clips lane. + fn panel( + &self, + position: f64, + duration: f64, + playing: bool, + cx: &mut Context, + ) -> impl IntoElement { + let filled = if duration > 0. { + (position / duration) as f32 } else { 0. }; @@ -238,33 +335,28 @@ impl Player { .flex() .items_center() .gap(px(12.)) - .child( - // A plain div: nothing here tracks focus, so the root's - // own mouse-down handler is what wins the click and the - // key listener keeps working after a press. - div() - .w(px(32.)) - .h(px(28.)) - .flex() - .justify_center() - .items_center() - .rounded(px(3.)) - .bg(rgb(SURFACE)) - .on_mouse_down( - MouseButton::Left, - cx.listener(|this, _: &MouseDownEvent, _, cx| { - this.toggle_or_restart(cx); - }), - ) - .child(transport_glyph(playing)), - ) + .child(control( + transport_glyph(playing), + cx.listener(|this, _: &MouseDownEvent, _, cx| { + this.toggle_or_restart(cx); + }), + )) + .child(control( + cut_glyph(), + cx.listener(|this, _: &MouseDownEvent, _, cx| this.cut(cx)), + )) + .child(control( + delete_glyph(), + cx.listener(|this, _: &MouseDownEvent, _, cx| this.delete_selected(cx)), + )) .child(div().flex_none().w(px(TIME_W)).child(format!( "{} / {}", timecode(position, self.fps), - timecode(self.duration, self.fps) + timecode(duration, self.fps) ))), ) - // Click to seek. Still not a scrubber: no drag, no hover preview. + // Press to seek, drag to scrub: the move and release halves live on + // the root, since the pointer leaves this 6 px strip immediately. .child( div() .flex_none() @@ -275,8 +367,8 @@ impl Player { .on_mouse_down( MouseButton::Left, cx.listener(|this, event: &MouseDownEvent, _, cx| { - let frac = frac_along(event.position.x, this.ruler.get()); - this.seek(f64::from(frac) * this.duration, cx); + this.scrubbing = true; + this.scrub_to(event.position.x, true, cx); }), ) .child(bounds_probe(self.ruler.clone())) @@ -288,9 +380,102 @@ impl Player { .bg(rgb(ACCENT)), ), ) + .child(self.clips_lane(duration, cx)) .child(track_lane()) - .child(track_lane()) } + + /// The edit list made visible: one box per clip, sized by its share of the + /// timeline. A cut adds a box without moving anything, a delete closes the + /// gap. Plain divs, so the root keeps focus and space still works after a + /// click (ledger:182). + fn clips_lane(&self, duration: f64, cx: &mut Context) -> impl IntoElement { + div() + .flex_none() + .h(px(LANE_H)) + .flex() + .gap(px(1.)) + .overflow_hidden() + .children( + self.session + .clip_spans() + .into_iter() + .enumerate() + .map(|(i, (_, len))| { + let selected = self.selected == Some(i); + div() + .h_full() + .w(relative(width_frac(len, duration))) + .rounded(px(3.)) + .border_1() + .border_color(rgb(if selected { ACCENT } else { SURFACE })) + .bg(rgb(if selected { SELECTED } else { SURFACE })) + .cursor_pointer() + .on_mouse_down( + MouseButton::Left, + cx.listener(move |this, _: &MouseDownEvent, _, cx| { + this.selected = Some(i); + cx.notify(); + }), + ) + }), + ) + } +} + +/// Rate limit for scrub seeks: a video worker reopen costs 72-87 ms on the +/// hardware path (215 ms in software), so one seek per mouse move would only +/// queue workers that are cancelled before they decode anything. +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 +} + +/// A clip's share of the lane. A timeline with no length reads as one full-width +/// box rather than as NaN, which gpui would carry into layout. +fn width_frac(len: f64, total: f64) -> f32 { + if total > 0. { (len / total) as f32 } else { 1. } +} + +/// The 32x28 control shape shared by transport, cut and delete. A plain div: +/// nothing here tracks focus, so the root's own key listener keeps working +/// after a press. +fn control( + glyph: impl IntoElement, + on_press: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static, +) -> impl IntoElement { + div() + .w(px(32.)) + .h(px(28.)) + .flex() + .justify_center() + .items_center() + .rounded(px(3.)) + .bg(rgb(SURFACE)) + .cursor_pointer() + .on_mouse_down(MouseButton::Left, on_press) + .child(glyph) +} + +/// A clip split in two -- the gap is the cut. Drawn, like every glyph here. +fn cut_glyph() -> impl IntoElement { + div() + .flex() + .items_center() + .gap(px(3.)) + .child(div().w(px(5.)).h(px(13.)).bg(rgb(INK))) + .child(div().w(px(5.)).h(px(13.)).bg(rgb(INK))) +} + +/// 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 @@ -311,7 +496,7 @@ fn frac_along(x: Pixels, bounds: Bounds) -> f32 { ((x - bounds.left()) / bounds.size.width).clamp(0., 1.) } -/// Placeholder chrome for the clips slice: deliberately empty. +/// The second lane: still a placeholder, deliberately empty. fn track_lane() -> impl IntoElement { div() .flex_none() @@ -370,8 +555,9 @@ fn timecode(t: f64, fps: f64) -> String { #[cfg(test)] mod tests { - use super::{frac_along, timecode}; + use super::{frac_along, scrub_due, timecode, width_frac}; use gpui::{Bounds, Pixels, point, px, size}; + use std::time::Duration; #[test] fn frac_along_measures_from_the_elements_own_left_edge() { @@ -401,6 +587,29 @@ mod tests { assert_eq!(timecode(1. - f64::EPSILON, 30.), "00:00:00:29"); assert_eq!(timecode(0.999, 29.97), "00:00:00:29"); } + + #[test] + fn scrub_seeks_only_on_a_new_frame_and_only_every_100ms() { + let (slow, fast) = (Duration::from_millis(100), Duration::from_millis(99)); + // Both halves must hold: a moved pointer that has not crossed a frame + // boundary would reopen the decoder for the same picture. + assert!(scrub_due(31, 30, slow)); + assert!(!scrub_due(30, 30, slow)); + assert!(!scrub_due(31, 30, fast)); + assert!(!scrub_due(30, 30, fast)); + // Exactly at the gap counts, and a long stall never blocks. + assert!(scrub_due(1, 0, Duration::from_secs(9))); + } + + #[test] + fn clip_boxes_split_the_lane_by_duration() { + // 1 s + 3 s of a 4 s timeline: a quarter and three quarters. + assert_eq!(width_frac(1., 4.), 0.25); + assert_eq!(width_frac(3., 4.), 0.75); + assert_eq!(width_frac(4., 4.), 1.); + // A timeline with no length must not hand gpui a NaN width. + assert_eq!(width_frac(0., 0.), 1.); + } } fn main() { @@ -444,7 +653,6 @@ fn main() { let player = cx.new(|cx| Player { session, fps: meta.frame_rate, - duration: f64::from(meta.frame_count) / meta.frame_rate, name: name.clone(), image: None, held: None, @@ -452,6 +660,10 @@ fn main() { done: false, pending_seek: false, ruler: Rc::default(), + selected: None, + scrubbing: false, + last_scrub: Instant::now(), + last_target: 0, launched: false, displayed: 0, dropped: 0,