forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

stance.rs2041 lines, 98.0 KiBHistoryRawDownload
1//! DESIGN.md §5 -- the stance: fixed geography, the only room now the
2//! legacy four-region tree is gone (`self.darkroom` no longer branches
3//! anything in `render.rs`), whole here as its own module rather than
4//! folded into that tree.
5//!
6//! This step lays out the six regions and nothing else: correct geometry,
7//! correct surfaces, a section-head label per region. No content, no
8//! interaction, no cut machinery -- `// hook:` comments below mark where the
9//! later steps in DESIGN §12's package attach.
10
11use crate::ui::bench_stance;
12use crate::ui::dock_stance;
13use crate::ui::hitmap;
14use crate::ui::menubar;
15use crate::ui::settings_stance;
16use crate::ui::timeband_stance;
17use crate::ui::toolbar;
18use crate::ui::type_scale::{self, Typeset};
19use crate::*;
20
21/// Keyboard focus v1: the three regions Tab/Shift-Tab cycle focus through
22/// (no ring is painted for it any more, user 2026-09-10) -- the bench, the dock's Sources tab (library) and the dock's
23/// Clip tab (inspector), the darkroom's own stand-ins for "timeline",
24/// "library" and "inspector" (there is no separate inspector *region* in
25/// this tree -- MOCK-SPEC's Clip tab, `dock_stance::clip_tab`, is it).
26/// `Player::focus` (the root handle every keybind hangs off) is not a
27/// member: Tab already means "select the clip under the playhead"
28/// (`ActionId::Select`, `keymap.rs`) at the root, unchanged here, and only
29/// starts meaning "enter the ring" once one of these three already holds
30/// focus.
31#[derive(Clone, Copy, PartialEq, Eq, Debug)]
32pub(crate) enum Surface {
33 Dock,
34 Bench,
35 Inspector,
36}
37
38/// Fixed cycle order: dock, bench, inspector.
39const SURFACE_CYCLE: [Surface; 3] = [Surface::Dock, Surface::Bench, Surface::Inspector];
40
41/// Tab (`backward` false) or Shift-Tab (`backward` true) from `current`,
42/// wrapping at either end of [`SURFACE_CYCLE`].
43pub(crate) fn next_surface(current: Surface, backward: bool) -> Surface {
44 let i = SURFACE_CYCLE.iter().position(|&s| s == current).unwrap();
45 let n = SURFACE_CYCLE.len();
46 SURFACE_CYCLE[if backward {
47 (i + n - 1) % n
48 } else {
49 (i + 1) % n
50 }]
51}
52
53/// The one key a surface's own `on_key_down` answers. Everything else is
54/// left alone on purpose, unhandled and un-stopped, so it bubbles to the
55/// root's fallback handler exactly as an unfocused key already does
56/// (`window.rs`'s key dispatch walks the focused node's ancestors in
57/// `Bubble` phase and stops only at `cx.stop_propagation()` -- the three
58/// surface handlers call that solely from this branch, gpui-0.2.2
59/// `window.rs:3897-3906`).
60pub(crate) fn is_focus_cycle_key(key: &str) -> bool {
61 key == "tab"
62}
63
64/// The other key a surface's own `on_key_down` answers: leaves the ring for
65/// the root handle (`Player::focus`) rather than letting the stroke bubble
66/// there itself -- same one-door reason as [`is_focus_cycle_key`], so the
67/// bench and both dock tabs cannot answer "what closes the ring" two
68/// different ways.
69pub(crate) fn is_focus_exit_key(key: &str) -> bool {
70 key == "escape"
71}
72
73/// The room-wide chords an open card does not take.
74///
75/// A card owns the keyboard for its own *values* -- the arrows on a slider, `r`
76/// for reset, `m` for maximize, tab on the equalizer, `enter` to apply
77/// ([`Player::param_card_key`]'s branch list) -- and every one of those is a
78/// *bare* stroke its own branch claims. These five are not: each acts on the
79/// document rather than on the card the hand is looking at, and while a card is
80/// open the room must still answer them. It is the equalizer card's own comment
81/// that says so from the inside: "Nothing to undo: every change is already at
82/// the clip, and undo is undo's own key".
83///
84/// - `Undo`/`Redo`: the edit history. The one chord a hand reaches for *while*
85/// looking at what it just changed, which is exactly when a card is open.
86/// - `Save`: the project file. Its chord is `ctrl+s`, and no card's branch
87/// answers a ctrl chord on purpose (`param_card_key` is handed the shift
88/// modifier alone).
89/// - `Copy`/`Paste`: the clip clipboard, the pair beside the history keys.
90///
91/// Asked against the [`keymap::ActionId`] the stroke resolved to, never against
92/// a key literal: a rebind moves the chord and this list follows it.
93///
94/// Deliberately *not* here, in three kinds:
95///
96/// 1. The strokes a card's own branch list claims, which the card must keep:
97/// escape (every card's way out, and `Deselect`'s own stroke), the arrows
98/// (`StepBack`/`StepForward`/`JumpBack`/`JumpForward` -- the branch reads
99/// them with or without ctrl), `m` (`ToggleMute`) and the digits, plus the
100/// bare letters the cards' verbs sit on -- `r` (`Loop`, `Resolution`), `f`
101/// (`Mix`, `Crossfade`), `a` (`AddAudioLane`, `SelectAll`), `s`
102/// (`Cut` -- the EQ card's spectrum), `x` (`Delete`, `Dissolve` -- the
103/// band's removal), `k` (`Color`), `j`, `u`, `y` (`SubtitleStyle`), `enter`
104/// (the silence card's apply).
105/// 2. The chords that open a card: `Export`/`Settings`/`Color`/`Transform`/
106/// `Speed`/`Silence`/`Mix`/`Equalizer`/`SubtitleStyle`. They own the very
107/// modal slot the open card is sitting in, and swapping the surface under a
108/// hand mid-stroke is not a chord this fix is for.
109/// 3. Everything else the keymap binds (the odometer, the trims, the zoom, the
110/// lane add/remove pair, the theme, the screenshot...). They are left to the
111/// card on purpose, the way [`Player::param_card_key`] left them before this:
112/// the defect is a card swallowing the *history* while the user edits through
113/// it, and each of these is one press away again the moment the card closes.
114pub(crate) fn card_safe_action(action: crate::keymap::ActionId) -> bool {
115 use crate::keymap::ActionId;
116 matches!(
117 action,
118 ActionId::Undo | ActionId::Redo | ActionId::Save | ActionId::Copy | ActionId::Paste
119 )
120}
121
122/// The strokes that keep their meaning while only a docked card is up
123/// ([`Player::docked_card_only`]): the transport and the room's own doors. The
124/// stepping, arrow and letter keys are left to the card, which reads them.
125pub(crate) fn docked_card_safe_action(action: crate::keymap::ActionId) -> bool {
126 use crate::keymap::ActionId;
127 matches!(
128 action,
129 ActionId::Play
130 | ActionId::GoStart
131 | ActionId::GoEnd
132 | ActionId::ShuttleStop
133 | ActionId::Export
134 | ActionId::Settings
135 | ActionId::ShowActions
136 | ActionId::Fullscreen
137 | ActionId::Theme
138 | ActionId::AccentColour
139 )
140}
141
142/// The strokes that keep their meaning while the Export tab shows: the transport's, and the
143/// ones that set what it exports -- I and O mark the range its In-Out choice uses, the arrows
144/// that step to the frame, and clearing the marks. The tab is a tab of the dock, not a sheet
145/// over the room, so the timeline stays in reach of the keyboard.
146pub(crate) fn export_tab_action(stroke: crate::keymap::ActionId) -> bool {
147 use crate::keymap::ActionId;
148 docked_card_safe_action(stroke)
149 || matches!(
150 stroke,
151 ActionId::SetIn | ActionId::SetOut | ActionId::ClearRange | ActionId::StepBack | ActionId::StepForward
152 )
153}
154
155/// Whether a docked card never reads this stroke. The cards read bare keys
156/// (arrows, digits, letters like `r`, `m`) and shift+arrow; a stroke with ctrl
157/// or alt, or shift on anything but an arrow, is nobody's card key, so the
158/// room's own bindings (Shift+E enable, Shift+R freeze, Ctrl+Alt+V...) answer it
159/// instead of the card swallowing it with the rest.
160pub(crate) fn docked_card_ignores(key: &str, ctrl: bool, shift: bool, alt: bool) -> bool {
161 let arrow = matches!(key, "left" | "right" | "up" | "down");
162 ctrl || alt || (shift && !arrow && key != "escape" && key != "tab")
163}
164
165/// The dock mounts only one of its two tabs at a time
166/// (`dock_stance::render`'s `match src_active`), so `focus_dock` only has a
167/// tree node under Sources and `focus_inspector` only under Clip -- focusing
168/// the unmounted one leaves gpui with a focused handle no node answers to,
169/// and every key dies until the next mouse click. Answers "does entering
170/// `surface` require flipping the dock tab first", pure so it's testable
171/// without a `Window`: `Some(true)`/`Some(false)` is the `dock_src_active`
172/// the surface needs mounted, `None` (bench) means leave the tab alone.
173pub(crate) fn surface_wants_src_active(surface: Surface) -> Option<bool> {
174 match surface {
175 Surface::Dock => Some(true),
176 Surface::Inspector => Some(false),
177 Surface::Bench => None,
178 }
179}
180
181impl Player {
182 /// The `FocusHandle` a [`Surface`] paints its ring on and Tab/Shift-Tab
183 /// moves to next -- one door, so `next_surface`'s answer and the handle
184 /// `window.focus` is given cannot name two different surfaces.
185 pub(crate) fn focus_handle(&self, surface: Surface) -> &FocusHandle {
186 match surface {
187 Surface::Dock => &self.focus_dock,
188 Surface::Bench => &self.focus_bench,
189 Surface::Inspector => &self.focus_inspector,
190 }
191 }
192
193 /// One door onto every ring move: flips the dock tab first
194 /// ([`surface_wants_src_active`]) so `surface`'s handle is always
195 /// mounted before `window.focus` lands on it, then persists the flip
196 /// exactly as the tab's own click does (`dock_stance::dock_tab`'s
197 /// `on_click`), so the ring and a mouse click can't disagree about
198 /// which tab was last chosen.
199 pub(crate) fn focus_surface(
200 &mut self,
201 surface: Surface,
202 window: &mut Window,
203 cx: &mut Context<Self>,
204 ) {
205 if let Some(src_active) = surface_wants_src_active(surface) {
206 self.dock_src_active = src_active;
207 crate::ui::dock_stance::save(src_active);
208 }
209 window.focus(self.focus_handle(surface));
210 cx.notify();
211 }
212}
213
214/// Fixed strip under the screen: timecode, transport, cut readout -- one row
215/// of 44px (DESIGN §5). The overview strip moved up above the ruler, so the
216/// band no longer carries a minimap. Kept `pub(crate)` for
217/// `layout::split_bounds`'s bench ceiling, the same one-door reason
218/// [`LEDGER_H`] already is.
219pub(crate) const TIME_BAND_H: f32 = 44.;
220/// The bench's untouched height -- [`Split::Bench`]'s own default, read by
221/// `layout::split_size` the same way the legacy tree's `library_w`/
222/// `inspector_w` feed `Split::Library`/`Split::Inspector`. A hand on the
223/// seam above it overrides this; nothing else does.
224pub(crate) const BENCH_H: f32 = 200.;
225/// Thin strip at the foot of the centre column. Read by `layout`'s
226/// `Split::Bench` drag formula (the seam sits above the fixed ledger, so a
227/// drag has to leave room for it) -- kept `pub(crate)` for that one door
228/// rather than a second copy of the number.
229pub(crate) const LEDGER_H: f32 = 24.;
230/// The dock's untouched width -- [`Split::Dock`]'s own default (DESIGN §5).
231/// Its floor is `layout::DOCK_MIN_W`, not the inspector's.
232pub(crate) const DOCK_W: f32 = 320.;
233/// What [`bench`] spends above `bench_stance::render`'s own content: the
234/// `bench` div's own `.border_t_1()` (1px) + its `py(4.)` top padding, and
235/// nothing else since the `BENCH` section head went (cleanse round 2 -- the
236/// ruler row starts the region and the geography says what it is). `1 + 4`
237/// = `5`. Named and `pub(crate)` rather than an inline subtraction, so
238/// `layout::BENCH_MIN_H` can derive from the real chrome.
239pub(crate) const BENCH_CHROME_H: f32 = 5.;
240
241/// The lowest a menu's top edge may sit and still land inside the
242/// bench/ledger/dock footprint below the screen (DESIGN §5, §9, §11 check 6):
243/// a right-click near the top of the window must not walk the menu up over
244/// the picture just because the pointer is there. `overlays.rs`/`library.rs`
245/// clamp their `menu.at.y` against this before handing it to `menu_at`, only
246/// in the darkroom stance -- the legacy tree has no fixed screen/time-band
247/// split for this to mean anything against, and must not move. `bench_h` is
248/// the live, possibly hand-dragged `Split::Bench` height (`Player::split_px`)
249/// rather than the fixed [`BENCH_H`] default, so a widened bench clamps the
250/// menu against the room actually left, not the room it started with.
251pub(crate) fn below_picture_floor(viewport_h: f32, bench_h: f32) -> f32 {
252 (viewport_h - TIME_BAND_H - bench_h - LEDGER_H).max(0.)
253}
254
255/// The maximized inspector card's own top -- deliberately *not*
256/// [`below_picture_floor`] fed the live bench straight through, the way
257/// `menu_floor` above correctly does for a menu. A maximized card is anchored
258/// to the same floor and grows downward to the window's own bottom edge, so
259/// its height is `viewport_h - floor` -- exactly the bench/ledger footprint,
260/// `TIME_BAND_H + bench_h + LEDGER_H`. Feeding the *live* bench in there means
261/// a hand-dragged bench smaller than [`BENCH_H`] starves the maximized card of
262/// room: driven at `bench=BENCH_MIN_H` the card shrank to 210px and its curve
263/// and band handles stopped rendering at all, while the same card *docked*
264/// (whose height was never bench-shaped to begin with) still drew everything
265/// -- maximize made the card strictly worse, backwards from what the feature
266/// promises. Floored at [`BENCH_H`], the bench's own untouched default, the
267/// maximized card is never smaller than it is at the bench nobody has
268/// dragged; a bench pulled *larger* than that still grows the card further,
269/// same as before, and the case actually verified good (card top exactly on
270/// the picture floor, picture unobstructed) is untouched because it ran at a
271/// bench already at or above this floor.
272pub(crate) fn maximized_card_top(viewport_h: f32, bench_h: f32) -> f32 {
273 below_picture_floor(viewport_h, bench_h.max(BENCH_H))
274}
275
276/// The floor-clamped placement for every scrolling menu (clip context menu,
277/// picker, library menu): the anchor pulled down to [`below_picture_floor`]
278/// *and* the room its list may fill capped to what is actually left between
279/// that floor and the window's bottom edge -- not the whole viewport. Passing
280/// the untouched viewport to `menu_rows_h` let a menu taller than the
281/// bench/ledger/dock footprint size itself against the full window, and then
282/// `menu_at`'s own bottom-edge clamp (`v.min(room - size)`) pulled the
283/// already-floored top edge back up over the picture to make it fit -- the
284/// menu-occlusion defect this exists to close. Sizing the list against the
285/// room *below the floor* instead means it never needs more than that room,
286/// so `menu_at` never has a reason to walk it back up; a list still taller
287/// than the room scrolls inside its own plate, same as the keys overlay.
288///
289/// The floor is the picture's own *painted* bottom edge
290/// ([`picture_bottom`]) when a frame is up, not the screen region's: the
291/// region letterboxes, and a black bar is not picture. With a 3840x1608
292/// film in a 2560x1440 window that edge sits ~170px above the region's own
293/// bottom, which is two more row slots the menu no longer has to scroll
294/// through. Nothing is shown (safelight, empty room, before the first
295/// paint) -> the region's bottom, unchanged. Returned alongside the anchor
296/// so the caller can flip the plate *above* its pointer without a second
297/// copy of this arithmetic.
298pub(crate) fn menu_floor(
299 at: Point<Pixels>,
300 viewport: Size<Pixels>,
301 bench_h: f32,
302 picture_bottom: Option<f32>,
303) -> (Point<Pixels>, Size<Pixels>, f32) {
304 let region = below_picture_floor(f32::from(viewport.height), bench_h);
305 let floor = picture_bottom.unwrap_or(region).clamp(0., region);
306 let at = point(at.x, px(f32::from(at.y).max(floor)));
307 let room = size(viewport.width, px(f32::from(viewport.height) - floor));
308 (at, room, floor)
309}
310
311/// The plate's top edge, flipped to sit *above* the pointer when the room
312/// below it does not hold the whole list -- `library.rs` already places its
313/// menu this way for the same reason, and every row above the fold is a row
314/// nobody has to wheel to. Never above `floor`: a menu that gained rows by
315/// climbing over the picture is the occlusion this file exists to prevent
316/// (DESIGN §5, §11 check 6). `room` from [`menu_floor`] already sizes the
317/// list to fit between `floor` and the window's bottom edge, so the clamped
318/// flip always fits.
319pub(crate) fn menu_above(
320 at: Point<Pixels>,
321 viewport: Size<Pixels>,
322 floor: f32,
323 h: f32,
324) -> Point<Pixels> {
325 if f32::from(at.y) + h + MENU_EDGE <= f32::from(viewport.height) {
326 return at;
327 }
328 point(at.x, px((f32::from(at.y) - h).max(floor)))
329}
330
331#[cfg(test)]
332mod menu_floor_tests {
333 use super::*;
334
335 /// The defect measured live: a 396px-tall menu anchored high in a 720px
336 /// window used to size itself against the full window (720), so
337 /// `menu_at`'s bottom clamp walked its floored top edge back up to
338 /// 720-396=324 -- 10px above the picture's own floor (404 at this
339 /// window height: 720-88-200-28). The room handed to the list sizer must
340 /// now be capped to the footprint (316px here), so the placed top edge
341 /// never leaves the floor.
342 #[test]
343 fn a_menu_taller_than_the_footprint_stays_pinned_to_the_floor_not_walked_back_over_it() {
344 let viewport = size(px(1280.), px(720.));
345 let floor = below_picture_floor(f32::from(viewport.height), BENCH_H);
346 let (at, room, _) = menu_floor(point(px(300.), px(20.)), viewport, BENCH_H, None);
347 assert_eq!(f32::from(at.y), floor);
348 // 17 rows -- more than the footprint holds -- sized through the real
349 // sizer, so the `MENU_EDGE` margin is in the number the clamp sees.
350 let list_h = crate::oracle::menu_rows_h(17, room);
351 assert!(list_h <= f32::from(room.height));
352 let h = crate::layout::MENU_PAD * 2. + list_h;
353 let (_, y) = crate::oracle::menu_at(at, viewport, h);
354 assert_eq!(
355 y, floor,
356 "the top edge must not be walked back above the floor"
357 );
358 }
359
360 /// Defect 1 as the user met it (`f-clip-menu.png`): a menu opened near the
361 /// right and bottom of a 1280x720 window ran off both edges -- chords cut
362 /// mid-word at the dock seam, rows past the frame. Pure clamp math, both
363 /// window sizes the charter names, and both the floored (clip) menu and
364 /// the unfloored (library) one: whatever the anchor, the whole plate lands
365 /// inside the frame with [`MENU_EDGE`] to spare, and the floored one never
366 /// buys that room off the picture.
367 #[test]
368 fn a_menu_opened_in_the_bottom_right_corner_lands_whole_inside_the_window() {
369 use crate::layout::{MENU_EDGE, MENU_PAD, MENU_W};
370 for viewport in [size(px(1280.), px(720.)), size(px(2560.), px(1440.))] {
371 let (w, v) = (f32::from(viewport.width), f32::from(viewport.height));
372 let floor = below_picture_floor(v, BENCH_H);
373 for rows in [1usize, 5, 16, 40] {
374 for anchor in [
375 point(px(w - 1.), px(v - 1.)),
376 point(px(w - 1.), px(0.)),
377 point(px(0.), px(v - 1.)),
378 ] {
379 // The clip menu's path: floored below the picture, sized
380 // against the room that leaves, then clamped.
381 // Both the picture floors a menu can get: the region's
382 // own bottom (nothing shown) and a letterboxed film's
383 // painted edge, 120px above it.
384 for pic in [None, Some(floor - 120.)] {
385 let (at, room, f) = menu_floor(anchor, viewport, BENCH_H, pic);
386 let h = MENU_PAD * 2. + crate::oracle::menu_rows_h(rows, room);
387 // Through the flip: the placement the app actually uses.
388 let at = menu_above(at, viewport, f, h);
389 let (x, y) = crate::oracle::menu_at(at, viewport, h);
390 assert!(y >= f, "y {y} walked above the menu floor {f}");
391 assert!(
392 x >= MENU_EDGE && x + MENU_W <= w - MENU_EDGE,
393 "x {x} rows {rows}"
394 );
395 assert!(
396 y >= MENU_EDGE && y + h <= v - MENU_EDGE,
397 "y {y} h {h} rows {rows}"
398 );
399 }
400 // The library menu's path: no floor, hung a row below the
401 // pointer, same clamp.
402 let h = MENU_PAD * 2. + crate::oracle::menu_rows_h(rows, viewport);
403 let (x, y) =
404 crate::oracle::menu_at(point(anchor.x, anchor.y + px(52.)), viewport, h);
405 assert!(x >= MENU_EDGE && x + MENU_W <= w - MENU_EDGE, "lib x {x}");
406 assert!(y >= MENU_EDGE && y + h <= v - MENU_EDGE, "lib y {y} h {h}");
407 }
408 }
409 }
410 }
411
412 /// The floor the charter names (R4): a wide film letterboxed into a tall
413 /// region stops being picture well above that region's bottom, and the
414 /// menu may have that black. A 3840x1608 film fit into the real
415 /// 2560x1440 darkroom's picture box (2224x1129) lands 931px tall -- a
416 /// 99px bar top and bottom -- so the floor rises 99px, two more row
417 /// slots. A 4:3 source in a 4:3 box has no bar at all and the floor stays
418 /// the region's own bottom.
419 #[test]
420 fn the_menu_floor_is_the_picture_s_painted_edge_not_the_region_s() {
421 let native = |w, h| size(gpui::DevicePixels(w), gpui::DevicePixels(h));
422 let box_of = |w: f32, h: f32| Bounds {
423 origin: point(px(0.), px(88.)),
424 size: size(px(w), px(h)),
425 };
426 // Wide film, tall box: bars top and bottom, so the edge rises.
427 let wide = fitted_bottom(box_of(2224., 1129.), native(3840, 1608)).unwrap();
428 let painted_h = 2224. * 1608. / 3840.;
429 let want = 88. + (1129. - painted_h) / 2. + painted_h;
430 assert!(
431 (wide - want).abs() < 1.,
432 "wide film's painted bottom {wide}, wanted {want}"
433 );
434 assert!(88. + 1129. - wide > 90., "the bar the menu gains is real");
435 // Same ratio as its box: no bar, the edge IS the box's bottom.
436 let square = fitted_bottom(box_of(800., 600.), native(1600, 1200)).unwrap();
437 assert!((square - 688.).abs() < 0.01, "4:3 in a 4:3 box: {square}");
438 // Nothing measured yet reads as no floor, never a NaN one.
439 assert_eq!(fitted_bottom(box_of(0., 0.), native(1600, 1200)), None);
440
441 // And the floor menu_floor hands the sizer follows it: the wide film
442 // buys the menu rows, the region's bottom is still the ceiling on it.
443 let viewport = size(px(2560.), px(1440.));
444 let region = below_picture_floor(1440., BENCH_H);
445 let (_, room, floor) = menu_floor(point(px(10.), px(10.)), viewport, BENCH_H, Some(wide));
446 assert_eq!(floor, wide);
447 assert!(f32::from(room.height) > 1440. - region);
448 // A bogus reading below the bench never lets a menu climb: clamped.
449 let (_, _, floor) = menu_floor(point(px(10.), px(10.)), viewport, BENCH_H, Some(9999.));
450 assert_eq!(floor, region);
451 }
452}
453
454#[cfg(test)]
455mod project_readout_tests {
456 use super::*;
457
458 /// The ledger's resting readout (nothing selected): the timeline's length
459 /// as a timecode and in seconds, and its clip count; an empty timeline
460 /// says so rather than reading `00:00:00:00 · 0 clips`.
461 #[test]
462 fn the_resting_readout_names_the_length_and_the_clip_count() {
463 assert_eq!(project_readout(285, 2, 30.), "Timeline 0:10 · 2 clips");
464 assert_eq!(project_readout(50, 1, 25.), "Timeline 0:02 · 1 clip");
465 assert_eq!(project_readout(6600, 20, 30.), "Timeline 3:40 · 20 clips");
466 assert_eq!(project_readout(0, 0, 25.), "Empty timeline · drag media here to start");
467 }
468}
469
470#[cfg(test)]
471mod maximized_card_top_tests {
472 use super::*;
473
474 /// The regression D1 shipped as: the old call site fed the *live* bench
475 /// straight into `below_picture_floor`, so a bench dragged down to
476 /// `crate::BENCH_MIN_H` (a legal value -- `layout::split_size` clamps
477 /// anything smaller up to it) gave the maximized card *less* room than
478 /// docked, not more. This binary has no `TestAppContext`, so it cannot
479 /// read back a painted rect the way a driven screenshot can -- this is a
480 /// value-level check of the two formulas the maximize feature is built
481 /// on, not a substitute for driving the app at the smallest bench. Swept
482 /// across the *whole* legal bench range (the earlier guard this replaces
483 /// checked only the untouched default, which is exactly why a small,
484 /// legal bench slipped through), maximized room must never fall below the
485 /// room at the bench nobody has dragged, and must never be smaller than
486 /// what the same live bench leaves for `below_picture_floor`'s own live
487 /// use (menu placement) -- the two must not tangle back together.
488 #[test]
489 fn maximized_room_never_shrinks_below_the_default_bench_across_every_legal_bench_height() {
490 let viewport = size(px(1280.), px(720.));
491 let v = f32::from(viewport.height);
492 let default_room = v - below_picture_floor(v, BENCH_H);
493 let mut bench_h = crate::BENCH_MIN_H;
494 while bench_h <= 600. {
495 let room = v - maximized_card_top(v, bench_h);
496 assert!(
497 room >= default_room,
498 "bench={bench_h}: maximized room {room} fell below the default-bench \
499 room {default_room}"
500 );
501 // Still strictly bigger than a bare `below_picture_floor` room
502 // would ever have given it below `BENCH_H` -- the coupling this
503 // fix breaks.
504 if bench_h < BENCH_H {
505 assert!(room > v - below_picture_floor(v, bench_h));
506 }
507 bench_h += 25.;
508 }
509 }
510}
511
512thread_local! {
513 // The picture region's own laid-out box, measured each frame by a
514 // [`bounds_probe`] the same shape `timeband_stance`'s contact strip keeps
515 // (`STRIP_BOUNDS`) -- [`picture_bottom`] needs the box the picture was
516 // fitted into, which nothing upstream of paint knows. (Cleanse round 2,
517 // 2026-09-10: the `scale 0.59` readout this also fed is deleted -- fit is
518 // `^0` and the number was a state nobody acts on.)
519 pub(crate) static PICTURE_BOUNDS: Rc<Cell<Bounds<Pixels>>> = Rc::new(Cell::new(Bounds::default()));
520}
521
522/// The pure half of [`picture_bottom`]: the bottom edge of the `Contain`
523/// fit of `native` into `bounds` -- gpui's own `get_bounds`, the same call
524/// [`letterboxed_image`] paints through, so this is the frame's real edge
525/// and not aspect math reimplemented here.
526fn fitted_bottom(bounds: Bounds<Pixels>, native: gpui::Size<gpui::DevicePixels>) -> Option<f32> {
527 if bounds.size.width <= px(0.)
528 || bounds.size.height <= px(0.)
529 || native.width.0 <= 0
530 || native.height.0 <= 0
531 {
532 return None;
533 }
534 let fitted = gpui::ObjectFit::Contain.get_bounds(bounds, native);
535 Some(f32::from(fitted.origin.y + fitted.size.height))
536}
537
538/// Where the picture actually stops being picture: the letterboxed frame's
539/// bottom edge in window coordinates, read off the last frame's measured box
540/// ([`PICTURE_BOUNDS`]). `None` with nothing shown or before the first paint
541/// measured anything -- [`menu_floor`] falls back to the region's bottom.
542pub(crate) fn picture_bottom(player: &Player) -> Option<f32> {
543 let image = player.image.clone()?;
544 fitted_bottom(PICTURE_BOUNDS.with(Rc::clone).get(), image.size(0))
545}
546
547/// Gap between the picture and the viewer's edge (DESIGN §6.2: "letterboxed
548/// and centred, with 12px padding").
549const VIEWER_PAD: f32 = 12.;
550
551/// The viewer header (REDESIGN §2.1): 28px on `e1` (24 on a window shorter than
552/// 800px), above the picture instead of a chip drawn over it. Left, the viewer's
553/// zoom and playback-quality choices and the guides toggle -- the viewer only
554/// fits the picture today, so they are drawn disabled with the reason; right,
555/// the project's format as a plain readout.
556fn viewer_header(player: &Player, window: &Window, cx: &mut Context<Player>) -> impl IntoElement {
557 use crate::ui::icons::{Icon, IconSize};
558 use crate::ui::kit::{Button, ButtonSize, ButtonStyle};
559 let t = crate::ui::theme::tokens();
560 let short = f32::from(window.viewport_size().height) < 800.;
561 let h = if short { crate::layout::redesign::VIEWER_HDR_H_SHORT } else { crate::layout::redesign::VIEWER_HDR_H };
562 // Each control sits in a fixed-width cell, so a longer value never moves its neighbours.
563 let dropdown = |id: &'static str, slot: usize, text: SharedString, w: f32, action: ActionId, cx: &mut Context<Player>| {
564 let yes = player.enable(action, None).yes();
565 div()
566 .relative()
567 .flex_none()
568 .w(px(w))
569 .child(bounds_probe(player.viewer_btns[slot].clone()))
570 .child(
571 Button::new(id)
572 .style(ButtonStyle::Ghost)
573 .size(ButtonSize::Small)
574 .label(text)
575 .min_w(w)
576 .enabled(yes)
577 .build()
578 .child(Icon::ChevronDown.el(IconSize::Inline, t.ink3))
579 .on_click(cx.listener(move |this, _: &ClickEvent, window, cx| this.act(action, window, cx)))
580 .tooltip(crate::ui::widgets::action_hover(player, action))
581 .children(crate::ui::hitmap::action(action, yes)),
582 )
583 };
584 let format = player.session.as_ref().map(|s| {
585 let (w, h) = s.resolution();
586 format!("{} · {} fps", size_label(w, h), fps_label(player.fps))
587 });
588 div()
589 .id("stance-viewer-header")
590 .flex_none()
591 .w_full()
592 .h(px(h))
593 .flex()
594 .items_center()
595 .gap(px(4.))
596 .px(px(12.))
597 .bg(rgb(t.e1))
598 .child(dropdown("vh-zoom", 0, player.viewer.zoom.label().into(), 64., ActionId::ViewZoom, cx))
599 .child(dropdown("vh-quality", 1, player.viewer.quality.closed_label().into(), 128., ActionId::PlaybackQuality, cx))
600 .child(dropdown("vh-guides", 2, format!("Guides: {}", player.viewer.guide.label()).into(), 136., ActionId::GuideStyle, cx))
601 .child(dropdown("vh-mask", 3, format!("Mask: {}", player.viewer.mask.label()).into(), 104., ActionId::GuideMask, cx))
602 .child(
603 div()
604 .flex_1()
605 .min_w(px(0.))
606 .flex()
607 .justify_end()
608 .overflow_hidden()
609 .type_style(type_scale::caption())
610 .text_color(rgb(t.ink2))
611 .children(source_name(player).map(|name| div().min_w(px(0.)).truncate().pr(px(8.)).child(name))),
612 )
613 .children(player.session.is_some().then(|| source_toggle(player, cx)))
614 // The readout is a door to the project's own settings, where the size
615 // and rate are changed: a hover says so, and a click goes there.
616 .children(format.map(|text| {
617 div()
618 .id("vh-project")
619 .flex_none()
620 .px(px(4.))
621 .rounded(px(4.))
622 .cursor_pointer()
623 .type_style(type_scale::caption())
624 .text_color(rgb(t.ink3))
625 .hover(|s| s.bg(rgb(t.e2)).text_color(rgb(t.ink1)))
626 .tooltip(crate::ui::widgets::overlay_tip_hover(
627 "Project settings",
628 "",
629 Some("The size and frame rate of this project: click to change them"),
630 ))
631 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
632 this.settings_tab = crate::ui::settings_stance::SettingsTab::Project;
633 this.open_settings(cx);
634 }))
635 .child(text)
636 }))
637}
638
639/// The name of the clip open in the source viewer, shown in the header while it is up.
640fn source_name(player: &Player) -> Option<SharedString> {
641 let (path, _) = player.source_target.as_ref().filter(|_| player.preview_session.is_some())?;
642 Some(stem(path).into())
643}
644
645/// The Source / Timeline switch of the viewer header: which of the two the
646/// picture shows. Source is the library item opened in the source viewer (its
647/// name is shown in the header beside it, [`source_name`]); Timeline
648/// is the edit. Both pills keep their width in either state, and Source is
649/// disabled until an item has been opened.
650fn source_toggle(player: &Player, cx: &mut Context<Player>) -> impl IntoElement {
651 use crate::ui::kit::{segmented, Segment};
652 let target = player.source_target.clone();
653 // The pill always says "Source": the clip's name is in the viewer header beside it, so the
654 // pill never changes width.
655 let label: SharedString = "Source".into();
656 let empty_source = player.source_hint && target.is_none();
657 let selected = usize::from(player.preview_session.is_none() && !empty_source);
658 let no_source = target.is_none();
659 let me = cx.entity();
660 div()
661 .id("vh-source-wrap")
662 .flex_none()
663 .mr(px(8.))
664 .child(segmented(
665 "vh-source",
666 &[Segment::text(label), Segment::text("Timeline")],
667 selected,
668 player.session.is_some(),
669 None,
670 move |i, _, app| {
671 me.update(app, |this, cx| match (i, this.source_target.clone()) {
672 (0, Some((path, stream))) if this.preview_session.is_none() => this.open_preview(&path, stream, cx),
673 // Nothing opened yet: the viewer says how to open a clip, instead of nothing happening.
674 (0, None) => {
675 this.source_hint = true;
676 cx.notify();
677 }
678 (1, _) => {
679 this.source_hint = false;
680 this.close_preview(cx);
681 cx.notify();
682 }
683 _ => {}
684 })
685 },
686 ))
687 .tooltip(crate::ui::widgets::tip_hover(
688 "Source or timeline",
689 "Esc",
690 no_source.then_some("Double-click a media item to open it here"),
691 ))
692 .children(crate::ui::hitmap::control("viewer.source", "Source or timeline", target.is_some()))
693}
694
695/// What the Source side shows before any clip was opened in it: the way to open one.
696fn source_empty() -> impl IntoElement {
697 use crate::ui::icons::{Icon, IconSize};
698 let t = crate::ui::theme::tokens();
699 div()
700 .id("source-empty")
701 .absolute()
702 .top_0()
703 .bottom_0()
704 .left_0()
705 .right_0()
706 .flex()
707 .flex_col()
708 .items_center()
709 .justify_center()
710 .gap(px(8.))
711 .child(Icon::Film.el(IconSize::Hero, t.ink3))
712 .child(div().type_style(type_scale::title()).text_color(rgb(t.ink2)).child("Open a clip from Media to preview it here"))
713 .child(
714 div()
715 .type_style(type_scale::body())
716 .text_color(rgb(t.ink3))
717 .child("Double-click it, or right-click it and choose Open in source viewer"),
718 )
719}
720
721/// The picture region: top of the centre column, takes the remaining space.
722/// Reuses [`Player::picture_area`] rather than a second image element -- the
723/// darkroom draws the same picture the legacy tree does. The picture is fitted
724/// into the viewer minus [`VIEWER_PAD`] on every side, and nothing is drawn over it (DESIGN §6.2).
725fn screen(
726 player: &mut Player,
727 position: f64,
728 window: &mut Window,
729 cx: &mut Context<Player>,
730) -> impl IntoElement {
731 div()
732 .id("stance-screen")
733 .on_mouse_down(
734 MouseButton::Right,
735 cx.listener(|this, event: &MouseDownEvent, _, cx| {
736 this.open_viewer_menu(event.position, cx);
737 }),
738 )
739 .flex_1()
740 .min_h(px(0.))
741 .flex()
742 .flex_col()
743 .relative()
744 // §4: room chrome takes 0 radius.
745 .rounded(px(0.))
746 .bg(rgb(crate::ui::theme::tokens().matte))
747 .child(viewer_header(player, window, cx))
748 .child(
749 div()
750 .id("stance-picture")
751 .on_scroll_wheel(cx.listener(|this, event: &ScrollWheelEvent, window, cx| {
752 this.viewer_wheel(event, window, cx);
753 }))
754 .on_mouse_down(MouseButton::Left, cx.listener(|this, e: &MouseDownEvent, _, _| this.viewer_drag_start(e.position)))
755 .on_mouse_down(MouseButton::Middle, cx.listener(|this, e: &MouseDownEvent, _, _| this.viewer_drag_start(e.position)))
756 .on_mouse_move(cx.listener(|this, e: &MouseMoveEvent, window, cx| {
757 if e.pressed_button.is_some() {
758 this.viewer_drag_move(e.position, e.modifiers.shift, window, cx);
759 } else {
760 this.viewer_drag_end(cx);
761 }
762 }))
763 .on_mouse_up(MouseButton::Left, cx.listener(|this, _: &MouseUpEvent, _, cx| this.viewer_drag_end(cx)))
764 .on_mouse_up(MouseButton::Middle, cx.listener(|this, _: &MouseUpEvent, _, cx| this.viewer_drag_end(cx)))
765 .flex_1()
766 .min_h(px(0.))
767 .p(px(VIEWER_PAD))
768 .flex()
769 .gap(px(VIEWER_PAD))
770 // The source monitor's picture is draggable onto a lane: the
771 // marked part (the whole source with no marks) lands where it
772 // is let go, through the same door a library row uses.
773 .when_some(player.source_target.clone().filter(|_| player.preview_session.is_some()), |d, (path, stream)| {
774 let ghost: SharedString = crate::file_name(&path).into();
775 let me = cx.entity();
776 d.on_drag(crate::interact::AssetDrag(path, stream), move |_, _, _, cx| {
777 me.update(cx, |this, _| {
778 this.drag_lane = None;
779 this.drag_x = None;
780 });
781 cx.new(|_| crate::ui::widgets::Tip(ghost.clone()))
782 })
783 })
784 .child(
785 // The padded box is the picture's box: the bounds probe
786 // measures it, so the fit and the subtitle placement both
787 // work in the same inset region.
788 div()
789 .flex_1()
790 .min_h(px(0.))
791 .flex()
792 .relative()
793 .children(program_and_monitor(player, position, window, cx))
794 .child(bounds_probe(PICTURE_BOUNDS.with(Rc::clone)))
795 .children(player.viewer_handle_layer(window.scale_factor(), cx)),
796 ),
797 )
798 // The preview's own plate, a flex sibling: drawn inside the picture it would cover the frame.
799 .children(player.source_strip(window, cx))
800 // Only while an edit point is being trimmed, rolled, slipped, slid or
801 // nudged: a split over the picture's own box, taking no room.
802 .children(player.trim_two_up())
803}
804
805/// The narrowest strip the angle monitor takes beside the program picture, in px. Narrower than
806/// this, the monitor shares the row with the picture instead, and the picture gives it room.
807const MONITOR_STRIP_MIN: f32 = 200.;
808
809/// The free strip left of the program picture, in px, from the picture box as the last frame
810/// measured it and the picture as it is drawn (zoom, pan and fit included). `None` before the
811/// first paint has measured the box.
812fn monitor_strip(player: &Player, window: &Window) -> Option<f32> {
813 let b = PICTURE_BOUNDS.with(Rc::clone).get();
814 if b.size.width <= px(0.) || b.size.height <= px(0.) {
815 return None;
816 }
817 let (ox, oy) = (f32::from(b.origin.x), f32::from(b.origin.y));
818 let bx = (f32::from(b.size.width), f32::from(b.size.height));
819 let Some(image) = player.image.clone() else {
820 return Some(bx.0);
821 };
822 let native = player.viewer_native_or(&image);
823 let frame = crate::viewer_view::picture_rect(player.viewer.zoom, native, bx, (ox, oy), player.viewer_pan, window.scale_factor());
824 Some(frame.0 - ox)
825}
826
827/// The program picture and, while the angle monitor is on, the monitor. The monitor sits over
828/// the empty canvas left of the picture, so the picture keeps its exact geometry. Where that
829/// strip is narrower than [`MONITOR_STRIP_MIN`], the monitor is a flex sibling of the picture
830/// instead, and the picture makes room for it.
831fn program_and_monitor(player: &mut Player, position: f64, window: &mut Window, cx: &mut Context<Player>) -> Vec<AnyElement> {
832 let program = match player.source_hint && player.source_target.is_none() && player.preview_session.is_none() {
833 true => source_empty().into_any_element(),
834 false => player.picture_area(position, window, cx).into_any_element(),
835 };
836 if !(player.angle_monitor && player.preview_session.is_none()) {
837 return vec![program];
838 }
839 let strip = monitor_strip(player, window).filter(|s| *s >= MONITOR_STRIP_MIN);
840 let Some(monitor) = player.angle_monitor_view(cx, if strip.is_some() { 2 } else { 3 }) else {
841 return vec![program];
842 };
843 match strip {
844 Some(strip) => {
845 let overlay = div()
846 .absolute()
847 .top(px(VIEWER_PAD))
848 .bottom(px(VIEWER_PAD))
849 .left(px(VIEWER_PAD))
850 .w(px(strip - 2. * VIEWER_PAD))
851 .child(monitor);
852 vec![program, overlay.into_any_element()]
853 }
854 None => vec![monitor, program],
855 }
856}
857
858/// Fixed-height strip under the screen: timecode leads, the transport sits
859/// centred, the cut readout closes the row (DESIGN §5). Frame only -- every
860/// row lives in [`crate::ui::timeband_stance`], the same split
861/// `bench_stance`/`dock_stance` already make for their regions.
862fn time_band(player: &mut Player, position: f64, cx: &mut Context<Player>) -> impl IntoElement {
863 // The position comes from `render`, the same one the screen and the ledger
864 // read. Asking `active_session` here instead read the PREVIEW's clock while
865 // a preview was up, so the hero timecode and the ledger's position -- two
866 // readouts of one truth -- disagreed on screen.
867 div()
868 .id("stance-time-band")
869 .relative()
870 .flex_none()
871 .h(px(TIME_BAND_H))
872 .bg(rgb(crate::ui::theme::tokens().e1))
873 .border_t_1()
874 .border_color(rgba(crate::ui::theme::tokens().line))
875 .flex()
876 // Measured, not computed: the record sheet hangs just above this band.
877 .child(crate::ui::anchor::probe("record-band"))
878 .child(timeband_stance::render(player, position, cx))
879}
880
881/// Lanes, under the time band. `canvas` is the bench background too (DESIGN
882/// §2's token table), so it shares its surface with the screen above it.
883/// Height comes from [`Player::split_px`] now, not the fixed [`BENCH_H`]:
884/// the seam [`crate::ui::stance::render`] mounts above this region is what
885/// answers "ui fields are not stretchable" for the bench.
886fn bench(
887 player: &mut Player,
888 bench_h: f32,
889 window: &mut Window,
890 cx: &mut Context<Player>,
891) -> impl IntoElement {
892 let focused = player.focus_bench.is_focused(window);
893 bench_stance::set_window_h(f32::from(window.viewport_size().height));
894 div()
895 .id("stance-bench")
896 .track_focus(&player.focus_bench)
897 .on_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| {
898 let key = event.keystroke.key.as_str();
899 if is_focus_cycle_key(key) {
900 let next = next_surface(Surface::Bench, event.keystroke.modifiers.shift);
901 this.focus_surface(next, window, cx);
902 cx.stop_propagation();
903 } else if is_focus_exit_key(key) && !this.any_text_field() {
904 // A dismissible overlay (context menu, library menu, picker,
905 // any card, a live preview) opened by a click into the bench
906 // takes this escape first -- the same door the root handler
907 // itself closes it through (`Player::escape_closes_overlay`)
908 // -- so it does not go on sitting open just because focus
909 // happened to be inside this ring when escape was pressed.
910 if this.escape_closes_overlay(cx) {
911 cx.stop_propagation();
912 return;
913 }
914 // Leaves the ring for the root and lets the stroke bubble on to it: the root
915 // answers escape as Deselect (the caption, title and clip selections go).
916 window.focus(&this.focus);
917 cx.notify();
918 }
919 }))
920 .flex_none()
921 .h(px(bench_h))
922 // The toast stack hangs off this box (DESIGN §8), so it is the anchor.
923 .relative()
924 // §4: lanes take 0 radius.
925 .rounded(px(0.))
926 .bg(rgb(DARK_CANVAS()))
927 .border_t_1()
928 // DESIGN §4.10: the focused region's top edge is the 1px ink2 rule,
929 // recoloured in place so no size moves. No ring or outline: a region
930 // is never outlined for holding focus (user 2026-09-10, "clicking
931 // through timeline draws a white overlay around the timeline"). Tab
932 // and Shift-Tab still land here ([`next_surface`]); the only ring left
933 // in the bench is the selection one a picked clip draws (DESIGN §2/§4).
934 .border_color(if focused {
935 rgb(INK2())
936 } else {
937 rgba(DARK_SEAM())
938 })
939 .flex()
940 .flex_col()
941 // The 12px side gutter is spent INSIDE `bench_stance`'s own content
942 // box, not here: gpui fires `on_drop` only on an element whose own
943 // hitbox holds the pointer (`div.rs:2089`), and padding on this
944 // parent left the gutter outside every registered target -- a clip
945 // let go at x < 12, hard against the left edge where a hand aiming
946 // at frame 0 puts it, reached nothing at all and moved nothing,
947 // silently (DESIGN §8: a release that has aimed has made an edit).
948 // Same box, same pixels; only the catch-all's bounds grow.
949 // The edit toolbar tops the box (DESIGN §6.4), so its height is spent
950 // here out of `bench_h` and the lanes get what is left -- the same
951 // `TOOLBAR_H` the bench's floor (`BENCH_MIN_H`) already counts.
952 .child(toolbar::render(player, cx))
953 .child(
954 div()
955 .flex_1()
956 .min_h(px(0.))
957 .py(px(4.))
958 .child(bench_stance::render(player, cx)),
959 )
960}
961
962/// DESIGN §8's toasts: ONE at a time, the newest notice, shown in the status
963/// bar ([`ledger`]) in place of its readout. Never over the timeline or the
964/// picture, and the bar's height is fixed, so no toast moves anything.
965///
966/// One toast: a 3px stripe in its tone, the line in INK1, the button its action
967/// wears as a ghost, and a ✕. An info or warn toast starts its hide timer the
968/// first frame it is drawn ([`Toast::timer_armed`]); the timer names the toast
969/// by id, so a late one finds nothing and hides nothing.
970/// The widest a toast grows in the status bar before its text is elided.
971pub(crate) const TOAST_MAX_W: f32 = 760.;
972
973/// REDESIGN §2's region heights for the stance, as new names (P3 adopts them
974/// and retires the legacy constants above). The shared definitions live in
975/// [`crate::layout::redesign`]; these four are the ones this module owns.
976#[allow(dead_code, reason = "defined by P1, adopted by P3")]
977pub(crate) mod redesign {
978 use crate::layout::redesign as r;
979 pub(crate) const TIME_BAND_H: f32 = r::TRANSPORT_H;
980 /// The bench (timeline panel) default share of the window height.
981 pub(crate) const BENCH_SHARE: f32 = r::TIMELINE_SHARE;
982 pub(crate) const LEDGER_H: f32 = r::STATUS_H;
983 pub(crate) const DOCK_W: f32 = r::DOCK_W;
984}
985
986/// The words a toast shows in its text box: the message, cut with an ellipsis to the width
987/// the box had on the last frame. The box is measured with a probe (as the readout is), so the
988/// cut is the one the strip paints. Before the first measurement the whole message is given and
989/// the box's own clip holds it; the probe asks for one more frame when its width changes.
990fn toast_words(text: &str, text_box: &Rc<Cell<Bounds<Pixels>>>, cx: &App) -> String {
991 let words = ledger_line(text);
992 // The probe covers the box with its 8 px side padding on each side.
993 // At least the room a toast can have: a box sized by its own text (a toast with no buttons)
994 // would otherwise never grow past the cut it was last given.
995 let width = (f32::from(text_box.get().size.width) - 16.).max(TOAST_MAX_W - 120.);
996 if width <= 0. {
997 return words;
998 }
999 bench_stance::clip::fit_label(cx, &words, width).unwrap_or_default()
1000}
1001
1002/// A canvas that records the toast text box's bounds for [`toast_words`], and asks for
1003/// another frame when the width changed, so the next frame cuts to the new width.
1004fn toast_text_probe(into: Rc<Cell<Bounds<Pixels>>>) -> impl IntoElement {
1005 canvas(
1006 move |bounds, window, _| {
1007 if into.replace(bounds).size.width != bounds.size.width {
1008 window.request_animation_frame();
1009 }
1010 },
1011 |_, _, _, _| (),
1012 )
1013 .absolute()
1014 .size_full()
1015}
1016
1017fn toast_card(toast: &Toast, text_box: &Rc<Cell<Bounds<Pixels>>>, cx: &mut Context<Player>) -> gpui::Stateful<gpui::Div> {
1018 let id = toast.id;
1019 if toast.hides() && !toast.timer_armed.replace(true) {
1020 cx.spawn(async move |this, cx| {
1021 cx.background_executor().timer(TOAST_HIDE).await;
1022 let _ = this.update(cx, |this, cx| this.dismiss_toast(id, cx));
1023 })
1024 .detach();
1025 }
1026 let t = crate::ui::theme::tokens();
1027 let (glyph, tone_ink) = match toast.tone {
1028 Tone::Info => (crate::ui::icons::Icon::Info, t.ink3),
1029 Tone::Warn => (crate::ui::icons::Icon::TriangleAlert, t.warn),
1030 Tone::Err => (crate::ui::icons::Icon::CircleX, t.err),
1031 };
1032 let ghost = |label: &'static str| {
1033 div()
1034 .flex_none()
1035 .h(px(18.))
1036 .px(px(8.))
1037 .flex()
1038 .items_center()
1039 .rounded(px(4.))
1040 .type_style(type_scale::caption_strong())
1041 .text_color(rgb(t.ink2))
1042 .hover(|s| s.bg(rgba(crate::ui::theme::WASH_HOVER)).text_color(rgb(crate::ui::theme::tokens().ink1)))
1043 .cursor_pointer()
1044 .child(label)
1045 };
1046 div()
1047 .id(SharedString::from(format!("stance-toast-{id}")))
1048 // Shrinks only when the strip itself runs out (the format and verbs on
1049 // the right keep their width): an ordinary message shows whole.
1050 .flex_shrink()
1051 .min_w(px(0.))
1052 .max_w(px(TOAST_MAX_W))
1053 .h(px(LEDGER_H - 2.))
1054 .flex()
1055 .items_center()
1056 .overflow_hidden()
1057 .rounded(px(6.))
1058 .bg(rgb(t.e3))
1059 .border_1()
1060 .border_color(rgba(t.line_hi))
1061 .pl(px(8.))
1062 .child(glyph.el(crate::ui::icons::IconSize::Inline, tone_ink))
1063 .child(
1064 div()
1065 .id(SharedString::from(format!("stance-toast-text-{id}")))
1066 .flex_grow().flex_shrink()
1067 .min_w(px(0.))
1068 .px(px(8.))
1069 // Cut short in the strip, whole on hover.
1070 .tooltip(crate::ui::widgets::tip_hover(&toast.text, "", None))
1071 // Ellipsis, not a bare cut: the name inside the message is
1072 // elided through its middle first ([`ledger_line`]) so the
1073 // state word at the front is never what gets dropped. Clipped
1074 // at its own edge too, so the words never paint over the buttons.
1075 .truncate()
1076 .type_style(type_scale::caption())
1077 .text_color(rgb(t.ink1))
1078 .relative()
1079 .child(toast_words(&toast.text, text_box, cx))
1080 .child(toast_text_probe(text_box.clone())),
1081 )
1082 .children(toast.actions.iter().enumerate().map(|(index, action)| {
1083 let label = match action {
1084 ToastAction::Undo => "Undo",
1085 ToastAction::Play(_) => "Play",
1086 ToastAction::ShowInFolder(_) => "Show in folder",
1087 ToastAction::Unlock(_) => "Unlock",
1088 ToastAction::Reload => "Reload",
1089 ToastAction::KeepMine => "Keep mine",
1090 ToastAction::Recover => "Recover",
1091 ToastAction::Discard => "Discard",
1092 ToastAction::SaveThenOpen(_) => "Save",
1093 ToastAction::OpenDiscarding(_) => "Don't save",
1094 };
1095 ghost(label)
1096 .id(SharedString::from(format!(
1097 "stance-toast-action-{id}-{index}"
1098 )))
1099 .mx(px(6.))
1100 .on_click(
1101 cx.listener(move |this, _: &ClickEvent, _, cx| {
1102 this.toast_action(id, index, cx)
1103 }),
1104 )
1105 }))
1106 .child(
1107 div()
1108 .id(SharedString::from(format!("stance-toast-close-{id}")))
1109 .flex_none()
1110 .w(px(28.))
1111 .h_full()
1112 .flex()
1113 .items_center()
1114 .justify_center()
1115 .child(crate::ui::icons::Icon::X.el(crate::ui::icons::IconSize::Inline, t.ink3))
1116 .on_click(
1117 cx.listener(move |this, _: &ClickEvent, _, cx| this.dismiss_toast(id, cx)),
1118 ),
1119 )
1120}
1121
1122/// The clip readout the ledger's left side shows while a clip is selected
1123/// (DESIGN §6.9): the source's stem, the length in seconds, and where the clip
1124/// starts as a m:ss span. The transport already shows the timecode.
1125/// `city_dusk · 9.5 s · starts at 0:00`.
1126pub(crate) fn clip_readout(name: &str, start: u32, frames: u32, fps: f64) -> String {
1127 format!(
1128 "{name} · {:.1} s · starts at {}",
1129 f64::from(frames) / fps,
1130 bench_stance::mmss(f64::from(start) / fps),
1131 )
1132}
1133
1134/// A frame rate the way the status bar writes it: `30`, or `29.97` where the
1135/// rate is fractional.
1136/// `1920×1080 (1080p)`: the size with its common name when it has one, else just `W×H`.
1137pub(crate) fn size_label(w: u32, h: u32) -> String {
1138 let name = match (w, h) {
1139 (1280, 720) => Some("720p"),
1140 (1920, 1080) => Some("1080p"),
1141 (2560, 1440) => Some("1440p"),
1142 (3840, 2160) => Some("4K"),
1143 _ => None,
1144 };
1145 match name {
1146 Some(n) => format!("{w}×{h} ({n})"),
1147 None => format!("{w}×{h}"),
1148 }
1149}
1150
1151pub(crate) fn fps_label(fps: f64) -> String {
1152 format!("{fps:.2}")
1153 .trim_end_matches('0')
1154 .trim_end_matches('.')
1155 .to_string()
1156}
1157
1158/// The gap readout the ledger's left side shows while a gap is picked (DESIGN
1159/// §6.9): the hole's length in seconds and where it starts as a m:ss span.
1160/// `Gap · 2.4 s · starts at 0:04`.
1161pub(crate) fn gap_readout(start: u32, frames: u32, fps: f64) -> String {
1162 format!(
1163 "Gap · {:.1} s · starts at {}",
1164 f64::from(frames) / fps,
1165 bench_stance::mmss(f64::from(start) / fps),
1166 )
1167}
1168
1169/// The readout the ledger's left side shows while nothing is selected or
1170/// picked (DESIGN §6.9 left blank then; the audit asked for the film's own
1171/// length instead of nothing): the whole timeline's length as a m:ss span, and
1172/// how many clips make it up. `Timeline 1:50 · 20 clips`; an empty timeline says so.
1173pub(crate) fn project_readout(frames: u32, clips: usize, fps: f64) -> String {
1174 if clips == 0 {
1175 return "Empty timeline · drag media here to start".to_string();
1176 }
1177 format!(
1178 "Timeline {} · {clips} {}",
1179 bench_stance::mmss(f64::from(frames) / fps),
1180 if clips == 1 { "clip" } else { "clips" },
1181 )
1182}
1183
1184/// The width of the status bar's readout slot.
1185const READOUT_W: f32 = 300.;
1186/// The slot while a trim says what it is doing: `Trimming both sides · Start −0.5 s · End +0.5 s`.
1187const TRIM_LINE_W: f32 = 420.;
1188
1189/// Thin strip at the bottom of the centre column (DESIGN §6.9): the selected
1190/// clip or picked gap (else the timeline's length) and export progress on the left, the picture's format
1191/// and the two room verbs on the right. Project identity and save state live
1192/// in the menu bar. Notices rise from here (DESIGN §5, §8).
1193fn ledger(player: &Player, cx: &mut Context<Player>) -> impl IntoElement {
1194 let fps = player.active_fps();
1195 // A selected clip, else a picked gap. `Clip` is `Copy`, so the lookup
1196 // hands back the clip itself and not a borrow of the session. A subtitle
1197 // pick has no `Clip` and reads nothing here.
1198 let selected = player
1199 .session
1200 .as_ref()
1201 .zip(player.selected.anchor())
1202 .filter(|(_, (lane, _))| lane.kind != LaneKind::Subtitle)
1203 .and_then(|(s, (lane, idx))| s.lane_clips(lane).get(idx).cloned());
1204 // One toast at a time, in this strip: it takes the readout's place for as
1205 // long as it lives, so nothing is ever drawn over the timeline.
1206 let toast = crate::notices::current_toast(&player.notices).map(|t| toast_card(t, &player.toast_text, cx));
1207 // A trim in hand, or a roll armed, says what it is doing in this strip in place of the
1208 // selection's readout (and the pointer's hint), so the transport band never changes.
1209 let trimming = crate::ui::timeband_stance::trim_text(player).or_else(|| bench_stance::clip::trim_in_flight(player));
1210 let trimming_now = trimming.is_some();
1211 let readout = selected
1212 .map(|c| {
1213 let name = player
1214 .sources()
1215 .get(c.source)
1216 .map_or_else(|| "clip".to_string(), |s| stem(&s.path));
1217 clip_readout(&name, c.start, c.len(), fps)
1218 })
1219 .or_else(|| {
1220 player
1221 .gap_pick()
1222 .map(|g| gap_readout(g.start, g.frames, fps))
1223 })
1224 // Nothing selected: the film's own length and clip count, so the
1225 // strip never sits empty while a project is open.
1226 .or_else(|| {
1227 player.session.as_ref().map(|s| {
1228 let frames = (s.timeline_duration() * fps).round() as u32;
1229 let clips = s.lanes().iter().map(|&l| s.lane_clips(l).len()).sum();
1230 project_readout(frames, clips, fps)
1231 })
1232 });
1233 let readout = trimming.or(readout);
1234 // What the file actions have to say is no longer read here: it rises as
1235 // toasts above this strip (DESIGN §8), so the strip keeps
1236 // its readout, export progress and the room's verbs only.
1237 let export = player
1238 .exporting()
1239 .map(|h| match h.stage() {
1240 Some((name, f)) => format!("{name} {:.0}%", f * 100.),
1241 None => format!("Exporting {:.0}%", h.progress() * 100.),
1242 })
1243 .or_else(|| player.reframe_words())
1244 .or_else(|| player.mcam_words())
1245 .or_else(|| player.render_words());
1246 div()
1247 .id("stance-ledger")
1248 .flex_none()
1249 .h(px(LEDGER_H))
1250 .bg(rgb(crate::ui::theme::tokens().e1))
1251 .border_t_1()
1252 .border_color(rgba(crate::ui::theme::tokens().line))
1253 .flex()
1254 .items_center()
1255 .gap(px(14.))
1256 .px(px(12.))
1257 // The readout reads first, on the left: the same mono strip, so it is
1258 // a status and not a dialog.
1259 .children(toast)
1260 .children(readout.filter(|_| player.notices.is_empty()).map(|r| {
1261 div()
1262 .relative()
1263 .child(bounds_probe(player.ledger_readout.clone()))
1264 .flex_none()
1265 // A fixed slot: the readout changes with every selection, and what follows it
1266 // (the drag hint) must not move with it.
1267 .w(px(if trimming_now { TRIM_LINE_W } else { READOUT_W }))
1268 .truncate()
1269 .type_style(type_scale::caption())
1270 .text_color(rgb(INK2()))
1271 .child(r)
1272 }))
1273 .children(export.map(|e| {
1274 div()
1275 .flex_none()
1276 // `Exporting 5%` to `Exporting 100%`: held at the widest.
1277 .w(px(13. * bench_stance::char_w(type_scale::CHORD_METADATA_MIN_PX)))
1278 .whitespace_nowrap()
1279 .type_style(type_scale::caption())
1280 .text_color(rgb(INK2()))
1281 .child(e)
1282 }))
1283 // The pointer's drag hint, or the drag in flight and how far it has
1284 // gone (`bench_stance::clip::drag_status`): here, in the strip, so
1285 // nothing floats over the lanes to say it.
1286 .children((!trimming_now).then(|| bench_stance::clip::drag_status(player)).flatten().map(|h| {
1287 div()
1288 .flex_shrink()
1289 .min_w(px(0.))
1290 .truncate()
1291 .type_style(type_scale::caption())
1292 .text_color(rgb(INK2()))
1293 .child(h)
1294 }))
1295 .child(div().flex_1().min_w(px(0.)))
1296 // The dropped-frames words, at the right edge in a slot as wide as their longest
1297 // form: they come and go without moving anything else in the strip.
1298 .child(
1299 div()
1300 .flex_none()
1301 .w(px(40. * bench_stance::char_w(type_scale::CHORD_METADATA_MIN_PX)))
1302 .overflow_hidden()
1303 .whitespace_nowrap()
1304 .type_style(type_scale::caption())
1305 .text_color(rgb(INK2()))
1306 .child(player.dropped_words().unwrap_or_default()),
1307 )
1308}
1309
1310/// The dock: the only side panel, right, fixed width, carrying the Src/Clip
1311/// tab pair (DESIGN §5). The frame is drawn here; `dock_stance.rs` owns the
1312/// tab row and both tabs' content (DESIGN §12 step 4).
1313/// Width comes from [`Player::split_px`] now, not the fixed [`DOCK_W`]: the
1314/// seam [`crate::ui::stance::render`] mounts to its left is what answers
1315/// "ui fields are not stretchable" for the dock. `window_size` is threaded
1316/// through so the maximize-in-place cards inside the dock (`dock_stance.rs`)
1317/// see the real viewport rather than a fabricated `size(px(DOCK_W), h)`.
1318fn dock(
1319 player: &Player,
1320 dock_w: f32,
1321 window_size: Size<Pixels>,
1322 window: &mut Window,
1323 cx: &mut Context<Player>,
1324) -> impl IntoElement {
1325 // Either dock tab's handle counts: Sources and Clip are one region (§6.7).
1326 let focused = player.focus_dock.is_focused(window) || player.focus_inspector.is_focused(window);
1327 div()
1328 .id("stance-dock")
1329 // The library's own answer to a file dragged in from outside: the
1330 // same raised fill every other drop target in the darkroom lifts to
1331 // (DESIGN §8's affordance, no plate and no copy). The drop itself is
1332 // heard by the room root (`render`), which covers this panel too.
1333 .drag_over::<gpui::ExternalPaths>(|d, _, _, _| d.bg(rgb(DARK_RAISED())))
1334 .flex_none()
1335 .w(px(dock_w))
1336 .h_full()
1337 .bg(rgb(DARK_PANEL()))
1338 .border_l_1()
1339 .border_color(rgba(DARK_SEAM()))
1340 .flex()
1341 .flex_col()
1342 .child(dock_stance::render(player, dock_w, window_size, window, cx))
1343 // DESIGN §4.10: the focused region's top rule, laid over the panel's
1344 // first pixel row so no size moves.
1345 .when(focused, |el| el.child(focus_top_rule()))
1346}
1347
1348/// The 1px ink2 top rule that marks a focused region (DESIGN §4.10). Absolute,
1349/// so it paints over the region's top edge without taking space in its flow.
1350fn focus_top_rule() -> impl IntoElement {
1351 div()
1352 .absolute()
1353 .top_0()
1354 .left_0()
1355 .right_0()
1356 .h(px(1.))
1357 .bg(rgb(INK2()))
1358}
1359
1360/// A zero-size element whose only job is `window.on_mouse_event`'s door:
1361/// `Interactivity`'s fluent `on_mouse_*` builders (the ones `render`'s root
1362/// div uses for the drag itself, just below) have no `MouseExitEvent` case,
1363/// so this is the lowest rung that reaches it -- registered fresh every
1364/// frame, the same way `canvas()` is already used elsewhere in this crate
1365/// for paint-time access `div()` does not expose. See
1366/// [`Player::drag_left_window`] for why this event, and not a release, is
1367/// what a seam drag ending outside the window is saved on.
1368fn mouse_exit_listener(cx: &mut Context<Player>) -> impl IntoElement {
1369 let player = cx.entity();
1370 canvas(
1371 |_, _, _| (),
1372 move |_, _, window, _| {
1373 window.on_mouse_event(move |_: &MouseExitEvent, phase, _window, cx| {
1374 if phase == gpui::DispatchPhase::Bubble {
1375 player.update(cx, |this, cx| this.drag_left_window(cx));
1376 }
1377 });
1378 },
1379 )
1380 .absolute()
1381 .size(px(0.))
1382}
1383
1384/// The whole stance: screen, time band, bench, ledger, dock, in the
1385/// order DESIGN §5 draws them, over the same key handler the legacy tree
1386/// uses (DESIGN §12 step 3): the darkroom draws its own regions but answers
1387/// to the one keymap.
1388pub(crate) fn render(
1389 player: &mut Player,
1390 window: &mut Window,
1391 cx: &mut Context<Player>,
1392) -> impl IntoElement {
1393 // The window, and the room below the menu bar (DESIGN §6.1): the regions lay
1394 // out against the room; only the root's own floating cards take the window.
1395 let viewport = window.viewport_size();
1396 let window_size = size(viewport.width, viewport.height - px(MENU_BAR_H));
1397 // Dialogs: a fresh frame of tab stops, and the keyboard goes to the root whenever one opens
1398 // (whatever field or control held it before), so Esc/Enter/Tab are always heard.
1399 crate::ui::kit::tab_frame_reset();
1400 let pool = player.dlg_pool.clone();
1401 let dialog_up = player.dialog_up();
1402 if dialog_up != player.dlg_was_up {
1403 player.dlg_was_up = dialog_up;
1404 if dialog_up {
1405 window.focus(&player.focus);
1406 }
1407 }
1408 let position = player.playhead(player.drawn_duration());
1409 // The two seams a hand may drag (`Split::Dock`, `Split::Bench`): read
1410 // through the same door every legacy region measures itself by
1411 // ([`Player::split_px`]), so a dragged size and a drawn one cannot
1412 // disagree here either.
1413 let dock_w = player.split_px(Split::Dock, window_size);
1414 let bench_h = player.split_px(Split::Bench, window_size);
1415 // Player fullscreen (F11, `ActionId::Fullscreen`): the picture and the transport band only.
1416 // Only the children below change; the root keeps its handlers and focus.
1417 let fullscreen = player.player_fullscreen;
1418 div()
1419 .id("stance-room")
1420 // Inter is the default face for any text that sets no role of its own.
1421 .font_family(type_scale::INTER)
1422 .track_focus(&player.focus)
1423 // A press anywhere leaves a text field first; the field's own click then reopens it.
1424 .capture_any_mouse_down(cx.listener(|this, _: &MouseDownEvent, window, cx| {
1425 // A click puts the ring away: it is the keyboard's.
1426 crate::ui::kit::set_kbd_ring(false);
1427 if this.any_text_field() {
1428 this.blur_text_fields(window, cx);
1429 }
1430 }))
1431 .on_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| {
1432 let key = event.keystroke.key.as_str();
1433 let ctrl = event.keystroke.modifiers.control;
1434 let shift = event.keystroke.modifiers.shift;
1435 let alt = event.keystroke.modifiers.alt;
1436 if event.is_held
1437 && !repeats(this.repeat_scope(), key, this.keymap.lookup(key, ctrl, shift, alt))
1438 {
1439 return;
1440 }
1441 // Escape also cancels a clip drag in the air: a drag let go with no
1442 // target sends no release that clears its dimmed source, snap line
1443 // and shadow. Falls through, so escape still closes what it did.
1444 if key == ESCAPE {
1445 this.end_drag_preview(cx);
1446 }
1447 // Esc shuts an open menu-bar dropdown first (DESIGN §4.12).
1448 if this.menu_open.is_some() && key == "escape" {
1449 this.menu_open = None;
1450 cx.notify();
1451 return;
1452 }
1453 // The clip menu's Adjust submenu: Right opens it, Left closes it.
1454 if let (Some(m), "left" | "right") = (this.context_menu.as_mut(), key)
1455 && matches!(m.on, MenuOn::Clip(_))
1456 {
1457 m.sub = if key == "right" { Sub::Adjust } else { Sub::Closed };
1458 cx.notify();
1459 return;
1460 }
1461 // Every dialog: Tab walks its controls, a focused control keeps Enter and Space.
1462 if this.dialog_up() && this.dialog_nav_key(key, shift, window, cx) {
1463 return;
1464 }
1465 // The caption font list's search line takes the letters typed into it before the keymap.
1466 if this.sub_font_key(key, ctrl, alt, event.keystroke.key_char.as_deref(), cx) {
1467 return;
1468 }
1469 // An open kit dropdown list answers Up, Down and Enter before anything else.
1470 if !ctrl && !alt && crate::ui::kit::list_nav(key, window, cx) {
1471 cx.notify();
1472 return;
1473 }
1474 // The About dialog: Esc or Enter closes it, and it takes no other key.
1475 if this.about_open {
1476 if matches!(key, "escape" | "enter") {
1477 this.about_open = false;
1478 cx.notify();
1479 }
1480 return;
1481 }
1482 // Left and Right walk the open menus, wrapping at the ends.
1483 if let (Some(open), "left" | "right") = (this.menu_open, key) {
1484 let n = crate::ui::menubar::Title::ALL.len();
1485 let at = crate::ui::menubar::Title::ALL
1486 .iter()
1487 .position(|t| *t == open)
1488 .unwrap_or(0);
1489 let to = match key == "right" {
1490 true => (at + 1) % n,
1491 false => (at + n - 1) % n,
1492 };
1493 this.menu_open = Some(crate::ui::menubar::Title::ALL[to]);
1494 cx.notify();
1495 return;
1496 }
1497 // Go to time's field on the transport owns the keyboard while it is typed into.
1498 if this.time_edit.is_some() {
1499 this.time_edit_key(key, ctrl, alt, event.keystroke.key_char.as_deref(), cx);
1500 return;
1501 }
1502 // The File menu's project dialogs own the keyboard while one is up.
1503 if this.proj_dialog.is_some() {
1504 this.project_dialog_key(key, ctrl, alt, event.keystroke.key_char.as_deref(), cx);
1505 return;
1506 }
1507 // The unsaved-work question (user 2026-09-10: "if timeline is not
1508 // empty and user does alt+f4 or exit somehow, ask user to save the
1509 // file if it's not already saved"). Asked ahead of every branch
1510 // below because while the plate is up it owns the keyboard: three
1511 // answers and nothing else -- `↵` saves and goes, `d` goes without
1512 // saving, `esc` stays, any other key does nothing at all.
1513 if this.quit_ask {
1514 match key {
1515 // Nothing to save, only exports to lose: Enter keeps the window, never closes it.
1516 "enter" if !this.close_dirty() => {
1517 this.quit_ask = false;
1518 cx.notify();
1519 }
1520 "enter" => {
1521 // The Save action's own door, so the notice, the
1522 // sidecar cleanup and the dirty flag are the ones a
1523 // ctrl+s writes. The window goes only once the file is
1524 // written: a failed save says why and keeps the work.
1525 // corner-cut: the overwrite guard is Save's door (`Player::save_guarded`), not this plate's -- this save was already answered.
1526 if this.save_project(cx) {
1527 window.remove_window();
1528 }
1529 }
1530 "d" => {
1531 // Don't save: the edits' autosave goes too, so the next open
1532 // does not offer them back as recovery.
1533 if this.close_dirty() {
1534 this.discard_unsaved_edits();
1535 }
1536 this.queue.cancel_all();
1537 window.remove_window();
1538 }
1539 "escape" => {
1540 this.quit_ask = false;
1541 cx.notify();
1542 }
1543 _ => {}
1544 }
1545 return;
1546 }
1547 // A chord that is the app's, not text editing (Ctrl+K, Alt+T, Ctrl+Y ...), is never
1548 // eaten by a field: the field is left and the chord runs.
1549 if crate::player::blur::is_app_chord(key, ctrl, shift, alt) && this.any_text_field() {
1550 this.blur_text_fields(window, cx);
1551 }
1552 // The overwrite question (user 2026-09-11: saving over an
1553 // existing file must warn first, "same pattern as the exit
1554 // guard"). Raised only by Save's own door
1555 // ([`Player::save_guarded`]) -- the target exists on disk and
1556 // `autosave_armed` says this window never loaded or wrote it --
1557 // so the ledger's unsaved ghost routes through the same ask.
1558 // Same ownership as the plate above: two answers and nothing
1559 // else -- `↵` overwrites and saves, `esc` keeps the file, any
1560 // other key does nothing at all.
1561 if this.save_ask {
1562 match key {
1563 "enter" => {
1564 // The answer IS the confirmation, so this goes
1565 // straight to the unconditional write and never
1566 // back through the guard; [`Player::save_project`]
1567 // arms `autosave_armed`, making later ^s on this
1568 // file silent again.
1569 this.save_project(cx);
1570 this.save_ask = false;
1571 cx.notify();
1572 }
1573 "escape" => {
1574 this.save_ask = false;
1575 cx.notify();
1576 }
1577 _ => {}
1578 }
1579 return;
1580 }
1581 // The export's own overwrite question (user 2026-09-11: "not just
1582 // save but export too"), asked inside the export sheet with three
1583 // buttons. Its keys: `↵` replaces, `k` keeps both under a new
1584 // name, `esc` keeps the file and goes back to the sheet; any
1585 // other key does nothing at all ([`Player::answer_overwrite`]).
1586 if this.export_ask {
1587 match key {
1588 "enter" => this.answer_overwrite(Overwrite::Replace, cx),
1589 "k" => this.answer_overwrite(Overwrite::KeepBoth, cx),
1590 "escape" => this.answer_overwrite(Overwrite::Cancel, cx),
1591 _ => {}
1592 }
1593 return;
1594 }
1595 // Every open text field takes the keyboard here, in one place (`Player::text_field_key`):
1596 // a letter, Backspace, Ctrl+A, the arrows and Escape go into the field, and none of them
1597 // reaches the palette, the chords or the timeline. Only an app chord (Ctrl+K, Alt+T ...)
1598 // leaves the field, and then runs.
1599 if this.text_field_key(event, window, cx) {
1600 return;
1601 }
1602 // The command palette (DESIGN §4.4) owns the keyboard while it is
1603 // up: letters and digits go to its field, the arrows move the
1604 // highlight, enter runs the row. Ctrl+K again and escape both shut
1605 // it; nothing else reaches the keymap meanwhile.
1606 if crate::ui::gallery::is_open() {
1607 if key == "escape" {
1608 crate::ui::gallery::set_open(false);
1609 cx.notify();
1610 }
1611 return;
1612 }
1613 if this.palette_open {
1614 let toggles =
1615 this.keymap.lookup(key, ctrl, shift, alt) == Some(ActionId::ShowActions);
1616 match key {
1617 _ if toggles || key == "escape" => this.palette_open = false,
1618 "up" => this.palette_move(-1),
1619 "down" => this.palette_move(1),
1620 "enter" => this.palette_run(window, cx),
1621 "backspace" => {
1622 this.palette_query.pop();
1623 this.palette_sel = 0;
1624 this.palette_scroll.set_offset(point(px(0.), px(0.)));
1625 }
1626 _ => {
1627 if let Some(c) = typed(key).filter(|_| !ctrl) {
1628 this.palette_query.push(c);
1629 this.palette_sel = 0;
1630 this.palette_scroll.set_offset(point(px(0.), px(0.)));
1631 }
1632 }
1633 }
1634 cx.notify();
1635 return;
1636 }
1637 // DESIGN §10.2: `?` and F1 are the ShowKeys action, which swings the dock to its
1638 // KEYS tab and a second `?` swings it back -- no plate, no hold,
1639 // no modal cheat-sheet. Asked ahead of the modal guard below so
1640 // the stroke is heard whatever else is up, and toggling here
1641 // rather than latching is what makes the same key the way out.
1642 // `?` is shift+`/` on a US board, and a layout that reports the
1643 // unshifted key name still means the same stroke.
1644 if this.keymap.lookup(key, ctrl, shift, alt) == Some(ActionId::ShowKeys)
1645 || (key == "/" && shift && !ctrl && !alt)
1646 {
1647 match this.keys_open {
1648 true => this.keys_open = false,
1649 false => this.show_keys(cx),
1650 }
1651 cx.notify();
1652 return;
1653 }
1654 // The other way back to the tab underneath (the tab strip being
1655 // the third): only when no card is up, so escape still shuts a
1656 // card first -- the KEYS tab is a dock tab now, not an overlay,
1657 // and nothing about it owns the keyboard.
1658 if this.keys_open && !this.card_open() {
1659 if key == "escape" {
1660 if this.keys_filter.is_empty() {
1661 this.keys_open = false;
1662 } else {
1663 this.keys_filter.clear();
1664 }
1665 cx.notify();
1666 return;
1667 }
1668 if key == "backspace" {
1669 this.keys_filter.pop();
1670 cx.notify();
1671 return;
1672 }
1673 if let Some(c) = typed(key).filter(|_| !ctrl && !alt) {
1674 this.keys_filter.push(c);
1675 cx.notify();
1676 return;
1677 }
1678 }
1679 // The Media panel's own keys (DESIGN §4, §6.7): with the panel
1680 // focused and a row picked, Space previews it and `↵` adds it.
1681 // Ahead of the keymap, so Space's Play never sees the stroke
1682 // there; with nothing picked or a menu/card up, it falls through.
1683 let panel_focused = this.focus_inspector.is_focused(window);
1684 if !this.overlaid()
1685 && this.transcript_key(key, ctrl, shift, alt, panel_focused, cx)
1686 {
1687 return;
1688 }
1689 let media_focused = this.dock_src_active && this.focus_dock.is_focused(window);
1690 if !this.overlaid()
1691 && let Some(item) = dock_stance::media_key(
1692 key,
1693 event.keystroke.modifiers,
1694 media_focused,
1695 this.selected_asset.is_some(),
1696 )
1697 {
1698 this.act_on_picked_row(item, cx);
1699 return;
1700 }
1701 // `↵` adds the picked source at the playhead (MOCK-SPEC "Dock"
1702 // hint paragraph, gesture 2; `dock_stance.rs`'s own hint promised
1703 // this and nothing answered it -- FAULT 1). Live only where a row
1704 // is actually picked, so a bare enter elsewhere still means
1705 // whatever it means below. `insert_source` already refuses
1706 // visibly on its own ("Nothing added: ...") when the span is
1707 // occupied, so there is nothing further to paint here.
1708 if key == "enter"
1709 && this.dock_src_active
1710 && this.selected_asset.is_some()
1711 && this.exporting().is_none()
1712 {
1713 if let Some((path, stream)) = this.selected_asset.clone() {
1714 this.append_source(&path, stream, cx);
1715 }
1716 cx.notify();
1717 return;
1718 }
1719 // A card is not a key-eating black box. The room-wide chords that
1720 // act on the document rather than on the card -- the edit history,
1721 // the project file, the clipboard ([`card_safe_action`]) -- run
1722 // here, ahead of the cards' own key branches below and ahead of the
1723 // blanket modal guard under them, so an open card cannot swallow
1724 // the stroke a hand reaches for while looking at what it changed.
1725 // `param_card_key` answers `true` for every stroke once a card is
1726 // open, so this has to stand in front of *it*, not only in front of
1727 // the guard: `ctrl+z` never reached `keymap.lookup` at all, and the
1728 // card's own comment says undo was always meant to be undo's key.
1729 //
1730 // Asked through the keymap rather than as a table of key literals:
1731 // a rebind moves the chord and this follows.
1732 if let Some(action) = this.keymap.lookup(key, ctrl, shift, alt)
1733 && card_safe_action(action)
1734 {
1735 this.act(action, window, cx);
1736 return;
1737 }
1738 // A docked card is not a modal: the transport and the room's own
1739 // doors answer while it shows ([`docked_card_safe_action`]).
1740 if this.docked_card_only()
1741 && let Some(action) = this.keymap.lookup(key, ctrl, shift, alt)
1742 && (docked_card_safe_action(action)
1743 || docked_card_ignores(key, ctrl, shift, alt))
1744 {
1745 this.act(action, window, cx);
1746 return;
1747 }
1748 // The Export tab is a tab, not a sheet: the range it exports is marked on the
1749 // timeline with I and O, so those strokes (and the transport's) still answer.
1750 if this.export_open
1751 && this.exporting().is_none()
1752 && !this.export_ask
1753 && this.context_menu.is_none()
1754 && this.library_menu.is_none()
1755 && this.picker.is_none()
1756 && let Some(action) = this.keymap.lookup(key, ctrl, shift, alt)
1757 && export_tab_action(action)
1758 {
1759 this.act(action, window, cx);
1760 return;
1761 }
1762 // An open dropdown list: up and down move its highlighted row, enter picks it, escape
1763 // (above) closes only the list; any other key still closes it.
1764 if let Some(pk) = this.picker
1765 && !ctrl
1766 && !alt
1767 && matches!(key, "up" | "down" | "enter")
1768 && this.context_menu.is_none()
1769 && this.library_menu.is_none()
1770 {
1771 let rows = this.choices(pk.of);
1772 let live: Vec<usize> = (0..rows.len()).filter(|&n| this.export_choice_refusal(rows[n].0).is_none()).collect();
1773 if let Some(at) = live.iter().position(|&n| n == pk.sel).or((!live.is_empty()).then_some(0)) {
1774 match key {
1775 "enter" => this.choose(rows[live[at]].0, cx),
1776 _ => {
1777 let to = crate::ui::choice::step(live.len(), at, key == "down");
1778 if let Some(p) = this.picker.as_mut() {
1779 p.sel = live[to];
1780 }
1781 cx.notify();
1782 }
1783 }
1784 return;
1785 }
1786 }
1787 // The param cards' own key branches (arrows nudge the focused
1788 // slider, digits pick an EQ band, `r` resets, card verbs) --
1789 // `Player::param_card_key` (`player/cards.rs`), the same
1790 // function `render.rs`'s legacy handler now calls too, so this
1791 // is not a second copy of that logic (DESIGN §6: "drag while
1792 // playing... `r` resets"). Asked before the generic modal guard
1793 // below so a card open in the darkroom is not just a key-eating
1794 // black box the way the old uniform guard made it.
1795 if this.param_card_key(key, event.keystroke.modifiers.shift, cx) {
1796 cx.notify();
1797 return;
1798 }
1799 // One rule: a docked card eats only the strokes it reads
1800 // (`param_card_key` above answered `false` for this one); every
1801 // other stroke belongs to the room's keymap. Only a sheet that
1802 // covers the room, or a menu, blocks the keymap outright.
1803 if this.docked_card_only()
1804 && this.context_menu.is_none()
1805 && this.library_menu.is_none()
1806 && this.picker.is_none()
1807 {
1808 let hit = this.keymap.lookup(key, ctrl, shift, alt);
1809 if let Some(action) = hit {
1810 this.act(action, window, cx);
1811 }
1812 return;
1813 }
1814 // Same modal guard the legacy handler's keys_open/export_open/
1815 // colour/transform/speed/EQ/silence/mix/subtitle-style/menu
1816 // chain (`render.rs`) amounts to, read as one bool instead of
1817 // re-copied field by field: while a card or a menu owns the
1818 // keyboard, the darkroom stance yields to it exactly as the
1819 // legacy tree does. This is the fix for the stance's
1820 // `Home`-inside-the-Colour-card misfire.
1821 //
1822 // `exporting()` alone is deliberately left out of this list
1823 // (`Player::card_open` is `modal()` minus it): a running export
1824 // draws no card of its own to own the keyboard for, and a key
1825 // caught here never reaches `enable()`/`act()` below, so a
1826 // refusal the oracle would have spoken (`ActionId::Settings`
1827 // among them) never got said -- the room went silent instead.
1828 // Letting an export-only moment fall through costs nothing this
1829 // guard exists for: every action the oracle would still refuse
1830 // during an export says so through `act()`'s own `Enable::No`
1831 // branch, and the six it leaves live (Theme, Fullscreen,
1832 // SubtitleStyle, CancelExport, ...) are exactly the ones meant
1833 // to keep working.
1834 if this.card_open()
1835 || this.context_menu.is_some()
1836 || this.cue_menu.is_some()
1837 || this.library_menu.is_some()
1838 || this.picker.is_some()
1839 {
1840 // Escape is every card's own way out (`Player::close_card`,
1841 // the same list `overlaid`/`modal` read) -- blocking every
1842 // key while a card is open must not also lock the card open.
1843 // `escape_closes_overlay` (`player/cards.rs`) is the same
1844 // call a focus surface's own escape branch makes first, so
1845 // this and that never disagree on what escape closes.
1846 if key == ESCAPE {
1847 this.escape_closes_overlay(cx);
1848 return;
1849 }
1850 // FAULT 2, general shape: `context_menu`/`library_menu`/
1851 // `picker` are three of the four reasons `overlaid()` refuses
1852 // every key, and none of the three is in `close_card`'s own
1853 // list (`modal()` never counted them) -- left uncleared, any
1854 // one of them left the room an invisible, permanent modal
1855 // that only escape even tried to leave, and closed nothing.
1856 // Any key answers a menu, the same rule the legacy tree's own
1857 // clip_menu/row_menu/list chain follows (`render.rs`): this is
1858 // the fix for "no state may make the room modal without
1859 // showing anything", not only the source-dot's menu.
1860 //
1861 // Except the document chords, which were answered *above* and
1862 // left the menu standing: a menu is a visible surface with
1863 // escape and any other key still shutting it, and losing an
1864 // undo to a square of the screen a right-click left open would
1865 // be the black box this handler no longer is.
1866 this.context_menu = None;
1867 this.cue_menu = None;
1868 this.library_menu = None;
1869 this.picker = None;
1870 cx.notify();
1871 return;
1872 }
1873 // The innermost thing left once no menu or card is up: a preview
1874 // takes the picture over the screen, and escape is its own way
1875 // out -- the chord `preview.rs`'s "Stop (esc)" bar already
1876 // advertised, dead until now (FAULT 3) because only the legacy
1877 // tree's handler answered it.
1878 if key == ESCAPE && !ctrl && this.preview_session.is_some() {
1879 this.close_preview(cx);
1880 return;
1881 }
1882 if key == ESCAPE && !ctrl && this.source_hint {
1883 this.source_hint = false;
1884 cx.notify();
1885 return;
1886 }
1887 // Escape is Deselect, which an export refuses; said here with the
1888 // chord that does cancel, so a press during an export is never a
1889 // silent no-op that could be mistaken for a cancel.
1890 if key == ESCAPE && !ctrl && this.exporting().is_some() {
1891 let cancel = this.keymap.chord(ActionId::CancelExport);
1892 this.notify_user(
1893 format!("Esc keeps the export running. {cancel} cancels it.").into(),
1894 );
1895 cx.notify();
1896 return;
1897 }
1898 if let Some(action) = this.keymap.lookup(key, ctrl, shift, alt) {
1899 // `ActionId::Export` used to be suppressed here because the
1900 // darkroom drew no export surface for the card to land on
1901 // (DESIGN §12 step 7's own hook). It has one now
1902 // ([`timeband_stance::export_chip`] opens it, `render`
1903 // below mounts [`Player::export_card`]
1904 // exactly where the legacy tree does), so `^e` dispatches
1905 // like every other action.
1906 this.act(action, window, cx);
1907 }
1908 }))
1909 // The seam drag is tracked on the root, same reason the legacy
1910 // ruler-scrub is (render.rs): the pointer outruns the 6px divider
1911 // hitbox on the first move, so only the whole-window root keeps
1912 // hearing it once a `Split::Dock`/`Split::Bench` drag has started.
1913 // A file dropped from outside the window (gpui's `ExternalPaths`,
1914 // Wayland's `text/uri-list`) lands on the room itself, not on the
1915 // centre column: the dock's Sources panel is the centre's flex
1916 // sibling, so a handler mounted there heard no drop
1917 // over the library at all -- the shipped "drag and drop import does
1918 // not work on the library panel" defect. Here it is the one surface
1919 // under every region, so a drop anywhere in the darkroom is heard.
1920 // No prior press starts this -- the drop itself arrives as a
1921 // `MouseUp` (gpui `window.rs`).
1922 .on_drop(cx.listener(|this, paths: &gpui::ExternalPaths, _, cx| {
1923 // `Player::import` is the one door a project or media path
1924 // already goes through (argv, the Import button, Paste path) --
1925 // it forks on `.edith` vs everything else itself (`arrival`) and
1926 // already refuses during an export, so a drop names nothing this
1927 // loop has to.
1928 for path in paths.paths() {
1929 this.import(path, cx);
1930 }
1931 }))
1932 .on_mouse_move(cx.listener(Player::drag_move))
1933 // A press off the cue editor's plate commits the words in it (the
1934 // plate stops its own presses), so the words are not lost to a click.
1935 .on_mouse_down(
1936 MouseButton::Left,
1937 cx.listener(Player::cue_edit_press_outside),
1938 )
1939 .on_mouse_up(MouseButton::Left, cx.listener(Player::drag_release))
1940 .size_full()
1941 // The menu bar is laid over the top rows (`menubar::bar`, absolute), so
1942 // the room starts below it.
1943 .pt(px(if fullscreen { 0. } else { MENU_BAR_H }))
1944 .flex()
1945 .bg(rgb(if fullscreen { 0x000000 } else { DARK_CANVAS() }))
1946 .children(hitmap::frame())
1947 .child(mouse_exit_listener(cx))
1948 .child(
1949 div()
1950 .id("stance-centre")
1951 // Same drag affordance the dock lifts to, on the other half
1952 // of the room: the drop is heard by the root above, this
1953 // only says where the file will land.
1954 .drag_over::<gpui::ExternalPaths>(|d, _, _, _| d.bg(rgb(DARK_RAISED())))
1955 .relative()
1956 .flex_1()
1957 .min_w(px(0.))
1958 .flex()
1959 .flex_col()
1960 // Fullscreen stands the picture up alone (the same builder the
1961 // darkroom's screen uses), with the time band under it.
1962 .when(fullscreen, |el| el.child(player.picture_area(position, window, cx)))
1963 .when(!fullscreen, |el| el.child(screen(player, position, window, cx)))
1964 .child(time_band(player, position, cx))
1965 .when(!fullscreen, |el| {
1966 el.child(divider(
1967 Split::Bench,
1968 player.split_drag == Some(Split::Bench),
1969 cx,
1970 ))
1971 .child(bench(player, bench_h, window, cx))
1972 .child(ledger(player, cx))
1973 })
1974 // A maximized clip param card (EQ/Colour/Transform/Speed/
1975 // Silence/Mix/Subtitle style) escapes the dock to mount here
1976 // instead, the same window-space `stance-centre` context
1977 // every card above already renders in -- `below_picture_floor`
1978 // is a window coordinate, and `dock_stance.rs`'s
1979 // "dock-clip-rows" is a ~280-390px strip whose own box is the
1980 // containing block for anything absolutely positioned inside
1981 // it, `.relative()` or not, so a card asking for the room
1982 // below the picture cannot get it there. Un-maximized, the
1983 // same seven functions stay mounted in the dock
1984 // (`dock_stance::clip_tab`'s own `.when(!card_maximized, ...)`
1985 // guard keeps this from ever double-mounting one).
1986 .when(player.card_maximized && !fullscreen, |el| {
1987 el.children(player.eq_card(window_size, cx))
1988 .children(player.color_card(window_size, cx))
1989 .children(player.transform_card(window_size, cx))
1990 .children(player.speed_card(window_size, cx))
1991 .children(player.effects_card(window_size, cx))
1992 .children(player.silence_card(window_size, cx))
1993 .children(player.beats_card(window_size, cx))
1994 .children(player.mix_card(window_size, cx))
1995 .children(player.markers_card(window_size, cx))
1996 .children(player.history_card(window_size, cx))
1997 .children(player.tools_card(window_size, cx))
1998 .children(player.subtitle_style_card(window_size, cx))
1999 }),
2000 )
2001 .when(!fullscreen, |el| {
2002 el.child(divider(
2003 Split::Dock,
2004 player.split_drag == Some(Split::Dock),
2005 cx,
2006 ))
2007 .child(dock(player, dock_w, window_size, window, cx))
2008 })
2009 // All three hanging menus (DESIGN §9: "verbs of the thing under the
2010 // cursor") mount on the ROOT, and none of them inside
2011 // `stance-centre`. Their anchors are *window* coordinates -- a
2012 // `MouseDownEvent::position` -- while an absolutely placed child of
2013 // the centre column is laid out from that column's own origin and
2014 // ends where it ends: the rail that used to stand left of the centre
2015 // shifted every clip menu right by its own 56px, and the dock,
2016 // painted after the centre, covered every
2017 // pixel past x = width - dock. That is the shipped "can not remove a
2018 // media from library" defect (the library plate was built, placed and
2019 // never visible) and the clip menu whose chords were cut off mid-word
2020 // at the dock seam. Mounted here they paint last, over the dock they
2021 // may overlap, and `menu_floor`/`menu_at`'s window coordinates finally
2022 // mean what they say. Order is `render.rs`'s -- clip menu, library
2023 // menu, then the open list last so it floats over whichever row set it.
2024 // The menu bar sits over the room's top edge and its click-away under
2025 // the root's own menus; its dropdown is deferred, so it paints over both.
2026 .when(!fullscreen, |el| {
2027 el.child(menubar::bar(player, f32::from(viewport.width), f32::from(viewport.height), cx))
2028 .children(menubar::backdrop(player, cx))
2029 })
2030 .children(player.context_card(viewport, cx))
2031 .children(player.library_card(viewport, cx))
2032 .children(player.picker_card(viewport, cx))
2033 .children(player.settings_open.then(|| crate::ui::kit::tab_scope(&pool, || settings_stance::render(player, window_size, cx))))
2034 .children(crate::ui::kit::tab_scope(&pool, || player.about_card(window_size, cx)))
2035 .children(crate::ui::kit::tab_scope(&pool, || player.project_dialog_card(window_size, cx)))
2036 // The command palette is the last thing painted: it floats over every
2037 // card and menu above (DESIGN §4.4).
2038 .children(player.command_palette(window_size, cx))
2039 // The component gallery (a debug page for the design kit) covers it all.
2040 .children(crate::ui::gallery::overlay(cx))
2041}