forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBef5832fTahinli3 months ago597 commits

timeline_math.rs683 lines, 29.7 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(session: &PlaybackSession, lane: Lane, idx: usize) -> Option<(Lane, usize)> {
69 let clip = *session.lane_clips(lane).get(idx)?;
70 let matches = |other: Lane| {
71 let i = session.lane_clips(other).iter().position(|c| {
72 (c.start, c.end()) == (clip.start, clip.end())
73 && !(c.link.is_some() && c.link == clip.link)
74 })?;
75 Some((other, i))
76 };
77 // Sound before picture (and picture before sound): "group this" means the
78 // other half of the take, and a project whose audio lane was added after a
79 // second video one has that half *after* the layer in storage order -- which
80 // is the order the lanes come in. A same-kind lane is still groupable (V1
81 // and V2 may be one take), but only where no opposite one covers the span.
82 let (opposite, same): (Vec<Lane>, Vec<Lane>) = session
83 .lanes()
84 .into_iter()
85 .filter(|&other| other != lane)
86 .partition(|other| other.kind != lane.kind);
87 opposite.into_iter().chain(same).find_map(matches)
88}
89
90/// What the timeline has picked: every clip and caption a hand ctrl-clicked
91/// into the selection, in click order and with no two the same. The last of
92/// them is the [`anchor`](Selection::anchor) -- the one every action that is
93/// about *one* thing (delete, lift, copy, the equalizer) acts on -- and the
94/// whole list is what a manual Group names to the engine.
95///
96/// Indices move under every edit, exactly as the single mark this replaces
97/// did, so every edit that renumbers a lane clears the picks it cannot keep
98/// honest. Pure and engine-free, so a test can build one without a window.
99#[derive(Clone, Debug, Default, PartialEq)]
100pub(crate) struct Selection {
101 /// `(lane, index into that lane's own list)` -- a subtitle lane's index
102 /// space for a caption, exactly the pair a click was told about.
103 picks: Vec<(Lane, usize)>,
104}
105
106impl Selection {
107 /// Nothing picked: what the timeline starts as and what an edit that moved
108 /// indices leaves behind.
109 pub(crate) fn new() -> Self {
110 Self::default()
111 }
112
113 /// The one a plain click and every selection key leave: the whole of the
114 /// selection, one pick. A click names a thing, and the things it had been
115 /// naming along with it are no longer named.
116 pub(crate) fn set_one(&mut self, pick: (Lane, usize)) {
117 self.picks.clear();
118 self.picks.push(pick);
119 }
120
121 /// A ctrl-click: the pick joins the selection if it was not in it and
122 /// leaves if it was -- the toggle that assembles a group by hand. The
123 /// order is the order they were picked in, and the anchor rides on it.
124 pub(crate) fn toggle(&mut self, pick: (Lane, usize)) {
125 match self.picks.iter().position(|&p| p == pick) {
126 Some(at) => {
127 self.picks.remove(at);
128 }
129 None => self.picks.push(pick),
130 }
131 }
132
133 /// The last pick: what "the selected clip" is to every action that acts on
134 /// one thing. The click order puts it under the hand, which is where the
135 /// eye is.
136 pub(crate) fn anchor(&self) -> Option<(Lane, usize)> {
137 self.picks.last().copied()
138 }
139
140 /// Whether `pick` is one of the selection's -- the question a right-click
141 /// asks before it decides whether the menu is about the selection or
142 /// about the clip under it.
143 pub(crate) fn contains(&self, pick: (Lane, usize)) -> bool {
144 self.picks.contains(&pick)
145 }
146
147 /// Every pick, in click order: what a manual Group names to the engine.
148 pub(crate) fn picks(&self) -> &[(Lane, usize)] {
149 &self.picks
150 }
151
152 pub(crate) fn is_empty(&self) -> bool {
153 self.picks.is_empty()
154 }
155
156 /// A pick that joins without disturbing the rest -- Select All's builder,
157 /// which names every placement there is and cannot be a `set_one`.
158 pub(crate) fn add(&mut self, pick: (Lane, usize)) {
159 if !self.picks.contains(&pick) {
160 self.picks.push(pick);
161 }
162 }
163}
164
165/// The rate a caption's box plays its window at, read off the placement
166/// itself: how long the words are, against how much timeline they cross. A
167/// clip's badge comes from its own `speed`; a caption has none, so its box
168/// derives one -- and keeps it even after the group that re-timed it comes
169/// apart, because the proportion is the placement's own. `None` at unity:
170/// placement rounding leaves an odd-width window a frame or so off real time,
171/// and a badge is for a box that was *re-timed*, not one that rounds.
172pub(crate) fn caption_rate(sub: SubClip, fps: f64) -> Option<Speed> {
173 if !(fps.is_finite() && fps > 0.0) || sub.window_us() <= 0 {
174 return None;
175 }
176 let (span_us, window_us) = (f64::from(sub.frames) / fps * 1e6, sub.window_us() as f64);
177 // The unity gate is absolute, in frames of the timeline: placement
178 // rounding (`frames_of_us`) leaves a short track up to half a frame off
179 // real time, which against a one-second window is fifteen permille -- a
180 // relative gate would badge most palette drops under two and a half
181 // seconds. Unity is "the window lands within a frame and a half of the
182 // span"; the permille is only ever the rate the badge shows.
183 if (span_us - window_us).abs() <= 1.5 / fps * 1e6 {
184 return None;
185 }
186 // The rate is the window over the span -- content per timeline, a clip's
187 // own `speed` in the same spelling: 10s of words crossing 5s of timeline
188 // is 2.00x.
189 let permille = (window_us / span_us * 1000.).round();
190 Some(Speed::from_permille(
191 permille.clamp(
192 f64::from(Speed::MIN.permille()),
193 f64::from(Speed::MAX.permille()),
194 ) as u16,
195 ))
196}
197
198/// The scrollbar's thumb over a track `w` px wide: `(x, width)` of the box
199/// standing for the visible share of a timeline `duration` long whose window
200/// starts at `start` and spans `span`. Full width when nothing is off-screen
201/// (there is nothing to scroll and the strip says so by filling), never
202/// narrower than [`SCROLL_THUMB_MIN`] when there is (a thumb a pixel wide is a
203/// thumb no hand can hold), and never off the track either way -- the clamp,
204/// not the caller, owns that, because a drag's samples arrive raw.
205pub(crate) fn scroll_thumb(
206 w: f32,
207 duration: f64,
208 start: f64,
209 span: f64,
210) -> (f32, f32) {
211 if w <= 0. || duration <= 0. || span >= duration {
212 return (0., w.max(0.));
213 }
214 let share = f64::from(w);
215 let width = ((span / duration) * share).clamp(f64::from(SCROLL_THUMB_MIN), f64::from(w));
216 let x = (start / duration * share).clamp(0., f64::from(w) - width);
217 (x as f32, width as f32)
218}
219
220/// The lane stack's thumb over a track `h` px tall: `(y, height)` of the box
221/// standing for the visible share of a stack `content` px tall in a box
222/// `box_h` px tall, taken down by `scrolled` px -- the time axis's
223/// [`scroll_thumb`] turned through a right angle, and on the same terms:
224/// full track when the whole stack is on screen, never shorter than
225/// [`SCROLL_THUMB_MIN`] when it is not, and never off the track either way.
226pub(crate) fn lanes_thumb(track: f32, content: f32, box_h: f32, scrolled: f32) -> (f32, f32) {
227 if track <= 0. || content <= 0. || box_h >= content {
228 return (0., track.max(0.));
229 }
230 let height = (track * box_h / content).clamp(SCROLL_THUMB_MIN, track);
231 let y = (scrolled / (content - box_h) * (track - height)).clamp(0., track - height);
232 (y, height)
233}
234
235impl Selection {
236 pub(crate) fn len(&self) -> usize {
237 self.picks.len()
238 }
239
240 pub(crate) fn clear(&mut self) {
241 self.picks.clear();
242 }
243}
244
245/// Whether a click marks this box: any pick on it always, and any box sharing
246/// a group id with a pick -- the clip the anchor was ctrl-clicked beside, and
247/// the caption a hand pinned to a clip. A group whose only member is picked
248/// marks that member alone, which is what makes a detached half separately
249/// deletable.
250///
251/// `pick_links` are the group ids of the picks themselves, read by the caller
252/// off the session in the same order as `picks` -- the one fact this pure
253/// question cannot know.
254pub(crate) fn marked(
255 here: (Lane, usize),
256 link: Option<u32>,
257 picks: &[(Lane, usize)],
258 pick_links: &[Option<u32>],
259) -> bool {
260 picks.contains(&here) || (link.is_some() && pick_links.contains(&link))
261}
262
263
264/// Whether a clip is wide enough to be worth naming.
265pub(crate) fn show_label(w: f32) -> bool {
266 w >= LABEL_MIN_W
267}
268
269/// The clip a trim is *showing*, worked out the way `Project::trim` will write
270/// it: the timeline room the edge leaves is turned into source frames by the one
271/// conversion that exists for it ([`Speed::fit`]), and the box is drawn from
272/// that. The preview and the commit are then the same arithmetic -- a box let go
273/// of stays where the hand left it at every rate. Assigning the timeline count
274/// straight to the source field, as this used to, drew a speeded clip's tail
275/// moving at the wrong rate (it snapped on release) and drew a *head* trim
276/// moving the clip's other edge, since the length it implied was not the length
277/// the release would commit.
278///
279/// A still grows forward from source frame 0 instead: every frame of it is the
280/// same picture, so there is no earlier one for an in-point to walk back to.
281///
282/// Room too narrow to hold one source frame is the edit the engine refuses, and
283/// the box is drawn unchanged rather than as something that will not be
284/// committed.
285pub(crate) fn trimmed_clip(clip: Clip, edge: Edge, to: u32, still: bool) -> Clip {
286 // An edge that has not moved is not an edit, and `Project::trim` refuses it
287 // as one: the press that starts a drag must draw the clip it pressed, not a
288 // clip a rounding narrower.
289 if to
290 == match edge {
291 Edge::Start => clip.start,
292 Edge::End => clip.end(),
293 }
294 {
295 return clip;
296 }
297 match edge {
298 Edge::Start => {
299 // What survives is measured from the *end* -- the frames that stay
300 // play what they always played, which is what makes this a trim.
301 let Some(keep) = clip.speed.fit(clip.end().saturating_sub(to)) else {
302 return clip;
303 };
304 match still {
305 true => Clip {
306 fade_in: 0,
307 fade_out: 0,
308 in_frame: 0,
309 out_frame: keep,
310 start: to,
311 ..clip
312 },
313 false => Clip {
314 fade_in: 0,
315 fade_out: 0,
316 in_frame: clip.out_frame - keep.min(clip.out_frame),
317 start: to,
318 ..clip
319 },
320 }
321 }
322 Edge::End => match clip.speed.fit(to.saturating_sub(clip.start)) {
323 Some(keep) => Clip {
324 fade_in: 0,
325 fade_out: 0,
326 out_frame: clip.in_frame + keep,
327 ..clip
328 },
329 None => clip,
330 },
331 }
332}
333
334/// How many timeline frames a stretch of a subtitle track is worth: the one
335/// conversion between the two clocks a caption has -- microseconds for its
336/// words, frames for where it sits -- and the app-side twin of the engine's own
337/// (`Project::trim_sub_room`). Never zero: a placement of no frames is the one
338/// [`Project::place_sub`] refuses as empty, and a track shorter than a frame is
339/// still a caption somebody dragged.
340/// A fade handle's drag, turned into timeline frames: `dx` pixels at `pps`
341/// pixels per second, at `fps` frames per second -- the one conversion a
342/// fade-in or fade-out handle needs, and the app-side twin of every other
343/// pixel-to-frame door on this bed ([`Scale::time_at`]). Zero for a
344/// degenerate scale (nothing drawn to drag against), never negative on its
345/// own -- the caller adds this to the fade's length before clamping to the
346/// clip's own room, so a delta can still shrink a fade by coming back signed.
347pub(crate) fn fade_delta_frames(dx: f32, pps: f64, fps: f64) -> i64 {
348 if pps <= 0. {
349 return 0;
350 }
351 ((f64::from(dx) / pps) * fps).round() as i64
352}
353
354pub(crate) fn frames_of_us(us: i64, fps: f64) -> u32 {
355 match fps.is_finite() && fps > 0. {
356 true => ((us as f64) * fps / 1e6)
357 .round()
358 .clamp(1., f64::from(u32::MAX)) as u32,
359 false => 1,
360 }
361}
362
363/// The *placement* a trim is showing, the same way for a caption:
364/// [`Project::trim_sub`] moves the head or the tail and the window follows it,
365/// so the box on screen is the frames alone -- the words it will keep are the
366/// engine's arithmetic at the release, and nothing here draws them.
367///
368/// An edge that has not moved draws the placement it pressed, and one dragged
369/// past its other end keeps the one frame the engine's own walls always leave.
370pub(crate) fn trimmed_sub(sub: SubClip, edge: Edge, to: u32) -> SubClip {
371 match edge {
372 Edge::Start => {
373 let to = to.min(sub.end() - 1);
374 SubClip {
375 start: to,
376 frames: sub.end() - to,
377 ..sub
378 }
379 }
380 Edge::End => SubClip {
381 frames: to.max(sub.start + 1) - sub.start,
382 ..sub
383 },
384 }
385}
386
387/// Which index on its own lane a dragged clip is at *now*: the one it was picked
388/// up at while nothing has moved, and wherever the clip itself has slid to when
389/// an edit during the drag rippled the lane's indices -- a delete, an undo or a
390/// paste from a stroke, none of which gpui's frozen drag payload hears about.
391/// `None` when the clip is gone altogether, and then the drop is not an edit at
392/// all: moving whatever slid into its place is the one thing the hand did not
393/// ask for. A lane's clips are disjoint and sorted, so at most one of them can
394/// be the clip that was picked up. Generic over what a lane holds, because a
395/// [`SubClip`] is dragged under exactly the same rule.
396pub(crate) fn live_idx<T: Copy + PartialEq>(clips: &[T], idx: usize, clip: T) -> Option<usize> {
397 match clips.get(idx) {
398 Some(&at) if at == clip => Some(idx),
399 _ => clips.iter().position(|&c| c == clip),
400 }
401}
402
403/// Which index a lane's mark is on after that lane was renumbered: the caption
404/// that starts at `start`, and `None` when it is not there any more.
405///
406/// The mark on a caption is an index like a clip's ([`Player::selected`]), and a
407/// subtitle lane both *inserts in start order* ([`engine::Project::place_sub`])
408/// and removes, so any placement or lift renumbers every caption after it and an
409/// index left as it was names a neighbour -- the caption the next Delete would
410/// take. So the mark is read off the caption's start frame before such an edit
411/// and found again by it after: captions on a lane are disjoint and in order, so
412/// a start frame names exactly one of them and is the identity an index is not.
413pub(crate) fn sub_mark(subs: &[SubClip], start: u32) -> Option<usize> {
414 subs.iter().position(|s| s.start == start)
415}
416
417/// The part of a clip's box that is on the bed, in the box's own pixels:
418/// `(left, width)` of its intersection with the visible strip. Everything drawn
419/// *inside* a box -- its waveform, its name, its speed badge -- is placed in
420/// here rather than at the box's own edges, which at a deep zoom sit thousands
421/// of pixels off either side of the screen: a label out there is a label nobody
422/// can read, and a waveform out there is a path with a point per two pixels of a
423/// width nobody can see. A bed that has not been measured yet answers with the
424/// whole box, which is what was drawn before there was a bed to clip to.
425pub(crate) fn visible_slice(left: f32, width: f32, bed: f32) -> (f32, f32) {
426 if bed <= 0. {
427 return (0., width);
428 }
429 let from = (-left).clamp(0., width);
430 let to = (bed - left).clamp(from, width);
431 (from, to - from)
432}
433
434/// Scales an envelope to its own loudest sample, so a quietly mastered source
435/// still draws as a shape. The fixtures peak around an eighth of full scale, and
436/// an eighth of a 30 px lane is a flat line -- which says "silent" about a file
437/// that is not.
438pub(crate) fn normalise(mut peaks: Vec<(f32, f32)>) -> Vec<(f32, f32)> {
439 let loudest = peaks.iter().fold(0f32, |m, &(lo, hi)| m.max(-lo).max(hi));
440 if loudest > 0. {
441 for (lo, hi) in &mut peaks {
442 *lo /= loudest;
443 *hi /= loudest;
444 }
445 }
446 peaks
447}
448
449/// The min/max envelope of `peaks` over the source seconds `from..to`, as
450/// `(x, top, bottom)` columns of a `w` x `h` box. Every point is inside that box
451/// -- a clip's waveform cannot paint over its neighbour -- and every column is
452/// at least a pixel tall, so silence reads as a line through the middle rather
453/// than as a polygon with no area.
454pub(crate) fn envelope(peaks: &[(f32, f32)], from: f64, to: f64, w: f32, h: f32) -> Vec<(f32, f32, f32)> {
455 if peaks.is_empty() || w <= 0. || h <= 0. {
456 return Vec::new();
457 }
458 let cols = ((w / WAVE_COL).ceil().max(1.) as usize).min(WAVE_COLS_MAX);
459 let mid = h / 2.;
460 (0..=cols)
461 .map(|col| {
462 let along = col as f64 / cols as f64;
463 let at = from + (to - from) * along;
464 // Casting a float to an integer saturates in Rust, so a source
465 // second past the end of the peaks clamps rather than wrapping.
466 let bucket = ((at * f64::from(WAVE_BPS)) as usize).min(peaks.len() - 1);
467 let (lo, hi) = peaks[bucket];
468 let top = (mid - hi.clamp(0., 1.) * mid).min(mid - 0.5);
469 let bottom = (mid - lo.clamp(-1., 0.) * mid).max(mid + 0.5);
470 (w * along as f32, top.max(0.), bottom.min(h))
471 })
472 .collect()
473}
474
475
476
477
478
479
480
481
482/// Records its parent's laid-out box: gpui hands a mouse listener the window
483/// position only, and the ruler sits behind the panel's padding. Paints
484/// nothing and takes no hitbox of its own, so the click still reaches the bar.
485pub(crate) fn bounds_probe(into: Rc<Cell<Bounds<Pixels>>>) -> impl IntoElement {
486 canvas(move |bounds, _, _| into.set(bounds), |_, _, _, _| ())
487 .absolute()
488 .size_full()
489}
490
491/// [`bounds_probe`] for a box something *else* is laid out against: it also asks
492/// for one more frame whenever the height changed.
493///
494/// A measurement is read by the frame after the one that took it, and a notice
495/// arriving over a paused picture repaints exactly once -- so without this the
496/// cue would sit under that notice until something else happened to draw, which
497/// on a paused window can be never.
498pub(crate) fn height_probe(into: Rc<Cell<Pixels>>) -> impl IntoElement {
499 canvas(
500 move |bounds, window, _| {
501 // Only on a change: an unconditional request is a repaint loop.
502 if into.replace(bounds.size.height) != bounds.size.height {
503 window.request_animation_frame();
504 }
505 },
506 |_, _, _, _| (),
507 )
508 .absolute()
509 .size_full()
510}
511
512/// Where along an element a click landed, 0..1. An element that was never
513/// painted has no width, and reads as its start rather than as NaN.
514pub(crate) fn frac_along(x: Pixels, bounds: Bounds<Pixels>) -> f32 {
515 if bounds.size.width <= px(0.) {
516 return 0.;
517 }
518 ((x - bounds.left()) / bounds.size.width).clamp(0., 1.)
519}
520
521/// Where along an element a click landed, in pixels from its own left edge:
522/// [`frac_along`] in the units the timeline is drawn in, since a [`Scale`]
523/// measures in pixels and not in shares of a bed. Clamped to the element -- a
524/// drag that slid off the end names its end -- and an element that was never
525/// painted reads as its start.
526pub(crate) fn px_along(x: Pixels, bounds: Bounds<Pixels>) -> f32 {
527 f32::from(x - bounds.left()).clamp(0., f32::from(bounds.size.width).max(0.))
528}
529
530/// [`px_along`] turned through a right angle, for the lane stack's scrollbar:
531/// how far down its track a press landed.
532pub(crate) fn px_down(y: Pixels, bounds: Bounds<Pixels>) -> f32 {
533 f32::from(y - bounds.top()).clamp(0., f32::from(bounds.size.height).max(0.))
534}
535
536/// One turn of the wheel as a single number, positive for a turn *up*, in
537/// whatever units the device sends (a mouse counts lines, a touchpad pixels).
538/// A tilt wheel's own axis counts as the same gesture: it is the sideways
539/// scroll a mouse that has one sends, and the controls this drives have one
540/// direction each, so the two axes are one answer here.
541pub(crate) fn wheel_delta(event: &ScrollWheelEvent) -> f32 {
542 let (dx, dy) = match event.delta {
543 ScrollDelta::Lines(d) => (d.x, d.y),
544 ScrollDelta::Pixels(d) => (f32::from(d.x), f32::from(d.y)),
545 };
546 match dy == 0. {
547 true => dx,
548 false => dy,
549 }
550}
551
552/// The frame a dropped clip's head lands on: `raw`, unless one of `marks` is
553/// within `tol` frames of where its head -- or its tail, `len` frames along --
554/// would come to rest, in which case that edge wins. The snap every timeline
555/// has: clips meet exactly instead of a frame apart, and the hand does not have
556/// to aim. The nearest mark wins, and a head landing on one beats a tail at the
557/// same distance -- what was dragged is the head.
558pub(crate) fn snapped(raw: u32, len: u32, tol: u32, marks: &[u32]) -> u32 {
559 let mut best: Option<(u32, u32)> = None;
560 for &mark in marks {
561 // Head on the mark, then tail on it -- a clip dragged up against the
562 // take in front of it snaps by whichever end reaches first.
563 for start in [Some(mark), mark.checked_sub(len)] {
564 let Some(start) = start else { continue };
565 let d = start.abs_diff(raw);
566 if d <= tol && best.is_none_or(|(near, _)| d < near) {
567 best = Some((d, start));
568 }
569 }
570 }
571 best.map_or(raw, |(_, start)| start)
572}
573
574/// The edges worth landing on, off *every* lane: both ends of every clip on the
575/// timeline, less `skip` -- the clip being dragged, which does not snap to where
576/// it already is -- and less `skip_link`, the group id of whatever is being
577/// dragged: its clips travel with it, and so does any caption the id names.
578/// `skip` is a lane's place in `lanes` and an index into it; `skip_link` is
579/// read off a caption by the caller, whose drag has no clip for `skip` to
580/// name. The playhead and the head of the timeline go on the end: a clip meets
581/// the cursor and the start of the show as readily as it meets another take.
582///
583/// All lanes rather than the one being dropped on, because a cut is made across
584/// the timeline: a title on V2 lines up with the shot under it, and a sound
585/// effect lines up with the frame it belongs to.
586pub(crate) fn snap_marks(
587 lanes: &[&[Clip]],
588 skip: Option<(usize, usize)>,
589 skip_link: Option<u32>,
590 playhead: u32,
591) -> Vec<u32> {
592 let mut marks: Vec<u32> = lanes
593 .iter()
594 .enumerate()
595 .flat_map(|(lane, clips)| {
596 clips
597 .iter()
598 .enumerate()
599 .filter(move |&(idx, clip)| {
600 Some((lane, idx)) != skip
601 && !(skip_link.is_some() && clip.link == skip_link)
602 })
603 .flat_map(|(_, clip)| [clip.start, clip.end()])
604 })
605 .collect();
606 marks.push(playhead);
607 marks.push(0);
608 marks
609}
610
611/// [`snapped`], and the mark that pulled it there -- the line the bed draws
612/// while the hand is still moving. `None` when nothing was near enough: a line
613/// standing over open bed would promise a landing that is not going to happen.
614/// The head is read before the tail, exactly as [`snapped`] prefers it.
615///
616/// `on` is the switch ([`ActionId::ToggleSnap`]): off, the gesture lands raw and
617/// draws no line at all, which is the whole point of being able to turn it off.
618pub(crate) fn snap_cue(on: bool, raw: u32, len: u32, tol: u32, marks: &[u32]) -> (u32, Option<u32>) {
619 if !on {
620 return (raw, None);
621 }
622 let start = snapped(raw, len, tol, marks);
623 let mark = [start, start.saturating_add(len)]
624 .into_iter()
625 .find(|mark| marks.contains(mark));
626 (start, mark)
627}
628
629/// Where a drag lands and the mark that pulled it there: the frame under the
630/// pointer, less however far into the box the hand grabbed it (so a clip travels
631/// with the pointer rather than jumping its head under it), snapped by
632/// [`snap_cue`]. One answer, asked by the shadow drawn in flight
633/// ([`Player::preview_ghost`]), by the line ([`Player::preview_drop`]) and by
634/// the drop that commits ([`Player::move_clip`]) -- which is what makes the
635/// promise and the landing the same frame.
636pub(crate) fn landing(
637 under: u32,
638 grab: u32,
639 len: u32,
640 on: bool,
641 tol: u32,
642 marks: &[u32],
643) -> (u32, Option<u32>) {
644 snap_cue(on, under.saturating_sub(grab), len, tol, marks)
645}
646
647/// Why this file may not go on that lane, in the words the refusal is told in --
648/// `None` when it may. A file with no picture belongs on an audio lane and
649/// nowhere else, and a still is silent, so an audio lane is the one place it
650/// cannot go. Asked twice: by the ghost tinting itself as refused on the way
651/// down, and by the insert that commits ([`Player::insert_source`]), so what is
652/// shown as impossible is exactly what is refused.
653pub(crate) fn lane_refuses(path: &Path, lane: Lane) -> Option<String> {
654 let name = file_name(path);
655 let label = lane.label();
656 match lane.kind {
657 LaneKind::Video if engine::is_audio(path) => {
658 Some(format!("NOT ON {label} — {name} has no picture; drop it on an audio lane"))
659 }
660 LaneKind::Audio if engine::is_image(path) => {
661 Some(format!("NOT ON {label} — {name} is a still image; drop it on a video lane"))
662 }
663 // A subtitle lane holds words and no media at all: the refusal is here
664 // rather than at the engine's door so the shadow is tinted red on the
665 // way down, like every other lane a file cannot go on.
666 LaneKind::Subtitle => Some(format!(
667 "NOT ON {label} — {name} is a file; a subtitle track takes captions, dragged from the \
668 Subtitles list"
669 )),
670 _ => None,
671 }
672}
673
674/// Where down an element a pointer sits, 0..1 from the top: the vertical twin
675/// of [`frac_along`], for the equalizer, whose gain axis is the y one. An
676/// element that was never painted reads as its middle -- flat, the one answer
677/// that changes nothing -- rather than as a full boost.
678pub(crate) fn frac_down(y: Pixels, bounds: Bounds<Pixels>) -> f32 {
679 if bounds.size.height <= px(0.) {
680 return 0.5;
681 }
682 ((y - bounds.top()) / bounds.size.height).clamp(0., 1.)
683}