forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBb02f499Tahinli1 month ago1000 commits

render.rs450 lines, 22.4 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
184impl Player {
185 /// Tells the active session where the picture actually lands, in device
186 /// pixels, so its seats can paint at that size instead of the project's
187 /// ([`engine::PlaybackSession::set_view_size`]). Read off the picture
188 /// area's own bounds -- the box `letterboxed_image` fits the frame into --
189 /// and the project's aspect, which is the aspect of every frame it hands
190 /// over.
191 ///
192 /// A size that moved enough for the eye to see gets a fresh picture: the
193 /// canvas a span paints at is decided when it opens, so a resized window
194 /// would otherwise sharpen on its next seek and not before.
195 fn push_view_size(&mut self, window: &mut Window) {
196 if self.shot_pending.is_some() {
197 // A screenshot in flight asked for the project's own size and is
198 // waiting on that frame: pushing the preview's size back now would
199 // cancel the very picture it is waiting for.
200 return;
201 }
202 let region = self.picture_box.get();
203 if region.size.width <= px(1.) || region.size.height <= px(1.) {
204 // Before the first paint there is no box to read, and a floor is
205 // not a measurement.
206 return;
207 }
208 let scale = window.scale_factor();
209 let Some(session) = self.active_session() else {
210 return;
211 };
212 let playing = session.is_playing();
213 // Device pixels, the unit `Contain` measures its fitting size in.
214 let meta = session.meta();
215 let native = (meta.width, meta.height);
216 let fitted = gpui::ObjectFit::Contain.get_bounds(
217 region,
218 size(
219 gpui::DevicePixels(meta.width as i32),
220 gpui::DevicePixels(meta.height as i32),
221 ),
222 );
223 let w = (f32::from(fitted.size.width) * scale).round() as u32;
224 let h = (f32::from(fitted.size.height) * scale).round() as u32;
225 let (w, h) = self.viewer_target((w, h), native, playing);
226 let Some(session) = self.active_session_mut() else {
227 return;
228 };
229 if session.set_view_size(w, h) {
230 session.resync_picture();
231 }
232 }
233}
234
235impl Player {
236 /// The focus invariant: keyboard focus is always somewhere inside the
237 /// room, so the root's key handler and every ring handler under it hear
238 /// the keys. A card, sheet or tab that unmounts while it (or a button in
239 /// it) holds focus leaves the window focused on a handle that is no longer
240 /// in the tree, and gpui then dispatches keys to nothing -- Space, Ctrl+Z
241 /// and Esc all go dead until a click lands on a focusable box. The tree a
242 /// render produces is only known once drawn, so a short check after it
243 /// puts focus back on the root if the focused handle is gone. One door for
244 /// every way a surface can close, rather than a refocus at each of them.
245 fn guard_focus(&mut self, window: &Window, cx: &mut Context<Self>) {
246 if self.focus_guard_pending {
247 return;
248 }
249 self.focus_guard_pending = true;
250 cx.spawn_in(window, async move |this, cx| {
251 gpui::Timer::after(std::time::Duration::from_millis(60)).await;
252 this.update_in(cx, |p, window, cx| {
253 p.focus_guard_pending = false;
254 if !p.focus.contains_focused(window, cx) {
255 window.focus(&p.focus);
256 }
257 })
258 .ok();
259 })
260 .detach();
261 }
262}
263
264impl Render for Player {
265 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
266 // A file that has just been opened sits on its first frame with the
267 // clock stopped: opening is not playing, whichever way the file
268 // arrived. The play binding and the transport button start it.
269 if let Some(session) = self.active_session_mut() {
270 session.tick();
271 }
272 self.pump();
273 // The dropped-frames words linger after a stop, timed from it, so the window is drawn
274 // again until the linger has run out and the words can go.
275 if self.drop_lingers() {
276 window.refresh();
277 }
278 // The frames the pump replaced leave every window's sprite atlas here, where the
279 // video output window's copy of them can be reached too.
280 for old in std::mem::take(&mut self.retired_images) {
281 cx.drop_image(old, Some(window));
282 }
283 self.sync_output(cx);
284 self.sync_dock_tab();
285 self.sync_sections(cx);
286 // Every press is noted for the tooltips: one still waiting to show must not show after it.
287 window.on_mouse_event(|e: &MouseDownEvent, phase, _, _| {
288 if phase.capture() {
289 crate::ui::widgets::note_press(e.position);
290 }
291 });
292 self.sync_transcript();
293 self.guard_focus(window, cx);
294 // A screenshot waiting for its project-sized frame is written on the
295 // repaint that lands it -- and before the size push below, which is
296 // what gives the preview its own size back.
297 self.flush_shot(cx);
298 // ...at the size it is watched at, not the project's: a visualizer
299 // seat redrawing 1920x1080 for a 600 px preview is nine times the
300 // pixels for nothing the eye can see. An export has a seat of its own
301 // and never comes through here.
302 self.push_view_size(window);
303 // What every hover label asks before it paints: a card or a menu is
304 // drawn over whatever the pointer is resting on.
305 OVERLAID.store(self.overlaid(), Ordering::Relaxed);
306 let vs = window.viewport_size();
307 let dock_left = f32::from(vs.width) - self.split_px(Split::Dock, vs);
308 crate::ui::widgets::DOCK_W_BITS.store((f32::from(vs.width) - dock_left).to_bits(), Ordering::Relaxed);
309 let timeline_top =
310 crate::ui::stance::below_picture_floor(f32::from(vs.height), self.split_px(Split::Bench, vs));
311 crate::ui::widgets::TIMELINE_TOP_BITS.store(timeline_top.to_bits(), Ordering::Relaxed);
312 // A cleared seek is a frame delivered, which is the one readiness signal
313 // there is: whatever a slider drag held back is written here.
314 if self.seek_since.is_none() {
315 self.flush_drag(cx);
316 }
317 self.poll_export();
318 self.poll_queue();
319 self.poll_import(cx);
320 self.poll_collect(cx);
321 self.poll_silence();
322 self.poll_proxies(cx);
323 self.poll_render(cx);
324 self.poll_stabilise();
325 self.poll_tracks();
326 self.poll_reframe();
327 self.poll_multicam();
328 // Every way a source can arrive -- argv, an import, a project load --
329 // has been through a repaint by the time its clips are drawn, so this
330 // is the one place that has to notice a new one.
331 self.cache_media(cx);
332 self.cache_export_seat(cx);
333 // The export sheet's one-second trial write, which prices its time.
334 self.cache_export_pace();
335 self.cache_hw_caps(cx);
336 // What the compositor calls this window. Pushed only when it changes:
337 // it is a protocol round trip and this runs at vsync.
338 let title = shown_title(&self.name, &self.project_path, self.new_project.as_deref(), self.autosave_armed);
339 if title != self.titled {
340 window.set_window_title(&title);
341 self.titled = title;
342 }
343 // A compositor keybind (the window manager's own fullscreen, not
344 // ours) can drop `window.is_fullscreen()` without ever going through
345 // [`Player::act`] -- the picture-only layout below must not survive
346 // that on its own, or the chrome never comes back. Only the *leaving*
347 // direction is reconciled here: the platform going fullscreen behind
348 // our back is not this editor asking for the picture-only layout, so
349 // it is left alone rather than guessed at.
350 if self.player_fullscreen && !window.is_fullscreen() {
351 self.player_fullscreen = false;
352 }
353 // No shadow flag: the session is the only truth about play state, and
354 // [`Player::transport`] is the one place it is read.
355 let state = self.transport();
356 // A paused timeline has nothing to animate; the toggle handlers notify,
357 // which is what starts the loop again. A paused seek keeps the loop
358 // running by itself until `pump` has the frame it asked for. An export
359 // pauses playback and still needs the loop: its progress only reaches
360 // the screen on a repaint. A notice does not: it waits to be dismissed
361 // rather than for a clock, so keeping the loop alive for it would spin
362 // the GPU until someone answered it.
363 // An import does too, and for the same reason: its clock and its sweep
364 // only reach the screen on a repaint, and a still line is the very
365 // thing it exists to disprove.
366 if state.is_playing()
367 || self.seek_since.is_some()
368 || self.export.is_some()
369 // ...and the queue, whose rows carry a percent.
370 || self.queue.is_going()
371 // ...and the sheet's trial write, whose answer is the time line.
372 || self.export_sheet.bench.is_some()
373 || self.importing.is_some()
374 // A silence scan too: its progress and its two clocks only reach
375 // the screen on a repaint, and a still line is the very thing this
376 // card was rewritten to disprove.
377 || self.silence_scan.is_some()
378 // ...and a stand-in being made: its percentage on the library row
379 // only reaches the screen on a repaint, and a bar that never moves
380 // is exactly what a person reads as a hung encode.
381 || self.making_proxies()
382 // ...and a stabilisation analysis: its percent on the transform
383 // card, and the corrected picture once it lands.
384 || !self.stab_waiting.is_empty()
385 // ...and a mask track: its percent on the effects card.
386 || !self.track_jobs.is_empty()
387 // ...and an auto reframe: its percent in the status bar.
388 || self.reframe_run.is_some()
389 // ...and angles being synced: the percent in the status bar.
390 || self.mcam_run.is_some()
391 // ...and a media collect: its bar and byte count only reach the screen on a repaint.
392 || self.collect_running()
393 // ...and a render preview: its bar fills, and its finish is seen, on a repaint.
394 || self.render.as_ref().is_some_and(|(job, _)| !job.is_finished())
395 {
396 window.request_animation_frame();
397 }
398
399 // Read per render, never cached: a delete shortens the timeline and the
400 // timecode, the ruler and the clamp below all have to follow it -- and
401 // so does the room a tail being dragged needs to grow into.
402 let duration = self.drawn_duration();
403 let position = self.playhead(duration);
404 // Re-settled every frame against the duration this one is drawing: an
405 // edit that shortens the timeline moves the far end of the view, and a
406 // playhead that has run off the bed pulls the view after it -- which is
407 // what makes a zoomed-in timeline scroll while it plays.
408 // ...but only a playhead that is *going* somewhere pulls it: following
409 // is what a moving one does, during playback and through a seek. A view
410 // yanked back to a playhead nobody moved is a hand's own scroll undone
411 // by the very next frame, which is what made the wheel look dead.
412 // ...and a hand that scrolled the view away from the head keeps it
413 // ([`Player::panned`]): a follow that centres the head again would undo
414 // the notch before it was seen, which is what made the wheel look dead
415 // while playing. It is given straight back below, the moment the head
416 // is on the bed a person chose to look at -- so the scroll wins now and
417 // the follow resumes by itself, with nothing to press.
418 // A fit asked for before the bed was painted ([`Player::zoom_fit`]) is
419 // taken here, on the first frame that measured one; until then the
420 // loop is kept alive so that frame comes.
421 if self.fit_pending {
422 match self.view().bed > 0. {
423 true => {
424 self.fit_to_bed();
425 self.fit_pending = false;
426 }
427 false => window.request_animation_frame(),
428 }
429 }
430 // A fit still in force follows the bed: the first frame measures the
431 // window's initial size, and a compositor resize to the tiled size
432 // after it changes the bed, so the fit is taken again for the new width
433 // ([`Player::fit_to_bed`]). A hand's zoom or scroll has cleared it.
434 if let Some(fitted) = self.fitted_bed {
435 let bed = self.view().bed;
436 if bed > 0. && bed != fitted {
437 self.fit_to_bed();
438 }
439 }
440 self.scale = match (state.is_playing() || self.seek_since.is_some()) && !self.panned {
441 true => self.view().following(position),
442 false => self.view().settled(),
443 };
444 if self.panned && self.view().shows(position) {
445 self.panned = false;
446 }
447
448 ui::stance::render(self, window, cx)
449 }
450}