forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

viewer_view.rs1008 lines, 39.9 KiBHistoryRawDownload
1//! How the viewer looks at the picture (REDESIGN §2.1): the zoom, the playback
2//! quality, the guides and the aspect mask. All of it is view state -- it
3//! changes what is drawn on this screen, never the project and never an
4//! export -- so it is kept in the project's view file ([`crate::view_state`])
5//! and has no MCP operation.
6
7/// The viewer's zoom: `Fit` letterboxes the whole frame, the rest show the
8/// frame at a fraction of the project's own pixels, centred and pannable.
9#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
10pub(crate) enum Zoom {
11 #[default]
12 Fit,
13 P25,
14 P50,
15 P100,
16 P200,
17}
18
19impl Zoom {
20 pub(crate) const ALL: [Zoom; 5] = [Zoom::Fit, Zoom::P25, Zoom::P50, Zoom::P100, Zoom::P200];
21
22 pub(crate) fn label(self) -> &'static str {
23 match self {
24 Zoom::Fit => "Fit",
25 Zoom::P25 => "25%",
26 Zoom::P50 => "50%",
27 Zoom::P100 => "100%",
28 Zoom::P200 => "200%",
29 }
30 }
31
32 /// The project pixels per device pixel; `None` for `Fit`.
33 pub(crate) fn factor(self) -> Option<f32> {
34 match self {
35 Zoom::Fit => None,
36 Zoom::P25 => Some(0.25),
37 Zoom::P50 => Some(0.5),
38 Zoom::P100 => Some(1.),
39 Zoom::P200 => Some(2.),
40 }
41 }
42
43 /// The stop one wheel notch away; `Fit` is the bottom of the ladder's far
44 /// end, so a zoom-out never leaves the list.
45 pub(crate) fn step(self, closer: bool) -> Zoom {
46 let at = Zoom::ALL.iter().position(|z| *z == self).unwrap_or(0);
47 // Fit sits first in the list but is the "smallest" stop to a wheel:
48 // zooming out from 25% lands on it.
49 let order = [Zoom::Fit, Zoom::P25, Zoom::P50, Zoom::P100, Zoom::P200];
50 let next = match closer {
51 true => (at + 1).min(order.len() - 1),
52 false => at.saturating_sub(1),
53 };
54 order[next]
55 }
56
57 pub(crate) fn key(self) -> &'static str {
58 match self {
59 Zoom::Fit => "fit",
60 Zoom::P25 => "25",
61 Zoom::P50 => "50",
62 Zoom::P100 => "100",
63 Zoom::P200 => "200",
64 }
65 }
66
67 pub(crate) fn from_key(key: &str) -> Option<Zoom> {
68 Zoom::ALL.into_iter().find(|z| z.key() == key)
69 }
70}
71
72/// The resolution the picture is decoded and scaled at *while playing*. A
73/// paused frame is always full quality, and an export never reads this.
74#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
75pub(crate) enum Quality {
76 #[default]
77 Full,
78 Half,
79 Quarter,
80}
81
82impl Quality {
83 pub(crate) const ALL: [Quality; 3] = [Quality::Full, Quality::Half, Quality::Quarter];
84
85 pub(crate) fn label(self) -> &'static str {
86 match self {
87 Quality::Full => "Full",
88 Quality::Half => "Half",
89 Quality::Quarter => "Quarter",
90 }
91 }
92
93 /// The label on the closed header dropdown: "Full" alone read as a zoom next to "Fit".
94 pub(crate) fn closed_label(self) -> &'static str {
95 match self {
96 Quality::Full => "Full quality",
97 Quality::Half => "Half quality",
98 Quality::Quarter => "Quarter quality",
99 }
100 }
101
102 pub(crate) fn detail(self) -> &'static str {
103 match self {
104 Quality::Full => "every pixel",
105 Quality::Half => "half width and height while playing",
106 Quality::Quarter => "quarter width and height while playing",
107 }
108 }
109
110 /// The share of each side kept while playing.
111 pub(crate) fn factor(self) -> f32 {
112 match self {
113 Quality::Full => 1.,
114 Quality::Half => 0.5,
115 Quality::Quarter => 0.25,
116 }
117 }
118
119 pub(crate) fn key(self) -> &'static str {
120 match self {
121 Quality::Full => "full",
122 Quality::Half => "half",
123 Quality::Quarter => "quarter",
124 }
125 }
126
127 pub(crate) fn from_key(key: &str) -> Option<Quality> {
128 Quality::ALL.into_iter().find(|q| q.key() == key)
129 }
130}
131
132/// The guide lines drawn over the picture to judge a composition by.
133#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
134pub(crate) enum Guide {
135 #[default]
136 Off,
137 /// The action-safe and title-safe rectangles, named in a small label.
138 Safe,
139 /// The rule of thirds.
140 Thirds,
141 /// A cross at the centre of the frame.
142 Centre,
143}
144
145impl Guide {
146 pub(crate) const ALL: [Guide; 4] = [Guide::Off, Guide::Safe, Guide::Thirds, Guide::Centre];
147
148 pub(crate) fn label(self) -> &'static str {
149 match self {
150 Guide::Off => "Off",
151 Guide::Safe => "Safe areas",
152 Guide::Thirds => "Thirds",
153 Guide::Centre => "Centre cross",
154 }
155 }
156
157 pub(crate) fn detail(self) -> &'static str {
158 match self {
159 Guide::Off => "",
160 Guide::Safe => "action and title",
161 Guide::Thirds => "rule of thirds",
162 Guide::Centre => "",
163 }
164 }
165
166 pub(crate) fn key(self) -> &'static str {
167 match self {
168 Guide::Off => "off",
169 Guide::Safe => "safe",
170 Guide::Thirds => "thirds",
171 Guide::Centre => "centre",
172 }
173 }
174
175 /// A key as saved; the old on/off flag (`1`, `0`) still reads.
176 pub(crate) fn from_key(key: &str) -> Option<Guide> {
177 match key {
178 "1" => Some(Guide::Safe),
179 "0" => Some(Guide::Off),
180 _ => Guide::ALL.into_iter().find(|g| g.key() == key),
181 }
182 }
183}
184
185/// A crop shape to judge a vertical or square delivery against.
186#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
187pub(crate) enum Mask {
188 #[default]
189 None,
190 Vertical,
191 Square,
192 Portrait,
193}
194
195impl Mask {
196 pub(crate) const ALL: [Mask; 4] = [Mask::None, Mask::Vertical, Mask::Square, Mask::Portrait];
197
198 pub(crate) fn label(self) -> &'static str {
199 match self {
200 Mask::None => "None",
201 Mask::Vertical => "9:16",
202 Mask::Square => "1:1",
203 Mask::Portrait => "4:5",
204 }
205 }
206
207 pub(crate) fn detail(self) -> &'static str {
208 match self {
209 Mask::None => "",
210 Mask::Vertical => "Reels, Shorts, TikTok",
211 Mask::Square => "square feed",
212 Mask::Portrait => "portrait feed",
213 }
214 }
215
216 /// Width over height of the kept window.
217 pub(crate) fn ratio(self) -> Option<f32> {
218 match self {
219 Mask::None => None,
220 Mask::Vertical => Some(9. / 16.),
221 Mask::Square => Some(1.),
222 Mask::Portrait => Some(4. / 5.),
223 }
224 }
225
226 pub(crate) fn key(self) -> &'static str {
227 match self {
228 Mask::None => "none",
229 Mask::Vertical => "9:16",
230 Mask::Square => "1:1",
231 Mask::Portrait => "4:5",
232 }
233 }
234
235 pub(crate) fn from_key(key: &str) -> Option<Mask> {
236 Mask::ALL.into_iter().find(|m| m.key() == key)
237 }
238}
239
240use crate::*;
241
242/// Everything about the viewer's look that a project remembers.
243#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
244pub(crate) struct Prefs {
245 pub(crate) zoom: Zoom,
246 pub(crate) quality: Quality,
247 pub(crate) guide: Guide,
248 pub(crate) mask: Mask,
249}
250
251/// An axis-aligned rectangle `(x, y, w, h)` in logical pixels.
252pub(crate) type Rect = (f32, f32, f32, f32);
253
254/// The size the picture is drawn at inside a box `(bw, bh)`: the whole frame
255/// fitted for `Fit`, otherwise the project's `native` pixels scaled by the
256/// zoom (device pixels over `dpr`).
257pub(crate) fn shown_size(zoom: Zoom, native: (f32, f32), bx: (f32, f32), dpr: f32) -> (f32, f32) {
258 match zoom.factor() {
259 None => {
260 let s = (bx.0 / native.0).min(bx.1 / native.1);
261 (native.0 * s, native.1 * s)
262 }
263 Some(z) => (native.0 * z / dpr.max(0.1), native.1 * z / dpr.max(0.1)),
264 }
265}
266
267/// The pan offset (from centred) clamped so the picture never leaves its box:
268/// zero on an axis the picture fits on.
269pub(crate) fn clamp_pan(pan: (f32, f32), shown: (f32, f32), bx: (f32, f32)) -> (f32, f32) {
270 let lim = |s: f32, b: f32| ((s - b) / 2.).max(0.);
271 let (lx, ly) = (lim(shown.0, bx.0), lim(shown.1, bx.1));
272 (pan.0.clamp(-lx, lx), pan.1.clamp(-ly, ly))
273}
274
275/// Where the picture lands inside a box of size `bx` whose top-left is `origin`:
276/// centred, offset by the (clamped) `pan`, whole pixels. The one rectangle the
277/// picture, its guides and the titles and captions over it are placed against.
278pub(crate) fn picture_rect(zoom: Zoom, native: (f32, f32), bx: (f32, f32), origin: (f32, f32), pan: (f32, f32), dpr: f32) -> Rect {
279 let shown = shown_size(zoom, native, bx, dpr);
280 let pan = clamp_pan(pan, shown, bx);
281 (
282 (origin.0 + (bx.0 - shown.0) / 2. + pan.0).round(),
283 (origin.1 + (bx.1 - shown.1) / 2. + pan.1).round(),
284 shown.0.round(),
285 shown.1.round(),
286 )
287}
288
289/// A rectangle of `share` of the frame on each side, centred.
290pub(crate) fn inset(frame: Rect, share: f32) -> Rect {
291 let (x, y, w, h) = frame;
292 (x + w * (1. - share) / 2., y + h * (1. - share) / 2., w * share, h * share)
293}
294
295/// The window of ratio `ratio` (w/h) kept inside `frame`, centred.
296pub(crate) fn mask_window(frame: Rect, ratio: f32) -> Rect {
297 let (x, y, w, h) = frame;
298 if w / h > ratio {
299 let kw = h * ratio;
300 (x + (w - kw) / 2., y, kw, h)
301 } else {
302 let kh = w / ratio;
303 (x, y + (h - kh) / 2., w, kh)
304 }
305}
306
307/// The pieces of `frame` outside `window`: up to four rectangles (top, bottom,
308/// left, right) that a mask dims, empty ones left out.
309pub(crate) fn outside(frame: Rect, window: Rect) -> Vec<Rect> {
310 let (fx, fy, fw, fh) = frame;
311 let (wx, wy, ww, wh) = window;
312 [
313 (fx, fy, fw, wy - fy),
314 (fx, wy + wh, fw, fy + fh - (wy + wh)),
315 (fx, wy, wx - fx, wh),
316 (wx + ww, wy, fx + fw - (wx + ww), wh),
317 ]
318 .into_iter()
319 .filter(|r| r.2 > 0.5 && r.3 > 0.5)
320 .collect()
321}
322
323impl Player {
324 /// Where a header control's list hangs: under the control, or under the header's left end
325 /// before the first paint measured anything.
326 pub(crate) fn viewer_anchor(&self, i: usize) -> Point<Pixels> {
327 let b = self.viewer_btns[i].get();
328 match b.size.width > px(0.) {
329 true => point(b.origin.x, b.origin.y + b.size.height + px(2.)),
330 false => point(px(12.), px(60.)),
331 }
332 }
333
334 /// A viewer setting changed: keep it with the project's view and repaint.
335 pub(crate) fn viewer_changed(&mut self, cx: &mut Context<Self>) {
336 self.save_view_state();
337 cx.notify();
338 }
339
340 pub(crate) fn set_viewer_zoom(&mut self, zoom: Zoom, cx: &mut Context<Self>) {
341 if zoom != self.viewer.zoom {
342 self.viewer_pan = (0., 0.);
343 }
344 self.viewer.zoom = zoom;
345 self.viewer_changed(cx);
346 }
347
348 /// The picture's native pixels, or `None` with nothing loaded.
349 fn viewer_native(&self) -> Option<(f32, f32)> {
350 let meta = self.active_session()?.meta();
351 Some((meta.width as f32, meta.height as f32))
352 }
353
354 /// The native size, or the image's own when no session is up to ask.
355 pub(crate) fn viewer_native_or(&self, image: &RenderImage) -> (f32, f32) {
356 self.viewer_native().unwrap_or_else(|| {
357 let s = image.size(0);
358 (s.width.0 as f32, s.height.0 as f32)
359 })
360 }
361
362 /// The project frame's outline over an empty picture: a 1 px line at the project's aspect,
363 /// fitted into the region, so the canvas edge reads on a near-black picture. `None` while a
364 /// picture is shown (its own edge is the outline), with no project, or before the first paint.
365 pub(crate) fn empty_canvas_outline(&self) -> Option<AnyElement> {
366 if self.image.is_some() {
367 return None;
368 }
369 let (w, h) = self.session.as_ref()?.resolution();
370 let b = self.picture_box.get();
371 let (bw, bh) = (f32::from(b.size.width), f32::from(b.size.height));
372 if bw <= 1. || bh <= 1. || w == 0 || h == 0 {
373 return None;
374 }
375 let k = (bw / w as f32).min(bh / h as f32);
376 let (fw, fh) = (w as f32 * k, h as f32 * k);
377 let (x, y) = ((bw - fw) / 2., (bh - fh) / 2.);
378 Some(
379 div()
380 .absolute()
381 .left(px(x.round()))
382 .top(px(y.round()))
383 .w(px(fw.round()))
384 .h(px(fh.round()))
385 .border_1()
386 .border_color(rgba(crate::ui::theme::tokens().line))
387 .into_any_element(),
388 )
389 }
390
391 /// The picture's rectangle in the picture region's own coordinates, as it is
392 /// drawn at the current zoom and pan; `None` with nothing loaded or measured.
393 pub(crate) fn viewer_frame_local(&self, dpr: f32) -> Option<Rect> {
394 let native = self.viewer_native()?;
395 let b = self.picture_box.get();
396 let bx = (f32::from(b.size.width), f32::from(b.size.height));
397 (bx.0 > 1. && bx.1 > 1.).then(|| picture_rect(self.viewer.zoom, native, bx, (0., 0.), self.viewer_pan, dpr))
398 }
399
400 /// Drags the zoomed picture by `(dx, dy)`, kept inside its box.
401 fn viewer_pan_by(&mut self, d: (f32, f32), dpr: f32, cx: &mut Context<Self>) {
402 let (Some(native), b) = (self.viewer_native(), self.picture_box.get()) else {
403 return;
404 };
405 let bx = (f32::from(b.size.width), f32::from(b.size.height));
406 let shown = shown_size(self.viewer.zoom, native, bx, dpr);
407 self.viewer_pan = clamp_pan((self.viewer_pan.0 + d.0, self.viewer_pan.1 + d.1), shown, bx);
408 cx.notify();
409 }
410
411 /// Wheel over the picture: Ctrl steps the zoom, a bare wheel pans a zoomed picture.
412 pub(crate) fn viewer_wheel(&mut self, event: &ScrollWheelEvent, window: &Window, cx: &mut Context<Self>) {
413 if event.modifiers.control {
414 let d = crate::timeline_math::wheel_delta(event);
415 if d != 0. {
416 self.set_viewer_zoom(self.viewer.zoom.step(d > 0.), cx);
417 }
418 } else if self.viewer.zoom != Zoom::Fit {
419 let d = event.delta.pixel_delta(px(20.));
420 self.viewer_pan_by((f32::from(d.x), f32::from(d.y)), window.scale_factor(), cx);
421 }
422 }
423
424 pub(crate) fn viewer_drag_start(&mut self, at: Point<Pixels>) {
425 if self.viewer.zoom != Zoom::Fit {
426 self.viewer_drag = Some(at);
427 }
428 }
429
430 /// The button came up: the pan (or the handle drag) is over.
431 pub(crate) fn viewer_drag_end(&mut self, cx: &mut Context<Self>) {
432 self.viewer_drag = None;
433 self.viewer_handle_end(cx);
434 }
435
436 pub(crate) fn viewer_drag_move(&mut self, at: Point<Pixels>, shift: bool, window: &Window, cx: &mut Context<Self>) {
437 if self.viewer_handle.is_some() {
438 self.viewer_handle_move(at, shift, cx);
439 } else if let Some(from) = self.viewer_drag {
440 self.viewer_drag = Some(at);
441 self.viewer_pan_by((f32::from(at.x - from.x), f32::from(at.y - from.y)), window.scale_factor(), cx);
442 }
443 }
444
445 /// The size, in device pixels, the session is asked to paint at inside `region`: the
446 /// zoom's own size (or the fitted one), reduced by the playback quality while it plays.
447 pub(crate) fn viewer_target(&self, fitted: (u32, u32), native: (u32, u32), playing: bool) -> (u32, u32) {
448 let (w, h) = match self.viewer.zoom.factor() {
449 Some(z) => ((native.0 as f32 * z).round() as u32, (native.1 as f32 * z).round() as u32),
450 None => fitted,
451 };
452 let q = if playing { self.viewer.quality.factor() } else { 1. };
453 (((w as f32) * q).round() as u32, ((h as f32) * q).round() as u32)
454 }
455
456 /// Whether the picture is being drawn below full resolution right now, for the pill.
457 pub(crate) fn viewer_reduced(&self) -> bool {
458 self.viewer.quality != Quality::Full && self.active_session().is_some_and(|s| s.is_playing())
459 }
460}
461
462/// How close, in screen px, a moved picture's centre or edge must come to the frame's centre or
463/// edge to snap onto it.
464pub(crate) const SNAP_PX: f32 = 6.;
465
466/// The smallest distance, in screen px, from a corner grab to the picture's centre that still
467/// scales it: nearer than this the ratio means nothing, so the grab does nothing.
468const CORNER_MIN_PX: f32 = 4.;
469
470/// What a viewer drag on the selected clip's picture takes: the whole picture, or the scale from
471/// a corner.
472#[derive(Clone, Copy, Debug, PartialEq, Eq)]
473pub(crate) enum HandleGrab {
474 Move,
475 Corner,
476}
477
478/// A viewer drag in progress: the grab, where the pointer began (picture-local px), the picture
479/// rectangle and placement it began from, the snap guides it is showing, and whether the next
480/// write is the first (the one that takes the undo step).
481#[derive(Clone, Copy, Debug)]
482pub(crate) struct ViewerHandle {
483 pub(crate) grab: HandleGrab,
484 pub(crate) start: (f32, f32),
485 pub(crate) frame: Rect,
486 pub(crate) base: engine::transform::TransformParams,
487 pub(crate) src: (u32, u32),
488 pub(crate) canvas: (u32, u32),
489 pub(crate) first: bool,
490 /// The frame line each axis snapped to, as a fraction of the frame (0, centre or 1).
491 pub(crate) guide: (Option<f32>, Option<f32>),
492}
493
494/// One axis of a moved picture: `pos` is its centre as a canvas fraction from the centre, `half`
495/// its half size, and the picture's centre and both edges snap to the frame's centre and edges
496/// within `thr` (canvas fractions). Returns the snapped `pos` and the frame line it landed on.
497fn snap_axis(pos: f32, half: f32, thr: f32) -> (f32, Option<f32>) {
498 let mut best: Option<(f32, f32)> = None;
499 for feature in [0.5 + pos - half, 0.5 + pos, 0.5 + pos + half] {
500 for line in [0., 0.5, 1.] {
501 let d = line - feature;
502 if d.abs() <= thr && best.is_none_or(|(b, _)| d.abs() < b.abs()) {
503 best = Some((d, line));
504 }
505 }
506 }
507 match best {
508 Some((d, line)) => (pos + d, Some(line)),
509 None => (pos, None),
510 }
511}
512
513/// [`snap_axis`] on both axes: the snapped centre offset and the guide each axis shows.
514pub(crate) fn snap_move(pos: (f32, f32), half: (f32, f32), thr: (f32, f32)) -> ((f32, f32), (Option<f32>, Option<f32>)) {
515 let (x, gx) = snap_axis(pos.0, half.0, thr.0);
516 let (y, gy) = snap_axis(pos.1, half.1, thr.1);
517 ((x, y), (gx, gy))
518}
519
520/// The scale a corner grab gives: the picture's scale `base` times how much farther the pointer
521/// is from the picture's `centre` now than where the grab began. `None` when the grab began on
522/// the centre, or the scale would leave the slider's range.
523pub(crate) fn corner_scale(base: f32, centre: (f32, f32), start: (f32, f32), now: (f32, f32)) -> Option<f32> {
524 let dist = |p: (f32, f32)| ((p.0 - centre.0).powi(2) + (p.1 - centre.1).powi(2)).sqrt();
525 let d0 = dist(start);
526 if d0 < CORNER_MIN_PX {
527 return None;
528 }
529 let (_, low, high) = crate::transform_ui::TRANSFORM_BANDS[crate::transform_ui::SCALE_BAND];
530 Some((base * dist(now) / d0).clamp(low, high))
531}
532
533impl Player {
534 /// The clip a viewer drag acts on: the selected video clip, when it is the one under the
535 /// playhead, the picture is fitted and no source is up in the monitor. Zoomed in, a drag
536 /// pans instead, so there is no clip to act on.
537 fn viewer_handle_target(&self) -> Option<(Lane, usize)> {
538 let session = self.session.as_ref()?;
539 if self.viewer.zoom != Zoom::Fit || self.preview_session.is_some() {
540 return None;
541 }
542 let (lane, idx) = self.selected.anchor()?;
543 let under = session.video_clip_at(session.now()) == Some((lane, idx));
544 (lane.kind == LaneKind::Video && under && self.clip_picture_size(lane, idx).is_some()).then_some((lane, idx))
545 }
546
547 /// Where the picture region's own box starts, in window px: the pointer's local origin.
548 fn picture_origin(&self) -> (f32, f32) {
549 let b = self.picture_box.get();
550 (f32::from(b.origin.x), f32::from(b.origin.y))
551 }
552
553 /// A press on the selected clip's picture or one of its corners: the card opens on that clip
554 /// (as the Transform card does), and the drag starts from the placement it has now.
555 pub(crate) fn viewer_handle_start(&mut self, grab: HandleGrab, at: Point<Pixels>, window: &Window, cx: &mut Context<Self>) {
556 let Some((lane, idx)) = self.viewer_handle_target() else {
557 return;
558 };
559 if self.transform_open != Some((lane, idx)) {
560 self.open_transform(cx);
561 }
562 if self.transform_open != Some((lane, idx)) {
563 return;
564 }
565 let (Some(frame), Some(src)) = (self.viewer_frame_local(window.scale_factor()), self.clip_picture_size(lane, idx)) else {
566 return;
567 };
568 let o = self.picture_origin();
569 self.viewer_handle = Some(ViewerHandle {
570 grab,
571 start: (f32::from(at.x) - o.0, f32::from(at.y) - o.1),
572 frame,
573 base: self.transform_params(),
574 src,
575 canvas: self.transform_canvas(),
576 first: true,
577 guide: (None, None),
578 });
579 cx.notify();
580 }
581
582 /// A drag sample: the placement the grab gives from where it began, snapped, written through
583 /// the Transform card's own path (keys and undo included). Shift keeps a move to one axis.
584 pub(crate) fn viewer_handle_move(&mut self, at: Point<Pixels>, shift: bool, cx: &mut Context<Self>) {
585 let Some(h) = self.viewer_handle else {
586 return;
587 };
588 let o = self.picture_origin();
589 let local = (f32::from(at.x) - o.0, f32::from(at.y) - o.1);
590 let (fx, fy, fw, fh) = h.frame;
591 let mut params = h.base;
592 let mut guide = (None, None);
593 match h.grab {
594 HandleGrab::Move => {
595 let (mut dx, mut dy) = (local.0 - h.start.0, local.1 - h.start.1);
596 if shift {
597 match dx.abs() >= dy.abs() {
598 true => dy = 0.,
599 false => dx = 0.,
600 }
601 }
602 let pos = (h.base.pos_x + dx / fw, h.base.pos_y + dy / fh);
603 let half = engine::transform::placed_half(&h.base, h.src, h.canvas);
604 let (snapped, g) = snap_move(pos, half, (SNAP_PX / fw, SNAP_PX / fh));
605 params.pos_x = snapped.0;
606 params.pos_y = snapped.1;
607 guide = g;
608 }
609 HandleGrab::Corner => {
610 let centre = (fx + fw * (0.5 + h.base.pos_x), fy + fh * (0.5 + h.base.pos_y));
611 let Some(scale) = corner_scale(h.base.scale, centre, h.start, local) else {
612 return;
613 };
614 params.scale = scale;
615 }
616 }
617 let first = h.first;
618 if params == self.transform_params() {
619 self.viewer_handle = Some(ViewerHandle { guide, ..h });
620 cx.notify();
621 return;
622 }
623 self.viewer_handle = Some(ViewerHandle { guide, first: false, ..h });
624 let busy = self.seek_since.is_some();
625 match crate::stash_or_write(&mut self.pending_transform, params, first, busy) {
626 Some(params) => self.write_transform(params, !first, cx),
627 None => cx.notify(),
628 }
629 }
630
631 /// The button came up, or the pointer left it: the drag is over and its guides are gone.
632 pub(crate) fn viewer_handle_end(&mut self, cx: &mut Context<Self>) {
633 if self.viewer_handle.take().is_some() {
634 cx.notify();
635 }
636 }
637
638 /// The handles over the selected clip's picture, placed in the picture stage's own
639 /// coordinates (the stage is the layer's box): an outline with a move area, four corner
640 /// squares, and the snap guide while one is held. `None` when no clip qualifies.
641 pub(crate) fn viewer_handle_layer(&self, dpr: f32, cx: &mut Context<Self>) -> Option<AnyElement> {
642 // The compare view draws both halves of the picture: the box and its handles would cross them.
643 if self.compare != Compare::Off {
644 return None;
645 }
646 let (lane, idx) = self.viewer_handle_target()?;
647 let session = self.session.as_ref()?;
648 let placement = match self.transform_open == Some((lane, idx)) {
649 true => self.transform_params(),
650 false => session.transform_at(lane, idx, self.key_frame()).unwrap_or_default(),
651 };
652 let src = self.clip_picture_size(lane, idx)?;
653 let canvas = self.transform_canvas();
654 let (lx, ly, fw, fh) = self.viewer_frame_local(dpr)?;
655 let container = crate::ui::stance::PICTURE_BOUNDS.with(std::rc::Rc::clone).get();
656 let o = self.picture_origin();
657 let offset = (
658 o.0 - f32::from(container.origin.x) + lx,
659 o.1 - f32::from(container.origin.y) + ly,
660 );
661 let (hw, hh) = engine::transform::placed_half(&placement, src, canvas);
662 let (ccx, ccy) = (offset.0 + fw * (0.5 + placement.pos_x), offset.1 + fh * (0.5 + placement.pos_y));
663 let (bw, bh) = (2. * hw * fw, 2. * hh * fh);
664 let (bx, by) = (ccx - bw / 2., ccy - bh / 2.);
665 let t = crate::ui::theme::tokens();
666 let me = cx.entity();
667 let mut layer = div().absolute().top_0().left_0().size_full().overflow_hidden();
668 if let Some(h) = self.viewer_handle {
669 let (gx, gy) = h.guide;
670 if let Some(line) = gx {
671 layer = layer.child(
672 div().absolute().top_0().bottom_0().left(px((offset.0 + fw * line).round())).w(px(1.)).bg(rgb(t.accent)),
673 );
674 }
675 if let Some(line) = gy {
676 layer = layer.child(
677 div().absolute().left_0().right_0().top(px((offset.1 + fh * line).round())).h(px(1.)).bg(rgb(t.accent)),
678 );
679 }
680 }
681 let me_move = me.clone();
682 let outline = div()
683 .id("viewer-handle-move")
684 .absolute()
685 .left(px(bx.round()))
686 .top(px(by.round()))
687 .w(px(bw.round()))
688 .h(px(bh.round()))
689 .border_1()
690 .border_color(rgb(t.accent))
691 .cursor(gpui::CursorStyle::OpenHand)
692 // No tip during a drag: the status bar already says what the drag does.
693 .when(self.viewer_handle.is_none(), |o| {
694 o.tooltip(crate::ui::widgets::overlay_tip_hover(
695 "Picture",
696 "",
697 Some("Drag to move, and it snaps to the centre and the edges (Shift keeps to one axis). Drag a corner to scale it. Zoomed in, a drag pans instead."),
698 ))
699 })
700 .on_mouse_down(gpui::MouseButton::Left, move |e: &gpui::MouseDownEvent, window, app| {
701 me_move.update(app, |this, cx| this.viewer_handle_start(HandleGrab::Move, e.position, window, cx));
702 app.stop_propagation();
703 });
704 layer = layer.child(outline);
705 let corners = [
706 (bx, by, gpui::CursorStyle::ResizeUpLeftDownRight),
707 (bx + bw, by, gpui::CursorStyle::ResizeUpRightDownLeft),
708 (bx, by + bh, gpui::CursorStyle::ResizeUpRightDownLeft),
709 (bx + bw, by + bh, gpui::CursorStyle::ResizeUpLeftDownRight),
710 ];
711 for (i, (x, y, cursor)) in corners.into_iter().enumerate() {
712 let me_corner = me.clone();
713 layer = layer.child(
714 div()
715 .id(("viewer-handle-corner", i))
716 .absolute()
717 .left(px((x - 5.).round()))
718 .top(px((y - 5.).round()))
719 .size(px(10.))
720 .bg(rgb(t.accent))
721 .border_1()
722 .border_color(rgb(t.e0))
723 .cursor(cursor)
724 .on_mouse_down(gpui::MouseButton::Left, move |e: &gpui::MouseDownEvent, window, app| {
725 me_corner.update(app, |this, cx| this.viewer_handle_start(HandleGrab::Corner, e.position, window, cx));
726 app.stop_propagation();
727 }),
728 );
729 }
730 Some(layer.into_any_element())
731 }
732}
733
734/// Paints the frame `image` in a box: fitted, or at the zoom's size with `pan` applied, then the
735/// guides and the aspect mask over the frame. Absolute and full-box, like [`crate::render::letterboxed_image`].
736pub(crate) fn viewer_picture(
737 image: Arc<RenderImage>,
738 native: (f32, f32),
739 prefs: Prefs,
740 pan: (f32, f32),
741 dpr: f32,
742) -> impl IntoElement + Styled {
743 canvas(
744 |_, _, _| (),
745 move |bounds, _, window, app| {
746 let bx = (f32::from(bounds.size.width), f32::from(bounds.size.height));
747 let origin = (f32::from(bounds.origin.x), f32::from(bounds.origin.y));
748 let frame = picture_rect(prefs.zoom, native, bx, origin, pan, dpr);
749 let _ = window.paint_image(quad(frame), Corners::default(), image.clone(), 0, false);
750 let t = crate::ui::theme::tokens();
751 let line = rgba(crate::ui::theme::with_alpha(t.accent, 0xc8));
752 if let Some(ratio) = prefs.mask.ratio() {
753 let keep = mask_window(frame, ratio);
754 let dim = rgba(crate::ui::theme::with_alpha(t.e0, 0xa8));
755 for r in outside(frame, keep) {
756 window.paint_quad(gpui::fill(quad(r), dim));
757 }
758 stroke(window, keep, line);
759 }
760 match prefs.guide {
761 Guide::Off => {}
762 Guide::Safe => {
763 stroke(window, inset(frame, 0.9), line);
764 stroke(window, inset(frame, 0.8), line);
765 for (share, name) in [(0.9, "Action safe"), (0.8, "Title safe")] {
766 let r = inset(frame, share);
767 guide_label(window, app, name, (r.0 + 4., r.1 + 2.), t.ink2, t.e0);
768 }
769 }
770 Guide::Thirds => {
771 let (x, y, w, h) = frame;
772 for k in [1., 2.] {
773 window.paint_quad(gpui::fill(quad(((x + w * k / 3.).round(), y, 1., h)), line));
774 window.paint_quad(gpui::fill(quad((x, (y + h * k / 3.).round(), w, 1.)), line));
775 }
776 }
777 Guide::Centre => {
778 let (cx, cy) = (frame.0 + frame.2 / 2., frame.1 + frame.3 / 2.);
779 let arm = (frame.2.min(frame.3) * 0.04).max(8.);
780 window.paint_quad(gpui::fill(quad((cx - arm, cy.round(), arm * 2., 1.)), line));
781 window.paint_quad(gpui::fill(quad((cx.round(), cy - arm, 1., arm * 2.)), line));
782 }
783 }
784 },
785 )
786 .absolute()
787 .top_0()
788 .bottom_0()
789 .left_0()
790 .right_0()
791 .size_full()
792}
793
794/// The viewer's compare view (View > Compare grade): the picture as shot against the graded one.
795/// Preview only: it changes what this screen draws, never the project or an export.
796#[derive(Clone, Copy, Debug, PartialEq, Eq, Default)]
797pub(crate) enum Compare {
798 #[default]
799 Off,
800 /// A vertical wipe at the centre: as shot on the left, graded on the right.
801 Split,
802 /// Both halves, each fitted to its half: as shot on the left, graded on the right.
803 Side,
804}
805
806impl Compare {
807 /// The choices in the order the card and the menu list them.
808 pub(crate) const ALL: [(Compare, &'static str); 3] = [(Compare::Off, "Off"), (Compare::Split, "Split"), (Compare::Side, "Side by side")];
809}
810
811/// The compare view's picture: `after` (the graded frame) in the box, and `before` (the frame as
812/// shot) over it. A split cuts `before` off at the centre, leaving the graded half on the right;
813/// side by side fits each frame to its own half. Absolute and full-box, like [`viewer_picture`].
814pub(crate) fn compare_picture(
815 mode: Compare,
816 before: Option<Arc<RenderImage>>,
817 after: Arc<RenderImage>,
818 native: (f32, f32),
819 zoom: Zoom,
820 pan: (f32, f32),
821 dpr: f32,
822) -> impl IntoElement + Styled {
823 canvas(
824 |_, _, _| (),
825 move |bounds, _, window, app| {
826 let bx = (f32::from(bounds.size.width), f32::from(bounds.size.height));
827 let origin = (f32::from(bounds.origin.x), f32::from(bounds.origin.y));
828 let t = crate::ui::theme::tokens();
829 let centre = origin.0 + bx.0 / 2.;
830 let (left, right) = ((origin.0, origin.1, bx.0 / 2., bx.1), (centre, origin.1, bx.0 / 2., bx.1));
831 match mode {
832 Compare::Side => {
833 // Each half fits its own picture; its caption sits inside the picture's bottom left.
834 let fit_r = rect_of(gpui::ObjectFit::Contain.get_bounds(quad(right), after.size(0)));
835 if let Some(b) = &before {
836 let fit_l = rect_of(gpui::ObjectFit::Contain.get_bounds(quad(left), b.size(0)));
837 let _ = window.paint_image(quad(fit_l), Corners::default(), b.clone(), 0, false);
838 compare_label(window, app, "Before", fit_l);
839 }
840 let _ = window.paint_image(quad(fit_r), Corners::default(), after.clone(), 0, false);
841 compare_label(window, app, "After", fit_r);
842 }
843 _ => {
844 let frame = picture_rect(zoom, native, bx, origin, pan, dpr);
845 let _ = window.paint_image(quad(frame), Corners::default(), after.clone(), 0, false);
846 if let Some(b) = &before {
847 window.with_content_mask(Some(gpui::ContentMask { bounds: quad(left) }), |window| {
848 let _ = window.paint_image(quad(frame), Corners::default(), b.clone(), 0, false);
849 });
850 }
851 // The part of the picture that is on screen, split at the centre.
852 let vis = clip_rect(frame, (origin.0, origin.1, bx.0, bx.1));
853 window.paint_quad(gpui::fill(quad((centre.round() - 1., vis.1, 2., vis.3)), rgb(t.ink1)));
854 if before.is_some() {
855 compare_label(window, app, "Before", (vis.0, vis.1, centre - vis.0, vis.3));
856 }
857 compare_label(window, app, "After", (centre, vis.1, vis.0 + vis.2 - centre, vis.3));
858 }
859 }
860 },
861 )
862 .absolute()
863 .top_0()
864 .bottom_0()
865 .left_0()
866 .right_0()
867 .size_full()
868}
869
870/// A bounds as a rectangle.
871fn rect_of(b: Bounds<Pixels>) -> Rect {
872 (f32::from(b.origin.x), f32::from(b.origin.y), f32::from(b.size.width), f32::from(b.size.height))
873}
874
875/// `r` cut down to the part inside `to`.
876fn clip_rect(r: Rect, to: Rect) -> Rect {
877 let (x0, y0) = (r.0.max(to.0), r.1.max(to.1));
878 let (x1, y1) = ((r.0 + r.2).min(to.0 + to.2), (r.1 + r.3).min(to.1 + to.3));
879 (x0, y0, (x1 - x0).max(0.), (y1 - y0).max(0.))
880}
881
882/// A caption at the bottom left of `img`, on the dim plate the guide names use, so it reads over the picture.
883fn compare_label(window: &mut Window, app: &mut App, text: &str, img: Rect) {
884 let t = crate::ui::theme::tokens();
885 let h = f32::from(crate::ui::type_scale::caption().size) + 6.;
886 // guide_label starts its plate 4 px left of the point it is given.
887 guide_label(window, app, text, (img.0 + 12., img.1 + img.3 - 8. - h), t.ink1, t.e0);
888}
889
890/// A small caption naming a guide, on a dim plate so it reads over any picture; its top-left at `at`.
891fn guide_label(window: &mut Window, app: &mut App, text: &str, at: (f32, f32), ink: u32, plate: u32) {
892 let style = crate::ui::type_scale::caption();
893 let run = gpui::TextRun {
894 len: text.len(),
895 font: style.font.clone(),
896 color: rgb(ink).into(),
897 background_color: None,
898 underline: None,
899 strikethrough: None,
900 };
901 let line = window.text_system().shape_line(text.to_string().into(), style.size, &[run], None);
902 let (w, h) = (f32::from(line.width) + 8., f32::from(style.size) + 6.);
903 window.paint_quad(gpui::fill(quad((at.0 - 4., at.1, w, h)), rgba(crate::ui::theme::with_alpha(plate, 0xb0))));
904 let _ = line.paint(point(px(at.0), px(at.1 + 3.)), px(f32::from(style.size) + 1.), window, app);
905}
906
907fn quad(r: Rect) -> Bounds<Pixels> {
908 Bounds::new(point(px(r.0), px(r.1)), size(px(r.2), px(r.3)))
909}
910
911/// A 1px outline of `r`.
912fn stroke(window: &mut Window, r: Rect, color: gpui::Rgba) {
913 let (x, y, w, h) = (r.0.round(), r.1.round(), r.2.round(), r.3.round());
914 for edge in [(x, y, w, 1.), (x, y + h - 1., w, 1.), (x, y, 1., h), (x + w - 1., y, 1., h)] {
915 window.paint_quad(gpui::fill(quad(edge), color));
916 }
917}
918
919#[cfg(test)]
920mod tests {
921 use super::*;
922
923 #[test]
924 fn fit_letterboxes_and_zoom_scales_native_pixels() {
925 assert_eq!(shown_size(Zoom::Fit, (1920., 1080.), (960., 960.), 1.), (960., 540.));
926 assert_eq!(shown_size(Zoom::P50, (1920., 1080.), (100., 100.), 1.), (960., 540.));
927 assert_eq!(shown_size(Zoom::P100, (1920., 1080.), (100., 100.), 2.), (960., 540.));
928 }
929
930 #[test]
931 fn pan_never_leaves_the_box_and_is_zero_when_the_picture_fits() {
932 assert_eq!(clamp_pan((50., 50.), (400., 200.), (500., 300.)), (0., 0.));
933 assert_eq!(clamp_pan((500., -500.), (1000., 800.), (600., 600.)), (200., -100.));
934 }
935
936 #[test]
937 fn wheel_steps_stay_on_the_ladder() {
938 assert_eq!(Zoom::Fit.step(true), Zoom::P25);
939 assert_eq!(Zoom::P25.step(false), Zoom::Fit);
940 assert_eq!(Zoom::Fit.step(false), Zoom::Fit);
941 assert_eq!(Zoom::P200.step(true), Zoom::P200);
942 }
943
944 #[test]
945 fn keys_round_trip() {
946 for z in Zoom::ALL {
947 assert_eq!(Zoom::from_key(z.key()), Some(z));
948 }
949 for q in Quality::ALL {
950 assert_eq!(Quality::from_key(q.key()), Some(q));
951 }
952 for m in Mask::ALL {
953 assert_eq!(Mask::from_key(m.key()), Some(m));
954 }
955 assert_eq!(Zoom::from_key("7"), None);
956 }
957
958 #[test]
959 fn safe_areas_and_masks_are_centred() {
960 let frame = (0., 0., 1920., 1080.);
961 let i = inset(frame, 0.9);
962 assert!((i.0 - 96.).abs() < 0.01 && (i.1 - 54.).abs() < 0.01 && (i.2 - 1728.).abs() < 0.01);
963 let w = mask_window(frame, 9. / 16.);
964 assert!((w.2 - 607.5).abs() < 0.01 && w.3 == 1080. && (w.0 - 656.25).abs() < 0.01);
965 assert_eq!(outside(frame, w).len(), 2);
966 let sq = mask_window((0., 0., 400., 600.), 1.);
967 assert_eq!(sq, (0., 100., 400., 400.));
968 assert_eq!(outside((0., 0., 400., 600.), sq).len(), 2);
969 assert!(outside(frame, frame).is_empty());
970 }
971
972 #[test]
973 fn quarter_keeps_a_quarter_of_each_side() {
974 assert_eq!(Quality::Quarter.factor(), 0.25);
975 assert_eq!(Quality::Full.factor(), 1.);
976 }
977
978 #[test]
979 fn a_move_snaps_its_centre_and_edges_to_the_frame() {
980 let thr = (0.01, 0.01);
981 // A box half the frame wide, nudged 0.004 off centre: the centre snaps back to 0.
982 let (p, g) = snap_move((0.004, 0.0), (0.25, 0.25), thr);
983 assert!(p.0.abs() < 1e-6, "{}", p.0);
984 assert_eq!(g.0, Some(0.5), "the centre guide sits on the frame's centre");
985 // A box 0.4 wide, its left edge 0.004 off the frame's left edge: it moves so the edge sits on it.
986 let (p, g) = snap_move((-0.296, 0.1), (0.2, 0.2), thr);
987 assert!((p.0 - (-0.3)).abs() < 1e-6, "{}", p.0);
988 assert_eq!(g.0, Some(0.0));
989 assert_eq!(g.1, None, "nothing near on the other axis, so no guide there");
990 assert_eq!(p.1, 0.1, "an axis with nothing to snap to keeps its place");
991 // Far from every line, nothing moves and no guide shows.
992 assert_eq!(snap_move((0.13, 0.13), (0.1, 0.1), thr), ((0.13, 0.13), (None, None)));
993 }
994
995 #[test]
996 fn a_corner_grab_scales_by_the_pointer_distance_from_the_centre() {
997 let centre = (100., 100.);
998 // Twice as far out from the centre: twice the scale.
999 let s = corner_scale(0.5, centre, (140., 100.), (180., 100.)).unwrap();
1000 assert!((s - 1.0).abs() < 1e-5, "{s}");
1001 // Half way back in.
1002 let s = corner_scale(1.0, centre, (140., 100.), (120., 100.)).unwrap();
1003 assert!((s - 0.5).abs() < 1e-5, "{s}");
1004 // A grab on the centre has no ratio, and the scale stays in the slider's range.
1005 assert_eq!(corner_scale(1.0, centre, (101., 100.), (150., 100.)), None);
1006 assert_eq!(corner_scale(1.0, centre, (110., 100.), (1100., 100.)), Some(4.0));
1007 }
1008}