forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

timeline_math.rs963 lines, 41.4 KiBHistoryRawDownload
1//! The timeline's arithmetic: takes, trims, snapping and envelopes.
2
3use crate::*;
4
5/// Whether this clip is a whole take, i.e. whether deleting it may close the
6/// hole under it: a take is what the first pair of lanes carries between them,
7/// `V1`'s picture and the sound grouped with it, and dropping one moves the
8/// frames after it on every lane. A caption a hand grouped with the clip
9/// counts as its partner too: the group is what pairs, not the lane's kind --
10/// and a group answers `true` from *whichever* member's lane the question is
11/// asked from, added row or not, because a grouped delete
12/// ([`PlaybackSession::delete_clip`] -> `Project::delete_members`) closes
13/// every member's own lane by its own span already, not just the first pair's.
14///
15/// Everything else is a half or a layer, and is *lifted* instead: a half whose
16/// picture was lifted (what a lift leaves behind) has no take to ripple, and an
17/// *ungrouped* clip on a further lane is laid over the timeline rather than
18/// part of it -- closing a hole under it would drag the take beneath out of
19/// step with it.
20pub(crate) fn whole_take(session: &PlaybackSession, lane: Lane, idx: usize) -> bool {
21 let Some(clip) = session.lane_clips(lane).get(idx) else {
22 return false;
23 };
24 let paired = || {
25 session
26 .lanes()
27 .into_iter()
28 .filter(|&other| other != lane)
29 .flat_map(|other| {
30 let clips = session.lane_clips(other).iter().map(|c| c.link);
31 let subs = session.sub_lane(other).iter().map(|s| s.link);
32 clips.chain(subs)
33 })
34 .any(|link| link.is_some() && link == clip.link)
35 };
36 match (lane.kind, lane.ord) {
37 // A clip a hand grouped closes its own lane wherever it sits:
38 // `Project::delete_members` already cuts every member's own span out
39 // of its own lane, whichever lanes those are -- so a caption or clip
40 // grouped onto an added row closes its hole exactly as `V1`/`A1`'s
41 // first pair does, not just the pair itself.
42 _ if paired() => true,
43 (_, 1..) => false,
44 // The picture of a take -- unless the take has been taken apart: a
45 // detached picture (a group id no other lane carries, which is also what
46 // a lift of the sound leaves) is a half like the sound is, and a ripple
47 // under it would drag away the very half it was detached from. A clip in
48 // no group at all is not a half but a placement, and on `V1` a placement
49 // is the take there is.
50 (LaneKind::Video, _) => clip.link.is_none(),
51 // The sound of a take, only while the take is still there: its group is
52 // carried by a clip on some other lane. Reached only when `paired()` is
53 // already false, so this is always false -- kept as its own arm for the
54 // reason a lone `A1` clip is not a take, not because it does the work.
55 (LaneKind::Audio, _) => false,
56 // A subtitle lane carries no `Clip` at all, so the lookup above already
57 // returned: never a take, and never rippled as one.
58 (LaneKind::Subtitle, _) => false,
59 }
60}
61
62/// The clip a Group would pair this one with: the first clip on another track,
63/// in the order the lanes are drawn, covering exactly the same frames and not in
64/// this clip's group already. Exactly the same frames because that is all a
65/// group id can mean (engine `links_are_consistent`), which is what leaves
66/// nothing for a second click to choose. `None` when no track has one, and the
67/// notice says so.
68pub(crate) fn span_partner(
69 session: &PlaybackSession,
70 lane: Lane,
71 idx: usize,
72) -> Option<(Lane, usize)> {
73 let clip = *session.lane_clips(lane).get(idx)?;
74 let matches = |other: Lane| {
75 let i = session.lane_clips(other).iter().position(|c| {
76 (c.start, c.end()) == (clip.start, clip.end())
77 && !(c.link.is_some() && c.link == clip.link)
78 })?;
79 Some((other, i))
80 };
81 // Sound before picture (and picture before sound): "group this" means the
82 // other half of the take, and a project whose audio lane was added after a
83 // second video one has that half *after* the layer in storage order -- which
84 // is the order the lanes come in. A same-kind lane is still groupable (V1
85 // and V2 may be one take), but only where no opposite one covers the span.
86 let (opposite, same): (Vec<Lane>, Vec<Lane>) = session
87 .lanes()
88 .into_iter()
89 .filter(|&other| other != lane)
90 .partition(|other| other.kind != lane.kind);
91 opposite.into_iter().chain(same).find_map(matches)
92}
93
94/// What the timeline has picked: every clip and caption a hand ctrl-clicked
95/// into the selection, in click order and with no two the same. The last of
96/// them is the [`anchor`](Selection::anchor) -- the one every action that is
97/// about *one* thing (delete, lift, copy, the equalizer) acts on -- and the
98/// whole list is what a manual Group names to the engine.
99///
100/// Indices move under every edit, exactly as the single mark this replaces
101/// did, so every edit that renumbers a lane clears the picks it cannot keep
102/// honest. Pure and engine-free, so a test can build one without a window.
103#[derive(Clone, Debug, Default, PartialEq)]
104pub(crate) struct Selection {
105 /// `(lane, index into that lane's own list)` -- a subtitle lane's index
106 /// space for a caption, exactly the pair a click was told about.
107 picks: Vec<(Lane, usize)>,
108}
109
110impl Selection {
111 /// Nothing picked: what the timeline starts as and what an edit that moved
112 /// indices leaves behind.
113 pub(crate) fn new() -> Self {
114 Self::default()
115 }
116
117 /// The one a plain click and every selection key leave: the whole of the
118 /// selection, one pick. A click names a thing, and the things it had been
119 /// naming along with it are no longer named.
120 pub(crate) fn set_one(&mut self, pick: (Lane, usize)) {
121 self.picks.clear();
122 self.picks.push(pick);
123 }
124
125 /// A ctrl-click: the pick joins the selection if it was not in it and
126 /// leaves if it was -- the toggle that assembles a group by hand. The
127 /// order is the order they were picked in, and the anchor rides on it.
128 pub(crate) fn toggle(&mut self, pick: (Lane, usize)) {
129 match self.picks.iter().position(|&p| p == pick) {
130 Some(at) => {
131 self.picks.remove(at);
132 }
133 None => self.picks.push(pick),
134 }
135 }
136
137 /// The last pick: what "the selected clip" is to every action that acts on
138 /// one thing. The click order puts it under the hand, which is where the
139 /// eye is.
140 pub(crate) fn anchor(&self) -> Option<(Lane, usize)> {
141 self.picks.last().copied()
142 }
143
144 /// Whether `pick` is one of the selection's -- the question a right-click
145 /// asks before it decides whether the menu is about the selection or
146 /// about the clip under it.
147 pub(crate) fn contains(&self, pick: (Lane, usize)) -> bool {
148 self.picks.contains(&pick)
149 }
150
151 /// Every pick, in click order: what a manual Group names to the engine.
152 pub(crate) fn picks(&self) -> &[(Lane, usize)] {
153 &self.picks
154 }
155
156 pub(crate) fn is_empty(&self) -> bool {
157 self.picks.is_empty()
158 }
159
160 /// A pick that joins without disturbing the rest -- Select All's builder,
161 /// which names every placement there is and cannot be a `set_one`.
162 pub(crate) fn add(&mut self, pick: (Lane, usize)) {
163 if !self.picks.contains(&pick) {
164 self.picks.push(pick);
165 }
166 }
167}
168
169/// The lane stack's thumb over a track `h` px tall: `(y, height)` of the box
170/// standing for the visible share of a stack `content` px tall in a box
171/// `box_h` px tall, taken down by `scrolled` px. Full track when the whole
172/// stack is on screen, never shorter than
173/// [`SCROLL_THUMB_MIN`] when it is not, and never off the track either way.
174pub(crate) fn lanes_thumb(track: f32, content: f32, box_h: f32, scrolled: f32) -> (f32, f32) {
175 if track <= 0. || content <= 0. || box_h >= content {
176 return (0., track.max(0.));
177 }
178 let height = (track * box_h / content).clamp(SCROLL_THUMB_MIN, track);
179 let y = (scrolled / (content - box_h) * (track - height)).clamp(0., track - height);
180 (y, height)
181}
182
183impl Selection {
184 pub(crate) fn len(&self) -> usize {
185 self.picks.len()
186 }
187
188 pub(crate) fn clear(&mut self) {
189 self.picks.clear();
190 }
191}
192
193/// Whether a click marks this box: any pick on it always, and any box sharing
194/// a group id with a pick -- the clip the anchor was ctrl-clicked beside, and
195/// the caption a hand pinned to a clip. A group whose only member is picked
196/// marks that member alone, which is what makes a detached half separately
197/// deletable.
198///
199/// `pick_links` are the group ids of the picks themselves, read by the caller
200/// off the session in the same order as `picks` -- the one fact this pure
201/// question cannot know.
202pub(crate) fn marked(
203 here: (Lane, usize),
204 link: Option<u32>,
205 picks: &[(Lane, usize)],
206 pick_links: &[Option<u32>],
207) -> bool {
208 picks.contains(&here) || (link.is_some() && pick_links.contains(&link))
209}
210
211/// The clip a trim is *showing*, worked out the way `Project::trim` will write
212/// it: the timeline room the edge leaves is turned into source frames by the one
213/// conversion that exists for it ([`Speed::fit`]), and the box is drawn from
214/// that. The preview and the commit are then the same arithmetic -- a box let go
215/// of stays where the hand left it at every rate. Assigning the timeline count
216/// straight to the source field, as this used to, drew a speeded clip's tail
217/// moving at the wrong rate (it snapped on release) and drew a *head* trim
218/// moving the clip's other edge, since the length it implied was not the length
219/// the release would commit.
220///
221/// A still grows forward from source frame 0 instead: every frame of it is the
222/// same picture, so there is no earlier one for an in-point to walk back to.
223///
224/// Room too narrow to hold one source frame is the edit the engine refuses, and
225/// the box is drawn unchanged rather than as something that will not be
226/// committed.
227pub(crate) fn trimmed_clip(clip: Clip, edge: Edge, to: u32, still: bool) -> Clip {
228 // An edge that has not moved is not an edit, and `Project::trim` refuses it
229 // as one: the press that starts a drag must draw the clip it pressed, not a
230 // clip a rounding narrower.
231 if to
232 == match edge {
233 Edge::Start => clip.start,
234 Edge::End => clip.end(),
235 }
236 {
237 return clip;
238 }
239 match edge {
240 Edge::Start => {
241 // What survives is measured from the *end* -- the frames that stay
242 // play what they always played, which is what makes this a trim.
243 let Some(keep) = clip.speed.fit(clip.end().saturating_sub(to)) else {
244 return clip;
245 };
246 match still {
247 true => Clip {
248 fade_in: 0,
249 fade_out: 0,
250 in_frame: 0,
251 out_frame: keep,
252 start: to,
253 ..clip
254 },
255 false => Clip {
256 fade_in: 0,
257 fade_out: 0,
258 in_frame: clip.out_frame - keep.min(clip.out_frame),
259 start: to,
260 ..clip
261 },
262 }
263 }
264 Edge::End => match clip.speed.fit(to.saturating_sub(clip.start)) {
265 Some(keep) => Clip {
266 fade_in: 0,
267 fade_out: 0,
268 out_frame: clip.in_frame + keep,
269 ..clip
270 },
271 None => clip,
272 },
273 }
274}
275
276/// The cut odometer's own arithmetic (DESIGN.md §6): where `,` `.` land from
277/// `idx`, `stride` cuts forward or back among `len` of them. Clamped rather
278/// than wrapping -- an odometer that wraps at the last cut reads as landing
279/// back at the first, which is not "next" -- so a walk already at either end
280/// simply holds there, the way [`Player::step`]'s own ends do.
281pub(crate) fn walk_cut(idx: usize, len: usize, forward: bool, stride: usize) -> usize {
282 if len == 0 {
283 return 0;
284 }
285 let delta = stride.min(len - 1) as isize;
286 let at = if forward {
287 idx as isize + delta
288 } else {
289 idx as isize - delta
290 };
291 at.clamp(0, len as isize - 1) as usize
292}
293
294/// The no-aim trim's own arithmetic (DESIGN.md §6): `current` moved `dir`
295/// frames (usually ±1, a held key's ratchet) and clamped into the room
296/// [`engine::PlaybackSession::trim_room`] already answered -- the same wall a
297/// pointer drag is clamped to, so a keyboard trim can never draw an edge the
298/// engine would refuse.
299pub(crate) fn nudge_edge(current: u32, dir: i32, lo: u32, hi: u32) -> u32 {
300 (i64::from(current) + i64::from(dir)).clamp(i64::from(lo), i64::from(hi)) as u32
301}
302
303/// Whether a loop-trim window ([`ActionId::LoopTrim`]) has been played out to
304/// its far edge and wants restarting at its near one: pure so the pump's own
305/// tick ([`Player::pump`]) is one `if` over a fact this decides. `None` --
306/// loop-trim off -- never restarts anything.
307pub(crate) fn should_loop_restart(frame: u32, window: Option<(u32, u32)>) -> bool {
308 window.is_some_and(|(_, hi)| frame >= hi)
309}
310
311/// Which window is actually looping, in priority order: the i/o range
312/// ([`Player::range`]) beats the subject-cut trim ([`Player::loop_trim`])
313/// beats the whole timeline -- but only once *something* is already armed
314/// (`loop_on` or `loop_trim`). A bare in/out mark with neither on is an
315/// export mark first, not a loop request, so it answers `None` here and
316/// never restarts anything on its own.
317pub(crate) fn active_loop_window(
318 loop_on: bool,
319 range: Option<(u32, u32)>,
320 loop_trim: Option<(u32, u32)>,
321) -> Option<(u32, u32)> {
322 if !loop_on && loop_trim.is_none() {
323 return None;
324 }
325 range.or(loop_trim)
326}
327
328/// Where a play resumes from on crossing into [`Transport::Ended`]
329/// (`Player::pump`): the active window's own near edge
330/// ([`active_loop_window`]) when one is armed, *even when its far edge is
331/// the film's own last frame* -- half of all cuts in a two-clip film sit on
332/// the final clip (DESIGN.md §6), so that coincidence is not an edge case
333/// and must not read as "reached the end, stop". Falls back to the
334/// whole-timeline loop's top, and `None` -- nothing armed -- restarts
335/// nothing, which is the halt this crossing otherwise means.
336pub(crate) fn loop_restart_frame(
337 loop_on: bool,
338 range: Option<(u32, u32)>,
339 loop_trim: Option<(u32, u32)>,
340) -> Option<u32> {
341 match active_loop_window(loop_on, range, loop_trim) {
342 Some((lo, _)) => Some(lo),
343 None => loop_on.then_some(0),
344 }
345}
346
347/// How many timeline frames a stretch of a subtitle track is worth: the one
348/// conversion between the two clocks a caption has -- microseconds for its
349/// words, frames for where it sits -- and the app-side twin of the engine's own
350/// (`Project::trim_sub_room`). Never zero: a placement of no frames is the one
351/// [`Project::place_sub`] refuses as empty, and a track shorter than a frame is
352/// still a caption somebody dragged.
353/// A fade handle's drag, turned into timeline frames: `dx` pixels at `pps`
354/// pixels per second, at `fps` frames per second -- the one conversion a
355/// fade-in or fade-out handle needs, and the app-side twin of every other
356/// pixel-to-frame door on this bed ([`Scale::time_at`]). Zero for a
357/// degenerate scale (nothing drawn to drag against), never negative on its
358/// own -- the caller adds this to the fade's length before clamping to the
359/// clip's own room, so a delta can still shrink a fade by coming back signed.
360pub(crate) fn fade_delta_frames(dx: f32, pps: f64, fps: f64) -> i64 {
361 if pps <= 0. {
362 return 0;
363 }
364 ((f64::from(dx) / pps) * fps).round() as i64
365}
366
367pub(crate) fn frames_of_us(us: i64, fps: f64) -> u32 {
368 match fps.is_finite() && fps > 0. {
369 true => ((us as f64) * fps / 1e6)
370 .round()
371 .clamp(1., f64::from(u32::MAX)) as u32,
372 false => 1,
373 }
374}
375
376/// The *placement* a trim is showing, the same way for a caption:
377/// [`Project::trim_sub`] moves the head or the tail and the window follows it,
378/// so the box on screen is the frames alone -- the words it will keep are the
379/// engine's arithmetic at the release, and nothing here draws them.
380///
381/// An edge that has not moved draws the placement it pressed, and one dragged
382/// past its other end keeps the one frame the engine's own walls always leave.
383pub(crate) fn trimmed_sub(sub: SubClip, edge: Edge, to: u32) -> SubClip {
384 match edge {
385 Edge::Start => {
386 let to = to.min(sub.end() - 1);
387 SubClip {
388 start: to,
389 frames: sub.end() - to,
390 ..sub
391 }
392 }
393 Edge::End => SubClip {
394 frames: to.max(sub.start + 1) - sub.start,
395 ..sub
396 },
397 }
398}
399
400/// Which index on its own lane a dragged clip is at *now*: the one it was picked
401/// up at while nothing has moved, and wherever the clip itself has slid to when
402/// an edit during the drag rippled the lane's indices -- a delete, an undo or a
403/// paste from a stroke, none of which gpui's frozen drag payload hears about.
404/// `None` when the clip is gone altogether, and then the drop is not an edit at
405/// all: moving whatever slid into its place is the one thing the hand did not
406/// ask for. A lane's clips are disjoint and sorted, so at most one of them can
407/// be the clip that was picked up. Generic over what a lane holds, because a
408/// [`SubClip`] is dragged under exactly the same rule.
409pub(crate) fn live_idx<T: Copy + PartialEq>(clips: &[T], idx: usize, clip: T) -> Option<usize> {
410 match clips.get(idx) {
411 Some(&at) if at == clip => Some(idx),
412 _ => clips.iter().position(|&c| c == clip),
413 }
414}
415
416/// Which index a lane's mark is on after that lane was renumbered: the caption
417/// that starts at `start`, and `None` when it is not there any more.
418///
419/// The mark on a caption is an index like a clip's ([`Player::selected`]), and a
420/// subtitle lane both *inserts in start order* ([`engine::Project::place_sub`])
421/// and removes, so any placement or lift renumbers every caption after it and an
422/// index left as it was names a neighbour -- the caption the next Delete would
423/// take. So the mark is read off the caption's start frame before such an edit
424/// and found again by it after: captions on a lane are disjoint and in order, so
425/// a start frame names exactly one of them and is the identity an index is not.
426pub(crate) fn sub_mark(subs: &[SubClip], start: u32) -> Option<usize> {
427 subs.iter().position(|s| s.start == start)
428}
429
430/// Scales an envelope to its own loudest sample, so a quietly mastered source
431/// still draws as a shape. The fixtures peak around an eighth of full scale, and
432/// an eighth of a 30 px lane is a flat line -- which says "silent" about a file
433/// that is not.
434pub(crate) fn normalise(mut peaks: Vec<(f32, f32)>) -> Vec<(f32, f32)> {
435 let loudest = peaks.iter().fold(0f32, |m, &(lo, hi)| m.max(-lo).max(hi));
436 if loudest > 0. {
437 for (lo, hi) in &mut peaks {
438 *lo /= loudest;
439 *hi /= loudest;
440 }
441 }
442 peaks
443}
444
445/// The min/max envelope of `peaks` over the source seconds `from..to`, as
446/// `(x, top, bottom)` columns of a `w` x `h` box. Every point is inside that box
447/// -- a clip's waveform cannot paint over its neighbour -- and every column is
448/// at least a pixel tall, so silence reads as a line through the middle rather
449/// than as a polygon with no area.
450pub(crate) fn envelope(
451 peaks: &[(f32, f32)],
452 from: f64,
453 to: f64,
454 w: f32,
455 h: f32,
456) -> Vec<(f32, f32, f32)> {
457 if peaks.is_empty() || w <= 0. || h <= 0. {
458 return Vec::new();
459 }
460 let cols = ((w / WAVE_COL).ceil().max(1.) as usize).min(WAVE_COLS_MAX);
461 let mid = h / 2.;
462 (0..=cols)
463 .map(|col| {
464 let along = col as f64 / cols as f64;
465 let at = from + (to - from) * along;
466 // Casting a float to an integer saturates in Rust, so a source
467 // second past the end of the peaks clamps rather than wrapping.
468 let bucket = ((at * f64::from(WAVE_BPS)) as usize).min(peaks.len() - 1);
469 let (lo, hi) = peaks[bucket];
470 let top = (mid - hi.clamp(0., 1.) * mid).min(mid - 0.5);
471 let bottom = (mid - lo.clamp(-1., 0.) * mid).max(mid + 0.5);
472 (w * along as f32, top.max(0.), bottom.min(h))
473 })
474 .collect()
475}
476
477/// Records its parent's laid-out box: gpui hands a mouse listener the window
478/// position only, and the ruler sits behind the panel's padding. Paints
479/// nothing and takes no hitbox of its own, so the click still reaches the bar.
480pub(crate) fn bounds_probe(into: Rc<Cell<Bounds<Pixels>>>) -> impl IntoElement {
481 canvas(move |bounds, _, _| into.set(bounds), |_, _, _, _| ())
482 .absolute()
483 .size_full()
484}
485
486/// [`bounds_probe`] for a box something *else* is laid out against: it also asks
487/// for one more frame whenever the height changed.
488///
489/// A measurement is read by the frame after the one that took it, and a notice
490/// arriving over a paused picture repaints exactly once -- so without this the
491/// cue would sit under that notice until something else happened to draw, which
492/// on a paused window can be never.
493pub(crate) fn height_probe(into: Rc<Cell<Pixels>>) -> impl IntoElement {
494 canvas(
495 move |bounds, window, _| {
496 // Only on a change: an unconditional request is a repaint loop.
497 if into.replace(bounds.size.height) != bounds.size.height {
498 window.request_animation_frame();
499 }
500 },
501 |_, _, _, _| (),
502 )
503 .absolute()
504 .size_full()
505}
506
507/// Where along an element a click landed, 0..1. An element that was never
508/// painted has no width, and reads as its start rather than as NaN.
509pub(crate) fn frac_along(x: Pixels, bounds: Bounds<Pixels>) -> f32 {
510 if bounds.size.width <= px(0.) {
511 return 0.;
512 }
513 ((x - bounds.left()) / bounds.size.width).clamp(0., 1.)
514}
515
516/// Where along an element a click landed, in pixels from its own left edge:
517/// [`frac_along`] in the units the timeline is drawn in, since a [`Scale`]
518/// measures in pixels and not in shares of a bed. Clamped to the element -- a
519/// drag that slid off the end names its end -- and an element that was never
520/// painted reads as its start.
521pub(crate) fn px_along(x: Pixels, bounds: Bounds<Pixels>) -> f32 {
522 f32::from(x - bounds.left()).clamp(0., f32::from(bounds.size.width).max(0.))
523}
524
525/// [`px_along`] turned through a right angle, for the lane stack's scrollbar:
526/// how far down its track a press landed.
527pub(crate) fn px_down(y: Pixels, bounds: Bounds<Pixels>) -> f32 {
528 f32::from(y - bounds.top()).clamp(0., f32::from(bounds.size.height).max(0.))
529}
530
531/// One turn of the wheel as a single number, positive for a turn *up*, in
532/// whatever units the device sends (a mouse counts lines, a touchpad pixels).
533/// A tilt wheel's own axis counts as the same gesture: it is the sideways
534/// scroll a mouse that has one sends, and the controls this drives have one
535/// direction each, so the two axes are one answer here.
536pub(crate) fn wheel_delta(event: &ScrollWheelEvent) -> f32 {
537 let (dx, dy) = match event.delta {
538 ScrollDelta::Lines(d) => (d.x, d.y),
539 ScrollDelta::Pixels(d) => (f32::from(d.x), f32::from(d.y)),
540 };
541 match dy == 0. {
542 true => dx,
543 false => dy,
544 }
545}
546
547/// The frame a dropped clip's head lands on: `raw`, unless one of `marks` is
548/// within `tol` frames of where its head -- or its tail, `len` frames along --
549/// would come to rest, in which case that edge wins. The snap every timeline
550/// has: clips meet exactly instead of a frame apart, and the hand does not have
551/// to aim. The nearest mark wins, and a head landing on one beats a tail at the
552/// same distance -- what was dragged is the head.
553pub(crate) fn snapped(raw: u32, len: u32, tol: u32, marks: &[u32]) -> u32 {
554 let mut best: Option<(u32, u32)> = None;
555 for &mark in marks {
556 // Head on the mark, then tail on it -- a clip dragged up against the
557 // take in front of it snaps by whichever end reaches first.
558 for start in [Some(mark), mark.checked_sub(len)] {
559 let Some(start) = start else { continue };
560 let d = start.abs_diff(raw);
561 if d <= tol && best.is_none_or(|(near, _)| d < near) {
562 best = Some((d, start));
563 }
564 }
565 }
566 best.map_or(raw, |(_, start)| start)
567}
568
569/// The edges worth landing on, off *every* lane: both ends of every clip on the
570/// timeline, less `skip` -- the clip being dragged, which does not snap to where
571/// it already is -- and less `skip_link`, the group id of whatever is being
572/// dragged: its clips travel with it, and so does any caption the id names.
573/// `skip` is a lane's place in `lanes` and an index into it; `skip_link` is
574/// read off a caption by the caller, whose drag has no clip for `skip` to
575/// name. The playhead and the head of the timeline go on the end: a clip meets
576/// the cursor and the start of the show as readily as it meets another take.
577///
578/// All lanes rather than the one being dropped on, because a cut is made across
579/// the timeline: a title on V2 lines up with the shot under it, and a sound
580/// effect lines up with the frame it belongs to.
581pub(crate) fn snap_marks(
582 lanes: &[&[Clip]],
583 skip: Option<(usize, usize)>,
584 skip_link: Option<u32>,
585 playhead: u32,
586 range: Option<(u32, u32)>,
587) -> Vec<u32> {
588 let mut marks: Vec<u32> = lanes
589 .iter()
590 .enumerate()
591 .flat_map(|(lane, clips)| {
592 clips
593 .iter()
594 .enumerate()
595 .filter(move |&(idx, clip)| {
596 Some((lane, idx)) != skip && !(skip_link.is_some() && clip.link == skip_link)
597 })
598 .flat_map(|(_, clip)| [clip.start, clip.end()])
599 })
600 .collect();
601 marks.push(playhead);
602 marks.push(0);
603 // The in and out points ([`Player::range`]): a hand that has marked a
604 // stretch is working to it, and a clip meets its brackets as readily as it
605 // meets a cut.
606 if let Some((in_, out)) = range {
607 marks.push(in_);
608 marks.push(out);
609 }
610 marks
611}
612
613/// [`snapped`], and the mark that pulled it there -- the line the bed draws
614/// while the hand is still moving. `None` when nothing was near enough: a line
615/// standing over open bed would promise a landing that is not going to happen.
616/// The head is read before the tail, exactly as [`snapped`] prefers it.
617///
618/// `on` is the switch ([`ActionId::ToggleSnap`]): off, the gesture lands raw and
619/// draws no line at all, which is the whole point of being able to turn it off.
620pub(crate) fn snap_cue(
621 on: bool,
622 raw: u32,
623 len: u32,
624 tol: u32,
625 marks: &[u32],
626) -> (u32, Option<u32>) {
627 if !on {
628 return (raw, None);
629 }
630 let start = snapped(raw, len, tol, marks);
631 let mark = [start, start.saturating_add(len)]
632 .into_iter()
633 .find(|mark| marks.contains(mark));
634 (start, mark)
635}
636
637/// Whether the magnet is on for the gesture in flight: the switch, unless
638/// `alt` is held -- the temporary override Resolve, Premiere and Final Cut all
639/// put on that key, off for this one drag and leaving the switch where the hand
640/// left it. [`Player::snap_live`]'s whole rule, here so it can be read without
641/// a window.
642pub(crate) fn snap_live(on: bool, alt: bool) -> bool {
643 on && !alt
644}
645
646/// Where a drag lands and the mark that pulled it there: the frame under the
647/// pointer, less however far into the box the hand grabbed it (so a clip travels
648/// with the pointer rather than jumping its head under it), snapped by
649/// [`snap_cue`]. One answer, asked by the shadow drawn in flight
650/// ([`Player::preview_ghost`]), by the line ([`Player::preview_drop`]) and by
651/// the drop that commits ([`Player::move_clip`]) -- which is what makes the
652/// promise and the landing the same frame.
653pub(crate) fn landing(
654 under: u32,
655 grab: u32,
656 len: u32,
657 on: bool,
658 tol: u32,
659 marks: &[u32],
660) -> (u32, Option<u32>) {
661 snap_cue(on, under.saturating_sub(grab), len, tol, marks)
662}
663
664/// Where a clip `len` frames long, let go over *another* lane with its head
665/// asked at `at`, really comes to rest -- `None` when the engine refuses the
666/// drop outright. A mirror of [`Project::move_room`]: the release is refused
667/// only when the asked head sits *inside* a take already there (a clamp has no
668/// answer for that), or when the gap it names is narrower than the clip;
669/// otherwise the head is clamped into that gap exactly as a same-lane move is
670/// ([`gap_clamp`]). `others` is `(start, end)` of every clip already on the
671/// destination lane, less the ones travelling with this one.
672///
673/// The shadow reads this, so a landing the release *will* make is never drawn
674/// as refused -- a whole-span overlap test refuses far more than the engine
675/// does, and a shadow that lies about a refusal reads as a broken timeline.
676pub(crate) fn cross_room(at: u32, len: u32, others: &[(u32, u32)]) -> Option<u32> {
677 let (mut lo, mut hi) = (0, u32::MAX);
678 for &(other_start, other_end) in others {
679 if other_start <= at && at < other_end {
680 return None;
681 }
682 match other_end <= at {
683 true => lo = lo.max(other_end),
684 false => hi = hi.min(other_start),
685 }
686 }
687 match hi - lo < len {
688 true => None,
689 false => Some(at.clamp(lo, hi - len)),
690 }
691}
692
693/// Where a clip staying on its own lane really comes to rest: `want`, clamped
694/// into the gap it is sitting in -- the take behind it and the take in front of
695/// it are walls ([`Project::move_selection`] clamps the delta by exactly these,
696/// it does not refuse), so a clip dragged hard left past its neighbour lands
697/// flush against that neighbour's tail rather than nowhere. `now` is its head
698/// today, which is what names the gap. The shadow reads this, so the box drawn
699/// in flight is the box the release leaves behind.
700pub(crate) fn gap_clamp(now: u32, len: u32, want: u32, others: &[(u32, u32)]) -> u32 {
701 let lo = others
702 .iter()
703 .filter(|&&(_, end)| end <= now)
704 .map(|&(_, end)| end)
705 .max()
706 .unwrap_or(0);
707 let hi = others
708 .iter()
709 .filter(|&&(start, _)| start >= now.saturating_add(len))
710 .map(|&(start, _)| start)
711 .min()
712 .unwrap_or(u32::MAX);
713 want.clamp(lo, hi.saturating_sub(len).max(lo))
714}
715
716/// The lane a release lands on when the pointer is off the rows themselves:
717/// the row under it while its kind can hold what is in the hand, and otherwise
718/// the last one that could -- a picture clip carried down across A1 on its way
719/// to the empty bench below is still aiming at V1. [`Player::drag_lane`]'s
720/// whole rule.
721pub(crate) fn held_lane(prev: Option<Lane>, over: Lane, from: Lane) -> Option<Lane> {
722 match over.kind == from.kind {
723 true => Some(over),
724 false => prev,
725 }
726}
727
728/// Why this file may not go on that lane, in the words the refusal is told in --
729/// `None` when it may. A file with no picture belongs on an audio lane and
730/// nowhere else, and a still is silent, so an audio lane is the one place it
731/// cannot go. Asked twice: by the ghost tinting itself as refused on the way
732/// down, and by the insert that commits ([`Player::insert_source`]), so what is
733/// shown as impossible is exactly what is refused.
734///
735/// `has_video` is [`Player::has_video`]'s answer for `path`: the probed truth
736/// where the header has been read, and an extension's guess otherwise -- never
737/// `engine::is_audio` alone, which a song muxed into an `.mp4` lies to.
738pub(crate) fn lane_refuses(path: &Path, lane: Lane, has_video: bool) -> Option<String> {
739 let name = file_name(path);
740 let label = lane.label();
741 match lane.kind {
742 LaneKind::Video if !has_video => Some(format!(
743 "NOT ON {label} — {name} has no picture"
744 )),
745 LaneKind::Audio if engine::is_image(path) => Some(format!(
746 "NOT ON {label} — {name} is a still image"
747 )),
748 // A subtitle lane holds words and no media at all: the refusal is here
749 // rather than at the engine's door so the shadow is tinted red on the
750 // way down, like every other lane a file cannot go on.
751 LaneKind::Subtitle => Some(format!(
752 "NOT ON {label} — {name} is a file; a subtitle track takes captions, dragged from the \
753 Subtitles list"
754 )),
755 _ => None,
756 }
757}
758
759/// Where down an element a pointer sits, 0..1 from the top: the vertical twin
760/// of [`frac_along`], for the equalizer, whose gain axis is the y one. An
761/// element that was never painted reads as its middle -- flat, the one answer
762/// that changes nothing -- rather than as a full boost.
763pub(crate) fn frac_down(y: Pixels, bounds: Bounds<Pixels>) -> f32 {
764 if bounds.size.height <= px(0.) {
765 return 0.5;
766 }
767 ((y - bounds.top()) / bounds.size.height).clamp(0., 1.)
768}
769
770#[cfg(test)]
771mod drop_landing_tests {
772 use super::*;
773
774 /// A release a few pixels' worth of frames right of an empty timeline's
775 /// head still lands on frame 0: [`snap_marks`] always offers 0
776 /// (`marks.push(0)`, above) even with no clips on the timeline yet, so
777 /// the "you must be exactly at 0.0" complaint is the tolerance, not a
778 /// missing mark.
779 #[test]
780 fn a_pull_near_the_head_of_an_empty_timeline_snaps_to_frame_0() {
781 let marks = snap_marks(&[&[]], None, None, 0, None);
782 assert!(marks.contains(&0), "an empty timeline still offers frame 0");
783 assert_eq!(snapped(4, 0, 10, &marks), 0);
784 // Outside the tolerance, the raw ask stands: this is a magnet, not a
785 // clamp to 0.
786 assert_eq!(snapped(11, 0, 10, &marks), 11);
787 }
788
789 /// A clip already on the lane offers both of its own edges as marks
790 /// ([`snap_marks`]'s `flat_map(|clip| [clip.start, clip.end()])`), and a
791 /// release close to either -- within the drop tolerance -- lands on it
792 /// rather than the raw pixel.
793 #[test]
794 fn a_pull_near_a_clip_edge_snaps_onto_it() {
795 let marks = [0, 100, 200];
796 assert_eq!(snapped(205, 0, 10, &marks), 200);
797 }
798
799 /// The playhead is a mark too, so a clip let go near it lines up with
800 /// where the timeline is parked.
801 #[test]
802 fn a_pull_near_the_playhead_snaps_onto_it() {
803 let marks = snap_marks(&[&[]], None, None, 500, None);
804 assert!(marks.contains(&500));
805 assert_eq!(snapped(493, 0, 10, &marks), 500);
806 }
807
808 /// The user's own repro: a clip dragged left through the lane-head column
809 /// -- window x *left of the bed* -- lands on frame 0 rather than nowhere.
810 /// Two clamps do it, and both are on the path the bench now takes for a
811 /// drop over the head ([`Player::frame_under`]): [`px_along`] pins an x
812 /// before the bed's left edge to 0 px, [`Scale::time_at`] pins the moment
813 /// to 0 s, and the grab offset comes off with a saturating subtraction, so
814 /// even a clip held by its tail cannot ask for a negative frame.
815 #[test]
816 fn a_drag_out_over_the_lane_head_lands_on_frame_0() {
817 let bed = Bounds {
818 origin: point(px(100.), px(0.)),
819 size: size(px(900.), px(60.)),
820 };
821 let scale = Scale::default();
822 // 40 px into the head column, and off the window entirely.
823 for x in [px(60.), px(-400.)] {
824 assert_eq!(px_along(x, bed), 0.);
825 let under = frame_at(scale.time_at(px_along(x, bed)), 25.);
826 assert_eq!(under, 0);
827 // Grabbed 30 frames into the box: still frame 0, never a refusal.
828 assert_eq!(landing(under, 30, 50, true, 10, &[0, 300]), (0, Some(0)));
829 }
830 }
831
832 /// Both edges of the clip in the hand are candidates and the nearest one
833 /// wins: a tail 2 frames short of a neighbour's head beats a head 8 frames
834 /// from the timeline's start.
835 #[test]
836 fn the_nearer_of_the_two_edges_wins() {
837 let marks = [0, 300, 500];
838 // len 292: the tail wants 300 (2 away), the head 0 (8 away).
839 // The tail already sits exactly on 300, so the head is left alone.
840 assert_eq!(snapped(8, 292, 10, &marks), 8);
841 assert_eq!(snapped(6, 292, 10, &marks), 8, "tail meets 300, head stays");
842 }
843
844 /// The threshold is a distance on *screen*: the same 10 px of aim at two
845 /// zooms is a different number of frames, which is what makes the magnet
846 /// feel identical zoomed in and zoomed out ([`Scale::drop_snap_frames`]).
847 /// Outside it the drag follows the pointer exactly.
848 #[test]
849 fn the_threshold_is_ten_pixels_at_any_zoom() {
850 let fps = 25.;
851 for pps in [50., 400.] {
852 let scale = Scale { pps, start: 0. };
853 let tol = scale.drop_snap_frames(fps);
854 // 10 px worth of frames, and one frame more than that is not near.
855 let near = (DROP_SNAP_PX / pps * fps) as u32;
856 assert_eq!(tol, near);
857 assert_eq!(snapped(500 + tol, 0, tol, &[500]), 500);
858 assert_eq!(
859 snapped(500 + tol + 1, 0, tol, &[500]),
860 500 + tol + 1,
861 "past the window the pointer is obeyed exactly"
862 );
863 }
864 }
865
866 /// `alt` held turns the magnet off for the gesture and nothing else: the
867 /// same raw ask, no line, and [`Player::snap`] itself untouched.
868 #[test]
869 fn alt_turns_the_magnet_off_for_this_drag_only() {
870 let on = true;
871 assert!(snap_live(on, false));
872 assert!(!snap_live(on, true));
873 let marks = [0, 300];
874 assert_eq!(
875 snap_cue(snap_live(on, true), 297, 0, 10, &marks),
876 (297, None)
877 );
878 assert_eq!(snap_cue(snap_live(on, false), 297, 0, 10, &marks), (300, Some(300)));
879 // The switch off stays off however the modifier is held.
880 assert!(!snap_live(false, false));
881 }
882
883 /// Every target an NLE offers is on the list: frame 0, the playhead, both
884 /// edges of every clip on *every* lane, and the in/out brackets.
885 #[test]
886 fn the_targets_are_zero_the_playhead_the_edges_and_the_marks() {
887 let clip = |start: u32, frames: u32| Clip {
888 fade_in: 0,
889 fade_out: 0,
890 transition_out: 0,
891 visualizer: 0,
892 viz_paint: 0,
893 start,
894 in_frame: 0,
895 out_frame: frames,
896 source: 0,
897 link: None,
898 eq: None,
899 color: None,
900 transform: None,
901 fit: Default::default(),
902 speed: Default::default(),
903 };
904 let v1 = [clip(100, 50), clip(400, 50)];
905 let a1 = [clip(700, 20)];
906 let marks = snap_marks(&[&v1, &a1], None, None, 900, Some((250, 600)));
907 for want in [0, 900, 100, 150, 400, 450, 700, 720, 250, 600] {
908 assert!(marks.contains(&want), "{want} is not a snap target");
909 }
910 // And each of them actually pulls a drag onto itself.
911 for target in [0, 250, 600, 900] {
912 assert_eq!(snapped(target + 4, 0, 10, &marks), target);
913 }
914 }
915
916 /// A release on the empty bench below the last row, or left of the heads,
917 /// lands on the lane the last live sample was over -- and a lane of the
918 /// wrong kind crossed on the way down never steals it.
919 #[test]
920 fn the_last_lane_that_could_hold_it_keeps_the_drag() {
921 let v1 = Lane::V1;
922 let v2 = Lane::new(LaneKind::Video, 1);
923 let a1 = Lane::A1;
924 // The head column is part of the row, so the row over it is the answer.
925 assert_eq!(held_lane(None, v1, v1), Some(v1));
926 assert_eq!(held_lane(Some(v1), v2, v1), Some(v2));
927 assert_eq!(held_lane(Some(v2), a1, v1), Some(v2), "audio cannot hold it");
928 // Nothing promised yet and nothing that can hold it: no landing.
929 assert_eq!(held_lane(None, a1, v1), None);
930 }
931
932 /// A clip dragged hard left past the take in front of it comes to rest
933 /// flush against that take -- the walls of its own gap, which is what the
934 /// engine clamps the drag by -- and one dragged off the head of the
935 /// timeline rests on frame 0.
936 #[test]
937 fn a_drag_past_a_neighbour_rests_flush_against_it() {
938 let others = [(0, 375), (900, 1000)];
939 assert_eq!(gap_clamp(375, 500, 0, &others), 375, "flush with its tail");
940 assert_eq!(gap_clamp(375, 500, 380, &others), 380, "room to spare");
941 assert_eq!(gap_clamp(375, 500, 800, &others), 400, "flush with the next");
942 // An empty lane clamps at the head of the timeline and nowhere else.
943 assert_eq!(gap_clamp(500, 100, 0, &[]), 0);
944 assert_eq!(gap_clamp(500, 100, 9_000, &[]), 9_000);
945 }
946
947 /// The cross-lane shadow's rule, mirroring the engine: refused only when
948 /// the asked head is inside a take or the gap is too narrow, and otherwise
949 /// clamped into the gap rather than refused. The middle case is the
950 /// verifier's repro -- an obstacle at (360, 420), a 90-frame clip asked at
951 /// 315, which the engine lands at 270.
952 #[test]
953 fn a_cross_lane_landing_clamps_into_the_gap_the_engine_leaves() {
954 let others = [(360, 420)];
955 assert_eq!(cross_room(315, 90, &others), Some(270), "clamped, not refused");
956 assert_eq!(cross_room(380, 90, &others), None, "head inside the take");
957 assert_eq!(cross_room(100, 90, &others), Some(100), "room to spare");
958 let tight = [(0, 100), (150, 300)];
959 assert_eq!(cross_room(120, 90, &tight), None, "the gap is 50 frames wide");
960 assert_eq!(cross_room(120, 50, &tight), Some(100), "and holds a 50-frame clip");
961 assert_eq!(cross_room(500, 90, &[]), Some(500), "an empty lane takes it as asked");
962 }
963}