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 @@
1 use std::cell::Cell;1 use std::cell::Cell;
2 use std::rc::Rc;2 use std::rc::Rc;
3 use std::sync::Arc;3 use std::sync::Arc;
4-use std::sync::mpsc::TryRecvError;4+use std::time::{Duration, Instant};
5-use std::time::Instant;
6 5
7 use engine::{Frame, PlaybackSession};6 use engine::{Frame, PlaybackSession};
8 use gpui::{7 use gpui::{
9 App, Application, Bounds, Context, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent,8 App, Application, Bounds, Context, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent,
10- PathBuilder, Pixels, RenderImage, SharedString, TitlebarOptions, Window, WindowBounds,9+ MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, RenderImage, SharedString, TitlebarOptions,
11- WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb, size,10+ Window, WindowBounds, WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb,
11+ size,
12 };12 };
13 13
14 /// Editor chrome: three grays and one accent, all darker than the picture so the14 /// Editor chrome: three grays and one accent, all darker than the picture so the
@@ -18,6 +18,8 @@ const CHROME: u32 = 0x242424;
18 const SURFACE: u32 = 0x333333;18 const SURFACE: u32 = 0x333333;
19 const INK: u32 = 0xc8c8c8;19 const INK: u32 = 0xc8c8c8;
20 const ACCENT: u32 = 0x4a9eff;20 const ACCENT: u32 = 0x4a9eff;
21+/// The accent at surface brightness: a selected clip is tinted, not lit up.
22+const SELECTED: u32 = 0x2a4a6b;
21 23
22 /// Fixed so the video region takes every pixel the window gains and the controls24 /// Fixed so the video region takes every pixel the window gains and the controls
23 /// never clip at 640x360.25 /// never clip at 640x360.
@@ -33,9 +35,6 @@ struct Player {
33 /// Timeline seconds -> frame index, so the clock can be compared to what35 /// Timeline seconds -> frame index, so the clock can be compared to what
34 /// the decoder hands over.36 /// the decoder hands over.
35 fps: f64,37 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,
39 name: SharedString,38 name: SharedString,
40 image: Option<Arc<RenderImage>>,39 image: Option<Arc<RenderImage>>,
41 /// A frame that arrived before its time; shown on the tick it comes due.40 /// A frame that arrived before its time; shown on the tick it comes due.
@@ -50,6 +49,14 @@ struct Player {
50 /// The ruler's own box, recorded at prepaint: a mouse listener is handed49 /// The ruler's own box, recorded at prepaint: a mouse listener is handed
51 /// the window position and nothing else.50 /// the window position and nothing else.
52 ruler: Rc<Cell<Bounds<Pixels>>>,51 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,
53 /// Playback was started once, on the first render. Space owns it after that.60 /// Playback was started once, on the first render. Space owns it after that.
54 launched: bool,61 launched: bool,
55 displayed: u32,62 displayed: u32,
@@ -69,11 +76,13 @@ impl Player {
69 loop {76 loop {
70 let frame = match self.held.take() {77 let frame = match self.held.take() {
71 Some(frame) => frame,78 Some(frame) => frame,
72- None => match self.session.frames().try_recv() {79+ // Nothing waiting means either a clip boundary being rebuilt or
73- Ok(frame) => frame,80+ // the real end of the timeline, and only the engine can tell
74- Err(TryRecvError::Empty) => break,81+ // them apart -- `frame.index` is already a timeline index.
75- Err(TryRecvError::Disconnected) => {82+ None => match self.session.try_frame() {
76- self.eos = true;83+ Some(frame) => frame,
84+ None => {
85+ self.eos = self.session.is_eos();
77 break;86 break;
78 }87 }
79 },88 },
@@ -119,18 +128,66 @@ impl Player {
119 }128 }
120 }129 }
121 130
122- /// Jumps the timeline. Every end-of-stream flag is app state and the131+ /// Every end-of-stream flag is app state and the engine knows nothing about
123- /// engine knows nothing about it, so clearing them here is what stops the132+ /// it, so clearing them after a reseek is what stops the picture from
124- /// picture from staying frozen on the old last frame.133+ /// staying frozen on the old last frame. Edits reseek inside the engine and
125- fn seek(&mut self, t: f64, cx: &mut Context<Self>) {134+ /// still owe this.
126- self.session.seek(t);135+ fn reset_after_reseek(&mut self) {
127 self.held = None;136 self.held = None;
128 self.eos = false;137 self.eos = false;
129 self.done = false;138 self.done = false;
130 self.pending_seek = true;139 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;
131 cx.notify();175 cx.notify();
132 }176 }
133 177
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+
134 /// Space and the transport button share it: once the timeline is finished191 /// Space and the transport button share it: once the timeline is finished
135 /// the only sensible "play" is from the top.192 /// the only sensible "play" is from the top.
136 fn toggle_or_restart(&mut self, cx: &mut Context<Self>) {193 fn toggle_or_restart(&mut self, cx: &mut Context<Self>) {
@@ -164,24 +221,58 @@ impl Render for Player {
164 window.request_animation_frame();221 window.request_animation_frame();
165 }222 }
166 223
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();
167 // The clock keeps running after the last frame (wall time takes over at227 // The clock keeps running after the last frame (wall time takes over at
168 // audio EOF) while the picture is frozen, so the timeline the UI shows is228 // audio EOF) while the picture is frozen, so the timeline the UI shows is
169 // the clamped one, pinned to the out-point once playback is done.229 // the clamped one, pinned to the out-point once playback is done.
170 let position = if self.done {230 let position = if self.done {
171- self.duration231+ duration
172 } else {232 } else {
173- self.session.now().clamp(0., self.duration)233+ self.session.now().clamp(0., duration)
174 };234 };
175 235
176 div()236 div()
177 .track_focus(&self.focus)237 .track_focus(&self.focus)
178 .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| {238 .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| {
179 // `is_held` filters auto-repeat, which would otherwise toggle239 // `is_held` filters auto-repeat, which would otherwise toggle
180- // playback many times a second.240+ // playback -- or cut the timeline -- many times a second.
181- if event.keystroke.key == "space" && !event.is_held {241+ if event.is_held {
182- this.toggle_or_restart(cx);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+ _ => {}
183 }250 }
184 }))251 }))
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+ )
185 .size_full()276 .size_full()
186 .flex()277 .flex()
187 .flex_col()278 .flex_col()
@@ -212,15 +303,21 @@ impl Render for Player {
212 .map(|i| img(i).size_full().object_fit(gpui::ObjectFit::Contain)),303 .map(|i| img(i).size_full().object_fit(gpui::ObjectFit::Contain)),
213 ),304 ),
214 )305 )
215- .child(self.panel(position, playing, cx))306+ .child(self.panel(position, duration, playing, cx))
216 }307 }
217 }308 }
218 309
219 impl Player {310 impl Player {
220- /// Transport, timecode, playhead and the (still empty) track lanes.311+ /// Transport, timecode, playhead, clips lane.
221- fn panel(&self, position: f64, playing: bool, cx: &mut Context<Self>) -> impl IntoElement {312+ fn panel(
222- let filled = if self.duration > 0. {313+ &self,
223- (position / self.duration) as f32314+ 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
224 } else {321 } else {
225 0.322 0.
226 };323 };
@@ -238,33 +335,28 @@ impl Player {
238 .flex()335 .flex()
239 .items_center()336 .items_center()
240 .gap(px(12.))337 .gap(px(12.))
241- .child(338+ .child(control(
242- // A plain div: nothing here tracks focus, so the root's339+ transport_glyph(playing),
243- // own mouse-down handler is what wins the click and the340+ cx.listener(|this, _: &MouseDownEvent, _, cx| {
244- // key listener keeps working after a press.341+ this.toggle_or_restart(cx);
245- div()342+ }),
246- .w(px(32.))343+ ))
247- .h(px(28.))344+ .child(control(
248- .flex()345+ cut_glyph(),
249- .justify_center()346+ cx.listener(|this, _: &MouseDownEvent, _, cx| this.cut(cx)),
250- .items_center()347+ ))
251- .rounded(px(3.))348+ .child(control(
252- .bg(rgb(SURFACE))349+ delete_glyph(),
253- .on_mouse_down(350+ cx.listener(|this, _: &MouseDownEvent, _, cx| this.delete_selected(cx)),
254- MouseButton::Left,351+ ))
255- cx.listener(|this, _: &MouseDownEvent, _, cx| {
256- this.toggle_or_restart(cx);
257- }),
258- )
259- .child(transport_glyph(playing)),
260- )
261 .child(div().flex_none().w(px(TIME_W)).child(format!(352 .child(div().flex_none().w(px(TIME_W)).child(format!(
262 "{} / {}",353 "{} / {}",
263 timecode(position, self.fps),354 timecode(position, self.fps),
264- timecode(self.duration, self.fps)355+ timecode(duration, self.fps)
265 ))),356 ))),
266 )357 )
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.
268 .child(360 .child(
269 div()361 div()
270 .flex_none()362 .flex_none()
@@ -275,8 +367,8 @@ impl Player {
275 .on_mouse_down(367 .on_mouse_down(
276 MouseButton::Left,368 MouseButton::Left,
277 cx.listener(|this, event: &MouseDownEvent, _, cx| {369 cx.listener(|this, event: &MouseDownEvent, _, cx| {
278- let frac = frac_along(event.position.x, this.ruler.get());370+ this.scrubbing = true;
279- this.seek(f64::from(frac) * this.duration, cx);371+ this.scrub_to(event.position.x, true, cx);
280 }),372 }),
281 )373 )
282 .child(bounds_probe(self.ruler.clone()))374 .child(bounds_probe(self.ruler.clone()))
@@ -288,9 +380,102 @@ impl Player {
288 .bg(rgb(ACCENT)),380 .bg(rgb(ACCENT)),
289 ),381 ),
290 )382 )
383+ .child(self.clips_lane(duration, cx))
291 .child(track_lane())384 .child(track_lane())
292- .child(track_lane())
293 }385 }
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)))
294 }479 }
295 480
296 /// Records its parent's laid-out box: gpui hands a mouse listener the window481 /// 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 {
311 ((x - bounds.left()) / bounds.size.width).clamp(0., 1.)496 ((x - bounds.left()) / bounds.size.width).clamp(0., 1.)
312 }497 }
313 498
314-/// Placeholder chrome for the clips slice: deliberately empty.499+/// The second lane: still a placeholder, deliberately empty.
315 fn track_lane() -> impl IntoElement {500 fn track_lane() -> impl IntoElement {
316 div()501 div()
317 .flex_none()502 .flex_none()
@@ -370,8 +555,9 @@ fn timecode(t: f64, fps: f64) -> String {
370 555
371 #[cfg(test)]556 #[cfg(test)]
372 mod tests {557 mod tests {
373- use super::{frac_along, timecode};558+ use super::{frac_along, scrub_due, timecode, width_frac};
374 use gpui::{Bounds, Pixels, point, px, size};559 use gpui::{Bounds, Pixels, point, px, size};
560+ use std::time::Duration;
375 561
376 #[test]562 #[test]
377 fn frac_along_measures_from_the_elements_own_left_edge() {563 fn frac_along_measures_from_the_elements_own_left_edge() {
@@ -401,6 +587,29 @@ mod tests {
401 assert_eq!(timecode(1. - f64::EPSILON, 30.), "00:00:00:29");587 assert_eq!(timecode(1. - f64::EPSILON, 30.), "00:00:00:29");
402 assert_eq!(timecode(0.999, 29.97), "00:00:00:29");588 assert_eq!(timecode(0.999, 29.97), "00:00:00:29");
403 }589 }
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+ }
404 }613 }
405 614
406 fn main() {615 fn main() {
@@ -444,7 +653,6 @@ fn main() {
444 let player = cx.new(|cx| Player {653 let player = cx.new(|cx| Player {
445 session,654 session,
446 fps: meta.frame_rate,655 fps: meta.frame_rate,
447- duration: f64::from(meta.frame_count) / meta.frame_rate,
448 name: name.clone(),656 name: name.clone(),
449 image: None,657 image: None,
450 held: None,658 held: None,
@@ -452,6 +660,10 @@ fn main() {
452 done: false,660 done: false,
453 pending_seek: false,661 pending_seek: false,
454 ruler: Rc::default(),662 ruler: Rc::default(),
663+ selected: None,
664+ scrubbing: false,
665+ last_scrub: Instant::now(),
666+ last_target: 0,
455 launched: false,667 launched: false,
456 displayed: 0,668 displayed: 0,
457 dropped: 0,669 dropped: 0,