forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

layout.rs4440 lines, 184.8 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 visualizer: 0,
750 viz_paint: 0,
751 start,
752 in_frame: 0,
753 out_frame: 30,
754 source: 0,
755 link: None,
756 eq: None,
757 color: None,
758 transform: None,
759 fit: FitPolicy::Fit,
760 speed: Speed::NORMAL,
761 };
762 let lane = [at(0), at(30), at(60)];
763 let dragged = lane[2];
764 assert_eq!(live_idx(&lane, 2, dragged), Some(2), "nothing moved");
765 // A delete in front of it: the clip is now index 1, and the index the
766 // drag froze names a clip nobody grabbed.
767 let after = [at(0), at(60)];
768 assert_eq!(live_idx(&after, 2, dragged), Some(1));
769 assert_eq!(live_idx(&after, 1, dragged), Some(1));
770 // Deleted mid-drag: there is nothing to move, and moving its neighbour
771 // instead is exactly the bug this exists for.
772 assert_eq!(live_idx(&[at(0)], 2, dragged), None);
773 assert_eq!(live_idx(&[], 0, dragged), None);
774}
775
776#[test]
777fn a_quiet_source_still_draws_as_a_shape() {
778 // An eighth of full scale, which is about where the fixtures sit.
779 let quiet: Vec<(f32, f32)> = vec![(-0.125, 0.125), (-0.0625, 0.0625)];
780 let loud = normalise(quiet.clone());
781 assert_eq!(loud[0], (-1., 1.));
782 assert_eq!(loud[1], (-0.5, 0.5));
783 // Digital silence has no loudest sample to scale to; it must not divide
784 // by zero and must stay flat.
785 assert_eq!(normalise(vec![(0., 0.)]), vec![(0., 0.)]);
786 assert!(normalise(Vec::new()).is_empty());
787}
788
789/// The whole waveform path, from the file on disk to the columns that get
790/// painted: what no screenshot can assert about the shape.
791#[test]
792fn the_fixtures_waveform_reaches_the_lane_as_a_shape() {
793 let asset = |name: &str| {
794 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
795 .join("../../assets")
796 .join(name)
797 };
798 let peaks = normalise(
799 engine::waveform::peaks(asset("test_av.mp4"), 0, WAVE_BPS)
800 .expect("open the fixture")
801 .expect("test_av.mp4 has audio"),
802 );
803 // 5 s of source at the rate the lane asks for.
804 assert!(peaks.len().abs_diff(5 * WAVE_BPS as usize) <= WAVE_BPS as usize);
805 let cols = envelope(&peaks, 0., 5., 600., 30.);
806 let height = |&(_, top, bottom): &(f32, f32, f32)| bottom - top;
807 let tallest = cols.iter().map(height).fold(0., f32::max);
808 let flattest = cols.iter().map(height).fold(f32::MAX, f32::min);
809 // The fixture's 1 Hz pulse: a full-scale peak and a near-silent dip in
810 // every second, so the drawn envelope is a shape and not a bar.
811 assert!(tallest > 25., "loudest column only {tallest} px of 30");
812 assert!(
813 flattest < 8.,
814 "quietest column {flattest} px -- no dips drawn"
815 );
816 // A video-only source draws no waveform at all rather than a flat fake.
817 assert!(
818 engine::waveform::peaks(asset("test_baseline.mp4"), 0, WAVE_BPS)
819 .expect("open the fixture")
820 .is_none()
821 );
822}
823
824#[test]
825fn every_mark_on_a_clip_is_legible_on_it() {
826 // The body a name and a waveform are drawn on is the clip's kind
827 // ([`clip_kind`]); the source tint is the border and the library
828 // swatch, and is measured for telling itself apart rather than for
829 // carrying text.
830 // Every palette a person can pick, not merely the one in force.
831 for id in crate::ui::theme::PaletteId::ALL {
832 let p = id.palette();
833 for (i, tint) in [p.CLIP_VIDEO, p.CLIP_AUDIO, p.CLIP_IMAGE, p.CLIP_TEXT]
834 .iter()
835 .enumerate()
836 {
837 // WCAG 1.4.3: the clip's name is body text on its tint.
838 assert!(
839 contrast(p.FG_PRIMARY, *tint) >= 4.5,
840 "{id:?} source {i}: label contrast {:.2}",
841 contrast(p.FG_PRIMARY, *tint)
842 );
843 // WCAG 1.4.11: the waveform is a non-text graphic on it.
844 assert!(
845 contrast(p.FG_SECONDARY, *tint) >= 3.,
846 "{id:?} source {i}: waveform contrast {:.2}",
847 contrast(p.FG_SECONDARY, *tint)
848 );
849 }
850 // A selected clip's bed is the same two marks on a different colour.
851 assert!(contrast(p.FG_PRIMARY, p.BG_SELECTED) >= 4.5, "{id:?}");
852 assert!(contrast(p.FG_SECONDARY, p.BG_SELECTED) >= 3., "{id:?}");
853 // The bed a gap shows through has to read as a hole in the lane --
854 // the clip is the object, the bed is the hole -- and the playhead
855 // has to be findable on both.
856 assert!(contrast(p.CLIP_VIDEO, p.BG_TIMELINE) >= 1.5, "{id:?}");
857 assert!(contrast(p.ACCENT_PLAYHEAD, p.BG_TIMELINE) >= 3., "{id:?}");
858 assert!(contrast(p.ACCENT_PLAYHEAD, p.CLIP_VIDEO) >= 3., "{id:?}");
859 }
860 // The sanity check on the ratio itself: black on white is 21:1.
861 assert!((contrast(0xffffff, 0x000000) - 21.).abs() < 0.01);
862}
863
864#[test]
865fn source_tints_differ_per_source_and_cycle() {
866 // The bug: the first entry *was* `BG_RAISED`, so the first file imported
867 // -- the one every session has -- wore the panel's own background and
868 // had no visible swatch at all.
869 assert_ne!(source_tint(0), BG_RAISED());
870 // ...in every family, since the swatch is drawn on whichever panel is
871 // in force (`ui::theme`) and a tint that vanished into one of them is a
872 // file with no colour at all.
873 for id in crate::ui::theme::PaletteId::ALL {
874 let p = id.palette();
875 for (i, &tint) in p.SOURCE_TINTS.iter().enumerate() {
876 assert_ne!(tint, p.BG_RAISED, "{id:?} tint {i} is the panel");
877 }
878 }
879 // Neighbouring sources must not share one, or an import is invisible.
880 assert_ne!(source_tint(0), source_tint(1));
881 assert_ne!(source_tint(1), source_tint(2));
882 assert_ne!(source_tint(2), source_tint(3));
883 // Past the palette it wraps -- never an index panic.
884 assert_eq!(source_tint(4), source_tint(0));
885 assert_eq!(source_tint(9), source_tint(1));
886 assert_eq!(source_tint(usize::MAX), SOURCE_TINTS()[usize::MAX % 4]);
887}
888
889/// Not "they are different numbers" -- different *enough to see*, against
890/// each other and against the surface a swatch is drawn on. The palette is
891/// deliberately dark and low-saturation, so the margin is thin and a new
892/// tint picked by eye can land inside it without anyone noticing.
893#[test]
894fn source_tints_are_all_discernible() {
895 // Summed channel distance: `BG_RAISED` to the warm tint is 18, and that
896 // step is the one already accepted as readable on a lane.
897 let apart = |a: u32, b: u32| {
898 (0..3)
899 .map(|i| {
900 let shift = i * 8;
901 ((a >> shift) & 0xff).abs_diff((b >> shift) & 0xff)
902 })
903 .sum::<u32>()
904 };
905 // Every family, not the one in force: a palette is picked at runtime
906 // now, and four tints tuned by eye on one ground are exactly where a
907 // pair lands inside the margin on another.
908 for id in crate::ui::theme::PaletteId::ALL {
909 let p = id.palette();
910 for (i, &tint) in p.SOURCE_TINTS.iter().enumerate() {
911 assert!(
912 apart(tint, p.BG_RAISED) >= 16,
913 "{id:?} tint {i} is {} from the panel it sits on",
914 apart(tint, p.BG_RAISED)
915 );
916 for (j, &other) in p.SOURCE_TINTS.iter().enumerate().skip(i + 1) {
917 // The eleven non-darkroom families still cycle four tuned
918 // tints through the 12-wide wheel (`source_tint`'s own `%
919 // len()` reads them back identically either way) -- a
920 // literal repeat there is the intended cycle, not a
921 // collision, so it is skipped rather than failed. Darkroom's
922 // own twelve (DESIGN §2) are twelve *different* hues and
923 // never repeat, so a real collision there still fails this.
924 if tint == other {
925 continue;
926 }
927 assert!(
928 apart(tint, other) >= 16,
929 "{id:?} tints {i} and {j} are only {} apart",
930 apart(tint, other)
931 );
932 }
933 }
934 // The two a person sees side by side first must be further apart
935 // than the floor: source 0 and source 1 are the first import and
936 // the second.
937 assert!(apart(p.SOURCE_TINTS[0], p.SOURCE_TINTS[1]) >= 32, "{id:?}");
938 }
939 // Darkroom's own 12-hue wheel (DESIGN §2/§12 step 5's hook): every one
940 // of the twelve is a genuinely different hue, not four repeated three
941 // times like the other families still cycle -- a hue accidentally
942 // reintroduced by a future edit here is the "four shades of grey" bug
943 // this task exists to fix, so it fails loudly rather than skip past the
944 // `tint == other` escape hatch above.
945 let dr = crate::ui::theme::PaletteId::Darkroom.palette();
946 for (i, &a) in dr.SOURCE_TINTS.iter().enumerate() {
947 for (j, &b) in dr.SOURCE_TINTS.iter().enumerate().skip(i + 1) {
948 assert_ne!(a, b, "darkroom tints {i} and {j} collide");
949 }
950 }
951}
952
953/// A `.srt` dropped on the window is nobody's stream: it has no source
954/// entry, and the lookup that used to fall back to index 0 painted it with
955/// the first file's colour -- a swatch saying it came out of a film it
956/// never touched.
957#[test]
958fn a_standalone_subtitle_wears_no_file_tint() {
959 let sources = [
960 Source {
961 path: PathBuf::from("/films/a.mkv"),
962 audio_stream: 0,
963 },
964 Source {
965 path: PathBuf::from("/films/b.mp4"),
966 audio_stream: 0,
967 },
968 // A second stream of the first file is a second source and the
969 // same colour.
970 Source {
971 path: PathBuf::from("/films/a.mkv"),
972 audio_stream: 1,
973 },
974 ];
975 assert_eq!(
976 file_tint(&sources, Path::new("/films/a.mkv")),
977 Some(source_tint(0))
978 );
979 assert_eq!(
980 file_tint(&sources, Path::new("/films/b.mp4")),
981 Some(source_tint(1))
982 );
983 assert_eq!(file_tint(&sources, Path::new("/subs/a.eng.srt")), None);
984 assert_eq!(file_tint(&[], Path::new("/films/a.mkv")), None);
985 // The same file under two spellings is one file and one colour: a
986 // source is stored symlink-resolved, everything else as it was typed.
987 let here = std::fs::canonicalize(".").expect("the crate directory");
988 let sources = [Source {
989 path: here.join("Cargo.toml"),
990 audio_stream: 0,
991 }];
992 assert_eq!(
993 file_tint(&sources, Path::new("Cargo.toml")),
994 Some(source_tint(0)),
995 "a relative spelling of the source file wears the source's colour"
996 );
997}
998
999/// A film's two ASS tracks with the timeline trimmed to twenty seconds:
1000/// one of them still has cues there and one has none, and the card said
1001/// nothing whatever about the second while the Subtitles list went on
1002/// showing it with its eighty-three cues.
1003///
1004/// And the 25 GB remux's thirty-five: naming those wrapped the row to ten
1005/// lines and pushed Destination under the fold, so past the value box's
1006/// three lines the same line counts instead.
1007#[test]
1008fn the_card_names_the_subtitle_it_leaves_off_and_counts_them_when_it_cannot() {
1009 let film = "/films/An Episode 01.mkv";
1010 let two = [
1011 sub(film, Some(1), "[ASS]"),
1012 sub(film, Some(2), "[ASS] [FOR DUB]"),
1013 ];
1014 // What the engine answers about the one pick that reached it, and what
1015 // this side knows about the row that did not.
1016 let named = subtitle_plan("[ASS] → embedded".to_string(), &two, &[0]);
1017 assert_eq!(
1018 named,
1019 "[ASS] → embedded; [ASS] [FOR DUB] — in the palette, on no track"
1020 );
1021 assert!(
1022 named.chars().count() <= SUB_PLAN_CHARS,
1023 "two tracks fit the value box: {named}"
1024 );
1025 // Thirty-five off one file: twenty-two carry cues here, nine are
1026 // pictures, one could not be read, three have nothing on this timeline.
1027 let many: Vec<_> = (0..35)
1028 .map(|i| {
1029 let mut track = sub("/films/A Remux.mkv", Some(i), "eng — Subtitles");
1030 track.bitmap = (22..31).contains(&i);
1031 track.refused = (i == 31).then(|| "VobSub is pictures".to_string());
1032 track
1033 })
1034 .collect();
1035 // The picks are every track with a cue on the timeline: the twenty-two
1036 // and the nine picture ones, which the engine drops itself.
1037 let picks: Vec<usize> = (0..31usize).collect();
1038 let counted = subtitle_plan("22 tracks → embedded (…)".to_string(), &many, &picks);
1039 assert_eq!(
1040 counted,
1041 "22 of 35 → embedded; 9 pictures; 1 unread; 3 in the palette, on no track"
1042 );
1043 assert!(
1044 counted.chars().count() <= SUB_PLAN_CHARS,
1045 "thirty-five tracks still fit the value box: {counted}"
1046 );
1047 // Nothing on the timeline at all is still the engine's word for it.
1048 assert_eq!(subtitle_plan("none".to_string(), &[], &[]), "none");
1049 // The lanes are what an export writes once anything is placed on one, and
1050 // the engine words that whole ([`engine::export::planned_subtitles`]) --
1051 // including the lanes it carries *nothing* of, which is a sentence with no
1052 // pick behind it at all. That used to be dropped on the floor: the card said
1053 // "[ASS] — no cues here" twice and never said what became of the lane.
1054 let placed = "S1 [ASS] — past the last picture".to_string();
1055 assert_eq!(
1056 subtitle_plan(placed.clone(), &two, &[]),
1057 "S1 [ASS] — past the last picture; [ASS] [FOR DUB] — in the palette, on no track"
1058 );
1059 // ...and the row that sentence speaks for gets no clause of its own: a line
1060 // that names a lane's track and then calls the same track unplaced is the
1061 // card contradicting itself in one breath.
1062 assert!(!subtitle_plan(placed, &two[..1], &[]).contains("in the palette"));
1063}
1064
1065/// The list is in the order tracks were added, which is not the order a
1066/// person reads it in: importing a second film puts its tracks after the
1067/// first film's, and importing a third `.srt` for the first film puts that
1068/// one last of all. The rows still read as three sources.
1069#[test]
1070fn subtitle_rows_group_a_source_however_they_were_added() {
1071 let tracks = [
1072 sub("/films/a.mkv", Some(1), "eng"),
1073 sub("/films/b.mkv", Some(1), "eng"),
1074 sub("/films/a.mkv", Some(2), "fre"),
1075 sub("/subs/late.srt", None, "late.srt"),
1076 sub("/films/b.mkv", Some(3), "ger"),
1077 ];
1078 let groups = subtitle_rows(&tracks);
1079 assert_eq!(
1080 groups.iter().map(|g| g.name.as_str()).collect::<Vec<_>>(),
1081 ["a", "b", "late"],
1082 "one group per file, in the order the files first appear"
1083 );
1084 assert_eq!(
1085 groups
1086 .iter()
1087 .map(|g| g.rows.iter().map(|r| r.label.as_str()).collect::<Vec<_>>())
1088 .collect::<Vec<_>>(),
1089 [vec!["eng", "fre"], vec!["eng", "ger"], vec!["late.srt"]],
1090 "a file's tracks are contiguous and in add order"
1091 );
1092 // Numbered within the file, the way `row_name` numbers audio streams:
1093 // two tracks that both say "eng" are told apart by nothing else.
1094 assert_eq!(
1095 groups
1096 .iter()
1097 .map(|g| g.rows.iter().map(|r| r.number).collect::<Vec<_>>())
1098 .collect::<Vec<_>>(),
1099 [vec![1, 2], vec![1, 2], vec![1]]
1100 );
1101 // The swatch key is the file, so a group and that file's media rows
1102 // wear one colour -- and the standalone one has none.
1103 let sources = [Source {
1104 path: PathBuf::from("/films/a.mkv"),
1105 audio_stream: 0,
1106 }];
1107 assert_eq!(
1108 file_tint(&sources, &groups[0].path),
1109 Some(source_tint(0)),
1110 "the group carries the path the tint is asked by"
1111 );
1112 assert_eq!(file_tint(&sources, &groups[2].path), None);
1113 // What a header's "N tracks" says: the group's own row count, which is
1114 // 2, 2, 1 here -- a film that gave several tracks and a standalone
1115 // `.srt` that gave exactly one.
1116 assert_eq!(
1117 groups.iter().map(|g| g.rows.len()).collect::<Vec<_>>(),
1118 [2, 2, 1]
1119 );
1120 // A standalone `.srt` is already its own group, named after its own
1121 // file ("late", not lumped under some catch-all "External" bucket) --
1122 // there is no sourceless case for a header to special-case.
1123 assert_eq!(groups[2].name, "late");
1124 assert_eq!(groups[2].path, PathBuf::from("/subs/late.srt"));
1125}
1126
1127/// The fold a click on a header sets is keyed by [`SubGroup::path`]
1128/// (`Player::sub_folded`), so it has to survive the very thing regrouping
1129/// is for: a second track landing on a file already in the list, or one
1130/// being removed from it. The group's path is the fold's whole identity,
1131/// so it must not move under either.
1132#[test]
1133fn a_groups_fold_key_survives_a_track_arriving_or_leaving_its_file() {
1134 let before = [
1135 sub("/films/a.mkv", Some(1), "eng"),
1136 sub("/films/b.mkv", Some(1), "eng"),
1137 ];
1138 let after_add = [
1139 sub("/films/a.mkv", Some(1), "eng"),
1140 sub("/films/b.mkv", Some(1), "eng"),
1141 sub("/films/a.mkv", Some(2), "fre"),
1142 ];
1143 let (before_groups, after_groups) = (subtitle_rows(&before), subtitle_rows(&after_add));
1144 assert_eq!(before_groups[0].path, after_groups[0].path, "a's key held");
1145 assert_eq!(before_groups[1].path, after_groups[1].path, "b's key held");
1146 // The group a second track landed on grew; the other did not move.
1147 assert_eq!(after_groups[0].rows.len(), 2);
1148 assert_eq!(after_groups[1].rows.len(), 1);
1149 // Removing that same track back off leaves the original key and count.
1150 let after_remove = subtitle_rows(&before);
1151 assert_eq!(after_remove[0].path, before_groups[0].path);
1152 assert_eq!(after_remove[0].rows.len(), 1);
1153}
1154
1155/// What the strip header, the section heading and the toggle's notice all
1156/// say. Two films each carrying an "eng" track are one word apart until the
1157/// film is in the name; a film carrying two is one word apart from itself.
1158#[test]
1159fn the_picked_subtitle_is_named_with_the_film_it_came_out_of() {
1160 let tracks = [
1161 sub("/films/a.mkv", Some(1), "eng"),
1162 sub("/films/b.mkv", Some(1), "eng"),
1163 sub("/films/a.mkv", Some(2), "eng"),
1164 sub("/films/b.mkv", Some(2), "und"),
1165 sub("/subs/late.srt", None, "late.srt"),
1166 ];
1167 let name = |track| sub_pick_name(&tracks, track).expect("a track that is there");
1168 // The two "eng"s of two films: one file gave several so its tracks are
1169 // numbered, the other gave one so it is not.
1170 assert_eq!(name(0), "eng 1 — a");
1171 assert_eq!(name(2), "eng 2 — a");
1172 assert_eq!(name(1), "eng 1 — b");
1173 assert_ne!(name(0), name(1), "two films' eng tracks read apart");
1174 for picked in [name(0), name(1), name(2)] {
1175 assert!(picked.contains(" — a") || picked.contains(" — b"));
1176 }
1177 // "und" is the tag for "nobody said", humanised once by
1178 // `subtitle_rows` and not again here.
1179 assert_eq!(name(3), "unknown language 2 — b");
1180 // A standalone `.srt` is its own file and its label already says so:
1181 // one track, so no number, and no stem after it saying it again.
1182 assert_eq!(name(4), "late.srt");
1183 // The silence a row left over from a timeline that is gone gets.
1184 assert_eq!(sub_pick_name(&tracks, 5), None);
1185 assert_eq!(sub_pick_name(&[], 0), None);
1186}
1187
1188/// What the toggle covers is what is *placed*, so what it says is a lane fact:
1189/// naming the palette row the list happens to mark named a track the stroke
1190/// never touched ("SUBTITLES OFF — one.srt is still on the timeline" for a
1191/// one.srt nobody dragged anywhere).
1192#[test]
1193fn the_subtitles_toggle_says_what_is_placed_and_never_the_picked_row() {
1194 for on in [true, false] {
1195 let text = subtitle_toggle_notice(on, 2);
1196 assert!(text.contains('2'), "{text} counts the captions placed");
1197 assert!(
1198 !text.contains("track(s)") && !text.contains(" — a"),
1199 "{text} names no palette row"
1200 );
1201 }
1202 // Off leaves them on the lanes; that is the half a person needs told.
1203 assert!(subtitle_toggle_notice(false, 2).contains("still placed"));
1204 // An empty timeline says the state, not a count that reads as broken --
1205 // and DESIGN §8 (2026-08-27) keeps this a state report, not a "drag it"
1206 // instruction.
1207 let none = subtitle_toggle_notice(true, 0);
1208 assert!(!none.contains('0'), "{none} counts nothing at nothing");
1209 assert!(
1210 none.contains("nothing placed"),
1211 "{none} says the state, not the move"
1212 );
1213}
1214
1215/// The door this editor answers "don't make me import the film again" with:
1216/// it reads a file's subtitle tracks onto the open timeline -- a release's
1217/// `.mkv`, an `.srt` beside it -- while the file itself joins nothing.
1218///
1219/// Cleanse round 2 (2026-09-10) took its ghost row out of the dock's footer
1220/// along with the `IMPORT` head: one `Add` row is the dock's one door, and
1221/// `Add` itself forks a subtitle file to the same place. The verb keeps its
1222/// stroke, its KEYS row, and a pointer door of its own -- the dock's
1223/// right-click menu ([`DOCK_ITEMS`]), which an *empty* library carries too.
1224/// It is the action and not a second implementation of it, so the row, the
1225/// stroke and the actions card cannot drift apart, and the menu row is
1226/// oracle-gated like every other, so with no timeline open it dims and says
1227/// why instead of opening a chooser for nothing.
1228#[test]
1229fn the_dock_menu_carries_the_add_subtitles_door() {
1230 use crate::{ActionId, DOCK_ITEMS};
1231 assert!(
1232 DOCK_ITEMS.contains(&ActionId::ImportSubtitles)
1233 && DOCK_ITEMS.contains(&ActionId::PasteFilePath)
1234 && DOCK_ITEMS.contains(&ActionId::AddFiles),
1235 "the dock's right-click menu lost one of the three ways in"
1236 );
1237 // ...and that menu is actually opened from the Sources body.
1238 let dock = src_text("ui/dock_stance.rs");
1239 assert!(
1240 dock.contains("on: MenuOn::Dock,"),
1241 "nothing in the dock opens the menu that now carries the two imports"
1242 );
1243 // The rows are drawn from `DOCK_ITEMS` by the one menu render.
1244 let overlays = src_text("ui/overlays.rs");
1245 assert!(
1246 overlays.contains("MenuOn::Dock => DOCK_ITEMS.to_vec(),"),
1247 "the dock menu draws something other than the three import actions"
1248 );
1249 // `act(ActionId::ImportSubtitles, ...)` routes to `pick_and_add_subtitles`
1250 // -- the row names the action, not a second implementation of it.
1251 let actions = src_text("player/actions.rs");
1252 assert!(
1253 actions.contains("ActionId::ImportSubtitles => self.pick_and_add_subtitles(cx)"),
1254 "ImportSubtitles no longer opens the subtitle chooser"
1255 );
1256 // A subtitle file taken through the plain `Add files` door lands as
1257 // subtitles rather than as a source that cannot be read.
1258 let library = src_text("player/library.rs");
1259 assert!(
1260 library.contains("if is_subtitle(path) {"),
1261 "Add files no longer forks a .srt/.vtt to the subtitle list"
1262 );
1263}
1264
1265/// The Darkroom keeps imported subtitle tracks in the Text tab itself (moved
1266/// off the unconditional spot under the Sources list, user 2026-08-27), where
1267/// a row can be selected, folded with its source, removed, and dragged to the
1268/// bench's existing subtitle-lane target.
1269#[test]
1270fn the_darkroom_subtitle_palette_drags_tracks_to_subtitle_lanes() {
1271 let dock = src_text("ui/dock_stance.rs");
1272 let palette = &dock[dock
1273 .find("fn subtitle_tab_rows")
1274 .expect("no Darkroom subtitle rows")..];
1275 for required in [
1276 "subtitle_rows",
1277 "dock-subtitle-group",
1278 "sub_folded.remove",
1279 "sub_folded.insert",
1280 "this.sub_track = track",
1281 ".on_drag(SubPick(track)",
1282 "remove_subtitle_track(track",
1283 ] {
1284 assert!(palette.contains(required), "palette lost {required}");
1285 }
1286 let bench = src_text("ui/bench_stance.rs");
1287 let drop_at = bench
1288 .find(".drag_over::<SubPick>")
1289 .expect("no subtitle-track lane target");
1290 let drop = &bench[drop_at..(drop_at + 500).min(bench.len())];
1291 assert!(
1292 drop.contains("this.place_sub(drag.0, lane"),
1293 "a dock subtitle drag does not place on the lane: {drop}"
1294 );
1295}
1296
1297/// A file's subtitle tracks are that file's subset and are listed as one:
1298/// directly under the row that names it, never after every unrelated file
1299/// (user 2026-09-10, screenshot -- two screen recordings sat between a film
1300/// and its own subtitle group). A `.srt` nobody carries stays top-level, in
1301/// arrival order, at the end.
1302#[test]
1303fn a_file_subtitle_group_follows_its_own_row() {
1304 use crate::ui::dock_stance::{Slot, source_list_order};
1305 let film = PathBuf::from("/films/a.mkv");
1306 let other = PathBuf::from("/rec/b.mp4");
1307 let loose = PathBuf::from("/subs/late.srt");
1308 assert_eq!(
1309 source_list_order(
1310 &[film.clone(), other.clone()],
1311 &[film.clone(), loose.clone()]
1312 ),
1313 [Slot::Media(0), Slot::Subs(0), Slot::Media(1), Slot::Subs(1)],
1314 "the film's own tracks must sit between it and the next file"
1315 );
1316 // A file with several audio streams has several rows; the tracks follow
1317 // the last of them, so the file's own rows stay together.
1318 assert_eq!(
1319 source_list_order(
1320 &[film.clone(), other.clone(), film.clone()],
1321 &[film.clone()]
1322 ),
1323 [
1324 Slot::Media(0),
1325 Slot::Media(1),
1326 Slot::Media(2),
1327 Slot::Subs(0)
1328 ],
1329 );
1330 // Nobody's `.srt`: still a top-level row, still last.
1331 assert_eq!(
1332 source_list_order(&[other], &[loose]),
1333 [Slot::Media(0), Slot::Subs(0)],
1334 );
1335}
1336
1337/// ...and the Sources list is *built* through that ordering rather than by
1338/// appending the subtitle groups after the media rows, which is what put a
1339/// film's own tracks at the end of the list.
1340#[test]
1341fn the_sources_list_is_built_through_the_ordering() {
1342 let dock = src_text("ui/dock_stance.rs");
1343 let tab = &dock[dock.find("fn sources_tab").expect("no sources tab")..];
1344 assert!(
1345 tab.contains("source_list_order(&media, &subs)"),
1346 "the Sources list no longer goes through source_list_order"
1347 );
1348 assert!(
1349 !tab.contains("row_elements.extend(subtitles)"),
1350 "the subtitle groups are appended after every source again"
1351 );
1352 // A parent already in the list gets the tracks bare, under it.
1353 let palette = &dock[dock.find("fn subtitle_tab_rows").expect("no subtitle rows")..];
1354 assert!(
1355 palette.contains("let nested = parents.contains(&group.path)")
1356 && palette.contains("let has_header = !nested || track_count > 3"),
1357 "a group under its own parent still draws a group row"
1358 );
1359}
1360
1361/// Two files whose rows read the same word are told apart on the metadata
1362/// line -- the folder, or `#n` when the folder is shared too.
1363#[test]
1364fn same_named_files_are_told_apart_on_the_metadata_line() {
1365 let three: Vec<Source> = ["/a/rec.mp4", "/b/rec.mp4", "/a/solo.mp4"]
1366 .into_iter()
1367 .map(|path| Source {
1368 path: PathBuf::from(path),
1369 audio_stream: 0,
1370 })
1371 .collect();
1372 let rows = library_rows(&three, &HashMap::new(), &HashMap::new(), None, |_| 90);
1373 assert_eq!(
1374 rows.iter()
1375 .map(|row| row.detail.as_str())
1376 .collect::<Vec<_>>(),
1377 ["a", "b", ""],
1378 "twins say which folder they came out of"
1379 );
1380 let twins: Vec<Source> = ["/a/rec.mp4", "/a/rec.mkv"]
1381 .into_iter()
1382 .map(|path| Source {
1383 path: PathBuf::from(path),
1384 audio_stream: 0,
1385 })
1386 .collect();
1387 let rows = library_rows(&twins, &HashMap::new(), &HashMap::new(), None, |_| 90);
1388 assert_eq!(
1389 rows.iter()
1390 .map(|row| row.detail.as_str())
1391 .collect::<Vec<_>>(),
1392 ["#1", "#2"],
1393 "one folder, one stem: arrival order tells them apart"
1394 );
1395}
1396
1397/// A subtitle group's header in the Text tab must not vanish on a short
1398/// window: `subtitle_tab_rows` draws one per group unconditionally -- there
1399/// is no viewport-height gate on it at all any more, so the list under it
1400/// is what would scroll instead, never the header itself. And it has to be
1401/// a real fold, not the click-cycling pattern this codebase has already
1402/// thrown out once: one click toggles `sub_folded` shut or open, it never
1403/// steps through more than those two states.
1404#[test]
1405fn a_subtitle_group_header_is_never_gated_on_window_height() {
1406 let dock = src_text("ui/dock_stance.rs");
1407 assert!(
1408 !dock.contains("sub_headers_fit"),
1409 "the header is still gated on the viewport's height"
1410 );
1411 // The header is a click target that flips membership in a set --
1412 // `remove` else `insert` -- not a value stepped through several states.
1413 let head_at = dock
1414 .find("\"dock-subtitle-group\"")
1415 .expect("no id on the group header");
1416 // Wide enough to reach the count line past the header's styling and its
1417 // commentary -- a window that stops short reads as the line deleted
1418 // (the same fixed-window misfire the modal-guard scan had, 2026-08-27).
1419 let block = &dock[head_at..(head_at + 3600).min(dock.len())];
1420 assert!(
1421 block.contains("sub_folded.remove"),
1422 "no fold-open path: {block}"
1423 );
1424 assert!(
1425 block.contains("sub_folded.insert"),
1426 "no fold-shut path: {block}"
1427 );
1428 assert!(
1429 block.contains("{track_count} track"),
1430 "the header does not say how many tracks it holds: {block}"
1431 );
1432}
1433
1434/// The one thing regrouping must not break: `sub_track` is a flat index
1435/// into the add-order list, a click sets it and a save writes it into the
1436/// `.edith`. Every row must still name the track it was made from -- rows
1437/// for refused tracks included, because they take a number in that list
1438/// whether or not anyone can pick them.
1439#[test]
1440fn a_subtitle_row_names_the_flat_track_it_was_made_from() {
1441 let mut tracks = vec![
1442 sub("/films/a.mkv", Some(1), "eng"),
1443 sub("/films/b.mkv", Some(1), "eng"),
1444 sub("/films/a.mkv", Some(2), "fre"),
1445 ];
1446 // Track 1 of b is pictures: still a row, still index 1 of the list.
1447 tracks[1].bitmap = true;
1448 tracks[1].refused = Some("PGS subtitles are pictures".to_string());
1449 let groups = subtitle_rows(&tracks);
1450 let flat: Vec<(usize, &str)> = groups
1451 .iter()
1452 .flat_map(|g| g.rows.iter().map(|r| (r.track, r.label.as_str())))
1453 .collect();
1454 assert_eq!(flat, [(0, "eng"), (2, "fre"), (1, "eng")]);
1455 for (track, label) in flat {
1456 assert_eq!(
1457 tracks[track].label, label,
1458 "row {track} picks the track it names"
1459 );
1460 }
1461 // (c) The refused one is here, saying why, and greyable by that alone.
1462 let refused = &groups[1].rows[0];
1463 assert_eq!(
1464 refused.refused.as_deref(),
1465 Some("PGS subtitles are pictures")
1466 );
1467 assert_eq!(refused.detail, "PGS subtitles are pictures");
1468 assert!(refused.bitmap);
1469 // ...and it was counted: the row after it in add order is still 2.
1470 assert_eq!(groups[0].rows[1].track, 2);
1471}
1472
1473/// The × on a row shifts every track after it down one, and the pick is
1474/// what an export writes into the file -- so a pick that stayed put would
1475/// silently change which track the next export carries. Every relation
1476/// between the pick and the row that went, on a list of three.
1477#[test]
1478fn removing_a_subtitle_row_carries_the_pick_with_it() {
1479 // A row *before* the pick: the same track stays picked, one index down.
1480 assert_eq!(sub_pick_after_removal(2, 0, 2), 1);
1481 assert_eq!(sub_pick_after_removal(2, 1, 2), 1);
1482 // A row *after* it: the pick has not moved and neither has its index.
1483 assert_eq!(sub_pick_after_removal(0, 2, 2), 0);
1484 assert_eq!(sub_pick_after_removal(1, 2, 2), 1);
1485 // The picked row itself: the one that slid into its place...
1486 assert_eq!(sub_pick_after_removal(1, 1, 2), 1);
1487 // ...and the last row when the picked one was the last, since there is
1488 // nothing after it to slide.
1489 assert_eq!(sub_pick_after_removal(2, 2, 2), 1);
1490 // The last row of all: an emptied list is legal for subtitles, and the
1491 // section is not drawn at all at that point.
1492 assert_eq!(sub_pick_after_removal(0, 0, 0), 0);
1493}
1494
1495/// A `^z` moves rows without saying which one moved, so the pick is followed by
1496/// what it *names* ([`sub_pick_after_restore`]) rather than by its index: the
1497/// same three rows as the removal test above, restored instead of taken away,
1498/// where the index is the wrong answer in the first case and the right one in
1499/// the second.
1500#[test]
1501fn a_restored_palette_carries_the_pick_by_what_it_names() {
1502 let palette = [
1503 sub("/films/a.mkv", Some(1), "eng"),
1504 sub("/films/a.mkv", Some(2), "fre"),
1505 sub("/films/a.mkv", Some(3), "ger"),
1506 ];
1507 // The pick on "ger" at index 1 of the two rows a removal of the first left.
1508 let short = [palette[1].clone(), palette[2].clone()];
1509 let picked = SubPickKey::of(&short, 1).expect("a row the pick names");
1510 assert_eq!(
1511 sub_pick_after_restore(1, Some(&picked), &palette),
1512 2,
1513 "the row above it came back"
1514 );
1515 // The row that came back *below* the pick leaves it where it was.
1516 let short = [palette[0].clone(), palette[1].clone()];
1517 let picked = SubPickKey::of(&short, 1).expect("a row the pick names");
1518 assert_eq!(
1519 sub_pick_after_restore(1, Some(&picked), &palette),
1520 1,
1521 "a row after it is not its business"
1522 );
1523 // The picked row itself gone from the restored palette: the old index
1524 // clamped into it, which is the removal door's own fallback.
1525 let picked = SubPickKey::of(&palette, 2).expect("a row the pick names");
1526 assert_eq!(sub_pick_after_restore(2, Some(&picked), &palette[..2]), 1);
1527 assert_eq!(
1528 sub_pick_after_restore(0, None, &[]),
1529 0,
1530 "an emptied palette is a state, not a panic"
1531 );
1532}
1533
1534/// The same claim from the click's end, on the order imports actually
1535/// arrive in: two films opened one after the other and an `.srt` dropped
1536/// last interleave in the flat list, and the display reorders them. What a
1537/// click sets is the row's own `track`, so the *n*th row on screen has to
1538/// pick the track it shows and the echoes have to name that same file.
1539#[test]
1540fn a_click_on_a_regrouped_row_picks_the_track_that_row_shows() {
1541 let tracks = [
1542 sub("/films/a.mkv", Some(1), "eng"),
1543 sub("/films/b.mkv", Some(1), "eng"),
1544 sub("/films/a.mkv", Some(2), "fre"),
1545 sub("/subs/late.srt", None, "late.srt"),
1546 sub("/films/b.mkv", Some(3), "ger"),
1547 ];
1548 let rows: Vec<_> = subtitle_rows(&tracks)
1549 .into_iter()
1550 .flat_map(|group| {
1551 group
1552 .rows
1553 .into_iter()
1554 .map(move |row| (group.path.clone(), row))
1555 })
1556 .collect();
1557 // Read top to bottom, the rows are no longer in add order...
1558 assert_eq!(
1559 rows.iter().map(|(_, row)| row.track).collect::<Vec<_>>(),
1560 [0, 2, 1, 4, 3]
1561 );
1562 for (path, row) in &rows {
1563 // ...and what the click writes into `sub_track` -- and a save into
1564 // the `.edith` -- still lands on the track the row is showing.
1565 let picked = &tracks[row.track];
1566 assert_eq!(&picked.path, path, "row {} picks another file", row.track);
1567 assert_eq!(lang_human(&picked.label), row.label);
1568 // And the heading, the strip and the notice name that same file
1569 // back, so a click cannot leave the echoes pointing elsewhere.
1570 let echo = sub_pick_name(&tracks, row.track).expect("the row's own track");
1571 let stem = path.file_stem().expect("a fixture path").to_string_lossy();
1572 assert!(
1573 echo.contains(&*stem),
1574 "picked {}, echoed {echo}",
1575 path.display()
1576 );
1577 }
1578}
1579
1580/// "und" is what a muxer writes when nobody said what the language is. A
1581/// row showing it verbatim names a language nobody speaks.
1582#[test]
1583fn an_untagged_language_says_it_is_unknown() {
1584 assert_eq!(lang_human("und"), "unknown language");
1585 assert_eq!(lang_human("eng"), "eng");
1586 assert_eq!(lang_human("fre — Commentary"), "fre — Commentary");
1587 // Reaching the subtitle rows too: a track whose only name was the tag.
1588 let groups = subtitle_rows(&[sub("/films/a.mkv", Some(1), "und")]);
1589 assert_eq!(groups[0].rows[0].label, "unknown language");
1590 // The pair, read as the pair: the row title comes off `language` and
1591 // `name` and never out of the flattened label, which is what let an
1592 // "und" beside a title through as a language nobody speaks. A refused
1593 // track states neither and keeps its label.
1594 let titled = |language: &str, name: &str, label: &str| engine::subtitle::SubtitleTrack {
1595 path: PathBuf::from("/films/a.mkv"),
1596 track: Some(1),
1597 language: language.into(),
1598 name: name.into(),
1599 label: label.into(),
1600 cues: Vec::new(),
1601 bitmap: false,
1602 refused: None,
1603 };
1604 for (language, name, label, title) in [
1605 ("fra", "Signs", "fra — Signs", "fra — Signs"),
1606 ("und", "Signs", "Signs", "Signs"),
1607 ("und", "", "und", "unknown language"),
1608 ("", "late.srt", "late.srt", "late.srt"),
1609 ("", "", "eng", "eng"),
1610 ] {
1611 let rows = subtitle_rows(&[titled(language, name, label)]);
1612 assert_eq!(rows[0].rows[0].label, title, "{language:?} {name:?}");
1613 }
1614}
1615
1616/// The bug: an empty timeline is end-of-stream from its one black frame
1617/// onward, so the pump had `done` set before anything was ever pressed --
1618/// and the transport's restart branch read that as "played out, start from
1619/// the top". It started a clock against a zero-length timeline, which was
1620/// `done` again by the next repaint, so every further press restarted it
1621/// too: the button read "Pause" and no press of it ever paused.
1622///
1623/// What holds it now is one predicate, checked here against real sessions
1624/// on both sides -- the emptied one refuses, a timeline with clips on it
1625/// does not.
1626#[test]
1627fn an_empty_timeline_has_nothing_to_play() {
1628 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1629 // Silent like the engine suite: this opens the real device.
1630 session.set_gain(0.0);
1631 // A timeline with clips on it plays, and always did: the guard must not
1632 // touch that side.
1633 assert!(!session.is_empty());
1634 assert!(!nothing_to_play(Some(&session)));
1635
1636 // Every clip taken off, which is a state and not a failure.
1637 while session.delete_clip(Lane::V1, 0) {}
1638 while session.delete_clip(Lane::A1, 0) {}
1639 assert!(session.is_empty(), "the timeline is empty");
1640 assert_eq!(session.timeline_duration(), 0.0);
1641
1642 // What the pump does every render, and what set `done` before the fix:
1643 // the black frame goes by and the session is at its end at once.
1644 for _ in 0..40 {
1645 while session.try_frame().is_some() {}
1646 std::thread::sleep(Duration::from_millis(10));
1647 }
1648 assert!(
1649 session.is_eos(),
1650 "an empty timeline is done before it starts"
1651 );
1652
1653 // So the press is refused rather than sent down the restart branch --
1654 // and with no session at all it is the same refusal.
1655 assert!(nothing_to_play(Some(&session)));
1656 assert!(nothing_to_play(None));
1657 assert!(!session.is_playing(), "and nothing was started");
1658}
1659
1660/// The slider writes the same numbers the keys do, and mute is not one of
1661/// them: dragging while muted picks the level unmuting comes back to.
1662#[test]
1663fn the_slider_lands_on_the_grid_the_keys_move_on() {
1664 let mut volume = Volume::default();
1665 // Both ends exactly, and clamped past them.
1666 volume.set_along(0.);
1667 assert_eq!(volume.gain(), 0.0);
1668 assert_eq!(volume.label(), "Vol 0%");
1669 volume.set_along(1.5);
1670 assert_eq!(volume.gain(), 1.0);
1671 assert_eq!(volume.along(), 1.0);
1672
1673 // Halfway is 50%, and a key press from there is 5% -- the same step
1674 // count as before, on a finer grid.
1675 volume.set_along(0.5);
1676 assert_eq!(volume.label(), "Vol 50%");
1677 volume.step(true);
1678 assert_eq!(volume.label(), "Vol 55%");
1679 volume.step(false);
1680 assert_eq!(volume.gain(), 0.5);
1681
1682 // A number no step lands on comes back as the nearest one, so the label
1683 // and the fill are the same value the device was handed.
1684 volume.set_along(0.333);
1685 assert_eq!(volume.label(), "Vol 33%");
1686 assert_eq!(volume.along(), 0.33);
1687
1688 // Muted, the drag moves the level and nothing comes out.
1689 volume.muted = true;
1690 volume.set_along(0.8);
1691 assert_eq!(volume.gain(), 0.0);
1692 assert_eq!(volume.label(), "Muted 80%");
1693 volume.muted = false;
1694 assert_eq!(volume.gain(), 0.8);
1695}
1696
1697/// The slider lands where it paints: the arithmetic `Player::drag_volume`
1698/// runs over the bar's own painted width, which is the one thing a test of
1699/// it can share without re-deriving it.
1700#[test]
1701fn the_volume_slider_lands_where_it_paints() {
1702 let bar = Bounds {
1703 origin: point(px(420.), px(508.)),
1704 size: size(px(VOLUME_W), px(CONTROL_H)),
1705 };
1706 let at = |x: f32| {
1707 let mut volume = Volume::default();
1708 volume.set_along(frac_along(px(x), bar));
1709 volume
1710 };
1711 assert_eq!(at(420.).gain(), 0.0, "the left end is silence");
1712 assert_eq!(at(420. + VOLUME_W).gain(), 1.0, "the right end is full");
1713 assert_eq!(at(-4000.).gain(), 0.0, "off the left clamps");
1714 assert_eq!(at(9999.).gain(), 1.0, "off the right clamps");
1715 // Every pixel along it: a level the keys could also reach, painted back
1716 // where the hand pressed to within the half step the rounding costs.
1717 for step in 0..=(VOLUME_W as u32) {
1718 let along = step as f32 / VOLUME_W;
1719 let volume = at(420. + along * VOLUME_W);
1720 let painted = volume.along();
1721 let slack = 0.5 / f32::from(Volume::MAX_STEPS) + 1e-4;
1722 assert!(
1723 (painted - along).abs() <= slack,
1724 "pressed at {along}, paints at {painted}"
1725 );
1726 }
1727}
1728
1729/// Darkroom lane heads dispatch only verbs that apply to the lane under the
1730/// pointer; source checks pin the visible pointer doors to that guarded path.
1731#[test]
1732fn darkroom_lane_header_verbs_are_targeted_and_visible() {
1733 let live = Ctx {
1734 timeline: true,
1735 ..Ctx::default()
1736 };
1737 assert_eq!(enable_lane(ActionId::Mix, Lane::A1, live), Enable::Yes);
1738 assert_eq!(
1739 enable_lane(ActionId::RemoveVideoLane, Lane::V1, live),
1740 Enable::Yes
1741 );
1742 assert_eq!(
1743 enable_lane(ActionId::RemoveAudioLane, Lane::A1, live),
1744 Enable::Yes
1745 );
1746 assert!(matches!(
1747 enable_lane(ActionId::Mix, Lane::V1, live),
1748 Enable::Hidden(_)
1749 ));
1750
1751 // The head itself carries a dot, a name and -- on a subtitle lane -- its
1752 // eye, and nothing else (cleanse round 2). Its mix and its remove are rows
1753 // in its own right-click menu instead, and they still reach the lane the
1754 // hand named rather than the last of the kind a bare stroke walks to:
1755 // `overlays.rs` routes those rows through the same `act_lane` door the
1756 // head's buttons used.
1757 let bench = src_text("ui/bench_stance.rs");
1758 for gone in [
1759 "\"bench-mix-lane\"",
1760 "\"bench-remove-lane\"",
1761 "lane.{}.remove",
1762 ] {
1763 assert!(!bench.contains(gone), "the lane head still wears {gone}");
1764 }
1765 for door in ["\"bench-show-sub-lane\"", "this.show_sub_lane(lane, cx)"] {
1766 assert!(bench.contains(door), "lane header lost {door}");
1767 }
1768 assert!(
1769 lane_items(Lane::A1).contains(&ActionId::Mix)
1770 && lane_items(Lane::A1).contains(&ActionId::RemoveAudioLane)
1771 && lane_items(Lane::V1).contains(&ActionId::RemoveVideoLane)
1772 && !lane_items(Lane::V1).contains(&ActionId::Mix),
1773 "a head verb left the head with no row in the head's own menu"
1774 );
1775 assert!(
1776 src_text("ui/overlays.rs").contains("this.act_lane(action, menu.lane, cx)"),
1777 "the head menu lane verbs no longer act on the lane that was clicked"
1778 );
1779 // Cleanse round 2 (2026-09-10): the monitoring cluster left the band
1780 // (chord + KEYS row only). What the band still owes a pointer is the
1781 // export range's two grips on the contact strip.
1782 let time_band = src_text("ui/timeband_stance.rs");
1783 for door in [
1784 "fn mark_grip(",
1785 "\"stance-strip-mark-in\"",
1786 "\"stance-strip-mark-out\"",
1787 "MARK_DRAG.with(|m| m.set(Some(action)))",
1788 ] {
1789 assert!(time_band.contains(door), "time band lost {door}");
1790 }
1791}
1792
1793/// The three seams a hand may move, and the two ends neither of them may be
1794/// dragged past: a panel dragged to nothing is a panel nobody can get back, and
1795/// a picture squeezed out by its two neighbours is that same loss from the
1796/// other side of the window.
1797#[test]
1798fn a_dragged_divider_stops_before_either_panel_disappears() {
1799 use crate::ui::theme::INSPECTOR_MIN_W;
1800 use crate::{
1801 SIDE_MAX_FRAC, SPLIT_W, Split, TIMELINE_MAX_SHARE, TOOLBAR_H, inspector_w, library_w,
1802 split_drag_size, split_size, timeline_fixed_h, timeline_h,
1803 };
1804 use gpui::{point, px, size};
1805
1806 let window = size(px(1280.), px(720.));
1807 // Untouched, every region is still the share the window gives it. The
1808 // timeline's answer is stated for both of its faces: the timeline fits
1809 // the bed with nothing to scroll to, and zoomed in past that line the
1810 // strip's row joins the furniture.
1811 assert_eq!(
1812 split_size(Split::Library, None, 2, window, false),
1813 library_w(1280.)
1814 );
1815 assert_eq!(
1816 split_size(Split::Inspector, None, 2, window, false),
1817 inspector_w(1280.)
1818 );
1819 assert_eq!(
1820 split_size(Split::Timeline, None, 2, window, false),
1821 timeline_h(2, false).min(720. * TIMELINE_SHARE)
1822 );
1823 assert_eq!(
1824 split_size(Split::Timeline, None, 2, window, true),
1825 timeline_h(2, true).min(720. * TIMELINE_SHARE)
1826 );
1827 // Dragged, it is what the hand asked for...
1828 assert_eq!(
1829 split_size(Split::Library, Some(300.), 2, window, false),
1830 300.
1831 );
1832 assert_eq!(
1833 split_size(Split::Timeline, Some(300.), 2, window, false),
1834 300.
1835 );
1836 // ...and never past either end of it.
1837 assert_eq!(
1838 split_size(Split::Library, Some(0.), 2, window, false),
1839 LIBRARY_MIN_W
1840 );
1841 assert_eq!(
1842 split_size(Split::Library, Some(9000.), 2, window, false),
1843 1280. * SIDE_MAX_FRAC
1844 );
1845 assert_eq!(
1846 split_size(Split::Inspector, Some(-40.), 2, window, false),
1847 INSPECTOR_MIN_W
1848 );
1849 // The timeline's own floor is a floor with a whole lane *drawn* in it. At
1850 // that height the column shows one row of a two-track project, so the line
1851 // saying the rest are below is drawn too -- out of the region's pixels,
1852 // not out of the lane's. Left unbudgeted the header came out 27 px of its
1853 // 48 and the track's name, its subtitle dot and its × were cut in half.
1854 // Stated for the strip-bearing face, the taller of the two -- that is the
1855 // one the clamp has to hold at the 640x360 floor.
1856 let floor = split_size(Split::Timeline, Some(0.), 2, window, true);
1857 assert_eq!(floor, timeline_fixed_h(true) + LANE_H + LABEL_H + 8.);
1858 // The same arithmetic the timeline lays the column out with
1859 // ([`Player::timeline`]): what the affordance costs comes off the box, and
1860 // a whole lane is still standing under it.
1861 let lanes_box = floor - timeline_fixed_h(true);
1862 assert!(lanes_box < lanes_h(2), "no line to pay for at the floor");
1863 assert!(
1864 lanes_box - LABEL_H - 8. >= LANE_H,
1865 "the floor leaves {} px for a {LANE_H} px lane",
1866 lanes_box - LABEL_H - 8.
1867 );
1868 // A lone track has nothing below it and pays nothing for the line -- the
1869 // floor is a floor, not a reserved corridor.
1870 assert_eq!(
1871 split_size(Split::Timeline, Some(0.), 1, window, true),
1872 timeline_fixed_h(true) + LANE_H
1873 );
1874 // A size dragged with one track and kept while a second arrives is raised
1875 // to the new floor as it is read, not silently drawn under it.
1876 assert_eq!(
1877 split_size(Split::Timeline, Some(126.), 2, window, true),
1878 floor
1879 );
1880 // And the floor still fits the share the shortest window gives the region.
1881 assert!(floor <= 360. * TIMELINE_SHARE, "{floor} px will not fit");
1882 assert_eq!(
1883 split_size(Split::Timeline, Some(9000.), 2, window, true),
1884 720. * TIMELINE_MAX_SHARE
1885 );
1886 // A window too narrow to honour both ends keeps the floor rather than
1887 // panicking inside `clamp`, which is what a ceiling under its own floor
1888 // does.
1889 let narrow = size(px(600.), px(360.));
1890 assert_eq!(
1891 split_size(Split::Inspector, Some(9000.), 2, narrow, false),
1892 INSPECTOR_MIN_W
1893 );
1894
1895 // The pointer turned into a size: the panel follows the hand, and the two
1896 // that do not start at the window's own edge are measured from the far one.
1897 // Half a strip off each, because the strip is grabbed by its middle.
1898 assert_eq!(
1899 split_drag_size(Split::Library, point(px(300.), px(400.)), window),
1900 300. - SPLIT_W / 2.
1901 );
1902 assert_eq!(
1903 split_drag_size(Split::Inspector, point(px(1000.), px(400.)), window),
1904 280. - SPLIT_W / 2.
1905 );
1906 // The seam sits above the fixed toolbar, so what the pointer leaves under
1907 // it is that strip and the timeline together.
1908 assert_eq!(
1909 split_drag_size(Split::Timeline, point(px(300.), px(500.)), window),
1910 220. - TOOLBAR_H - SPLIT_W / 2.
1911 );
1912}
1913
1914/// The darkroom's own two seams (`Split::Dock`, `Split::Bench`): a hand may
1915/// not drag either past its floor or its ceiling, the same promise
1916/// [`a_dragged_divider_stops_before_either_panel_disappears`] makes for the
1917/// legacy three.
1918#[test]
1919fn the_darkroom_seams_stop_before_either_side_disappears() {
1920 use crate::ui::theme::INSPECTOR_MIN_W;
1921 use crate::{
1922 BENCH_MIN_H, SIDE_MAX_FRAC, SPLIT_W, Split, split_bounds, split_drag_size, split_size,
1923 };
1924 use gpui::{point, px, size};
1925
1926 let window = size(px(1280.), px(720.));
1927 // Untouched, each answers its own stance default.
1928 assert_eq!(
1929 split_size(Split::Dock, None, 2, window, false),
1930 crate::ui::stance::DOCK_W
1931 );
1932 assert_eq!(
1933 split_size(Split::Bench, None, 2, window, false),
1934 crate::ui::stance::BENCH_H
1935 );
1936 // Dragged, it is what the hand asked for...
1937 assert_eq!(split_size(Split::Dock, Some(400.), 2, window, false), 400.);
1938 assert_eq!(split_size(Split::Bench, Some(300.), 2, window, false), 300.);
1939 // ...and never past the floor...
1940 assert_eq!(
1941 split_size(Split::Dock, Some(0.), 2, window, false),
1942 INSPECTOR_MIN_W
1943 );
1944 assert_eq!(
1945 split_size(Split::Bench, Some(0.), 2, window, false),
1946 BENCH_MIN_H
1947 );
1948 // ...nor the ceiling. The bench's is not a window-share one -- it leaves
1949 // the screen and time band a fixed 160px, [`split_bounds`]'s own reason.
1950 assert_eq!(
1951 split_size(Split::Dock, Some(9000.), 2, window, false),
1952 1280. * SIDE_MAX_FRAC
1953 );
1954 let (_, bench_max) = split_bounds(Split::Bench, 2, window, false);
1955 assert_eq!(
1956 split_size(Split::Bench, Some(9000.), 2, window, false),
1957 bench_max
1958 );
1959 assert!(bench_max < 720.);
1960 // The pointer turned into a size, half a strip off for the same reason
1961 // the legacy seams read it that way.
1962 assert_eq!(
1963 split_drag_size(Split::Dock, point(px(1000.), px(400.)), window),
1964 280. - SPLIT_W / 2.
1965 );
1966 assert_eq!(
1967 split_drag_size(Split::Bench, point(px(300.), px(500.)), window),
1968 220. - crate::ui::stance::LEDGER_H - SPLIT_W / 2.
1969 );
1970}
1971
1972/// At the bench's floor, both default lanes' rows actually fit inside the
1973/// `bench-lanes` column `bench_stance::render` gives them -- not just each
1974/// row's own clamped height, but their *sum plus the gap between them*,
1975/// since `bench-lanes` scrolls rather than clipping visibly and a sum that
1976/// overruns the column loses its bottom row's pixels off-screen, unscrolled
1977/// (this session's F1: the A1 lane's clip-bar border and status dot, cut by
1978/// ~2px at the old `BENCH_MIN_H = 80.`).
1979#[test]
1980fn both_default_lanes_fit_the_bench_at_its_floor() {
1981 use crate::BENCH_MIN_H;
1982 use crate::ui::bench_stance::{LANE_MIN_H, ROW_GAP, RULER_H, row_h};
1983 use crate::ui::stance::BENCH_CHROME_H;
1984
1985 let box_h = BENCH_MIN_H - BENCH_CHROME_H;
1986 let avail = box_h - RULER_H - ROW_GAP;
1987 let h = row_h(2, avail);
1988 // Not an exact `LANE_MIN_H` any more: `BENCH_MIN_H` now carries one spare
1989 // row (`layout::LEDGER_SEAM_CLEARANCE`) so the last lane's own last pixel
1990 // never shares a row with the ledger's border, which lands here as
1991 // `avail` being a touch over the two-rows-plus-gap tight fit.
1992 assert!(
1993 h >= LANE_MIN_H,
1994 "the floor should give both lanes at least their own minimum ({h} < {LANE_MIN_H})"
1995 );
1996 let content = 2. * h + ROW_GAP;
1997 assert!(
1998 content <= avail + 1e-4,
1999 "the two lane rows ({content}px) overrun the column ({avail}px) -- \
2000 the bottom lane's pixels get cut, unscrolled"
2001 );
2002}
2003
2004/// `BENCH_CHROME_H` on its own: the previous test's `box_h = BENCH_MIN_H -
2005/// BENCH_CHROME_H` line trusts `BENCH_CHROME_H` to already be correct, so it
2006/// cannot catch `BENCH_CHROME_H` itself drifting -- which is exactly how the
2007/// third clip (this session's) survived it: the constant undercounted the
2008/// section head's real line box by 1px and this test's predecessor never
2009/// looked. Recomputes what `ui::stance::bench` actually draws above
2010/// `bench_stance::render`'s content -- the div's own `.border_t_1()` (1px)
2011/// + its `py(4.)` top padding + the section head's real line box at gpui's
2012/// golden-ratio line-height, not the label's bare font size (the same trap
2013/// `a_lane_row_fits_what_its_own_head_draws` already checks for the lane
2014/// heads) -- and then checks the *whole* stack -- chrome, ruler, both gaps,
2015/// both lanes, and the clear row the ledger's own fixed-position border
2016/// needs (`LEDGER_SEAM_CLEARANCE`, not exported, so this recomputes it as
2017/// `BENCH_MIN_H` minus every other named term) -- fits inside `BENCH_MIN_H`
2018/// with nothing left over uncounted. This binary carries no `TestAppContext`
2019/// to mount `ui::stance::bench` and `ui::stance::ledger` for real and read
2020/// painted bounds back, so it stays geometry-only, same as its neighbours.
2021#[test]
2022fn the_whole_bench_stack_fits_its_own_floor_with_the_ledger_seam_clear() {
2023 use crate::BENCH_MIN_H;
2024 use crate::ui::bench_stance::{LANE_MIN_H, ROW_GAP, RULER_H};
2025 use crate::ui::stance::BENCH_CHROME_H;
2026
2027 const BENCH_BORDER_T: f32 = 1.;
2028 const BENCH_PY_TOP: f32 = 4.;
2029 // No section head any more (cleanse round 2): the border and the padding
2030 // are the whole of what `stance::bench` draws above the ruler.
2031 let real_chrome = BENCH_BORDER_T + BENCH_PY_TOP;
2032 assert_eq!(
2033 BENCH_CHROME_H, real_chrome,
2034 "BENCH_CHROME_H ({BENCH_CHROME_H}) does not match what `stance::bench` \
2035 actually draws above the content ({real_chrome}px: {BENCH_BORDER_T}px \
2036 border + {BENCH_PY_TOP}px padding) -- bench_stance::render gets handed the wrong box_h and lays its \
2037 rows out past its own real space"
2038 );
2039
2040 // The ledger's own fixed-position border needs one more clear row below
2041 // the last lane, on top of chrome + ruler + both gaps + both lanes --
2042 // recomputed here rather than importing the private
2043 // `layout::LEDGER_SEAM_CLEARANCE`, so this test fails if that term is
2044 // ever silently dropped from `BENCH_MIN_H`'s own sum.
2045 let content_need = real_chrome + RULER_H + ROW_GAP + 2. * LANE_MIN_H + ROW_GAP;
2046 let ledger_seam_clearance = BENCH_MIN_H - content_need;
2047 assert!(
2048 ledger_seam_clearance >= 1. - 1e-4,
2049 "BENCH_MIN_H ({BENCH_MIN_H}) leaves only {ledger_seam_clearance}px \
2050 between the last lane row and the ledger's own top border -- driven \
2051 at exactly the content's need (0px clearance) the border still won \
2052 the shared pixel and clipped the last lane's status dot"
2053 );
2054}
2055
2056/// The previous test asserted lane ROWS fit the bench column -- not that a
2057/// lane's own CONTENT fits its row, which is how the defect it fixed
2058/// survived it: at the old `LANE_MIN_H` of `18.` both lanes fit the bench
2059/// exactly while V1's status dot silently overflowed into A1's row (masked)
2060/// and A1's overflowed into the ledger (visible, since A1 has no next row).
2061/// This binary carries no `TestAppContext` to mount a real `lane_row` and
2062/// read its painted bounds back, so this recomputes the label's own line
2063/// box from the constants `lane_row` actually draws with (gpui's default
2064/// `TextStyle::line_height` is the golden ratio, not 1x the font size --
2065/// see `LANE_MIN_H`'s own doc comment) rather than a literal, so a future
2066/// shrink of `LANE_MIN_H` or growth of the label size fails this instead of
2067/// silently clipping the last lane again.
2068#[test]
2069fn a_lane_row_fits_what_its_own_head_draws() {
2070 use crate::ui::bench_stance::{LANE_DOT_D, LANE_HEAD_GAP, LANE_MIN_H};
2071 use crate::ui::type_scale::CHORD_METADATA_MIN_PX;
2072
2073 let label_line_h = (CHORD_METADATA_MIN_PX * 1.618_034).round();
2074 let content = label_line_h + LANE_HEAD_GAP + LANE_DOT_D;
2075 assert!(
2076 LANE_MIN_H >= content,
2077 "LANE_MIN_H ({LANE_MIN_H}) is shorter than what a lane head actually \
2078 draws ({content}px: {label_line_h}px label line box + \
2079 {LANE_HEAD_GAP}px gap + {LANE_DOT_D}px dot) -- the status dot \
2080 would spill past the row, invisible until it is the last lane \
2081 with no next row to spill into"
2082 );
2083}
2084
2085/// A round trip through the file: what is saved is what the next load reads
2086/// back, all five seams touched -- a scratch path, not the real config, the
2087/// same isolation `keymap::tests`' own `load_from`/`save_to` already takes.
2088/// One of the five is written past its own ceiling (the library, past
2089/// `SIDE_MAX_FRAC` of the window it is loaded back into): a file written at
2090/// a wider window must not hand a narrower one an illegal layout, so the
2091/// load clamps it back down rather than reading it verbatim.
2092#[test]
2093fn a_saved_seam_survives_a_reload() {
2094 use crate::{
2095 BENCH_MIN_H, SIDE_MAX_FRAC, Split, Splits, load_stance_splits_from, save_stance_splits_to,
2096 };
2097 use gpui::{Pixels, Size, px, size};
2098
2099 let dir = engine::scratch::Scratch::dir("edith-stance-splits");
2100 let path = dir.join("stance-splits");
2101 let window: Size<Pixels> = size(px(1280.), px(720.));
2102
2103 let mut splits = Splits::default();
2104 splits.set(Split::Library, 9000.);
2105 splits.set(Split::Inspector, 200.);
2106 splits.set(Split::Timeline, 250.);
2107 splits.set(Split::Dock, 333.);
2108 splits.set(Split::Bench, 200.);
2109 save_stance_splits_to(&splits, &path);
2110 let loaded = load_stance_splits_from(&path, window);
2111 assert_eq!(
2112 loaded.get(Split::Library),
2113 Some(1280. * SIDE_MAX_FRAC),
2114 "a library past its own ceiling should clamp to it on load"
2115 );
2116 assert_eq!(loaded.get(Split::Inspector), Some(200.));
2117 assert_eq!(loaded.get(Split::Timeline), Some(250.));
2118 assert_eq!(loaded.get(Split::Dock), Some(333.));
2119 assert_eq!(loaded.get(Split::Bench), Some(200.));
2120
2121 // A bench saved below its own floor clamps up to it, the same ceiling
2122 // logic mirrored on the one seam whose bound is a minimum.
2123 let mut low_bench = Splits::default();
2124 low_bench.set(Split::Bench, 1.);
2125 save_stance_splits_to(&low_bench, &path);
2126 let loaded = load_stance_splits_from(&path, window);
2127 assert_eq!(loaded.get(Split::Bench), Some(BENCH_MIN_H));
2128}
2129
2130/// The guard [`crate::split_drag_owes_save`] runs at the moment a drag ends
2131/// with no further pointer event ever coming (`Player::drag_left_window`,
2132/// wired to a live `MouseExitEvent` a `TestAppContext`-less test binary
2133/// cannot raise -- see `tests/media.rs`'s own note on the same limit, and
2134/// the harness drive `D2` in this session's report for the wiring itself).
2135/// What *is* checkable here without a window: exactly the persisted
2136/// seams owe that save, the same set `Split::PERSISTED` already names, and a
2137/// drag that never started (`None`) owes nothing.
2138#[test]
2139fn only_the_persisted_seams_owe_a_save_when_a_drag_loses_the_window() {
2140 use crate::{Split, player::timeline_edit::split_drag_owes_save};
2141
2142 assert!(split_drag_owes_save(Some(Split::Dock)));
2143 assert!(split_drag_owes_save(Some(Split::Bench)));
2144 assert!(split_drag_owes_save(Some(Split::Library)));
2145 assert!(split_drag_owes_save(Some(Split::Inspector)));
2146 assert!(split_drag_owes_save(Some(Split::Timeline)));
2147 assert!(!split_drag_owes_save(None));
2148}
2149
2150/// A missing file leaves every region at its default -- the silent fallback
2151/// `load_stance_splits`'s doc comment promises.
2152#[test]
2153fn a_missing_stance_splits_file_leaves_every_region_at_its_default() {
2154 use crate::{Split, load_stance_splits_from};
2155 use gpui::{Pixels, Size, px, size};
2156
2157 let dir = engine::scratch::Scratch::dir("edith-stance-splits-missing");
2158 let window: Size<Pixels> = size(px(1280.), px(720.));
2159 let splits = load_stance_splits_from(&dir.join("nothing-here"), window);
2160 assert_eq!(splits.get(Split::Library), None);
2161 assert_eq!(splits.get(Split::Inspector), None);
2162 assert_eq!(splits.get(Split::Timeline), None);
2163 assert_eq!(splits.get(Split::Dock), None);
2164 assert_eq!(splits.get(Split::Bench), None);
2165}
2166
2167/// Every seam in the main layout has a handle on it, and every region draws
2168/// itself at the size that handle sets: a region still measuring itself off the
2169/// window's own share is a panel whose divider moves nothing.
2170#[test]
2171fn every_seam_in_the_layout_has_a_divider_on_it() {
2172 // The darkroom collapsed Library/Inspector/Timeline into rooms with no
2173 // seam of their own; render.rs no longer draws any divider at all --
2174 // ui::stance::render is the whole root now -- so the only two seams a
2175 // hand can still drag are the ones the stance itself owns.
2176 let stance = src_text("ui/stance.rs");
2177 for split in ["Split::Dock", "Split::Bench"] {
2178 assert!(
2179 stance.contains(&format!("divider({split}")),
2180 "{split} has no divider to drag"
2181 );
2182 }
2183 // The strip is drawn wide enough to hit and says which way it moves --
2184 // an invisible hairline is a feature nobody finds.
2185 let interact = src_text("interact.rs");
2186 assert!(
2187 interact.contains("cursor_col_resize") && interact.contains("cursor_row_resize"),
2188 "a divider with no resize cursor on it"
2189 );
2190 // ...and nothing lays a region out off the untouched share any more:
2191 // the legacy panels that read `library_w`/`inspector_w` (`ui/library.rs`,
2192 // `ui/inspector.rs`, `ui/toolbar.rs`) are gone or gone from the render
2193 // path, so what remains is layout.rs's own Split::Library/Inspector
2194 // arms -- kept for save-file compat, never drawn.
2195 assert!(
2196 !src_text("render.rs").contains("library_w("),
2197 "render.rs still measures a panel with library_w("
2198 );
2199}
2200
2201/// DESIGN.md §12 step 2 as amended 2026-09-09 (user decision "option C"):
2202/// the stance skeleton draws its five regions -- screen, time band, bench,
2203/// ledger, dock -- in the order §5's diagram lays them out, and
2204/// `Player::render` actually reaches it when the flag is on. The sixth, the
2205/// 56px rail, is deleted -- the room root is centre | dock.
2206#[test]
2207fn the_stance_renders_its_five_regions_in_the_documented_order() {
2208 let stance = src_text("ui/stance.rs");
2209 let order = [
2210 "stance-screen",
2211 "stance-time-band",
2212 "stance-bench",
2213 "stance-ledger",
2214 "stance-dock",
2215 ];
2216 let defined: Vec<usize> = order
2217 .iter()
2218 .map(|id| {
2219 stance
2220 .find(&format!("\"{id}\""))
2221 .unwrap_or_else(|| panic!("no {id} region in the stance"))
2222 })
2223 .collect();
2224 assert!(
2225 defined.windows(2).all(|w| w[0] < w[1]),
2226 "the five regions are not defined in DESIGN §5's order: {defined:?}"
2227 );
2228
2229 // Defined in order is not composed in order -- `render()` has to call
2230 // them in it too, or the geometry above is dead prose.
2231 let render_body = &stance[stance
2232 .find("pub(crate) fn render(")
2233 .expect("the stance's entry point")..];
2234 // Open paren only, no close: DESIGN §12 steps 3 and 4 hand most of the
2235 // regions player/window state to read, so their call sites carry
2236 // arguments now. Order is what this asserts, not arity.
2237 let calls = ["screen(", "time_band(", "bench(", "ledger(", "dock("];
2238 let composed: Vec<usize> = calls
2239 .iter()
2240 .map(|c| {
2241 render_body
2242 .find(c)
2243 .unwrap_or_else(|| panic!("render() never calls {c}"))
2244 })
2245 .collect();
2246 assert!(
2247 composed.windows(2).all(|w| w[0] < w[1]),
2248 "render() does not compose the six regions in DESIGN §5's order: {composed:?}"
2249 );
2250
2251 // The skeleton is reached unconditionally now -- the darkroom is the
2252 // only room, and `self.darkroom`'s branch is gone with the legacy tree
2253 // it used to choose between.
2254 let render_rs = src_text("render.rs");
2255 assert!(
2256 render_rs.contains("ui::stance::render("),
2257 "render.rs no longer reaches ui::stance::render"
2258 );
2259 assert!(
2260 !render_rs.contains("self.darkroom"),
2261 "render.rs still branches on self.darkroom after the legacy tree was removed"
2262 );
2263}
2264
2265/// The picture is letterboxed, never stretched: both the picture region and
2266/// the subtitle picture overlay paint through [`letterboxed_image`] (the
2267/// `canvas()` element that hands `ObjectFit::Contain::get_bounds` a real
2268/// resolved size) rather than a plain `img().object_fit(...)`, which reads
2269/// right by hand but never gets a fitted box from taffy in this pin -- see
2270/// `render.rs`'s own doc comment on the function for the measured dead end.
2271/// A regression back to `img(...).object_fit(` in either caller is the
2272/// stretch-to-fill bug returning silently.
2273#[test]
2274fn the_picture_letterboxes_through_a_canvas_never_a_plain_img_object_fit() {
2275 let render_rs = src_text("render.rs");
2276 assert!(
2277 render_rs.contains("pub(crate) fn letterboxed_image"),
2278 "the letterbox helper moved or was renamed"
2279 );
2280 assert!(
2281 render_rs.contains("ObjectFit::Contain.get_bounds(bounds, image.size(0))"),
2282 "letterboxed_image no longer computes the Contain rect by hand"
2283 );
2284 for (file, needle) in [
2285 ("render.rs", "letterboxed_image(i)"),
2286 ("ui/preview.rs", "letterboxed_image(image)"),
2287 ] {
2288 let text = src_text(file);
2289 assert!(
2290 text.contains(needle),
2291 "{file} no longer paints through letterboxed_image"
2292 );
2293 assert!(
2294 !text.contains(".object_fit(gpui::ObjectFit::Contain)"),
2295 "{file} reintroduced the stretched img().object_fit(Contain) dead end"
2296 );
2297 }
2298}
2299
2300/// DESIGN §8: "No full-width bars, no covering the picture, ever." The
2301/// darkroom stance (`ui::stance::screen`) draws
2302/// [`Player::picture_area`](crate::Player::picture_area) directly, so a
2303/// notice surface that reaches into that method unconditionally reaches the
2304/// picture on the darkroom path too -- measured live covering the bottom 10%
2305/// of the frame (rows 300-333 of 335). The legacy full-width `notice_bar`
2306/// and its non-darkroom caller are gone with the rest of the old tree, and
2307/// the floating notice plate went after them (user 2026-08-27: the ledger's
2308/// own "last action" strip is the one notice channel now), so this pins
2309/// `picture_area` itself never growing a notice surface back.
2310#[test]
2311fn the_darkroom_path_never_lets_a_notice_surface_reach_the_picture() {
2312 // The ledger strip (`ui::stance::ledger` reading `notices.back()`) is
2313 // the only notice channel left, and the invariant is that
2314 // picture_area's body never draws one over the picture.
2315 let body = fn_body("picture_area");
2316 assert!(
2317 !body.contains("notice_bar"),
2318 "picture_area draws a notice surface over the picture again (the old occlusion defect)"
2319 );
2320}
2321
2322/// DESIGN §5/§11 check 6, the fourth occlusion defect (notice bar, export
2323/// card, preview badge, now menus): every floating menu that can open above
2324/// the picture -- the clip context menu, the picker -- must size its
2325/// scrolling list against `stance::menu_floor`'s room, not the raw window.
2326/// Sizing against the whole viewport is exactly the bug that shipped: a menu
2327/// taller than the bench/ledger/dock footprint got clamped by `menu_at`'s
2328/// own bottom-edge fit back up over the picture, because nothing had told
2329/// the list it only had the footprint to grow into. This pins the general
2330/// rule so the next surface someone floats -- a fourth menu, a fifth
2331/// occlusion -- cannot silently reintroduce `menu_rows_h(rows.len(),
2332/// viewport)` in its place.
2333///
2334/// The library menu is the deliberate exception (user 2026-08-27, "right
2335/// clicking a library media opens a menu in somewhere nonsense"): it anchors
2336/// to a pointer that is always inside the dock, where no picture exists to
2337/// protect, and `menu_floor`'s clamp teleported it down to the picture floor
2338/// -- so `ui/library.rs` must open at the pointer through `menu_at` alone,
2339/// and this guard pins that it never routes back through `menu_floor`.
2340#[test]
2341fn every_darkroom_menu_sizes_its_list_against_the_floor_room_not_the_raw_viewport() {
2342 for file in ["ui/overlays.rs"] {
2343 let text = src_text(file);
2344 assert!(
2345 !text.contains("menu_rows_h(rows.len(), viewport)"),
2346 "{file} sizes a menu's list against the raw viewport again -- \
2347 route it through stance::menu_floor's room instead, or a tall \
2348 menu will climb back over the picture"
2349 );
2350 let floors = text.matches("menu_floor(").count();
2351 let sizings = text.matches("menu_rows_h(rows.len(),").count();
2352 assert_eq!(
2353 floors, sizings,
2354 "{file} has a menu list-sizing call not paired with a menu_floor \
2355 call -- every darkroom menu must clamp both its anchor and its \
2356 list room together"
2357 );
2358 assert!(
2359 sizings > 0,
2360 "{file} no longer opens any menu -- update this guard"
2361 );
2362 }
2363 let library = src_text("ui/library.rs");
2364 assert!(
2365 !library.contains("menu_floor("),
2366 "ui/library.rs routes its menu through menu_floor's picture-floor \
2367 clamp again -- a right-click high in the dock teleports back down \
2368 to the picture floor (the 'menu in somewhere nonsense' defect)"
2369 );
2370 assert!(
2371 library.contains("menu_at(at, viewport, h)")
2372 && library.contains("point(menu.at.x, menu.at.y + px(ROW_CLEAR))"),
2373 "ui/library.rs no longer anchors its menu to the pointer -- one row \
2374 clear of it, so the menu cannot cover the row it names -- through \
2375 menu_at; update this guard"
2376 );
2377}
2378
2379/// The settings page's own organising rule: PROJECT rows open only the
2380/// doors that write into the `.edith` file ([`Player::open_picker`],
2381/// [`Player::open_mix`]), and EDITOR rows open only the doors that do not
2382/// ([`Player::toggle_proxies`], [`Player::toggle_auto_proxies`],
2383/// [`Player::open_subtitle_style`]) -- never the config-file writers
2384/// (`ui::dock_stance::config_path`/`ui::theme::config_path`/
2385/// `keymap::Keymap::config_path`) directly, which every editor-side row
2386/// already routes around through its own opener. A row wired to the wrong
2387/// section's opener is exactly the regression a page organised around named
2388/// sections invites -- and the tab strip did not loosen it: a tab decides
2389/// which section is *shown*, never which door a row opens. This pins each
2390/// half to its own doors so the two lists cannot cross.
2391#[test]
2392fn settings_project_and_editor_sections_open_disjoint_doors() {
2393 let source = src_text("ui/settings_stance.rs");
2394 let project_start = source
2395 .find("fn project_section(")
2396 .expect("the project section");
2397 let editor_start = source
2398 .find("fn editor_section(")
2399 .expect("the editor section");
2400 let render_start = source
2401 .find("pub(crate) fn render(")
2402 .expect("the page's render fn");
2403 assert!(
2404 project_start < editor_start && editor_start < render_start,
2405 "the three fns moved; this scan is blind"
2406 );
2407 let project_body = &source[project_start..editor_start];
2408 let editor_body = &source[editor_start..render_start];
2409
2410 // `Pick::Theme` is the one list that is nobody's project -- the palette
2411 // lives in ~/.config/edith like the subtitle font beside it (see
2412 // `menus.rs`'s own note on the variant), so its row is EDITOR's by the
2413 // same rule every other row here follows. The scan below is on the door
2414 // *string*, so the palette row is subtracted from the EDITOR body before
2415 // the project-door check runs rather than the check being loosened for
2416 // every picker.
2417 let editor_no_theme = editor_body.replace("open_picker(Pick::Theme", "");
2418 for door in ["open_picker(", "open_mix("] {
2419 assert!(
2420 project_body.contains(door),
2421 "PROJECT section no longer opens {door} -- update this guard"
2422 );
2423 assert!(
2424 !editor_no_theme.contains(door),
2425 "EDITOR section opens {door}, a project-file door -- that value belongs in PROJECT, not here"
2426 );
2427 }
2428 assert!(
2429 editor_body.contains("open_picker(Pick::Theme"),
2430 "the palette row left EDITOR -- it is a ~/.config preference, not a project value"
2431 );
2432 for door in [
2433 "toggle_proxies(",
2434 "toggle_auto_proxies(",
2435 "open_subtitle_style(",
2436 ] {
2437 assert!(
2438 editor_body.contains(door),
2439 "EDITOR section no longer opens {door} -- update this guard"
2440 );
2441 assert!(
2442 !project_body.contains(door),
2443 "PROJECT section opens {door}, an editor-only door -- that value belongs in EDITOR, not here"
2444 );
2445 }
2446 // Neither section writes a config file straight from a row: both go
2447 // through an opener, which is the one place a config-file write (the
2448 // subtitle style card's Save, this window's next project load) is
2449 // allowed to live.
2450 for path_fn in [
2451 "dock_stance::config_path",
2452 "theme::config_path",
2453 "Keymap::config_path",
2454 ] {
2455 assert!(
2456 !project_body.contains(path_fn),
2457 "PROJECT section touches {path_fn} directly"
2458 );
2459 assert!(
2460 !editor_body.contains(path_fn),
2461 "EDITOR section touches {path_fn} directly"
2462 );
2463 }
2464}
2465
2466/// D1's own class, pinned per row rather than per section: a row's hint can
2467/// claim a `~/.config/edith` default (the section header claims nothing on
2468/// its own since [`settings_project_and_editor_sections_open_disjoint_doors`]'s
2469/// commit, so a lying section head no longer slips past a reviewer -- but a
2470/// lying *row* hint did, on Proxies, because nothing scanned row text at all).
2471/// For every row whose own hint text names that file, this requires the
2472/// matching `save_*_pref`/`load_*_pref` pair to actually exist in
2473/// `player/library.rs` -- the exact gap Proxies shipped with: a hint promising
2474/// a default the row's own door never wrote.
2475#[test]
2476fn settings_row_hints_naming_config_edith_have_a_matching_pref_pair() {
2477 let source = src_text("ui/settings_stance.rs");
2478 let library = src_text("player/library.rs");
2479 // (row id, the stem its pref functions are named after)
2480 for (row_id, stem) in [
2481 ("settings-proxies", "proxies"),
2482 ("settings-auto-proxies", "auto_proxies"),
2483 ] {
2484 let row_start = source
2485 .find(&format!("\"{row_id}\""))
2486 .unwrap_or_else(|| panic!("{row_id} row moved or renamed -- update this guard"));
2487 let row_end = source[row_start..]
2488 .find(",\n ))")
2489 .map_or(source.len(), |i| row_start + i);
2490 let row_text = &source[row_start..row_end];
2491 if !row_text.contains("~/.config/edith") {
2492 continue;
2493 }
2494 for prefix in ["save_", "load_"] {
2495 let fn_name = format!("{prefix}{stem}_pref");
2496 assert!(
2497 library.contains(&format!("fn {fn_name}(")),
2498 "{row_id}'s hint claims a ~/.config/edith default but \
2499 player/library.rs has no `{fn_name}` -- the hint promises \
2500 storage the row does not have"
2501 );
2502 }
2503 }
2504}
2505
2506/// With no project open, a PROJECT row must not fall back to a bare noun
2507/// ("Size"/"Rate"/"HDR") standing in the value slot -- it reads as a value
2508/// while carrying none. This binary has no `TestAppContext` to actually
2509/// render the page with `player.session` empty, so this is a source scan
2510/// for the fallback strings the bug shipped as, same as the guard above it.
2511#[test]
2512fn settings_project_rows_have_no_bare_noun_placeholder() {
2513 let source = src_text("ui/settings_stance.rs");
2514 let project_start = source
2515 .find("fn project_section(")
2516 .expect("the project section");
2517 let editor_start = source
2518 .find("fn editor_section(")
2519 .expect("the editor section");
2520 let project_body = &source[project_start..editor_start];
2521 for placeholder in [
2522 "\"Size\".to_string()",
2523 "\"Rate\".to_string()",
2524 "\"HDR\".to_string()",
2525 ] {
2526 assert!(
2527 !project_body.contains(placeholder),
2528 "a PROJECT row fell back to the bare noun {placeholder} -- it reads as a value with no project open"
2529 );
2530 }
2531}
2532
2533/// The HDR reference rows must read the file's own declared numbers off
2534/// [`engine::colorspace::ContentLight`] -- not invent a monitor override the
2535/// engine has nowhere to persist -- and must fall back to the page's one
2536/// established empty state (a bare `—` in `INK4`, [`row_ink`]/[`row_static`]'s
2537/// own idiom) rather than a second placeholder idiom. No `TestAppContext`
2538/// here either, so this is the same source-scan the guard above it is.
2539#[test]
2540fn hdr_reference_rows_read_content_light_and_use_the_established_empty_state() {
2541 let source = src_text("ui/settings_stance.rs");
2542 let project_start = source
2543 .find("fn project_section(")
2544 .expect("the project section");
2545 let editor_start = source
2546 .find("fn editor_section(")
2547 .expect("the editor section");
2548 let project_body = &source[project_start..editor_start];
2549
2550 assert!(
2551 project_body.contains("settings-hdr-reference"),
2552 "the HDR reference row is missing"
2553 );
2554 assert!(
2555 project_body.contains("settings-content-light"),
2556 "the content-light row is missing"
2557 );
2558
2559 // Reads the real declared numbers, not an invented default or a fixed
2560 // string standing in for one.
2561 for field in ["mastering_max", "max_cll", "max_fall"] {
2562 assert!(
2563 project_body.contains(field),
2564 "the HDR reference rows do not read ContentLight::{field}"
2565 );
2566 }
2567
2568 // No override field exists on the engine side to write one into, so the
2569 // row must never claim a picker/opener the way every other PROJECT row
2570 // does -- it is built with `row_static`, not `row`/`row_ink`.
2571 assert!(
2572 project_body.contains("row_static(\n \"settings-hdr-reference\""),
2573 "the HDR reference row must be read-only (row_static), not a picker"
2574 );
2575 assert!(
2576 project_body.contains("row_static(\n \"settings-content-light\""),
2577 "the content-light row must be read-only (row_static), not a picker"
2578 );
2579
2580 // The established empty state: a bare "—" reused, never a second idiom
2581 // ("N/A", "None", "Unknown"...) invented for the same absence.
2582 assert!(
2583 project_body.contains("\"—\".to_string()"),
2584 "the HDR reference rows must reuse the page's own empty-state dash"
2585 );
2586}
2587/// The parity class this user has reported four separate times: "some
2588/// options are only reachable via keyboard shortcut". A source scan (this
2589/// binary has no `TestAppContext` to click through) over every darkroom
2590/// surface -- the dock, the bench/timeband transport, the
2591/// settings page, the maximized cards and the clip context menu
2592/// (`menus.rs`'s `MENU_ITEMS`, rendered mouse-and-chord-visible by
2593/// `overlays.rs`) -- for a literal `ActionId::<variant>` mention. An
2594/// [`ActionId`] reachable by chord ([`Keymap::defaults`]) but absent from
2595/// every one of those texts has no mouse door into the darkroom at all,
2596/// which is exactly this bug's shape (`Fit` and `Redo` shipped that way
2597/// until this commit).
2598///
2599/// [`ActionId::Resolution`] and [`ActionId::SubtitleStyle`] are the two
2600/// deliberate exceptions: their settings-page rows open them through
2601/// `Pick::Resolution` and `open_subtitle_style(cx)` respectively, never
2602/// spelling the action name itself, so each is matched on its own door
2603/// string instead.
2604///
2605/// Every action gets a persistent regional control or the context-menu row for
2606/// the thing it acts on. The four exemptions are independently-owned lane
2607/// parity work, named with their owners so a future removal cannot silently
2608/// turn any unrelated action back into keyboard-only.
2609#[test]
2610fn every_action_has_a_darkroom_widget_home_or_explicit_owner() {
2611 use crate::ActionId;
2612 const EXPLICITLY_OWNED_ELSEWHERE: &[(ActionId, &str)] = &[
2613 (
2614 ActionId::FocusPanels,
2615 "keyboard-only by design: a mouse already focuses whatever it \
2616 clicks, so a click-through door for \"move keyboard focus\" \
2617 has nothing to do that a click has not already done",
2618 ),
2619 (
2620 ActionId::Deselect,
2621 "clicking empty timeline space already clears the selection with the mouse; \
2622 bare escape is a keyboard-only accelerator for that existing door, not a new one",
2623 ),
2624 (
2625 ActionId::SelectNext,
2626 "clicking a clip already selects it with the mouse; `}` is a keyboard-only \
2627 accelerator for cycling that existing selection, not a new door -- legacy had no \
2628 toolbar button for it either",
2629 ),
2630 (
2631 ActionId::SelectPrev,
2632 "clicking a clip already selects it with the mouse; `{` is a keyboard-only \
2633 accelerator for cycling that existing selection, not a new door -- legacy had no \
2634 toolbar button for it either",
2635 ),
2636 // The keyboard's own trim: `^[` and `^]` do with a stroke what the
2637 // pointer does by dragging the clip edge to the spot it wants, and
2638 // that drag is the door -- a menu row for it would be a second name
2639 // for a gesture the bench already answers.
2640 (
2641 ActionId::TrimInToPlayhead,
2642 "the pointer's version is dragging the clip edge to the playhead",
2643 ),
2644 (
2645 ActionId::TrimOutToPlayhead,
2646 "the pointer's version is dragging the clip edge to the playhead",
2647 ),
2648 // The rail's own eighteen are gone from this list: the right-click
2649 // parity (DESIGN §5 as amended 2026-09-09, user decision "option C")
2650 // gave every one of them a door on the thing it acts on -- the clip
2651 // menu, the ruler's, the lane head's -- and the staleness check below
2652 // is what deleted their entries as each landed.
2653 // Cleanse round 2 (2026-09-10, user "seems cool, let's apply"): the
2654 // time band kept the timecode, one three-glyph transport, the
2655 // odometer, the contact strip and Export. Everything below left it.
2656 // Each keeps its chord and its KEYS-tab row; the ruler menu already
2657 // owns the ones that act on the ruler (zoom/fit/snap). Named here
2658 // rather than re-mounted, per DESIGN §5's amendment: the geography of
2659 // a verb is the thing it acts on, and playback has no thing.
2660 (
2661 ActionId::JumpBack,
2662 "KEYS tab + key: the shuttle pair left the band in cleanse round 2",
2663 ),
2664 (
2665 ActionId::JumpForward,
2666 "KEYS tab + key: the shuttle pair left the band in cleanse round 2",
2667 ),
2668 (
2669 ActionId::GoStart,
2670 "KEYS tab + key: home/end left the band in cleanse round 2 -- the \
2671 contact strip's own ends are the pointer's version",
2672 ),
2673 (
2674 ActionId::GoEnd,
2675 "KEYS tab + key: home/end left the band in cleanse round 2 -- the \
2676 contact strip's own ends are the pointer's version",
2677 ),
2678 (
2679 ActionId::PrevSyncPoint,
2680 "KEYS tab + key: the sync pair left the band in cleanse round 2",
2681 ),
2682 (
2683 ActionId::NextSyncPoint,
2684 "KEYS tab + key: the sync pair left the band in cleanse round 2",
2685 ),
2686 (
2687 ActionId::Loop,
2688 "KEYS tab + key: the loop toggle left the band in cleanse round 2",
2689 ),
2690 (
2691 ActionId::ClearRange,
2692 "KEYS tab + key: `I O ×` left the band in cleanse round 2 -- in and out \
2693 became the contact strip's own grips, and clearing both at once is \
2694 not a thing on the film to point at",
2695 ),
2696 (
2697 ActionId::Screenshot,
2698 "the picture the frame is written from is the *watched* frame and \
2699 nothing else is under the pointer to right-click for it: keyboard \
2700 and the KEYS card, like the selection accelerators above",
2701 ),
2702 ];
2703 /// `ActionId::Loop` is a prefix of `ActionId::LoopTrim`, and the keys
2704 /// menu's own label arm (`ActionId::ToggleMute | ActionId::Paste =>
2705 /// format!("{full} (global)")`) shapes a string rather than opening a
2706 /// door -- neither is a widget home, so neither counts as a mention.
2707 fn mentions(text: &str, name: &str) -> bool {
2708 text.lines()
2709 .filter(|l| !l.contains("=> format!(\"{full} (global)\")"))
2710 .any(|line| {
2711 line.match_indices(&format!("ActionId::{name}"))
2712 .any(|(i, m)| {
2713 !line[i + m.len()..]
2714 .chars()
2715 .next()
2716 .is_some_and(|c| c.is_alphanumeric() || c == '_')
2717 })
2718 })
2719 }
2720 let darkroom = [
2721 "ui/bench_stance.rs",
2722 "ui/cards.rs",
2723 "ui/dock_stance.rs",
2724 "ui/overlays.rs",
2725 "ui/settings_stance.rs",
2726 "ui/stance.rs",
2727 "ui/timeband_stance.rs",
2728 "menus.rs",
2729 ]
2730 .map(src_text)
2731 .join("\n");
2732 for action in ActionId::ALL {
2733 if let Some((_, owner)) = EXPLICITLY_OWNED_ELSEWHERE
2734 .iter()
2735 .find(|(owned, _)| *owned == action)
2736 {
2737 assert!(!owner.is_empty(), "ActionId::{action:?} needs an owner");
2738 // An exemption is a debt, not a licence: once the owning lane
2739 // has mounted the action, the entry has to go, or the sweep
2740 // goes blind on an action that is covered.
2741 assert!(
2742 !mentions(&darkroom, &format!("{action:?}")),
2743 "ActionId::{action:?} has a darkroom home now -- delete its \
2744 EXPLICITLY_OWNED_ELSEWHERE entry ({owner})"
2745 );
2746 continue;
2747 }
2748 let name = format!("{action:?}");
2749 let mentioned = mentions(&darkroom, &name)
2750 || (action == ActionId::Resolution && darkroom.contains("Pick::Resolution"))
2751 || (action == ActionId::SubtitleStyle && darkroom.contains("open_subtitle_style(cx)"));
2752 let hitmap_id = crate::ui::hitmap::action_id(action);
2753 assert_eq!(
2754 hitmap_id,
2755 format!("action.{name}"),
2756 "ActionId::{name} has a Darkroom widget home but no stable hitmap id"
2757 );
2758 assert!(
2759 mentioned,
2760 "ActionId::{name} is bound to a chord but has no visible affordance \
2761 anywhere in the darkroom tree -- either mount it or name the owning parity lane"
2762 );
2763 }
2764}
2765
2766/// Transition affordances must be painted and use the existing edit state:
2767/// fades own their drag handles, an active dissolve remains a mouse toggle,
2768/// and a carried lane names the exact slot `reorder_lane` will use.
2769#[test]
2770fn darkroom_bench_wires_transition_controls_and_lane_drop_cue() {
2771 let bench = src_text("ui/bench_stance.rs");
2772 let clip = &bench[bench.find("fn clip_box(").expect("the clip renderer")
2773 ..bench.find("fn sub_box(").expect("the subtitle renderer")];
2774 for needle in [
2775 "fade_wedge(true)",
2776 "fade_wedge(false)",
2777 "dissolve_glyph()",
2778 "this.start_fade_drag(lane, idx, is_in, event.position.x, cx)",
2779 "this.dissolve_selected(cx)",
2780 ] {
2781 assert!(
2782 clip.contains(needle),
2783 "the Darkroom clip lost its transition affordance: {needle}"
2784 );
2785 }
2786 let dissolve = &clip[clip
2787 .find(".when(dissolves, |d| {")
2788 .expect("the dissolve affordance")
2789 ..clip.find(".when(trims(span),").expect("the fade handles")];
2790 assert!(
2791 dissolve.contains(".w(px(FADE_HANDLE_W))"),
2792 "dissolve click target no longer matches fade-handle width"
2793 );
2794 assert!(
2795 dissolve.contains(".h(px(FADE_HANDLE_H))"),
2796 "dissolve click target no longer matches fade-handle height"
2797 );
2798 assert!(
2799 !dissolve.contains("h_full()"),
2800 "dissolve click target still covers the clip body"
2801 );
2802 assert!(
2803 !dissolve.contains(".w(px(scale"),
2804 "dissolve hit test still tracks transition width"
2805 );
2806
2807 let lane = &bench[bench.find("fn lane_row(").expect("the lane renderer")
2808 ..bench
2809 .find("pub(crate) fn render(")
2810 .expect("the bench renderer")];
2811 for needle in [
2812 "this.preview_lane_drop(event.drag(cx).0, lane, cx)",
2813 "this.forget_lane_drop(lane, cx)",
2814 ".lane_drop",
2815 "if drop.above",
2816 ] {
2817 assert!(
2818 lane.contains(needle),
2819 "the Darkroom lane lost its reorder feedback: {needle}"
2820 );
2821 }
2822}
2823
2824/// The pointer harness can only drive controls that report the bounds of the
2825/// element that owns the gesture. Keep every dynamic Darkroom entry surface
2826/// named, so UI verification never falls back to guessed pixels.
2827#[test]
2828fn hitmap_names_every_darkroom_pointer_entry_surface() {
2829 let bench = src_text("ui/bench_stance.rs");
2830 for needle in [
2831 "clip.{}.{}.{}.fade-{}",
2832 "clip.{}.{}.{}.trim-{}",
2833 "clip.{}.{}.{}.dissolve",
2834 "lane.{}.reorder",
2835 "lane.{}.eye",
2836 ] {
2837 assert!(
2838 bench.contains(needle),
2839 "bench control missing hitmap id: {needle}"
2840 );
2841 }
2842 assert!(
2843 bench.contains(".when(trims(span), |d| {"),
2844 "fade handles must cover video clips as well as audio clips"
2845 );
2846
2847 let dock = src_text("ui/dock_stance.rs");
2848 for needle in [
2849 "subtitle.{group_ord}.{track}.row",
2850 "subtitle.{group_ord}.{track}.select",
2851 "source.{i}.row",
2852 "source.{i}.add",
2853 "dock.filter",
2854 ] {
2855 assert!(
2856 dock.contains(needle),
2857 "dock control missing hitmap contract: {needle}"
2858 );
2859 }
2860
2861 for (path, needles) in [
2862 (
2863 "ui/timeband_stance.rs",
2864 &[
2865 "timeline.contact-strip",
2866 "stance-strip-grip-lt",
2867 "stance-strip-grip-rb",
2868 "stance-strip-mark-in",
2869 "stance-strip-mark-out",
2870 ][..],
2871 ),
2872 ("ui/preview.rs", &["preview.stop", "preview.scrub"][..]),
2873 (
2874 "ui/overlays.rs",
2875 &[
2876 "menu.{action:?}",
2877 "menu.properties",
2878 "theme.{n}.row",
2879 "let enabled = refusal.yes()",
2880 "hitmap::dynamic(\n move || (format!(\"menu.{action:?}\"",
2881 ][..],
2882 ),
2883 (
2884 "ui/settings_stance.rs",
2885 &[".children(hitmap::control(id, label_text, !exporting))"][..],
2886 ),
2887 ] {
2888 let source = src_text(path);
2889 for needle in needles {
2890 assert!(
2891 source.contains(needle),
2892 "{path} missing hitmap contract: {needle}"
2893 );
2894 }
2895 }
2896}
2897
2898/// An external file drag (gpui `ExternalPaths`, Wayland `text/uri-list`) has
2899/// to be heard over the DOCK -- the Sources/library panel -- and not only
2900/// over the centre column: the dock is the centre's flex sibling, so the
2901/// handler `stance-centre` used to carry covered none of
2902/// the library panel, which is exactly the shipped "drag and drop file
2903/// import is not working on library panel" defect. The listener therefore
2904/// belongs to the room root (`stance-room`), above every region, and it must
2905/// route the dropped paths through `import` -- the same door the Import
2906/// action uses.
2907///
2908/// A scan, not a click: this crate has no gpui `VisualTestContext` harness
2909/// (nothing in `tests/` opens a window), and a drop cannot be simulated
2910/// without one -- the compositor half (`wl_data_device`) is out of reach of
2911/// the test process either way.
2912#[test]
2913fn an_external_file_drop_is_heard_by_the_whole_room_and_imports() {
2914 let stance = src_text("ui/stance.rs");
2915 let root_at = stance
2916 .find(".id(\"stance-room\")")
2917 .expect("no stance root div");
2918 let centre_at = stance
2919 .find(".id(\"stance-centre\")")
2920 .expect("no stance centre column");
2921 let drop_at = stance
2922 .find(".on_drop(cx.listener(|this, paths: &gpui::ExternalPaths")
2923 .expect("no external-file drop handler in the stance");
2924 assert!(
2925 drop_at > root_at && drop_at < centre_at,
2926 "the external drop handler is not on the room root -- \
2927 a drop over the dock's library panel is heard by nothing"
2928 );
2929 let body = &stance[drop_at..(drop_at + 700).min(stance.len())];
2930 assert!(
2931 body.contains("this.import(path, cx)"),
2932 "a dropped file does not go through the import door: {body}"
2933 );
2934 // ...and the library panel says so while the file is over it.
2935 let dock_at = stance.find(".id(\"stance-dock\")").expect("no dock div");
2936 let dock = &stance[dock_at..(dock_at + 700).min(stance.len())];
2937 assert!(
2938 dock.contains(".drag_over::<gpui::ExternalPaths>"),
2939 "the dock answers an external file drag with nothing: {dock}"
2940 );
2941}
2942
2943/// The wheel is the bench's, not a clip's: the user rolled it over the bench
2944/// and nothing moved unless the pointer happened to sit on a track, because
2945/// the only listeners were one per bed and one on the ruler strip. The row's
2946/// listener now sits on the whole row (head column included) and stops there,
2947/// and `bench-content` answers everything else -- the strip left of the ruler,
2948/// the ruler itself, the gaps between rows, the space below the last track.
2949/// Exactly two listeners, so no strip answers one notch twice.
2950#[test]
2951fn the_bench_answers_a_wheel_notch_anywhere_over_it() {
2952 let bench = src_text("ui/bench_stance.rs");
2953 assert_eq!(
2954 bench.matches(".on_scroll_wheel(").count(),
2955 2,
2956 "the bench has a wheel listener per region again -- a notch would be answered twice"
2957 );
2958 let row = bench
2959 .find(".id((\"bench-lane\", lane.ord")
2960 .expect("no lane row");
2961 let bed = bench.find(".id((\"bench-bed\"").expect("no lane bed");
2962 let row_wheel = bench[row..bed]
2963 .find(".on_scroll_wheel(")
2964 .map(|at| &bench[row + at..bed])
2965 .expect("the lane row does not answer the wheel -- only its bed does");
2966 assert!(
2967 row_wheel[..200].contains("cx.stop_propagation();")
2968 && row_wheel[..200].contains("this.timeline_wheel(event, cx)"),
2969 "the row's wheel lost the mapping or its stop: {}",
2970 &row_wheel[..200]
2971 );
2972 let content = bench
2973 .find(".id(\"bench-content\")")
2974 .expect("no bench content");
2975 let content_wheel = bench[content..]
2976 .find(".on_scroll_wheel(")
2977 .expect("the bench container does not answer the wheel");
2978 assert!(
2979 content_wheel < 700 && bench[content..].contains("this.timeline_wheel(event, cx)"),
2980 "the container's wheel listener is not on the container itself"
2981 );
2982 let ruler = bench.find(".id(\"bench-ruler\")").expect("no ruler");
2983 let lanes = bench.find(".id(\"bench-lanes\")").expect("no lane column");
2984 assert!(
2985 !bench[ruler..lanes].contains(".on_scroll_wheel("),
2986 "the ruler answers the wheel on its own again -- one notch, two scrolls"
2987 );
2988}
2989
2990/// The way back from a layout dragged somewhere unusable: a double press on
2991/// the seam forgets the size, and the region is the window's own share again
2992/// -- the *same* share an untouched window gives it, not a second default
2993/// kept beside the first ([`Splits::clear`]).
2994#[test]
2995fn a_double_pressed_divider_forgets_the_size_it_was_dragged_to() {
2996 use crate::layout::{Split, Splits, split_size};
2997 use gpui::{px, size};
2998
2999 let window = size(px(1280.), px(720.));
3000 let mut splits = Splits::default();
3001 for split in Split::PERSISTED {
3002 let default = split_size(split, None, 2, window, false);
3003 // A hand takes the seam somewhere else...
3004 splits.set(split, split_size(split, Some(300.), 2, window, false));
3005 assert_ne!(
3006 splits.get(split),
3007 None,
3008 "{split:?} kept nothing of the drag"
3009 );
3010 // ...and the double press puts it back where an untouched window
3011 // would have drawn it.
3012 splits.clear(split);
3013 assert_eq!(splits.get(split), None, "{split:?} still holds a size");
3014 assert_eq!(
3015 split_size(split, splits.get(split), 2, window, false),
3016 default,
3017 "{split:?} came back to something other than its own share"
3018 );
3019 }
3020}
3021
3022/// The seam is a ghost (DESIGN §11.2): 6 px of hit area with *nothing* painted
3023/// at rest, one hairline of dim ink under the pointer, the same line one step
3024/// brighter while it is held. The scan is the guard because the failure it
3025/// catches -- a `bg` on the strip, which is what the divider shipped with --
3026/// draws a 6 px band of colour down the room at rest and reads as the chrome
3027/// the user called crowded.
3028#[test]
3029fn the_seam_paints_nothing_until_a_pointer_finds_it() {
3030 let src = src_text("interact.rs");
3031 let start = src.find("pub(crate) fn divider(").expect("the divider");
3032 let body = &src[start..start + src[start..].find("\n}\n").expect("its end")];
3033 assert!(
3034 !body.contains(".bg("),
3035 "the divider fills its strip at rest: {body}"
3036 );
3037 assert!(
3038 body.contains("gpui::transparent_black()"),
3039 "the divider's line is inked at rest: {body}"
3040 );
3041 for step in [
3042 ".group_hover(",
3043 "GRAB_W",
3044 "BENCH_GRAB_H",
3045 "STROKE_DIVIDER()",
3046 "INK3()",
3047 "border_t_1()",
3048 "border_l_1()",
3049 ] {
3050 assert!(body.contains(step), "the divider is missing {step}");
3051 }
3052 // The hairline is the *band's* child, not the strip's own border: a line
3053 // raised only by the 6 px that already grab the seam is feedback the hand
3054 // gets after it no longer needs it (a `bench=207` -- a press with no
3055 // drag in it -- beside a dragged `dock=277`).
3056 assert!(
3057 body.find(".group(group.clone())")
3058 .expect("the band's group")
3059 < body.find("border_t_1()").expect("the hairline"),
3060 "the hairline is painted outside the band: {body}"
3061 );
3062}
3063
3064/// The band the hand actually gets, in seam coordinates. It once reached 13px
3065/// past the line to cover the `BENCH` label row a hand aimed at; that row is
3066/// gone (cleanse round 2) and the ruler under the seam answers presses of its
3067/// own (it scrubs), so the bench seam takes every other seam's reach and no
3068/// more -- a deeper band would eat scrubs at the film's own top edge.
3069#[test]
3070fn the_bench_seam_reaches_no_further_than_every_other_seam() {
3071 let above = 1.;
3072 let reach = |grab: f32| grab - above - crate::layout::SPLIT_W;
3073 assert_eq!(reach(crate::layout::GRAB_W), 7.);
3074 assert_eq!(
3075 reach(crate::layout::BENCH_GRAB_H),
3076 7.,
3077 "the bench band reaches past the ruler row, which answers presses itself"
3078 );
3079}
3080
3081/// The clamp table, driven: the seam refuses exactly two things, and neither
3082/// is anywhere near where a hand drags. Measured live at 2560x1440 --
3083/// `bench=105` at the floor, `bench=1164` at the ceiling.
3084#[test]
3085fn the_bench_seam_stops_at_its_floor_and_its_ceiling() {
3086 use crate::{BENCH_MIN_H, Split, split_bounds, split_size};
3087 use gpui::{px, size};
3088
3089 let window = size(px(2560.), px(1440.));
3090 let (min, max) = split_bounds(Split::Bench, 2, window, false);
3091 assert_eq!(min, BENCH_MIN_H);
3092 assert_eq!(
3093 max,
3094 1440. - crate::ui::stance::TIME_BAND_H - crate::ui::stance::LEDGER_H - 160.
3095 );
3096 for (asked, want) in [(0., min), (-942., min), (5000., max), (207., 207.)] {
3097 assert_eq!(
3098 split_size(Split::Bench, Some(asked), 2, window, false),
3099 want,
3100 "a bench dragged to {asked}"
3101 );
3102 }
3103}
3104
3105/// DESIGN §7: "lanes scroll behind the pinned ruler and track heads" -- pinned
3106/// means pinned. A clip that starts left of the view sits at a negative `left`
3107/// inside its bed, and with no clip mask gpui paints it (and its hitbox) over
3108/// the `HEAD_W` px head column, so V1/A1 and their verbs disappear under the first
3109/// take as soon as the bench is wheeled past frame 0. The mask belongs on the
3110/// bed itself so a half-scrolled clip still drags on the half that shows.
3111#[test]
3112fn the_lane_bed_clips_its_clips_at_the_pinned_heads() {
3113 let src = src_text("ui/bench_stance.rs");
3114 let start = src.find(r#".id(("bench-bed""#).expect("the bed");
3115 let bed = &src[start
3116 ..start
3117 + src[start..]
3118 .find(".bg(rgb(DARK_CANVAS()))")
3119 .expect("its fill")];
3120 assert!(
3121 bed.contains(".overflow_hidden()"),
3122 "the bed lets its clips paint outside itself, straight over the \
3123 pinned lane heads: {bed}"
3124 );
3125}
3126
3127/// A source row is its name first (user 2026-09-09: "clunky, crowded and
3128/// problematic"). At DOCK_W 280 the name used to be the only flexible child
3129/// among six, so it measured 0px and the library showed
3130/// `● V1 A1 · 2 uses Preview Add ↵ ○` -- every part of a row except the one
3131/// thing the row is for. The fix is subtraction, not a hover gate (DESIGN §8):
3132/// the name keeps 60% of the row, usage joins the metadata line under it, and
3133/// the three verbs shrink to glyph ghosts at the right edge.
3134#[test]
3135fn a_source_row_shows_its_name_before_anything_else() {
3136 let dock = src_text("ui/dock_stance.rs");
3137 let start = dock.find("fn source_row(").expect("the source row");
3138 let row = &dock[start..dock.find("/// Imported subtitle tracks").expect("its end")];
3139 assert!(
3140 row.contains(".min_w(relative(0.6))"),
3141 "the row name can still collapse under its siblings"
3142 );
3143 assert!(
3144 !row.contains(".min_w(px(0.))"),
3145 "the row name is still allowed to measure nothing"
3146 );
3147 // Cleanse round 2: the name is what the editor calls the film, not what
3148 // the filesystem calls the bytes.
3149 assert!(
3150 row.contains("let name: SharedString = stem(&row.name).into();"),
3151 "the row name still wears its extension"
3152 );
3153 assert_eq!(
3154 crate::ui::dock_stance::stem("he_is_not_the_only_one.mp4"),
3155 "he_is_not_the_only_one"
3156 );
3157 // A file with several audio streams keeps the stream half of its name and
3158 // loses only the extension; a name that is all extension keeps it.
3159 assert_eq!(
3160 crate::ui::dock_stance::stem("A Film.mkv [audio 2]"),
3161 "A Film [audio 2]"
3162 );
3163 assert_eq!(crate::ui::dock_stance::stem(".srt"), ".srt");
3164 // One ghost on the right edge, and one only: preview and the stand-in
3165 // moved into the row's own menu (`RowItem::Preview`/`Proxy`).
3166 for glyph in [r#".child("+")"#, r#".child("↵")"#] {
3167 assert!(row.contains(glyph), "the right-edge verb lost {glyph}");
3168 }
3169 for gone in [r#".child("▷")"#, "dock-proxy-toggle", "dock-preview"] {
3170 assert!(!row.contains(gone), "the row still carries `{gone}`");
3171 }
3172 assert!(
3173 row.contains("source.{i}.add"),
3174 "the add ghost lost its hitmap entry"
3175 );
3176 // The metadata line is codec · length · lanes: no decoder seat, no use
3177 // count (`usage_line` and the `seats` filter above it).
3178 assert!(
3179 row.contains(".map(Backend::label);") && row.contains(".child(under)"),
3180 "the metadata line no longer drops the decoder seat"
3181 );
3182 let usage = &dock[dock.find("fn usage_line(").expect("the usage line")..start];
3183 assert!(
3184 !usage.contains("use{}"),
3185 "the metadata line still counts uses"
3186 );
3187 // DESIGN §8: the permanent footer telling the editor how to use a list
3188 // ("drag · ↵ add · double-click plays") is instructional copy and is gone.
3189 assert!(
3190 !dock.contains("double-click plays"),
3191 "the dock still carries an instruction footer"
3192 );
3193 // ...and an empty list is a single noun, whatever emptied it.
3194 assert!(
3195 dock.contains(r#".child("none"),"#),
3196 "the empty dock says something other than the one noun"
3197 );
3198}
3199
3200/// The dock's metadata line drops the decoder *seat* and nothing else. A file
3201/// the decoder refused has no seat to drop: its detail is the refusal, and it
3202/// is the only thing the line has to say.
3203#[test]
3204fn the_dock_keeps_a_refusal_where_it_drops_a_seat() {
3205 use crate::ui::dock_stance::without_seats;
3206 use engine::decode::Backend;
3207
3208 let seats = [
3209 Backend::Opening,
3210 Backend::Hardware,
3211 Backend::Software,
3212 Backend::Still,
3213 Backend::Gap,
3214 ]
3215 .map(Backend::label);
3216 assert_eq!(
3217 without_seats("h264 · HW", &seats),
3218 "h264",
3219 "the seat is how this machine reads it, and the row says what the file is"
3220 );
3221 let refusal = "no Segment element: not a Matroska file";
3222 assert_eq!(
3223 without_seats(refusal, &seats),
3224 refusal,
3225 "a refusal is not a seat, and reaches the row whole"
3226 );
3227 // The halves keep their separator either way: a stream detail beside a
3228 // refusal is still two things said in order.
3229 assert_eq!(
3230 without_seats(&format!("{refusal} · stereo · 48 kHz"), &seats),
3231 format!("{refusal} · stereo · 48 kHz")
3232 );
3233}
3234
3235/// A room key pressed while the ring sits in the dock has to reach the room.
3236/// Two ways it did not: the dock's own handler could stop a key it does not
3237/// answer, and the body the dock mounts could leave the focused
3238/// `FocusHandle` with no element -- gpui dispatches only along the rendered
3239/// focus node's ancestors (`gpui-0.2.2` `window.rs:3982`, falling back to the
3240/// *window* root, which is not the room's div), so an orphaned handle kills
3241/// every key until the next click. Measured 2026-09-09: with KEYS open, a
3242/// second `?` and `space` reached no listener at all.
3243#[test]
3244fn every_dock_body_mounts_the_ring_it_is_standing_in_for() {
3245 let dock = src_text("ui/dock_stance.rs");
3246 for (body, id) in [
3247 ("sources", "\"dock-sources\""),
3248 ("clip", "\"dock-clip\""),
3249 ("keys", "\"dock-keys-rows\""),
3250 ] {
3251 let after = dock
3252 .split(id)
3253 .nth(1)
3254 .unwrap_or_else(|| panic!("the dock's {body} body is gone"));
3255 let head: String = after.lines().take(4).collect();
3256 assert!(
3257 head.contains(".track_focus(") && head.contains(".on_key_down("),
3258 "the dock's {body} body mounts no focus handle: a ring left on it dies"
3259 );
3260 }
3261 // ...and the shared handler answers exactly two keys, stopping the stroke
3262 // only there; anything else bubbles to `ui::stance::render`'s handler.
3263 let handler = dock
3264 .split("fn cycle_on_key_down(")
3265 .nth(1)
3266 .expect("the dock's shared key handler is gone");
3267 let body = handler.split("\n}\n").next().unwrap();
3268 assert_eq!(
3269 body.matches("cx.stop_propagation()").count(),
3270 3,
3271 "the dock's key handler stops a stroke outside its tab/escape branches"
3272 );
3273 for branch in ["is_focus_cycle_key(key)", "is_focus_exit_key(key)"] {
3274 assert!(
3275 body.contains(branch),
3276 "{branch} left the dock's key handler"
3277 );
3278 }
3279}
3280
3281/// Focus and selection rings are drawn, never inserted: a `when(focused,
3282/// border_1())` puts a pixel of box into the flow and every row in the dock
3283/// steps sideways the moment the surface takes focus (hunter: h-clip-tab.png
3284/// vs i-library-menu.png).
3285#[test]
3286fn a_dock_ring_never_moves_what_it_rings() {
3287 let dock = src_text("ui/dock_stance.rs");
3288 for gate in [
3289 ".when(picked, |d| d.border_1()",
3290 ".when(focused, |d| d.border_1()",
3291 ] {
3292 assert!(
3293 !dock.contains(gate),
3294 "a dock ring is still added on state ({gate}), shifting its content"
3295 );
3296 }
3297 assert_eq!(
3298 dock.matches("gpui::transparent_black()").count(),
3299 4,
3300 "a dock ring lost its at-rest transparent border"
3301 );
3302 // ...and the focus ring is not painted at all (user 2026-09-09:
3303 // "clicking through timeline draws a white overlay around the timeline,
3304 // same happens for library section too"). Keyboard focus is unchanged --
3305 // only the paint is gone -- so no dock surface may reach for the focus
3306 // stroke or for `ink1` on a focused border.
3307 assert!(
3308 !dock.contains("STROKE_FOCUS"),
3309 "a dock surface paints the focus ring again"
3310 );
3311 assert!(
3312 !dock.contains("is_focused(window)"),
3313 "a dock surface reads focus for paint again"
3314 );
3315 assert!(
3316 dock.contains(".track_focus(&player.focus_dock)")
3317 && dock.contains(".track_focus(&player.focus_inspector)"),
3318 "dropping the ring's paint took the surface's keyboard focus with it"
3319 );
3320}
3321
3322/// DESIGN §9 as amended 2026-09-09: the keys list lives in the dock BODY,
3323/// not a plate over the bench and not a tab of its own (user: "remove keys
3324/// section from here since we also have it next to ledger"). The strip is
3325/// the SOURCES/CLIP pair; the list rides `keys_open` under a KEYS section
3326/// head, and the rows still come off `keys_rows` with the refused ones
3327/// greyed rather than hidden (§8).
3328#[test]
3329fn the_keys_list_is_dock_body_state_not_a_tab() {
3330 let stance = src_text("ui/stance.rs");
3331 assert!(
3332 !stance.contains("keys_overlay") && !stance.contains("stance-keys-overlay"),
3333 "the keys plate is still mounted over the bench"
3334 );
3335 let dock = src_text("ui/dock_stance.rs");
3336 for (id, label) in [("dock-tab-src", "SOURCES"), ("dock-tab-clip", "CLIP")] {
3337 assert!(
3338 dock.contains(&format!("dock_tab(\"{id}\", \"{label}\"")),
3339 "the dock's tab strip lost {label}"
3340 );
3341 }
3342 assert!(
3343 !dock.contains("dock-tab-keys"),
3344 "KEYS is still a tab in the strip"
3345 );
3346 assert!(
3347 dock[dock.find("fn keys_tab(").unwrap()..].contains("section_head(\"KEYS\")"),
3348 "the keys list draws no KEYS head in the dock body"
3349 );
3350 assert!(
3351 dock.contains("fn keys_tab(") && dock.contains("keys_rows_matching("),
3352 "the KEYS tab draws something other than the action registry"
3353 );
3354 assert!(
3355 dock.contains("Enable::Yes => INK2(),") && dock.contains("_ => INK4(),"),
3356 "a refused action's row no longer greys to ink4 (DESIGN §8)"
3357 );
3358 assert!(
3359 dock[dock.find("fn keys_tab(").unwrap()..].contains(".overflow_y_scroll()"),
3360 "the keys list does not scroll like its neighbours"
3361 );
3362 // The Sources filter box belongs to Sources: it is built inside
3363 // `sources_tab`, never in the shared frame `render` draws.
3364 let frame = &dock[dock.find("pub(crate) fn render(").unwrap()..];
3365 assert!(
3366 !frame.contains("dock-filter"),
3367 "the Sources filter box leaked into the shared dock frame"
3368 );
3369}
3370
3371/// The user's screenshot: the old rail ended with `?` over `?`. The rule
3372/// outlived the rail -- a ledger room ghost whose primary chord IS its own
3373/// name wears no badge; every other one still does.
3374#[test]
3375fn a_room_ghost_wears_no_chord_that_repeats_its_name() {
3376 let src = src_text("ui/stance.rs");
3377 assert!(
3378 src.contains(".when(player.keymap.chord(action) != name, |el| {"),
3379 "a room ghost draws its chord badge even when the badge repeats its name"
3380 );
3381}
3382
3383/// DESIGN §5 as amended 2026-09-09 (user decision "option C"): there is no
3384/// rail. The room root is centre | dock, `spine_stance` is deleted, and the
3385/// four verbs that act on the ROOM -- the only ones with no thing under the
3386/// cursor to be right-clicked -- live at the ledger's right end, each
3387/// wearing its chord, `CC` carrying the shown/hidden state the rail's glyph
3388/// used to.
3389#[test]
3390fn the_ledger_carries_the_rooms_four_verbs_and_no_rail_remains() {
3391 let src = src_text("ui/stance.rs");
3392 for gone in ["stance-spine", "spine_stance", "SPINE_W", "fn spine("] {
3393 assert!(
3394 !src.contains(gone),
3395 "the rail is still in the stance: {gone}"
3396 );
3397 }
3398 let ledger = &src[src.find("fn ledger(").expect("the ledger strip")
3399 ..src.find("/// The dock:").expect("the dock frame")];
3400 for (name, action) in [
3401 ("CC", "ActionId::ToggleSubtitles"),
3402 ("settings", "ActionId::Settings"),
3403 ("keys", "ActionId::ShowActions"),
3404 ("full", "ActionId::Fullscreen"),
3405 ] {
3406 assert!(
3407 ledger.contains(&format!("\"{name}\",")) && ledger.contains(action),
3408 "the ledger lost its {name} room verb"
3409 );
3410 }
3411 // Before the position timecode, which stays the strip's last word.
3412 assert!(
3413 ledger.find("room_ghost(").expect("a room verb")
3414 < ledger.find(".child(tc),").expect("the position"),
3415 "the room verbs drew after the position timecode"
3416 );
3417 // Each wears its chord, live off the keymap (DESIGN §4), and `CC` reads
3418 // active while subtitles are shown.
3419 let ghost = &src[src.find("fn room_ghost(").expect("the room ghost")..];
3420 assert!(
3421 ghost.contains("player.keymap.chord(action)") && ghost.contains("widgets::action_hover"),
3422 "a room verb lost its live chord or its hover plate"
3423 );
3424 assert!(
3425 ledger.contains("player.subs_on"),
3426 "`CC` no longer shows whether subtitles are shown"
3427 );
3428}
3429
3430/// The `all` control left the ruler (cleanse round 2, DESIGN §5): the ruler
3431/// row is the bench's own top edge and carries ticks and the playhead alone.
3432/// Every removed control keeps a door -- `^a` still fires it, and the ruler's
3433/// own right-click menu ([`BENCH_ITEMS`]) is where the pointer reaches it --
3434/// so this checks the control is gone AND that the row exists, not just the
3435/// deletion.
3436#[test]
3437fn select_all_left_the_ruler_for_the_rulers_own_menu() {
3438 use crate::ActionId;
3439 use crate::menus::BENCH_ITEMS;
3440 let bench = src_text("ui/bench_stance.rs");
3441 for gone in ["bench-select-all", "select_all_band", "SELECT_ALL_PAD"] {
3442 assert!(!bench.contains(gone), "the ruler still carries {gone}");
3443 }
3444 assert!(
3445 BENCH_ITEMS.contains(&ActionId::SelectAll),
3446 "`all` left the ruler with no menu row behind it"
3447 );
3448 // And the band it reserved is the ticks' again: nothing subtracts a
3449 // control's width from the bed's right edge any more.
3450 assert!(
3451 bench.contains("if x >= plate_w && x + label_w <= bed_w {"),
3452 "the tick loop still keeps a band clear for a control that is gone"
3453 );
3454}
3455
3456/// The rest of cleanse round 2's bench + ledger, which is all about *one*
3457/// saying per thing: the head is a dot and a name (its verbs left, checked
3458/// above), a source's name is drawn once per source -- the audio half of a
3459/// linked insert has no plate, because the picture plate directly above it
3460/// and the shared dot already say whose it is -- names lose their extension
3461/// through one helper, and the ledger's state word is Save's only door now
3462/// (the time band's parking-spot ghost, filed there because the ledger was a
3463/// concurrent builder's file, is deleted).
3464#[test]
3465fn one_name_per_source_one_stem_helper_and_one_save_door() {
3466 let bench = src_text("ui/bench_stance.rs");
3467 assert!(
3468 bench.contains(".filter(|_| !(audio && clip.link.is_some()))"),
3469 "the audio half of a linked insert wears a second name plate again"
3470 );
3471 assert!(
3472 bench.contains("stem(&s.path)") && !bench.contains("file_name(&s.path)"),
3473 "a name plate shows the file's extension again"
3474 );
3475 let stance = src_text("ui/stance.rs");
3476 assert!(
3477 stance.contains("stem(&player.project_path)"),
3478 "the ledger shows the project's extension again"
3479 );
3480 assert!(
3481 stance.contains(r#"room_ghost(player, "unsaved", ActionId::Save"#),
3482 "the ledger's unsaved state is not Save's door -- it is a word again"
3483 );
3484 // The close request is intercepted and routed through the predicate, and
3485 // the plate it raises is answered: this repo can build no window in a
3486 // test ([`Player`] needs a `TestAppContext`), so the wiring itself is
3487 // what is guarded -- the hook, the rule it asks, and the three answers.
3488 let main = src_text("main.rs");
3489 assert!(
3490 main.contains("on_window_should_close") && main.contains("close_needs_answer()"),
3491 "alt+F4 closes the window without asking about unsaved work"
3492 );
3493 assert!(
3494 stance.contains("if this.quit_ask {")
3495 && stance.contains("this.save_project(cx);")
3496 && stance.contains("window.remove_window()"),
3497 "the unsaved plate is up with no key answering it"
3498 );
3499 assert!(
3500 stance.contains("UNSAVED — save ↵ · discard d · stay esc"),
3501 "the decision plate speaks prose instead of state + verb·chord"
3502 );
3503 // The overwrite guard (user 2026-09-11: saving over an existing file
3504 // must warn first, same pattern as the exit guard): Save no longer
3505 // writes through the action directly -- it routes through the guarded
3506 // door, which raises the plate with the target's own name, and the
3507 // plate is answered by its own key block beside the quit plate's.
3508 let actions = src_text("player/actions.rs");
3509 assert!(
3510 actions.contains("ActionId::Save => self.save_guarded(cx)")
3511 && !actions.contains("ActionId::Save => self.save_project(cx)"),
3512 "^s overwrites a foreign .edith without asking"
3513 );
3514 assert!(
3515 stance.contains("if this.save_ask {")
3516 && stance.contains("OVERWRITE {} — overwrite ↵ · keep esc"),
3517 "the overwrite plate is up with no key answering it"
3518 );
3519 assert!(
3520 !src_text("ui/timeband_stance.rs").contains("ActionId::Save"),
3521 "Save has two doors: the ledger's state word and the time band's ghost"
3522 );
3523 // The helper itself, since three surfaces read one file's name through
3524 // it: a plain name loses its extension, a name with none is itself, and
3525 // a path with no name at all still reads as something.
3526 use crate::files::{file_name, stem};
3527 use std::path::Path;
3528 assert_eq!(
3529 stem(Path::new("/x/he_is_not_the_only_one.mp4")),
3530 "he_is_not_the_only_one"
3531 );
3532 assert_eq!(stem(Path::new("/x/untitled")), "untitled");
3533 assert_eq!(stem(Path::new("/x/a.b.edith")), "a.b");
3534 assert_eq!(stem(Path::new("/")), file_name(Path::new("/")));
3535}
3536
3537/// DESIGN §4/§5: the hero timecode leads the time band and the ledger carries
3538/// position. The ruler's left plate was a third resting copy of the same
3539/// reading -- it stays only for the state change it belongs to, a live scrub.
3540#[test]
3541fn the_ruler_plate_shows_the_timecode_only_while_a_scrub_is_live() {
3542 let bench = src_text("ui/bench_stance.rs");
3543 let at = bench
3544 .find(".child(playhead_tc)")
3545 .expect("no playhead timecode in the ruler");
3546 let before = &bench[..at];
3547 let guard = before
3548 .rfind(".when(player.scrubbing")
3549 .expect("the ruler plate draws its timecode at rest -- the third copy");
3550 assert!(
3551 before[guard..].matches(".child(").count() <= 2,
3552 "the scrubbing guard is not the plate's own: {}",
3553 &before[guard..guard + 200]
3554 );
3555 assert!(
3556 bench.contains("let plate_w = if player.scrubbing { PLATE_W } else { 0. };"),
3557 "the ticks still lose the plate's width at rest"
3558 );
3559}
3560
3561/// The band overflowed its own column at 1280x720 (`$EDITH_HITMAP`:
3562/// `action.Export x=1113 w=80` with the column ending at x=995, the contact
3563/// strip measured `w=0`), so the Export chip was invisible under the dock and
3564/// a click on blank dock space at (1130,435) opened the export card. Three
3565/// things hold that shut: the row clips itself, the strip keeps a floor, and
3566/// the ladder sheds groups above it.
3567#[test]
3568fn the_time_band_never_paints_outside_its_own_column() {
3569 let src = src_text("ui/timeband_stance.rs");
3570 let start = src
3571 .find(r#".id("stance-time-band-row")"#)
3572 .expect("the band row");
3573 let row = &src[start
3574 ..start
3575 + src[start..]
3576 .find(".child(hero_timecode(")
3577 .expect("the timecode")];
3578 assert!(
3579 row.contains(".overflow_hidden()"),
3580 "the band row lets its children paint (and be clicked) under the dock: {row}"
3581 );
3582 assert!(
3583 src.contains(".min_w(px(STRIP_MIN_W))"),
3584 "the contact strip is the flex_1 that absorbs the slack; without a floor it measures 0"
3585 );
3586 assert!(crate::ui::timeband_stance::STRIP_MIN_W >= 120.);
3587}
3588
3589/// DESIGN §7's ladder, cleanse round 2 (2026-09-10): the band is five
3590/// things -- timecode, the three transport glyphs, the odometer, the contact
3591/// strip and Export -- and the only sheddable layer left is the chord row
3592/// under the glyphs. This pins the one threshold (measured in the harness:
3593/// 454px of fixed groups + `STRIP_MIN_W`, rounded up -- a 640x600 window
3594/// reads 539px of band and draws no chords, a 1280x720 one reads 982px and
3595/// draws them) and that it never comes back off.
3596#[test]
3597fn the_band_sheds_its_chords_and_nothing_else() {
3598 use crate::ui::timeband_stance::band_layers;
3599 assert_eq!(
3600 [2000., 982., 580., 579., 539., 0.].map(|w| band_layers(w).chords),
3601 [true, true, true, false, false, false],
3602 "the band's one rung is the chord row at 580px"
3603 );
3604 // Monotone: a wider band never shows less than a narrower one.
3605 let mut prev = band_layers(0.);
3606 for w in (0..2400).step_by(10).map(|w| w as f32) {
3607 let now = band_layers(w);
3608 assert!(now.chords || !prev.chords, "layer came back off at {w}px");
3609 prev = now;
3610 }
3611}
3612
3613/// Every door in this band is at least `HIT_MIN` wide and tall (WCAG 2.5.8).
3614/// The hitmap read `SetIn w=8`, `VolumeDown w=12`, `Loop w=13`, `SetOut w=15`,
3615/// `Prev/NextSyncPoint w=16` before this: padding on the shared `ghost`, not a
3616/// bigger glyph. Those five glyphs left the band in cleanse round 2; the
3617/// three that stayed are drawn by the same `ghost`, so the floor is still
3618/// checked where it is spent.
3619#[test]
3620fn every_ghost_in_the_time_band_carries_a_full_hit_area() {
3621 let src = src_text("ui/timeband_stance.rs");
3622 let start = src.find("fn ghost(").expect("the band's ghost");
3623 let ghost = &src[start
3624 ..start
3625 + src[start..]
3626 .find(".child(glyph.into())")
3627 .expect("its glyph")];
3628 for needle in [".min_w(px(HIT_MIN))", ".min_h(px(HIT_MIN))"] {
3629 assert!(
3630 ghost.contains(needle),
3631 "the band's ghost lost {needle}: {ghost}"
3632 );
3633 }
3634 assert!(HIT_MIN >= 24.);
3635}
3636
3637/// Mute wore `"{volume}%"` as its glyph while the slider beside it drew the
3638/// same value: one number, two places. Cleanse round 2 (2026-09-10) settled
3639/// it the other way -- the whole monitoring cluster left the band (mute is
3640/// `m`, the level is the `-`/`=` pair), so the band writes no level at all.
3641#[test]
3642fn the_band_writes_no_monitoring_level() {
3643 let src = src_text("ui/timeband_stance.rs");
3644 for gone in [
3645 "player.volume.percent()",
3646 "fn volume_readout(",
3647 "fn volume_slider(",
3648 ] {
3649 assert!(
3650 !src.contains(gone),
3651 "the monitoring cluster is back in the band: {gone}"
3652 );
3653 }
3654}
3655
3656/// `Play` and `StepForward` drew the same solid right-triangle: two verbs one
3657/// shape, told apart only by their chords. Step wears the frame-step pair.
3658#[test]
3659fn transport_verbs_differ_by_shape_not_only_by_chord() {
3660 let src = src_text("ui/timeband_stance.rs");
3661 let glyph = |action: &str| {
3662 let at = src.find(&format!("ActionId::{action},")).expect("the call");
3663 src[..at].rsplit('"').nth(1).expect("its glyph").to_string()
3664 };
3665 // Cleanse round 2: the shuttle pair left the band, so the three that
3666 // stayed are what must still differ by shape.
3667 let shapes = ["Play", "StepBack", "StepForward"].map(glyph);
3668 let mut seen = shapes.to_vec();
3669 seen.sort();
3670 seen.dedup();
3671 assert_eq!(
3672 seen.len(),
3673 shapes.len(),
3674 "two transport verbs share one glyph: {shapes:?}"
3675 );
3676}
3677
3678/// DESIGN §6: "the cut readout is the odometer". Keyed off the selection it
3679/// read `cut —/—` immediately after a split -- two clips on the bench, the
3680/// playhead resting on the new cut, nothing picked. It reads the playhead
3681/// now: the cut under it, else the next one ahead, else the selection.
3682#[test]
3683fn the_cut_readout_counts_from_the_playhead() {
3684 use crate::ui::timeband_stance::odometer_cut;
3685 let at = |start: u32, len: u32| Clip {
3686 fade_in: 0,
3687 fade_out: 0,
3688 transition_out: 0,
3689 visualizer: 0,
3690 viz_paint: 0,
3691 start,
3692 in_frame: 0,
3693 out_frame: len,
3694 source: 0,
3695 link: None,
3696 eq: None,
3697 color: None,
3698 transform: None,
3699 fit: FitPolicy::Fit,
3700 speed: Speed::NORMAL,
3701 };
3702 let lane = [at(0, 30), at(30, 30)];
3703 assert_eq!(odometer_cut(&lane, 0), Some(0));
3704 assert_eq!(odometer_cut(&lane, 29), Some(0));
3705 // The split's own frame: the playhead rests on the SECOND cut's head.
3706 assert_eq!(odometer_cut(&lane, 30), Some(1));
3707 assert_eq!(odometer_cut(&lane, 59), Some(1));
3708 // Past the last cut there is nothing to count -- the selection answers.
3709 assert_eq!(odometer_cut(&lane, 60), None);
3710 // In a gap: the next cut ahead of the playhead.
3711 let gapped = [at(0, 10), at(40, 10)];
3712 assert_eq!(odometer_cut(&gapped, 20), Some(1));
3713 assert_eq!(odometer_cut(&[], 0), None);
3714 assert!(
3715 src_text("ui/timeband_stance.rs").contains("odometer_cut(s.lane_clips(lane), frame)"),
3716 "the readout must derive its odometer from the playhead"
3717 );
3718}
3719
3720/// DESIGN §8's rejected pattern, swept over the source rather than argued
3721/// per message: "the room never explains itself in prose ... any new string
3722/// over ~4 words that instructs rather than reports state is a defect". The
3723/// notices are what the ledger strip paints, and a sentence there is what cut
3724/// mid-word in the user's own screenshot (`OPENED ... 1 subtitle track(s) in `).
3725///
3726/// The scan reads every literal handed to a notice constructor, found by its
3727/// *call site* and not by its shape: the head of a composed refusal is the
3728/// verb's own label ("Delete — click a clip first", seen live 2026-09-09), so
3729/// a caps-headed filter walked past every one of them. Any imperative tell in
3730/// such a literal is a defect at any length. A refusal *claim* may still be
3731/// long: those are the allowlist below, each one naming a genuine absent
3732/// capability, never a lesson in how to use the room.
3733#[test]
3734fn no_notice_teaches_the_room_in_prose() {
3735 // Long refusal claims that report a capability genuinely absent from this
3736 // machine (DESIGN §8, "a refusal string is a claim"), kept whole on
3737 // purpose: the remedy is not a chord in this room because the missing
3738 // thing is not in this room.
3739 const ALLOWED: &[&str] = &["NO FILE CHOOSER"];
3740 const TELLS: &[&str] = &[
3741 "drag ",
3742 "press ",
3743 "pick ",
3744 "type ",
3745 "click ",
3746 "to show",
3747 "to use",
3748 "takes it back",
3749 "puts it back",
3750 " first",
3751 ];
3752 let mut offenders = Vec::new();
3753 for path in source_files() {
3754 let text = std::fs::read_to_string(&path).expect("a source file");
3755 for literal in notice_literals(&text) {
3756 if ALLOWED.iter().any(|allowed| literal.contains(allowed)) {
3757 continue;
3758 }
3759 let lower = literal.to_lowercase();
3760 if TELLS.iter().any(|tell| lower.contains(tell)) {
3761 offenders.push(format!("{}: {literal}", path.display()));
3762 }
3763 }
3764 }
3765 assert!(
3766 offenders.is_empty(),
3767 "a notice that instructs instead of reporting state (DESIGN §8):\n{}",
3768 offenders.join("\n")
3769 );
3770}
3771
3772/// Every string literal that reaches the user as a notice: the arguments of
3773/// the doors a message comes through -- the queue's own two, and the oracle's
3774/// refusal words, which the dispatch pastes behind an action label
3775/// ([`crate::player::actions`]). Reading the call site rather than the string
3776/// is the point: a message's case says nothing about whether it teaches.
3777fn notice_literals(text: &str) -> Vec<String> {
3778 const CALLS: &[&str] = &[
3779 "notify_user(",
3780 "push_notice(",
3781 "Enable::No(",
3782 "Enable::Hidden(",
3783 ];
3784 let code: String = text
3785 .lines()
3786 .filter(|line| !line.trim_start().starts_with("//"))
3787 .collect::<Vec<_>>()
3788 .join("\n");
3789 let mut out = Vec::new();
3790 for call in CALLS {
3791 for (at, _) in code.match_indices(call) {
3792 let open = at + call.len();
3793 // The call's own argument list, to its matching paren: a literal
3794 // written two lines below the opening one is still this call's.
3795 let mut depth = 1usize;
3796 let mut in_string = false;
3797 let mut escaped = false;
3798 let mut end = open;
3799 for (offset, c) in code[open..].char_indices() {
3800 end = open + offset;
3801 match (in_string, c) {
3802 (true, '\\') => escaped = !escaped,
3803 (true, '"') if !escaped => in_string = false,
3804 (true, _) => escaped = false,
3805 (false, '"') => in_string = true,
3806 (false, '(') => depth += 1,
3807 (false, ')') => {
3808 depth -= 1;
3809 if depth == 0 {
3810 break;
3811 }
3812 }
3813 _ => {}
3814 }
3815 }
3816 out.extend(string_literals(&code[open..end]));
3817 }
3818 }
3819 out
3820}
3821
3822/// Every string literal in `text`, comments dropped first so the prose about
3823/// a message is never read as the message.
3824fn string_literals(text: &str) -> Vec<String> {
3825 let code: String = text
3826 .lines()
3827 .filter(|line| !line.trim_start().starts_with("//"))
3828 .collect::<Vec<_>>()
3829 .join("\n");
3830 let mut out = Vec::new();
3831 let mut chars = code.chars().peekable();
3832 while let Some(c) = chars.next() {
3833 if c != '"' {
3834 continue;
3835 }
3836 let mut literal = String::new();
3837 while let Some(c) = chars.next() {
3838 match c {
3839 // A line continuation joins the halves of a wrapped message;
3840 // every other escape is not a word either way.
3841 '\\' => {
3842 if chars.next() == Some('\n') {
3843 while chars.peek() == Some(&' ') {
3844 chars.next();
3845 }
3846 }
3847 }
3848 '"' => break,
3849 _ => literal.push(c),
3850 }
3851 }
3852 out.push(literal);
3853 }
3854 out
3855}
3856
3857/// The export moment holds the file and the budget; everything a project is
3858/// *delivered as* is a settings row now (user: the export card was "too
3859/// complicated"). Four rows, and a fifth would be the card growing back --
3860/// this is a source scan for the same reason every guard on this page is.
3861#[test]
3862fn the_export_section_is_four_rows_and_no_fifth() {
3863 let source = src_text("ui/settings_stance.rs");
3864 let start = source
3865 .find("fn export_section(")
3866 .expect("the export section");
3867 let body = &source[start..];
3868 let end = body
3869 .find("\n/// The page itself")
3870 .expect("the page's render fn");
3871 let body = &body[..end];
3872 let rows = [
3873 "settings-export-picture",
3874 "settings-export-sound",
3875 "settings-export-encoder",
3876 "settings-export-range",
3877 ];
3878 for row in rows {
3879 assert!(body.contains(row), "the EXPORT section has no {row} row");
3880 }
3881 // The Sound row is written twice -- a rated codec's keyed row and an
3882 // unrated one's readout, never both at once -- so the count is by label,
3883 // not by id.
3884 for label in ["\"Picture\"", "\"Sound\"", "\"Encoder\"", "\"Range\""] {
3885 assert!(
3886 body.contains(label),
3887 "the EXPORT section has no {label} row"
3888 );
3889 }
3890 let ids = body.match_indices("\"settings-export-").count();
3891 assert_eq!(
3892 ids, 5,
3893 "the EXPORT section grew a row past the four (the two Sound rows are one row's two shapes)"
3894 );
3895 assert!(
3896 source.contains("what a delivery is written as"),
3897 "the section lost its head"
3898 );
3899 // Every row wears its chord (DESIGN §4): three keyed rows plus the
3900 // range's own marks, which are keymap actions.
3901 for chord in ["\"c\"", "\"b\"", "\"g\"", "ActionId::SetIn"] {
3902 assert!(body.contains(chord), "an EXPORT row lost its chord {chord}");
3903 }
3904}
3905
3906/// `c` walks the nine files in one order -- a codec's two boxes side by side,
3907/// the sound-only formats last -- and never stops on a format this machine
3908/// cannot write, because [`Player::set_format`] would only refuse it back.
3909#[test]
3910fn the_picture_row_cycles_codec_and_container_together_and_skips_a_refusal() {
3911 use crate::ui::settings_stance::{PICTURE_CYCLE, next_picture, picture_label};
3912 assert_eq!(
3913 PICTURE_CYCLE,
3914 [
3915 Format::Mp4,
3916 Format::Av1Mp4,
3917 Format::Av1,
3918 Format::Hevc,
3919 Format::HevcMp4,
3920 Format::Wav,
3921 Format::Flac,
3922 Format::Mp3,
3923 Format::Ogg,
3924 ]
3925 );
3926 // Nothing refused: the whole ring, wrapping back to the head.
3927 let mut at = Format::Mp4;
3928 let mut walked = vec![at];
3929 for _ in 1..PICTURE_CYCLE.len() {
3930 at = next_picture(at, |_| false);
3931 walked.push(at);
3932 }
3933 assert_eq!(walked, PICTURE_CYCLE.to_vec());
3934 assert_eq!(next_picture(at, |_| false), Format::Mp4);
3935
3936 // HEVC unavailable (no plugin): `c` steps over both of its boxes rather
3937 // than parking on a pick the setter refuses.
3938 let no_hevc = |f: Format| matches!(f, Format::Hevc | Format::HevcMp4);
3939 assert_eq!(next_picture(Format::Av1, no_hevc), Format::Wav);
3940 // Everything refused: the row keeps what it has instead of cycling to
3941 // nothing.
3942 assert_eq!(next_picture(Format::Mp4, |_| true), Format::Mp4);
3943
3944 assert_eq!(picture_label(Format::Mp4), "H.264 · MP4");
3945 assert_eq!(picture_label(Format::Av1), "AV1 · MKV");
3946 assert_eq!(picture_label(Format::Av1Mp4), "AV1 · MP4");
3947 assert_eq!(picture_label(Format::Wav), "WAV");
3948}
3949
3950/// A refused codec is greyed with its reason, never hidden (DESIGN §8), and
3951/// the reason is short enough to sit beside a value: six words, the rest of
3952/// the sentence still said by the export moment's own banner. The sound row
3953/// wears a chord only where its codec has a rate to step.
3954#[test]
3955fn a_refusal_is_six_words_beside_the_value_and_soundless_codecs_wear_no_chord() {
3956 use crate::ui::settings_stance::{encoder_word, short_reason, sound_codec};
3957 let long = "HEVC needs the VA-API plugin, which this machine has not built";
3958 assert_eq!(short_reason(long), "HEVC needs the VA-API plugin, which");
3959 assert!(short_reason(long).split_whitespace().count() <= 6);
3960 assert_eq!(short_reason("no encoder here"), "no encoder here");
3961
3962 for (format, codec, rated) in [
3963 (Format::Mp4, "AAC", true),
3964 (Format::Av1, "AAC", true),
3965 (Format::Mp3, "MP3", true),
3966 (Format::Wav, "PCM", false),
3967 (Format::Flac, "FLAC", false),
3968 (Format::Ogg, "Vorbis", false),
3969 ] {
3970 assert_eq!(sound_codec(format), (codec, rated), "{format:?}");
3971 }
3972
3973 assert_eq!(encoder_word(EncoderSeat::Auto), "auto");
3974 assert_eq!(encoder_word(EncoderSeat::Hardware), "GPU");
3975 assert_eq!(encoder_word(EncoderSeat::Software), "software");
3976}
3977
3978/// The one amber line on the page is the AV1-on-the-GPU seat, and it is the
3979/// only hue the EXPORT rows introduce -- every other value is an ink.
3980#[test]
3981fn the_only_hue_in_the_export_section_is_the_av1_gpu_notice() {
3982 let source = src_text("ui/settings_stance.rs");
3983 let start = source
3984 .find("fn export_section(")
3985 .expect("the export section");
3986 let body = &source[start..];
3987 let body = &body[..body.find("\n/// The page itself").expect("the render fn")];
3988 assert!(
3989 body.contains("NOTICE_LOOK()"),
3990 "the AV1-on-the-GPU row lost its amber"
3991 );
3992 assert_eq!(
3993 crate::ui::settings_stance::AV1_GPU_NOTICE,
3994 "ignores the budget \u{2014} constant quality"
3995 );
3996 for hue in ["ACCENT_", "STATUS_", "NOTICE_TELL", "NOTICE_DECIDE"] {
3997 assert!(
3998 !body.contains(hue),
3999 "the EXPORT rows reached for a second hue ({hue})"
4000 );
4001 }
4002}
4003
4004/// Every control the hitmap names wears a hover line (the user, 2026-09-09,
4005/// over a screenshot of the time band: "each and every button needs hover
4006/// over information ... I don't know some of them"). The hitmap already
4007/// carries the pair a plate needs -- an id and a label -- so the sweep walks
4008/// the same emitters: a builder chain that records a control and never calls
4009/// `.tooltip` is a glyph the user cannot name.
4010///
4011/// A scan and not a render: this crate has no gpui window in its tests, so
4012/// the text is the finest grain available. Each emitter must claim a
4013/// `.tooltip(` of *its own* within [`REACH`] lines -- one to one, nearest
4014/// first. Counting them per function instead let an unrelated plate (the
4015/// empty-dock hint) pay for a control that had none: `dock.sort.cycle` sat
4016/// bare under a green gate until this pairing was written.
4017///
4018/// Controls outside the hitmap are outside this gate by charter. Named for
4019/// the record, since each is a control the pointer can press: a card's own
4020/// picker rows (colour/transform/mix/subtitle/silence bands, the speed
4021/// chips) and the two menus' rows, all of which already read as
4022/// `<label> <value-or-chord>` on the row itself -- a plate would repeat the
4023/// row it hangs off, which is DESIGN §8's prose rule the other way round.
4024#[test]
4025fn every_hitmap_control_wears_a_hover_line() {
4026 /// How far from a control's `hitmap::` line its plate may be attached.
4027 /// A builder chain runs long here (the contact strip's tooltip sits 65
4028 /// lines above its emitter), so the reach is generous; what it buys is
4029 /// that a plate can be spent only once.
4030 const REACH: usize = 80;
4031 // Ids that name a control a *previous* emitter in the same chain already
4032 // plated -- the second id is the harness's aim point, not a second
4033 // control -- with the reason each is exempt.
4034 const DOUBLE_NAMED: &[&str] = &[
4035 // `subtitle.N.M.row` and `subtitle.N.M.select` are one row.
4036 ".select\")",
4037 ];
4038 let mut controls = 0;
4039 let mut naked = Vec::new();
4040 for path in source_files() {
4041 let text = std::fs::read_to_string(&path).expect("a source file");
4042 if !text.contains("hitmap::") {
4043 continue;
4044 }
4045 let file = path
4046 .file_name()
4047 .and_then(|n| n.to_str())
4048 .expect("a file name")
4049 .to_string();
4050 let lines: Vec<&str> = text.lines().collect();
4051 let mut tips: Vec<(usize, bool)> = lines
4052 .iter()
4053 .enumerate()
4054 .filter(|(_, l)| l.contains(".tooltip("))
4055 .map(|(i, _)| (i, false))
4056 .collect();
4057 for (i, line) in lines.iter().enumerate() {
4058 let emitter = ["hitmap::control(", "hitmap::dynamic(", "hitmap::action("]
4059 .iter()
4060 .any(|needle| line.contains(needle));
4061 if !emitter {
4062 continue;
4063 }
4064 // The id a `dynamic` builds sits a line or three below its call.
4065 let head = lines[i..(i + 6).min(lines.len())].join("\n");
4066 if DOUBLE_NAMED.iter().any(|id| head.contains(id)) {
4067 continue;
4068 }
4069 controls += 1;
4070 let mut free: Vec<usize> = (0..tips.len())
4071 .filter(|n| !tips[*n].1 && tips[*n].0.abs_diff(i) <= REACH)
4072 .collect();
4073 free.sort_by_key(|n| tips[*n].0.abs_diff(i));
4074 match free.first() {
4075 Some(n) => tips[*n].1 = true,
4076 None => naked.push(format!("{file}:{}: {}", i + 1, line.trim())),
4077 }
4078 }
4079 }
4080 // The floor moved 40 -> 34 with cleanse round 2 (2026-09-10): the band lost its
4081 // shuttle/marks/monitoring cluster, the bench its head verbs and `all`, and the dock
4082 // gave up five named controls in one diff (the three sub-tabs, the sort
4083 // cycle, the row's preview and stand-in ghosts, against one Add row kept)
4084 // and a floor above the true count is a red gate, not a blindness check.
4085 assert!(
4086 controls >= 34,
4087 "the hover sweep found only {controls} controls -- it has gone blind"
4088 );
4089 assert!(
4090 naked.is_empty(),
4091 "controls with no hover line of their own (attach \
4092 `widgets::tip_hover`/`action_hover` in the chain that emits the \
4093 hitmap id): {naked:#?}"
4094 );
4095}
4096
4097/// The one hover shape for the whole room: `<name> · <chord>`, and a control
4098/// the state refuses says why instead of naming a stroke that will not fire
4099/// (DESIGN §4/§8 -- a tooltip is not a sentence).
4100#[test]
4101fn a_hover_line_is_a_name_and_a_chord() {
4102 use crate::ui::widgets::tip_line;
4103 assert_eq!(
4104 tip_line("One frame forward", "right", None),
4105 "One frame forward · right"
4106 );
4107 assert_eq!(
4108 tip_line("Split", "s", Some("nothing selected")),
4109 "Split · nothing selected"
4110 );
4111 // `Keymap::chord`'s unbound badge is not a stroke.
4112 assert_eq!(tip_line("Add files", "--", None), "Add files");
4113 assert_eq!(tip_line("Source", "", None), "Source");
4114}
4115
4116/// A region is a place, not a control: none of the region roots paints a
4117/// border because it holds focus (user 2026-09-10, "clicking through
4118/// timeline draws a white overlay around the timeline"; DESIGN §4's ring
4119/// line is about the *selected thing*). Focus routing itself is untouched.
4120#[test]
4121fn no_region_root_wears_a_focus_ring() {
4122 let stance = src_text("ui/stance.rs");
4123 let bench = src_text("ui/bench_stance.rs");
4124 let band = src_text("ui/timeband_stance.rs");
4125 for (name, text) in [
4126 ("stance.rs", &stance),
4127 ("bench_stance.rs", &bench),
4128 ("timeband_stance.rs", &band),
4129 ] {
4130 for line in text.lines() {
4131 let code = line.trim_start();
4132 if code.starts_with("//") {
4133 continue;
4134 }
4135 assert!(
4136 !(code.contains("is_focused(") || code.contains("when(focused"))
4137 || !code.contains("border"),
4138 "{name} still paints a focus-conditional border: {code}"
4139 );
4140 assert!(
4141 !code.contains("STROKE_FOCUS"),
4142 "{name} paints the focus stroke on a region: {code}"
4143 );
4144 }
4145 }
4146}
4147
4148/// The user could not find the three columns (2026-09-10: "I couldn't realize
4149/// them when I look at"), because their heads were 12px `ink3` -- the room's
4150/// quietest type -- with a prose tail running on after each one. The page's
4151/// answer has since become a tab strip (user 2026-09-19): three columns at
4152/// once asked the eye to find three anchors in one glance and then to read a
4153/// column that began mid-screen. The pin moved with the page: the sections are
4154/// tabs now, each tab wears the dock's own tab look -- [`crate::ui::dock_stance`]'s
4155/// `dock_tab`, reproduced here because that fn is private to its module -- and
4156/// each section's one-line explanation rides the tab's hover plate
4157/// (DESIGN §8), never running on after a head as ambient text.
4158#[test]
4159fn the_settings_sections_are_tabs_that_carry_their_own_explanation() {
4160 let source = src_text("ui/settings_stance.rs");
4161 let start = source.find("fn settings_tab(").expect("the tab builder");
4162 let body = &source[start..source[start..].find("\n}\n").unwrap() + start];
4163 // The dock's own tab look: no pill, no fill; a 1px `ink1` top rule and
4164 // `ink1` text mark the showing tab, the resting one is `ink3`. Every tab
4165 // is a `hitmap::control` wearing a plate of its own (the hover-line gate
4166 // below counts the plates one to one).
4167 for needle in [
4168 "type_scale::LABEL_ROW_PX",
4169 "gpui::FontWeight::MEDIUM",
4170 "border_t_1()",
4171 "rgb(INK1())",
4172 "INK3()",
4173 ".cursor_pointer()",
4174 ".tooltip(",
4175 "hitmap::control(",
4176 ] {
4177 assert!(body.contains(needle), "a settings tab lost {needle}");
4178 }
4179 assert!(
4180 !body.contains("type_scale::head()"),
4181 "the settings tabs fell back to the 12px in-list section head"
4182 );
4183 // Three tabs, one per section, named the way the room names the section.
4184 for tab in ["project", "editor", "export"] {
4185 assert!(
4186 source.contains(&format!("\"settings-tab-{tab}\"")),
4187 "the settings strip has no {tab} tab"
4188 );
4189 }
4190 // Each section's one-line explanation is the tab's plate now.
4191 for explanation in [
4192 "stored in the .edith file",
4193 "this machine, this window",
4194 "what a delivery is written as",
4195 ] {
4196 assert!(
4197 source.contains(explanation),
4198 "a settings tab lost its explanation: {explanation}"
4199 );
4200 }
4201 // ...and none of them runs on after a head as ambient text.
4202 for run_on in ["PROJECT \u{b7}", "EDITOR \u{b7}", "EXPORT \u{b7}"] {
4203 assert!(
4204 !source.contains(run_on),
4205 "a settings head grew its prose tail back: {run_on}"
4206 );
4207 }
4208 // One section shows at a time: the plate mounts the showing tab's own
4209 // section and nothing else -- a page that drew all three under the strip
4210 // would be the three columns back with the strip doing nothing.
4211 for (tab, section) in [
4212 ("SettingsTab::Project", "project_section(player, cx)"),
4213 ("SettingsTab::Editor", "editor_section(player, cx)"),
4214 ("SettingsTab::Export", "export_section(player, cx)"),
4215 ] {
4216 assert!(
4217 source.contains(&format!("{tab} => {section}")),
4218 "the {tab} tab no longer shows {section}"
4219 );
4220 }
4221}
4222
4223/// The page's own geometry, after the user retired the below-picture sheet
4224/// (2026-09-19: "this settings section should be a modal instead of covering
4225/// the timeline"). The page is a centred modal now -- a centred scrim and a
4226/// plate of one tabbed column's own measure, never `w_full()`, which put a
4227/// `justify_between` row's value a window away from its label, and never the
4228/// [`crate::ui::stance::below_picture_floor`] anchor that laid the sheet over
4229/// the bench at the window's full width. The height is a viewport cap with
4230/// headroom, the rows scroll under the strip when a short window cannot hold
4231/// them, and the modal keeps the two things its callers read: the
4232/// `settings-card` id and the press-away exit (`this.close_card()`, the same
4233/// one every other card's scrim leads with). A source scan, like every other
4234/// guard on this page -- this binary renders no window of its own.
4235#[test]
4236fn the_settings_page_is_a_centred_modal_with_one_column_of_measure() {
4237 let source = src_text("ui/settings_stance.rs");
4238 let start = source
4239 .find("pub(crate) fn render(")
4240 .expect("the page's render fn");
4241 let body = &source[start..];
4242 let end = body.find("\n}\n").map_or(body.len(), |at| at + 2);
4243 let body = &body[..end];
4244
4245 // Centred on both axes, and the below-picture sheet gone with the rest
4246 // of it: no floor arithmetic, no bottom-edge alignment, no full-width
4247 // plate.
4248 for needle in [".justify_center()", ".items_center()"] {
4249 assert!(body.contains(needle), "the settings modal lost {needle}");
4250 }
4251 for gone in ["below_picture_floor", "items_end()", "w_full()"] {
4252 assert!(
4253 !body.contains(gone),
4254 "the settings page drew {gone} again -- that is the below-picture sheet, \
4255 not the centred modal the user asked for"
4256 );
4257 }
4258 // The plate: one column's own measure with its yield for a narrow centre
4259 // column, a capped height, and the rows scrolled inside the cap.
4260 for needle in [
4261 ".id(\"settings-card\")",
4262 ".w(px(SETTINGS_W))",
4263 ".max_w(relative(1.))",
4264 ".max_h(px(max_h))",
4265 "\"settings-rows\"",
4266 "overflow_y_scroll()",
4267 ] {
4268 assert!(
4269 body.contains(needle),
4270 "the settings modal lost {needle} -- the plate is no longer one capped \
4271 column with its rows scrolling"
4272 );
4273 }
4274 // One measure for every tab (user 2026-09-20: "switching between them
4275 // feels weird" -- the plate hugged its rows, so PROJECT's seven and
4276 // EXPORT's four resized it under the hand). The rows area wears the
4277 // tallest section's fixed height, and that height is PROJECT's own
4278 // arithmetic: count the section's rows out of its body rather than
4279 // trusting the constant's comment.
4280 assert!(
4281 body.contains(".h(px(SETTINGS_ROWS_H))"),
4282 "the settings rows lost their fixed measure -- a tab switch resizes the plate again"
4283 );
4284 let project = &source[source
4285 .find("fn project_section(")
4286 .expect("the PROJECT section")..];
4287 let project = &project[..project.find("\n}\n").map_or(project.len(), |at| at + 2)];
4288 let rows = [
4289 "row(",
4290 "row_ink(",
4291 "row_static(",
4292 "row_keyed(",
4293 "row_full(",
4294 "row_chord(",
4295 ]
4296 .iter()
4297 .map(|call| project.matches(call).count())
4298 .sum::<usize>();
4299 assert_eq!(
4300 crate::ui::settings_stance::SETTINGS_ROWS_H,
4301 rows as f32 * CONTROL_H + (rows - 1) as f32 * 2.,
4302 "SETTINGS_ROWS_H no longer measures the PROJECT section's {rows} rows"
4303 );
4304 assert!(
4305 body.contains("this.close_card()"),
4306 "the settings scrim swallows the press without closing the modal"
4307 );
4308}
4309
4310/// The Picture row said every refused format's reason after its value
4311/// (`H.264 no picture -- an mp4 would \u{b7} AV1 no picture -- ...`; the user
4312/// called it "funny"). A row says its own pick: one value, and a refusal only
4313/// when *that* pick is the refused one.
4314#[test]
4315fn the_picture_row_tail_is_the_current_format_alone() {
4316 let source = src_text("ui/settings_stance.rs");
4317 let start = source
4318 .find("fn export_section(")
4319 .expect("the export section");
4320 let body = &source[start..];
4321 let body = &body[..body
4322 .find("\n/// The page itself")
4323 .expect("the page's render fn")];
4324 assert!(
4325 !body.contains("PICTURE_CYCLE"),
4326 "the Picture row walks the whole cycle to build its tail again"
4327 );
4328 assert!(
4329 !body.contains(".join("),
4330 "an EXPORT row concatenates a list into one row's tail again"
4331 );
4332 assert!(
4333 body.contains("format_refusal(session, format)"),
4334 "the Picture row's refusal is no longer asked about the current format"
4335 );
4336 // Six words at most, and the value greys with the refusal it carries.
4337 assert!(
4338 body.contains("short_reason(&why)") && body.contains("picture_ink"),
4339 "the Picture row lost its short reason or its greyed value"
4340 );
4341}
4342
4343/// The monitoring level's home. Cleanse round 2 took the mute button, the
4344/// `- +` pair and the slider off the time band on the promise that the level
4345/// "lives in Settings" (DESIGN 5) -- a promise nothing kept until this row,
4346/// which is why the volume trio sat in
4347/// [`every_action_has_a_darkroom_widget_home_or_explicit_owner`]'s exemption
4348/// list. A source scan, like every other guard on this page: the EDITOR
4349/// section carries the row, the row wears the mute chord (`m`), and the wheel
4350/// over it moves the level through the very actions the keys do -- no second
4351/// setter, no slider growing back.
4352#[test]
4353fn the_editor_section_owns_the_monitoring_level_row() {
4354 let source = src_text("ui/settings_stance.rs");
4355 let editor_start = source
4356 .find("fn editor_section(")
4357 .expect("the editor section");
4358 let render_start = source
4359 .find("pub(crate) fn render(")
4360 .expect("the page's render fn");
4361 let editor_body = &source[editor_start..render_start];
4362 for needle in [
4363 "\"settings-level\"",
4364 "\"Level\"",
4365 "ActionId::ToggleMute",
4366 "ActionId::VolumeUp",
4367 "ActionId::VolumeDown",
4368 ".on_scroll_wheel(",
4369 ] {
4370 assert!(
4371 editor_body.contains(needle),
4372 "the EDITOR section's Level row is missing {needle}"
4373 );
4374 }
4375 // The chord the row draws is the keymap's own, so the badge reads `m`
4376 // wherever this test's reader looks for it.
4377 assert_eq!(
4378 crate::keymap::Keymap::defaults().chord(crate::ActionId::ToggleMute),
4379 "m",
4380 "the mute chord moved -- the Level row's badge is no longer `m`"
4381 );
4382 // Muted reads as a word in the quieter ink, never as `0%`: the level is
4383 // what unmuting comes back to and the row must not lie about it.
4384 assert!(
4385 editor_body.contains("\"muted\".to_string()"),
4386 "the Level row must say `muted` rather than a number when silenced"
4387 );
4388 // A readout, not a widget: the slider stayed dead (DESIGN 5).
4389 assert!(
4390 !editor_body.contains("volume_bar") && !editor_body.contains("drag_volume"),
4391 "the level slider grew back in Settings"
4392 );
4393 // The page counts as a card ([`Player::card_open`]), so the darkroom's
4394 // modal guard eats every stroke this branch does not answer: without
4395 // these three arms the row wears a chord that does nothing while the page
4396 // is the visible thing on screen (what the first harness run showed).
4397 let cards = src_text("player/cards.rs");
4398 let branch_start = cards
4399 .find("if self.settings_open {")
4400 .expect("the settings key branch");
4401 let branch = &cards[branch_start..(branch_start + 1600).min(cards.len())];
4402 for arm in ["\"m\" =>", "\"=\" =>", "\"-\" =>"] {
4403 assert!(
4404 branch.contains(arm),
4405 "the settings key branch does not answer {arm} -- the Level row's \
4406 chord is swallowed by the modal guard while the page is up"
4407 );
4408 }
4409}
4410
4411/// The wheel's own arithmetic: one notch is one key press (5%), and the count
4412/// stops at both ends rather than wrapping silence into full volume -- the
4413/// saturating pair [`Volume::step`] is written for. Pure, so it runs without
4414/// a window.
4415#[test]
4416fn the_level_wheel_steps_five_percent_and_clamps_at_both_ends() {
4417 use crate::transport::Volume;
4418 let mut volume = Volume::default();
4419 assert_eq!(volume.percent(), 100);
4420 for expected in [95, 90, 85, 80] {
4421 volume.step(false);
4422 assert_eq!(volume.percent(), expected, "a notch down is 5%");
4423 }
4424 for _ in 0..40 {
4425 volume.step(false);
4426 }
4427 assert_eq!(volume.percent(), 0, "the level floors at silence");
4428 volume.step(false);
4429 assert_eq!(volume.percent(), 0, "a notch below silence is silence");
4430 for _ in 0..40 {
4431 volume.step(true);
4432 }
4433 assert_eq!(volume.percent(), 100, "the level ceilings at full");
4434 volume.step(true);
4435 assert_eq!(volume.percent(), 100, "a notch above full is full");
4436 // Turning it down while muted is not what makes sound come out.
4437 volume.muted = true;
4438 volume.step(false);
4439 assert!(volume.muted && volume.percent() == 95);
4440}