forge
Explore
Log in

Don't you dare go Hollow

Clips lane — cut/delete/undo, drag-scrub

Browse files at this commit

5372bfda87ac86a9bd6f9ed1e72d67217730c75eAhmet Kaan GümüşParent: 7d2251c
  • feat
    • clips lane — cut/delete/undo, drag-scrub
Show full message
✨ feat(app): clips lane — cut/delete/undo, drag-scrub

- 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.rsmodified+267 -55
@@ -1,14 +1,14 @@
11 use std::cell::Cell;
22 use std::rc::Rc;
33 use std::sync::Arc;
4-use std::sync::mpsc::TryRecvError;
5-use std::time::Instant;
4+use std::time::{Duration, Instant};
65
76 use engine::{Frame, PlaybackSession};
87 use gpui::{
98 App, Application, Bounds, Context, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent,
10- PathBuilder, Pixels, RenderImage, SharedString, TitlebarOptions, Window, WindowBounds,
11- WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb, size,
9+ MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, RenderImage, SharedString, TitlebarOptions,
10+ Window, WindowBounds, WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb,
11+ size,
1212 };
1313
1414 /// Editor chrome: three grays and one accent, all darker than the picture so the
@@ -18,6 +18,8 @@ const CHROME: u32 = 0x242424;
1818 const SURFACE: u32 = 0x333333;
1919 const INK: u32 = 0xc8c8c8;
2020 const ACCENT: u32 = 0x4a9eff;
21+/// The accent at surface brightness: a selected clip is tinted, not lit up.
22+const SELECTED: u32 = 0x2a4a6b;
2123
2224 /// Fixed so the video region takes every pixel the window gains and the controls
2325 /// never clip at 640x360.
@@ -33,9 +35,6 @@ struct Player {
3335 /// Timeline seconds -> frame index, so the clock can be compared to what
3436 /// the decoder hands over.
3537 fps: f64,
36- /// `frame_count / frame_rate`: the timeline's end, and the clamp for a clock
37- /// that keeps running past it.
38- duration: f64,
3938 name: SharedString,
4039 image: Option<Arc<RenderImage>>,
4140 /// A frame that arrived before its time; shown on the tick it comes due.
@@ -50,6 +49,14 @@ struct Player {
5049 /// The ruler's own box, recorded at prepaint: a mouse listener is handed
5150 /// the window position and nothing else.
5251 ruler: Rc<Cell<Bounds<Pixels>>>,
52+ /// Which clip the edit keys act on. Indices move under every edit, so this
53+ /// is cleared by all of them.
54+ selected: Option<usize>,
55+ /// A drag that started on the ruler. Moves anywhere in the window scrub
56+ /// while it is set; the release commits the exact position.
57+ scrubbing: bool,
58+ last_scrub: Instant,
59+ last_target: u32,
5360 /// Playback was started once, on the first render. Space owns it after that.
5461 launched: bool,
5562 displayed: u32,
@@ -69,11 +76,13 @@ impl Player {
6976 loop {
7077 let frame = match self.held.take() {
7178 Some(frame) => frame,
72- None => match self.session.frames().try_recv() {
73- Ok(frame) => frame,
74- Err(TryRecvError::Empty) => break,
75- Err(TryRecvError::Disconnected) => {
76- self.eos = true;
79+ // Nothing waiting means either a clip boundary being rebuilt or
80+ // the real end of the timeline, and only the engine can tell
81+ // them apart -- `frame.index` is already a timeline index.
82+ None => match self.session.try_frame() {
83+ Some(frame) => frame,
84+ None => {
85+ self.eos = self.session.is_eos();
7786 break;
7887 }
7988 },
@@ -119,18 +128,66 @@ impl Player {
119128 }
120129 }
121130
122- /// Jumps the timeline. Every end-of-stream flag is app state and the
123- /// engine knows nothing about it, so clearing them here is what stops the
124- /// picture from staying frozen on the old last frame.
125- fn seek(&mut self, t: f64, cx: &mut Context<Self>) {
126- self.session.seek(t);
131+ /// Every end-of-stream flag is app state and the engine knows nothing about
132+ /// it, so clearing them after a reseek is what stops the picture from
133+ /// staying frozen on the old last frame. Edits reseek inside the engine and
134+ /// still owe this.
135+ fn reset_after_reseek(&mut self) {
127136 self.held = None;
128137 self.eos = false;
129138 self.done = false;
130139 self.pending_seek = true;
140+ }
141+
142+ /// Jumps the timeline.
143+ fn seek(&mut self, t: f64, cx: &mut Context<Self>) {
144+ self.session.seek(t);
145+ self.reset_after_reseek();
146+ cx.notify();
147+ }
148+
149+ /// Splits the clip under the playhead. Metadata only: the timeline->source
150+ /// mapping is unchanged, so nothing reseeks and no flag is touched.
151+ fn cut(&mut self, cx: &mut Context<Self>) {
152+ self.session.cut_at(self.session.now());
153+ self.selected = None;
154+ cx.notify();
155+ }
156+
157+ /// Drops the selected clip. The engine reseeks itself, so all this owes is
158+ /// the flag reset.
159+ fn delete_selected(&mut self, cx: &mut Context<Self>) {
160+ if self
161+ .selected
162+ .take()
163+ .is_some_and(|i| self.session.delete_clip(i))
164+ {
165+ self.reset_after_reseek();
166+ }
167+ cx.notify();
168+ }
169+
170+ fn undo(&mut self, cx: &mut Context<Self>) {
171+ if self.session.undo() {
172+ self.reset_after_reseek();
173+ }
174+ self.selected = None;
131175 cx.notify();
132176 }
133177
178+ /// Seeks to where the pointer sits along the ruler. `commit` is the press
179+ /// and the release, which must land exactly even when the throttle below
180+ /// would have skipped them.
181+ fn scrub_to(&mut self, x: Pixels, commit: bool, cx: &mut Context<Self>) {
182+ let t = f64::from(frac_along(x, self.ruler.get())) * self.session.timeline_duration();
183+ let target = (t * self.fps) as u32;
184+ if commit || scrub_due(target, self.last_target, self.last_scrub.elapsed()) {
185+ self.last_target = target;
186+ self.last_scrub = Instant::now();
187+ self.seek(t, cx);
188+ }
189+ }
190+
134191 /// Space and the transport button share it: once the timeline is finished
135192 /// the only sensible "play" is from the top.
136193 fn toggle_or_restart(&mut self, cx: &mut Context<Self>) {
@@ -164,24 +221,58 @@ impl Render for Player {
164221 window.request_animation_frame();
165222 }
166223
224+ // Read per render, never cached: a delete shortens the timeline and the
225+ // timecode, the ruler and the clamp below all have to follow it.
226+ let duration = self.session.timeline_duration();
167227 // The clock keeps running after the last frame (wall time takes over at
168228 // audio EOF) while the picture is frozen, so the timeline the UI shows is
169229 // the clamped one, pinned to the out-point once playback is done.
170230 let position = if self.done {
171- self.duration
231+ duration
172232 } else {
173- self.session.now().clamp(0., self.duration)
233+ self.session.now().clamp(0., duration)
174234 };
175235
176236 div()
177237 .track_focus(&self.focus)
178238 .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| {
179239 // `is_held` filters auto-repeat, which would otherwise toggle
180- // playback many times a second.
181- if event.keystroke.key == "space" && !event.is_held {
182- this.toggle_or_restart(cx);
240+ // playback -- or cut the timeline -- many times a second.
241+ if event.is_held {
242+ return;
243+ }
244+ match event.keystroke.key.as_str() {
245+ "space" => this.toggle_or_restart(cx),
246+ "c" => this.cut(cx),
247+ "x" | "delete" => this.delete_selected(cx),
248+ "z" => this.undo(cx),
249+ _ => {}
183250 }
184251 }))
252+ // Scrubbing is tracked on the root because the pointer leaves the
253+ // 6 px ruler on the first drag and its own listeners then stop
254+ // firing; the root's hitbox is the whole window.
255+ .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _, cx| {
256+ if !this.scrubbing {
257+ return;
258+ }
259+ if event.pressed_button == Some(MouseButton::Left) {
260+ this.scrub_to(event.position.x, false, cx);
261+ } else {
262+ // A release outside the window never reaches the handler
263+ // below, so the first button-up move is when we learn the
264+ // drag is over. Without this the next hover would scrub.
265+ this.scrubbing = false;
266+ }
267+ }))
268+ .on_mouse_up(
269+ MouseButton::Left,
270+ cx.listener(|this, event: &MouseUpEvent, _, cx| {
271+ if std::mem::take(&mut this.scrubbing) {
272+ this.scrub_to(event.position.x, true, cx);
273+ }
274+ }),
275+ )
185276 .size_full()
186277 .flex()
187278 .flex_col()
@@ -212,15 +303,21 @@ impl Render for Player {
212303 .map(|i| img(i).size_full().object_fit(gpui::ObjectFit::Contain)),
213304 ),
214305 )
215- .child(self.panel(position, playing, cx))
306+ .child(self.panel(position, duration, playing, cx))
216307 }
217308 }
218309
219310 impl Player {
220- /// Transport, timecode, playhead and the (still empty) track lanes.
221- fn panel(&self, position: f64, playing: bool, cx: &mut Context<Self>) -> impl IntoElement {
222- let filled = if self.duration > 0. {
223- (position / self.duration) as f32
311+ /// Transport, timecode, playhead, clips lane.
312+ fn panel(
313+ &self,
314+ position: f64,
315+ duration: f64,
316+ playing: bool,
317+ cx: &mut Context<Self>,
318+ ) -> impl IntoElement {
319+ let filled = if duration > 0. {
320+ (position / duration) as f32
224321 } else {
225322 0.
226323 };
@@ -238,33 +335,28 @@ impl Player {
238335 .flex()
239336 .items_center()
240337 .gap(px(12.))
241- .child(
242- // A plain div: nothing here tracks focus, so the root's
243- // own mouse-down handler is what wins the click and the
244- // key listener keeps working after a press.
245- div()
246- .w(px(32.))
247- .h(px(28.))
248- .flex()
249- .justify_center()
250- .items_center()
251- .rounded(px(3.))
252- .bg(rgb(SURFACE))
253- .on_mouse_down(
254- MouseButton::Left,
255- cx.listener(|this, _: &MouseDownEvent, _, cx| {
256- this.toggle_or_restart(cx);
257- }),
258- )
259- .child(transport_glyph(playing)),
260- )
338+ .child(control(
339+ transport_glyph(playing),
340+ cx.listener(|this, _: &MouseDownEvent, _, cx| {
341+ this.toggle_or_restart(cx);
342+ }),
343+ ))
344+ .child(control(
345+ cut_glyph(),
346+ cx.listener(|this, _: &MouseDownEvent, _, cx| this.cut(cx)),
347+ ))
348+ .child(control(
349+ delete_glyph(),
350+ cx.listener(|this, _: &MouseDownEvent, _, cx| this.delete_selected(cx)),
351+ ))
261352 .child(div().flex_none().w(px(TIME_W)).child(format!(
262353 "{} / {}",
263354 timecode(position, self.fps),
264- timecode(self.duration, self.fps)
355+ timecode(duration, self.fps)
265356 ))),
266357 )
267- // Click to seek. Still not a scrubber: no drag, no hover preview.
358+ // Press to seek, drag to scrub: the move and release halves live on
359+ // the root, since the pointer leaves this 6 px strip immediately.
268360 .child(
269361 div()
270362 .flex_none()
@@ -275,8 +367,8 @@ impl Player {
275367 .on_mouse_down(
276368 MouseButton::Left,
277369 cx.listener(|this, event: &MouseDownEvent, _, cx| {
278- let frac = frac_along(event.position.x, this.ruler.get());
279- this.seek(f64::from(frac) * this.duration, cx);
370+ this.scrubbing = true;
371+ this.scrub_to(event.position.x, true, cx);
280372 }),
281373 )
282374 .child(bounds_probe(self.ruler.clone()))
@@ -288,9 +380,102 @@ impl Player {
288380 .bg(rgb(ACCENT)),
289381 ),
290382 )
383+ .child(self.clips_lane(duration, cx))
291384 .child(track_lane())
292- .child(track_lane())
293385 }
386+
387+ /// The edit list made visible: one box per clip, sized by its share of the
388+ /// timeline. A cut adds a box without moving anything, a delete closes the
389+ /// gap. Plain divs, so the root keeps focus and space still works after a
390+ /// click (ledger:182).
391+ fn clips_lane(&self, duration: f64, cx: &mut Context<Self>) -> impl IntoElement {
392+ div()
393+ .flex_none()
394+ .h(px(LANE_H))
395+ .flex()
396+ .gap(px(1.))
397+ .overflow_hidden()
398+ .children(
399+ self.session
400+ .clip_spans()
401+ .into_iter()
402+ .enumerate()
403+ .map(|(i, (_, len))| {
404+ let selected = self.selected == Some(i);
405+ div()
406+ .h_full()
407+ .w(relative(width_frac(len, duration)))
408+ .rounded(px(3.))
409+ .border_1()
410+ .border_color(rgb(if selected { ACCENT } else { SURFACE }))
411+ .bg(rgb(if selected { SELECTED } else { SURFACE }))
412+ .cursor_pointer()
413+ .on_mouse_down(
414+ MouseButton::Left,
415+ cx.listener(move |this, _: &MouseDownEvent, _, cx| {
416+ this.selected = Some(i);
417+ cx.notify();
418+ }),
419+ )
420+ }),
421+ )
422+ }
423+}
424+
425+/// Rate limit for scrub seeks: a video worker reopen costs 72-87 ms on the
426+/// hardware path (215 ms in software), so one seek per mouse move would only
427+/// queue workers that are cancelled before they decode anything.
428+const SCRUB_GAP: Duration = Duration::from_millis(100);
429+
430+fn scrub_due(target: u32, last_target: u32, since: Duration) -> bool {
431+ target != last_target && since >= SCRUB_GAP
432+}
433+
434+/// A clip's share of the lane. A timeline with no length reads as one full-width
435+/// box rather than as NaN, which gpui would carry into layout.
436+fn width_frac(len: f64, total: f64) -> f32 {
437+ if total > 0. { (len / total) as f32 } else { 1. }
438+}
439+
440+/// The 32x28 control shape shared by transport, cut and delete. A plain div:
441+/// nothing here tracks focus, so the root's own key listener keeps working
442+/// after a press.
443+fn control(
444+ glyph: impl IntoElement,
445+ on_press: impl Fn(&MouseDownEvent, &mut Window, &mut App) + 'static,
446+) -> impl IntoElement {
447+ div()
448+ .w(px(32.))
449+ .h(px(28.))
450+ .flex()
451+ .justify_center()
452+ .items_center()
453+ .rounded(px(3.))
454+ .bg(rgb(SURFACE))
455+ .cursor_pointer()
456+ .on_mouse_down(MouseButton::Left, on_press)
457+ .child(glyph)
458+}
459+
460+/// A clip split in two -- the gap is the cut. Drawn, like every glyph here.
461+fn cut_glyph() -> impl IntoElement {
462+ div()
463+ .flex()
464+ .items_center()
465+ .gap(px(3.))
466+ .child(div().w(px(5.)).h(px(13.)).bg(rgb(INK)))
467+ .child(div().w(px(5.)).h(px(13.)).bg(rgb(INK)))
468+}
469+
470+/// A lid over a bin.
471+fn delete_glyph() -> impl IntoElement {
472+ div()
473+ .flex()
474+ .flex_col()
475+ .items_center()
476+ .gap(px(2.))
477+ .child(div().w(px(13.)).h(px(2.)).bg(rgb(INK)))
478+ .child(div().w(px(9.)).h(px(9.)).bg(rgb(INK)))
294479 }
295480
296481 /// 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<Pixels>) -> f32 {
311496 ((x - bounds.left()) / bounds.size.width).clamp(0., 1.)
312497 }
313498
314-/// Placeholder chrome for the clips slice: deliberately empty.
499+/// The second lane: still a placeholder, deliberately empty.
315500 fn track_lane() -> impl IntoElement {
316501 div()
317502 .flex_none()
@@ -370,8 +555,9 @@ fn timecode(t: f64, fps: f64) -> String {
370555
371556 #[cfg(test)]
372557 mod tests {
373- use super::{frac_along, timecode};
558+ use super::{frac_along, scrub_due, timecode, width_frac};
374559 use gpui::{Bounds, Pixels, point, px, size};
560+ use std::time::Duration;
375561
376562 #[test]
377563 fn frac_along_measures_from_the_elements_own_left_edge() {
@@ -401,6 +587,29 @@ mod tests {
401587 assert_eq!(timecode(1. - f64::EPSILON, 30.), "00:00:00:29");
402588 assert_eq!(timecode(0.999, 29.97), "00:00:00:29");
403589 }
590+
591+ #[test]
592+ fn scrub_seeks_only_on_a_new_frame_and_only_every_100ms() {
593+ let (slow, fast) = (Duration::from_millis(100), Duration::from_millis(99));
594+ // Both halves must hold: a moved pointer that has not crossed a frame
595+ // boundary would reopen the decoder for the same picture.
596+ assert!(scrub_due(31, 30, slow));
597+ assert!(!scrub_due(30, 30, slow));
598+ assert!(!scrub_due(31, 30, fast));
599+ assert!(!scrub_due(30, 30, fast));
600+ // Exactly at the gap counts, and a long stall never blocks.
601+ assert!(scrub_due(1, 0, Duration::from_secs(9)));
602+ }
603+
604+ #[test]
605+ fn clip_boxes_split_the_lane_by_duration() {
606+ // 1 s + 3 s of a 4 s timeline: a quarter and three quarters.
607+ assert_eq!(width_frac(1., 4.), 0.25);
608+ assert_eq!(width_frac(3., 4.), 0.75);
609+ assert_eq!(width_frac(4., 4.), 1.);
610+ // A timeline with no length must not hand gpui a NaN width.
611+ assert_eq!(width_frac(0., 0.), 1.);
612+ }
404613 }
405614
406615 fn main() {
@@ -444,7 +653,6 @@ fn main() {
444653 let player = cx.new(|cx| Player {
445654 session,
446655 fps: meta.frame_rate,
447- duration: f64::from(meta.frame_count) / meta.frame_rate,
448656 name: name.clone(),
449657 image: None,
450658 held: None,
@@ -452,6 +660,10 @@ fn main() {
452660 done: false,
453661 pending_seek: false,
454662 ruler: Rc::default(),
663+ selected: None,
664+ scrubbing: false,
665+ last_scrub: Instant::now(),
666+ last_target: 0,
455667 launched: false,
456668 displayed: 0,
457669 dropped: 0,