forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

render.rs476 lines, 23.6 KiBHistoryRawDownload
1//! What the window looks like this frame: the one `render` the whole
2//! interface hangs off, root to overlays.
3
4use crate::*;
5use crate::ui::type_scale::Typeset;
6
7/// The frame `image`, letterboxed/pillarboxed into whatever box it is given,
8/// filling that box on its own axis and leaving the other bare -- the bare
9/// strip is the box's own background (`BG_CANVAS`), never painted here, which
10/// is why every caller sits this on a div already carrying that colour.
11///
12/// `Img::object_fit(Contain)` reads right (verified by hand against
13/// `ObjectFit::Contain::get_bounds`) but only when taffy has already given the
14/// element a real size to fit *into* -- and for a plain `img()` with both axes
15/// `Auto` (`size_full()`/`max_w_full().max_h_full()` both resolve that way in
16/// this pin), it resolves to the image's own native size first and object-fit
17/// never gets a box smaller than the frame to shrink into, so the frame reads
18/// through un-fitted. A `canvas()` element carries no such precompute -- its
19/// `request_layout` is a plain `Style` read, so it is sized by its parent
20/// exactly as a `div()` would be -- and its `paint` callback is handed the
21/// real resolved `bounds`, which is all `Contain::get_bounds` needs.
22///
23/// `.absolute()` with all four insets zero, not `.size_full()` in flex flow:
24/// a flex item under `justify_center()`/`items_center()` (see `picture_area`
25/// below) never resolves a percentage cross-axis size for a plain-`Style`
26/// element like `canvas()`, which is a taffy circularity and not this
27/// element's own bug (confirmed live: bounds handed to `paint` came back
28/// `944px x 0px`, main axis right, cross axis collapsed). An absolutely
29/// positioned box is sized against its containing block directly instead --
30/// the nearest `.relative()` ancestor, which every caller here already sits
31/// this on -- so it never asks taffy's flex algorithm for a cross-axis size
32/// at all.
33///
34/// That containing block still has to have a real size of its own, though:
35/// gpui's default `display` is `Block` (`Style::default()`), not `Flex`, and
36/// a `Block` box with height `auto` is sized by its *normal-flow* children --
37/// an `.absolute()` one, this, takes no part in that (confirmed live: with
38/// the box lacking its own `.flex()`, this canvas's own bounds came back
39/// `944px x 0px` even though its containing block, measured independently,
40/// was a real `944px x 335px`). Every `.relative()` ancestor this sits on
41/// must also be `.flex()` (see `ui::stance::screen`'s `stance-picture`) for
42/// exactly this reason.
43pub(crate) fn letterboxed_image(image: Arc<RenderImage>) -> impl IntoElement + Styled {
44 canvas(
45 |_, _, _| (),
46 move |bounds, _, window, _| {
47 let fitted = gpui::ObjectFit::Contain.get_bounds(bounds, image.size(0));
48 let _ = window.paint_image(fitted, Corners::default(), image, 0, false);
49 },
50 )
51 .absolute()
52 .top_0()
53 .bottom_0()
54 .left_0()
55 .right_0()
56 .size_full()
57}
58
59impl Player {
60 /// The picture region alone: the image, the subtitle cue plate, the
61 /// preview badge and the three transient bars over its bottom edge.
62 /// Its own method so player fullscreen ([`Player::act`]) can stand it up
63 /// as the window's only child without a second copy of what it draws --
64 /// and so the darkroom's own screen region (DESIGN.md §5,
65 /// `ui::stance::screen`) draws the same picture rather than a second one.
66 pub(crate) fn picture_area(
67 &mut self,
68 position: f64,
69 window: &mut Window,
70 cx: &mut Context<Self>,
71 ) -> impl IntoElement {
72 // The compare view's picture as shot is read for the frame on screen, if it is not in hand.
73 self.refresh_before(window, cx);
74 div()
75 .flex_1()
76 .min_h(px(0.))
77 .overflow_hidden()
78 // The bed the cue plate is placed against: it hangs off the
79 // bottom of the picture region, which is the one box that is the
80 // picture and nothing else.
81 .relative()
82 // ...and the box the frame is *watched* in, which is what the
83 // session paints at ([`Player::push_view_size`]).
84 .child(bounds_probe(self.picture_box.clone()))
85 .flex()
86 .justify_center()
87 .items_center()
88 .bg(rgb(BG_CANVAS()))
89 .children(
90 // A clip whose file is off the disk shows black, not the last frame it had:
91 // the banner says what is wrong, and a frame of another clip would read as this one.
92 self.image
93 .clone()
94 .filter(|_| !self.picture_is_missing())
95 .map(|i| {
96 let native = self.viewer_native_or(&i);
97 // The compare view draws the graded frame with the picture as shot beside it.
98 // A source preview has no grade to compare, so it keeps the plain picture.
99 if self.compare != crate::viewer_view::Compare::Off && self.preview_session.is_none() {
100 return crate::viewer_view::compare_picture(
101 self.compare,
102 self.before.clone(),
103 i,
104 native,
105 self.viewer.zoom,
106 self.viewer_pan,
107 window.scale_factor(),
108 )
109 .into_any_element();
110 }
111 crate::viewer_view::viewer_picture(i, native, self.viewer, self.viewer_pan, window.scale_factor())
112 .into_any_element()
113 })
114 // With no file open the letterbox is the whole region,
115 // and a black rectangle says only that something is
116 // broken -- so it says what it wants instead. The window
117 // is already the drop target.
118 .or_else(|| {
119 (self.active_session().is_none()).then(|| self.empty_viewer(cx).into_any_element())
120 }),
121 )
122 // The empty project frame's edge, so a near-black canvas still reads as a frame.
123 .children(self.empty_canvas_outline())
124 // The clip under the playhead reads a file that is gone: say so over the picture.
125 .children(self.missing_clip_note(cx))
126 // After the picture, so the plate is drawn over it rather than
127 // under.
128 // Titles first, so the captions over them draw on top.
129 // Placed against the picture as drawn: the fitted frame, or the zoomed and panned one.
130 .children(self.title_overlay(position, window.scale_factor(), window, cx))
131 .children(self.subtitle_overlay(position, window).map(|overlay| {
132 // Zoomed, the caption's box is the picture's rectangle, not the region.
133 match (self.viewer.zoom, self.viewer_frame_local(window.scale_factor())) {
134 (crate::viewer_view::Zoom::Fit, _) | (_, None) => overlay.into_any_element(),
135 (_, Some((x, y, w, h))) => div()
136 .absolute()
137 .left(px(x))
138 .top(px(y))
139 .w(px(w))
140 .h(px(h))
141 .child(overlay)
142 .into_any_element(),
143 }
144 }))
145 .children(self.viewer_reduced().then(|| {
146 div()
147 .absolute()
148 .top(px(8.))
149 .left(px(8.))
150 .px(px(6.))
151 .py(px(2.))
152 .rounded(px(4.))
153 .bg(rgba(crate::ui::theme::with_alpha(crate::ui::theme::tokens().e0, 0x99)))
154 .type_style(crate::ui::type_scale::caption())
155 .text_color(rgb(crate::ui::theme::tokens().ink1))
156 .child(format!("{} res", self.viewer.quality.label()))
157 }))
158 // The three transient lines hang off the bottom of the picture
159 // rather than taking a row of the column: a notice that arrives
160 // must not push the transport, the toolbar and the timeline down
161 // by its own height -- which is a control moving with state, on
162 // every control below it at once.
163 .child(
164 div()
165 .absolute()
166 .bottom_0()
167 .left_0()
168 .right_0()
169 .flex()
170 .flex_col()
171 .gap(px(2.))
172 .children(self.import_bar(cx))
173 .children(self.seek_bar())
174 // How tall the lot came out, for the cue plate above to
175 // step over ([`sub_bottom`]) -- the bars are over the
176 // picture, and a message drawn across the line being
177 // read loses both of them. Zero with no bar up, since
178 // this box is then empty.
179 .child(height_probe(self.notice_h.clone())),
180 )
181 }
182}
183
184/// How long a viewer size must hold still while playing before the picture is
185/// restarted for it. Each restart stalls the picture until the new stream
186/// refills, so a window being dragged (a step every few pixels) is applied
187/// once the drag rests instead of on every step.
188const VIEW_SETTLE: std::time::Duration = std::time::Duration::from_millis(200);
189
190impl Player {
191 /// Tells the active session where the picture actually lands, in device
192 /// pixels, so its seats can paint at that size instead of the project's
193 /// ([`engine::PlaybackSession::set_view_size`]). Read off the picture
194 /// area's own bounds -- the box `letterboxed_image` fits the frame into --
195 /// and the project's aspect, which is the aspect of every frame it hands
196 /// over.
197 ///
198 /// A size that moved enough for the eye to see gets a fresh picture: the
199 /// canvas a span paints at is decided when it opens, so a resized window
200 /// would otherwise sharpen on its next seek and not before.
201 fn push_view_size(&mut self, window: &mut Window) {
202 if self.shot_pending.is_some() {
203 // A screenshot in flight asked for the project's own size and is
204 // waiting on that frame: pushing the preview's size back now would
205 // cancel the very picture it is waiting for.
206 return;
207 }
208 let region = self.picture_box.get();
209 if region.size.width <= px(1.) || region.size.height <= px(1.) {
210 // Before the first paint there is no box to read, and a floor is
211 // not a measurement.
212 return;
213 }
214 let scale = window.scale_factor();
215 let Some(session) = self.active_session() else {
216 return;
217 };
218 let playing = session.is_playing();
219 // Device pixels, the unit `Contain` measures its fitting size in.
220 let meta = session.meta();
221 let native = (meta.width, meta.height);
222 let fitted = gpui::ObjectFit::Contain.get_bounds(
223 region,
224 size(
225 gpui::DevicePixels(meta.width as i32),
226 gpui::DevicePixels(meta.height as i32),
227 ),
228 );
229 let w = (f32::from(fitted.size.width) * scale).round() as u32;
230 let h = (f32::from(fitted.size.height) * scale).round() as u32;
231 let (w, h) = self.viewer_target((w, h), native, playing);
232 // Playing: a size that is still moving is held back until it has rested
233 // for VIEW_SETTLE, since every apply restarts the picture. Paused, a frame
234 // is cheap and must be sharp, so the size is applied at once.
235 let settled = if !playing {
236 self.view_seen = None;
237 true
238 } else {
239 match self.view_seen {
240 Some((size, since)) if size == (w, h) => since.elapsed() >= VIEW_SETTLE,
241 _ => {
242 self.view_seen = Some(((w, h), Instant::now()));
243 false
244 }
245 }
246 };
247 if !settled {
248 // The loop keeps turning while playing; asked again in case it does not.
249 window.request_animation_frame();
250 return;
251 }
252 let Some(session) = self.active_session_mut() else {
253 return;
254 };
255 if session.set_view_size(w, h) {
256 session.resync_picture();
257 }
258 }
259}
260
261impl Player {
262 /// The focus invariant: keyboard focus is always somewhere inside the
263 /// room, so the root's key handler and every ring handler under it hear
264 /// the keys. A card, sheet or tab that unmounts while it (or a button in
265 /// it) holds focus leaves the window focused on a handle that is no longer
266 /// in the tree, and gpui then dispatches keys to nothing -- Space, Ctrl+Z
267 /// and Esc all go dead until a click lands on a focusable box. The tree a
268 /// render produces is only known once drawn, so a short check after it
269 /// puts focus back on the root if the focused handle is gone. One door for
270 /// every way a surface can close, rather than a refocus at each of them.
271 fn guard_focus(&mut self, window: &Window, cx: &mut Context<Self>) {
272 if self.focus_guard_pending {
273 return;
274 }
275 self.focus_guard_pending = true;
276 cx.spawn_in(window, async move |this, cx| {
277 gpui::Timer::after(std::time::Duration::from_millis(60)).await;
278 this.update_in(cx, |p, window, cx| {
279 p.focus_guard_pending = false;
280 if !p.focus.contains_focused(window, cx) {
281 window.focus(&p.focus);
282 }
283 })
284 .ok();
285 })
286 .detach();
287 }
288}
289
290impl Render for Player {
291 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
292 // A file that has just been opened sits on its first frame with the
293 // clock stopped: opening is not playing, whichever way the file
294 // arrived. The play binding and the transport button start it.
295 if let Some(session) = self.active_session_mut() {
296 session.tick();
297 }
298 self.pump();
299 // The dropped-frames words linger after a stop, timed from it, so the window is drawn
300 // again until the linger has run out and the words can go.
301 if self.drop_lingers() {
302 window.refresh();
303 }
304 // The frames the pump replaced leave every window's sprite atlas here, where the
305 // video output window's copy of them can be reached too.
306 for old in std::mem::take(&mut self.retired_images) {
307 cx.drop_image(old, Some(window));
308 }
309 self.sync_output(cx);
310 self.sync_dock_tab();
311 self.sync_sections(cx);
312 // Every press is noted for the tooltips: one still waiting to show must not show after it.
313 window.on_mouse_event(|e: &MouseDownEvent, phase, _, _| {
314 if phase.capture() {
315 crate::ui::widgets::note_press(e.position);
316 }
317 });
318 self.sync_transcript();
319 self.guard_focus(window, cx);
320 // A screenshot waiting for its project-sized frame is written on the
321 // repaint that lands it -- and before the size push below, which is
322 // what gives the preview its own size back.
323 self.flush_shot(cx);
324 // ...at the size it is watched at, not the project's: a visualizer
325 // seat redrawing 1920x1080 for a 600 px preview is nine times the
326 // pixels for nothing the eye can see. An export has a seat of its own
327 // and never comes through here.
328 self.push_view_size(window);
329 // What every hover label asks before it paints: a card or a menu is
330 // drawn over whatever the pointer is resting on.
331 OVERLAID.store(self.overlaid(), Ordering::Relaxed);
332 let vs = window.viewport_size();
333 let dock_left = f32::from(vs.width) - self.split_px(Split::Dock, vs);
334 crate::ui::widgets::DOCK_W_BITS.store((f32::from(vs.width) - dock_left).to_bits(), Ordering::Relaxed);
335 let timeline_top =
336 crate::ui::stance::below_picture_floor(f32::from(vs.height), self.split_px(Split::Bench, vs));
337 crate::ui::widgets::TIMELINE_TOP_BITS.store(timeline_top.to_bits(), Ordering::Relaxed);
338 // A cleared seek is a frame delivered, which is the one readiness signal
339 // there is: whatever a slider drag held back is written here.
340 if self.seek_since.is_none() {
341 self.flush_drag(cx);
342 }
343 self.poll_export();
344 self.poll_queue();
345 self.poll_import(cx);
346 self.poll_collect(cx);
347 self.poll_silence();
348 self.poll_proxies(cx);
349 self.poll_render(cx);
350 self.poll_stabilise();
351 self.poll_tracks();
352 self.poll_reframe();
353 self.poll_multicam();
354 // Every way a source can arrive -- argv, an import, a project load --
355 // has been through a repaint by the time its clips are drawn, so this
356 // is the one place that has to notice a new one.
357 self.cache_media(cx);
358 self.cache_export_seat(cx);
359 // The export sheet's one-second trial write, which prices its time.
360 self.cache_export_pace();
361 self.cache_hw_caps(cx);
362 // What the compositor calls this window. Pushed only when it changes:
363 // it is a protocol round trip and this runs at vsync.
364 let title = shown_title(&self.name, &self.project_path, self.new_project.as_deref(), self.autosave_armed);
365 if title != self.titled {
366 window.set_window_title(&title);
367 self.titled = title;
368 }
369 // A compositor keybind (the window manager's own fullscreen, not
370 // ours) can drop `window.is_fullscreen()` without ever going through
371 // [`Player::act`] -- the picture-only layout below must not survive
372 // that on its own, or the chrome never comes back. Only the *leaving*
373 // direction is reconciled here: the platform going fullscreen behind
374 // our back is not this editor asking for the picture-only layout, so
375 // it is left alone rather than guessed at.
376 if self.player_fullscreen && !window.is_fullscreen() {
377 self.player_fullscreen = false;
378 }
379 // No shadow flag: the session is the only truth about play state, and
380 // [`Player::transport`] is the one place it is read.
381 let state = self.transport();
382 // A paused timeline has nothing to animate; the toggle handlers notify,
383 // which is what starts the loop again. A paused seek keeps the loop
384 // running by itself until `pump` has the frame it asked for. An export
385 // pauses playback and still needs the loop: its progress only reaches
386 // the screen on a repaint. A notice does not: it waits to be dismissed
387 // rather than for a clock, so keeping the loop alive for it would spin
388 // the GPU until someone answered it.
389 // An import does too, and for the same reason: its clock and its sweep
390 // only reach the screen on a repaint, and a still line is the very
391 // thing it exists to disprove.
392 if state.is_playing()
393 || self.seek_since.is_some()
394 || self.export.is_some()
395 // ...and the queue, whose rows carry a percent.
396 || self.queue.is_going()
397 // ...and the sheet's trial write, whose answer is the time line.
398 || self.export_sheet.bench.is_some()
399 || self.importing.is_some()
400 // A silence scan too: its progress and its two clocks only reach
401 // the screen on a repaint, and a still line is the very thing this
402 // card was rewritten to disprove.
403 || self.silence_scan.is_some()
404 // ...and a stand-in being made: its percentage on the library row
405 // only reaches the screen on a repaint, and a bar that never moves
406 // is exactly what a person reads as a hung encode.
407 || self.making_proxies()
408 // ...and a stabilisation analysis: its percent on the transform
409 // card, and the corrected picture once it lands.
410 || !self.stab_waiting.is_empty()
411 // ...and a mask track: its percent on the effects card.
412 || !self.track_jobs.is_empty()
413 // ...and an auto reframe: its percent in the status bar.
414 || self.reframe_run.is_some()
415 // ...and angles being synced: the percent in the status bar.
416 || self.mcam_run.is_some()
417 // ...and a media collect: its bar and byte count only reach the screen on a repaint.
418 || self.collect_running()
419 // ...and a render preview: its bar fills, and its finish is seen, on a repaint.
420 || self.render.as_ref().is_some_and(|(job, _)| !job.is_finished())
421 {
422 window.request_animation_frame();
423 }
424
425 // Read per render, never cached: a delete shortens the timeline and the
426 // timecode, the ruler and the clamp below all have to follow it -- and
427 // so does the room a tail being dragged needs to grow into.
428 let duration = self.drawn_duration();
429 let position = self.playhead(duration);
430 // Re-settled every frame against the duration this one is drawing: an
431 // edit that shortens the timeline moves the far end of the view, and a
432 // playhead that has run off the bed pulls the view after it -- which is
433 // what makes a zoomed-in timeline scroll while it plays.
434 // ...but only a playhead that is *going* somewhere pulls it: following
435 // is what a moving one does, during playback and through a seek. A view
436 // yanked back to a playhead nobody moved is a hand's own scroll undone
437 // by the very next frame, which is what made the wheel look dead.
438 // ...and a hand that scrolled the view away from the head keeps it
439 // ([`Player::panned`]): a follow that centres the head again would undo
440 // the notch before it was seen, which is what made the wheel look dead
441 // while playing. It is given straight back below, the moment the head
442 // is on the bed a person chose to look at -- so the scroll wins now and
443 // the follow resumes by itself, with nothing to press.
444 // A fit asked for before the bed was painted ([`Player::zoom_fit`]) is
445 // taken here, on the first frame that measured one; until then the
446 // loop is kept alive so that frame comes.
447 if self.fit_pending {
448 match self.view().bed > 0. {
449 true => {
450 self.fit_to_bed();
451 self.fit_pending = false;
452 }
453 false => window.request_animation_frame(),
454 }
455 }
456 // A fit still in force follows the bed: the first frame measures the
457 // window's initial size, and a compositor resize to the tiled size
458 // after it changes the bed, so the fit is taken again for the new width
459 // ([`Player::fit_to_bed`]). A hand's zoom or scroll has cleared it.
460 if let Some(fitted) = self.fitted_bed {
461 let bed = self.view().bed;
462 if bed > 0. && bed != fitted {
463 self.fit_to_bed();
464 }
465 }
466 self.scale = match (state.is_playing() || self.seek_since.is_some()) && !self.panned {
467 true => self.view().following(position),
468 false => self.view().settled(),
469 };
470 if self.panned && self.view().shows(position) {
471 self.panned = false;
472 }
473
474 ui::stance::render(self, window, cx)
475 }
476}