forge
Explore
Log in

Don't you dare go Hollow

🔀 merge(main): detach and group beside the colour drag and the edge trim

Browse files at this commit

7cce619aca6e11e7c63e669d9a6fde23ebf7dc44Ahmet Kaan GümüşParent: 0c00d5cdcd2d0f
The one conflict is the test module's import list: both sides added names to
it, so the resolution is the union of the two.
crates/app/src/main.rsmodified+661 -73
@@ -13,12 +13,13 @@ use engine::audio::StreamInfo;
13 use engine::color::ColorParams;13 use engine::color::ColorParams;
14 use engine::eq::{Band, BandKind, EqParams};14 use engine::eq::{Band, BandKind, EqParams};
15 use engine::export::{ExportSettings, Format};15 use engine::export::{ExportSettings, Format};
16-use engine::project::{Lane, LaneKind, Source};16+use engine::project::{Edge, Lane, LaneKind, Source};
17 use engine::scale::FitPolicy;17 use engine::scale::FitPolicy;
18 use engine::{Clip, ExportHandle, Frame, PlaybackSession};18 use engine::{Clip, ExportHandle, Frame, PlaybackSession};
19 use gpui::{19 use gpui::{
20- AnyElement, App, Application, Bounds, ClickEvent, Context, Div, FocusHandle, KeyDownEvent,20+ AnyElement, App, Application, Bounds, ClickEvent, Context, CursorStyle, Div, FocusHandle,
21- MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, Point,21+ KeyDownEvent, MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels,
22+ Point,
22 RenderImage, SharedString, Size, Stateful, TextAlign, TitlebarOptions, Window, WindowBounds,23 RenderImage, SharedString, Size, Stateful, TextAlign, TitlebarOptions, Window, WindowBounds,
23 WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb, rgba, size,24 WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb, rgba, size,
24 };25 };
@@ -216,6 +217,31 @@ struct ClipDrag {
216 idx: usize,217 idx: usize,
217 }218 }
218 219
220+/// A clip edge being dragged: which end of which clip, and the timeline frame
221+/// the pointer has pulled it to. The box on screen is drawn from `to` while this
222+/// is set and the engine hears about it once, at the release
223+/// ([`Player::commit_trim`]) -- one edit, one undo step for the whole gesture,
224+/// exactly as an equalizer drag works.
225+#[derive(Clone, Copy)]
226+struct Trim {
227+ lane: Lane,
228+ idx: usize,
229+ edge: Edge,
230+ /// Already clamped by `PlaybackSession::trim_room`, so the width drawn from
231+ /// it is the width the release commits -- an edge stops under the pointer
232+ /// rather than snapping back after the fact.
233+ to: u32,
234+ /// The dragged clip's group, so its other halves' boxes follow the edge on
235+ /// screen exactly as the engine will move them.
236+ link: Option<u32>,
237+}
238+
239+/// How wide a clip's edge is as a *target*: the strip at each end where a press
240+/// means "make this longer or shorter" instead of "move this to another lane".
241+/// Wide enough to hit, narrow enough that the middle of even a small box is
242+/// still the body.
243+const EDGE_W: f32 = 6.;
244+
219 /// An open clip menu: which clip it was opened on, where it hangs, and whether245 /// An open clip menu: which clip it was opened on, where it hangs, and whether
220 /// it has been turned over to show what that clip *is* instead of what can be246 /// it has been turned over to show what that clip *is* instead of what can be
221 /// done to it. The lane and index are the ones the same click selected, so247 /// done to it. The lane and index are the ones the same click selected, so
@@ -298,16 +324,37 @@ const COLOR_BANDS: [(&str, f32, f32); 4] = [
298 ("Tint (cool–warm)", -1., 1.),324 ("Tint (cool–warm)", -1., 1.),
299 ];325 ];
300 326
301-/// A press of a nudge key or button: a fortieth of a band's range, so a slider327+/// A press of a nudge key: a fortieth of a band's range, so a slider crosses it
302-/// crosses it in forty presses and every stop is a number the file can write.328+/// in forty presses and every stop is a number the file can write. A drag lands
329+/// on the same grid ([`Player::drag_color`]), so the pointer and the keyboard
330+/// cannot reach two different sets of values.
303 const COLOR_STEP: f32 = 0.05;331 const COLOR_STEP: f32 = 0.05;
304 332
305-/// The card's width: a slider row is a label, two buttons, the bar and the333+/// The card's width: a slider row is a label, the bar and the value, and the
306-/// value, and the longest label has to fit beside all four without truncating334+/// longest label has to fit beside all three without truncating (measured
307-/// (measured against "Tint (cool–warm)" at 460).335+/// against "Tint (cool–warm)").
308 const COLOR_W: f32 = 460.;336 const COLOR_W: f32 = 460.;
309-/// How much of a slider row the bar itself gets.337+/// How much of a slider row the bar itself gets -- what a drag is read against,
310-const COLOR_BAR_W: f32 = 140.;338+/// so it takes the width the two nudge buttons used to.
339+const COLOR_BAR_W: f32 = 240.;
340+
341+/// The histogram's bins per channel. 64 is four codes of an 8-bit ramp per bin:
342+/// fine enough to see a grade tilt, coarse enough that a subsampled count is
343+/// not noise.
344+const HIST_BINS: usize = 64;
345+
346+/// How many pixels of a frame the histogram reads. The stride is
347+/// `pixels / HIST_SAMPLES` (1920x1080 -> every 253rd pixel), which is a
348+/// thousandth of the frame and walks across columns rather than down one.
349+const HIST_SAMPLES: usize = 8_192;
350+
351+/// The histogram box. Shorter than the equalizer's curve because four slider
352+/// rows stand under it and the card still has to fit a 360 px window.
353+const HIST_H: f32 = 96.;
354+
355+/// What each channel's line is drawn in, in `[r, g, b]` order -- the channel it
356+/// counts, lightened enough to read on the dark box.
357+const HIST_INK: [u32; 3] = [0xE0_5A_5A, 0x5A_D0_7A, 0x5A_9A_E0];
311 358
312 struct Player {359 struct Player {
313 /// The timeline, once there is one. A run with no file opens without it and360 /// The timeline, once there is one. A run with no file opens without it and
@@ -361,6 +408,10 @@ struct Player {
361 /// A drag that started on the ruler. Moves anywhere in the window scrub408 /// A drag that started on the ruler. Moves anywhere in the window scrub
362 /// while it is set; the release commits the exact position.409 /// while it is set; the release commits the exact position.
363 scrubbing: bool,410 scrubbing: bool,
411+ /// A drag that started on a clip's edge, tracked on the root for
412+ /// `scrubbing`'s reason: a 6 px strip is not where the pointer stays. See
413+ /// [`Trim`].
414+ trim: Option<Trim>,
364 last_scrub: Instant,415 last_scrub: Instant,
365 last_target: u32,416 last_target: u32,
366 /// The running export. While it owns the UI the editor is read-only.417 /// The running export. While it owns the UI the editor is read-only.
@@ -428,9 +479,24 @@ struct Player {
428 /// there. `None` when it is closed, which is the only place that state479 /// there. `None` when it is closed, which is the only place that state
429 /// lives: the grade itself is the project's.480 /// lives: the grade itself is the project's.
430 color_open: Option<(Lane, usize)>,481 color_open: Option<(Lane, usize)>,
431- /// Which of the card's four sliders the arrow keys and the buttons move.482+ /// Which of the card's four sliders the arrow keys and a drag move. The
432- /// The card's own focus, since nothing in it takes gpui's (ledger:182).483+ /// card's own focus, since nothing in it takes gpui's (ledger:182).
433 color_band: usize,484 color_band: usize,
485+ /// A slider is being dragged. Tracked on the root like `scrubbing` and the
486+ /// equalizer's drag, for the same reason: a 4 px bar is left by the pointer
487+ /// on the first move and its own listeners then stop firing.
488+ color_dragging: bool,
489+ /// Each slider's box, recorded at prepaint: a mouse listener is handed the
490+ /// window position only, so this is what a press and a drag are read against
491+ /// ([`frac_along`]). One per band, because the press picks the row it landed
492+ /// on and the drag then belongs to that row's range.
493+ color_bars: [Rc<Cell<Bounds<Pixels>>>; COLOR_BANDS.len()],
494+ /// The frame on screen counted into `HIST_BINS` bins per channel -- the
495+ /// *graded* frame, because the grade is applied in the decode worker and
496+ /// what arrives here is already through it. Refilled by every pumped frame,
497+ /// which is what makes the colour card's graph move as a slider is dragged:
498+ /// each live write reseeks, and the reseek's frame is the next count.
499+ histogram: [[u32; HIST_BINS]; 3],
434 /// The action whose row is waiting for a stroke. The next key that is500 /// The action whose row is waiting for a stroke. The next key that is
435 /// neither escape nor a lone modifier becomes the whole of what reaches it.501 /// neither escape nor a lone modifier becomes the whole of what reaches it.
436 rebinding: Option<ActionId>,502 rebinding: Option<ActionId>,
@@ -497,6 +563,12 @@ impl Player {
497 });563 });
498 let buf = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra)564 let buf = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra)
499 .expect("frame buffer sized width*height*4");565 .expect("frame buffer sized width*height*4");
566+ // Counted here rather than under `color_open`, because the card
567+ // opens on a frame that was pumped before it: gating this on the
568+ // card would leave its graph flat until something reseeked. A
569+ // thousandth of the pixels, against a conversion that just touched
570+ // all of them.
571+ self.histogram = histogram(buf.as_raw());
500 let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)]));572 let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)]));
501 if let Some(old) = self.image.replace(next) {573 if let Some(old) = self.image.replace(next) {
502 // Every RenderImage gets a fresh id and its own atlas tile:574 // Every RenderImage gets a fresh id and its own atlas tile:
@@ -529,6 +601,11 @@ impl Player {
529 self.eos = false;601 self.eos = false;
530 self.done = false;602 self.done = false;
531 self.pending_seek = true;603 self.pending_seek = true;
604+ // An edit moves the indices a drag in flight is holding -- a stroke
605+ // during one is exactly that -- and an edge committed against a moved
606+ // index would trim a clip nobody grabbed. Dropping it is the whole fix:
607+ // nothing has been written yet.
608+ self.trim = None;
532 }609 }
533 610
534 /// What an action does, wherever it was asked for -- a stroke, or the clip611 /// What an action does, wherever it was asked for -- a stroke, or the clip
@@ -722,6 +799,7 @@ impl Player {
722 Some(clip) => {799 Some(clip) => {
723 self.color_open = Some(clip);800 self.color_open = Some(clip);
724 self.color_band = 0;801 self.color_band = 0;
802+ self.color_dragging = false;
725 // One card at a time, the rule both the others already follow.803 // One card at a time, the rule both the others already follow.
726 self.keys_open = false;804 self.keys_open = false;
727 self.export_open = false;805 self.export_open = false;
@@ -748,6 +826,14 @@ impl Player {
748 /// frame on screen repaints through the new grade; this only owes the flags826 /// frame on screen repaints through the new grade; this only owes the flags
749 /// that reseek clears.827 /// that reseek clears.
750 fn set_color(&mut self, params: ColorParams, cx: &mut Context<Self>) {828 fn set_color(&mut self, params: ColorParams, cx: &mut Context<Self>) {
829+ self.write_color(params, false, cx);
830+ }
831+
832+ /// Both writes: `live` is the one that takes no undo step, which is what
833+ /// every sample *inside* a drag goes through
834+ /// (`PlaybackSession::set_color_live`). Either way the engine reseeks, so
835+ /// the picture -- and the histogram counted off it -- is regraded at once.
836+ fn write_color(&mut self, params: ColorParams, live: bool, cx: &mut Context<Self>) {
751 let Some((lane, idx)) = self.color_open else {837 let Some((lane, idx)) = self.color_open else {
752 return;838 return;
753 };839 };
@@ -755,7 +841,11 @@ impl Player {
755 return;841 return;
756 };842 };
757 let grade = Some(params).filter(|p| !p.is_identity());843 let grade = Some(params).filter(|p| !p.is_identity());
758- if session.set_color(lane, idx, grade) {844+ let took = match live {
845+ true => session.set_color_live(lane, idx, grade),
846+ false => session.set_color(lane, idx, grade),
847+ };
848+ if took {
759 self.reset_after_reseek();849 self.reset_after_reseek();
760 }850 }
761 cx.notify();851 cx.notify();
@@ -771,6 +861,35 @@ impl Player {
771 self.set_color(params, cx);861 self.set_color(params, cx);
772 }862 }
773 863
864+ /// Where the pointer sits along a slider, as that band's value: the left end
865+ /// of the bar is the bottom of its range and the right end the top. Called
866+ /// on every pointer sample, so the grade -- and the picture, and the
867+ /// histogram over it -- moves under the hand.
868+ ///
869+ /// `first` is the press: it takes the undo step the whole gesture rolls back
870+ /// to, and every sample after it is live. That is why it writes even when
871+ /// the value did not change -- without that snapshot the rest of the drag
872+ /// would be unundoable.
873+ ///
874+ /// Values land on the [`COLOR_STEP`] grid the keys use, which also bounds
875+ /// one drag to forty-odd entries in the project's colour table.
876+ ///
877+ /// ponytail: one reseek per step crossed, up to ~40 for a bar-wide sweep. If
878+ /// that ever stutters, the throttle is [`scrub_due`]'s, which the ruler drag
879+ /// already uses for the same cost.
880+ fn drag_color(&mut self, x: Pixels, first: bool, cx: &mut Context<Self>) {
881+ let (_, low, high) = COLOR_BANDS[self.color_band];
882+ let along = frac_along(x, self.color_bars[self.color_band].get());
883+ let value = color_snap(low + along * (high - low)).clamp(low, high);
884+ let mut params = self.color_params();
885+ let at = band_mut(&mut params, self.color_band);
886+ if *at == value && !first {
887+ return;
888+ }
889+ *at = value;
890+ self.write_color(params, !first, cx);
891+ }
892+
774 /// Whether a card owns the window. While one does the timeline under it is893 /// Whether a card owns the window. While one does the timeline under it is
775 /// out of reach, so a right-click there opens no menu -- the same rule the894 /// out of reach, so a right-click there opens no menu -- the same rule the
776 /// key handler and the drop target already follow.895 /// key handler and the drop target already follow.
@@ -1229,6 +1348,135 @@ impl Player {
1229 cx.notify();1348 cx.notify();
1230 }1349 }
1231 1350
1351+ /// Opens the clip menu on the box under the pointer, from the right button
1352+ /// wherever it was pressed on that box -- its middle or one of its edge
1353+ /// strips, which cover the middle's own listener. Selecting first is part of
1354+ /// it: every item acts on the clip the menu names.
1355+ fn open_menu(&mut self, lane: Lane, idx: usize, at: Point<Pixels>, cx: &mut Context<Self>) {
1356+ if self.modal() {
1357+ return;
1358+ }
1359+ self.select((lane, idx), cx);
1360+ self.context_menu = Some(ContextMenu {
1361+ lane,
1362+ idx,
1363+ at,
1364+ details: false,
1365+ });
1366+ cx.notify();
1367+ }
1368+
1369+ /// A press on a clip's edge: the start of the drag that changes how much of
1370+ /// its source it plays. It selects the clip as a press anywhere else on the
1371+ /// box does -- the edge strip covers the box's own listener (`occlude`), so
1372+ /// this is the only one that fires there.
1373+ fn start_trim(&mut self, lane: Lane, idx: usize, edge: Edge, cx: &mut Context<Self>) {
1374+ if self.modal() || self.exporting().is_some() {
1375+ return;
1376+ }
1377+ let Some(clip) = self
1378+ .session
1379+ .as_ref()
1380+ .and_then(|session| session.lane_clips(lane).get(idx).copied())
1381+ else {
1382+ return;
1383+ };
1384+ self.select((lane, idx), cx);
1385+ self.trim = Some(Trim {
1386+ lane,
1387+ idx,
1388+ edge,
1389+ // Where the edge already is: a press that never moves is not an
1390+ // edit, and `Project::trim` refuses exactly that.
1391+ to: match edge {
1392+ Edge::Start => clip.start,
1393+ Edge::End => clip.end(),
1394+ },
1395+ link: clip.link,
1396+ });
1397+ cx.notify();
1398+ }
1399+
1400+ /// Where the pointer has pulled the edge to, clamped to the room the engine
1401+ /// says that edge has. Along the same bed the ruler is measured on and
1402+ /// against the same duration the boxes are drawn to, so the edge tracks the
1403+ /// pointer exactly.
1404+ fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) {
1405+ let (duration, fps) = (self.drawn_duration(), self.fps);
1406+ let frac = frac_along(x, self.ruler.get());
1407+ let (Some(trim), Some(session)) = (&mut self.trim, &self.session) else {
1408+ return;
1409+ };
1410+ let Some((lo, hi)) = session.trim_room(trim.lane, trim.idx, trim.edge) else {
1411+ return;
1412+ };
1413+ trim.to = frame_at(f64::from(frac) * duration, fps).clamp(lo, hi);
1414+ cx.notify();
1415+ }
1416+
1417+ /// The release: the whole drag reaches the engine as one edit, so it is one
1418+ /// undo step. The selection survives it -- a trim inserts and removes
1419+ /// nothing, so every index a lane had still names the clip it named.
1420+ fn commit_trim(&mut self, cx: &mut Context<Self>) {
1421+ let Some(trim) = self.trim.take() else {
1422+ return;
1423+ };
1424+ let trimmed = self
1425+ .session
1426+ .as_mut()
1427+ .is_some_and(|session| session.trim_clip(trim.lane, trim.idx, trim.edge, trim.to));
1428+ if trimmed {
1429+ self.reset_after_reseek();
1430+ }
1431+ cx.notify();
1432+ }
1433+
1434+ /// The clip as the drag is showing it: an edge under the pointer moves its
1435+ /// own box, and the boxes of the halves linked to it, before anything is
1436+ /// committed. Display only -- the project is not touched until the release.
1437+ fn trimmed(&self, lane: Lane, idx: usize, clip: Clip) -> Clip {
1438+ let Some(trim) = self.trim.filter(|t| {
1439+ (t.lane, t.idx) == (lane, idx) || (t.link.is_some() && t.link == clip.link)
1440+ }) else {
1441+ return clip;
1442+ };
1443+ match trim.edge {
1444+ // The in-point follows the head, exactly as `Project::trim` moves
1445+ // it: what stays on screen plays what it always played.
1446+ Edge::Start => Clip {
1447+ in_frame: (i64::from(clip.in_frame) + i64::from(trim.to) - i64::from(clip.start))
1448+ .clamp(0, i64::from(clip.out_frame - 1)) as u32,
1449+ start: trim.to,
1450+ ..clip
1451+ },
1452+ Edge::End => Clip {
1453+ out_frame: clip.in_frame + trim.to.saturating_sub(clip.start).max(1),
1454+ ..clip
1455+ },
1456+ }
1457+ }
1458+
1459+ /// How long the timeline is *drawn* as: its own length, and while a tail is
1460+ /// being dragged the furthest that tail may reach. A bed that ends exactly
1461+ /// at the last frame has nowhere to put a pointer that means "longer", so
1462+ /// without this the last clip on the timeline could be pulled in and never
1463+ /// let back out.
1464+ fn drawn_duration(&self) -> f64 {
1465+ let Some(session) = &self.session else {
1466+ return 0.;
1467+ };
1468+ let duration = session.timeline_duration();
1469+ match self.trim {
1470+ Some(trim) if trim.edge == Edge::End => {
1471+ let (_, hi) = session
1472+ .trim_room(trim.lane, trim.idx, trim.edge)
1473+ .unwrap_or((0, 0));
1474+ duration.max(f64::from(hi) / self.fps)
1475+ }
1476+ _ => duration,
1477+ }
1478+ }
1479+
1232 /// The one way a library row reaches the timeline: the Add button and a row1480 /// The one way a library row reaches the timeline: the Add button and a row
1233 /// dragged onto a lane both come here, so there is a single answer to what1481 /// dragged onto a lane both come here, so there is a single answer to what
1234 /// "add this source" does. The whole source goes in at the playhead as one1482 /// "add this source" does. The whole source goes in at the playhead as one
@@ -1761,11 +2009,9 @@ impl Render for Player {
1761 }2009 }
1762 2010
1763 // Read per render, never cached: a delete shortens the timeline and the2011 // Read per render, never cached: a delete shortens the timeline and the
1764- // timecode, the ruler and the clamp below all have to follow it.2012+ // timecode, the ruler and the clamp below all have to follow it -- and
1765- let duration = self2013+ // so does the room a tail being dragged needs to grow into.
1766- .session2014+ let duration = self.drawn_duration();
1767- .as_ref()
1768- .map_or(0., PlaybackSession::timeline_duration);
1769 // The clock keeps running after the last frame (wall time takes over at2015 // The clock keeps running after the last frame (wall time takes over at
1770 // audio EOF) while the picture is frozen, so the timeline the UI shows is2016 // audio EOF) while the picture is frozen, so the timeline the UI shows is
1771 // the clamped one, pinned to the out-point once playback is done.2017 // the clamped one, pinned to the out-point once playback is done.
@@ -1902,7 +2148,10 @@ impl Render for Player {
1902 // the keys menu still lists them.2148 // the keys menu still lists them.
1903 if this.color_open.is_some() {2149 if this.color_open.is_some() {
1904 match color_key(key) {2150 match color_key(key) {
1905- Some(ColorKey::Close) => this.color_open = None,2151+ Some(ColorKey::Close) => {
2152+ this.color_open = None;
2153+ this.color_dragging = false;
2154+ }
1906 Some(ColorKey::Band(step)) => {2155 Some(ColorKey::Band(step)) => {
1907 this.color_band = (this.color_band + step) % COLOR_BANDS.len();2156 this.color_band = (this.color_band + step) % COLOR_BANDS.len();
1908 }2157 }
@@ -1970,6 +2219,28 @@ impl Render for Player {
1970 }2219 }
1971 return;2220 return;
1972 }2221 }
2222+ // A clip edge is 6 px wide and the pointer leaves it on the
2223+ // first drag, so the gesture is tracked here for the same
2224+ // reason -- and it ends here too when the button came up
2225+ // outside the window, still owing its one edit.
2226+ if this.trim.is_some() {
2227+ match event.pressed_button {
2228+ Some(MouseButton::Left) => this.trim_to(event.position.x, cx),
2229+ _ => this.commit_trim(cx),
2230+ }
2231+ return;
2232+ }
2233+ // A colour slider is 4 px tall and the pointer leaves it just as
2234+ // fast; every sample is live, so the release owes no write of
2235+ // its own -- what the last sample set is what the clip carries.
2236+ if this.color_dragging {
2237+ if event.pressed_button == Some(MouseButton::Left) {
2238+ this.drag_color(event.position.x, false, cx);
2239+ } else {
2240+ this.color_dragging = false;
2241+ }
2242+ return;
2243+ }
1973 if !this.scrubbing {2244 if !this.scrubbing {
1974 return;2245 return;
1975 }2246 }
@@ -1992,6 +2263,20 @@ impl Render for Player {
1992 this.commit_eq(cx);2263 this.commit_eq(cx);
1993 return;2264 return;
1994 }2265 }
2266+ if this.trim.is_some() {
2267+ // The release lands exactly, then the gesture is
2268+ // written once -- one edit, one undo step.
2269+ this.trim_to(event.position.x, cx);
2270+ this.commit_trim(cx);
2271+ return;
2272+ }
2273+ if std::mem::take(&mut this.color_dragging) {
2274+ // The release lands exactly where the hand let go, and
2275+ // it is a live write like every other sample: the undo
2276+ // step the gesture rolls back to was the press's.
2277+ this.drag_color(event.position.x, false, cx);
2278+ return;
2279+ }
1995 if std::mem::take(&mut this.scrubbing) {2280 if std::mem::take(&mut this.scrubbing) {
1996 this.scrub_to(event.position.x, true, cx);2281 this.scrub_to(event.position.x, true, cx);
1997 }2282 }
@@ -3147,14 +3432,17 @@ impl Player {
3147 )3432 )
3148 }3433 }
3149 3434
3150- /// The colour card: a row per control, each showing where in its range it3435+ /// The colour card: the graded frame's histogram over a row per control,
3151- /// stands and carrying the pair of buttons that move it -- the same move the3436+ /// each row a bar the pointer drags straight to a value -- no stepper
3152- /// arrow keys make, because a control only the pointer can reach is not one3437+ /// buttons, because a slider is a thing to pull, and the arrow keys still
3153- /// everyone can reach. Same scrim, surface and row shape as the other two3438+ /// move the same value for anyone not using a pointer. Same scrim, surface
3154- /// cards, and the same plain divs, so the root keeps the keyboard.3439+ /// and row shape as the other two cards, and the same plain divs, so the
3440+ /// root keeps the keyboard.
3155 ///3441 ///
3156 /// The values are read from the project every render: what is drawn is what3442 /// The values are read from the project every render: what is drawn is what
3157- /// the decoder is grading with, never a copy that could drift from it.3443+ /// the decoder is grading with, never a copy that could drift from it. The
3444+ /// graph above them is counted off the frame that came *back* through that
3445+ /// grade ([`histogram`]), so pulling exposure tilts it while the hand moves.
3158 fn color_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {3446 fn color_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
3159 let (lane, idx) = self.color_open?;3447 let (lane, idx) = self.color_open?;
3160 let params = self.color_params();3448 let params = self.color_params();
@@ -3166,26 +3454,6 @@ impl Player {
3166 let value = *band_mut(&mut read, i);3454 let value = *band_mut(&mut read, i);
3167 let frac = ((value - low) / (high - low)).clamp(0., 1.);3455 let frac = ((value - low) / (high - low)).clamp(0., 1.);
3168 let picked = i == self.color_band;3456 let picked = i == self.color_band;
3169- // Both buttons of a row do what the arrows do, so there is one
3170- // rule for what a press is worth and one place it is clamped.
3171- let step = |name: &'static str, steps: f32| {
3172- div()
3173- .id((name, i))
3174- .w(px(CONTROL_H))
3175- .h(px(CONTROL_H))
3176- .flex()
3177- .items_center()
3178- .justify_center()
3179- .rounded(px(3.))
3180- .bg(rgb(CHROME))
3181- .cursor_pointer()
3182- .hover(|s| s.bg(rgb(HOVER)))
3183- .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
3184- this.color_band = i;
3185- this.nudge_color(steps, cx);
3186- }))
3187- .child(if steps < 0. { "–" } else { "+" })
3188- };
3189 div()3457 div()
3190 .id(("color-row", i))3458 .id(("color-row", i))
3191 .flex()3459 .flex()
@@ -3202,22 +3470,43 @@ impl Player {
3202 cx.notify();3470 cx.notify();
3203 }))3471 }))
3204 .child(div().flex_1().min_w(px(0.)).truncate().child(label))3472 .child(div().flex_1().min_w(px(0.)).truncate().child(label))
3205- .child(step("color-down", -1.))
3206 .child(3473 .child(
3474+ // The bar is 4 px to look at and a whole row to hit
3475+ // (WCAG 2.5.8), the same split the ruler makes between
3476+ // what is drawn and what is grabbed. The press is
3477+ // already the first sample of the drag, so a plain click
3478+ // sets the value it landed on.
3207 div()3479 div()
3480+ .id(("color-bar", i))
3481+ .relative()
3208 .w(px(COLOR_BAR_W))3482 .w(px(COLOR_BAR_W))
3209- .h(px(4.))3483+ .h(px(KEYS_ROW_H))
3210- .rounded(px(2.))3484+ .flex()
3211- .bg(rgb(CHROME))3485+ .items_center()
3486+ .on_mouse_down(
3487+ MouseButton::Left,
3488+ cx.listener(move |this, event: &MouseDownEvent, _, cx| {
3489+ this.color_band = i;
3490+ this.color_dragging = true;
3491+ this.drag_color(event.position.x, true, cx);
3492+ }),
3493+ )
3494+ .child(bounds_probe(self.color_bars[i].clone()))
3212 .child(3495 .child(
3213 div()3496 div()
3214- .h_full()3497+ .w_full()
3215- .w(relative(frac))3498+ .h(px(4.))
3216 .rounded(px(2.))3499 .rounded(px(2.))
3217- .bg(rgb(ACCENT)),3500+ .bg(rgb(CHROME))
3501+ .child(
3502+ div()
3503+ .h_full()
3504+ .w(relative(frac))
3505+ .rounded(px(2.))
3506+ .bg(rgb(ACCENT)),
3507+ ),
3218 ),3508 ),
3219 )3509 )
3220- .child(step("color-up", 1.))
3221 .child(3510 .child(
3222 div()3511 div()
3223 .w(px(44.))3512 .w(px(44.))
@@ -3258,7 +3547,22 @@ impl Player {
3258 .px(px(6.))3547 .px(px(6.))
3259 .text_size(px(11.))3548 .text_size(px(11.))
3260 .text_color(rgb(INK_DIM))3549 .text_color(rgb(INK_DIM))
3261- .child("↑↓ picks a slider, ←→ moves it, r resets — esc closes"),3550+ .child(
3551+ "drag a bar, or ↑↓ picks one and ←→ moves it, r resets — esc closes",
3552+ ),
3553+ )
3554+ // The frame as it is being graded, over the controls
3555+ // grading it: the three lines are what the picture is
3556+ // made of, and every sample of a drag reseeks, so they
3557+ // move with the bar under the hand.
3558+ .child(
3559+ div()
3560+ .flex_none()
3561+ .h(px(HIST_H))
3562+ .rounded(px(3.))
3563+ .bg(rgb(HOVER_DIM))
3564+ .relative()
3565+ .child(hist_curves(self.histogram)),
3262 )3566 )
3263 .children(rows)3567 .children(rows)
3264 .child(3568 .child(
@@ -3515,7 +3819,7 @@ impl Player {
3515 let (sel, sel_link) = (self.selected, self.selected_link());3819 let (sel, sel_link) = (self.selected, self.selected_link());
3516 let audio = lane.kind == LaneKind::Audio;3820 let audio = lane.kind == LaneKind::Audio;
3517 let tip: SharedString = format!(3821 let tip: SharedString = format!(
3518- "Select (or {} under the playhead, {}/{} along the lane) — {} removes the take, {} leaves a gap, {} rejoins a cut",3822+ "Select (or {} under the playhead, {}/{} along the lane) — drag an end to trim, {} removes the take, {} leaves a gap, {} rejoins a cut",
3519 self.keymap.display(ActionId::Select),3823 self.keymap.display(ActionId::Select),
3520 self.keymap.display(ActionId::SelectPrev),3824 self.keymap.display(ActionId::SelectPrev),
3521 self.keymap.display(ActionId::SelectNext),3825 self.keymap.display(ActionId::SelectNext),
@@ -3573,6 +3877,9 @@ impl Player {
3573 }))3877 }))
3574 .drag_over::<ClipDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))3878 .drag_over::<ClipDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))
3575 .children(clips.iter().enumerate().map(|(i, clip)| {3879 .children(clips.iter().enumerate().map(|(i, clip)| {
3880+ // What a drag on an edge is showing, which is the clip
3881+ // itself while nothing is being dragged.
3882+ let clip = &self.trimmed(lane, i, *clip);
3576 let (start, len) = (3883 let (start, len) = (
3577 f64::from(clip.start) / self.fps,3884 f64::from(clip.start) / self.fps,
3578 f64::from(clip.len()) / self.fps,3885 f64::from(clip.len()) / self.fps,
@@ -3651,19 +3958,44 @@ impl Player {
3651 .on_mouse_down(3958 .on_mouse_down(
3652 MouseButton::Right,3959 MouseButton::Right,
3653 cx.listener(move |this, event: &MouseDownEvent, _, cx| {3960 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
3654- if this.modal() {3961+ this.open_menu(lane, i, event.position, cx);
3655- return;
3656- }
3657- this.select((lane, i), cx);
3658- this.context_menu = Some(ContextMenu {
3659- lane,
3660- idx: i,
3661- at: event.position,
3662- details: false,
3663- });
3664- cx.notify();
3665 }),3962 }),
3666 )3963 )
3964+ // The two strips a drag *lengthens* the clip by,
3965+ // one at each end. They occlude the box behind
3966+ // them, which is what keeps one gesture one thing:
3967+ // a press here trims, a press anywhere else on the
3968+ // box still starts the move to another lane.
3969+ .children([Edge::Start, Edge::End].map(|edge| {
3970+ let mut zone = div()
3971+ .absolute()
3972+ .top_0()
3973+ .h_full()
3974+ .w(px(EDGE_W))
3975+ .occlude()
3976+ .cursor(CursorStyle::ResizeLeftRight)
3977+ .hover(|s| s.bg(rgb(ACCENT)))
3978+ .on_mouse_down(
3979+ MouseButton::Left,
3980+ cx.listener(move |this, _: &MouseDownEvent, _, cx| {
3981+ this.start_trim(lane, i, edge, cx);
3982+ }),
3983+ )
3984+ // Occluded, so the box's own right-button
3985+ // listener never fires here: the menu is
3986+ // the same menu, opened by the same call.
3987+ .on_mouse_down(
3988+ MouseButton::Right,
3989+ cx.listener(move |this, event: &MouseDownEvent, _, cx| {
3990+ this.open_menu(lane, i, event.position, cx);
3991+ }),
3992+ );
3993+ zone = match edge {
3994+ Edge::Start => zone.left_0(),
3995+ Edge::End => zone.right_0(),
3996+ };
3997+ zone
3998+ }))
3667 // Under the label row, never through it.3999 // Under the label row, never through it.
3668 .children(wave.filter(|_| audio).and_then(|wave| {4000 .children(wave.filter(|_| audio).and_then(|wave| {
3669 let inner: AnyElement = match wave {4001 let inner: AnyElement = match wave {
@@ -4788,6 +5120,73 @@ fn frac_down(y: Pixels, bounds: Bounds<Pixels>) -> f32 {
4788 ((y - bounds.top()) / bounds.size.height).clamp(0., 1.)5120 ((y - bounds.top()) / bounds.size.height).clamp(0., 1.)
4789 }5121 }
4790 5122
5123+/// A slider value on the [`COLOR_STEP`] grid: what a drag rounds to, so the
5124+/// pointer stops where the arrow keys do and "0.35" on screen is the number the
5125+/// file writes rather than a rounding of one.
5126+fn color_snap(value: f32) -> f32 {
5127+ (value / COLOR_STEP).round() * COLOR_STEP
5128+}
5129+
5130+/// How the frame on screen is spread across the tone range: `HIST_BINS` counts
5131+/// per channel, read off the BGRA the decoder handed over -- which is the
5132+/// *graded* picture, because the grade is folded into the conversion
5133+/// (`engine::convert::i420_to_bgra_with`). So what this counts is what the eye
5134+/// is looking at, and moving a slider moves it.
5135+///
5136+/// Every [`HIST_SAMPLES`]th-of-a-frame pixel, not every pixel: a shape drawn
5137+/// from eight thousand samples is the same shape, at a thousandth of the reads.
5138+fn histogram(bgra: &[u8]) -> [[u32; HIST_BINS]; 3] {
5139+ let pixels = bgra.len() / 4;
5140+ let stride = (pixels / HIST_SAMPLES).max(1);
5141+ let mut bins = [[0u32; HIST_BINS]; 3];
5142+ for p in (0..pixels).step_by(stride) {
5143+ let px = &bgra[p * 4..];
5144+ // BGRA on the wire, `[r, g, b]` in the bins: the graph names channels
5145+ // the way a person does.
5146+ for (channel, value) in [px[2], px[1], px[0]].into_iter().enumerate() {
5147+ bins[channel][usize::from(value) * HIST_BINS / 256] += 1;
5148+ }
5149+ }
5150+ bins
5151+}
5152+
5153+/// The three counts drawn as three lines across the box, tallest bin to the top.
5154+///
5155+/// Square root, not linear: a shot with a big flat area (a night sky, a title
5156+/// card) puts one bin so far above the rest that a linear graph is a single
5157+/// spike beside a flat line, and the tilt a grade puts in the rest is exactly
5158+/// what the card is for.
5159+fn hist_curves(bins: [[u32; HIST_BINS]; 3]) -> impl IntoElement {
5160+ canvas(
5161+ |_, _, _| (),
5162+ move |bounds, _, window, _| {
5163+ let (o, s) = (bounds.origin, bounds.size);
5164+ // Shared across the channels, so their relative weight is readable;
5165+ // never zero, so an unpumped (all-zero) histogram is a flat line
5166+ // rather than a division by nothing.
5167+ let top = bins.iter().flatten().copied().max().unwrap_or(0).max(1) as f32;
5168+ for (channel, counts) in bins.iter().enumerate() {
5169+ let mut path = PathBuilder::stroke(px(1.5));
5170+ for (bin, &count) in counts.iter().enumerate() {
5171+ let at = point(
5172+ o.x + s.width * (bin as f32 / (HIST_BINS - 1) as f32),
5173+ o.y + s.height * (1. - (count as f32 / top).sqrt()),
5174+ );
5175+ match bin {
5176+ 0 => path.move_to(at),
5177+ _ => path.line_to(at),
5178+ }
5179+ }
5180+ if let Ok(path) = path.build() {
5181+ window.paint_path(path, rgb(HIST_INK[channel]));
5182+ }
5183+ }
5184+ },
5185+ )
5186+ .absolute()
5187+ .size_full()
5188+}
5189+
4791 /// The cascade's frequency response, drawn as one line across the graph.5190 /// The cascade's frequency response, drawn as one line across the graph.
4792 ///5191 ///
4793 /// Every point comes from `EqParams::response_db`, which reads the very5192 /// Every point comes from `EqParams::response_db`, which reads the very
@@ -4893,16 +5292,17 @@ fn timecode(t: f64, fps: f64) -> String {
4893 #[cfg(test)]5292 #[cfg(test)]
4894 mod tests {5293 mod tests {
4895 use super::{5294 use super::{
4896- ACCENT, CONTROL_H, Clip, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE,5295+ ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, EQ_FREQ_HIGH,
4897- EQ_TICKS, EXPORT_ROWS_H, FORMATS, Format, HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM,5296+ EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_TICKS, EXPORT_ROWS_H, FORMATS,
5297+ Format, HEADER_GAP, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM,
4898 KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX,5298 KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX,
4899 LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H,5299 LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H,
4900 RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume,5300 RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume,
4901- WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, cancels_export, envelope, eq_x,5301+ WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, cancels_export, color_snap,
4902- eq_y, export_path, export_settings, format_line, frac_along, frac_down, frame_at,5302+ envelope, eq_x, eq_y, export_path, export_settings, format_line, frac_along, frac_down,
4903- is_bare_modifier, is_project, keymap, lane_clips, lanes_h, marked, menu_at, mp4_refusal,5303+ frame_at, histogram, is_bare_modifier, is_project, keymap, lane_clips, lanes_h, marked,
4904- normalise, panel_h, project_path, push_digit, retarget, scrub_due, show_label,5304+ menu_at, mp4_refusal, normalise, panel_h, project_path, push_digit, retarget, scrub_due,
4905- source_frames, source_tint, span_partner, start_frac, timecode, unseen_paths,5305+ show_label, source_frames, source_tint, span_partner, start_frac, timecode, unseen_paths,
4906 unseen_sources, whole_take, width_frac, window_title,5306 unseen_sources, whole_take, width_frac, window_title,
4907 };5307 };
4908 use super::{file_name, file_uri, library_rows};5308 use super::{file_name, file_uri, library_rows};
@@ -5343,6 +5743,64 @@ mod tests {
5343 );5743 );
5344 }5744 }
5345 5745
5746+ /// The trim-a-clip path through the doors the edge drag uses:
5747+ /// [`Player::trim_to`] clamps the pointer with `trim_room` and
5748+ /// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less
5749+ /// of its file, the sound linked to it follows, the head trim moves the
5750+ /// in-point, and one undo takes a whole gesture back.
5751+ ///
5752+ /// The routing *to* these doors -- the 6 px edge strip claiming the press
5753+ /// the clip's own body-drag would otherwise take -- is gpui hitbox
5754+ /// behaviour (`occlude`) and is not reachable without a window.
5755+ #[test]
5756+ fn a_clip_trimmed_by_its_edge_plays_less_of_its_file() {
5757+ use engine::project::Edge;
5758+
5759+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
5760+ session.set_gain(0.0);
5761+ let whole = session.lane_clips(Lane::V1)[0];
5762+ let full = session.timeline_duration();
5763+ assert_eq!(
5764+ session.trim_room(Lane::V1, 0, Edge::End),
5765+ Some((whole.start + 1, whole.end())),
5766+ "the file's own last frame is how far the tail goes"
5767+ );
5768+ assert!(
5769+ !session.trim_clip(Lane::V1, 0, Edge::End, 9_999),
5770+ "it already plays all of it"
5771+ );
5772+
5773+ // Pulled in by a third: the timeline ends earlier and the sound with it.
5774+ let shorter = whole.end() - whole.len() / 3;
5775+ assert!(session.trim_clip(Lane::V1, 0, Edge::End, shorter));
5776+ assert_eq!(session.lane_clips(Lane::V1)[0].end(), shorter);
5777+ assert_eq!(
5778+ session.lane_clips(Lane::A1)[0].end(),
5779+ shorter,
5780+ "the linked sound was trimmed with the picture"
5781+ );
5782+ assert!(session.timeline_duration() < full, "and plays out earlier");
5783+
5784+ // ...and dragged back out, as far as the file goes and no further.
5785+ assert!(session.trim_clip(Lane::V1, 0, Edge::End, 9_999));
5786+ assert_eq!(session.lane_clips(Lane::V1)[0], whole, "the whole take back");
5787+
5788+ // The head takes the in-point with it, so what plays at the new start
5789+ // is source frame 10 rather than source frame 0.
5790+ assert!(session.trim_clip(Lane::V1, 0, Edge::Start, 10));
5791+ let head = session.lane_clips(Lane::V1)[0];
5792+ assert_eq!((head.start, head.in_frame), (10, 10));
5793+ assert_eq!(session.lane_clips(Lane::A1)[0].in_frame, 10, "sound too");
5794+ assert_eq!(
5795+ session.trim_room(Lane::V1, 0, Edge::Start).map(|r| r.0),
5796+ Some(0),
5797+ "and it may be pulled back out to the file's first frame"
5798+ );
5799+
5800+ assert!(session.undo(), "one step for the whole drag");
5801+ assert_eq!(session.lane_clips(Lane::V1)[0], whole);
5802+ }
5803+
5346 /// The move-a-clip-between-tracks path through the door the drop uses5804 /// The move-a-clip-between-tracks path through the door the drop uses
5347 /// ([`Player::move_clip`] calls exactly this): the clip changes row, the5805 /// ([`Player::move_clip`] calls exactly this): the clip changes row, the
5348 /// *picture* comes from the new row afterwards -- which is what "it plays5806 /// *picture* comes from the new row afterwards -- which is what "it plays
@@ -5876,6 +6334,130 @@ mod tests {
5876 assert!(KEYS_ROW_H >= HIT_MIN);6334 assert!(KEYS_ROW_H >= HIT_MIN);
5877 }6335 }
5878 6336
6337+ /// A colour slider is dragged straight to a value, so where the pointer
6338+ /// lands and where the bar then paints have to be the same place: this is
6339+ /// the round trip [`Player::drag_color`] makes, pixels -> value -> fill.
6340+ #[test]
6341+ fn a_colour_drag_lands_where_it_paints_and_the_card_fits_the_smallest_window() {
6342+ // A bar as laid out, somewhere that is not the window's origin -- a
6343+ // mapping that forgot the offset would pass at zero.
6344+ let bar = Bounds {
6345+ origin: point(px(180.), px(240.)),
6346+ size: size(px(COLOR_BAR_W), px(KEYS_ROW_H)),
6347+ };
6348+ for &(label, low, high) in &COLOR_BANDS {
6349+ // The ends are the ends: the left of the bar is the bottom of the
6350+ // range and the right is the top, so a slider can be pulled to
6351+ // either without hunting for the last pixel.
6352+ let at = |x: f32| color_snap(low + frac_along(px(x), bar) * (high - low));
6353+ assert_eq!(at(180.), low, "{label} left end");
6354+ assert_eq!(at(180. + COLOR_BAR_W), high, "{label} right end");
6355+ // Off either end clamps rather than running past the range.
6356+ assert_eq!(at(-4000.), low, "{label} off the left");
6357+ assert_eq!(at(9999.), high, "{label} off the right");
6358+
6359+ for step in 0..=48 {
6360+ let along = step as f32 / 48.;
6361+ let value = at(180. + along * COLOR_BAR_W);
6362+ // Every stop is one the keyboard can also reach, which is what
6363+ // keeps "0.35" the number the file writes.
6364+ let steps = value / COLOR_STEP;
6365+ assert!(
6366+ (steps - steps.round()).abs() < 1e-3,
6367+ "{label}: {value} is off the {COLOR_STEP} grid"
6368+ );
6369+ assert!(
6370+ (low..=high).contains(&value),
6371+ "{label}: {value} outside {low}..{high}"
6372+ );
6373+ // What the row paints from that value is where the pointer was,
6374+ // to within the half step the snap costs.
6375+ let painted = (value - low) / (high - low);
6376+ let slack = COLOR_STEP / (high - low) / 2. + 1e-4;
6377+ assert!(
6378+ (painted - along).abs() <= slack,
6379+ "{label}: pressed at {along}, paints at {painted}"
6380+ );
6381+ }
6382+ }
6383+
6384+ // The same shape as the other two cards, so it fits where they do: the
6385+ // graph, four rows and the reset button inside a 360 px window.
6386+ let (title, status, gaps, padding) = (17., 17., 6. * 2., 24.);
6387+ let rows = COLOR_BANDS.len() as f32 * KEYS_ROW_H;
6388+ assert!(
6389+ title + status + HIST_H + rows + gaps + padding + CONTROL_H + 4. <= 360.,
6390+ "card too tall"
6391+ );
6392+ assert!(COLOR_W <= 640., "card too wide");
6393+ // The label still has room beside the bar and the readout, which is
6394+ // what the buttons coming off the row bought.
6395+ let row = COLOR_W - padding - 12. - 2. * 8. - COLOR_BAR_W - 44.;
6396+ assert!(row >= LABEL_MIN_W, "no room left for a label: {row}px");
6397+ // What is dragged is the whole row's height, not the 4 px the bar is
6398+ // drawn as (WCAG 2.5.8) -- the same split the ruler makes.
6399+ assert!(KEYS_ROW_H >= HIT_MIN);
6400+ }
6401+
6402+ /// The graph over the sliders is the frame the grade already went through,
6403+ /// so it has to count what is actually in those bytes -- BGRA on the wire,
6404+ /// red-green-blue in the bins.
6405+ #[test]
6406+ fn the_histogram_counts_the_frame_it_is_handed() {
6407+ // Half pure red, half mid grey: two known values, in two known bins.
6408+ let (w, h) = (64usize, 64usize);
6409+ let mut frame = Vec::with_capacity(w * h * 4);
6410+ for _ in 0..h {
6411+ for col in 0..w {
6412+ match col < w / 2 {
6413+ true => frame.extend_from_slice(&[0, 0, 255, 255]),
6414+ false => frame.extend_from_slice(&[128, 128, 128, 255]),
6415+ }
6416+ }
6417+ }
6418+ let bins = histogram(&frame);
6419+ let half = (w * h / 2) as u32;
6420+ // 64 bins over 256 codes: 255 is the last bin, 128 the middle one, 0 the
6421+ // first.
6422+ assert_eq!(bins[0][63], half, "the red half tops the red channel");
6423+ assert_eq!(bins[0][32], half, "and the grey half sits mid red");
6424+ for channel in [1, 2] {
6425+ assert_eq!(bins[channel][0], half, "no green or blue in the red half");
6426+ assert_eq!(bins[channel][32], half);
6427+ assert_eq!(bins[channel][63], 0);
6428+ }
6429+ // Nothing is counted twice and nothing is dropped: this frame is small
6430+ // enough to be read whole.
6431+ for channel in bins {
6432+ assert_eq!(channel.iter().sum::<u32>(), (w * h) as u32);
6433+ }
6434+
6435+ // A grade shifts it, which is the whole point of drawing it: the same
6436+ // frame darkened lands in lower bins.
6437+ let darker: Vec<u8> = frame.iter().map(|b| b / 2).collect();
6438+ let bins = histogram(&darker);
6439+ assert_eq!(bins[0][31], half, "255 -> 127");
6440+ assert_eq!(bins[0][16], half, "128 -> 64");
6441+
6442+ // A real frame is subsampled: a 1080p one is read every 253rd pixel, so
6443+ // the shape costs a thousandth of the reads and still counts thousands.
6444+ let big = vec![200u8; 1920 * 1080 * 4];
6445+ let bins = histogram(&big);
6446+ let counted = bins[0].iter().sum::<u32>();
6447+ let pixels = 1920 * 1080usize;
6448+ let expected = pixels.div_ceil(pixels / HIST_SAMPLES) as u32;
6449+ assert_eq!(counted, expected, "every strided pixel counted, once");
6450+ assert!(
6451+ (HIST_SAMPLES as u32..=HIST_SAMPLES as u32 + 64).contains(&counted),
6452+ "{counted} samples is not the budget"
6453+ );
6454+ assert_eq!(bins[0][200 * HIST_BINS / 256], counted, "all in one bin");
6455+
6456+ // An empty buffer is a flat graph rather than a panic: the card is open
6457+ // before the first frame is pumped.
6458+ assert_eq!(histogram(&[]), [[0; HIST_BINS]; 3]);
6459+ }
6460+
5879 /// Mute and level are one control with two states, and the whole point is6461 /// Mute and level are one control with two states, and the whole point is
5880 /// that mute keeps the level: the user gets back what they had, not 100%.6462 /// that mute keeps the level: the user gets back what they had, not 100%.
5881 #[test]6463 #[test]
@@ -6390,6 +6972,7 @@ fn main() {
6390 streams: HashMap::new(),6972 streams: HashMap::new(),
6391 clipboard: None,6973 clipboard: None,
6392 scrubbing: false,6974 scrubbing: false,
6975+ trim: None,
6393 last_scrub: Instant::now(),6976 last_scrub: Instant::now(),
6394 last_target: 0,6977 last_target: 0,
6395 export: None,6978 export: None,
@@ -6408,6 +6991,11 @@ fn main() {
6408 eq_graph: Rc::default(),6991 eq_graph: Rc::default(),
6409 color_open: None,6992 color_open: None,
6410 color_band: 0,6993 color_band: 0,
6994+ color_dragging: false,
6995+ color_bars: std::array::from_fn(|_| Rc::default()),
6996+ // Empty until the first frame is pumped, which draws as a
6997+ // flat line rather than as a shape nothing measured.
6998+ histogram: [[0; HIST_BINS]; 3],
6411 // What an export is until someone says otherwise: the6999 // What an export is until someone says otherwise: the
6412 // bitrate the picture asks for.7000 // bitrate the picture asks for.
6413 quality: Quality::Auto,7001 quality: Quality::Auto,
crates/engine/src/playback.rsmodified+62 -1
@@ -25,7 +25,7 @@ use crate::color::ColorParams;
25 use crate::decode::{DecodeSession, Frame, Worker};25 use crate::decode::{DecodeSession, Frame, Worker};
26 use crate::demux::{Demuxer, VideoMeta};26 use crate::demux::{Demuxer, VideoMeta};
27 use crate::eq::EqParams;27 use crate::eq::EqParams;
28-use crate::project::{Clip, Lane, LaneKind, Project, Source, Span};28+use crate::project::{Clip, Edge, Lane, LaneKind, Project, Source, Span};
29 use crate::scale::{Composer, FitPolicy};29 use crate::scale::{Composer, FitPolicy};
30 30
31 /// How long the feeder waits out a full ring. The ring holds a second, so this31 /// How long the feeder waits out a full ring. The ring holds a second, so this
@@ -122,6 +122,15 @@ pub struct PlaybackSession {
122 /// The edit list. Everything a caller says in seconds is a *timeline*122 /// The edit list. Everything a caller says in seconds is a *timeline*
123 /// position; only this maps it onto the file.123 /// position; only this maps it onto the file.
124 project: Project,124 project: Project,
125+ /// How many frames each source actually holds, indexed exactly as
126+ /// [`Project::sources`] is and grown with it. The project itself does not
127+ /// know -- a clip names a source by index and carries its own range -- and
128+ /// [`Self::trim_clip`] is the one edit that could ask for frames past the
129+ /// end of a file, which is a save that would not open again
130+ /// ([`Self::open_project`] refuses one by name). Append-only for
131+ /// `sources`'s reason: an index handed out stays valid, undone import or
132+ /// not.
133+ counts: Vec<u32>,
125 /// What the current video worker was opened for: where it sits on the134 /// What the current video worker was opened for: where it sits on the
126 /// timeline, how long it runs, and which source frame it started at --135 /// timeline, how long it runs, and which source frame it started at --
127 /// together they rewrite a source frame index into a timeline one. Not a136 /// together they rewrite a source frame index into a timeline one. Not a
@@ -191,6 +200,7 @@ impl PlaybackSession {
191 audio,200 audio,
192 audio_disabled,201 audio_disabled,
193 project,202 project,
203+ counts: vec![meta.frame_count],
194 span,204 span,
195 eos: false,205 eos: false,
196 })206 })
@@ -316,6 +326,7 @@ impl PlaybackSession {
316 audio,326 audio,
317 audio_disabled,327 audio_disabled,
318 project,328 project,
329+ counts,
319 span,330 span,
320 eos: false,331 eos: false,
321 };332 };
@@ -639,6 +650,45 @@ impl PlaybackSession {
639 self.edit(|p| p.move_to_lane(from, idx, to))650 self.edit(|p| p.move_to_lane(from, idx, to))
640 }651 }
641 652
653+ /// Drags one end of that clip to timeline frame `to`, changing how much of
654+ /// its source it plays and nothing else on the lane -- see [`Project::trim`]
655+ /// for the walls it is clamped by, which this fills the source lengths in
656+ /// for. One undo step per call, so a front-end calls it once, at the release
657+ /// of the drag. Reseeks like every other edit, which is what makes the
658+ /// picture (and the sound) follow a new in-point straight away. `false` for
659+ /// a bad index and for an edge already where it was asked to go.
660+ ///
661+ /// A *frame*, where the rest of this type takes seconds: a drag has already
662+ /// asked [`trim_room`](Self::trim_room) where the edge may land, and that
663+ /// answer is in frames -- converting it back through seconds would be a
664+ /// rounding step between the width drawn and the width committed.
665+ pub fn trim_clip(&mut self, lane: Lane, idx: usize, edge: Edge, to: u32) -> bool {
666+ // Spelled out rather than through `edit`, whose closure cannot hold a
667+ // second borrow of the session while it has the project.
668+ if !self.project.trim(lane, idx, edge, to, &self.counts) {
669+ return false;
670+ }
671+ let now = self.now();
672+ self.seek(now);
673+ true
674+ }
675+
676+ /// Where that edge may land, `(first, last)` timeline frame inclusive: what
677+ /// a drag clamps the pointer to so the box it draws is the box
678+ /// [`trim_clip`](Self::trim_clip) will commit. `None` for a bad index.
679+ pub fn trim_room(&self, lane: Lane, idx: usize, edge: Edge) -> Option<(u32, u32)> {
680+ self.project.trim_room(lane, idx, edge, &self.counts)
681+ }
682+
683+ /// Records how long a source is, for a source index that may be one
684+ /// `Project::import` just made or one it handed back. See [`Self::counts`].
685+ fn note_frames(&mut self, source: usize, frames: u32) {
686+ if source == self.counts.len() {
687+ self.counts.push(frames);
688+ }
689+ debug_assert_eq!(self.counts.len(), self.project.sources().len());
690+ }
691+
642 /// The clip the picture is coming from at `timeline_secs`: the lane it sits692 /// The clip the picture is coming from at `timeline_secs`: the lane it sits
643 /// on and its index there, by the same topmost-lane-wins rule the decoder693 /// on and its index there, by the same topmost-lane-wins rule the decoder
644 /// follows. `None` over a gap and past the end. What a card that grades694 /// follows. `None` over a gap and past the end. What a card that grades
@@ -672,6 +722,14 @@ impl PlaybackSession {
672 self.edit(|p| p.set_color(lane, idx, params))722 self.edit(|p| p.set_color(lane, idx, params))
673 }723 }
674 724
725+ /// The same grade and the same reseek without the undo step
726+ /// ([`Project::set_color_live`]): what the samples inside one slider drag go
727+ /// through, so the frame regrades under the hand and the whole gesture is
728+ /// still a single `z`.
729+ pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
730+ self.edit(|p| p.set_color_live(lane, idx, params))
731+ }
732+
675 /// The project's resolution: what every clip is composed onto, what the733 /// The project's resolution: what every clip is composed onto, what the
676 /// window is sized to and what an export writes -- *not* any one file's.734 /// window is sized to and what an export writes -- *not* any one file's.
677 /// It starts as source 0's picture, which is what a project meant before it735 /// It starts as source 0's picture, which is what a project meant before it
@@ -777,6 +835,7 @@ impl PlaybackSession {
777 let first = self.first_audio()?;835 let first = self.first_audio()?;
778 audio_matches(&wanted, &first)?;836 audio_matches(&wanted, &first)?;
779 let source = self.project.import(path, stream);837 let source = self.project.import(path, stream);
838+ self.note_frames(source, frames.max(1));
780 let clip = Clip {839 let clip = Clip {
781 start: 0,840 start: 0,
782 in_frame: 0,841 in_frame: 0,
@@ -869,6 +928,7 @@ impl PlaybackSession {
869 928
870 let old_end = self.timeline_duration();929 let old_end = self.timeline_duration();
871 let source = self.project.import(path, 0);930 let source = self.project.import(path, 0);
931+ self.note_frames(source, meta.frame_count);
872 // Refused only for an unknown index, and this one just came from `import`.932 // Refused only for an unknown index, and this one just came from `import`.
873 self.project.append_clip(source, meta.frame_count);933 self.project.append_clip(source, meta.frame_count);
874 // Reseek like any other edit, even though nothing before the playhead934 // Reseek like any other edit, even though nothing before the playhead
@@ -901,6 +961,7 @@ impl PlaybackSession {
901 961
902 let old_end = self.timeline_duration();962 let old_end = self.timeline_duration();
903 let source = self.project.import(path, 0);963 let source = self.project.import(path, 0);
964+ self.note_frames(source, frames);
904 let at = self.project.timeline_frames();965 let at = self.project.timeline_frames();
905 self.project.place(966 self.project.place(
906 Lane::A1,967 Lane::A1,
crates/engine/src/project.rsmodified+340 -1
@@ -212,6 +212,17 @@ impl LaneData {
212 }212 }
213 }213 }
214 214
215+/// Which end of a clip a [`Project::trim`] moves: the one the pointer grabbed.
216+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
217+pub enum Edge {
218+ /// Its first timeline frame; moving it changes where in the source the clip
219+ /// starts reading, so the picture behind the edge slides with it.
220+ Start,
221+ /// One past its last timeline frame; moving it only says how much of the
222+ /// source to keep.
223+ End,
224+}
225+
215 /// What a lane holds over one stretch of the timeline: either a placed clip or226 /// What a lane holds over one stretch of the timeline: either a placed clip or
216 /// a gap. Returned already trimmed to the position it was asked about, so a227 /// a gap. Returned already trimmed to the position it was asked about, so a
217 /// caller can hand `len` straight to a decoder (or to a black-frame generator).228 /// caller can hand `len` straight to a decoder (or to a black-frame generator).
@@ -646,6 +657,24 @@ impl Project {
646 /// (and no history) for an index that is not there or a value that is not657 /// (and no history) for an index that is not there or a value that is not
647 /// finite, and equal settings share a table entry.658 /// finite, and equal settings share a table entry.
648 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {659 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
660+ self.write_color(lane, idx, params, true)
661+ }
662+
663+ /// [`set_color`](Self::set_color) without the undo step: the samples *inside*
664+ /// one pointer drag, whose first write (a plain `set_color`) already took the
665+ /// snapshot the gesture rolls back to. A drag across a slider is one undo,
666+ /// not one per pixel -- and undoing it lands where the hand picked it up.
667+ pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
668+ self.write_color(lane, idx, params, false)
669+ }
670+
671+ fn write_color(
672+ &mut self,
673+ lane: Lane,
674+ idx: usize,
675+ params: Option<ColorParams>,
676+ snapshot: bool,
677+ ) -> bool {
649 if idx >= self.lane(lane).len() {678 if idx >= self.lane(lane).len() {
650 return false;679 return false;
651 }680 }
@@ -668,7 +697,9 @@ impl Project {
668 })697 })
669 }698 }
670 };699 };
671- self.snapshot();700+ if snapshot {
701+ self.snapshot();
702+ }
672 self.lane_mut(lane).expect("checked above")[idx].color = slot;703 self.lane_mut(lane).expect("checked above")[idx].color = slot;
673 true704 true
674 }705 }
@@ -1153,6 +1184,145 @@ impl Project {
1153 true1184 true
1154 }1185 }
1155 1186
1187+ /// Move one `edge` of the clip at `idx` of `lane` to timeline frame `to` --
1188+ /// the drag on a clip's end that makes it play more or less of its source.
1189+ /// The rest of the lane stays exactly where it is (nothing ripples), so what
1190+ /// a shortened clip leaves behind is a gap and what a lengthened one takes
1191+ /// is room that was already empty. One snapshot, so a whole drag is one
1192+ /// [`Project::undo`] -- commit once, at the release, rather than per pointer
1193+ /// sample. Changes the timeline->source mapping: the caller must reseek.
1194+ ///
1195+ /// [`Edge::Start`] moves the in-point with it: the frames that stay play
1196+ /// exactly what they played before, which is what makes this a trim and not
1197+ /// a slip.
1198+ ///
1199+ /// `to` is **clamped**, never refused -- a hand pulling an edge past what is
1200+ /// legal means "as far as it goes", and stopping the box there is the
1201+ /// affordance. The walls are: one frame of clip always survives, an edge
1202+ /// never crosses the neighbouring clip on its own lane, an in-point never
1203+ /// walks back past the source's first frame, and an out-point never runs
1204+ /// past `source_frames[clip.source]` -- the caller's table of how long each
1205+ /// source actually is ([`Project`] does not know, and a clip ending past its
1206+ /// file's last frame is a save that will not open again; see
1207+ /// `PlaybackSession::trim_clip`, which fills it in). A source with no entry
1208+ /// there may not grow at all.
1209+ ///
1210+ /// Linked clips trim *together*, to one clamped edge: a link is one span on
1211+ /// however many lanes ([`links_are_consistent`]), so a picture trimmed away
1212+ /// from its sound would be a group no save could load. The room is therefore
1213+ /// what every member of the group has -- the tightest wall wins.
1214+ ///
1215+ /// `false`, changing nothing and costing no undo step, for an index that is
1216+ /// not there and for an edge that is already where it was asked to go.
1217+ pub fn trim(
1218+ &mut self,
1219+ lane: Lane,
1220+ idx: usize,
1221+ edge: Edge,
1222+ to: u32,
1223+ source_frames: &[u32],
1224+ ) -> bool {
1225+ let (Some((lo, hi)), Some(clip)) = (
1226+ self.trim_room(lane, idx, edge, source_frames),
1227+ self.lane(lane).get(idx).copied(),
1228+ ) else {
1229+ return false;
1230+ };
1231+ let to = to.clamp(lo, hi);
1232+ let at = match edge {
1233+ Edge::Start => clip.start,
1234+ Edge::End => clip.end(),
1235+ };
1236+ if to == at {
1237+ return false;
1238+ }
1239+ self.snapshot();
1240+ for (l, i) in self.group_of(lane, idx).expect("checked above") {
1241+ let c = &mut self.lanes[l].clips[i];
1242+ match edge {
1243+ Edge::Start => {
1244+ // Non-negative by `lo`, which is what keeps the in-point on
1245+ // the source.
1246+ c.in_frame = (i64::from(c.in_frame) + i64::from(to) - i64::from(c.start)) as u32;
1247+ c.start = to;
1248+ }
1249+ Edge::End => c.out_frame = c.in_frame + (to - c.start),
1250+ }
1251+ debug_assert!(sorted_disjoint(&self.lanes[l].clips));
1252+ }
1253+ true
1254+ }
1255+
1256+ /// How far that edge may travel, `(first, last)` timeline frame inclusive --
1257+ /// the walls [`trim`](Project::trim) clamps to, without moving anything.
1258+ /// What a front-end drawing the box *during* a drag asks, so the live width
1259+ /// is the width the release will commit and an edge stops under the pointer
1260+ /// rather than snapping back. `None` for an index that is not there.
1261+ pub fn trim_room(
1262+ &self,
1263+ lane: Lane,
1264+ idx: usize,
1265+ edge: Edge,
1266+ source_frames: &[u32],
1267+ ) -> Option<(u32, u32)> {
1268+ let (mut lo, mut hi) = (u32::MIN, u32::MAX);
1269+ for (l, i) in self.group_of(lane, idx)? {
1270+ let clips = &self.lanes[l].clips;
1271+ let c = clips[i];
1272+ let (member_lo, member_hi) = match edge {
1273+ Edge::Start => (
1274+ // Back to the source's own first frame, and never over the
1275+ // clip in front of it. Saturating because a clip may hold
1276+ // *more* head than the timeline has room for -- a ripple
1277+ // delete slides a clip back to frame 0 with its in-point
1278+ // wherever the cut left it -- and frame 0 is the other wall.
1279+ c.start
1280+ .saturating_sub(c.in_frame)
1281+ .max(i.checked_sub(1).map_or(0, |p| clips[p].end())),
1282+ c.end() - 1,
1283+ ),
1284+ Edge::End => (
1285+ c.start + 1,
1286+ // Out to whatever is left of the source, and never over the
1287+ // clip behind it.
1288+ c.start
1289+ .saturating_add(
1290+ source_frames
1291+ .get(c.source)
1292+ .copied()
1293+ .unwrap_or(c.out_frame)
1294+ .saturating_sub(c.in_frame),
1295+ )
1296+ .min(clips.get(i + 1).map_or(u32::MAX, |n| n.start)),
1297+ ),
1298+ };
1299+ lo = lo.max(member_lo);
1300+ hi = hi.min(member_hi);
1301+ }
1302+ // `hi.max(lo)`: for a clip the invariants hold for, the range always
1303+ // contains the edge's own place, and a caller's wrong `source_frames`
1304+ // must not become an empty range (or a panicking `clamp`) here.
1305+ Some((lo, hi.max(lo)))
1306+ }
1307+
1308+ /// The clips that move as one with the clip at `idx` of `lane` -- itself and
1309+ /// whatever carries its link on the other lanes -- as `(lane storage index,
1310+ /// clip index)` pairs. `None` for an index that is not there.
1311+ fn group_of(&self, lane: Lane, idx: usize) -> Option<Vec<(usize, usize)>> {
1312+ let clip = *self.lane(lane).get(idx)?;
1313+ Some(match clip.link {
1314+ Some(link) => self
1315+ .lanes
1316+ .iter()
1317+ .enumerate()
1318+ .filter_map(|(l, data)| {
1319+ Some((l, data.clips.iter().position(|c| c.link == Some(link))?))
1320+ })
1321+ .collect(),
1322+ None => vec![(self.index(lane).expect("the clip was found on it"), idx)],
1323+ })
1324+ }
1325+
1156 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one1326 /// Insert `clip` into the first lane of each kind at `timeline_frame` as one
1157 /// new group, pushing everything from there on later by its length in1327 /// new group, pushing everything from there on later by its length in
1158 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip1328 /// *every* lane -- the grouped, rippling paste a clipboard does. Mid-clip
@@ -2324,6 +2494,139 @@ mod tests {
2324 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);2494 assert_eq!(shape(&p)[2], vec![clip(0, 0, 3, 0), clip(3, 100, 101, 0)]);
2325 }2495 }
2326 2496
2497+ /// How long `FILE` is, which is what a trim's tail is allowed to reach:
2498+ /// [`three`] cuts up all nine of its frames.
2499+ const SRC: &[u32] = &[9];
2500+
2501+ /// The drag on a clip's tail: it plays less (or more) of its source, nothing
2502+ /// else on the lane moves, and every wall stops the edge rather than
2503+ /// refusing the gesture.
2504+ #[test]
2505+ fn trimming_the_tail_stops_at_every_wall() {
2506+ let mut p = three();
2507+
2508+ // Pulled in: a gap opens behind it and the clip after it stays put.
2509+ assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
2510+ assert_eq!(
2511+ shape(&p)[0],
2512+ vec![clip(0, 0, 3, 0), clip(3, 3, 4, 0), clip(5, 5, 9, 0)]
2513+ );
2514+ assert_eq!(p.timeline_frames(), 9, "a trim ripples nothing");
2515+ assert_eq!(p.map(Lane::V1, 4), None, "the frame it gave up is a gap");
2516+
2517+ // ...and back out, no further than the clip behind it.
2518+ assert!(p.trim(Lane::V1, 1, Edge::End, 8, SRC));
2519+ assert_eq!(shape(&p)[0][1], clip(3, 3, 5, 0), "stopped at the neighbour");
2520+ assert!(!p.trim(Lane::V1, 1, Edge::End, 8, SRC), "already at the wall");
2521+
2522+ // One frame of clip always survives, however far back the pointer went.
2523+ assert!(p.trim(Lane::V1, 1, Edge::End, 0, SRC));
2524+ assert_eq!(shape(&p)[0][1], clip(3, 3, 4, 0));
2525+
2526+ // The last clip has no neighbour, so what stops it is the file: nine
2527+ // frames is nine frames.
2528+ assert!(p.trim(Lane::V1, 2, Edge::End, 7, SRC));
2529+ assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
2530+ assert_eq!(shape(&p)[0][2], clip(5, 5, 9, 0), "back to the whole take");
2531+ assert!(!p.trim(Lane::V1, 2, Edge::End, 9999, SRC), "and no further");
2532+ // A source nobody told us the length of may not grow at all -- an
2533+ // out-point past the end of a file is a save that will not open again.
2534+ assert!(p.trim(Lane::V1, 2, Edge::End, 7, &[]));
2535+ assert!(!p.trim(Lane::V1, 2, Edge::End, 9, &[]), "length unknown");
2536+ }
2537+
2538+ /// The head pulled in takes the in-point with it -- what stays plays what it
2539+ /// always played -- and stops at the source's own first frame.
2540+ #[test]
2541+ fn trimming_the_head_moves_the_in_point() {
2542+ let mut p = three();
2543+ assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
2544+ assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0), "two frames off the front");
2545+ assert_eq!(p.map(Lane::V1, 2), Some((0, 2)), "frame 2 still plays 2");
2546+ assert_eq!(p.map(Lane::V1, 1), None, "and the front is a gap");
2547+ assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "back out again");
2548+ assert_eq!(shape(&p)[0][0], clip(0, 0, 3, 0));
2549+ // One frame survives here too.
2550+ assert!(p.trim(Lane::V1, 0, Edge::Start, 9, SRC));
2551+ assert_eq!(shape(&p)[0][0], clip(2, 2, 3, 0));
2552+
2553+ // A clip that does not begin at its source's first frame: its head goes
2554+ // back to source frame 0 and not one frame further.
2555+ let mut p = Project::single(FILE, 9);
2556+ assert!(p.place(Lane::V1, 5, clip(0, 1, 4, 0)));
2557+ assert!(p.lift(Lane::V1, 0), "nothing in front of it to stop it");
2558+ assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC));
2559+ assert_eq!(shape(&p)[0][0], clip(4, 0, 4, 0), "one frame of head left");
2560+ }
2561+
2562+ /// A clip whose in-point is *past* its own start -- what a ripple delete
2563+ /// leaves, the piece in front of it gone and this one slid back to frame 0
2564+ /// carrying the in-point the cut gave it. Its head has more source behind it
2565+ /// than the timeline has room for, and the timeline's own first frame is the
2566+ /// wall: asking is not an overflow, and the answer is 0.
2567+ #[test]
2568+ fn a_ripple_closed_clip_can_still_be_head_trimmed() {
2569+ let mut p = Project::single(FILE, 9);
2570+ assert!(p.split(5));
2571+ assert!(p.delete_in(Lane::V1, 0), "the first piece goes");
2572+ assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)], "start 0, in-point 5");
2573+
2574+ assert_eq!(
2575+ p.trim_room(Lane::V1, 0, Edge::Start, SRC),
2576+ Some((0, 3)),
2577+ "back to frame 0 at most, and one frame of clip always survives"
2578+ );
2579+ assert!(!p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "already there");
2580+ assert!(p.trim(Lane::V1, 0, Edge::Start, 2, SRC));
2581+ assert_eq!(shape(&p)[0], vec![clip(2, 7, 9, 0)], "the in-point followed");
2582+ assert!(p.trim(Lane::V1, 0, Edge::Start, 0, SRC), "and back out");
2583+ assert_eq!(shape(&p)[0], vec![clip(0, 5, 9, 0)]);
2584+ }
2585+
2586+ /// Linked halves trim as one: a link is one span on however many lanes, so
2587+ /// the sound follows the picture's edge -- and the tightest wall of the two
2588+ /// is what stops both.
2589+ #[test]
2590+ fn linked_halves_trim_together() {
2591+ let mut p = three();
2592+ let link = p.lane(Lane::V1)[2].link.expect("a split hands out ids");
2593+ assert_eq!(p.lane(Lane::A1)[2].link, Some(link), "both halves grouped");
2594+
2595+ assert!(p.trim(Lane::V1, 2, Edge::Start, 7, SRC));
2596+ assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0));
2597+ assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0), "the sound followed");
2598+ assert!(p.trim(Lane::A1, 2, Edge::End, 8, SRC), "either half drags it");
2599+ assert_eq!(shape(&p)[0][2], clip(7, 7, 8, 0), "and the picture follows");
2600+ links_are_consistent(&p.lanes).expect("one id per lane, one span");
2601+
2602+ // Something in the way on the *audio* lane stops the picture's tail as
2603+ // well: the group can only go as far as its tightest member.
2604+ assert!(p.place(Lane::A1, 9, clip(0, 0, 1, 0)));
2605+ assert!(p.trim(Lane::V1, 2, Edge::End, 9999, SRC));
2606+ assert_eq!(shape(&p)[0][2], clip(7, 7, 9, 0), "stopped by A1's clip");
2607+ assert_eq!(shape(&p)[1][2], clip(7, 7, 9, 0));
2608+ links_are_consistent(&p.lanes).expect("still one span");
2609+ }
2610+
2611+ /// A whole drag is one undo step -- the front-end commits once, at the
2612+ /// release -- and an edge asked to stay where it is costs none at all.
2613+ #[test]
2614+ fn a_trim_is_one_undo_step() {
2615+ let mut p = three();
2616+ let before = shape(&p);
2617+ let history = p.history.len();
2618+
2619+ assert!(p.trim(Lane::V1, 1, Edge::End, 4, SRC));
2620+ assert_eq!(p.history.len(), history + 1, "one snapshot per gesture");
2621+ assert!(!p.trim(Lane::V1, 1, Edge::End, 4, SRC), "already there");
2622+ assert!(!p.trim(Lane::V1, 9, Edge::End, 4, SRC), "no such clip");
2623+ assert!(!p.trim(Lane::new(LaneKind::Video, 7), 0, Edge::End, 4, SRC));
2624+ assert_eq!(p.history.len(), history + 1, "a refusal snapshots nothing");
2625+
2626+ assert!(p.undo());
2627+ assert_eq!(shape(&p), before, "both halves back, in one step");
2628+ }
2629+
2327 /// A moved half stays in its group: a link names a span, not a lane, so the2630 /// A moved half stays in its group: a link names a span, not a lane, so the
2328 /// picture on `V2` is still the same take as the sound under it on `A1`.2631 /// picture on `V2` is still the same take as the sound under it on `A1`.
2329 #[test]2632 #[test]
@@ -2754,6 +3057,42 @@ mod tests {
2754 );3057 );
2755 }3058 }
2756 3059
3060+ /// A slider drag is one gesture: the press snapshots, every sample after it
3061+ /// only regrades, and the single undo lands on what the clip was *before*
3062+ /// the hand touched it -- not one step back down the drag.
3063+ #[test]
3064+ fn a_whole_colour_drag_undoes_in_one_step() {
3065+ let mut p = three();
3066+ assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press");
3067+ for n in 2..=8 {
3068+ assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample");
3069+ }
3070+ assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8)));
3071+ assert!(p.undo());
3072+ assert!(
3073+ p.color_of(Lane::V1, 0).is_none(),
3074+ "one undo is the whole gesture, back to ungraded"
3075+ );
3076+
3077+ // The live write refuses what the snapshotting one refuses, and a
3078+ // refusal still costs no history either way.
3079+ assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1))));
3080+ assert!(!p.set_color_live(
3081+ Lane::V1,
3082+ 0,
3083+ Some(ColorParams {
3084+ contrast: f32::NAN,
3085+ ..grade_at(1)
3086+ })
3087+ ));
3088+ assert!(p.undo());
3089+ assert_eq!(
3090+ p.lane(Lane::V1).len(),
3091+ 2,
3092+ "the next step back is the split before the drag: no sample pushed one"
3093+ );
3094+ }
3095+
2757 /// The colour table is append-only within a session, exactly as the eq one3096 /// The colour table is append-only within a session, exactly as the eq one
2758 /// is -- and a save is where an undone grade goes.3097 /// is -- and a save is where an undone grade goes.
2759 #[test]3098 #[test]
crates/engine/tests/saveload.rsmodified+38 -0
@@ -100,6 +100,44 @@ fn a_picked_audio_stream_lands_saves_and_comes_back() {
100 std::fs::remove_dir_all(&dir).expect("cleanup");100 std::fs::remove_dir_all(&dir).expect("cleanup");
101 }101 }
102 102
103+/// Why a trim's tail stops where the file ends: a clip reaching past the last
104+/// frame of its source is a project that will not open again (`open_project`
105+/// refuses it by name). Pulled in on both ends and then dragged out as far as
106+/// the pointer can ask for, the save still comes back as itself.
107+#[test]
108+fn a_trimmed_timeline_saves_and_opens_again() {
109+ use engine::project::Edge;
110+
111+ let dir = scratch("trim");
112+ let media = copy_in(&dir, "test_av.mp4");
113+ let mut session = PlaybackSession::open(&media).expect("open the fixture");
114+ session.set_gain(0.0);
115+ let whole = session.clip_at(0).expect("one clip");
116+
117+ assert!(session.trim_clip(Lane::V1, 0, Edge::End, whole.end() / 2));
118+ assert!(session.trim_clip(Lane::V1, 0, Edge::Start, 5));
119+ let path = dir.join("trimmed.edith");
120+ session.save_project(&path).expect("save");
121+ let loaded = PlaybackSession::open_project(&path).expect("a trimmed project opens");
122+ assert_eq!(
123+ loaded.clip_at(0).map(|c| (c.start, c.in_frame, c.out_frame)),
124+ Some((5, 5, whole.end() / 2)),
125+ "the trimmed range is what came back"
126+ );
127+
128+ // A hand that keeps pulling: the tail stops at the file's own last frame,
129+ // and the save of *that* opens too.
130+ assert!(session.trim_clip(Lane::V1, 0, Edge::End, u32::MAX));
131+ assert_eq!(
132+ session.clip_at(0).expect("still one clip").out_frame,
133+ whole.out_frame,
134+ "as far as the file goes and not one frame further"
135+ );
136+ session.save_project(&path).expect("save");
137+ PlaybackSession::open_project(&path).expect("and it still opens");
138+ std::fs::remove_dir_all(&dir).expect("cleanup");
139+}
140+
103 /// Two files, four clips, one of them deleted, playhead at 3 s -- a timeline141 /// Two files, four clips, one of them deleted, playhead at 3 s -- a timeline
104 /// with something to lose in every field.142 /// with something to lose in every field.
105 fn edited(dir: &Path) -> PlaybackSession {143 fn edited(dir: &Path) -> PlaybackSession {