forge
Explore
Log in

Don't you dare go Hollow

Sliders are dragged and the graded frame is drawn over them

Browse files at this commit

8d8d8808a2dd2437eed1ab3601a66369948e2ffaAhmet Kaan GümüşParent: c3b6ce2
  • feat
    • sliders are dragged and the graded frame is drawn over them
Show full message
✨ feat(colour): sliders are dragged and the graded frame is drawn over them

The colour card loses its stepper buttons: each row's bar is now pressed and
pulled straight to a value, which is what a slider is for. The press takes the
undo step and every sample after it is a live write (`set_color_live`), so a
whole drag is one `z` rather than one per pixel -- and because a live write
reseeks like any other edit, the picture regrades under the hand.

Above the rows, an RGB histogram of the frame on screen: counted off the BGRA
the decoder handed over, which is already through the grade, so pulling
brightness tilts the graph as it moves. Every 253rd pixel of a 1080p frame
(HIST_SAMPLES), 64 bins a channel, square-rooted so a flat black area does not
draw the rest as a line.

The arrow keys still move the same values, on the same 0.05 grid a drag snaps
to, and the bar is 4 px to look at but a whole row to hit.
crates/app/src/main.rsmodified+375 -54
@@ -296,16 +296,37 @@ const COLOR_BANDS: [(&str, f32, f32); 4] = [
296296 ("Tint (cool–warm)", -1., 1.),
297297 ];
298298
299-/// A press of a nudge key or button: a fortieth of a band's range, so a slider
300-/// crosses it in forty presses and every stop is a number the file can write.
299+/// A press of a nudge key: a fortieth of a band's range, so a slider crosses it
300+/// in forty presses and every stop is a number the file can write. A drag lands
301+/// on the same grid ([`Player::drag_color`]), so the pointer and the keyboard
302+/// cannot reach two different sets of values.
301303 const COLOR_STEP: f32 = 0.05;
302304
303-/// The card's width: a slider row is a label, two buttons, the bar and the
304-/// value, and the longest label has to fit beside all four without truncating
305-/// (measured against "Tint (cool–warm)" at 460).
305+/// The card's width: a slider row is a label, the bar and the value, and the
306+/// longest label has to fit beside all three without truncating (measured
307+/// against "Tint (cool–warm)").
306308 const COLOR_W: f32 = 460.;
307-/// How much of a slider row the bar itself gets.
308-const COLOR_BAR_W: f32 = 140.;
309+/// How much of a slider row the bar itself gets -- what a drag is read against,
310+/// so it takes the width the two nudge buttons used to.
311+const COLOR_BAR_W: f32 = 240.;
312+
313+/// The histogram's bins per channel. 64 is four codes of an 8-bit ramp per bin:
314+/// fine enough to see a grade tilt, coarse enough that a subsampled count is
315+/// not noise.
316+const HIST_BINS: usize = 64;
317+
318+/// How many pixels of a frame the histogram reads. The stride is
319+/// `pixels / HIST_SAMPLES` (1920x1080 -> every 253rd pixel), which is a
320+/// thousandth of the frame and walks across columns rather than down one.
321+const HIST_SAMPLES: usize = 8_192;
322+
323+/// The histogram box. Shorter than the equalizer's curve because four slider
324+/// rows stand under it and the card still has to fit a 360 px window.
325+const HIST_H: f32 = 96.;
326+
327+/// What each channel's line is drawn in, in `[r, g, b]` order -- the channel it
328+/// counts, lightened enough to read on the dark box.
329+const HIST_INK: [u32; 3] = [0xE0_5A_5A, 0x5A_D0_7A, 0x5A_9A_E0];
309330
310331 struct Player {
311332 /// The timeline, once there is one. A run with no file opens without it and
@@ -426,9 +447,24 @@ struct Player {
426447 /// there. `None` when it is closed, which is the only place that state
427448 /// lives: the grade itself is the project's.
428449 color_open: Option<(Lane, usize)>,
429- /// Which of the card's four sliders the arrow keys and the buttons move.
430- /// The card's own focus, since nothing in it takes gpui's (ledger:182).
450+ /// Which of the card's four sliders the arrow keys and a drag move. The
451+ /// card's own focus, since nothing in it takes gpui's (ledger:182).
431452 color_band: usize,
453+ /// A slider is being dragged. Tracked on the root like `scrubbing` and the
454+ /// equalizer's drag, for the same reason: a 4 px bar is left by the pointer
455+ /// on the first move and its own listeners then stop firing.
456+ color_dragging: bool,
457+ /// Each slider's box, recorded at prepaint: a mouse listener is handed the
458+ /// window position only, so this is what a press and a drag are read against
459+ /// ([`frac_along`]). One per band, because the press picks the row it landed
460+ /// on and the drag then belongs to that row's range.
461+ color_bars: [Rc<Cell<Bounds<Pixels>>>; COLOR_BANDS.len()],
462+ /// The frame on screen counted into `HIST_BINS` bins per channel -- the
463+ /// *graded* frame, because the grade is applied in the decode worker and
464+ /// what arrives here is already through it. Refilled by every pumped frame,
465+ /// which is what makes the colour card's graph move as a slider is dragged:
466+ /// each live write reseeks, and the reseek's frame is the next count.
467+ histogram: [[u32; HIST_BINS]; 3],
432468 /// The action whose row is waiting for a stroke. The next key that is
433469 /// neither escape nor a lone modifier becomes the whole of what reaches it.
434470 rebinding: Option<ActionId>,
@@ -495,6 +531,12 @@ impl Player {
495531 });
496532 let buf = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra)
497533 .expect("frame buffer sized width*height*4");
534+ // Counted here rather than under `color_open`, because the card
535+ // opens on a frame that was pumped before it: gating this on the
536+ // card would leave its graph flat until something reseeked. A
537+ // thousandth of the pixels, against a conversion that just touched
538+ // all of them.
539+ self.histogram = histogram(buf.as_raw());
498540 let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)]));
499541 if let Some(old) = self.image.replace(next) {
500542 // Every RenderImage gets a fresh id and its own atlas tile:
@@ -718,6 +760,7 @@ impl Player {
718760 Some(clip) => {
719761 self.color_open = Some(clip);
720762 self.color_band = 0;
763+ self.color_dragging = false;
721764 // One card at a time, the rule both the others already follow.
722765 self.keys_open = false;
723766 self.export_open = false;
@@ -744,6 +787,14 @@ impl Player {
744787 /// frame on screen repaints through the new grade; this only owes the flags
745788 /// that reseek clears.
746789 fn set_color(&mut self, params: ColorParams, cx: &mut Context<Self>) {
790+ self.write_color(params, false, cx);
791+ }
792+
793+ /// Both writes: `live` is the one that takes no undo step, which is what
794+ /// every sample *inside* a drag goes through
795+ /// (`PlaybackSession::set_color_live`). Either way the engine reseeks, so
796+ /// the picture -- and the histogram counted off it -- is regraded at once.
797+ fn write_color(&mut self, params: ColorParams, live: bool, cx: &mut Context<Self>) {
747798 let Some((lane, idx)) = self.color_open else {
748799 return;
749800 };
@@ -751,7 +802,11 @@ impl Player {
751802 return;
752803 };
753804 let grade = Some(params).filter(|p| !p.is_identity());
754- if session.set_color(lane, idx, grade) {
805+ let took = match live {
806+ true => session.set_color_live(lane, idx, grade),
807+ false => session.set_color(lane, idx, grade),
808+ };
809+ if took {
755810 self.reset_after_reseek();
756811 }
757812 cx.notify();
@@ -767,6 +822,35 @@ impl Player {
767822 self.set_color(params, cx);
768823 }
769824
825+ /// Where the pointer sits along a slider, as that band's value: the left end
826+ /// of the bar is the bottom of its range and the right end the top. Called
827+ /// on every pointer sample, so the grade -- and the picture, and the
828+ /// histogram over it -- moves under the hand.
829+ ///
830+ /// `first` is the press: it takes the undo step the whole gesture rolls back
831+ /// to, and every sample after it is live. That is why it writes even when
832+ /// the value did not change -- without that snapshot the rest of the drag
833+ /// would be unundoable.
834+ ///
835+ /// Values land on the [`COLOR_STEP`] grid the keys use, which also bounds
836+ /// one drag to forty-odd entries in the project's colour table.
837+ ///
838+ /// ponytail: one reseek per step crossed, up to ~40 for a bar-wide sweep. If
839+ /// that ever stutters, the throttle is [`scrub_due`]'s, which the ruler drag
840+ /// already uses for the same cost.
841+ fn drag_color(&mut self, x: Pixels, first: bool, cx: &mut Context<Self>) {
842+ let (_, low, high) = COLOR_BANDS[self.color_band];
843+ let along = frac_along(x, self.color_bars[self.color_band].get());
844+ let value = color_snap(low + along * (high - low)).clamp(low, high);
845+ let mut params = self.color_params();
846+ let at = band_mut(&mut params, self.color_band);
847+ if *at == value && !first {
848+ return;
849+ }
850+ *at = value;
851+ self.write_color(params, !first, cx);
852+ }
853+
770854 /// Whether a card owns the window. While one does the timeline under it is
771855 /// out of reach, so a right-click there opens no menu -- the same rule the
772856 /// key handler and the drop target already follow.
@@ -1831,7 +1915,10 @@ impl Render for Player {
18311915 // the keys menu still lists them.
18321916 if this.color_open.is_some() {
18331917 match color_key(key) {
1834- Some(ColorKey::Close) => this.color_open = None,
1918+ Some(ColorKey::Close) => {
1919+ this.color_open = None;
1920+ this.color_dragging = false;
1921+ }
18351922 Some(ColorKey::Band(step)) => {
18361923 this.color_band = (this.color_band + step) % COLOR_BANDS.len();
18371924 }
@@ -1899,6 +1986,17 @@ impl Render for Player {
18991986 }
19001987 return;
19011988 }
1989+ // A colour slider is 4 px tall and the pointer leaves it just as
1990+ // fast; every sample is live, so the release owes no write of
1991+ // its own -- what the last sample set is what the clip carries.
1992+ if this.color_dragging {
1993+ if event.pressed_button == Some(MouseButton::Left) {
1994+ this.drag_color(event.position.x, false, cx);
1995+ } else {
1996+ this.color_dragging = false;
1997+ }
1998+ return;
1999+ }
19022000 if !this.scrubbing {
19032001 return;
19042002 }
@@ -1921,6 +2019,13 @@ impl Render for Player {
19212019 this.commit_eq(cx);
19222020 return;
19232021 }
2022+ if std::mem::take(&mut this.color_dragging) {
2023+ // The release lands exactly where the hand let go, and
2024+ // it is a live write like every other sample: the undo
2025+ // step the gesture rolls back to was the press's.
2026+ this.drag_color(event.position.x, false, cx);
2027+ return;
2028+ }
19242029 if std::mem::take(&mut this.scrubbing) {
19252030 this.scrub_to(event.position.x, true, cx);
19262031 }
@@ -3076,14 +3181,17 @@ impl Player {
30763181 )
30773182 }
30783183
3079- /// The colour card: a row per control, each showing where in its range it
3080- /// stands and carrying the pair of buttons that move it -- the same move the
3081- /// arrow keys make, because a control only the pointer can reach is not one
3082- /// everyone can reach. Same scrim, surface and row shape as the other two
3083- /// cards, and the same plain divs, so the root keeps the keyboard.
3184+ /// The colour card: the graded frame's histogram over a row per control,
3185+ /// each row a bar the pointer drags straight to a value -- no stepper
3186+ /// buttons, because a slider is a thing to pull, and the arrow keys still
3187+ /// move the same value for anyone not using a pointer. Same scrim, surface
3188+ /// and row shape as the other two cards, and the same plain divs, so the
3189+ /// root keeps the keyboard.
30843190 ///
30853191 /// The values are read from the project every render: what is drawn is what
3086- /// the decoder is grading with, never a copy that could drift from it.
3192+ /// the decoder is grading with, never a copy that could drift from it. The
3193+ /// graph above them is counted off the frame that came *back* through that
3194+ /// grade ([`histogram`]), so pulling exposure tilts it while the hand moves.
30873195 fn color_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
30883196 let (lane, idx) = self.color_open?;
30893197 let params = self.color_params();
@@ -3095,26 +3203,6 @@ impl Player {
30953203 let value = *band_mut(&mut read, i);
30963204 let frac = ((value - low) / (high - low)).clamp(0., 1.);
30973205 let picked = i == self.color_band;
3098- // Both buttons of a row do what the arrows do, so there is one
3099- // rule for what a press is worth and one place it is clamped.
3100- let step = |name: &'static str, steps: f32| {
3101- div()
3102- .id((name, i))
3103- .w(px(CONTROL_H))
3104- .h(px(CONTROL_H))
3105- .flex()
3106- .items_center()
3107- .justify_center()
3108- .rounded(px(3.))
3109- .bg(rgb(CHROME))
3110- .cursor_pointer()
3111- .hover(|s| s.bg(rgb(HOVER)))
3112- .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
3113- this.color_band = i;
3114- this.nudge_color(steps, cx);
3115- }))
3116- .child(if steps < 0. { "–" } else { "+" })
3117- };
31183206 div()
31193207 .id(("color-row", i))
31203208 .flex()
@@ -3131,22 +3219,43 @@ impl Player {
31313219 cx.notify();
31323220 }))
31333221 .child(div().flex_1().min_w(px(0.)).truncate().child(label))
3134- .child(step("color-down", -1.))
31353222 .child(
3223+ // The bar is 4 px to look at and a whole row to hit
3224+ // (WCAG 2.5.8), the same split the ruler makes between
3225+ // what is drawn and what is grabbed. The press is
3226+ // already the first sample of the drag, so a plain click
3227+ // sets the value it landed on.
31363228 div()
3229+ .id(("color-bar", i))
3230+ .relative()
31373231 .w(px(COLOR_BAR_W))
3138- .h(px(4.))
3139- .rounded(px(2.))
3140- .bg(rgb(CHROME))
3232+ .h(px(KEYS_ROW_H))
3233+ .flex()
3234+ .items_center()
3235+ .on_mouse_down(
3236+ MouseButton::Left,
3237+ cx.listener(move |this, event: &MouseDownEvent, _, cx| {
3238+ this.color_band = i;
3239+ this.color_dragging = true;
3240+ this.drag_color(event.position.x, true, cx);
3241+ }),
3242+ )
3243+ .child(bounds_probe(self.color_bars[i].clone()))
31413244 .child(
31423245 div()
3143- .h_full()
3144- .w(relative(frac))
3246+ .w_full()
3247+ .h(px(4.))
31453248 .rounded(px(2.))
3146- .bg(rgb(ACCENT)),
3249+ .bg(rgb(CHROME))
3250+ .child(
3251+ div()
3252+ .h_full()
3253+ .w(relative(frac))
3254+ .rounded(px(2.))
3255+ .bg(rgb(ACCENT)),
3256+ ),
31473257 ),
31483258 )
3149- .child(step("color-up", 1.))
31503259 .child(
31513260 div()
31523261 .w(px(44.))
@@ -3187,7 +3296,22 @@ impl Player {
31873296 .px(px(6.))
31883297 .text_size(px(11.))
31893298 .text_color(rgb(INK_DIM))
3190- .child("↑↓ picks a slider, ←→ moves it, r resets — esc closes"),
3299+ .child(
3300+ "drag a bar, or ↑↓ picks one and ←→ moves it, r resets — esc closes",
3301+ ),
3302+ )
3303+ // The frame as it is being graded, over the controls
3304+ // grading it: the three lines are what the picture is
3305+ // made of, and every sample of a drag reseeks, so they
3306+ // move with the bar under the hand.
3307+ .child(
3308+ div()
3309+ .flex_none()
3310+ .h(px(HIST_H))
3311+ .rounded(px(3.))
3312+ .bg(rgb(HOVER_DIM))
3313+ .relative()
3314+ .child(hist_curves(self.histogram)),
31913315 )
31923316 .children(rows)
31933317 .child(
@@ -4683,6 +4807,73 @@ fn frac_down(y: Pixels, bounds: Bounds<Pixels>) -> f32 {
46834807 ((y - bounds.top()) / bounds.size.height).clamp(0., 1.)
46844808 }
46854809
4810+/// A slider value on the [`COLOR_STEP`] grid: what a drag rounds to, so the
4811+/// pointer stops where the arrow keys do and "0.35" on screen is the number the
4812+/// file writes rather than a rounding of one.
4813+fn color_snap(value: f32) -> f32 {
4814+ (value / COLOR_STEP).round() * COLOR_STEP
4815+}
4816+
4817+/// How the frame on screen is spread across the tone range: `HIST_BINS` counts
4818+/// per channel, read off the BGRA the decoder handed over -- which is the
4819+/// *graded* picture, because the grade is folded into the conversion
4820+/// (`engine::convert::i420_to_bgra_with`). So what this counts is what the eye
4821+/// is looking at, and moving a slider moves it.
4822+///
4823+/// Every [`HIST_SAMPLES`]th-of-a-frame pixel, not every pixel: a shape drawn
4824+/// from eight thousand samples is the same shape, at a thousandth of the reads.
4825+fn histogram(bgra: &[u8]) -> [[u32; HIST_BINS]; 3] {
4826+ let pixels = bgra.len() / 4;
4827+ let stride = (pixels / HIST_SAMPLES).max(1);
4828+ let mut bins = [[0u32; HIST_BINS]; 3];
4829+ for p in (0..pixels).step_by(stride) {
4830+ let px = &bgra[p * 4..];
4831+ // BGRA on the wire, `[r, g, b]` in the bins: the graph names channels
4832+ // the way a person does.
4833+ for (channel, value) in [px[2], px[1], px[0]].into_iter().enumerate() {
4834+ bins[channel][usize::from(value) * HIST_BINS / 256] += 1;
4835+ }
4836+ }
4837+ bins
4838+}
4839+
4840+/// The three counts drawn as three lines across the box, tallest bin to the top.
4841+///
4842+/// Square root, not linear: a shot with a big flat area (a night sky, a title
4843+/// card) puts one bin so far above the rest that a linear graph is a single
4844+/// spike beside a flat line, and the tilt a grade puts in the rest is exactly
4845+/// what the card is for.
4846+fn hist_curves(bins: [[u32; HIST_BINS]; 3]) -> impl IntoElement {
4847+ canvas(
4848+ |_, _, _| (),
4849+ move |bounds, _, window, _| {
4850+ let (o, s) = (bounds.origin, bounds.size);
4851+ // Shared across the channels, so their relative weight is readable;
4852+ // never zero, so an unpumped (all-zero) histogram is a flat line
4853+ // rather than a division by nothing.
4854+ let top = bins.iter().flatten().copied().max().unwrap_or(0).max(1) as f32;
4855+ for (channel, counts) in bins.iter().enumerate() {
4856+ let mut path = PathBuilder::stroke(px(1.5));
4857+ for (bin, &count) in counts.iter().enumerate() {
4858+ let at = point(
4859+ o.x + s.width * (bin as f32 / (HIST_BINS - 1) as f32),
4860+ o.y + s.height * (1. - (count as f32 / top).sqrt()),
4861+ );
4862+ match bin {
4863+ 0 => path.move_to(at),
4864+ _ => path.line_to(at),
4865+ }
4866+ }
4867+ if let Ok(path) = path.build() {
4868+ window.paint_path(path, rgb(HIST_INK[channel]));
4869+ }
4870+ }
4871+ },
4872+ )
4873+ .absolute()
4874+ .size_full()
4875+}
4876+
46864877 /// The cascade's frequency response, drawn as one line across the graph.
46874878 ///
46884879 /// Every point comes from `EqParams::response_db`, which reads the very
@@ -4788,17 +4979,18 @@ fn timecode(t: f64, fps: f64) -> String {
47884979 #[cfg(test)]
47894980 mod tests {
47904981 use super::{
4791- ACCENT, CONTROL_H, Clip, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE,
4792- EQ_TICKS, EXPORT_ROWS_H, FORMATS, Format, HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM,
4982+ ACCENT, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, EQ_FREQ_HIGH,
4983+ EQ_FREQ_LOW, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_TICKS, EXPORT_ROWS_H, FORMATS,
4984+ Format, HEADER_GAP, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, INK, INK_DIM,
47934985 KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX,
47944986 LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H,
47954987 RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume,
4796- WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, cancels_export, envelope, eq_x,
4797- eq_y, export_path, export_settings, format_line, frac_along, frac_down, frame_at,
4798- is_bare_modifier, is_project, keymap, lane_clips, lanes_h, marked, menu_at, mp4_refusal,
4799- normalise, panel_h, project_path, push_digit, retarget, scrub_due, show_label,
4800- source_frames, source_tint, start_frac, timecode, unseen_paths, unseen_sources, whole_take,
4801- width_frac, window_title,
4988+ WAVE_BPS, WAVE_COL, Wave, applicable, band_label, can_add, cancels_export, color_snap,
4989+ envelope, eq_x, eq_y, export_path, export_settings, format_line, frac_along, frac_down,
4990+ frame_at, histogram, is_bare_modifier, is_project, keymap, lane_clips, lanes_h, marked,
4991+ menu_at, mp4_refusal, normalise, panel_h, project_path, push_digit, retarget, scrub_due,
4992+ show_label, source_frames, source_tint, start_frac, timecode, unseen_paths, unseen_sources,
4993+ whole_take, width_frac, window_title,
48024994 };
48034995 use super::{file_name, file_uri, library_rows};
48044996
@@ -5712,6 +5904,130 @@ mod tests {
57125904 assert!(KEYS_ROW_H >= HIT_MIN);
57135905 }
57145906
5907+ /// A colour slider is dragged straight to a value, so where the pointer
5908+ /// lands and where the bar then paints have to be the same place: this is
5909+ /// the round trip [`Player::drag_color`] makes, pixels -> value -> fill.
5910+ #[test]
5911+ fn a_colour_drag_lands_where_it_paints_and_the_card_fits_the_smallest_window() {
5912+ // A bar as laid out, somewhere that is not the window's origin -- a
5913+ // mapping that forgot the offset would pass at zero.
5914+ let bar = Bounds {
5915+ origin: point(px(180.), px(240.)),
5916+ size: size(px(COLOR_BAR_W), px(KEYS_ROW_H)),
5917+ };
5918+ for &(label, low, high) in &COLOR_BANDS {
5919+ // The ends are the ends: the left of the bar is the bottom of the
5920+ // range and the right is the top, so a slider can be pulled to
5921+ // either without hunting for the last pixel.
5922+ let at = |x: f32| color_snap(low + frac_along(px(x), bar) * (high - low));
5923+ assert_eq!(at(180.), low, "{label} left end");
5924+ assert_eq!(at(180. + COLOR_BAR_W), high, "{label} right end");
5925+ // Off either end clamps rather than running past the range.
5926+ assert_eq!(at(-4000.), low, "{label} off the left");
5927+ assert_eq!(at(9999.), high, "{label} off the right");
5928+
5929+ for step in 0..=48 {
5930+ let along = step as f32 / 48.;
5931+ let value = at(180. + along * COLOR_BAR_W);
5932+ // Every stop is one the keyboard can also reach, which is what
5933+ // keeps "0.35" the number the file writes.
5934+ let steps = value / COLOR_STEP;
5935+ assert!(
5936+ (steps - steps.round()).abs() < 1e-3,
5937+ "{label}: {value} is off the {COLOR_STEP} grid"
5938+ );
5939+ assert!(
5940+ (low..=high).contains(&value),
5941+ "{label}: {value} outside {low}..{high}"
5942+ );
5943+ // What the row paints from that value is where the pointer was,
5944+ // to within the half step the snap costs.
5945+ let painted = (value - low) / (high - low);
5946+ let slack = COLOR_STEP / (high - low) / 2. + 1e-4;
5947+ assert!(
5948+ (painted - along).abs() <= slack,
5949+ "{label}: pressed at {along}, paints at {painted}"
5950+ );
5951+ }
5952+ }
5953+
5954+ // The same shape as the other two cards, so it fits where they do: the
5955+ // graph, four rows and the reset button inside a 360 px window.
5956+ let (title, status, gaps, padding) = (17., 17., 6. * 2., 24.);
5957+ let rows = COLOR_BANDS.len() as f32 * KEYS_ROW_H;
5958+ assert!(
5959+ title + status + HIST_H + rows + gaps + padding + CONTROL_H + 4. <= 360.,
5960+ "card too tall"
5961+ );
5962+ assert!(COLOR_W <= 640., "card too wide");
5963+ // The label still has room beside the bar and the readout, which is
5964+ // what the buttons coming off the row bought.
5965+ let row = COLOR_W - padding - 12. - 2. * 8. - COLOR_BAR_W - 44.;
5966+ assert!(row >= LABEL_MIN_W, "no room left for a label: {row}px");
5967+ // What is dragged is the whole row's height, not the 4 px the bar is
5968+ // drawn as (WCAG 2.5.8) -- the same split the ruler makes.
5969+ assert!(KEYS_ROW_H >= HIT_MIN);
5970+ }
5971+
5972+ /// The graph over the sliders is the frame the grade already went through,
5973+ /// so it has to count what is actually in those bytes -- BGRA on the wire,
5974+ /// red-green-blue in the bins.
5975+ #[test]
5976+ fn the_histogram_counts_the_frame_it_is_handed() {
5977+ // Half pure red, half mid grey: two known values, in two known bins.
5978+ let (w, h) = (64usize, 64usize);
5979+ let mut frame = Vec::with_capacity(w * h * 4);
5980+ for _ in 0..h {
5981+ for col in 0..w {
5982+ match col < w / 2 {
5983+ true => frame.extend_from_slice(&[0, 0, 255, 255]),
5984+ false => frame.extend_from_slice(&[128, 128, 128, 255]),
5985+ }
5986+ }
5987+ }
5988+ let bins = histogram(&frame);
5989+ let half = (w * h / 2) as u32;
5990+ // 64 bins over 256 codes: 255 is the last bin, 128 the middle one, 0 the
5991+ // first.
5992+ assert_eq!(bins[0][63], half, "the red half tops the red channel");
5993+ assert_eq!(bins[0][32], half, "and the grey half sits mid red");
5994+ for channel in [1, 2] {
5995+ assert_eq!(bins[channel][0], half, "no green or blue in the red half");
5996+ assert_eq!(bins[channel][32], half);
5997+ assert_eq!(bins[channel][63], 0);
5998+ }
5999+ // Nothing is counted twice and nothing is dropped: this frame is small
6000+ // enough to be read whole.
6001+ for channel in bins {
6002+ assert_eq!(channel.iter().sum::<u32>(), (w * h) as u32);
6003+ }
6004+
6005+ // A grade shifts it, which is the whole point of drawing it: the same
6006+ // frame darkened lands in lower bins.
6007+ let darker: Vec<u8> = frame.iter().map(|b| b / 2).collect();
6008+ let bins = histogram(&darker);
6009+ assert_eq!(bins[0][31], half, "255 -> 127");
6010+ assert_eq!(bins[0][16], half, "128 -> 64");
6011+
6012+ // A real frame is subsampled: a 1080p one is read every 253rd pixel, so
6013+ // the shape costs a thousandth of the reads and still counts thousands.
6014+ let big = vec![200u8; 1920 * 1080 * 4];
6015+ let bins = histogram(&big);
6016+ let counted = bins[0].iter().sum::<u32>();
6017+ let pixels = 1920 * 1080usize;
6018+ let expected = pixels.div_ceil(pixels / HIST_SAMPLES) as u32;
6019+ assert_eq!(counted, expected, "every strided pixel counted, once");
6020+ assert!(
6021+ (HIST_SAMPLES as u32..=HIST_SAMPLES as u32 + 64).contains(&counted),
6022+ "{counted} samples is not the budget"
6023+ );
6024+ assert_eq!(bins[0][200 * HIST_BINS / 256], counted, "all in one bin");
6025+
6026+ // An empty buffer is a flat graph rather than a panic: the card is open
6027+ // before the first frame is pumped.
6028+ assert_eq!(histogram(&[]), [[0; HIST_BINS]; 3]);
6029+ }
6030+
57156031 /// Mute and level are one control with two states, and the whole point is
57166032 /// that mute keeps the level: the user gets back what they had, not 100%.
57176033 #[test]
@@ -6244,6 +6560,11 @@ fn main() {
62446560 eq_graph: Rc::default(),
62456561 color_open: None,
62466562 color_band: 0,
6563+ color_dragging: false,
6564+ color_bars: std::array::from_fn(|_| Rc::default()),
6565+ // Empty until the first frame is pumped, which draws as a
6566+ // flat line rather than as a shape nothing measured.
6567+ histogram: [[0; HIST_BINS]; 3],
62476568 // What an export is until someone says otherwise: the
62486569 // bitrate the picture asks for.
62496570 quality: Quality::Auto,
crates/engine/src/playback.rsmodified+8 -0
@@ -624,6 +624,14 @@ impl PlaybackSession {
624624 self.edit(|p| p.set_color(lane, idx, params))
625625 }
626626
627+ /// The same grade and the same reseek without the undo step
628+ /// ([`Project::set_color_live`]): what the samples inside one slider drag go
629+ /// through, so the frame regrades under the hand and the whole gesture is
630+ /// still a single `z`.
631+ pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
632+ self.edit(|p| p.set_color_live(lane, idx, params))
633+ }
634+
627635 /// The project's resolution: what every clip is composed onto, what the
628636 /// window is sized to and what an export writes -- *not* any one file's.
629637 /// It starts as source 0's picture, which is what a project meant before it
crates/engine/src/project.rsmodified+57 -1
@@ -633,6 +633,24 @@ impl Project {
633633 /// (and no history) for an index that is not there or a value that is not
634634 /// finite, and equal settings share a table entry.
635635 pub fn set_color(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
636+ self.write_color(lane, idx, params, true)
637+ }
638+
639+ /// [`set_color`](Self::set_color) without the undo step: the samples *inside*
640+ /// one pointer drag, whose first write (a plain `set_color`) already took the
641+ /// snapshot the gesture rolls back to. A drag across a slider is one undo,
642+ /// not one per pixel -- and undoing it lands where the hand picked it up.
643+ pub fn set_color_live(&mut self, lane: Lane, idx: usize, params: Option<ColorParams>) -> bool {
644+ self.write_color(lane, idx, params, false)
645+ }
646+
647+ fn write_color(
648+ &mut self,
649+ lane: Lane,
650+ idx: usize,
651+ params: Option<ColorParams>,
652+ snapshot: bool,
653+ ) -> bool {
636654 if idx >= self.lane(lane).len() {
637655 return false;
638656 }
@@ -655,7 +673,9 @@ impl Project {
655673 })
656674 }
657675 };
658- self.snapshot();
676+ if snapshot {
677+ self.snapshot();
678+ }
659679 self.lane_mut(lane).expect("checked above")[idx].color = slot;
660680 true
661681 }
@@ -2514,6 +2534,42 @@ mod tests {
25142534 );
25152535 }
25162536
2537+ /// A slider drag is one gesture: the press snapshots, every sample after it
2538+ /// only regrades, and the single undo lands on what the clip was *before*
2539+ /// the hand touched it -- not one step back down the drag.
2540+ #[test]
2541+ fn a_whole_colour_drag_undoes_in_one_step() {
2542+ let mut p = three();
2543+ assert!(p.set_color(Lane::V1, 0, Some(grade_at(1))), "the press");
2544+ for n in 2..=8 {
2545+ assert!(p.set_color_live(Lane::V1, 0, Some(grade_at(n))), "a sample");
2546+ }
2547+ assert_eq!(p.color_of(Lane::V1, 0), Some(&grade_at(8)));
2548+ assert!(p.undo());
2549+ assert!(
2550+ p.color_of(Lane::V1, 0).is_none(),
2551+ "one undo is the whole gesture, back to ungraded"
2552+ );
2553+
2554+ // The live write refuses what the snapshotting one refuses, and a
2555+ // refusal still costs no history either way.
2556+ assert!(!p.set_color_live(Lane::V1, 99, Some(grade_at(1))));
2557+ assert!(!p.set_color_live(
2558+ Lane::V1,
2559+ 0,
2560+ Some(ColorParams {
2561+ contrast: f32::NAN,
2562+ ..grade_at(1)
2563+ })
2564+ ));
2565+ assert!(p.undo());
2566+ assert_eq!(
2567+ p.lane(Lane::V1).len(),
2568+ 2,
2569+ "the next step back is the split before the drag: no sample pushed one"
2570+ );
2571+ }
2572+
25172573 /// The colour table is append-only within a session, exactly as the eq one
25182574 /// is -- and a save is where an undone grade goes.
25192575 #[test]