forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

view.rs478 lines, 21.5 KiBHistoryRawDownload
1//! What of the timeline is on the bed and what of it is picked: the zoom,
2//! the scroll and the selection.
3
4use crate::*;
5
6/// The share of the bed a fit spreads the whole edit across: the rest is the
7/// margin on the right, so the last frame never sits against the bed's edge
8/// (DESIGN §7, about 2%).
9const FIT_SHARE: f32 = 0.98;
10
11/// The margin Zoom to selection leaves either side of the selected span, as a share of its length.
12const SELECTION_MARGIN: f64 = 0.05;
13
14impl Player {
15 /// The one place a clip becomes *the* selected one: a plain click, a
16 /// right-click that opens the menu, and every selection key go through
17 /// here, so what a keyboard marks and what a pointer marks are the same
18 /// state marked the same way (group and all -- see [`marked`]). One pick,
19 /// because one click names one thing; [`Player::pick`] is the ctrl+click
20 /// that grows the selection instead.
21 pub(crate) fn select(&mut self, target: (Lane, usize), cx: &mut Context<Self>) {
22 // A locked lane refuses selection (DESIGN §7): the item stays where it
23 // is and the toast offers the unlock.
24 if self.lane_locked_refusal(target.0) {
25 return;
26 }
27 self.drop_title_selection(cx);
28 self.drop_sel_cue();
29 self.selected.set_one(target);
30 self.gap = None;
31 cx.notify();
32 }
33
34 /// A press with ctrl held: the pick joins the selection, or leaves it if
35 /// it was already in -- the toggle that assembles a group by hand.
36 /// Without ctrl, a press on a member of an existing multi-pick keeps the
37 /// whole set rather than collapsing it -- collapsing here would make a
38 /// set-drag unreachable, since the drag begins on this very press. A
39 /// plain press anywhere else is exactly [`Player::select`]. Collapsing to
40 /// the one pressed clip belongs to the click that follows, once it is
41 /// plain a press and not the start of a drag (see the boxes' own
42 /// `on_click`), which is why every box on the bed asks this one for the
43 /// press and its own click listener for the collapse.
44 pub(crate) fn pick(&mut self, target: (Lane, usize), ctrl: bool, cx: &mut Context<Self>) {
45 if self.lane_locked_refusal(target.0) {
46 return;
47 }
48 self.drop_title_selection(cx);
49 self.drop_sel_cue();
50 match ctrl {
51 true => self.selected.toggle(target),
52 false if self.selected.contains(target) => {}
53 false => self.selected.set_one(target),
54 }
55 self.gap = None;
56 // A picked envelope key belongs to the clip it sits on; another clip takes it away.
57 if self.gain_pick.is_some_and(|(l, i, _)| (l, i) != target) {
58 self.gain_pick = None;
59 }
60 cx.notify();
61 }
62
63 /// Empties every kind of pick the timeline holds at once: clips, a picked gap, a title and a
64 /// caption. Escape does this, so the one thing left picked is always the one named last.
65 pub(crate) fn clear_picks(&mut self, cx: &mut Context<Self>) {
66 self.selected = Selection::new();
67 self.gap = None;
68 self.drop_title_selection(cx);
69 self.drop_sel_cue();
70 cx.notify();
71 }
72
73 /// Every clip the playhead is over, one per lane, in the order the lanes are
74 /// drawn -- video first, which is the order [`PlaybackSession::lanes`] comes
75 /// in. What the select key walks.
76 pub(crate) fn under_playhead(&self) -> Vec<(Lane, usize)> {
77 let Some(session) = &self.session else {
78 return Vec::new();
79 };
80 let now = session.now();
81 session
82 .lanes()
83 .into_iter()
84 .filter_map(|lane| Some((lane, session.lane_clip_at(lane, now)?)))
85 .collect()
86 }
87 /// Selects the clip under the playhead, and on a repeat press the next
88 /// lane's -- so one key reaches every clip the playhead is over, which is
89 /// what makes selection (and everything that acts on a selection: delete,
90 /// lift, the equalizer, the grade) reachable with no pointer at all.
91 pub(crate) fn select_under_playhead(&mut self, cx: &mut Context<Self>) {
92 let under = self.under_playhead();
93 let Some(&first) = under.first() else {
94 self.notify_user("Nothing under the playhead".into());
95 cx.notify();
96 return;
97 };
98 // Where the current selection sits in that walk decides what "again"
99 // means; a selection off the playhead starts the walk over.
100 let next = self
101 .selected
102 .anchor()
103 .and_then(|sel| under.iter().position(|&clip| clip == sel))
104 .map_or(first, |at| under[(at + 1) % under.len()]);
105 self.select(next, cx);
106 }
107
108 /// Walks the selection along its own lane, wrapping at either end. Nothing
109 /// selected means nothing to walk from, so it selects under the playhead
110 /// exactly as the select key does: either key can start as well as continue.
111 pub(crate) fn select_step(&mut self, forward: bool, cx: &mut Context<Self>) {
112 let clips = self
113 .selected
114 .anchor()
115 .zip(self.session.as_ref())
116 .map_or(0, |((lane, _), session)| session.lane_clips(lane).len());
117 match (self.selected.anchor(), clips) {
118 // An empty lane is a selection nothing can be stepped from -- as is
119 // no selection at all, and the playhead answers both.
120 (Some((lane, idx)), len) if len > 0 => {
121 let next = if forward {
122 (idx + 1) % len
123 } else {
124 (idx + len - 1) % len
125 };
126 self.select((lane, next), cx);
127 }
128 _ => self.select_under_playhead(cx),
129 }
130 }
131
132 /// Every placement on every lane, in the order the lanes are drawn: what
133 /// Select All marks -- the clips and the captions both, one selection that
134 /// a Group can take apart lane by lane and a Delete can walk pick by pick.
135 pub(crate) fn select_all(&mut self, cx: &mut Context<Self>) {
136 let Some(session) = &self.session else {
137 return;
138 };
139 let mut selected = Selection::new();
140 for lane in session.lanes() {
141 // A locked lane's items are not selectable, so Select All leaves
142 // them out rather than marking what the next edit would refuse.
143 if session.lane_locked(lane) {
144 continue;
145 }
146 let len = match lane.kind {
147 LaneKind::Subtitle => session.sub_lane(lane).len(),
148 _ => session.lane_clips(lane).len(),
149 };
150 for idx in 0..len {
151 selected.add((lane, idx));
152 }
153 }
154 self.selected = selected;
155 if self.selected.is_empty() {
156 // A key that does nothing looks broken: an empty timeline has
157 // nothing to select, and that is a thing to say rather than skip.
158 self.notify_user("Nothing to select: the timeline is empty".into());
159 }
160 cx.notify();
161 }
162
163 /// Opens the list of fit policies for the clip the picture is coming from -- the
164 /// clicked one when it is a video clip, else the composite's own, exactly as
165 /// the colour card picks its target -- at `at`, the one in force ticked.
166 ///
167 /// Only means anything when the clip is not the project's size -- a clip
168 /// that already fills the canvas looks the same under all four -- so the
169 /// notice after a pick says the size it is placing, not just the word.
170 pub(crate) fn open_fit_list(&mut self, at: Point<Pixels>, cx: &mut Context<Self>) {
171 if self.exporting().is_some() {
172 return;
173 }
174 match self.fit_target() {
175 Ok((lane, idx)) => self.open_picker(Pick::Fit(lane, idx), at, cx),
176 Err(why) => {
177 self.notify_user(why.into());
178 cx.notify();
179 }
180 }
181 }
182
183 /// The clip the fit list is about, or why there is none.
184 pub(crate) fn fit_target(&self) -> Result<(Lane, usize), &'static str> {
185 let session = self.session.as_ref().ok_or("Nothing to fit: no file open")?;
186 // A caption the hand is on names the clip it was pinned to, and the
187 // policy is that clip's; one in no group has no picture to fit and it
188 // says so, rather than fitting the playhead's clip behind the hand's
189 // back.
190 let target = match self.selected.anchor() {
191 Some((lane, idx)) if lane.kind == LaneKind::Subtitle => {
192 Some(caption_media_half(session, (lane, idx), LaneKind::Video).ok_or("Nothing to fit: a caption has no picture")?)
193 }
194 // A sound half has no picture of its own: the playhead's clip, as
195 // it always was.
196 Some((lane, _)) if lane.kind == LaneKind::Audio => session.video_clip_at(session.now()),
197 other => other.or_else(|| session.video_clip_at(session.now())),
198 };
199 target.ok_or("Nothing to fit: no clip under the playhead")
200 }
201
202 /// One clip's fit policy set, whichever asked: the stroke that steps to the
203 /// next one and the list that names one outright come through here, so they
204 /// cannot differ in what they do or in what they say they did.
205 pub(crate) fn apply_fit(
206 &mut self,
207 lane: Lane,
208 idx: usize,
209 fit: FitPolicy,
210 cx: &mut Context<Self>,
211 ) {
212 // The policy has to have moved before this is an edit: `set_fit`
213 // answers "the index existed", not "the value changed" (the engine
214 // snapshot-and-rewrites the same policy and still says true), and the
215 // list keeps the row already in force clickable -- so the engine's
216 // own bool would light the ledger's `unsaved` ghost over a project
217 // nobody touched.
218 if let Some(session) = &mut self.session
219 && session.fit_of(lane, idx) != fit
220 && session.set_fit(lane, idx, fit)
221 {
222 let (w, h) = session.resolution();
223 // A clip's own fit policy, written from a click: arms autosave
224 // and the close gate itself ([`Player::act`]'s list is the action
225 // doors only).
226 self.mark_dirty();
227 self.notify_user(format!("Fit to frame: {} on {w}x{h}", fit_label(fit)).into());
228 self.reset_after_reseek();
229 }
230 cx.notify();
231 }
232
233 /// The scale against the bed it is drawn on and the timeline it is drawn
234 /// from: every clamp, zoom and scroll is worked out through this, and the
235 /// bed is measured off the ruler's probe rather than remembered, so a
236 /// resized window is a resized view on the very next answer.
237 pub(crate) fn view(&self) -> View {
238 View {
239 scale: self.scale,
240 bed: f32::from(self.ruler.get().size.width),
241 duration: self.drawn_duration(),
242 fps: self.fps,
243 }
244 }
245
246 /// Magnifies the timeline about a point that stays put: `anchor` is how many
247 /// pixels along the bed to hold still (a ctrl+wheel holds the pointer), and
248 /// with none it is the playhead -- so the frame being worked on is still the
249 /// frame on screen after the zoom. Clamped at both ends by [`View`]: out
250 /// stops at the whole timeline on the bed, in at a handful of frames.
251 pub(crate) fn zoom(&mut self, factor: f32, anchor: Option<f32>, cx: &mut Context<Self>) {
252 let view = self.view();
253 let at = self.playhead(view.duration);
254 let anchor = anchor.unwrap_or_else(|| self.scale.px_at(at).clamp(0., view.bed));
255 self.scale = view.zoomed(factor, anchor);
256 // The view a hand chose. A zoom about the playhead leaves it on the
257 // bed, so this is given back on the very next frame and only a zoom
258 // that took the head off screen -- ctrl+wheel away from it -- holds.
259 self.panned = true;
260 // A hand's zoom ends a fit that was following the bed: from here the
261 // scale is the hand's, and a resized window keeps it.
262 self.fitted_bed = None;
263 cx.notify();
264 }
265
266 /// All the way back out: the whole timeline across the bed, and the one
267 /// thing that reads the timeline's own length to decide how wide a second
268 /// is drawn.
269 pub(crate) fn zoom_fit(&mut self, cx: &mut Context<Self>) {
270 // An unpainted bed has no width to fit into: the fit is asked for again
271 // on the first frame that has one ([`Render`]) rather than taken now
272 // against the default scale, which is the 40 px/s a first import used
273 // to land at.
274 match self.view().bed > 0. {
275 true => {
276 self.fit_to_bed();
277 self.fit_pending = false;
278 }
279 false => self.fit_pending = true,
280 }
281 cx.notify();
282 }
283
284 /// View > Zoom to selection: the view fitted to the span the selected clips cover, with a
285 /// margin of [`SELECTION_MARGIN`] of that span either side. The oracle refuses it with
286 /// nothing selected, so the empty case here only leaves the view as it is.
287 pub(crate) fn zoom_to_selection(&mut self, cx: &mut Context<Self>) {
288 let Some((from, to)) = self.selection_span() else {
289 cx.notify();
290 return;
291 };
292 let view = self.view();
293 if view.bed <= 0. {
294 cx.notify();
295 return;
296 }
297 let margin = (to - from) * SELECTION_MARGIN;
298 let from = (from - margin).max(0.);
299 let len = (to + margin - from).max(1. / self.fps);
300 let pps = f64::from(view.bed) / len;
301 self.scale = View {
302 scale: Scale { pps, start: from },
303 ..view
304 }
305 .settled();
306 // A hand's fit, the same bookkeeping a zoom keeps: the scale is the view's own now.
307 self.panned = true;
308 self.fitted_bed = None;
309 cx.notify();
310 }
311
312 /// The seconds the selected placements cover, first start to last end, or `None` with no
313 /// placement picked.
314 fn selection_span(&self) -> Option<(f64, f64)> {
315 let session = self.session.as_ref()?;
316 let fps = self.fps;
317 let (picks, _) = self.marks();
318 let frames = picks.iter().filter_map(|&(lane, idx)| match lane.kind {
319 LaneKind::Subtitle => session.sub_lane(lane).get(idx).map(|s| (s.start, s.start + s.frames)),
320 _ => session.lane_clips(lane).get(idx).map(|c| (c.start, c.end())),
321 });
322 let (start, end) = frames.fold(None, |acc: Option<(u32, u32)>, (a, b)| match acc {
323 None => Some((a, b)),
324 Some((x, y)) => Some((x.min(a), y.max(b))),
325 })?;
326 Some((f64::from(start) / fps, f64::from(end) / fps))
327 }
328
329 /// The whole timeline across the bed, with the margin ([`FIT_SHARE`]), and
330 /// the bed width it was worked out for. That width is what keeps the fit
331 /// sticky: while it still matches the bed, nothing refits, and a window the
332 /// compositor resizes -- the first frame measures the initial size -- is
333 /// refitted by [`Render`] the next frame. Only a bed that has been measured
334 /// is fitted, so a zero width is never stored.
335 pub(crate) fn fit_to_bed(&mut self) {
336 let view = self.view();
337 self.scale = View {
338 bed: view.bed * FIT_SHARE,
339 ..view
340 }
341 .fit();
342 self.fitted_bed = Some(view.bed);
343 }
344
345 /// Slides the view along the timeline by `notches` of the wheel, later in
346 /// time for a positive one and [`SCROLL_NOTCH_SHARE`] of the bed each. The
347 /// scale is untouched: this is the timeline's scrollbar, and the only thing
348 /// on the panel that moves what is on screen without magnifying it.
349 pub(crate) fn scroll_view(&mut self, notches: f32, cx: &mut Context<Self>) {
350 let view = self.view();
351 // Nothing painted yet: there is no bed to measure a notch against, and
352 // a start moved against a zero width would be a jump to the head.
353 if view.bed <= 0. {
354 return;
355 }
356 self.scale = view.scrolled(notches * view.bed * SCROLL_NOTCH_SHARE);
357 // The one gesture whose whole purpose is to look away from the
358 // playhead: while playing it wins over the follow, which is what every
359 // editor does with a scroll during playback.
360 self.panned = true;
361 // A scroll is a hand's view too: it ends the sticky fit.
362 self.fitted_bed = None;
363 cx.notify();
364 }
365
366 /// A sample of a thumb drag: the window starts where the thumb's grabbed
367 /// point sits under the pointer, clamped by the same `settled` every other
368 /// scroll answers to. No reseek, no worker -- the view is the only thing
369 /// moving.
370 pub(crate) fn scroll_drag_to(&mut self, x: Pixels, cx: &mut Context<Self>) {
371 let at = px_along(x, self.scroll_track.get());
372 self.pan_window_to(at, cx);
373 }
374
375 /// The window follows a drag held by `scroll_drag`: `at` is how far along
376 /// the bed the pointer is, in px. Shared by the scrollbar's thumb and the
377 /// overview's window box (`ui/bench_stance/overview.rs`), so both pan the
378 /// same way. A drag is a hand's view, so it holds against the follow and
379 /// ends the sticky fit.
380 pub(crate) fn pan_window_to(&mut self, at: f32, cx: &mut Context<Self>) {
381 let Some(grab) = self.scroll_drag else {
382 return;
383 };
384 self.scale = panned_view(self.view(), at, grab);
385 self.panned = true;
386 self.fitted_bed = None;
387 cx.notify();
388 }
389
390 /// The lane stack's own scroll, as one number: how far down the column
391 /// has been taken, clamped to what it can show. The names and the beds
392 /// are one column (`id("lanes")`), so one offset moves them together and
393 /// this is the whole of the stack's scrolling -- the wheel over the names
394 /// and the thumb on the strip both land here.
395 fn lanes_taken(&self, to: f32) -> f32 {
396 let max = f32::from(self.lanes_scroll.max_offset().height);
397 to.clamp(0., max)
398 }
399
400 /// A sample of the lane thumb's drag: the stack is taken to where the
401 /// thumb's grabbed point sits under the pointer, clamped by the same
402 /// `max_offset` the column's own wheel answers to. No reseek, no repaint
403 /// of anything outside the column -- the view is not moving.
404 pub(crate) fn lanes_drag_to(&mut self, y: Pixels, cx: &mut Context<Self>) {
405 let Some(grab) = self.lanes_drag else {
406 return;
407 };
408 let track = f32::from(self.lanes_scroll.bounds().size.height);
409 let max = f32::from(self.lanes_scroll.max_offset().height);
410 let (_, thumb_h) = lanes_thumb(track, track + max, track, 0.);
411 let at = px_down(y, self.lanes_scroll.bounds());
412 let to = self.lanes_taken((at - grab).max(0.) / (track - thumb_h).max(1.) * max);
413 self.lanes_scroll
414 .set_offset(point(self.lanes_scroll.offset().x, px(-to)));
415 cx.notify();
416 }
417
418 /// One notch of the wheel anywhere over the timeline -- the ruler or a
419 /// lane's bed alike, since a hand aims at the clip it is working on and not
420 /// at the strip above it. Ctrl zooms about the pointer, Shift (or a sideways
421 /// swipe) scrolls the view along, and a bare wheel scrolls the lanes when
422 /// more lie below -- else it runs the view along: the NLE convention.
423 ///
424 /// The anchor is measured off the ruler's probe wherever the pointer is,
425 /// because that probe *is* the bed's x-to-time mapping ([`HEADER_W`]) and
426 /// every lane is drawn through the same one.
427 pub(crate) fn timeline_wheel(&mut self, event: &ScrollWheelEvent, cx: &mut Context<Self>) {
428 let d = wheel_delta(event);
429 if d == 0. {
430 return;
431 }
432 let factor = match d > 0. {
433 true => ZOOM_STEP,
434 false => 1. / ZOOM_STEP,
435 };
436 let (dx, dy) = match event.delta {
437 ScrollDelta::Lines(l) => (l.x, l.y),
438 ScrollDelta::Pixels(p) => (f32::from(p.x), f32::from(p.y)),
439 };
440 if event.modifiers.control {
441 // Ctrl zooms about the pointer, the NLE convention.
442 let anchor = px_along(event.position.x, self.ruler.get());
443 self.zoom(factor, Some(anchor), cx);
444 } else if event.modifiers.shift || dx.abs() > dy.abs() {
445 // Shift, or a sideways swipe on a trackpad, runs the view along the film. Up or
446 // left is back towards the head, the way a page reads.
447 self.scroll_view(-d.signum(), cx);
448 } else if f32::from(self.lanes_scroll.max_offset().height) > 0. {
449 // A plain wheel scrolls the stack of lanes when there are more than fit.
450 let by = match event.delta {
451 ScrollDelta::Lines(l) => l.y * 40.,
452 ScrollDelta::Pixels(p) => f32::from(p.y),
453 };
454 let to = self.lanes_taken(-f32::from(self.lanes_scroll.offset().y) - by);
455 self.lanes_scroll.set_offset(point(self.lanes_scroll.offset().x, px(-to)));
456 cx.notify();
457 } else {
458 // Nothing below to scroll to: the wheel runs the film, as it did before.
459 self.scroll_view(-d.signum(), cx);
460 }
461 }
462}
463
464/// The scale a window drag asks for: the start moves so the point `grab` px
465/// into the window sits under `at` (both px along the bed). `settled` owns
466/// the ends -- a window dragged past either one stops at it, and so does a
467/// thumb on a timeline so long it sits at its floor width.
468pub(crate) fn panned_view(view: View, at: f32, grab: f32) -> Scale {
469 let start = f64::from((at - grab).max(0.)) / f64::from(view.bed.max(1.)) * view.duration;
470 View {
471 scale: Scale {
472 start,
473 ..view.scale
474 },
475 ..view
476 }
477 .settled()
478}