forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB0563cbfTahinli2 months ago824 commits

layout.rs3765 lines, 158.0 KiBHistoryRawDownload
1//! What is drawn and where: the toolbar, the theme, the notices, the lanes
2//! and their marks, the tints, the subtitle rows and the sliders.
3
4use super::*;
5
6/// The class the user reported twice in one day ("some menus are belongs to
7/// old ui ... for example resolution picker", then "right click menu in
8/// library is old too"): a surface that paints a *role* token
9/// (`BG_HOVER`/`BG_SELECTED`/`BG_RAISED`) rather than a Darkroom token used
10/// to get the legacy tree's pale greys, because the Darkroom palette still
11/// carried them. Dozens of call sites read those three roles; the fix is the
12/// palette, and this pins it: every interaction grey in the Darkroom palette
13/// stays inside DESIGN §2's `raised` band (#14171B - #17191D), with only the
14/// picked-row fill allowed one step past it, and each stays distinguishable
15/// from the one below it so a hover is still visible on a resting row.
16#[test]
17fn the_darkroom_palettes_interaction_greys_stay_inside_the_raised_band() {
18 use crate::ui::theme::darkroom;
19 let grey = |v: u32| (v >> 16 & 0xff, v >> 8 & 0xff, v & 0xff);
20 let lum = |v: u32| {
21 let (r, g, b) = grey(v);
22 u32::from(r) + u32::from(g) + u32::from(b)
23 };
24 let band_low = lum(0x14171b);
25 let band_high = lum(0x17191d);
26 for (name, value) in [
27 ("BG_RAISED", darkroom::BG_RAISED),
28 ("BG_HOVER", darkroom::BG_HOVER),
29 ] {
30 assert!(
31 (band_low..=band_high).contains(&lum(value)),
32 "darkroom::{name} = {value:#08x} is outside DESIGN §2's raised band \
33 -- every menu, card and row that paints this role would open a \
34 pale plate in a dim room"
35 );
36 }
37 assert!(
38 lum(darkroom::BG_SELECTED) > lum(darkroom::BG_HOVER)
39 && lum(darkroom::BG_SELECTED) <= lum(0x1c1f24),
40 "the picked-row fill is one step past hover at most; the real mark is \
41 the 1px ink1 ring (DESIGN §4)"
42 );
43 assert!(
44 lum(darkroom::BG_HOVER) > lum(darkroom::BG_RAISED),
45 "hover must be a step ABOVE the resting raised fill or a hovered row \
46 cannot be seen at all"
47 );
48 assert!(
49 lum(darkroom::BG_HOVER_DIM) < lum(darkroom::BG_RAISED),
50 "the dim hover is the step below, not above"
51 );
52}
53
54/// The whole reason `ui/theme.rs` exists: a colour written anywhere else is
55/// a colour the next palette sweep will miss, which is exactly how 186 grey
56/// calls survived every previous attempt at this.
57#[test]
58fn no_colour_is_written_outside_the_theme() {
59 let source = ui_source();
60 let stray: Vec<&str> = source
61 .lines()
62 .filter(|l| l.contains("rgb(0x") || l.contains("rgba(0x"))
63 .collect();
64 assert!(
65 stray.is_empty(),
66 "colour written outside the theme: {stray:?}"
67 );
68}
69
70/// The literal-grep above is blind to a hue arriving through a theme
71/// *constant*: `DARK_SEAM` carried `rgba(0,0,0,.7)` (`0xRRGGBBAA`) into
72/// `rgb()`, which reads the alpha byte as blue -- 2436 blue pixels in a
73/// darkroom screenshot, on a call site that never once wrote `0x` itself.
74/// So this scan reads the theme's own encoding: every constant whose low
75/// byte is not `ff` (i.e. `0xRRGGBBAA` with a real alpha) is alpha-carrying,
76/// and an alpha-carrying role may only ever be handed to `rgba(`, never
77/// `rgb(`.
78#[test]
79fn an_alpha_carrying_role_never_reaches_rgb() {
80 let theme = src_text("ui/theme.rs");
81 let alpha_roles: Vec<&str> = theme
82 .lines()
83 .filter_map(|l| {
84 let l = l.trim();
85 let l = l.strip_prefix("pub const ")?;
86 let (name, rest) = l.split_once(':')?;
87 let hex = rest.trim().strip_prefix("u32 = 0x")?;
88 let hex = hex.trim_end_matches(';');
89 (hex.len() == 8 && !hex.ends_with("ff")).then_some(name.trim())
90 })
91 .collect();
92 assert!(
93 alpha_roles.len() >= 8,
94 "the theme's alpha-carrying roles moved; this scan is blind"
95 );
96
97 let source = ui_source();
98 let mut misuses = Vec::new();
99 for role in &alpha_roles {
100 if source.contains(&format!("rgb({role}(")) {
101 misuses.push(*role);
102 }
103 }
104 assert!(
105 misuses.is_empty(),
106 "alpha-carrying role(s) reaching rgb() instead of rgba(): {misuses:?}"
107 );
108}
109
110/// "It scrolls" is not "it can be found": at the 640x360 floor the timeline
111/// takes its share and no more, so a third track is behind a scroll -- and
112/// the line that says so has to keep telling the truth *while* the column is
113/// being scrolled, or it is an instruction nobody can carry out.
114#[test]
115fn the_line_about_what_is_below_the_fold_counts_what_is_still_below_it() {
116 // The timeline is a region and not the window: its chrome -- the
117 // scrollbar strip's row included, which is the larger of the two the
118 // zoom can leave in it -- and one whole lane fit the share it may take
119 // at the floor.
120 let floor = 360. * TIMELINE_SHARE;
121 assert!(
122 timeline_fixed_h(true) + LANE_H <= floor,
123 "{} px of chrome and a lane will not fit {floor} px",
124 timeline_fixed_h(true)
125 );
126 // The inspector's rows are not one height, so its own line is measured
127 // in pixels off the scroll instead: gpui keeps the offset negative going
128 // down, and at the bottom the two cancel out exactly.
129 assert_eq!(px_below(120., 0.), 120.);
130 assert_eq!(px_below(120., -40.), 80.);
131 assert_eq!(px_below(120., -120.), 0.);
132 assert_eq!(px_below(0., 0.), 0.);
133}
134
135/// The failure a user never learns about is the one that was answered by
136/// another failure: two imports failing back to back are two messages, in
137/// the order they happened, and the second does not overwrite the first
138/// before a frame has drawn it.
139#[test]
140fn a_second_message_queues_behind_the_first_instead_of_erasing_it() {
141 let mut q = std::collections::VecDeque::new();
142 push_notice(&mut q, "NOTHING ADDED — no video stream".into());
143 push_notice(&mut q, "NOTHING ADDED — the file is not there".into());
144 assert_eq!(q.len(), 2);
145 assert_eq!(
146 q.front().map(|n: &gpui::SharedString| n.as_ref()),
147 Some("NOTHING ADDED — no video stream")
148 );
149
150 // A held key that refuses says its one sentence once: the count on the
151 // bar is a count of messages, not of how long the key was held.
152 push_notice(&mut q, "NOTHING ADDED — the file is not there".into());
153 assert_eq!(q.len(), 2);
154
155 // ...and the ceiling drops the oldest rather than the newest: the thing
156 // that just happened is the thing worth reading.
157 for i in 0..NOTICES_MAX + 3 {
158 push_notice(&mut q, format!("SCAN FAILED: {i}").into());
159 }
160 assert_eq!(q.len(), NOTICES_MAX);
161 assert_eq!(
162 q.back().map(|n: &gpui::SharedString| n.as_ref()),
163 Some("SCAN FAILED: 10")
164 );
165
166 // Answering the bar brings the next one up, oldest first.
167 let front = q.pop_front();
168 assert_ne!(front, q.front().cloned());
169}
170
171/// An export's own outcome is what a person started it to read, so it must
172/// never sit behind two progress lines queued while it ran: it jumps to the
173/// front and is the one showing the moment it arrives.
174#[test]
175fn an_export_outcome_jumps_the_queue() {
176 let mut q = std::collections::VecDeque::new();
177 push_notice(
178 &mut q,
179 "PROXY READY for a.mp4 — Proxies on cuts on it".into(),
180 );
181 push_notice(&mut q, "SUBTITLES b.srt — 1 track(s) in the palette".into());
182 push_notice(&mut q, format!("{EXPORT_DONE}out.mp4").into());
183 assert_eq!(q.len(), 3);
184 assert_eq!(
185 q.front().map(|n: &gpui::SharedString| n.as_ref()),
186 Some(format!("{EXPORT_DONE}out.mp4")).as_deref(),
187 "the export's result must be the notice showing, not third in line"
188 );
189
190 // A failed export is the same class: the outcome, whichever it was.
191 let mut q = std::collections::VecDeque::new();
192 push_notice(
193 &mut q,
194 "PROXY READY for a.mp4 — Proxies on cuts on it".into(),
195 );
196 push_notice(&mut q, "EXPORT FAILED: disk full".into());
197 assert_eq!(
198 q.front().map(|n: &gpui::SharedString| n.as_ref()),
199 Some("EXPORT FAILED: disk full")
200 );
201}
202
203/// The bar colours itself off the words the message already opens with, so
204/// the tone cannot disagree with the sentence it labels.
205#[test]
206fn a_message_wears_the_colour_its_own_words_say() {
207 assert_eq!(notice_tone("SCAN FAILED: no audio"), STATUS_ERROR());
208 assert_eq!(
209 notice_tone(&format!("{EXPORT_DONE}out.mp4")),
210 STATUS_SUCCESS()
211 );
212 assert_eq!(
213 notice_tone("NOTHING DETACHED — not grouped"),
214 STATUS_WARNING()
215 );
216 assert_eq!(notice_tone("SNAP ON"), ACCENT_PRIMARY());
217}
218
219/// The cards are sections of the inspector, not sheets over the timeline:
220/// adjusting a clip must never hide the clip. Structural, because that is
221/// where the rule lives -- a card rendered from the root again would be an
222/// overlay again, whatever it looked like on the day it was written.
223#[test]
224fn an_inspector_section_occludes_no_timeline() {
225 // Whichever file the root render has come to live in, from the impl to the
226 // end of it -- found rather than named, so moving the root does not quietly
227 // leave this rule reading a file the render is no longer in.
228 let render = source_from("impl Render for Player");
229 let dock = src_text("ui/dock_stance.rs");
230 let stance = src_text("ui/stance.rs");
231 for card in [
232 "eq_card",
233 "color_card",
234 "speed_card",
235 "silence_card",
236 "mix_card",
237 "subtitle_style_card",
238 ] {
239 // Docked (unmaximized), the card is a section of the dock's own
240 // narrow column; maximized, it escapes to `stance-centre`'s window-
241 // space positioning context instead -- either way it is mounted
242 // through the darkroom's own structure, never straight off the
243 // root render.
244 assert!(
245 dock.contains(&format!("player.{card}("))
246 || stance.contains(&format!("player.{card}(")),
247 "{card} is not mounted anywhere in the darkroom"
248 );
249 assert!(
250 !render.contains(&format!("self.{card}(")),
251 "{card} is drawn from the root again -- it is an overlay over the timeline"
252 );
253 }
254 // The docked cards are placed against the dock's own box, and the
255 // maximized escape against `stance-centre` -- both positioning contexts,
256 // which is what turns `scrim()` (`absolute().inset_0()`) from a
257 // window-wide sheet into a contained one.
258 assert!(
259 stance.contains(".relative()"),
260 "the darkroom has no positioning context: its cards would cover the window"
261 );
262}
263
264#[test]
265fn a_stateful_button_keeps_its_rect() {
266 // A toggle's own state must never gate whether the button exists --
267 // only how it looks. Flip the state and the pointer's target (the
268 // element the hitmap id names, and the rect a click lands on) is
269 // unchanged; only the label and the `active` styling read the flag.
270 // "eq-spectrum" and "export-cancel" are the darkroom's own stateful
271 // toggles: the first flips `self.eq_spectrum`, the second reads
272 // `armed` (whether cancel is armed), and neither may gate its own
273 // button out of the tree.
274 let cards = src_text("ui/cards.rs");
275 for (id, flag) in [
276 ("\"eq-spectrum\"", "self.eq_spectrum"),
277 ("\"export-cancel\"", "armed"),
278 ] {
279 let at = cards.find(id).unwrap_or_else(|| panic!("no {id} button"));
280 let before = &cards[at.saturating_sub(350)..at];
281 assert!(
282 !before.contains(&format!(".when({flag}"))
283 && !before.contains(&format!(".when(!{flag}")),
284 "{id} is gated on the very flag it flips -- its rect would move when the state does"
285 );
286 }
287}
288
289#[test]
290fn nothing_clickable_is_smaller_than_the_wcag_minimum() {
291 // Every hit target in the panel, including the scrub strip -- whose bar
292 // is 6 px to look at and whose click area must not be.
293 assert!(CONTROL_H >= HIT_MIN);
294 assert!(RULER_HIT_H >= HIT_MIN);
295 assert!(LANE_H >= HIT_MIN);
296 // A clip box is a hit target too, and its two trim strips occlude it:
297 // on a box narrower than the pair there is no body left to press, so
298 // the clip cannot be selected, dragged or menued at all -- which is
299 // every clip a jumpcut leaves at a normal zoom. Below three handles
300 // there are no strips.
301 assert!(!trims(0.));
302 assert!(!trims(EDGE_W));
303 assert!(!trims(2. * EDGE_W), "a box that is all handle and no clip");
304 assert!(!trims(3. * EDGE_W - 0.1));
305 // And where they are drawn, what is left between them is a hit target
306 // in its own right -- a whole handle's width of clip.
307 for width in [3. * EDGE_W, 24., 100., 4000.] {
308 assert!(trims(width));
309 assert!(
310 width - 2. * EDGE_W >= EDGE_W,
311 "{width} px of box leaves no middle"
312 );
313 }
314}
315
316#[test]
317fn a_lane_row_is_a_fixed_header_and_a_bed_that_can_be_hit() {
318 // Two lanes, a ruler, a button row and the timecode line, inside the
319 // panel the window is sized for.
320 assert!(
321 CONTROL_H + RULER_HIT_H + 2. * LANE_H + 17. + 4. * 8. + 16. <= PANEL_H,
322 "the second lane does not fit the panel"
323 );
324 // Headers and clip boxes are as tall as the lane, and the lane is a
325 // click target (WCAG 2.5.8).
326 assert!(LANE_H >= HIT_MIN);
327 // A label row that ate the whole lane would leave no waveform.
328 assert!(LABEL_H < LANE_H / 2.);
329 // An added track adds its own row to the panel, and the two a project
330 // starts with leave it exactly the height it has always been.
331 assert_eq!(panel_h(2), PANEL_H);
332 assert_eq!(panel_h(1), PANEL_H);
333 assert_eq!(panel_h(3), PANEL_H + LANE_H + 8.);
334 assert_eq!(
335 panel_h(LANES_MAX),
336 PANEL_H + lanes_h(LANES_MAX) - lanes_h(2)
337 );
338 // Past the cap the column scrolls instead: the panel stops growing, so
339 // no number of tracks can push the picture off the window.
340 assert_eq!(panel_h(LANES_MAX + 1), panel_h(LANES_MAX));
341 assert_eq!(panel_h(50), panel_h(LANES_MAX));
342 assert_eq!(lanes_h(0), 0.);
343 assert_eq!(lanes_h(1), LANE_H);
344 assert_eq!(lanes_h(2), 2. * LANE_H + 8.);
345}
346
347/// The strip's row is furniture only while there is somewhere to scroll to:
348/// zoomed out to the whole timeline the strip is not drawn and neither is its
349/// height -- out of every budget at once (the region, the box the lanes are
350/// laid out against, and the seam's floor), or the lanes would gain or lose a
351/// strip's row at the zoom boundary without the strip to show for it.
352#[test]
353fn the_scroll_strip_row_comes_and_goes_with_the_zoom() {
354 use crate::{SCROLL_HIT, Split, lanes_h, split_size, timeline_fixed_h, timeline_h};
355 use gpui::{px, size};
356
357 // The strip's row, and only the strip's row, is what the two faces differ
358 // by -- the gap above it and its own hit height.
359 assert_eq!(
360 timeline_fixed_h(true) - timeline_fixed_h(false),
361 8. + SCROLL_HIT
362 );
363 let window = size(px(1280.), px(720.));
364 for scroll in [false, true] {
365 // Whatever the strip is doing, the lanes keep exactly the room they
366 // had: the region grows by the strip's row when it appears, by
367 // exactly the row the lanes would otherwise lose to it.
368 assert_eq!(timeline_h(2, scroll) - timeline_fixed_h(scroll), lanes_h(2));
369 assert_eq!(timeline_h(6, scroll) - timeline_fixed_h(scroll), lanes_h(6));
370 // ...and the floor keeps a whole lane standing under the line, on
371 // either face of the zoom boundary.
372 let floor = split_size(Split::Timeline, Some(0.), 2, window, scroll);
373 let box_h = floor - timeline_fixed_h(scroll);
374 assert!(box_h < lanes_h(2), "no line to pay for at the floor");
375 assert!(
376 box_h - LABEL_H - 8. >= LANE_H,
377 "the floor leaves {} px for a {LANE_H} px lane",
378 box_h - LABEL_H - 8.
379 );
380 // The two floors land the lanes in the same place: whichever face
381 // the zoom is on, a timeline held at its floor shows the same whole
382 // lane under the same line -- the strip's row comes and goes with
383 // the floor, not out of the lane. (A size dragged into the interior
384 // stays the hand's across the boundary, and the lanes are simply
385 // given the row back.)
386 assert_eq!(box_h, LANE_H + LABEL_H + 8.);
387 }
388 // The share covers the taller floor, strip in -- the one the clamp would
389 // otherwise overrule at the 640x360 floor, saying the panel takes less of
390 // a short window than it does.
391 assert!(
392 timeline_fixed_h(true) + LANE_H + LABEL_H + 8. <= 360. * TIMELINE_SHARE,
393 "the strip-bearing floor will not fit the share"
394 );
395}
396
397/// The lane stack's thumb: the visible share of the rows at their own place
398/// on the track, the time axis's own thumb turned through a right angle.
399#[test]
400fn the_lane_thumb_is_the_visible_share_of_the_stack() {
401 use crate::SCROLL_THUMB_MIN;
402 use crate::lanes_thumb;
403
404 // Whole stack on screen: the track fills and there is nothing to scroll.
405 assert_eq!(lanes_thumb(200., 104., 200., 0.), (0., 200.));
406 assert_eq!(lanes_thumb(200., 0., 0., 0.), (0., 200.));
407 // Half the stack visible, taken halfway down: a half-height thumb at the
408 // halfway mark.
409 assert_eq!(lanes_thumb(200., 400., 200., 100.), (50., 100.));
410 assert_eq!(lanes_thumb(200., 400., 200., 0.), (0., 100.));
411 // The floor height: however tall the stack, the thumb stays holdable --
412 // and the clamp keeps it on the track, not the caller.
413 let (y, h) = lanes_thumb(200., 2000., 200., 1800.);
414 assert_eq!(h, SCROLL_THUMB_MIN);
415 assert_eq!(y, 200. - SCROLL_THUMB_MIN);
416 assert_eq!(lanes_thumb(200., 2000., 200., 0.).0, 0.);
417 assert_eq!(lanes_thumb(200., 1_000_000., 200., 0.).0, 0.);
418}
419
420/// The selection itself: clicks in order, the anchor under the hand, the
421/// toggle that assembles a group, and the plain click that replaces it all.
422#[test]
423fn a_selection_holds_its_picks_in_click_order_and_anchors_the_last() {
424 use crate::Selection;
425
426 let mut sel = Selection::new();
427 assert!(sel.is_empty());
428 assert_eq!(sel.anchor(), None);
429
430 let (v, a, cap) = (
431 (Lane::V1, 0),
432 (Lane::A1, 1),
433 (Lane::new(LaneKind::Subtitle, 0), 0),
434 );
435 sel.set_one(v);
436 assert_eq!(sel.len(), 1);
437 assert_eq!(sel.anchor(), Some(v));
438
439 // Ctrl-clicks join, in the order they were made.
440 sel.toggle(a);
441 sel.toggle(cap);
442 assert_eq!(sel.picks(), &[v, a, cap]);
443 assert_eq!(sel.anchor(), Some(cap), "the last pick is the anchor");
444 assert!(sel.contains(a));
445
446 // ...and a ctrl-click on a pick already held takes it back out, leaving
447 // the others where they were.
448 sel.toggle(a);
449 assert_eq!(sel.picks(), &[v, cap]);
450 assert!(!sel.contains(a));
451
452 // A plain click is the whole selection, one pick: whatever was held gives
453 // way to the thing just named.
454 sel.set_one(a);
455 assert_eq!(sel.picks(), &[a]);
456
457 // `add` joins without disturbing -- Select All's builder.
458 let mut all = Selection::new();
459 all.add(v);
460 all.add(a);
461 all.add(v);
462 assert_eq!(all.picks(), &[v, a], "a pick is never held twice");
463
464 sel.clear();
465 assert!(sel.is_empty());
466 assert_eq!(sel.anchor(), None);
467}
468
469/// `Player::pick`'s own decision, mirrored here against `Selection` alone
470/// (`pick` itself needs a `Context<Player>` this module has no window to
471/// build): a plain press on a clip already in a multi-pick must leave the
472/// set alone, since the press is where a set-drag begins -- collapsing here
473/// would make dragging a member of a selection move only that one clip.
474/// Collapsing to the one pressed belongs to a plain click, once it is a
475/// click and not a drag (`ui/bench_stance.rs`/`ui/timeline.rs`'s `on_click`).
476#[test]
477fn a_plain_press_on_an_already_picked_clip_keeps_the_set() {
478 use crate::Selection;
479
480 let (v, a, cap) = (
481 (Lane::V1, 0),
482 (Lane::A1, 0),
483 (Lane::new(LaneKind::Subtitle, 0), 0),
484 );
485 let mut sel = Selection::new();
486 sel.toggle(v);
487 sel.toggle(a);
488 sel.toggle(cap);
489 assert_eq!(sel.picks(), &[v, a, cap]);
490
491 let press = |sel: &mut Selection, target, ctrl| match ctrl {
492 true => sel.toggle(target),
493 false if sel.contains(target) => {}
494 false => sel.set_one(target),
495 };
496
497 press(&mut sel, a, false);
498 assert_eq!(
499 sel.picks(),
500 &[v, a, cap],
501 "a plain press on a member of the set keeps it, for a set-drag to move"
502 );
503
504 // A plain press on something outside the set still collapses to it --
505 // the ordinary single-select case.
506 let outside = (Lane::V1, 1);
507 press(&mut sel, outside, false);
508 assert_eq!(sel.picks(), &[outside]);
509}
510
511#[test]
512fn a_click_marks_the_whole_group_and_nothing_else() {
513 let (v, a) = ((Lane::V1, 0), (Lane::A1, 0));
514 // Clicking the video half of group 1 marks the audio half with it -- the
515 // pick, and everything sharing its link.
516 assert!(marked(v, Some(1), &[v], &[Some(1)]));
517 assert!(marked(a, Some(1), &[v], &[Some(1)]));
518 // Another group's clips stay unmarked, in either lane.
519 assert!(!marked((Lane::V1, 1), Some(2), &[v], &[Some(1)]));
520 assert!(!marked((Lane::A1, 1), Some(2), &[v], &[Some(1)]));
521 // A half a lift left behind has no group: it marks itself only, which
522 // is what makes it separately deletable. Two ungrouped clips must not
523 // mark each other by both being ungrouped.
524 assert!(marked(a, None, &[a], &[None]));
525 assert!(!marked(v, None, &[a], &[None]));
526 // A caption ctrl-clicked into the selection marks the clip it was pinned
527 // to, and the caption is marked by the clip's pick just the same.
528 let cap = (Lane::new(LaneKind::Subtitle, 0), 0);
529 assert!(marked(cap, Some(1), &[cap, v], &[None, Some(1)]));
530 assert!(marked(a, Some(1), &[cap, v], &[None, Some(1)]));
531 // Nothing selected marks nothing.
532 assert!(!marked(v, Some(1), &[], &[]));
533}
534
535#[test]
536fn an_envelope_stays_inside_the_box_it_is_drawn_in() {
537 // A ramp: silence at the start, full scale at the end.
538 let peaks: Vec<(f32, f32)> = (0..40)
539 .map(|i| (-(i as f32) / 39., i as f32 / 39.))
540 .collect();
541 let (w, h) = (100., 30.);
542 let cols = envelope(&peaks, 0., 1., w, h);
543 assert_eq!(cols.len(), (w / WAVE_COL) as usize + 1);
544 for &(x, top, bottom) in &cols {
545 assert!((0. ..=w).contains(&x), "x {x} outside 0..{w}");
546 assert!((0. ..=h).contains(&top), "top {top} outside 0..{h}");
547 assert!(
548 (0. ..=h).contains(&bottom),
549 "bottom {bottom} outside 0..{h}"
550 );
551 // Never inverted, and never a polygon with no area: silence has to
552 // read as a line rather than as nothing at all.
553 assert!(
554 bottom - top >= 1.,
555 "column {top}..{bottom} is thinner than a pixel"
556 );
557 }
558 // The ramp is drawn as a ramp: the last column is taller than the first.
559 let height = |&(_, top, bottom): &(f32, f32, f32)| bottom - top;
560 assert!(height(cols.last().unwrap()) > height(cols.first().unwrap()) + 5.);
561 // Degenerate inputs draw nothing rather than panicking.
562 assert!(envelope(&[], 0., 1., w, h).is_empty());
563 assert!(envelope(&peaks, 0., 1., 0., h).is_empty());
564 // A clip whose range runs past the peaks clamps to the last bucket.
565 assert!(!envelope(&peaks, 0., 99., w, h).is_empty());
566}
567
568/// A box laid out wider than any screen -- a long clip at a deep zoom -- is
569/// still one screen's worth of columns: the path a repaint has to build is
570/// bounded by what can be seen, not by what the layout says the box is.
571/// Unbounded, a 5 s clip zoomed to the frame is a path of millions of points
572/// per frame, and the repaint that stalls on it is the waveform that
573/// "disappeared".
574#[test]
575fn an_envelope_never_costs_more_points_than_a_screen_can_show() {
576 let peaks: Vec<(f32, f32)> = (0..200).map(|i| (-(i as f32) / 199., 1.)).collect();
577 // The width a 5 s clip is laid out at when the bed shows 8 frames of it.
578 let huge = 5. * 30. / 8. * 1200.;
579 let cols = envelope(&peaks, 0., 5., huge, 30.);
580 assert!(
581 cols.len() <= WAVE_COLS_MAX + 1,
582 "{} columns for a {huge} px box",
583 cols.len()
584 );
585 // ...and the slice actually painted is the part of the box on the bed,
586 // which is where that width stops mattering: a column per two visible
587 // pixels, at every zoom.
588 assert_eq!(envelope(&peaks, 0., 5., 1200., 30.).len(), 601);
589}
590
591/// The box a trim draws is the box its release commits, at every speed. The
592/// preview used to hand the *timeline* frame count to a source-frame field:
593/// at 2x a tail moved twice as fast as the pointer and snapped back on
594/// release, and a head drag moved the clip's other edge.
595#[test]
596fn a_trim_preview_lands_where_the_release_commits() {
597 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
598 session.set_gain(0.0);
599 for permille in SPEED_PRESETS {
600 // Live, so the loop owes it no undo step: the speeds are the axis
601 // this walks, and the trims below are what is undone.
602 session
603 .set_speed_live(Lane::V1, 0, Speed::from_permille(permille))
604 .expect("a clip alone on its lane may be speeded");
605 for edge in [Edge::Start, Edge::End] {
606 let clip = session.lane_clips(Lane::V1)[0];
607 let (lo, hi) = session
608 .trim_room(Lane::V1, 0, edge)
609 .expect("clip 0 is there");
610 // Both walls and the middle of the room: the whole range a
611 // pointer can be clamped to.
612 for to in [lo, (lo + hi) / 2, hi] {
613 let preview = trimmed_clip(clip, edge, to, false);
614 // The drag is one edit and one undo step, so the next `to`
615 // is measured from the same clip this one was.
616 if session.trim_clip(Lane::V1, 0, edge, to) {
617 assert_eq!(
618 preview,
619 session.lane_clips(Lane::V1)[0],
620 "{edge:?} to {to} at {permille} per mille"
621 );
622 assert!(session.undo(), "the trim is one undo step");
623 } else {
624 // An edge already where it was asked to go is not an
625 // edit, and the preview draws the clip unchanged.
626 assert_eq!(preview, clip, "{edge:?} to {to} at {permille} per mille");
627 }
628 assert_eq!(session.lane_clips(Lane::V1)[0], clip, "back where it was");
629 }
630 }
631 }
632}
633
634/// The caption a drag is showing lands where the release commits -- the
635/// subtitle twin of the trim preview above -- and the two contracts the boxes
636/// on the lanes rest on: `place_sub`'s `at` wins over the placement's own
637/// `start`, and a gesture that changed nothing is `Ok` and not a refusal, so a
638/// front-end that toasted every `Ok` would toast a pick-up-put-back.
639#[test]
640fn a_caption_trim_preview_lands_where_the_release_commits() {
641 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
642 session.set_gain(0.0);
643 let fps = session.meta().frame_rate;
644 let srt = Path::new(env!("CARGO_MANIFEST_DIR"))
645 .join("../engine/tests/data/test_subs.srt")
646 .canonicalize()
647 .expect("the subtitle fixture");
648 session.import_subtitles(&srt).expect("the .srt imports");
649 let lane = session.add_lane(LaneKind::Subtitle);
650 // The whole track as a placement, exactly as `Player::sub_of_track` builds
651 // one from a palette row.
652 let out_us = session.subtitles()[0]
653 .cues
654 .iter()
655 .map(|c| c.end_us)
656 .max()
657 .expect("the fixture has cues");
658 let whole = SubClip {
659 start: 0,
660 frames: frames_of_us(out_us, fps),
661 track: 0,
662 in_us: 0,
663 out_us,
664 link: None,
665 };
666 session
667 .place_sub(lane, 30, whole)
668 .expect("an empty subtitle lane takes it");
669 assert_eq!(
670 session.sub_lane(lane)[0].start,
671 30,
672 "the frame the hand let go on wins over the placement's own start"
673 );
674 for edge in [Edge::Start, Edge::End] {
675 let (lo, hi) = session
676 .trim_sub_room(lane, 0, edge)
677 .expect("placement 0 is there");
678 for to in [lo, (lo + hi) / 2, hi] {
679 let placed = session.sub_lane(lane)[0];
680 let preview = trimmed_sub(placed, edge, to);
681 session
682 .trim_sub(lane, 0, edge, to)
683 .expect("an edge inside its own room is never refused");
684 let now = session.sub_lane(lane)[0];
685 assert_eq!(
686 (preview.start, preview.frames),
687 (now.start, now.frames),
688 "{edge:?} to {to}"
689 );
690 // One edit, one undo step -- and none at all where the edge was
691 // already there, which is the `Ok` that must stay silent.
692 if (now.start, now.frames) != (placed.start, placed.frames) {
693 assert!(session.undo(), "the trim is one undo step");
694 }
695 }
696 }
697 // Picked up and put back down: `Ok`, nothing moved, nothing to say.
698 let before = session.sub_lane(lane)[0];
699 session
700 .move_sub(lane, 0, lane, before.start)
701 .expect("a drop that changes nothing is not a refusal");
702 assert_eq!(session.sub_lane(lane)[0], before);
703 // ...and two captions over one frame are refused in words, which is what
704 // the notice shows verbatim.
705 let over = session
706 .place_sub(lane, before.start, whole)
707 .expect_err("two captions may not cover one frame");
708 assert!(over.to_string().contains("already covers"), "{over}");
709}
710
711/// A still trims the same way, and the preview knows it: its head grows
712/// forward from source frame 0 -- every frame of it is the same picture --
713/// so the box stretches instead of sliding left.
714#[test]
715fn a_stills_trim_preview_grows_forward_like_the_commit() {
716 let mut session = PlaybackSession::open(asset("test_still.png")).expect("a picture opens");
717 for edge in [Edge::Start, Edge::End] {
718 let clip = session.lane_clips(Lane::V1)[0];
719 let (lo, hi) = session
720 .trim_room(Lane::V1, 0, edge)
721 .expect("clip 0 is there");
722 for to in [lo, (lo + hi) / 2, hi] {
723 let preview = trimmed_clip(clip, edge, to, true);
724 match session.trim_clip(Lane::V1, 0, edge, to) {
725 true => {
726 assert_eq!(
727 preview,
728 session.lane_clips(Lane::V1)[0],
729 "a still {edge:?} to {to}"
730 );
731 assert!(session.undo(), "the trim is one undo step");
732 }
733 false => assert_eq!(preview, clip, "a still {edge:?} to {to}"),
734 }
735 assert_eq!(session.lane_clips(Lane::V1)[0], clip, "back where it was");
736 }
737 }
738}
739
740/// gpui freezes a drag's payload for the whole gesture, and nothing stops a
741/// stroke from editing the lane under it: the drop has to find the clip that
742/// was picked up, not whatever slid into its index.
743#[test]
744fn a_drop_moves_the_clip_that_was_picked_up_not_its_old_index() {
745 let at = |start: u32| Clip {
746 fade_in: 0,
747 fade_out: 0,
748 transition_out: 0,
749 start,
750 in_frame: 0,
751 out_frame: 30,
752 source: 0,
753 link: None,
754 eq: None,
755 color: None,
756 transform: None,
757 fit: FitPolicy::Fit,
758 speed: Speed::NORMAL,
759 };
760 let lane = [at(0), at(30), at(60)];
761 let dragged = lane[2];
762 assert_eq!(live_idx(&lane, 2, dragged), Some(2), "nothing moved");
763 // A delete in front of it: the clip is now index 1, and the index the
764 // drag froze names a clip nobody grabbed.
765 let after = [at(0), at(60)];
766 assert_eq!(live_idx(&after, 2, dragged), Some(1));
767 assert_eq!(live_idx(&after, 1, dragged), Some(1));
768 // Deleted mid-drag: there is nothing to move, and moving its neighbour
769 // instead is exactly the bug this exists for.
770 assert_eq!(live_idx(&[at(0)], 2, dragged), None);
771 assert_eq!(live_idx(&[], 0, dragged), None);
772}
773
774#[test]
775fn a_quiet_source_still_draws_as_a_shape() {
776 // An eighth of full scale, which is about where the fixtures sit.
777 let quiet: Vec<(f32, f32)> = vec![(-0.125, 0.125), (-0.0625, 0.0625)];
778 let loud = normalise(quiet.clone());
779 assert_eq!(loud[0], (-1., 1.));
780 assert_eq!(loud[1], (-0.5, 0.5));
781 // Digital silence has no loudest sample to scale to; it must not divide
782 // by zero and must stay flat.
783 assert_eq!(normalise(vec![(0., 0.)]), vec![(0., 0.)]);
784 assert!(normalise(Vec::new()).is_empty());
785}
786
787/// The whole waveform path, from the file on disk to the columns that get
788/// painted: what no screenshot can assert about the shape.
789#[test]
790fn the_fixtures_waveform_reaches_the_lane_as_a_shape() {
791 let asset = |name: &str| {
792 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
793 .join("../../assets")
794 .join(name)
795 };
796 let peaks = normalise(
797 engine::waveform::peaks(asset("test_av.mp4"), 0, WAVE_BPS)
798 .expect("open the fixture")
799 .expect("test_av.mp4 has audio"),
800 );
801 // 5 s of source at the rate the lane asks for.
802 assert!(peaks.len().abs_diff(5 * WAVE_BPS as usize) <= WAVE_BPS as usize);
803 let cols = envelope(&peaks, 0., 5., 600., 30.);
804 let height = |&(_, top, bottom): &(f32, f32, f32)| bottom - top;
805 let tallest = cols.iter().map(height).fold(0., f32::max);
806 let flattest = cols.iter().map(height).fold(f32::MAX, f32::min);
807 // The fixture's 1 Hz pulse: a full-scale peak and a near-silent dip in
808 // every second, so the drawn envelope is a shape and not a bar.
809 assert!(tallest > 25., "loudest column only {tallest} px of 30");
810 assert!(
811 flattest < 8.,
812 "quietest column {flattest} px -- no dips drawn"
813 );
814 // A video-only source draws no waveform at all rather than a flat fake.
815 assert!(
816 engine::waveform::peaks(asset("test_baseline.mp4"), 0, WAVE_BPS)
817 .expect("open the fixture")
818 .is_none()
819 );
820}
821
822#[test]
823fn every_mark_on_a_clip_is_legible_on_it() {
824 // The body a name and a waveform are drawn on is the clip's kind
825 // ([`clip_kind`]); the source tint is the border and the library
826 // swatch, and is measured for telling itself apart rather than for
827 // carrying text.
828 // Every palette a person can pick, not merely the one in force.
829 for id in crate::ui::theme::PaletteId::ALL {
830 let p = id.palette();
831 for (i, tint) in [p.CLIP_VIDEO, p.CLIP_AUDIO, p.CLIP_IMAGE, p.CLIP_TEXT]
832 .iter()
833 .enumerate()
834 {
835 // WCAG 1.4.3: the clip's name is body text on its tint.
836 assert!(
837 contrast(p.FG_PRIMARY, *tint) >= 4.5,
838 "{id:?} source {i}: label contrast {:.2}",
839 contrast(p.FG_PRIMARY, *tint)
840 );
841 // WCAG 1.4.11: the waveform is a non-text graphic on it.
842 assert!(
843 contrast(p.FG_SECONDARY, *tint) >= 3.,
844 "{id:?} source {i}: waveform contrast {:.2}",
845 contrast(p.FG_SECONDARY, *tint)
846 );
847 }
848 // A selected clip's bed is the same two marks on a different colour.
849 assert!(contrast(p.FG_PRIMARY, p.BG_SELECTED) >= 4.5, "{id:?}");
850 assert!(contrast(p.FG_SECONDARY, p.BG_SELECTED) >= 3., "{id:?}");
851 // The bed a gap shows through has to read as a hole in the lane --
852 // the clip is the object, the bed is the hole -- and the playhead
853 // has to be findable on both.
854 assert!(contrast(p.CLIP_VIDEO, p.BG_TIMELINE) >= 1.5, "{id:?}");
855 assert!(contrast(p.ACCENT_PLAYHEAD, p.BG_TIMELINE) >= 3., "{id:?}");
856 assert!(contrast(p.ACCENT_PLAYHEAD, p.CLIP_VIDEO) >= 3., "{id:?}");
857 }
858 // The sanity check on the ratio itself: black on white is 21:1.
859 assert!((contrast(0xffffff, 0x000000) - 21.).abs() < 0.01);
860}
861
862#[test]
863fn source_tints_differ_per_source_and_cycle() {
864 // The bug: the first entry *was* `BG_RAISED`, so the first file imported
865 // -- the one every session has -- wore the panel's own background and
866 // had no visible swatch at all.
867 assert_ne!(source_tint(0), BG_RAISED());
868 // ...in every family, since the swatch is drawn on whichever panel is
869 // in force (`ui::theme`) and a tint that vanished into one of them is a
870 // file with no colour at all.
871 for id in crate::ui::theme::PaletteId::ALL {
872 let p = id.palette();
873 for (i, &tint) in p.SOURCE_TINTS.iter().enumerate() {
874 assert_ne!(tint, p.BG_RAISED, "{id:?} tint {i} is the panel");
875 }
876 }
877 // Neighbouring sources must not share one, or an import is invisible.
878 assert_ne!(source_tint(0), source_tint(1));
879 assert_ne!(source_tint(1), source_tint(2));
880 assert_ne!(source_tint(2), source_tint(3));
881 // Past the palette it wraps -- never an index panic.
882 assert_eq!(source_tint(4), source_tint(0));
883 assert_eq!(source_tint(9), source_tint(1));
884 assert_eq!(source_tint(usize::MAX), SOURCE_TINTS()[usize::MAX % 4]);
885}
886
887/// Not "they are different numbers" -- different *enough to see*, against
888/// each other and against the surface a swatch is drawn on. The palette is
889/// deliberately dark and low-saturation, so the margin is thin and a new
890/// tint picked by eye can land inside it without anyone noticing.
891#[test]
892fn source_tints_are_all_discernible() {
893 // Summed channel distance: `BG_RAISED` to the warm tint is 18, and that
894 // step is the one already accepted as readable on a lane.
895 let apart = |a: u32, b: u32| {
896 (0..3)
897 .map(|i| {
898 let shift = i * 8;
899 ((a >> shift) & 0xff).abs_diff((b >> shift) & 0xff)
900 })
901 .sum::<u32>()
902 };
903 // Every family, not the one in force: a palette is picked at runtime
904 // now, and four tints tuned by eye on one ground are exactly where a
905 // pair lands inside the margin on another.
906 for id in crate::ui::theme::PaletteId::ALL {
907 let p = id.palette();
908 for (i, &tint) in p.SOURCE_TINTS.iter().enumerate() {
909 assert!(
910 apart(tint, p.BG_RAISED) >= 16,
911 "{id:?} tint {i} is {} from the panel it sits on",
912 apart(tint, p.BG_RAISED)
913 );
914 for (j, &other) in p.SOURCE_TINTS.iter().enumerate().skip(i + 1) {
915 // The eleven non-darkroom families still cycle four tuned
916 // tints through the 12-wide wheel (`source_tint`'s own `%
917 // len()` reads them back identically either way) -- a
918 // literal repeat there is the intended cycle, not a
919 // collision, so it is skipped rather than failed. Darkroom's
920 // own twelve (DESIGN §2) are twelve *different* hues and
921 // never repeat, so a real collision there still fails this.
922 if tint == other {
923 continue;
924 }
925 assert!(
926 apart(tint, other) >= 16,
927 "{id:?} tints {i} and {j} are only {} apart",
928 apart(tint, other)
929 );
930 }
931 }
932 // The two a person sees side by side first must be further apart
933 // than the floor: source 0 and source 1 are the first import and
934 // the second.
935 assert!(apart(p.SOURCE_TINTS[0], p.SOURCE_TINTS[1]) >= 32, "{id:?}");
936 }
937 // Darkroom's own 12-hue wheel (DESIGN §2/§12 step 5's hook): every one
938 // of the twelve is a genuinely different hue, not four repeated three
939 // times like the other families still cycle -- a hue accidentally
940 // reintroduced by a future edit here is the "four shades of grey" bug
941 // this task exists to fix, so it fails loudly rather than skip past the
942 // `tint == other` escape hatch above.
943 let dr = crate::ui::theme::PaletteId::Darkroom.palette();
944 for (i, &a) in dr.SOURCE_TINTS.iter().enumerate() {
945 for (j, &b) in dr.SOURCE_TINTS.iter().enumerate().skip(i + 1) {
946 assert_ne!(a, b, "darkroom tints {i} and {j} collide");
947 }
948 }
949}
950
951/// A `.srt` dropped on the window is nobody's stream: it has no source
952/// entry, and the lookup that used to fall back to index 0 painted it with
953/// the first file's colour -- a swatch saying it came out of a film it
954/// never touched.
955#[test]
956fn a_standalone_subtitle_wears_no_file_tint() {
957 let sources = [
958 Source {
959 path: PathBuf::from("/films/a.mkv"),
960 audio_stream: 0,
961 },
962 Source {
963 path: PathBuf::from("/films/b.mp4"),
964 audio_stream: 0,
965 },
966 // A second stream of the first file is a second source and the
967 // same colour.
968 Source {
969 path: PathBuf::from("/films/a.mkv"),
970 audio_stream: 1,
971 },
972 ];
973 assert_eq!(
974 file_tint(&sources, Path::new("/films/a.mkv")),
975 Some(source_tint(0))
976 );
977 assert_eq!(
978 file_tint(&sources, Path::new("/films/b.mp4")),
979 Some(source_tint(1))
980 );
981 assert_eq!(file_tint(&sources, Path::new("/subs/a.eng.srt")), None);
982 assert_eq!(file_tint(&[], Path::new("/films/a.mkv")), None);
983 // The same file under two spellings is one file and one colour: a
984 // source is stored symlink-resolved, everything else as it was typed.
985 let here = std::fs::canonicalize(".").expect("the crate directory");
986 let sources = [Source {
987 path: here.join("Cargo.toml"),
988 audio_stream: 0,
989 }];
990 assert_eq!(
991 file_tint(&sources, Path::new("Cargo.toml")),
992 Some(source_tint(0)),
993 "a relative spelling of the source file wears the source's colour"
994 );
995}
996
997/// A film's two ASS tracks with the timeline trimmed to twenty seconds:
998/// one of them still has cues there and one has none, and the card said
999/// nothing whatever about the second while the Subtitles list went on
1000/// showing it with its eighty-three cues.
1001///
1002/// And the 25 GB remux's thirty-five: naming those wrapped the row to ten
1003/// lines and pushed Destination under the fold, so past the value box's
1004/// three lines the same line counts instead.
1005#[test]
1006fn the_card_names_the_subtitle_it_leaves_off_and_counts_them_when_it_cannot() {
1007 let film = "/films/An Episode 01.mkv";
1008 let two = [
1009 sub(film, Some(1), "[ASS]"),
1010 sub(film, Some(2), "[ASS] [FOR DUB]"),
1011 ];
1012 // What the engine answers about the one pick that reached it, and what
1013 // this side knows about the row that did not.
1014 let named = subtitle_plan("[ASS] → embedded".to_string(), &two, &[0]);
1015 assert_eq!(
1016 named,
1017 "[ASS] → embedded; [ASS] [FOR DUB] — in the palette, on no track"
1018 );
1019 assert!(
1020 named.chars().count() <= SUB_PLAN_CHARS,
1021 "two tracks fit the value box: {named}"
1022 );
1023 // Thirty-five off one file: twenty-two carry cues here, nine are
1024 // pictures, one could not be read, three have nothing on this timeline.
1025 let many: Vec<_> = (0..35)
1026 .map(|i| {
1027 let mut track = sub("/films/A Remux.mkv", Some(i), "eng — Subtitles");
1028 track.bitmap = (22..31).contains(&i);
1029 track.refused = (i == 31).then(|| "VobSub is pictures".to_string());
1030 track
1031 })
1032 .collect();
1033 // The picks are every track with a cue on the timeline: the twenty-two
1034 // and the nine picture ones, which the engine drops itself.
1035 let picks: Vec<usize> = (0..31usize).collect();
1036 let counted = subtitle_plan("22 tracks → embedded (…)".to_string(), &many, &picks);
1037 assert_eq!(
1038 counted,
1039 "22 of 35 → embedded; 9 pictures; 1 unread; 3 in the palette, on no track"
1040 );
1041 assert!(
1042 counted.chars().count() <= SUB_PLAN_CHARS,
1043 "thirty-five tracks still fit the value box: {counted}"
1044 );
1045 // Nothing on the timeline at all is still the engine's word for it.
1046 assert_eq!(subtitle_plan("none".to_string(), &[], &[]), "none");
1047 // The lanes are what an export writes once anything is placed on one, and
1048 // the engine words that whole ([`engine::export::planned_subtitles`]) --
1049 // including the lanes it carries *nothing* of, which is a sentence with no
1050 // pick behind it at all. That used to be dropped on the floor: the card said
1051 // "[ASS] — no cues here" twice and never said what became of the lane.
1052 let placed = "S1 [ASS] — past the last picture".to_string();
1053 assert_eq!(
1054 subtitle_plan(placed.clone(), &two, &[]),
1055 "S1 [ASS] — past the last picture; [ASS] [FOR DUB] — in the palette, on no track"
1056 );
1057 // ...and the row that sentence speaks for gets no clause of its own: a line
1058 // that names a lane's track and then calls the same track unplaced is the
1059 // card contradicting itself in one breath.
1060 assert!(!subtitle_plan(placed, &two[..1], &[]).contains("in the palette"));
1061}
1062
1063/// The list is in the order tracks were added, which is not the order a
1064/// person reads it in: importing a second film puts its tracks after the
1065/// first film's, and importing a third `.srt` for the first film puts that
1066/// one last of all. The rows still read as three sources.
1067#[test]
1068fn subtitle_rows_group_a_source_however_they_were_added() {
1069 let tracks = [
1070 sub("/films/a.mkv", Some(1), "eng"),
1071 sub("/films/b.mkv", Some(1), "eng"),
1072 sub("/films/a.mkv", Some(2), "fre"),
1073 sub("/subs/late.srt", None, "late.srt"),
1074 sub("/films/b.mkv", Some(3), "ger"),
1075 ];
1076 let groups = subtitle_rows(&tracks);
1077 assert_eq!(
1078 groups.iter().map(|g| g.name.as_str()).collect::<Vec<_>>(),
1079 ["a", "b", "late"],
1080 "one group per file, in the order the files first appear"
1081 );
1082 assert_eq!(
1083 groups
1084 .iter()
1085 .map(|g| g.rows.iter().map(|r| r.label.as_str()).collect::<Vec<_>>())
1086 .collect::<Vec<_>>(),
1087 [vec!["eng", "fre"], vec!["eng", "ger"], vec!["late.srt"]],
1088 "a file's tracks are contiguous and in add order"
1089 );
1090 // Numbered within the file, the way `row_name` numbers audio streams:
1091 // two tracks that both say "eng" are told apart by nothing else.
1092 assert_eq!(
1093 groups
1094 .iter()
1095 .map(|g| g.rows.iter().map(|r| r.number).collect::<Vec<_>>())
1096 .collect::<Vec<_>>(),
1097 [vec![1, 2], vec![1, 2], vec![1]]
1098 );
1099 // The swatch key is the file, so a group and that file's media rows
1100 // wear one colour -- and the standalone one has none.
1101 let sources = [Source {
1102 path: PathBuf::from("/films/a.mkv"),
1103 audio_stream: 0,
1104 }];
1105 assert_eq!(
1106 file_tint(&sources, &groups[0].path),
1107 Some(source_tint(0)),
1108 "the group carries the path the tint is asked by"
1109 );
1110 assert_eq!(file_tint(&sources, &groups[2].path), None);
1111 // What a header's "N tracks" says: the group's own row count, which is
1112 // 2, 2, 1 here -- a film that gave several tracks and a standalone
1113 // `.srt` that gave exactly one.
1114 assert_eq!(
1115 groups.iter().map(|g| g.rows.len()).collect::<Vec<_>>(),
1116 [2, 2, 1]
1117 );
1118 // A standalone `.srt` is already its own group, named after its own
1119 // file ("late", not lumped under some catch-all "External" bucket) --
1120 // there is no sourceless case for a header to special-case.
1121 assert_eq!(groups[2].name, "late");
1122 assert_eq!(groups[2].path, PathBuf::from("/subs/late.srt"));
1123}
1124
1125/// The fold a click on a header sets is keyed by [`SubGroup::path`]
1126/// (`Player::sub_folded`), so it has to survive the very thing regrouping
1127/// is for: a second track landing on a file already in the list, or one
1128/// being removed from it. The group's path is the fold's whole identity,
1129/// so it must not move under either.
1130#[test]
1131fn a_groups_fold_key_survives_a_track_arriving_or_leaving_its_file() {
1132 let before = [
1133 sub("/films/a.mkv", Some(1), "eng"),
1134 sub("/films/b.mkv", Some(1), "eng"),
1135 ];
1136 let after_add = [
1137 sub("/films/a.mkv", Some(1), "eng"),
1138 sub("/films/b.mkv", Some(1), "eng"),
1139 sub("/films/a.mkv", Some(2), "fre"),
1140 ];
1141 let (before_groups, after_groups) = (subtitle_rows(&before), subtitle_rows(&after_add));
1142 assert_eq!(before_groups[0].path, after_groups[0].path, "a's key held");
1143 assert_eq!(before_groups[1].path, after_groups[1].path, "b's key held");
1144 // The group a second track landed on grew; the other did not move.
1145 assert_eq!(after_groups[0].rows.len(), 2);
1146 assert_eq!(after_groups[1].rows.len(), 1);
1147 // Removing that same track back off leaves the original key and count.
1148 let after_remove = subtitle_rows(&before);
1149 assert_eq!(after_remove[0].path, before_groups[0].path);
1150 assert_eq!(after_remove[0].rows.len(), 1);
1151}
1152
1153/// What the strip header, the section heading and the toggle's notice all
1154/// say. Two films each carrying an "eng" track are one word apart until the
1155/// film is in the name; a film carrying two is one word apart from itself.
1156#[test]
1157fn the_picked_subtitle_is_named_with_the_film_it_came_out_of() {
1158 let tracks = [
1159 sub("/films/a.mkv", Some(1), "eng"),
1160 sub("/films/b.mkv", Some(1), "eng"),
1161 sub("/films/a.mkv", Some(2), "eng"),
1162 sub("/films/b.mkv", Some(2), "und"),
1163 sub("/subs/late.srt", None, "late.srt"),
1164 ];
1165 let name = |track| sub_pick_name(&tracks, track).expect("a track that is there");
1166 // The two "eng"s of two films: one file gave several so its tracks are
1167 // numbered, the other gave one so it is not.
1168 assert_eq!(name(0), "eng 1 — a");
1169 assert_eq!(name(2), "eng 2 — a");
1170 assert_eq!(name(1), "eng 1 — b");
1171 assert_ne!(name(0), name(1), "two films' eng tracks read apart");
1172 for picked in [name(0), name(1), name(2)] {
1173 assert!(picked.contains(" — a") || picked.contains(" — b"));
1174 }
1175 // "und" is the tag for "nobody said", humanised once by
1176 // `subtitle_rows` and not again here.
1177 assert_eq!(name(3), "unknown language 2 — b");
1178 // A standalone `.srt` is its own file and its label already says so:
1179 // one track, so no number, and no stem after it saying it again.
1180 assert_eq!(name(4), "late.srt");
1181 // The silence a row left over from a timeline that is gone gets.
1182 assert_eq!(sub_pick_name(&tracks, 5), None);
1183 assert_eq!(sub_pick_name(&[], 0), None);
1184}
1185
1186/// What the toggle covers is what is *placed*, so what it says is a lane fact:
1187/// naming the palette row the list happens to mark named a track the stroke
1188/// never touched ("SUBTITLES OFF — one.srt is still on the timeline" for a
1189/// one.srt nobody dragged anywhere).
1190#[test]
1191fn the_subtitles_toggle_says_what_is_placed_and_never_the_picked_row() {
1192 for on in [true, false] {
1193 let text = subtitle_toggle_notice(on, 2);
1194 assert!(text.contains('2'), "{text} counts the captions placed");
1195 assert!(
1196 !text.contains("track(s)") && !text.contains(" — a"),
1197 "{text} names no palette row"
1198 );
1199 }
1200 // Off leaves them on the lanes; that is the half a person needs told.
1201 assert!(subtitle_toggle_notice(false, 2).contains("still placed"));
1202 // An empty timeline says the state, not a count that reads as broken --
1203 // and DESIGN §8 (2026-08-27) keeps this a state report, not a "drag it"
1204 // instruction.
1205 let none = subtitle_toggle_notice(true, 0);
1206 assert!(!none.contains('0'), "{none} counts nothing at nothing");
1207 assert!(
1208 none.contains("nothing placed"),
1209 "{none} says the state, not the move"
1210 );
1211}
1212
1213/// The door this editor answers "don't make me import the film again" with,
1214/// and it is in the dock's IMPORT section beside the other two imports
1215/// (`ui/dock_stance.rs`'s own doc comment: it moved off the old rail's crowded
1216/// TRACK group here): reads a file's subtitle tracks onto the open timeline
1217/// -- a release's `.mkv`, an `.srt` beside it -- while the file itself
1218/// joins nothing. It is the *action* and not a second implementation of it,
1219/// so the button, the stroke and the actions card cannot drift apart, and
1220/// it is oracle-gated like every other verb in the dock, so with no timeline
1221/// open it dims and says why instead of opening a chooser for nothing.
1222#[test]
1223fn the_text_tab_carries_the_add_subtitles_door() {
1224 let dock = src_text("ui/dock_stance.rs");
1225 let at = dock
1226 .find("\"dock-import-subtitles\"")
1227 .expect("no import-subtitles control in the dock");
1228 let block = &dock[at..(at + 500).min(dock.len())];
1229 assert!(
1230 block.contains("ActionId::ImportSubtitles"),
1231 "the button is a door of its own rather than the action: {block}"
1232 );
1233 assert!(
1234 block.contains("this.act(ActionId::ImportSubtitles"),
1235 "the button does not dispatch through the action oracle: {block}"
1236 );
1237 // `act(ActionId::ImportSubtitles, ...)` routes to `pick_and_add_subtitles`
1238 // -- the button names the action, not a second implementation of it.
1239 let actions = src_text("player/actions.rs");
1240 assert!(
1241 actions.contains("ActionId::ImportSubtitles => self.pick_and_add_subtitles(cx)"),
1242 "ImportSubtitles no longer opens the subtitle chooser"
1243 );
1244 // `ghost_verb` is the oracle-gated one: dimmed with the refusal in the
1245 // oracle's own words (`player.enable(action, None)` in its own body).
1246 assert!(
1247 dock[..at].ends_with("ghost_verb(\n "),
1248 "the add-subtitles button is not built from the oracle-gated ghost_verb"
1249 );
1250 // ...and the empty tab stays a noun, not a sentence pointing at the
1251 // button (DESIGN §8, 2026-08-27: no instructional copy).
1252 assert_eq!(crate::LibraryTab::Text.empty(), "No subtitles");
1253}
1254
1255/// The Darkroom keeps imported subtitle tracks in the Text tab itself (moved
1256/// off the unconditional spot under the Sources list, user 2026-08-27), where
1257/// a row can be selected, folded with its source, removed, and dragged to the
1258/// bench's existing subtitle-lane target.
1259#[test]
1260fn the_darkroom_subtitle_palette_drags_tracks_to_subtitle_lanes() {
1261 let dock = src_text("ui/dock_stance.rs");
1262 let palette = &dock[dock
1263 .find("fn subtitle_tab_rows")
1264 .expect("no Darkroom subtitle rows")..];
1265 for required in [
1266 "subtitle_rows",
1267 "dock-subtitle-group",
1268 "sub_folded.remove",
1269 "sub_folded.insert",
1270 "this.sub_track = track",
1271 ".on_drag(SubPick(track)",
1272 "remove_subtitle_track(track",
1273 ] {
1274 assert!(palette.contains(required), "palette lost {required}");
1275 }
1276 let bench = src_text("ui/bench_stance.rs");
1277 let drop_at = bench
1278 .find(".drag_over::<SubPick>")
1279 .expect("no subtitle-track lane target");
1280 let drop = &bench[drop_at..(drop_at + 500).min(bench.len())];
1281 assert!(
1282 drop.contains("this.place_sub(drag.0, lane"),
1283 "a dock subtitle drag does not place on the lane: {drop}"
1284 );
1285}
1286
1287/// A subtitle group's header in the Text tab must not vanish on a short
1288/// window: `subtitle_tab_rows` draws one per group unconditionally -- there
1289/// is no viewport-height gate on it at all any more, so the list under it
1290/// is what would scroll instead, never the header itself. And it has to be
1291/// a real fold, not the click-cycling pattern this codebase has already
1292/// thrown out once: one click toggles `sub_folded` shut or open, it never
1293/// steps through more than those two states.
1294#[test]
1295fn a_subtitle_group_header_is_never_gated_on_window_height() {
1296 let dock = src_text("ui/dock_stance.rs");
1297 assert!(
1298 !dock.contains("sub_headers_fit"),
1299 "the header is still gated on the viewport's height"
1300 );
1301 // The header is a click target that flips membership in a set --
1302 // `remove` else `insert` -- not a value stepped through several states.
1303 let head_at = dock
1304 .find("\"dock-subtitle-group\"")
1305 .expect("no id on the group header");
1306 // Wide enough to reach the count line past the header's styling and its
1307 // commentary -- a window that stops short reads as the line deleted
1308 // (the same fixed-window misfire the modal-guard scan had, 2026-08-27).
1309 let block = &dock[head_at..(head_at + 3600).min(dock.len())];
1310 assert!(
1311 block.contains("sub_folded.remove"),
1312 "no fold-open path: {block}"
1313 );
1314 assert!(
1315 block.contains("sub_folded.insert"),
1316 "no fold-shut path: {block}"
1317 );
1318 assert!(
1319 block.contains("{track_count} track"),
1320 "the header does not say how many tracks it holds: {block}"
1321 );
1322}
1323
1324/// The one thing regrouping must not break: `sub_track` is a flat index
1325/// into the add-order list, a click sets it and a save writes it into the
1326/// `.edith`. Every row must still name the track it was made from -- rows
1327/// for refused tracks included, because they take a number in that list
1328/// whether or not anyone can pick them.
1329#[test]
1330fn a_subtitle_row_names_the_flat_track_it_was_made_from() {
1331 let mut tracks = vec![
1332 sub("/films/a.mkv", Some(1), "eng"),
1333 sub("/films/b.mkv", Some(1), "eng"),
1334 sub("/films/a.mkv", Some(2), "fre"),
1335 ];
1336 // Track 1 of b is pictures: still a row, still index 1 of the list.
1337 tracks[1].bitmap = true;
1338 tracks[1].refused = Some("PGS subtitles are pictures".to_string());
1339 let groups = subtitle_rows(&tracks);
1340 let flat: Vec<(usize, &str)> = groups
1341 .iter()
1342 .flat_map(|g| g.rows.iter().map(|r| (r.track, r.label.as_str())))
1343 .collect();
1344 assert_eq!(flat, [(0, "eng"), (2, "fre"), (1, "eng")]);
1345 for (track, label) in flat {
1346 assert_eq!(
1347 tracks[track].label, label,
1348 "row {track} picks the track it names"
1349 );
1350 }
1351 // (c) The refused one is here, saying why, and greyable by that alone.
1352 let refused = &groups[1].rows[0];
1353 assert_eq!(
1354 refused.refused.as_deref(),
1355 Some("PGS subtitles are pictures")
1356 );
1357 assert_eq!(refused.detail, "PGS subtitles are pictures");
1358 assert!(refused.bitmap);
1359 // ...and it was counted: the row after it in add order is still 2.
1360 assert_eq!(groups[0].rows[1].track, 2);
1361}
1362
1363/// The × on a row shifts every track after it down one, and the pick is
1364/// what an export writes into the file -- so a pick that stayed put would
1365/// silently change which track the next export carries. Every relation
1366/// between the pick and the row that went, on a list of three.
1367#[test]
1368fn removing_a_subtitle_row_carries_the_pick_with_it() {
1369 // A row *before* the pick: the same track stays picked, one index down.
1370 assert_eq!(sub_pick_after_removal(2, 0, 2), 1);
1371 assert_eq!(sub_pick_after_removal(2, 1, 2), 1);
1372 // A row *after* it: the pick has not moved and neither has its index.
1373 assert_eq!(sub_pick_after_removal(0, 2, 2), 0);
1374 assert_eq!(sub_pick_after_removal(1, 2, 2), 1);
1375 // The picked row itself: the one that slid into its place...
1376 assert_eq!(sub_pick_after_removal(1, 1, 2), 1);
1377 // ...and the last row when the picked one was the last, since there is
1378 // nothing after it to slide.
1379 assert_eq!(sub_pick_after_removal(2, 2, 2), 1);
1380 // The last row of all: an emptied list is legal for subtitles, and the
1381 // section is not drawn at all at that point.
1382 assert_eq!(sub_pick_after_removal(0, 0, 0), 0);
1383}
1384
1385/// The same claim from the click's end, on the order imports actually
1386/// arrive in: two films opened one after the other and an `.srt` dropped
1387/// last interleave in the flat list, and the display reorders them. What a
1388/// click sets is the row's own `track`, so the *n*th row on screen has to
1389/// pick the track it shows and the echoes have to name that same file.
1390#[test]
1391fn a_click_on_a_regrouped_row_picks_the_track_that_row_shows() {
1392 let tracks = [
1393 sub("/films/a.mkv", Some(1), "eng"),
1394 sub("/films/b.mkv", Some(1), "eng"),
1395 sub("/films/a.mkv", Some(2), "fre"),
1396 sub("/subs/late.srt", None, "late.srt"),
1397 sub("/films/b.mkv", Some(3), "ger"),
1398 ];
1399 let rows: Vec<_> = subtitle_rows(&tracks)
1400 .into_iter()
1401 .flat_map(|group| {
1402 group
1403 .rows
1404 .into_iter()
1405 .map(move |row| (group.path.clone(), row))
1406 })
1407 .collect();
1408 // Read top to bottom, the rows are no longer in add order...
1409 assert_eq!(
1410 rows.iter().map(|(_, row)| row.track).collect::<Vec<_>>(),
1411 [0, 2, 1, 4, 3]
1412 );
1413 for (path, row) in &rows {
1414 // ...and what the click writes into `sub_track` -- and a save into
1415 // the `.edith` -- still lands on the track the row is showing.
1416 let picked = &tracks[row.track];
1417 assert_eq!(&picked.path, path, "row {} picks another file", row.track);
1418 assert_eq!(lang_human(&picked.label), row.label);
1419 // And the heading, the strip and the notice name that same file
1420 // back, so a click cannot leave the echoes pointing elsewhere.
1421 let echo = sub_pick_name(&tracks, row.track).expect("the row's own track");
1422 let stem = path.file_stem().expect("a fixture path").to_string_lossy();
1423 assert!(
1424 echo.contains(&*stem),
1425 "picked {}, echoed {echo}",
1426 path.display()
1427 );
1428 }
1429}
1430
1431/// "und" is what a muxer writes when nobody said what the language is. A
1432/// row showing it verbatim names a language nobody speaks.
1433#[test]
1434fn an_untagged_language_says_it_is_unknown() {
1435 assert_eq!(lang_human("und"), "unknown language");
1436 assert_eq!(lang_human("eng"), "eng");
1437 assert_eq!(lang_human("fre — Commentary"), "fre — Commentary");
1438 // Reaching the subtitle rows too: a track whose only name was the tag.
1439 let groups = subtitle_rows(&[sub("/films/a.mkv", Some(1), "und")]);
1440 assert_eq!(groups[0].rows[0].label, "unknown language");
1441 // The pair, read as the pair: the row title comes off `language` and
1442 // `name` and never out of the flattened label, which is what let an
1443 // "und" beside a title through as a language nobody speaks. A refused
1444 // track states neither and keeps its label.
1445 let titled = |language: &str, name: &str, label: &str| engine::subtitle::SubtitleTrack {
1446 path: PathBuf::from("/films/a.mkv"),
1447 track: Some(1),
1448 language: language.into(),
1449 name: name.into(),
1450 label: label.into(),
1451 cues: Vec::new(),
1452 bitmap: false,
1453 refused: None,
1454 };
1455 for (language, name, label, title) in [
1456 ("fra", "Signs", "fra — Signs", "fra — Signs"),
1457 ("und", "Signs", "Signs", "Signs"),
1458 ("und", "", "und", "unknown language"),
1459 ("", "late.srt", "late.srt", "late.srt"),
1460 ("", "", "eng", "eng"),
1461 ] {
1462 let rows = subtitle_rows(&[titled(language, name, label)]);
1463 assert_eq!(rows[0].rows[0].label, title, "{language:?} {name:?}");
1464 }
1465}
1466
1467/// The bug: an empty timeline is end-of-stream from its one black frame
1468/// onward, so the pump had `done` set before anything was ever pressed --
1469/// and the transport's restart branch read that as "played out, start from
1470/// the top". It started a clock against a zero-length timeline, which was
1471/// `done` again by the next repaint, so every further press restarted it
1472/// too: the button read "Pause" and no press of it ever paused.
1473///
1474/// What holds it now is one predicate, checked here against real sessions
1475/// on both sides -- the emptied one refuses, a timeline with clips on it
1476/// does not.
1477#[test]
1478fn an_empty_timeline_has_nothing_to_play() {
1479 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1480 // Silent like the engine suite: this opens the real device.
1481 session.set_gain(0.0);
1482 // A timeline with clips on it plays, and always did: the guard must not
1483 // touch that side.
1484 assert!(!session.is_empty());
1485 assert!(!nothing_to_play(Some(&session)));
1486
1487 // Every clip taken off, which is a state and not a failure.
1488 while session.delete_clip(Lane::V1, 0) {}
1489 while session.delete_clip(Lane::A1, 0) {}
1490 assert!(session.is_empty(), "the timeline is empty");
1491 assert_eq!(session.timeline_duration(), 0.0);
1492
1493 // What the pump does every render, and what set `done` before the fix:
1494 // the black frame goes by and the session is at its end at once.
1495 for _ in 0..40 {
1496 while session.try_frame().is_some() {}
1497 std::thread::sleep(Duration::from_millis(10));
1498 }
1499 assert!(
1500 session.is_eos(),
1501 "an empty timeline is done before it starts"
1502 );
1503
1504 // So the press is refused rather than sent down the restart branch --
1505 // and with no session at all it is the same refusal.
1506 assert!(nothing_to_play(Some(&session)));
1507 assert!(nothing_to_play(None));
1508 assert!(!session.is_playing(), "and nothing was started");
1509}
1510
1511/// The slider writes the same numbers the keys do, and mute is not one of
1512/// them: dragging while muted picks the level unmuting comes back to.
1513#[test]
1514fn the_slider_lands_on_the_grid_the_keys_move_on() {
1515 let mut volume = Volume::default();
1516 // Both ends exactly, and clamped past them.
1517 volume.set_along(0.);
1518 assert_eq!(volume.gain(), 0.0);
1519 assert_eq!(volume.label(), "Vol 0%");
1520 volume.set_along(1.5);
1521 assert_eq!(volume.gain(), 1.0);
1522 assert_eq!(volume.along(), 1.0);
1523
1524 // Halfway is 50%, and a key press from there is 5% -- the same step
1525 // count as before, on a finer grid.
1526 volume.set_along(0.5);
1527 assert_eq!(volume.label(), "Vol 50%");
1528 volume.step(true);
1529 assert_eq!(volume.label(), "Vol 55%");
1530 volume.step(false);
1531 assert_eq!(volume.gain(), 0.5);
1532
1533 // A number no step lands on comes back as the nearest one, so the label
1534 // and the fill are the same value the device was handed.
1535 volume.set_along(0.333);
1536 assert_eq!(volume.label(), "Vol 33%");
1537 assert_eq!(volume.along(), 0.33);
1538
1539 // Muted, the drag moves the level and nothing comes out.
1540 volume.muted = true;
1541 volume.set_along(0.8);
1542 assert_eq!(volume.gain(), 0.0);
1543 assert_eq!(volume.label(), "Muted 80%");
1544 volume.muted = false;
1545 assert_eq!(volume.gain(), 0.8);
1546}
1547
1548/// The slider lands where it paints: the arithmetic `Player::drag_volume`
1549/// runs over the bar's own painted width, which is the one thing a test of
1550/// it can share without re-deriving it.
1551#[test]
1552fn the_volume_slider_lands_where_it_paints() {
1553 let bar = Bounds {
1554 origin: point(px(420.), px(508.)),
1555 size: size(px(VOLUME_W), px(CONTROL_H)),
1556 };
1557 let at = |x: f32| {
1558 let mut volume = Volume::default();
1559 volume.set_along(frac_along(px(x), bar));
1560 volume
1561 };
1562 assert_eq!(at(420.).gain(), 0.0, "the left end is silence");
1563 assert_eq!(at(420. + VOLUME_W).gain(), 1.0, "the right end is full");
1564 assert_eq!(at(-4000.).gain(), 0.0, "off the left clamps");
1565 assert_eq!(at(9999.).gain(), 1.0, "off the right clamps");
1566 // Every pixel along it: a level the keys could also reach, painted back
1567 // where the hand pressed to within the half step the rounding costs.
1568 for step in 0..=(VOLUME_W as u32) {
1569 let along = step as f32 / VOLUME_W;
1570 let volume = at(420. + along * VOLUME_W);
1571 let painted = volume.along();
1572 let slack = 0.5 / f32::from(Volume::MAX_STEPS) + 1e-4;
1573 assert!(
1574 (painted - along).abs() <= slack,
1575 "pressed at {along}, paints at {painted}"
1576 );
1577 }
1578}
1579
1580/// Darkroom lane heads dispatch only verbs that apply to the lane under the
1581/// pointer; source checks pin the visible pointer doors to that guarded path.
1582#[test]
1583fn darkroom_lane_header_verbs_are_targeted_and_visible() {
1584 let live = Ctx {
1585 timeline: true,
1586 ..Ctx::default()
1587 };
1588 assert_eq!(enable_lane(ActionId::Mix, Lane::A1, live), Enable::Yes);
1589 assert_eq!(
1590 enable_lane(ActionId::RemoveVideoLane, Lane::V1, live),
1591 Enable::Yes
1592 );
1593 assert_eq!(
1594 enable_lane(ActionId::RemoveAudioLane, Lane::A1, live),
1595 Enable::Yes
1596 );
1597 assert!(matches!(
1598 enable_lane(ActionId::Mix, Lane::V1, live),
1599 Enable::Hidden(_)
1600 ));
1601
1602 let bench = src_text("ui/bench_stance.rs");
1603 for door in [
1604 "\"bench-mix-lane\"",
1605 "\"bench-show-sub-lane\"",
1606 "\"bench-remove-lane\"",
1607 "this.act_lane(ActionId::Mix, lane, cx)",
1608 "this.show_sub_lane(lane, cx)",
1609 "this.act_lane(action, lane, cx)",
1610 ] {
1611 assert!(bench.contains(door), "lane header lost {door}");
1612 }
1613 let time_band = src_text("ui/timeband_stance.rs");
1614 for door in [
1615 "fn volume_slider(",
1616 "\"stance-tb-volume-bar\"",
1617 "this.drag_volume(event.position.x, cx)",
1618 ".child(volume_slider(player, cx))",
1619 ] {
1620 assert!(time_band.contains(door), "time band lost {door}");
1621 }
1622}
1623
1624/// The three seams a hand may move, and the two ends neither of them may be
1625/// dragged past: a panel dragged to nothing is a panel nobody can get back, and
1626/// a picture squeezed out by its two neighbours is that same loss from the
1627/// other side of the window.
1628#[test]
1629fn a_dragged_divider_stops_before_either_panel_disappears() {
1630 use crate::ui::theme::INSPECTOR_MIN_W;
1631 use crate::{
1632 SIDE_MAX_FRAC, SPLIT_W, Split, TIMELINE_MAX_SHARE, TOOLBAR_H, inspector_w, library_w,
1633 split_drag_size, split_size, timeline_fixed_h, timeline_h,
1634 };
1635 use gpui::{point, px, size};
1636
1637 let window = size(px(1280.), px(720.));
1638 // Untouched, every region is still the share the window gives it. The
1639 // timeline's answer is stated for both of its faces: the timeline fits
1640 // the bed with nothing to scroll to, and zoomed in past that line the
1641 // strip's row joins the furniture.
1642 assert_eq!(
1643 split_size(Split::Library, None, 2, window, false),
1644 library_w(1280.)
1645 );
1646 assert_eq!(
1647 split_size(Split::Inspector, None, 2, window, false),
1648 inspector_w(1280.)
1649 );
1650 assert_eq!(
1651 split_size(Split::Timeline, None, 2, window, false),
1652 timeline_h(2, false).min(720. * TIMELINE_SHARE)
1653 );
1654 assert_eq!(
1655 split_size(Split::Timeline, None, 2, window, true),
1656 timeline_h(2, true).min(720. * TIMELINE_SHARE)
1657 );
1658 // Dragged, it is what the hand asked for...
1659 assert_eq!(
1660 split_size(Split::Library, Some(300.), 2, window, false),
1661 300.
1662 );
1663 assert_eq!(
1664 split_size(Split::Timeline, Some(300.), 2, window, false),
1665 300.
1666 );
1667 // ...and never past either end of it.
1668 assert_eq!(
1669 split_size(Split::Library, Some(0.), 2, window, false),
1670 LIBRARY_MIN_W
1671 );
1672 assert_eq!(
1673 split_size(Split::Library, Some(9000.), 2, window, false),
1674 1280. * SIDE_MAX_FRAC
1675 );
1676 assert_eq!(
1677 split_size(Split::Inspector, Some(-40.), 2, window, false),
1678 INSPECTOR_MIN_W
1679 );
1680 // The timeline's own floor is a floor with a whole lane *drawn* in it. At
1681 // that height the column shows one row of a two-track project, so the line
1682 // saying the rest are below is drawn too -- out of the region's pixels,
1683 // not out of the lane's. Left unbudgeted the header came out 27 px of its
1684 // 48 and the track's name, its subtitle dot and its × were cut in half.
1685 // Stated for the strip-bearing face, the taller of the two -- that is the
1686 // one the clamp has to hold at the 640x360 floor.
1687 let floor = split_size(Split::Timeline, Some(0.), 2, window, true);
1688 assert_eq!(floor, timeline_fixed_h(true) + LANE_H + LABEL_H + 8.);
1689 // The same arithmetic the timeline lays the column out with
1690 // ([`Player::timeline`]): what the affordance costs comes off the box, and
1691 // a whole lane is still standing under it.
1692 let lanes_box = floor - timeline_fixed_h(true);
1693 assert!(lanes_box < lanes_h(2), "no line to pay for at the floor");
1694 assert!(
1695 lanes_box - LABEL_H - 8. >= LANE_H,
1696 "the floor leaves {} px for a {LANE_H} px lane",
1697 lanes_box - LABEL_H - 8.
1698 );
1699 // A lone track has nothing below it and pays nothing for the line -- the
1700 // floor is a floor, not a reserved corridor.
1701 assert_eq!(
1702 split_size(Split::Timeline, Some(0.), 1, window, true),
1703 timeline_fixed_h(true) + LANE_H
1704 );
1705 // A size dragged with one track and kept while a second arrives is raised
1706 // to the new floor as it is read, not silently drawn under it.
1707 assert_eq!(
1708 split_size(Split::Timeline, Some(126.), 2, window, true),
1709 floor
1710 );
1711 // And the floor still fits the share the shortest window gives the region.
1712 assert!(floor <= 360. * TIMELINE_SHARE, "{floor} px will not fit");
1713 assert_eq!(
1714 split_size(Split::Timeline, Some(9000.), 2, window, true),
1715 720. * TIMELINE_MAX_SHARE
1716 );
1717 // A window too narrow to honour both ends keeps the floor rather than
1718 // panicking inside `clamp`, which is what a ceiling under its own floor
1719 // does.
1720 let narrow = size(px(600.), px(360.));
1721 assert_eq!(
1722 split_size(Split::Inspector, Some(9000.), 2, narrow, false),
1723 INSPECTOR_MIN_W
1724 );
1725
1726 // The pointer turned into a size: the panel follows the hand, and the two
1727 // that do not start at the window's own edge are measured from the far one.
1728 // Half a strip off each, because the strip is grabbed by its middle.
1729 assert_eq!(
1730 split_drag_size(Split::Library, point(px(300.), px(400.)), window),
1731 300. - SPLIT_W / 2.
1732 );
1733 assert_eq!(
1734 split_drag_size(Split::Inspector, point(px(1000.), px(400.)), window),
1735 280. - SPLIT_W / 2.
1736 );
1737 // The seam sits above the fixed toolbar, so what the pointer leaves under
1738 // it is that strip and the timeline together.
1739 assert_eq!(
1740 split_drag_size(Split::Timeline, point(px(300.), px(500.)), window),
1741 220. - TOOLBAR_H - SPLIT_W / 2.
1742 );
1743}
1744
1745/// The darkroom's own two seams (`Split::Dock`, `Split::Bench`): a hand may
1746/// not drag either past its floor or its ceiling, the same promise
1747/// [`a_dragged_divider_stops_before_either_panel_disappears`] makes for the
1748/// legacy three.
1749#[test]
1750fn the_darkroom_seams_stop_before_either_side_disappears() {
1751 use crate::ui::theme::INSPECTOR_MIN_W;
1752 use crate::{
1753 BENCH_MIN_H, SIDE_MAX_FRAC, SPLIT_W, Split, split_bounds, split_drag_size, split_size,
1754 };
1755 use gpui::{point, px, size};
1756
1757 let window = size(px(1280.), px(720.));
1758 // Untouched, each answers its own stance default.
1759 assert_eq!(
1760 split_size(Split::Dock, None, 2, window, false),
1761 crate::ui::stance::DOCK_W
1762 );
1763 assert_eq!(
1764 split_size(Split::Bench, None, 2, window, false),
1765 crate::ui::stance::BENCH_H
1766 );
1767 // Dragged, it is what the hand asked for...
1768 assert_eq!(split_size(Split::Dock, Some(400.), 2, window, false), 400.);
1769 assert_eq!(split_size(Split::Bench, Some(300.), 2, window, false), 300.);
1770 // ...and never past the floor...
1771 assert_eq!(
1772 split_size(Split::Dock, Some(0.), 2, window, false),
1773 INSPECTOR_MIN_W
1774 );
1775 assert_eq!(
1776 split_size(Split::Bench, Some(0.), 2, window, false),
1777 BENCH_MIN_H
1778 );
1779 // ...nor the ceiling. The bench's is not a window-share one -- it leaves
1780 // the screen and time band a fixed 160px, [`split_bounds`]'s own reason.
1781 assert_eq!(
1782 split_size(Split::Dock, Some(9000.), 2, window, false),
1783 1280. * SIDE_MAX_FRAC
1784 );
1785 let (_, bench_max) = split_bounds(Split::Bench, 2, window, false);
1786 assert_eq!(
1787 split_size(Split::Bench, Some(9000.), 2, window, false),
1788 bench_max
1789 );
1790 assert!(bench_max < 720.);
1791 // The pointer turned into a size, half a strip off for the same reason
1792 // the legacy seams read it that way.
1793 assert_eq!(
1794 split_drag_size(Split::Dock, point(px(1000.), px(400.)), window),
1795 280. - SPLIT_W / 2.
1796 );
1797 assert_eq!(
1798 split_drag_size(Split::Bench, point(px(300.), px(500.)), window),
1799 220. - crate::ui::stance::LEDGER_H - SPLIT_W / 2.
1800 );
1801}
1802
1803/// At the bench's floor, both default lanes' rows actually fit inside the
1804/// `bench-lanes` column `bench_stance::render` gives them -- not just each
1805/// row's own clamped height, but their *sum plus the gap between them*,
1806/// since `bench-lanes` scrolls rather than clipping visibly and a sum that
1807/// overruns the column loses its bottom row's pixels off-screen, unscrolled
1808/// (this session's F1: the A1 lane's clip-bar border and status dot, cut by
1809/// ~2px at the old `BENCH_MIN_H = 80.`).
1810#[test]
1811fn both_default_lanes_fit_the_bench_at_its_floor() {
1812 use crate::BENCH_MIN_H;
1813 use crate::ui::bench_stance::{LANE_MIN_H, ROW_GAP, RULER_H, row_h};
1814 use crate::ui::stance::BENCH_CHROME_H;
1815
1816 let box_h = BENCH_MIN_H - BENCH_CHROME_H;
1817 let avail = box_h - RULER_H - ROW_GAP;
1818 let h = row_h(2, avail);
1819 // Not an exact `LANE_MIN_H` any more: `BENCH_MIN_H` now carries one spare
1820 // row (`layout::LEDGER_SEAM_CLEARANCE`) so the last lane's own last pixel
1821 // never shares a row with the ledger's border, which lands here as
1822 // `avail` being a touch over the two-rows-plus-gap tight fit.
1823 assert!(
1824 h >= LANE_MIN_H,
1825 "the floor should give both lanes at least their own minimum ({h} < {LANE_MIN_H})"
1826 );
1827 let content = 2. * h + ROW_GAP;
1828 assert!(
1829 content <= avail + 1e-4,
1830 "the two lane rows ({content}px) overrun the column ({avail}px) -- \
1831 the bottom lane's pixels get cut, unscrolled"
1832 );
1833}
1834
1835/// `BENCH_CHROME_H` on its own: the previous test's `box_h = BENCH_MIN_H -
1836/// BENCH_CHROME_H` line trusts `BENCH_CHROME_H` to already be correct, so it
1837/// cannot catch `BENCH_CHROME_H` itself drifting -- which is exactly how the
1838/// third clip (this session's) survived it: the constant undercounted the
1839/// section head's real line box by 1px and this test's predecessor never
1840/// looked. Recomputes what `ui::stance::bench` actually draws above
1841/// `bench_stance::render`'s content -- the div's own `.border_t_1()` (1px)
1842/// + its `py(4.)` top padding + the section head's real line box at gpui's
1843/// golden-ratio line-height, not the label's bare font size (the same trap
1844/// `a_lane_row_fits_what_its_own_head_draws` already checks for the lane
1845/// heads) -- and then checks the *whole* stack -- chrome, ruler, both gaps,
1846/// both lanes, and the clear row the ledger's own fixed-position border
1847/// needs (`LEDGER_SEAM_CLEARANCE`, not exported, so this recomputes it as
1848/// `BENCH_MIN_H` minus every other named term) -- fits inside `BENCH_MIN_H`
1849/// with nothing left over uncounted. This binary carries no `TestAppContext`
1850/// to mount `ui::stance::bench` and `ui::stance::ledger` for real and read
1851/// painted bounds back, so it stays geometry-only, same as its neighbours.
1852#[test]
1853fn the_whole_bench_stack_fits_its_own_floor_with_the_ledger_seam_clear() {
1854 use crate::BENCH_MIN_H;
1855 use crate::ui::bench_stance::{LANE_MIN_H, ROW_GAP, RULER_H};
1856 use crate::ui::stance::BENCH_CHROME_H;
1857 use crate::ui::type_scale::SECTION_HEAD_PX;
1858
1859 const BENCH_BORDER_T: f32 = 1.;
1860 const BENCH_PY_TOP: f32 = 4.;
1861 let section_head_line_h = (SECTION_HEAD_PX * 1.618_034).round();
1862 let real_chrome = BENCH_BORDER_T + BENCH_PY_TOP + section_head_line_h;
1863 assert_eq!(
1864 BENCH_CHROME_H, real_chrome,
1865 "BENCH_CHROME_H ({BENCH_CHROME_H}) does not match what `stance::bench` \
1866 actually draws above the content ({real_chrome}px: {BENCH_BORDER_T}px \
1867 border + {BENCH_PY_TOP}px padding + {section_head_line_h}px label line \
1868 box) -- bench_stance::render gets handed the wrong box_h and lays its \
1869 rows out past its own real space"
1870 );
1871
1872 // The ledger's own fixed-position border needs one more clear row below
1873 // the last lane, on top of chrome + ruler + both gaps + both lanes --
1874 // recomputed here rather than importing the private
1875 // `layout::LEDGER_SEAM_CLEARANCE`, so this test fails if that term is
1876 // ever silently dropped from `BENCH_MIN_H`'s own sum.
1877 let content_need = real_chrome + RULER_H + ROW_GAP + 2. * LANE_MIN_H + ROW_GAP;
1878 let ledger_seam_clearance = BENCH_MIN_H - content_need;
1879 assert!(
1880 ledger_seam_clearance >= 1. - 1e-4,
1881 "BENCH_MIN_H ({BENCH_MIN_H}) leaves only {ledger_seam_clearance}px \
1882 between the last lane row and the ledger's own top border -- driven \
1883 at exactly the content's need (0px clearance) the border still won \
1884 the shared pixel and clipped the last lane's status dot"
1885 );
1886}
1887
1888/// The previous test asserted lane ROWS fit the bench column -- not that a
1889/// lane's own CONTENT fits its row, which is how the defect it fixed
1890/// survived it: at the old `LANE_MIN_H` of `18.` both lanes fit the bench
1891/// exactly while V1's status dot silently overflowed into A1's row (masked)
1892/// and A1's overflowed into the ledger (visible, since A1 has no next row).
1893/// This binary carries no `TestAppContext` to mount a real `lane_row` and
1894/// read its painted bounds back, so this recomputes the label's own line
1895/// box from the constants `lane_row` actually draws with (gpui's default
1896/// `TextStyle::line_height` is the golden ratio, not 1x the font size --
1897/// see `LANE_MIN_H`'s own doc comment) rather than a literal, so a future
1898/// shrink of `LANE_MIN_H` or growth of the label size fails this instead of
1899/// silently clipping the last lane again.
1900#[test]
1901fn a_lane_row_fits_what_its_own_head_draws() {
1902 use crate::ui::bench_stance::{LANE_DOT_D, LANE_HEAD_GAP, LANE_MIN_H};
1903 use crate::ui::type_scale::CHORD_METADATA_MIN_PX;
1904
1905 let label_line_h = (CHORD_METADATA_MIN_PX * 1.618_034).round();
1906 let content = label_line_h + LANE_HEAD_GAP + LANE_DOT_D;
1907 assert!(
1908 LANE_MIN_H >= content,
1909 "LANE_MIN_H ({LANE_MIN_H}) is shorter than what a lane head actually \
1910 draws ({content}px: {label_line_h}px label line box + \
1911 {LANE_HEAD_GAP}px gap + {LANE_DOT_D}px dot) -- the status dot \
1912 would spill past the row, invisible until it is the last lane \
1913 with no next row to spill into"
1914 );
1915}
1916
1917/// A round trip through the file: what is saved is what the next load reads
1918/// back, all five seams touched -- a scratch path, not the real config, the
1919/// same isolation `keymap::tests`' own `load_from`/`save_to` already takes.
1920/// One of the five is written past its own ceiling (the library, past
1921/// `SIDE_MAX_FRAC` of the window it is loaded back into): a file written at
1922/// a wider window must not hand a narrower one an illegal layout, so the
1923/// load clamps it back down rather than reading it verbatim.
1924#[test]
1925fn a_saved_seam_survives_a_reload() {
1926 use crate::{
1927 BENCH_MIN_H, SIDE_MAX_FRAC, Split, Splits, load_stance_splits_from, save_stance_splits_to,
1928 };
1929 use gpui::{Pixels, Size, px, size};
1930
1931 let dir = engine::scratch::Scratch::dir("edith-stance-splits");
1932 let path = dir.join("stance-splits");
1933 let window: Size<Pixels> = size(px(1280.), px(720.));
1934
1935 let mut splits = Splits::default();
1936 splits.set(Split::Library, 9000.);
1937 splits.set(Split::Inspector, 200.);
1938 splits.set(Split::Timeline, 250.);
1939 splits.set(Split::Dock, 333.);
1940 splits.set(Split::Bench, 200.);
1941 save_stance_splits_to(&splits, &path);
1942 let loaded = load_stance_splits_from(&path, window);
1943 assert_eq!(
1944 loaded.get(Split::Library),
1945 Some(1280. * SIDE_MAX_FRAC),
1946 "a library past its own ceiling should clamp to it on load"
1947 );
1948 assert_eq!(loaded.get(Split::Inspector), Some(200.));
1949 assert_eq!(loaded.get(Split::Timeline), Some(250.));
1950 assert_eq!(loaded.get(Split::Dock), Some(333.));
1951 assert_eq!(loaded.get(Split::Bench), Some(200.));
1952
1953 // A bench saved below its own floor clamps up to it, the same ceiling
1954 // logic mirrored on the one seam whose bound is a minimum.
1955 let mut low_bench = Splits::default();
1956 low_bench.set(Split::Bench, 1.);
1957 save_stance_splits_to(&low_bench, &path);
1958 let loaded = load_stance_splits_from(&path, window);
1959 assert_eq!(loaded.get(Split::Bench), Some(BENCH_MIN_H));
1960}
1961
1962/// The guard [`crate::split_drag_owes_save`] runs at the moment a drag ends
1963/// with no further pointer event ever coming (`Player::drag_left_window`,
1964/// wired to a live `MouseExitEvent` a `TestAppContext`-less test binary
1965/// cannot raise -- see `tests/media.rs`'s own note on the same limit, and
1966/// the harness drive `D2` in this session's report for the wiring itself).
1967/// What *is* checkable here without a window: exactly the persisted
1968/// seams owe that save, the same set `Split::PERSISTED` already names, and a
1969/// drag that never started (`None`) owes nothing.
1970#[test]
1971fn only_the_persisted_seams_owe_a_save_when_a_drag_loses_the_window() {
1972 use crate::{Split, player::timeline_edit::split_drag_owes_save};
1973
1974 assert!(split_drag_owes_save(Some(Split::Dock)));
1975 assert!(split_drag_owes_save(Some(Split::Bench)));
1976 assert!(split_drag_owes_save(Some(Split::Library)));
1977 assert!(split_drag_owes_save(Some(Split::Inspector)));
1978 assert!(split_drag_owes_save(Some(Split::Timeline)));
1979 assert!(!split_drag_owes_save(None));
1980}
1981
1982/// A missing file leaves every region at its default -- the silent fallback
1983/// `load_stance_splits`'s doc comment promises.
1984#[test]
1985fn a_missing_stance_splits_file_leaves_every_region_at_its_default() {
1986 use crate::{Split, load_stance_splits_from};
1987 use gpui::{Pixels, Size, px, size};
1988
1989 let dir = engine::scratch::Scratch::dir("edith-stance-splits-missing");
1990 let window: Size<Pixels> = size(px(1280.), px(720.));
1991 let splits = load_stance_splits_from(&dir.join("nothing-here"), window);
1992 assert_eq!(splits.get(Split::Library), None);
1993 assert_eq!(splits.get(Split::Inspector), None);
1994 assert_eq!(splits.get(Split::Timeline), None);
1995 assert_eq!(splits.get(Split::Dock), None);
1996 assert_eq!(splits.get(Split::Bench), None);
1997}
1998
1999/// Every seam in the main layout has a handle on it, and every region draws
2000/// itself at the size that handle sets: a region still measuring itself off the
2001/// window's own share is a panel whose divider moves nothing.
2002#[test]
2003fn every_seam_in_the_layout_has_a_divider_on_it() {
2004 // The darkroom collapsed Library/Inspector/Timeline into rooms with no
2005 // seam of their own; render.rs no longer draws any divider at all --
2006 // ui::stance::render is the whole root now -- so the only two seams a
2007 // hand can still drag are the ones the stance itself owns.
2008 let stance = src_text("ui/stance.rs");
2009 for split in ["Split::Dock", "Split::Bench"] {
2010 assert!(
2011 stance.contains(&format!("divider({split}")),
2012 "{split} has no divider to drag"
2013 );
2014 }
2015 // The strip is drawn wide enough to hit and says which way it moves --
2016 // an invisible hairline is a feature nobody finds.
2017 let interact = src_text("interact.rs");
2018 assert!(
2019 interact.contains("cursor_col_resize") && interact.contains("cursor_row_resize"),
2020 "a divider with no resize cursor on it"
2021 );
2022 // ...and nothing lays a region out off the untouched share any more:
2023 // the legacy panels that read `library_w`/`inspector_w` (`ui/library.rs`,
2024 // `ui/inspector.rs`, `ui/toolbar.rs`) are gone or gone from the render
2025 // path, so what remains is layout.rs's own Split::Library/Inspector
2026 // arms -- kept for save-file compat, never drawn.
2027 assert!(
2028 !src_text("render.rs").contains("library_w("),
2029 "render.rs still measures a panel with library_w("
2030 );
2031}
2032
2033/// DESIGN.md §12 step 2 as amended 2026-09-09 (user decision "option C"):
2034/// the stance skeleton draws its five regions -- screen, time band, bench,
2035/// ledger, dock -- in the order §5's diagram lays them out, and
2036/// `Player::render` actually reaches it when the flag is on. The sixth, the
2037/// 56px rail, is deleted -- the room root is centre | dock.
2038#[test]
2039fn the_stance_renders_its_five_regions_in_the_documented_order() {
2040 let stance = src_text("ui/stance.rs");
2041 let order = [
2042 "stance-screen",
2043 "stance-time-band",
2044 "stance-bench",
2045 "stance-ledger",
2046 "stance-dock",
2047 ];
2048 let defined: Vec<usize> = order
2049 .iter()
2050 .map(|id| {
2051 stance
2052 .find(&format!("\"{id}\""))
2053 .unwrap_or_else(|| panic!("no {id} region in the stance"))
2054 })
2055 .collect();
2056 assert!(
2057 defined.windows(2).all(|w| w[0] < w[1]),
2058 "the five regions are not defined in DESIGN §5's order: {defined:?}"
2059 );
2060
2061 // Defined in order is not composed in order -- `render()` has to call
2062 // them in it too, or the geometry above is dead prose.
2063 let render_body = &stance[stance
2064 .find("pub(crate) fn render(")
2065 .expect("the stance's entry point")..];
2066 // Open paren only, no close: DESIGN §12 steps 3 and 4 hand most of the
2067 // regions player/window state to read, so their call sites carry
2068 // arguments now. Order is what this asserts, not arity.
2069 let calls = [
2070 "screen(",
2071 "time_band(",
2072 "bench(",
2073 "ledger(",
2074 "dock(",
2075 ];
2076 let composed: Vec<usize> = calls
2077 .iter()
2078 .map(|c| {
2079 render_body
2080 .find(c)
2081 .unwrap_or_else(|| panic!("render() never calls {c}"))
2082 })
2083 .collect();
2084 assert!(
2085 composed.windows(2).all(|w| w[0] < w[1]),
2086 "render() does not compose the six regions in DESIGN §5's order: {composed:?}"
2087 );
2088
2089 // The skeleton is reached unconditionally now -- the darkroom is the
2090 // only room, and `self.darkroom`'s branch is gone with the legacy tree
2091 // it used to choose between.
2092 let render_rs = src_text("render.rs");
2093 assert!(
2094 render_rs.contains("ui::stance::render("),
2095 "render.rs no longer reaches ui::stance::render"
2096 );
2097 assert!(
2098 !render_rs.contains("self.darkroom"),
2099 "render.rs still branches on self.darkroom after the legacy tree was removed"
2100 );
2101}
2102
2103/// The picture is letterboxed, never stretched: both the picture region and
2104/// the subtitle picture overlay paint through [`letterboxed_image`] (the
2105/// `canvas()` element that hands `ObjectFit::Contain::get_bounds` a real
2106/// resolved size) rather than a plain `img().object_fit(...)`, which reads
2107/// right by hand but never gets a fitted box from taffy in this pin -- see
2108/// `render.rs`'s own doc comment on the function for the measured dead end.
2109/// A regression back to `img(...).object_fit(` in either caller is the
2110/// stretch-to-fill bug returning silently.
2111#[test]
2112fn the_picture_letterboxes_through_a_canvas_never_a_plain_img_object_fit() {
2113 let render_rs = src_text("render.rs");
2114 assert!(
2115 render_rs.contains("pub(crate) fn letterboxed_image"),
2116 "the letterbox helper moved or was renamed"
2117 );
2118 assert!(
2119 render_rs.contains("ObjectFit::Contain.get_bounds(bounds, image.size(0))"),
2120 "letterboxed_image no longer computes the Contain rect by hand"
2121 );
2122 for (file, needle) in [
2123 ("render.rs", "letterboxed_image(i)"),
2124 ("ui/preview.rs", "letterboxed_image(image)"),
2125 ] {
2126 let text = src_text(file);
2127 assert!(
2128 text.contains(needle),
2129 "{file} no longer paints through letterboxed_image"
2130 );
2131 assert!(
2132 !text.contains(".object_fit(gpui::ObjectFit::Contain)"),
2133 "{file} reintroduced the stretched img().object_fit(Contain) dead end"
2134 );
2135 }
2136}
2137
2138/// DESIGN §8: "No full-width bars, no covering the picture, ever." The
2139/// darkroom stance (`ui::stance::screen`) draws
2140/// [`Player::picture_area`](crate::Player::picture_area) directly, so a
2141/// notice surface that reaches into that method unconditionally reaches the
2142/// picture on the darkroom path too -- measured live covering the bottom 10%
2143/// of the frame (rows 300-333 of 335). The legacy full-width `notice_bar`
2144/// and its non-darkroom caller are gone with the rest of the old tree, and
2145/// the floating notice plate went after them (user 2026-08-27: the ledger's
2146/// own "last action" strip is the one notice channel now), so this pins
2147/// `picture_area` itself never growing a notice surface back.
2148#[test]
2149fn the_darkroom_path_never_lets_a_notice_surface_reach_the_picture() {
2150 // The ledger strip (`ui::stance::ledger` reading `notices.back()`) is
2151 // the only notice channel left, and the invariant is that
2152 // picture_area's body never draws one over the picture.
2153 let body = fn_body("picture_area");
2154 assert!(
2155 !body.contains("notice_bar"),
2156 "picture_area draws a notice surface over the picture again (the old occlusion defect)"
2157 );
2158}
2159
2160/// DESIGN §5/§11 check 6, the fourth occlusion defect (notice bar, export
2161/// card, preview badge, now menus): every floating menu that can open above
2162/// the picture -- the clip context menu, the picker -- must size its
2163/// scrolling list against `stance::menu_floor`'s room, not the raw window.
2164/// Sizing against the whole viewport is exactly the bug that shipped: a menu
2165/// taller than the bench/ledger/dock footprint got clamped by `menu_at`'s
2166/// own bottom-edge fit back up over the picture, because nothing had told
2167/// the list it only had the footprint to grow into. This pins the general
2168/// rule so the next surface someone floats -- a fourth menu, a fifth
2169/// occlusion -- cannot silently reintroduce `menu_rows_h(rows.len(),
2170/// viewport)` in its place.
2171///
2172/// The library menu is the deliberate exception (user 2026-08-27, "right
2173/// clicking a library media opens a menu in somewhere nonsense"): it anchors
2174/// to a pointer that is always inside the dock, where no picture exists to
2175/// protect, and `menu_floor`'s clamp teleported it down to the picture floor
2176/// -- so `ui/library.rs` must open at the pointer through `menu_at` alone,
2177/// and this guard pins that it never routes back through `menu_floor`.
2178#[test]
2179fn every_darkroom_menu_sizes_its_list_against_the_floor_room_not_the_raw_viewport() {
2180 for file in ["ui/overlays.rs"] {
2181 let text = src_text(file);
2182 assert!(
2183 !text.contains("menu_rows_h(rows.len(), viewport)"),
2184 "{file} sizes a menu's list against the raw viewport again -- \
2185 route it through stance::menu_floor's room instead, or a tall \
2186 menu will climb back over the picture"
2187 );
2188 let floors = text.matches("menu_floor(").count();
2189 let sizings = text.matches("menu_rows_h(rows.len(),").count();
2190 assert_eq!(
2191 floors, sizings,
2192 "{file} has a menu list-sizing call not paired with a menu_floor \
2193 call -- every darkroom menu must clamp both its anchor and its \
2194 list room together"
2195 );
2196 assert!(
2197 sizings > 0,
2198 "{file} no longer opens any menu -- update this guard"
2199 );
2200 }
2201 let library = src_text("ui/library.rs");
2202 assert!(
2203 !library.contains("menu_floor("),
2204 "ui/library.rs routes its menu through menu_floor's picture-floor \
2205 clamp again -- a right-click high in the dock teleports back down \
2206 to the picture floor (the 'menu in somewhere nonsense' defect)"
2207 );
2208 assert!(
2209 library.contains("menu_at(at, viewport, h)")
2210 && library.contains("point(menu.at.x, menu.at.y + px(ROW_CLEAR))"),
2211 "ui/library.rs no longer anchors its menu to the pointer -- one row \
2212 clear of it, so the menu cannot cover the row it names -- through \
2213 menu_at; update this guard"
2214 );
2215}
2216
2217/// The settings page's own organising rule: PROJECT rows open only the
2218/// doors that write into the `.edith` file ([`Player::open_picker`],
2219/// [`Player::open_mix`]), and EDITOR rows open only the doors that do not
2220/// ([`Player::toggle_proxies`], [`Player::toggle_auto_proxies`],
2221/// [`Player::open_subtitle_style`]) -- never the config-file writers
2222/// (`ui::dock_stance::config_path`/`ui::theme::config_path`/
2223/// `keymap::Keymap::config_path`) directly, which every editor-side row
2224/// already routes around through its own opener. A row wired to the wrong
2225/// section's opener is exactly the regression a page organised around two
2226/// headings invites; this pins each half to its own doors so the two lists
2227/// cannot cross.
2228#[test]
2229fn settings_project_and_editor_sections_open_disjoint_doors() {
2230 let source = src_text("ui/settings_stance.rs");
2231 let project_start = source
2232 .find("fn project_section(")
2233 .expect("the project section");
2234 let editor_start = source
2235 .find("fn editor_section(")
2236 .expect("the editor section");
2237 let render_start = source
2238 .find("pub(crate) fn render(")
2239 .expect("the page's render fn");
2240 assert!(
2241 project_start < editor_start && editor_start < render_start,
2242 "the three fns moved; this scan is blind"
2243 );
2244 let project_body = &source[project_start..editor_start];
2245 let editor_body = &source[editor_start..render_start];
2246
2247 // `Pick::Theme` is the one list that is nobody's project -- the palette
2248 // lives in ~/.config/edith like the subtitle font beside it (see
2249 // `menus.rs`'s own note on the variant), so its row is EDITOR's by the
2250 // same rule every other row here follows. The scan below is on the door
2251 // *string*, so the palette row is subtracted from the EDITOR body before
2252 // the project-door check runs rather than the check being loosened for
2253 // every picker.
2254 let editor_no_theme = editor_body.replace("open_picker(Pick::Theme", "");
2255 for door in ["open_picker(", "open_mix("] {
2256 assert!(
2257 project_body.contains(door),
2258 "PROJECT section no longer opens {door} -- update this guard"
2259 );
2260 assert!(
2261 !editor_no_theme.contains(door),
2262 "EDITOR section opens {door}, a project-file door -- that value belongs in PROJECT, not here"
2263 );
2264 }
2265 assert!(
2266 editor_body.contains("open_picker(Pick::Theme"),
2267 "the palette row left EDITOR -- it is a ~/.config preference, not a project value"
2268 );
2269 for door in [
2270 "toggle_proxies(",
2271 "toggle_auto_proxies(",
2272 "open_subtitle_style(",
2273 ] {
2274 assert!(
2275 editor_body.contains(door),
2276 "EDITOR section no longer opens {door} -- update this guard"
2277 );
2278 assert!(
2279 !project_body.contains(door),
2280 "PROJECT section opens {door}, an editor-only door -- that value belongs in EDITOR, not here"
2281 );
2282 }
2283 // Neither section writes a config file straight from a row: both go
2284 // through an opener, which is the one place a config-file write (the
2285 // subtitle style card's Save, this window's next project load) is
2286 // allowed to live.
2287 for path_fn in [
2288 "dock_stance::config_path",
2289 "theme::config_path",
2290 "Keymap::config_path",
2291 ] {
2292 assert!(
2293 !project_body.contains(path_fn),
2294 "PROJECT section touches {path_fn} directly"
2295 );
2296 assert!(
2297 !editor_body.contains(path_fn),
2298 "EDITOR section touches {path_fn} directly"
2299 );
2300 }
2301}
2302
2303/// D1's own class, pinned per row rather than per section: a row's hint can
2304/// claim a `~/.config/edith` default (the section header claims nothing on
2305/// its own since [`settings_project_and_editor_sections_open_disjoint_doors`]'s
2306/// commit, so a lying section head no longer slips past a reviewer -- but a
2307/// lying *row* hint did, on Proxies, because nothing scanned row text at all).
2308/// For every row whose own hint text names that file, this requires the
2309/// matching `save_*_pref`/`load_*_pref` pair to actually exist in
2310/// `player/library.rs` -- the exact gap Proxies shipped with: a hint promising
2311/// a default the row's own door never wrote.
2312#[test]
2313fn settings_row_hints_naming_config_edith_have_a_matching_pref_pair() {
2314 let source = src_text("ui/settings_stance.rs");
2315 let library = src_text("player/library.rs");
2316 // (row id, the stem its pref functions are named after)
2317 for (row_id, stem) in [
2318 ("settings-proxies", "proxies"),
2319 ("settings-auto-proxies", "auto_proxies"),
2320 ] {
2321 let row_start = source
2322 .find(&format!("\"{row_id}\""))
2323 .unwrap_or_else(|| panic!("{row_id} row moved or renamed -- update this guard"));
2324 let row_end = source[row_start..]
2325 .find(",\n ))")
2326 .map_or(source.len(), |i| row_start + i);
2327 let row_text = &source[row_start..row_end];
2328 if !row_text.contains("~/.config/edith") {
2329 continue;
2330 }
2331 for prefix in ["save_", "load_"] {
2332 let fn_name = format!("{prefix}{stem}_pref");
2333 assert!(
2334 library.contains(&format!("fn {fn_name}(")),
2335 "{row_id}'s hint claims a ~/.config/edith default but \
2336 player/library.rs has no `{fn_name}` -- the hint promises \
2337 storage the row does not have"
2338 );
2339 }
2340 }
2341}
2342
2343/// With no project open, a PROJECT row must not fall back to a bare noun
2344/// ("Size"/"Rate"/"HDR") standing in the value slot -- it reads as a value
2345/// while carrying none. This binary has no `TestAppContext` to actually
2346/// render the page with `player.session` empty, so this is a source scan
2347/// for the fallback strings the bug shipped as, same as the guard above it.
2348#[test]
2349fn settings_project_rows_have_no_bare_noun_placeholder() {
2350 let source = src_text("ui/settings_stance.rs");
2351 let project_start = source
2352 .find("fn project_section(")
2353 .expect("the project section");
2354 let editor_start = source
2355 .find("fn editor_section(")
2356 .expect("the editor section");
2357 let project_body = &source[project_start..editor_start];
2358 for placeholder in [
2359 "\"Size\".to_string()",
2360 "\"Rate\".to_string()",
2361 "\"HDR\".to_string()",
2362 ] {
2363 assert!(
2364 !project_body.contains(placeholder),
2365 "a PROJECT row fell back to the bare noun {placeholder} -- it reads as a value with no project open"
2366 );
2367 }
2368}
2369
2370/// The HDR reference rows must read the file's own declared numbers off
2371/// [`engine::colorspace::ContentLight`] -- not invent a monitor override the
2372/// engine has nowhere to persist -- and must fall back to the page's one
2373/// established empty state (a bare `—` in `INK4`, [`row_ink`]/[`row_static`]'s
2374/// own idiom) rather than a second placeholder idiom. No `TestAppContext`
2375/// here either, so this is the same source-scan the guard above it is.
2376#[test]
2377fn hdr_reference_rows_read_content_light_and_use_the_established_empty_state() {
2378 let source = src_text("ui/settings_stance.rs");
2379 let project_start = source
2380 .find("fn project_section(")
2381 .expect("the project section");
2382 let editor_start = source
2383 .find("fn editor_section(")
2384 .expect("the editor section");
2385 let project_body = &source[project_start..editor_start];
2386
2387 assert!(
2388 project_body.contains("settings-hdr-reference"),
2389 "the HDR reference row is missing"
2390 );
2391 assert!(
2392 project_body.contains("settings-content-light"),
2393 "the content-light row is missing"
2394 );
2395
2396 // Reads the real declared numbers, not an invented default or a fixed
2397 // string standing in for one.
2398 for field in ["mastering_max", "max_cll", "max_fall"] {
2399 assert!(
2400 project_body.contains(field),
2401 "the HDR reference rows do not read ContentLight::{field}"
2402 );
2403 }
2404
2405 // No override field exists on the engine side to write one into, so the
2406 // row must never claim a picker/opener the way every other PROJECT row
2407 // does -- it is built with `row_static`, not `row`/`row_ink`.
2408 assert!(
2409 project_body.contains("row_static(\n \"settings-hdr-reference\""),
2410 "the HDR reference row must be read-only (row_static), not a picker"
2411 );
2412 assert!(
2413 project_body.contains("row_static(\n \"settings-content-light\""),
2414 "the content-light row must be read-only (row_static), not a picker"
2415 );
2416
2417 // The established empty state: a bare "—" reused, never a second idiom
2418 // ("N/A", "None", "Unknown"...) invented for the same absence.
2419 assert!(
2420 project_body.contains("\"—\".to_string()"),
2421 "the HDR reference rows must reuse the page's own empty-state dash"
2422 );
2423}
2424/// The parity class this user has reported four separate times: "some
2425/// options are only reachable via keyboard shortcut". A source scan (this
2426/// binary has no `TestAppContext` to click through) over every darkroom
2427/// surface -- the dock, the bench/timeband transport, the
2428/// settings page, the maximized cards and the clip context menu
2429/// (`menus.rs`'s `MENU_ITEMS`, rendered mouse-and-chord-visible by
2430/// `overlays.rs`) -- for a literal `ActionId::<variant>` mention. An
2431/// [`ActionId`] reachable by chord ([`Keymap::defaults`]) but absent from
2432/// every one of those texts has no mouse door into the darkroom at all,
2433/// which is exactly this bug's shape (`Fit` and `Redo` shipped that way
2434/// until this commit).
2435///
2436/// [`ActionId::Resolution`] and [`ActionId::SubtitleStyle`] are the two
2437/// deliberate exceptions: their settings-page rows open them through
2438/// `Pick::Resolution` and `open_subtitle_style(cx)` respectively, never
2439/// spelling the action name itself, so each is matched on its own door
2440/// string instead.
2441///
2442/// Every action gets a persistent regional control or the context-menu row for
2443/// the thing it acts on. The four exemptions are independently-owned lane
2444/// parity work, named with their owners so a future removal cannot silently
2445/// turn any unrelated action back into keyboard-only.
2446#[test]
2447fn every_action_has_a_darkroom_widget_home_or_explicit_owner() {
2448 use crate::ActionId;
2449 const EXPLICITLY_OWNED_ELSEWHERE: &[(ActionId, &str)] = &[
2450 (
2451 ActionId::FocusPanels,
2452 "keyboard-only by design: a mouse already focuses whatever it \
2453 clicks, so a click-through door for \"move keyboard focus\" \
2454 has nothing to do that a click has not already done",
2455 ),
2456 (
2457 ActionId::Deselect,
2458 "clicking empty timeline space already clears the selection with the mouse; \
2459 bare escape is a keyboard-only accelerator for that existing door, not a new one",
2460 ),
2461 (
2462 ActionId::SelectNext,
2463 "clicking a clip already selects it with the mouse; `}` is a keyboard-only \
2464 accelerator for cycling that existing selection, not a new door -- legacy had no \
2465 toolbar button for it either",
2466 ),
2467 (
2468 ActionId::SelectPrev,
2469 "clicking a clip already selects it with the mouse; `{` is a keyboard-only \
2470 accelerator for cycling that existing selection, not a new door -- legacy had no \
2471 toolbar button for it either",
2472 ),
2473 // The group trio: a group is *made* with the pointer already --
2474 // ctrl-click the halves and the grammar is the selection itself
2475 // (DESIGN §9) -- so a row per verb in the clip menu was three rows
2476 // saying what the click had already said. Chords and KEYS rows keep
2477 // them reachable.
2478 (
2479 ActionId::Group,
2480 "made by ctrl-clicking the halves: the selection is the grammar",
2481 ),
2482 (
2483 ActionId::Detach,
2484 "made by ctrl-clicking the halves: the selection is the grammar",
2485 ),
2486 (
2487 ActionId::Regroup,
2488 "made by ctrl-clicking the halves: the selection is the grammar",
2489 ),
2490 // The keyboard's own trim: `^[` and `^]` do with a stroke what the
2491 // pointer does by dragging the clip edge to the spot it wants, and
2492 // that drag is the door -- a menu row for it would be a second name
2493 // for a gesture the bench already answers.
2494 (
2495 ActionId::TrimInToPlayhead,
2496 "the pointer's version is dragging the clip edge to the playhead",
2497 ),
2498 (
2499 ActionId::TrimOutToPlayhead,
2500 "the pointer's version is dragging the clip edge to the playhead",
2501 ),
2502 // The rail's own eighteen are gone from this list: the right-click
2503 // parity (DESIGN §5 as amended 2026-09-09, user decision "option C")
2504 // gave every one of them a door on the thing it acts on -- the clip
2505 // menu, the ruler's, the lane head's -- and the staleness check below
2506 // is what deleted their entries as each landed.
2507 (
2508 ActionId::Screenshot,
2509 "the picture the frame is written from is the *watched* frame and \
2510 nothing else is under the pointer to right-click for it: keyboard \
2511 and the KEYS card, like the selection accelerators above",
2512 ),
2513 ];
2514 let darkroom = [
2515 "ui/bench_stance.rs",
2516 "ui/cards.rs",
2517 "ui/dock_stance.rs",
2518 "ui/overlays.rs",
2519 "ui/settings_stance.rs",
2520 "ui/stance.rs",
2521 "ui/timeband_stance.rs",
2522 "menus.rs",
2523 ]
2524 .map(src_text)
2525 .join("\n");
2526 for action in ActionId::ALL {
2527 if let Some((_, owner)) = EXPLICITLY_OWNED_ELSEWHERE
2528 .iter()
2529 .find(|(owned, _)| *owned == action)
2530 {
2531 assert!(!owner.is_empty(), "ActionId::{action:?} needs an owner");
2532 // An exemption is a debt, not a licence: once the owning lane
2533 // has mounted the action, the entry has to go, or the sweep
2534 // goes blind on an action that is covered.
2535 assert!(
2536 !darkroom.contains(&format!("ActionId::{action:?}")),
2537 "ActionId::{action:?} has a darkroom home now -- delete its \
2538 EXPLICITLY_OWNED_ELSEWHERE entry ({owner})"
2539 );
2540 continue;
2541 }
2542 let name = format!("{action:?}");
2543 let mentioned = darkroom.contains(&format!("ActionId::{name}"))
2544 || (action == ActionId::Resolution && darkroom.contains("Pick::Resolution"))
2545 || (action == ActionId::SubtitleStyle && darkroom.contains("open_subtitle_style(cx)"));
2546 let hitmap_id = crate::ui::hitmap::action_id(action);
2547 assert_eq!(
2548 hitmap_id,
2549 format!("action.{name}"),
2550 "ActionId::{name} has a Darkroom widget home but no stable hitmap id"
2551 );
2552 assert!(
2553 mentioned,
2554 "ActionId::{name} is bound to a chord but has no visible affordance \
2555 anywhere in the darkroom tree -- either mount it or name the owning parity lane"
2556 );
2557 }
2558}
2559
2560/// Transition affordances must be painted and use the existing edit state:
2561/// fades own their drag handles, an active dissolve remains a mouse toggle,
2562/// and a carried lane names the exact slot `reorder_lane` will use.
2563#[test]
2564fn darkroom_bench_wires_transition_controls_and_lane_drop_cue() {
2565 let bench = src_text("ui/bench_stance.rs");
2566 let clip = &bench[bench.find("fn clip_box(").expect("the clip renderer")
2567 ..bench.find("fn sub_box(").expect("the subtitle renderer")];
2568 for needle in [
2569 "fade_wedge(true)",
2570 "fade_wedge(false)",
2571 "dissolve_glyph()",
2572 "this.start_fade_drag(lane, idx, is_in, event.position.x, cx)",
2573 "this.dissolve_selected(cx)",
2574 ] {
2575 assert!(
2576 clip.contains(needle),
2577 "the Darkroom clip lost its transition affordance: {needle}"
2578 );
2579 }
2580 let dissolve = &clip[clip
2581 .find(".when(dissolves, |d| {")
2582 .expect("the dissolve affordance")
2583 ..clip.find(".when(trims(span),").expect("the fade handles")];
2584 assert!(
2585 dissolve.contains(".w(px(FADE_HANDLE_W))"),
2586 "dissolve click target no longer matches fade-handle width"
2587 );
2588 assert!(
2589 dissolve.contains(".h(px(FADE_HANDLE_H))"),
2590 "dissolve click target no longer matches fade-handle height"
2591 );
2592 assert!(
2593 !dissolve.contains("h_full()"),
2594 "dissolve click target still covers the clip body"
2595 );
2596 assert!(
2597 !dissolve.contains(".w(px(scale"),
2598 "dissolve hit test still tracks transition width"
2599 );
2600
2601 let lane = &bench[bench.find("fn lane_row(").expect("the lane renderer")
2602 ..bench
2603 .find("pub(crate) fn render(")
2604 .expect("the bench renderer")];
2605 for needle in [
2606 "this.preview_lane_drop(event.drag(cx).0, lane, cx)",
2607 "this.forget_lane_drop(lane, cx)",
2608 ".lane_drop",
2609 "if drop.above",
2610 ] {
2611 assert!(
2612 lane.contains(needle),
2613 "the Darkroom lane lost its reorder feedback: {needle}"
2614 );
2615 }
2616}
2617
2618/// The pointer harness can only drive controls that report the bounds of the
2619/// element that owns the gesture. Keep every dynamic Darkroom entry surface
2620/// named, so UI verification never falls back to guessed pixels.
2621#[test]
2622fn hitmap_names_every_darkroom_pointer_entry_surface() {
2623 let bench = src_text("ui/bench_stance.rs");
2624 for needle in [
2625 "clip.{}.{}.{}.fade-{}",
2626 "clip.{}.{}.{}.trim-{}",
2627 "clip.{}.{}.{}.dissolve",
2628 "lane.{}.reorder",
2629 "lane.{}.mix",
2630 "lane.{}.eye",
2631 "lane.{}.remove",
2632 ] {
2633 assert!(
2634 bench.contains(needle),
2635 "bench control missing hitmap id: {needle}"
2636 );
2637 }
2638 assert!(
2639 bench.contains(".when(trims(span), |d| {"),
2640 "fade handles must cover video clips as well as audio clips"
2641 );
2642
2643 let dock = src_text("ui/dock_stance.rs");
2644 for needle in [
2645 "subtitle.{group_ord}.{track}.row",
2646 "subtitle.{group_ord}.{track}.select",
2647 "source.{i}.preview",
2648 "source.{i}.proxy",
2649 "Proxy making",
2650 ] {
2651 assert!(
2652 dock.contains(needle),
2653 "dock control missing hitmap contract: {needle}"
2654 );
2655 }
2656
2657 for (path, needles) in [
2658 (
2659 "ui/timeband_stance.rs",
2660 &[
2661 "timeline.contact-strip",
2662 "stance-strip-grip-lt",
2663 "stance-strip-grip-rb",
2664 ][..],
2665 ),
2666 ("ui/preview.rs", &["preview.stop", "preview.scrub"][..]),
2667 (
2668 "ui/overlays.rs",
2669 &[
2670 "menu.{action:?}",
2671 "menu.properties",
2672 "theme.{n}.row",
2673 "let enabled = refusal.yes()",
2674 "hitmap::dynamic(\n move || (format!(\"menu.{action:?}\"",
2675 ][..],
2676 ),
2677 (
2678 "ui/settings_stance.rs",
2679 &[".children(hitmap::control(id, label_text, !exporting))"][..],
2680 ),
2681 ] {
2682 let source = src_text(path);
2683 for needle in needles {
2684 assert!(
2685 source.contains(needle),
2686 "{path} missing hitmap contract: {needle}"
2687 );
2688 }
2689 }
2690}
2691
2692/// An external file drag (gpui `ExternalPaths`, Wayland `text/uri-list`) has
2693/// to be heard over the DOCK -- the Sources/library panel -- and not only
2694/// over the centre column: the dock is the centre's flex sibling, so the
2695/// handler `stance-centre` used to carry covered none of
2696/// the library panel, which is exactly the shipped "drag and drop file
2697/// import is not working on library panel" defect. The listener therefore
2698/// belongs to the room root (`stance-room`), above every region, and it must
2699/// route the dropped paths through `import` -- the same door the Import
2700/// action uses.
2701///
2702/// A scan, not a click: this crate has no gpui `VisualTestContext` harness
2703/// (nothing in `tests/` opens a window), and a drop cannot be simulated
2704/// without one -- the compositor half (`wl_data_device`) is out of reach of
2705/// the test process either way.
2706#[test]
2707fn an_external_file_drop_is_heard_by_the_whole_room_and_imports() {
2708 let stance = src_text("ui/stance.rs");
2709 let root_at = stance
2710 .find(".id(\"stance-room\")")
2711 .expect("no stance root div");
2712 let centre_at = stance
2713 .find(".id(\"stance-centre\")")
2714 .expect("no stance centre column");
2715 let drop_at = stance
2716 .find(".on_drop(cx.listener(|this, paths: &gpui::ExternalPaths")
2717 .expect("no external-file drop handler in the stance");
2718 assert!(
2719 drop_at > root_at && drop_at < centre_at,
2720 "the external drop handler is not on the room root -- \
2721 a drop over the dock's library panel is heard by nothing"
2722 );
2723 let body = &stance[drop_at..(drop_at + 700).min(stance.len())];
2724 assert!(
2725 body.contains("this.import(path, cx)"),
2726 "a dropped file does not go through the import door: {body}"
2727 );
2728 // ...and the library panel says so while the file is over it.
2729 let dock_at = stance.find(".id(\"stance-dock\")").expect("no dock div");
2730 let dock = &stance[dock_at..(dock_at + 700).min(stance.len())];
2731 assert!(
2732 dock.contains(".drag_over::<gpui::ExternalPaths>"),
2733 "the dock answers an external file drag with nothing: {dock}"
2734 );
2735}
2736
2737/// The wheel is the bench's, not a clip's: the user rolled it over the bench
2738/// and nothing moved unless the pointer happened to sit on a track, because
2739/// the only listeners were one per bed and one on the ruler strip. The row's
2740/// listener now sits on the whole row (head column included) and stops there,
2741/// and `bench-content` answers everything else -- the strip left of the ruler,
2742/// the ruler itself, the gaps between rows, the space below the last track.
2743/// Exactly two listeners, so no strip answers one notch twice.
2744#[test]
2745fn the_bench_answers_a_wheel_notch_anywhere_over_it() {
2746 let bench = src_text("ui/bench_stance.rs");
2747 assert_eq!(
2748 bench.matches(".on_scroll_wheel(").count(),
2749 2,
2750 "the bench has a wheel listener per region again -- a notch would be answered twice"
2751 );
2752 let row = bench
2753 .find(".id((\"bench-lane\", lane.ord")
2754 .expect("no lane row");
2755 let bed = bench.find(".id((\"bench-bed\"").expect("no lane bed");
2756 let row_wheel = bench[row..bed]
2757 .find(".on_scroll_wheel(")
2758 .map(|at| &bench[row + at..bed])
2759 .expect("the lane row does not answer the wheel -- only its bed does");
2760 assert!(
2761 row_wheel[..200].contains("cx.stop_propagation();")
2762 && row_wheel[..200].contains("this.timeline_wheel(event, cx)"),
2763 "the row's wheel lost the mapping or its stop: {}",
2764 &row_wheel[..200]
2765 );
2766 let content = bench
2767 .find(".id(\"bench-content\")")
2768 .expect("no bench content");
2769 let content_wheel = bench[content..]
2770 .find(".on_scroll_wheel(")
2771 .expect("the bench container does not answer the wheel");
2772 assert!(
2773 content_wheel < 700 && bench[content..].contains("this.timeline_wheel(event, cx)"),
2774 "the container's wheel listener is not on the container itself"
2775 );
2776 let ruler = bench.find(".id(\"bench-ruler\")").expect("no ruler");
2777 let lanes = bench.find(".id(\"bench-lanes\")").expect("no lane column");
2778 assert!(
2779 !bench[ruler..lanes].contains(".on_scroll_wheel("),
2780 "the ruler answers the wheel on its own again -- one notch, two scrolls"
2781 );
2782}
2783
2784/// The way back from a layout dragged somewhere unusable: a double press on
2785/// the seam forgets the size, and the region is the window's own share again
2786/// -- the *same* share an untouched window gives it, not a second default
2787/// kept beside the first ([`Splits::clear`]).
2788#[test]
2789fn a_double_pressed_divider_forgets_the_size_it_was_dragged_to() {
2790 use crate::layout::{Split, Splits, split_size};
2791 use gpui::{px, size};
2792
2793 let window = size(px(1280.), px(720.));
2794 let mut splits = Splits::default();
2795 for split in Split::PERSISTED {
2796 let default = split_size(split, None, 2, window, false);
2797 // A hand takes the seam somewhere else...
2798 splits.set(split, split_size(split, Some(300.), 2, window, false));
2799 assert_ne!(
2800 splits.get(split),
2801 None,
2802 "{split:?} kept nothing of the drag"
2803 );
2804 // ...and the double press puts it back where an untouched window
2805 // would have drawn it.
2806 splits.clear(split);
2807 assert_eq!(splits.get(split), None, "{split:?} still holds a size");
2808 assert_eq!(
2809 split_size(split, splits.get(split), 2, window, false),
2810 default,
2811 "{split:?} came back to something other than its own share"
2812 );
2813 }
2814}
2815
2816/// The seam is a ghost (DESIGN §11.2): 6 px of hit area with *nothing* painted
2817/// at rest, one hairline of dim ink under the pointer, the same line one step
2818/// brighter while it is held. The scan is the guard because the failure it
2819/// catches -- a `bg` on the strip, which is what the divider shipped with --
2820/// draws a 6 px band of colour down the room at rest and reads as the chrome
2821/// the user called crowded.
2822#[test]
2823fn the_seam_paints_nothing_until_a_pointer_finds_it() {
2824 let src = src_text("interact.rs");
2825 let start = src.find("pub(crate) fn divider(").expect("the divider");
2826 let body = &src[start..start + src[start..].find("\n}\n").expect("its end")];
2827 assert!(
2828 !body.contains(".bg("),
2829 "the divider fills its strip at rest: {body}"
2830 );
2831 assert!(
2832 body.contains("gpui::transparent_black()"),
2833 "the divider's line is inked at rest: {body}"
2834 );
2835 for step in [
2836 ".group_hover(",
2837 "GRAB_W",
2838 "BENCH_GRAB_H",
2839 "STROKE_DIVIDER()",
2840 "INK3()",
2841 "border_t_1()",
2842 "border_l_1()",
2843 ] {
2844 assert!(body.contains(step), "the divider is missing {step}");
2845 }
2846 // The hairline is the *band's* child, not the strip's own border: a line
2847 // raised only by the 6 px that already grab the seam is feedback the hand
2848 // gets after it no longer needs it (a `bench=207` -- a press with no
2849 // drag in it -- beside a dragged `dock=277`).
2850 assert!(
2851 body.find(".group(group.clone())").expect("the band's group")
2852 < body.find("border_t_1()").expect("the hairline"),
2853 "the hairline is painted outside the band: {body}"
2854 );
2855}
2856
2857/// The band the hand actually gets, in seam coordinates -- driven at
2858/// 2560x1440 with a real `bench=207` before this diff: a press answered only
2859/// within +/-7 px of the line the eye sees, and the `BENCH` label row under it
2860/// -- the visible top edge of the timeline, the thing a hand aims at -- was
2861/// silent. The band is hung one row above the [`SPLIT_W`] strip, so its reach
2862/// past the line is `grab - 1 - SPLIT_W`.
2863#[test]
2864fn the_bench_seam_reaches_into_the_row_a_hand_aims_at() {
2865 let above = 1.;
2866 let reach = |grab: f32| grab - above - crate::layout::SPLIT_W;
2867 // Every other seam is unchanged: its neighbour's own first row carries
2868 // content (the dock's rows, the legacy toolbar's buttons).
2869 assert_eq!(reach(crate::layout::GRAB_W), 7.);
2870 // The bench's reaches through the 24 px section head far enough to cover
2871 // the label row a hand lands on, and no further than the head itself.
2872 let past = reach(crate::layout::BENCH_GRAB_H);
2873 assert!(
2874 (10. ..=crate::ui::stance::BENCH_CHROME_H).contains(&past),
2875 "the bench band reaches {past}px past the seam"
2876 );
2877}
2878
2879/// The clamp table, driven: the seam refuses exactly two things, and neither
2880/// is anywhere near where a hand drags. Measured live at 2560x1440 --
2881/// `bench=105` at the floor, `bench=1164` at the ceiling.
2882#[test]
2883fn the_bench_seam_stops_at_its_floor_and_its_ceiling() {
2884 use crate::{BENCH_MIN_H, Split, split_bounds, split_size};
2885 use gpui::{px, size};
2886
2887 let window = size(px(2560.), px(1440.));
2888 let (min, max) = split_bounds(Split::Bench, 2, window, false);
2889 assert_eq!(min, BENCH_MIN_H);
2890 assert_eq!(
2891 max,
2892 1440. - crate::ui::stance::TIME_BAND_H - crate::ui::stance::LEDGER_H - 160.
2893 );
2894 for (asked, want) in [(0., min), (-942., min), (5000., max), (207., 207.)] {
2895 assert_eq!(
2896 split_size(Split::Bench, Some(asked), 2, window, false),
2897 want,
2898 "a bench dragged to {asked}"
2899 );
2900 }
2901}
2902
2903/// DESIGN §7: "lanes scroll behind the pinned ruler and track heads" -- pinned
2904/// means pinned. A clip that starts left of the view sits at a negative `left`
2905/// inside its bed, and with no clip mask gpui paints it (and its hitbox) over
2906/// the 72 px head column, so V1/A1 and their verbs disappear under the first
2907/// take as soon as the bench is wheeled past frame 0. The mask belongs on the
2908/// bed itself so a half-scrolled clip still drags on the half that shows.
2909#[test]
2910fn the_lane_bed_clips_its_clips_at_the_pinned_heads() {
2911 let src = src_text("ui/bench_stance.rs");
2912 let start = src.find(r#".id(("bench-bed""#).expect("the bed");
2913 let bed =
2914 &src[start..start + src[start..].find(".bg(rgb(DARK_CANVAS()))").expect("its fill")];
2915 assert!(
2916 bed.contains(".overflow_hidden()"),
2917 "the bed lets its clips paint outside itself, straight over the \
2918 pinned lane heads: {bed}"
2919 );
2920}
2921
2922/// A source row is its name first (user 2026-09-09: "clunky, crowded and
2923/// problematic"). At DOCK_W 280 the name used to be the only flexible child
2924/// among six, so it measured 0px and the library showed
2925/// `● V1 A1 · 2 uses Preview Add ↵ ○` -- every part of a row except the one
2926/// thing the row is for. The fix is subtraction, not a hover gate (DESIGN §8):
2927/// the name keeps 60% of the row, usage joins the metadata line under it, and
2928/// the three verbs shrink to glyph ghosts at the right edge.
2929#[test]
2930fn a_source_row_shows_its_name_before_anything_else() {
2931 let dock = src_text("ui/dock_stance.rs");
2932 let start = dock.find("fn source_row(").expect("the source row");
2933 let row = &dock[start..dock.find("/// Imported subtitle tracks").expect("its end")];
2934 assert!(
2935 row.contains(".min_w(relative(0.6))"),
2936 "the row name can still collapse under its siblings"
2937 );
2938 assert!(
2939 !row.contains(".min_w(px(0.))"),
2940 "the row name is still allowed to measure nothing"
2941 );
2942 // The usage moved to the second line, beside codec/length, in ink3.
2943 assert!(
2944 row.contains(r#".child(format!("{usage} · {under}"))"#),
2945 "usage is not folded into the metadata line"
2946 );
2947 // Preview / Add / proxy are glyph+chord ghosts now, not word buttons:
2948 // ~66px for the three together, inside the 96px the name can spare.
2949 for glyph in [r#".child("▷")"#, r#".child("+")"#, r#".child("↵")"#] {
2950 assert!(row.contains(glyph), "the right-edge verbs lost {glyph}");
2951 }
2952 for word in [r#".child("Preview")"#, r#".child("Add")"#] {
2953 assert!(!row.contains(word), "{word} still spends the name's width");
2954 }
2955 // Every verb keeps its own hitmap name and its chord.
2956 for id in ["source.{i}.preview", "source.{i}.add", "source.{i}.proxy"] {
2957 assert!(row.contains(id), "{id} lost its hitmap entry");
2958 }
2959 // DESIGN §8: the permanent footer telling the editor how to use a list
2960 // ("drag · ↵ add · double-click plays") is instructional copy and is gone.
2961 assert!(
2962 !dock.contains("double-click plays"),
2963 "the dock still carries an instruction footer"
2964 );
2965 // ...and an Audio tab with no audio-only file in it is a single noun, not
2966 // the claim `No sound` over a source whose A1 stream is on the bench.
2967 assert_eq!(crate::LibraryTab::Audio.empty(), "none");
2968}
2969
2970/// Focus and selection rings are drawn, never inserted: a `when(focused,
2971/// border_1())` puts a pixel of box into the flow and every row in the dock
2972/// steps sideways the moment the surface takes focus (hunter: h-clip-tab.png
2973/// vs i-library-menu.png).
2974#[test]
2975fn a_dock_ring_never_moves_what_it_rings() {
2976 let dock = src_text("ui/dock_stance.rs");
2977 for gate in [
2978 ".when(picked, |d| d.border_1()",
2979 ".when(focused, |d| d.border_1()",
2980 ] {
2981 assert!(
2982 !dock.contains(gate),
2983 "a dock ring is still added on state ({gate}), shifting its content"
2984 );
2985 }
2986 assert_eq!(
2987 dock.matches("gpui::transparent_black()").count(),
2988 4,
2989 "a dock ring lost its at-rest transparent border"
2990 );
2991 // ...and the focus ring is not painted at all (user 2026-09-09:
2992 // "clicking through timeline draws a white overlay around the timeline,
2993 // same happens for library section too"). Keyboard focus is unchanged --
2994 // only the paint is gone -- so no dock surface may reach for the focus
2995 // stroke or for `ink1` on a focused border.
2996 assert!(
2997 !dock.contains("STROKE_FOCUS"),
2998 "a dock surface paints the focus ring again"
2999 );
3000 assert!(
3001 !dock.contains("is_focused(window)"),
3002 "a dock surface reads focus for paint again"
3003 );
3004 assert!(
3005 dock.contains(".track_focus(&player.focus_dock)")
3006 && dock.contains(".track_focus(&player.focus_inspector)"),
3007 "dropping the ring's paint took the surface's keyboard focus with it"
3008 );
3009}
3010
3011/// DESIGN §9 as amended 2026-09-09: the keys list lives in the dock BODY,
3012/// not a plate over the bench and not a tab of its own (user: "remove keys
3013/// section from here since we also have it next to ledger"). The strip is
3014/// the SOURCES/CLIP pair; the list rides `keys_open` under a KEYS section
3015/// head, and the rows still come off `keys_rows` with the refused ones
3016/// greyed rather than hidden (§8).
3017#[test]
3018fn the_keys_list_is_dock_body_state_not_a_tab() {
3019 let stance = src_text("ui/stance.rs");
3020 assert!(
3021 !stance.contains("keys_overlay") && !stance.contains("stance-keys-overlay"),
3022 "the keys plate is still mounted over the bench"
3023 );
3024 let dock = src_text("ui/dock_stance.rs");
3025 for (id, label) in [("dock-tab-src", "SOURCES"), ("dock-tab-clip", "CLIP")] {
3026 assert!(
3027 dock.contains(&format!("dock_tab(\"{id}\", \"{label}\"")),
3028 "the dock's tab strip lost {label}"
3029 );
3030 }
3031 assert!(
3032 !dock.contains("dock-tab-keys"),
3033 "KEYS is still a tab in the strip"
3034 );
3035 assert!(
3036 dock[dock.find("fn keys_tab(").unwrap()..].contains("section_head(\"KEYS\")"),
3037 "the keys list draws no KEYS head in the dock body"
3038 );
3039 assert!(
3040 dock.contains("fn keys_tab(") && dock.contains("keys_rows()"),
3041 "the KEYS tab draws something other than the action registry"
3042 );
3043 assert!(
3044 dock.contains("Enable::Yes => INK2(),") && dock.contains("_ => INK4(),"),
3045 "a refused action's row no longer greys to ink4 (DESIGN §8)"
3046 );
3047 assert!(
3048 dock[dock.find("fn keys_tab(").unwrap()..].contains(".overflow_y_scroll()"),
3049 "the keys list does not scroll like its neighbours"
3050 );
3051 // The Sources filter box belongs to Sources: it is built inside
3052 // `sources_tab`, never in the shared frame `render` draws.
3053 let frame = &dock[dock.find("pub(crate) fn render(").unwrap()..];
3054 assert!(
3055 !frame.contains("dock-filter"),
3056 "the Sources filter box leaked into the shared dock frame"
3057 );
3058}
3059
3060/// The user's screenshot: the old rail ended with `?` over `?`. The rule
3061/// outlived the rail -- a ledger room ghost whose primary chord IS its own
3062/// name wears no badge; every other one still does.
3063#[test]
3064fn a_room_ghost_wears_no_chord_that_repeats_its_name() {
3065 let src = src_text("ui/stance.rs");
3066 assert!(
3067 src.contains(".when(player.keymap.chord(action) != name, |el| {"),
3068 "a room ghost draws its chord badge even when the badge repeats its name"
3069 );
3070}
3071
3072/// DESIGN §5 as amended 2026-09-09 (user decision "option C"): there is no
3073/// rail. The room root is centre | dock, `spine_stance` is deleted, and the
3074/// four verbs that act on the ROOM -- the only ones with no thing under the
3075/// cursor to be right-clicked -- live at the ledger's right end, each
3076/// wearing its chord, `CC` carrying the shown/hidden state the rail's glyph
3077/// used to.
3078#[test]
3079fn the_ledger_carries_the_rooms_four_verbs_and_no_rail_remains() {
3080 let src = src_text("ui/stance.rs");
3081 for gone in ["stance-spine", "spine_stance", "SPINE_W", "fn spine("] {
3082 assert!(!src.contains(gone), "the rail is still in the stance: {gone}");
3083 }
3084 let ledger = &src[src.find("fn ledger(").expect("the ledger strip")
3085 ..src.find("/// The dock:").expect("the dock frame")];
3086 for (name, action) in [
3087 ("CC", "ActionId::ToggleSubtitles"),
3088 ("settings", "ActionId::Settings"),
3089 ("keys", "ActionId::ShowActions"),
3090 ("full", "ActionId::Fullscreen"),
3091 ] {
3092 assert!(
3093 ledger.contains(&format!("\"{name}\",")) && ledger.contains(action),
3094 "the ledger lost its {name} room verb"
3095 );
3096 }
3097 // Before the position timecode, which stays the strip's last word.
3098 assert!(
3099 ledger.find("room_ghost(").expect("a room verb")
3100 < ledger.find(".child(tc),").expect("the position"),
3101 "the room verbs drew after the position timecode"
3102 );
3103 // Each wears its chord, live off the keymap (DESIGN §4), and `CC` reads
3104 // active while subtitles are shown.
3105 let ghost = &src[src.find("fn room_ghost(").expect("the room ghost")..];
3106 assert!(
3107 ghost.contains("player.keymap.chord(action)") && ghost.contains("widgets::action_hover"),
3108 "a room verb lost its live chord or its hover plate"
3109 );
3110 assert!(
3111 ledger.contains("player.subs_on"),
3112 "`CC` no longer shows whether subtitles are shown"
3113 );
3114}
3115
3116/// The ruler's right edge was soup: `bench-select-all` sits `right(4.)` over
3117/// the tick band while tick suppression only guarded the LEFT plate, so the
3118/// `00:20` label drew straight under the `all` chord. The control's band is
3119/// reserved now -- a label whose right edge would enter it is dropped, the
3120/// mirror of the left rule.
3121#[test]
3122fn the_ruler_reserves_a_band_for_its_select_all_control() {
3123 use crate::ui::bench_stance::{SELECT_ALL_PAD, char_w};
3124 use crate::ui::type_scale::{CHORD_METADATA_MIN_PX, FLOOR_PX};
3125 let bench = src_text("ui/bench_stance.rs");
3126 assert!(
3127 bench.contains("x + label_w <= bed_w - all_w"),
3128 "the tick loop no longer keeps the select-all band clear"
3129 );
3130 // The rule itself, with the shipped widths: `all` + `^a` at the chord
3131 // size, a `00:20` label at the floor size, a 850 px bed.
3132 let all_w = ("all".len() + "^a".len()) as f32 * char_w(CHORD_METADATA_MIN_PX) + SELECT_ALL_PAD;
3133 let label_w = "00:20".len() as f32 * char_w(FLOOR_PX);
3134 let clear = |x: f32| x + label_w <= 850. - all_w;
3135 assert!(!clear(820.), "a tick at the right edge still draws under `all`");
3136 assert!(
3137 !clear(850. - all_w - label_w + 1.),
3138 "the band's own edge leaks"
3139 );
3140 assert!(clear(700.), "the rule eats ticks that clear the band");
3141}
3142
3143/// Clicking `all` selected all AND scrubbed: the control lives inside
3144/// `bench-ruler`, whose `on_mouse_down` seeks, and the press reached it (the
3145/// playhead jumped 00:00:11:12 -> 00:00:20:14). The scrub refuses the
3146/// control's reserved band now -- a `stop_propagation` on the control is what
3147/// this looks like at first and it does NOT work: gpui builds the control's
3148/// own click out of that same mouse-down, so stopping it drops the selection
3149/// (measured live, run 20260909-174243-jZzccm/after-all.png: nothing but the
3150/// hover changed).
3151#[test]
3152fn a_press_on_the_select_all_band_does_not_scrub_the_ruler() {
3153 use crate::ui::bench_stance::select_all_band;
3154 let bench = src_text("ui/bench_stance.rs");
3155 let at = bench.find(r#".id("bench-ruler")"#).expect("no ruler");
3156 let listener = &bench[at..at + bench[at..].find(".children(ticks").expect("its ticks")];
3157 assert!(
3158 listener.contains("bed_w - band") && listener.contains("select_all_band("),
3159 "the ruler's scrub takes the select-all band's presses again: {listener}"
3160 );
3161 assert!(
3162 !bench[at..].contains("cx.stop_propagation()"),
3163 "a press stopped inside the ruler also swallows the control's own click"
3164 );
3165 // The rule the listener runs, at the shipped widths: a 850 px bed, `^a`.
3166 let band = select_all_band("^a");
3167 assert!(band > 30. && band < 70., "the band is not a control's width: {band}");
3168 assert!(850. - 4. >= 850. - band, "a press on the control still seeks");
3169 assert!(500. < 850. - band, "a press mid-ruler stopped seeking");
3170}
3171
3172/// DESIGN §4/§5: the hero timecode leads the time band and the ledger carries
3173/// position. The ruler's left plate was a third resting copy of the same
3174/// reading -- it stays only for the state change it belongs to, a live scrub.
3175#[test]
3176fn the_ruler_plate_shows_the_timecode_only_while_a_scrub_is_live() {
3177 let bench = src_text("ui/bench_stance.rs");
3178 let at = bench
3179 .find(".child(playhead_tc)")
3180 .expect("no playhead timecode in the ruler");
3181 let before = &bench[..at];
3182 let guard = before
3183 .rfind(".when(player.scrubbing")
3184 .expect("the ruler plate draws its timecode at rest -- the third copy");
3185 assert!(
3186 before[guard..].matches(".child(").count() <= 2,
3187 "the scrubbing guard is not the plate's own: {}",
3188 &before[guard..guard + 200]
3189 );
3190 assert!(
3191 bench.contains("let plate_w = if player.scrubbing { PLATE_W } else { 0. };"),
3192 "the ticks still lose the plate's width at rest"
3193 );
3194}
3195
3196
3197/// The band overflowed its own column at 1280x720 (`$EDITH_HITMAP`:
3198/// `action.Export x=1113 w=80` with the column ending at x=995, the contact
3199/// strip measured `w=0`), so the Export chip was invisible under the dock and
3200/// a click on blank dock space at (1130,435) opened the export card. Three
3201/// things hold that shut: the row clips itself, the strip keeps a floor, and
3202/// the ladder sheds groups above it.
3203#[test]
3204fn the_time_band_never_paints_outside_its_own_column() {
3205 let src = src_text("ui/timeband_stance.rs");
3206 let start = src.find(r#".id("stance-time-band-row")"#).expect("the band row");
3207 let row = &src[start..start + src[start..].find(".child(hero_timecode(").expect("the timecode")];
3208 assert!(
3209 row.contains(".overflow_hidden()"),
3210 "the band row lets its children paint (and be clicked) under the dock: {row}"
3211 );
3212 assert!(
3213 src.contains(".min_w(px(STRIP_MIN_W))"),
3214 "the contact strip is the flex_1 that absorbs the slack; without a floor it measures 0"
3215 );
3216 assert!(crate::ui::timeband_stance::STRIP_MIN_W >= 120.);
3217}
3218
3219/// DESIGN §7's ladder, one layer per threshold: the four things the band is
3220/// *for* -- timecode, cut readout, contact strip, Export -- survive every
3221/// rung, and the sheddable groups go in a fixed order (chords, then the
3222/// monitoring cluster, then sync/loop, then the range marks), never all at
3223/// once. Thresholds are the measured group widths; this pins their order and
3224/// the 1280x720 column (939px measured when a 56px rail still stood left of
3225/// it; the rail is gone since 2026-09-09, so the same window measures ~989px)
3226/// landing on the
3227/// marks-only rung, which is what makes Export fit there (it ended at x=991
3228/// inside a column ending at 995, against x=1113 under the dock before).
3229#[test]
3230fn the_band_sheds_one_layer_per_threshold_in_a_fixed_order() {
3231 use crate::ui::timeband_stance::band_layers;
3232 let ladder = [2000., 1300., 1100., 939., 800., 0.]
3233 .map(|w| band_layers(w))
3234 .map(|l| (l.chords, l.volume, l.sync, l.marks));
3235 assert_eq!(
3236 ladder,
3237 [
3238 (true, true, true, true),
3239 (false, true, true, true),
3240 (false, false, true, true),
3241 (false, false, false, true),
3242 (false, false, false, false),
3243 (false, false, false, false),
3244 ],
3245 "the band must drop chords, then the monitoring cluster, then sync/loop, then the marks"
3246 );
3247 // Monotone: a wider band never shows less than a narrower one.
3248 let mut prev = band_layers(0.);
3249 for w in (0..2400).step_by(10).map(|w| w as f32) {
3250 let now = band_layers(w);
3251 for (a, b) in [
3252 (prev.chords, now.chords),
3253 (prev.volume, now.volume),
3254 (prev.sync, now.sync),
3255 (prev.marks, now.marks),
3256 ] {
3257 assert!(b || !a, "layer came back off at {w}px");
3258 }
3259 prev = now;
3260 }
3261}
3262
3263/// Every door in this band is at least `HIT_MIN` wide and tall (WCAG 2.5.8).
3264/// The hitmap read `SetIn w=8`, `VolumeDown w=12`, `Loop w=13`, `SetOut w=15`,
3265/// `Prev/NextSyncPoint w=16` before this: padding on the shared `ghost`, not a
3266/// bigger glyph.
3267#[test]
3268fn every_ghost_in_the_time_band_carries_a_full_hit_area() {
3269 let src = src_text("ui/timeband_stance.rs");
3270 let start = src.find("fn ghost(").expect("the band's ghost");
3271 let ghost = &src[start..start + src[start..].find(".child(glyph.into())").expect("its glyph")];
3272 for needle in [".min_w(px(HIT_MIN))", ".min_h(px(HIT_MIN))"] {
3273 assert!(ghost.contains(needle), "the band's ghost lost {needle}: {ghost}");
3274 }
3275 assert!(HIT_MIN >= 24.);
3276}
3277
3278/// Mute wore `"{volume}%"` as its glyph while the slider beside it drew the
3279/// same value: one number, two places, and a toggle with no verb of its own.
3280/// The level is a mono readout beside the slider now, once.
3281#[test]
3282fn the_level_is_written_once_and_mute_wears_a_glyph() {
3283 let src = src_text("ui/timeband_stance.rs");
3284 assert_eq!(
3285 src.matches(r#"player.volume.percent()"#).count(),
3286 1,
3287 "the volume level must be written in exactly one place in the band"
3288 );
3289 assert!(
3290 src.contains(r#"if player.volume.muted { "◁×" } else { "◁))" }"#),
3291 "mute must wear a speaker glyph, struck when muted"
3292 );
3293 assert!(src.contains("fn volume_readout("), "the level readout is the one place it is written");
3294}
3295
3296/// `Play` and `StepForward` drew the same solid right-triangle: two verbs one
3297/// shape, told apart only by their chords. Step wears the frame-step pair.
3298#[test]
3299fn transport_verbs_differ_by_shape_not_only_by_chord() {
3300 let src = src_text("ui/timeband_stance.rs");
3301 let glyph = |action: &str| {
3302 let at = src.find(&format!("ActionId::{action},")).expect("the call");
3303 src[..at].rsplit('"').nth(1).expect("its glyph").to_string()
3304 };
3305 let shapes = ["Play", "StepBack", "StepForward", "JumpBack", "JumpForward"].map(glyph);
3306 let mut seen = shapes.to_vec();
3307 seen.sort();
3308 seen.dedup();
3309 assert_eq!(seen.len(), shapes.len(), "two transport verbs share one glyph: {shapes:?}");
3310}
3311
3312/// DESIGN §6: "the cut readout is the odometer". Keyed off the selection it
3313/// read `cut —/—` immediately after a split -- two clips on the bench, the
3314/// playhead resting on the new cut, nothing picked. It reads the playhead
3315/// now: the cut under it, else the next one ahead, else the selection.
3316#[test]
3317fn the_cut_readout_counts_from_the_playhead() {
3318 use crate::ui::timeband_stance::odometer_cut;
3319 let at = |start: u32, len: u32| Clip {
3320 fade_in: 0,
3321 fade_out: 0,
3322 transition_out: 0,
3323 start,
3324 in_frame: 0,
3325 out_frame: len,
3326 source: 0,
3327 link: None,
3328 eq: None,
3329 color: None,
3330 transform: None,
3331 fit: FitPolicy::Fit,
3332 speed: Speed::NORMAL,
3333 };
3334 let lane = [at(0, 30), at(30, 30)];
3335 assert_eq!(odometer_cut(&lane, 0), Some(0));
3336 assert_eq!(odometer_cut(&lane, 29), Some(0));
3337 // The split's own frame: the playhead rests on the SECOND cut's head.
3338 assert_eq!(odometer_cut(&lane, 30), Some(1));
3339 assert_eq!(odometer_cut(&lane, 59), Some(1));
3340 // Past the last cut there is nothing to count -- the selection answers.
3341 assert_eq!(odometer_cut(&lane, 60), None);
3342 // In a gap: the next cut ahead of the playhead.
3343 let gapped = [at(0, 10), at(40, 10)];
3344 assert_eq!(odometer_cut(&gapped, 20), Some(1));
3345 assert_eq!(odometer_cut(&[], 0), None);
3346 assert!(
3347 src_text("ui/timeband_stance.rs").contains("odometer_cut(s.lane_clips(lane), frame)"),
3348 "the readout must derive its odometer from the playhead"
3349 );
3350}
3351
3352/// DESIGN §8's rejected pattern, swept over the source rather than argued
3353/// per message: "the room never explains itself in prose ... any new string
3354/// over ~4 words that instructs rather than reports state is a defect". The
3355/// notices are what the ledger strip paints, and a sentence there is what cut
3356/// mid-word in the user's own screenshot (`OPENED ... 1 subtitle track(s) in `).
3357///
3358/// The scan reads every literal handed to a notice constructor, found by its
3359/// *call site* and not by its shape: the head of a composed refusal is the
3360/// verb's own label ("Delete — click a clip first", seen live 2026-09-09), so
3361/// a caps-headed filter walked past every one of them. Any imperative tell in
3362/// such a literal is a defect at any length. A refusal *claim* may still be
3363/// long: those are the allowlist below, each one naming a genuine absent
3364/// capability, never a lesson in how to use the room.
3365#[test]
3366fn no_notice_teaches_the_room_in_prose() {
3367 // Long refusal claims that report a capability genuinely absent from this
3368 // machine (DESIGN §8, "a refusal string is a claim"), kept whole on
3369 // purpose: the remedy is not a chord in this room because the missing
3370 // thing is not in this room.
3371 const ALLOWED: &[&str] = &["NO FILE CHOOSER"];
3372 const TELLS: &[&str] = &[
3373 "drag ",
3374 "press ",
3375 "pick ",
3376 "type ",
3377 "click ",
3378 "to show",
3379 "to use",
3380 "takes it back",
3381 "puts it back",
3382 " first",
3383 ];
3384 let mut offenders = Vec::new();
3385 for path in source_files() {
3386 let text = std::fs::read_to_string(&path).expect("a source file");
3387 for literal in notice_literals(&text) {
3388 if ALLOWED.iter().any(|allowed| literal.contains(allowed)) {
3389 continue;
3390 }
3391 let lower = literal.to_lowercase();
3392 if TELLS.iter().any(|tell| lower.contains(tell)) {
3393 offenders.push(format!("{}: {literal}", path.display()));
3394 }
3395 }
3396 }
3397 assert!(
3398 offenders.is_empty(),
3399 "a notice that instructs instead of reporting state (DESIGN §8):\n{}",
3400 offenders.join("\n")
3401 );
3402}
3403
3404/// Every string literal that reaches the user as a notice: the arguments of
3405/// the doors a message comes through -- the queue's own two, and the oracle's
3406/// refusal words, which the dispatch pastes behind an action label
3407/// ([`crate::player::actions`]). Reading the call site rather than the string
3408/// is the point: a message's case says nothing about whether it teaches.
3409fn notice_literals(text: &str) -> Vec<String> {
3410 const CALLS: &[&str] = &[
3411 "notify_user(",
3412 "push_notice(",
3413 "Enable::No(",
3414 "Enable::Hidden(",
3415 ];
3416 let code: String = text
3417 .lines()
3418 .filter(|line| !line.trim_start().starts_with("//"))
3419 .collect::<Vec<_>>()
3420 .join("\n");
3421 let mut out = Vec::new();
3422 for call in CALLS {
3423 for (at, _) in code.match_indices(call) {
3424 let open = at + call.len();
3425 // The call's own argument list, to its matching paren: a literal
3426 // written two lines below the opening one is still this call's.
3427 let mut depth = 1usize;
3428 let mut in_string = false;
3429 let mut escaped = false;
3430 let mut end = open;
3431 for (offset, c) in code[open..].char_indices() {
3432 end = open + offset;
3433 match (in_string, c) {
3434 (true, '\\') => escaped = !escaped,
3435 (true, '"') if !escaped => in_string = false,
3436 (true, _) => escaped = false,
3437 (false, '"') => in_string = true,
3438 (false, '(') => depth += 1,
3439 (false, ')') => {
3440 depth -= 1;
3441 if depth == 0 {
3442 break;
3443 }
3444 }
3445 _ => {}
3446 }
3447 }
3448 out.extend(string_literals(&code[open..end]));
3449 }
3450 }
3451 out
3452}
3453
3454/// Every string literal in `text`, comments dropped first so the prose about
3455/// a message is never read as the message.
3456fn string_literals(text: &str) -> Vec<String> {
3457 let code: String = text
3458 .lines()
3459 .filter(|line| !line.trim_start().starts_with("//"))
3460 .collect::<Vec<_>>()
3461 .join("\n");
3462 let mut out = Vec::new();
3463 let mut chars = code.chars().peekable();
3464 while let Some(c) = chars.next() {
3465 if c != '"' {
3466 continue;
3467 }
3468 let mut literal = String::new();
3469 while let Some(c) = chars.next() {
3470 match c {
3471 // A line continuation joins the halves of a wrapped message;
3472 // every other escape is not a word either way.
3473 '\\' => {
3474 if chars.next() == Some('\n') {
3475 while chars.peek() == Some(&' ') {
3476 chars.next();
3477 }
3478 }
3479 }
3480 '"' => break,
3481 _ => literal.push(c),
3482 }
3483 }
3484 out.push(literal);
3485 }
3486 out
3487}
3488
3489/// The export moment holds the file and the budget; everything a project is
3490/// *delivered as* is a settings row now (user: the export card was "too
3491/// complicated"). Four rows, and a fifth would be the card growing back --
3492/// this is a source scan for the same reason every guard on this page is.
3493#[test]
3494fn the_export_section_is_four_rows_and_no_fifth() {
3495 let source = src_text("ui/settings_stance.rs");
3496 let start = source
3497 .find("fn export_section(")
3498 .expect("the export section");
3499 let body = &source[start..];
3500 let end = body.find("\n/// The page itself").expect("the page's render fn");
3501 let body = &body[..end];
3502 let rows = [
3503 "settings-export-picture",
3504 "settings-export-sound",
3505 "settings-export-encoder",
3506 "settings-export-range",
3507 ];
3508 for row in rows {
3509 assert!(body.contains(row), "the EXPORT section has no {row} row");
3510 }
3511 // The Sound row is written twice -- a rated codec's keyed row and an
3512 // unrated one's readout, never both at once -- so the count is by label,
3513 // not by id.
3514 for label in ["\"Picture\"", "\"Sound\"", "\"Encoder\"", "\"Range\""] {
3515 assert!(body.contains(label), "the EXPORT section has no {label} row");
3516 }
3517 let ids = body.match_indices("\"settings-export-").count();
3518 assert_eq!(ids, 5, "the EXPORT section grew a row past the four (the two Sound rows are one row's two shapes)");
3519 assert!(
3520 source.contains("what a delivery is written as"),
3521 "the section lost its head"
3522 );
3523 // Every row wears its chord (DESIGN §4): three keyed rows plus the
3524 // range's own marks, which are keymap actions.
3525 for chord in ["\"c\"", "\"b\"", "\"g\"", "ActionId::SetIn"] {
3526 assert!(body.contains(chord), "an EXPORT row lost its chord {chord}");
3527 }
3528}
3529
3530/// `c` walks the nine files in one order -- a codec's two boxes side by side,
3531/// the sound-only formats last -- and never stops on a format this machine
3532/// cannot write, because [`Player::set_format`] would only refuse it back.
3533#[test]
3534fn the_picture_row_cycles_codec_and_container_together_and_skips_a_refusal() {
3535 use crate::ui::settings_stance::{PICTURE_CYCLE, next_picture, picture_label};
3536 assert_eq!(
3537 PICTURE_CYCLE,
3538 [
3539 Format::Mp4,
3540 Format::Av1Mp4,
3541 Format::Av1,
3542 Format::Hevc,
3543 Format::HevcMp4,
3544 Format::Wav,
3545 Format::Flac,
3546 Format::Mp3,
3547 Format::Ogg,
3548 ]
3549 );
3550 // Nothing refused: the whole ring, wrapping back to the head.
3551 let mut at = Format::Mp4;
3552 let mut walked = vec![at];
3553 for _ in 1..PICTURE_CYCLE.len() {
3554 at = next_picture(at, |_| false);
3555 walked.push(at);
3556 }
3557 assert_eq!(walked, PICTURE_CYCLE.to_vec());
3558 assert_eq!(next_picture(at, |_| false), Format::Mp4);
3559
3560 // HEVC unavailable (no plugin): `c` steps over both of its boxes rather
3561 // than parking on a pick the setter refuses.
3562 let no_hevc = |f: Format| matches!(f, Format::Hevc | Format::HevcMp4);
3563 assert_eq!(next_picture(Format::Av1, no_hevc), Format::Wav);
3564 // Everything refused: the row keeps what it has instead of cycling to
3565 // nothing.
3566 assert_eq!(next_picture(Format::Mp4, |_| true), Format::Mp4);
3567
3568 assert_eq!(picture_label(Format::Mp4), "H.264 · MP4");
3569 assert_eq!(picture_label(Format::Av1), "AV1 · MKV");
3570 assert_eq!(picture_label(Format::Av1Mp4), "AV1 · MP4");
3571 assert_eq!(picture_label(Format::Wav), "WAV");
3572}
3573
3574/// A refused codec is greyed with its reason, never hidden (DESIGN §8), and
3575/// the reason is short enough to sit beside a value: six words, the rest of
3576/// the sentence still said by the export moment's own banner. The sound row
3577/// wears a chord only where its codec has a rate to step.
3578#[test]
3579fn a_refusal_is_six_words_beside_the_value_and_soundless_codecs_wear_no_chord() {
3580 use crate::ui::settings_stance::{encoder_word, short_reason, sound_codec};
3581 let long = "HEVC needs the VA-API plugin, which this machine has not built";
3582 assert_eq!(short_reason(long), "HEVC needs the VA-API plugin, which");
3583 assert!(short_reason(long).split_whitespace().count() <= 6);
3584 assert_eq!(short_reason("no encoder here"), "no encoder here");
3585
3586 for (format, codec, rated) in [
3587 (Format::Mp4, "AAC", true),
3588 (Format::Av1, "AAC", true),
3589 (Format::Mp3, "MP3", true),
3590 (Format::Wav, "PCM", false),
3591 (Format::Flac, "FLAC", false),
3592 (Format::Ogg, "Vorbis", false),
3593 ] {
3594 assert_eq!(sound_codec(format), (codec, rated), "{format:?}");
3595 }
3596
3597 assert_eq!(encoder_word(EncoderSeat::Auto), "auto");
3598 assert_eq!(encoder_word(EncoderSeat::Hardware), "GPU");
3599 assert_eq!(encoder_word(EncoderSeat::Software), "software");
3600}
3601
3602/// The one amber line on the page is the AV1-on-the-GPU seat, and it is the
3603/// only hue the EXPORT rows introduce -- every other value is an ink.
3604#[test]
3605fn the_only_hue_in_the_export_section_is_the_av1_gpu_notice() {
3606 let source = src_text("ui/settings_stance.rs");
3607 let start = source
3608 .find("fn export_section(")
3609 .expect("the export section");
3610 let body = &source[start..];
3611 let body = &body[..body.find("\n/// The page itself").expect("the render fn")];
3612 assert!(
3613 body.contains("NOTICE_LOOK()"),
3614 "the AV1-on-the-GPU row lost its amber"
3615 );
3616 assert_eq!(
3617 crate::ui::settings_stance::AV1_GPU_NOTICE,
3618 "ignores the budget \u{2014} constant quality"
3619 );
3620 for hue in ["ACCENT_", "STATUS_", "NOTICE_TELL", "NOTICE_DECIDE"] {
3621 assert!(
3622 !body.contains(hue),
3623 "the EXPORT rows reached for a second hue ({hue})"
3624 );
3625 }
3626}
3627
3628/// Every control the hitmap names wears a hover line (the user, 2026-09-09,
3629/// over a screenshot of the time band: "each and every button needs hover
3630/// over information ... I don't know some of them"). The hitmap already
3631/// carries the pair a plate needs -- an id and a label -- so the sweep walks
3632/// the same emitters: a builder chain that records a control and never calls
3633/// `.tooltip` is a glyph the user cannot name.
3634///
3635/// A scan and not a render: this crate has no gpui window in its tests, so
3636/// the text is the finest grain available. Each emitter must claim a
3637/// `.tooltip(` of *its own* within [`REACH`] lines -- one to one, nearest
3638/// first. Counting them per function instead let an unrelated plate (the
3639/// empty-dock hint) pay for a control that had none: `dock.sort.cycle` sat
3640/// bare under a green gate until this pairing was written.
3641///
3642/// Controls outside the hitmap are outside this gate by charter. Named for
3643/// the record, since each is a control the pointer can press: a card's own
3644/// picker rows (colour/transform/mix/subtitle/silence bands, the speed
3645/// chips) and the two menus' rows, all of which already read as
3646/// `<label> <value-or-chord>` on the row itself -- a plate would repeat the
3647/// row it hangs off, which is DESIGN §8's prose rule the other way round.
3648#[test]
3649fn every_hitmap_control_wears_a_hover_line() {
3650 /// How far from a control's `hitmap::` line its plate may be attached.
3651 /// A builder chain runs long here (the contact strip's tooltip sits 65
3652 /// lines above its emitter), so the reach is generous; what it buys is
3653 /// that a plate can be spent only once.
3654 const REACH: usize = 80;
3655 // Ids that name a control a *previous* emitter in the same chain already
3656 // plated -- the second id is the harness's aim point, not a second
3657 // control -- with the reason each is exempt.
3658 const DOUBLE_NAMED: &[&str] = &[
3659 // `subtitle.N.M.row` and `subtitle.N.M.select` are one row.
3660 ".select\")",
3661 ];
3662 let mut controls = 0;
3663 let mut naked = Vec::new();
3664 for path in source_files() {
3665 let text = std::fs::read_to_string(&path).expect("a source file");
3666 if !text.contains("hitmap::") {
3667 continue;
3668 }
3669 let file = path
3670 .file_name()
3671 .and_then(|n| n.to_str())
3672 .expect("a file name")
3673 .to_string();
3674 let lines: Vec<&str> = text.lines().collect();
3675 let mut tips: Vec<(usize, bool)> = lines
3676 .iter()
3677 .enumerate()
3678 .filter(|(_, l)| l.contains(".tooltip("))
3679 .map(|(i, _)| (i, false))
3680 .collect();
3681 for (i, line) in lines.iter().enumerate() {
3682 let emitter = ["hitmap::control(", "hitmap::dynamic(", "hitmap::action("]
3683 .iter()
3684 .any(|needle| line.contains(needle));
3685 if !emitter {
3686 continue;
3687 }
3688 // The id a `dynamic` builds sits a line or three below its call.
3689 let head = lines[i..(i + 6).min(lines.len())].join("\n");
3690 if DOUBLE_NAMED.iter().any(|id| head.contains(id)) {
3691 continue;
3692 }
3693 controls += 1;
3694 let mut free: Vec<usize> = (0..tips.len())
3695 .filter(|n| !tips[*n].1 && tips[*n].0.abs_diff(i) <= REACH)
3696 .collect();
3697 free.sort_by_key(|n| tips[*n].0.abs_diff(i));
3698 match free.first() {
3699 Some(n) => tips[*n].1 = true,
3700 None => naked.push(format!("{file}:{}: {}", i + 1, line.trim())),
3701 }
3702 }
3703 }
3704 assert!(
3705 controls >= 40,
3706 "the hover sweep found only {controls} controls -- it has gone blind"
3707 );
3708 assert!(
3709 naked.is_empty(),
3710 "controls with no hover line of their own (attach \
3711 `widgets::tip_hover`/`action_hover` in the chain that emits the \
3712 hitmap id): {naked:#?}"
3713 );
3714}
3715
3716/// The one hover shape for the whole room: `<name> · <chord>`, and a control
3717/// the state refuses says why instead of naming a stroke that will not fire
3718/// (DESIGN §4/§8 -- a tooltip is not a sentence).
3719#[test]
3720fn a_hover_line_is_a_name_and_a_chord() {
3721 use crate::ui::widgets::tip_line;
3722 assert_eq!(
3723 tip_line("One frame forward", "right", None),
3724 "One frame forward · right"
3725 );
3726 assert_eq!(
3727 tip_line("Split", "s", Some("nothing selected")),
3728 "Split · nothing selected"
3729 );
3730 // `Keymap::chord`'s unbound badge is not a stroke.
3731 assert_eq!(tip_line("Add files", "--", None), "Add files");
3732 assert_eq!(tip_line("Source", "", None), "Source");
3733}
3734
3735/// A region is a place, not a control: none of the region roots paints a
3736/// border because it holds focus (user 2026-09-10, "clicking through
3737/// timeline draws a white overlay around the timeline"; DESIGN §4's ring
3738/// line is about the *selected thing*). Focus routing itself is untouched.
3739#[test]
3740fn no_region_root_wears_a_focus_ring() {
3741 let stance = src_text("ui/stance.rs");
3742 let bench = src_text("ui/bench_stance.rs");
3743 let band = src_text("ui/timeband_stance.rs");
3744 for (name, text) in [
3745 ("stance.rs", &stance),
3746 ("bench_stance.rs", &bench),
3747 ("timeband_stance.rs", &band),
3748 ] {
3749 for line in text.lines() {
3750 let code = line.trim_start();
3751 if code.starts_with("//") {
3752 continue;
3753 }
3754 assert!(
3755 !(code.contains("is_focused(") || code.contains("when(focused"))
3756 || !code.contains("border"),
3757 "{name} still paints a focus-conditional border: {code}"
3758 );
3759 assert!(
3760 !code.contains("STROKE_FOCUS"),
3761 "{name} paints the focus stroke on a region: {code}"
3762 );
3763 }
3764 }
3765}