forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7f487c1Tahinli3 months ago659 commits

layout.rs2380 lines, 105.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 edit toolbar against the 640x360 floor the whole editor is measured
7/// at. It does not fit and cannot be made to -- so what it may never do is
8/// *hide* the tail: the row scrolls, and the door to everything scrolled
9/// off it is pinned outside the scrolling box.
10#[test]
11fn toolbar_fits_the_smallest_window() {
12 let toolbar = src_text("ui/toolbar.rs");
13 let row = &toolbar[toolbar.find("pub(crate) fn toolbar(").expect("the toolbar")..];
14 // Every button in the row is a hit target, so none of them is narrower
15 // than `HIT_MIN`, and they sit in 8 px gaps inside the row's own 12 px
16 // padding.
17 let buttons = row.matches("action_control(").count();
18 assert!(buttons >= 11, "the row's buttons moved; this scan is blind");
19 // The row is shorter than it was -- the project's own settings (size,
20 // rate, HDR) are the inspector's now and the transport is the
21 // picture's -- so whether it fits at 640 px depends on the words in it
22 // and is not something this scan can measure. What it can hold to is
23 // the rule: "it scrolls" is not "it can be found", so the door to
24 // whatever is off the right edge is pinned outside the scrolling box
25 // and the card it opens carries every action there is
26 // (`every_action_is_on_the_actions_card`).
27 assert!(
28 row.contains("\"controls-more\""),
29 "nothing pinned beside the scrolling row: the tail is unreachable at 640 px"
30 );
31 assert_eq!(row.matches("overflow_x_scroll").count(), 1);
32 assert!(
33 row.find("\"controls-more\"") > row.find("overflow_x_scroll"),
34 "the pinned door is inside the row it is meant to outlive"
35 );
36 // ...and nothing in the row decides for itself whether it can act: the
37 // oracle does, once, for the key and the button alike. A raw `control(`
38 // in here is a button that can go dead while its stroke still fires --
39 // the bug this redesign was called in for.
40 assert_eq!(
41 row.matches("\n .child(control(").count(),
42 0,
43 "a toolbar button bypassing the availability oracle"
44 );
45}
46
47/// The whole reason `ui/theme.rs` exists: a colour written anywhere else is
48/// a colour the next palette sweep will miss, which is exactly how 186 grey
49/// calls survived every previous attempt at this.
50#[test]
51fn no_colour_is_written_outside_the_theme() {
52 let source = ui_source();
53 let stray: Vec<&str> = source
54 .lines()
55 .filter(|l| l.contains("rgb(0x") || l.contains("rgba(0x"))
56 .collect();
57 assert!(stray.is_empty(), "colour written outside the theme: {stray:?}");
58}
59
60/// The literal-grep above is blind to a hue arriving through a theme
61/// *constant*: `DARK_SEAM` carried `rgba(0,0,0,.7)` (`0xRRGGBBAA`) into
62/// `rgb()`, which reads the alpha byte as blue -- 2436 blue pixels in a
63/// darkroom screenshot, on a call site that never once wrote `0x` itself.
64/// So this scan reads the theme's own encoding: every constant whose low
65/// byte is not `ff` (i.e. `0xRRGGBBAA` with a real alpha) is alpha-carrying,
66/// and an alpha-carrying role may only ever be handed to `rgba(`, never
67/// `rgb(`.
68#[test]
69fn an_alpha_carrying_role_never_reaches_rgb() {
70 let theme = src_text("ui/theme.rs");
71 let alpha_roles: Vec<&str> = theme
72 .lines()
73 .filter_map(|l| {
74 let l = l.trim();
75 let l = l.strip_prefix("pub const ")?;
76 let (name, rest) = l.split_once(':')?;
77 let hex = rest.trim().strip_prefix("u32 = 0x")?;
78 let hex = hex.trim_end_matches(';');
79 (hex.len() == 8 && !hex.ends_with("ff")).then_some(name.trim())
80 })
81 .collect();
82 assert!(alpha_roles.len() >= 8, "the theme's alpha-carrying roles moved; this scan is blind");
83
84 let source = ui_source();
85 let mut misuses = Vec::new();
86 for role in &alpha_roles {
87 if source.contains(&format!("rgb({role}(")) {
88 misuses.push(*role);
89 }
90 }
91 assert!(misuses.is_empty(), "alpha-carrying role(s) reaching rgb() instead of rgba(): {misuses:?}");
92}
93
94/// "It scrolls" is not "it can be found": at the 640x360 floor the timeline
95/// takes its share and no more, so a third track is behind a scroll -- and
96/// the line that says so has to keep telling the truth *while* the column is
97/// being scrolled, or it is an instruction nobody can carry out.
98#[test]
99fn the_line_about_what_is_below_the_fold_counts_what_is_still_below_it() {
100
101 // The timeline is a region and not the window: its chrome -- the
102 // scrollbar strip's row included, which is the larger of the two the
103 // zoom can leave in it -- and one whole lane fit the share it may take
104 // at the floor.
105 let floor = 360. * TIMELINE_SHARE;
106 assert!(
107 timeline_fixed_h(true) + LANE_H <= floor,
108 "{} px of chrome and a lane will not fit {floor} px",
109 timeline_fixed_h(true)
110 );
111 // The lane questions, asked of the mixed math the render actually walks
112 // (the uniform lanes_shown/rows_below pair went with their last caller;
113 // a lane in the stack may be a thinner
114 // caption one: a uniform stack answers exactly what the plain
115 // functions above do, and a mixed one answers off the real heights,
116 // never the media one alone.
117 let uniform = [LaneKind::Video, LaneKind::Audio];
118 assert_eq!(lanes_h_mixed(&uniform), lanes_h(2));
119 assert_eq!(lanes_shown_mixed(&uniform, LANE_H), 1);
120 let mixed = [LaneKind::Video, LaneKind::Audio, LaneKind::Subtitle];
121 assert_eq!(
122 lanes_h_mixed(&mixed),
123 2. * LANE_H + SUB_LANE_H + 2. * 8.,
124 "a caption lane is not counted as a full LANE_H row"
125 );
126 // A box exactly tall enough for the two media lanes and no more: the
127 // thinner third lane still does not fit above it.
128 assert_eq!(lanes_shown_mixed(&mixed, lanes_h(2)), 2);
129 // ...and with room for the caption lane too, all three show and
130 // nothing is below the fold.
131 assert_eq!(lanes_shown_mixed(&mixed, lanes_h_mixed(&mixed)), 3);
132 assert_eq!(rows_below_mixed(&mixed, lanes_h_mixed(&mixed), 0.), 0);
133 assert_eq!(rows_below_mixed(&mixed, lanes_h(2), 0.), 1);
134
135 // The inspector's rows are not one height, so its own line is measured
136 // in pixels off the scroll instead: gpui keeps the offset negative going
137 // down, and at the bottom the two cancel out exactly.
138 assert_eq!(px_below(120., 0.), 120.);
139 assert_eq!(px_below(120., -40.), 80.);
140 assert_eq!(px_below(120., -120.), 0.);
141 assert_eq!(px_below(0., 0.), 0.);
142}
143
144/// The failure a user never learns about is the one that was answered by
145/// another failure: two imports failing back to back are two messages, in
146/// the order they happened, and the second does not overwrite the first
147/// before a frame has drawn it.
148#[test]
149fn a_second_message_queues_behind_the_first_instead_of_erasing_it() {
150 let mut q = std::collections::VecDeque::new();
151 push_notice(&mut q, "NOTHING ADDED — no video stream".into());
152 push_notice(&mut q, "NOTHING ADDED — the file is not there".into());
153 assert_eq!(q.len(), 2);
154 assert_eq!(q.front().map(|n: &gpui::SharedString| n.as_ref()), Some("NOTHING ADDED — no video stream"));
155
156 // A held key that refuses says its one sentence once: the count on the
157 // bar is a count of messages, not of how long the key was held.
158 push_notice(&mut q, "NOTHING ADDED — the file is not there".into());
159 assert_eq!(q.len(), 2);
160
161 // ...and the ceiling drops the oldest rather than the newest: the thing
162 // that just happened is the thing worth reading.
163 for i in 0..NOTICES_MAX + 3 {
164 push_notice(&mut q, format!("SCAN FAILED: {i}").into());
165 }
166 assert_eq!(q.len(), NOTICES_MAX);
167 assert_eq!(q.back().map(|n: &gpui::SharedString| n.as_ref()), Some("SCAN FAILED: 10"));
168
169 // Answering the bar brings the next one up, oldest first.
170 let front = q.pop_front();
171 assert_ne!(front, q.front().cloned());
172}
173
174/// An export's own outcome is what a person started it to read, so it must
175/// never sit behind two progress lines queued while it ran: it jumps to the
176/// front and is the one showing the moment it arrives.
177#[test]
178fn an_export_outcome_jumps_the_queue() {
179 let mut q = std::collections::VecDeque::new();
180 push_notice(&mut q, "PROXY READY for a.mp4 — Proxies on cuts on it".into());
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(&mut q, "PROXY READY for a.mp4 — Proxies on cuts on it".into());
193 push_notice(&mut q, "EXPORT FAILED: disk full".into());
194 assert_eq!(
195 q.front().map(|n: &gpui::SharedString| n.as_ref()),
196 Some("EXPORT FAILED: disk full")
197 );
198}
199
200/// The bar colours itself off the words the message already opens with, so
201/// the tone cannot disagree with the sentence it labels.
202#[test]
203fn a_message_wears_the_colour_its_own_words_say() {
204 assert_eq!(notice_tone("SCAN FAILED: no audio"), STATUS_ERROR());
205 assert_eq!(notice_tone(&format!("{EXPORT_DONE}out.mp4")), STATUS_SUCCESS());
206 assert_eq!(notice_tone("NOTHING DETACHED — not grouped"), STATUS_WARNING());
207 assert_eq!(notice_tone("SNAP ON"), ACCENT_PRIMARY());
208}
209
210/// The cards are sections of the inspector, not sheets over the timeline:
211/// adjusting a clip must never hide the clip. Structural, because that is
212/// where the rule lives -- a card rendered from the root again would be an
213/// overlay again, whatever it looked like on the day it was written.
214#[test]
215fn an_inspector_section_occludes_no_timeline() {
216 let inspector = src_text("ui/inspector.rs");
217 // Whichever file the root render has come to live in, from the impl to the
218 // end of it -- found rather than named, so moving the root does not quietly
219 // leave this rule reading a file the render is no longer in.
220 let render = source_from("impl Render for Player");
221 for card in [
222 "eq_card", "color_card", "speed_card", "silence_card", "mix_card", "subtitle_style_card",
223 ] {
224 assert!(
225 inspector.contains(&format!("self.{card}(")),
226 "{card} is not a section of the inspector"
227 );
228 assert!(
229 !render.contains(&format!("self.{card}(")),
230 "{card} is drawn from the root again -- it is an overlay over the timeline"
231 );
232 }
233 // The docked cards are placed against the inspector's own box, which is
234 // what turns `scrim()` (`absolute().inset_0()`) from a window-wide sheet
235 // into this column.
236 assert!(
237 inspector.contains(".relative()"),
238 "the inspector is not a positioning context: its cards would cover the window"
239 );
240}
241
242/// MUST 1, on the two named offenders: the button that relabels itself
243/// mid-export and the one that used to read "Muted 80%". Both live in a
244/// rect that is reserved once, so the words change and the box does not.
245#[test]
246fn a_stateful_button_keeps_its_rect() {
247 use crate::ui::toolbar::{EXPORT_SLOT_W, SNAP_SLOT_W, VOLUME_SLOT_W};
248 // Widest word each slot can hold, at the 12 px text this window is set
249 // in -- ~7 px a character plus the 16 px of padding.
250 let fits = |slot: f32, word: &str| slot >= word.chars().count() as f32 * 7. + 16.;
251 for word in ["Export", "Cancel"] {
252 assert!(fits(EXPORT_SLOT_W, word), "{word} overflows its rect");
253 }
254 for word in ["Snap on", "Snap off", "No subs", "Subs off"] {
255 assert!(fits(SNAP_SLOT_W, word), "{word} overflows its rect");
256 }
257 for word in ["100%", "× 100%"] {
258 assert!(fits(VOLUME_SLOT_W, word), "{word} overflows its rect");
259 }
260 // And the rect is passed, not hoped for: every stateful control in the
261 // three chrome rows names its width.
262 let toolbar = src_text("ui/toolbar.rs");
263 for (id, slot) in [
264 ("\"export\"", "EXPORT_SLOT_W"),
265 ("\"snap\"", "SNAP_SLOT_W"),
266 ("\"subs\"", "SNAP_SLOT_W"),
267 ("\"volume\"", "VOLUME_SLOT_W"),
268 ("\"zoom-fit\"", "ZOOM_SLOT_W"),
269 ] {
270 let at = toolbar.find(id).unwrap_or_else(|| panic!("no {id} button"));
271 assert!(
272 toolbar[at..at + 120].contains(slot),
273 "{id} does not reserve {slot}"
274 );
275 }
276}
277
278#[test]
279fn nothing_clickable_is_smaller_than_the_wcag_minimum() {
280 // Every hit target in the panel, including the scrub strip -- whose bar
281 // is 6 px to look at and whose click area must not be.
282 assert!(CONTROL_H >= HIT_MIN);
283 assert!(RULER_HIT_H >= HIT_MIN);
284 assert!(LANE_H >= HIT_MIN);
285 // A caption lane's header carries exactly one hit target now (the
286 // show/hide eye; remove moved to its right button), and that target
287 // fills the whole row -- so the row is never allowed to undercut the
288 // target it *is*.
289 assert!(SUB_LANE_H >= HIT_MIN);
290 // A clip box is a hit target too, and its two trim strips occlude it:
291 // on a box narrower than the pair there is no body left to press, so
292 // the clip cannot be selected, dragged or menued at all -- which is
293 // every clip a jumpcut leaves at a normal zoom. Below three handles
294 // there are no strips.
295 assert!(!trims(0.));
296 assert!(!trims(EDGE_W));
297 assert!(!trims(2. * EDGE_W), "a box that is all handle and no clip");
298 assert!(!trims(3. * EDGE_W - 0.1));
299 // And where they are drawn, what is left between them is a hit target
300 // in its own right -- a whole handle's width of clip.
301 for width in [3. * EDGE_W, 24., 100., 4000.] {
302 assert!(trims(width));
303 assert!(
304 width - 2. * EDGE_W >= EDGE_W,
305 "{width} px of box leaves no middle"
306 );
307 }
308}
309
310#[test]
311fn a_lane_row_is_a_fixed_header_and_a_bed_that_can_be_hit() {
312 // The header column is what the ruler is offset by as well, so both
313 // numbers are shared rather than repeated per row (A-MUST1/A-MUST2).
314 assert!(HEADER_W > 0. && HEADER_GAP >= 0.);
315 // Two lanes, a ruler, a button row and the timecode line, inside the
316 // panel the window is sized for.
317 assert!(
318 CONTROL_H + RULER_HIT_H + 2. * LANE_H + 17. + 4. * 8. + 16. <= PANEL_H,
319 "the second lane does not fit the panel"
320 );
321 // Headers and clip boxes are as tall as the lane, and the lane is a
322 // click target (WCAG 2.5.8).
323 assert!(LANE_H >= HIT_MIN);
324 // A label row that ate the whole lane would leave no waveform.
325 assert!(LABEL_H < LANE_H / 2.);
326 // An added track adds its own row to the panel, and the two a project
327 // starts with leave it exactly the height it has always been.
328 assert_eq!(panel_h(2), PANEL_H);
329 assert_eq!(panel_h(1), PANEL_H);
330 assert_eq!(panel_h(3), PANEL_H + LANE_H + 8.);
331 assert_eq!(
332 panel_h(LANES_MAX),
333 PANEL_H + lanes_h(LANES_MAX) - lanes_h(2)
334 );
335 // Past the cap the column scrolls instead: the panel stops growing, so
336 // no number of tracks can push the picture off the window.
337 assert_eq!(panel_h(LANES_MAX + 1), panel_h(LANES_MAX));
338 assert_eq!(panel_h(50), panel_h(LANES_MAX));
339 assert_eq!(lanes_h(0), 0.);
340 assert_eq!(lanes_h(1), LANE_H);
341 assert_eq!(lanes_h(2), 2. * LANE_H + 8.);
342}
343
344/// The scrollbar's thumb: the visible share of the timeline at its own
345/// place on the track, full width with nothing to scroll, never narrower than
346/// a hand can hold, and never off the ends.
347#[test]
348fn the_scroll_thumb_is_the_visible_share_at_its_own_place() {
349 use crate::scroll_thumb;
350 use crate::SCROLL_THUMB_MIN;
351
352 // Nothing to scroll: the strip fills and says so.
353 assert_eq!(scroll_thumb(400., 10., 0., 12.), (0., 400.));
354 assert_eq!(scroll_thumb(400., 0., 0., 0.), (0., 400.));
355 // Half the timeline on the bed: a half-width thumb, halfway along for a
356 // window starting halfway in.
357 assert_eq!(scroll_thumb(400., 20., 0., 10.), (0., 200.));
358 assert_eq!(scroll_thumb(400., 20., 10., 10.), (200., 200.));
359 // The floor width: however long the timeline, the thumb stays holdable --
360 // and the clamp keeps it on the track, not the caller.
361 let (x, w) = scroll_thumb(400., 1_000_000., 999_000., 100.);
362 assert_eq!(w, SCROLL_THUMB_MIN);
363 assert_eq!(x, 400. - SCROLL_THUMB_MIN);
364 assert_eq!(scroll_thumb(400., 1_000_000., 0., 100.).0, 0.);
365}
366
367/// A press beside the time axis's thumb jumps so the thumb's middle is under
368/// the pointer, and the drag that carries on from the press must land exactly
369/// where the jump left the view: both are read through the track's own
370/// proportion (a jump worked out in pixels at the view's pps used to land at
371/// span-over-duration of the target, and the snap on the first move was the
372/// drag correcting it). The equality below is the no-snap invariant, at the
373/// thumb's own width and at its floor width alike.
374#[test]
375fn a_beside_thumb_press_jumps_by_the_tracks_own_proportion() {
376 use crate::scroll_thumb;
377
378 let bed = 400.;
379 // The mapping both halves of the gesture share: a place on the track is
380 // that share of the drawn duration.
381 let jump = |at: f32, thumb_w: f32| (at - thumb_w / 2.).max(0.) / bed;
382 for (duration, span) in [(100_f32, 20_f32), (1_000_000_f32, 100_f32)] {
383 let (_, thumb_w) = scroll_thumb(bed, f64::from(duration), 0., f64::from(span));
384 let at = 3. * bed / 4.;
385 let start = jump(at, thumb_w) * duration;
386 // The jump centres the thumb on the press (the far end of a million
387 // seconds is the clamp's to hold, so the pin is measured from the
388 // thumb the track actually shows).
389 let (x, w) = scroll_thumb(bed, f64::from(duration), f64::from(start), f64::from(span));
390 let centre = (x + w / 2.).min(bed - w / 2.);
391 assert!(
392 (centre - at.min(bed - w / 2.)).abs() < 1.,
393 "thumb centre {centre} not at the press {at}"
394 );
395 // The drag's first sample from that press -- the grabbed middle, the
396 // same track proportion -- is the same start, whatever the width.
397 let grab = thumb_w / 2.;
398 assert_eq!(jump(at, 2. * grab) * duration, start);
399 }
400}
401
402/// The strip's row is furniture only while there is somewhere to scroll to:
403/// zoomed out to the whole timeline the strip is not drawn and neither is its
404/// height -- out of every budget at once (the region, the box the lanes are
405/// laid out against, and the seam's floor), or the lanes would gain or lose a
406/// strip's row at the zoom boundary without the strip to show for it.
407#[test]
408fn the_scroll_strip_row_comes_and_goes_with_the_zoom() {
409 use crate::{SCROLL_HIT, Split, lanes_h, split_size, timeline_fixed_h, timeline_h};
410 use gpui::{px, size};
411
412 // The strip's row, and only the strip's row, is what the two faces differ
413 // by -- the gap above it and its own hit height.
414 assert_eq!(
415 timeline_fixed_h(true) - timeline_fixed_h(false),
416 8. + SCROLL_HIT
417 );
418 let window = size(px(1280.), px(720.));
419 for scroll in [false, true] {
420 // Whatever the strip is doing, the lanes keep exactly the room they
421 // had: the region grows by the strip's row when it appears, by
422 // exactly the row the lanes would otherwise lose to it.
423 assert_eq!(timeline_h(2, scroll) - timeline_fixed_h(scroll), lanes_h(2));
424 assert_eq!(
425 timeline_h(6, scroll) - timeline_fixed_h(scroll),
426 lanes_h(6)
427 );
428 // ...and the floor keeps a whole lane standing under the line, on
429 // either face of the zoom boundary.
430 let floor = split_size(Split::Timeline, Some(0.), 2, window, scroll);
431 let box_h = floor - timeline_fixed_h(scroll);
432 assert!(
433 2 > lanes_shown_mixed(&[LaneKind::Video, LaneKind::Audio], box_h),
434 "no line to pay for at the floor"
435 );
436 assert!(
437 box_h - LABEL_H - 8. >= LANE_H,
438 "the floor leaves {} px for a {LANE_H} px lane",
439 box_h - LABEL_H - 8.
440 );
441 // The two floors land the lanes in the same place: whichever face
442 // the zoom is on, a timeline held at its floor shows the same whole
443 // lane under the same line -- the strip's row comes and goes with
444 // the floor, not out of the lane. (A size dragged into the interior
445 // stays the hand's across the boundary, and the lanes are simply
446 // given the row back.)
447 assert_eq!(box_h, LANE_H + LABEL_H + 8.);
448 }
449 // The share covers the taller floor, strip in -- the one the clamp would
450 // otherwise overrule at the 640x360 floor, saying the panel takes less of
451 // a short window than it does.
452 assert!(
453 timeline_fixed_h(true) + LANE_H + LABEL_H + 8. <= 360. * TIMELINE_SHARE,
454 "the strip-bearing floor will not fit the share"
455 );
456}
457
458/// The lane stack's thumb: the visible share of the rows at their own place
459/// on the track, the time axis's own thumb turned through a right angle.
460#[test]
461fn the_lane_thumb_is_the_visible_share_of_the_stack() {
462 use crate::lanes_thumb;
463 use crate::SCROLL_THUMB_MIN;
464
465 // Whole stack on screen: the track fills and there is nothing to scroll.
466 assert_eq!(lanes_thumb(200., 104., 200., 0.), (0., 200.));
467 assert_eq!(lanes_thumb(200., 0., 0., 0.), (0., 200.));
468 // Half the stack visible, taken halfway down: a half-height thumb at the
469 // halfway mark.
470 assert_eq!(lanes_thumb(200., 400., 200., 100.), (50., 100.));
471 assert_eq!(lanes_thumb(200., 400., 200., 0.), (0., 100.));
472 // The floor height: however tall the stack, the thumb stays holdable --
473 // and the clamp keeps it on the track, not the caller.
474 let (y, h) = lanes_thumb(200., 2000., 200., 1800.);
475 assert_eq!(h, SCROLL_THUMB_MIN);
476 assert_eq!(y, 200. - SCROLL_THUMB_MIN);
477 assert_eq!(lanes_thumb(200., 2000., 200., 0.).0, 0.);
478 assert_eq!(lanes_thumb(200., 1_000_000., 200., 0.).0, 0.);
479}
480
481/// A caption's box wears the rate its window plays at, derived off the
482/// placement itself: unity placements -- including odd widths whose frames
483/// came off `frames_of_us` rounding -- do not badge, and a re-rate does, with
484/// the rate surviving the group coming apart.
485#[test]
486fn a_caption_box_wears_the_rate_its_window_plays_at() {
487 use crate::caption_rate;
488
489 let sub = |frames: u32, out_us: i64| SubClip {
490 start: 0,
491 frames,
492 track: 0,
493 in_us: 0,
494 out_us,
495 link: None,
496 };
497 // Unity, exact and rounded: neither is a re-timing.
498 assert_eq!(caption_rate(sub(300, 10_000_000), 30.), None);
499 assert_eq!(
500 caption_rate(sub(100, 3_333_333), 30.),
501 None,
502 "placement rounding is not a re-timing"
503 );
504 // ...and rounding on SHORT tracks, where half a frame is a large share of
505 // the window: `frames_of_us` of 1,016,667µs gives 31 frames (16,667µs of
506 // error -- 16 permille, but half a frame), and of 5,015,000µs gives 150
507 // (15,000µs). Both are unity; a relative gate badges one 0.98x and the
508 // other a self-contradicting 1.00x.
509 assert_eq!(
510 caption_rate(sub(31, 1_016_667), 30.),
511 None,
512 "half a frame off a one-second window is still unity"
513 );
514 assert_eq!(
515 caption_rate(sub(150, 5_015_000), 30.),
516 None,
517 "a hair under five seconds rounds to 150 frames and stays unity"
518 );
519 // A 2x re-rate: a 5s span holding the same 10s of words.
520 assert_eq!(
521 caption_rate(sub(150, 10_000_000), 30.).map(|s| s.permille()),
522 Some(2000)
523 );
524 // ...and a slowed one -- a 20s span for the same words -- which the badge
525 // keeps after any detach: the proportion is the placement's own.
526 assert_eq!(
527 caption_rate(sub(600, 10_000_000), 30.).map(|s| s.permille()),
528 Some(500)
529 );
530}
531
532/// The selection itself: clicks in order, the anchor under the hand, the
533/// toggle that assembles a group, and the plain click that replaces it all.
534#[test]
535fn a_selection_holds_its_picks_in_click_order_and_anchors_the_last() {
536 use crate::Selection;
537
538 let mut sel = Selection::new();
539 assert!(sel.is_empty());
540 assert_eq!(sel.anchor(), None);
541
542 let (v, a, cap) = (
543 (Lane::V1, 0),
544 (Lane::A1, 1),
545 (Lane::new(LaneKind::Subtitle, 0), 0),
546 );
547 sel.set_one(v);
548 assert_eq!(sel.len(), 1);
549 assert_eq!(sel.anchor(), Some(v));
550
551 // Ctrl-clicks join, in the order they were made.
552 sel.toggle(a);
553 sel.toggle(cap);
554 assert_eq!(sel.picks(), &[v, a, cap]);
555 assert_eq!(sel.anchor(), Some(cap), "the last pick is the anchor");
556 assert!(sel.contains(a));
557
558 // ...and a ctrl-click on a pick already held takes it back out, leaving
559 // the others where they were.
560 sel.toggle(a);
561 assert_eq!(sel.picks(), &[v, cap]);
562 assert!(!sel.contains(a));
563
564 // A plain click is the whole selection, one pick: whatever was held gives
565 // way to the thing just named.
566 sel.set_one(a);
567 assert_eq!(sel.picks(), &[a]);
568
569 // `add` joins without disturbing -- Select All's builder.
570 let mut all = Selection::new();
571 all.add(v);
572 all.add(a);
573 all.add(v);
574 assert_eq!(all.picks(), &[v, a], "a pick is never held twice");
575
576 sel.clear();
577 assert!(sel.is_empty());
578 assert_eq!(sel.anchor(), None);
579}
580
581#[test]
582fn a_click_marks_the_whole_group_and_nothing_else() {
583 let (v, a) = ((Lane::V1, 0), (Lane::A1, 0));
584 // Clicking the video half of group 1 marks the audio half with it -- the
585 // pick, and everything sharing its link.
586 assert!(marked(v, Some(1), &[v], &[Some(1)]));
587 assert!(marked(a, Some(1), &[v], &[Some(1)]));
588 // Another group's clips stay unmarked, in either lane.
589 assert!(!marked((Lane::V1, 1), Some(2), &[v], &[Some(1)]));
590 assert!(!marked((Lane::A1, 1), Some(2), &[v], &[Some(1)]));
591 // A half a lift left behind has no group: it marks itself only, which
592 // is what makes it separately deletable. Two ungrouped clips must not
593 // mark each other by both being ungrouped.
594 assert!(marked(a, None, &[a], &[None]));
595 assert!(!marked(v, None, &[a], &[None]));
596 // A caption ctrl-clicked into the selection marks the clip it was pinned
597 // to, and the caption is marked by the clip's pick just the same.
598 let cap = (Lane::new(LaneKind::Subtitle, 0), 0);
599 assert!(marked(cap, Some(1), &[cap, v], &[None, Some(1)]));
600 assert!(marked(a, Some(1), &[cap, v], &[None, Some(1)]));
601 // Nothing selected marks nothing.
602 assert!(!marked(v, Some(1), &[], &[]));
603}
604
605#[test]
606fn a_name_is_dropped_rather_than_smeared_across_a_thin_clip() {
607 assert!(show_label(LABEL_MIN_W));
608 assert!(show_label(400.));
609 assert!(!show_label(LABEL_MIN_W - 0.1));
610 // The label test is the box's own width in pixels now, which is what
611 // the scale hands it -- no bed width, and so nothing to be zero.
612 let scale = Scale::default();
613 assert!(show_label(scale.width_px(LABEL_MIN_W as f64 / PPS_DEFAULT)));
614 assert!(!show_label(scale.width_px(0.)));
615}
616
617#[test]
618fn an_envelope_stays_inside_the_box_it_is_drawn_in() {
619 // A ramp: silence at the start, full scale at the end.
620 let peaks: Vec<(f32, f32)> = (0..40)
621 .map(|i| (-(i as f32) / 39., i as f32 / 39.))
622 .collect();
623 let (w, h) = (100., 30.);
624 let cols = envelope(&peaks, 0., 1., w, h);
625 assert_eq!(cols.len(), (w / WAVE_COL) as usize + 1);
626 for &(x, top, bottom) in &cols {
627 assert!((0. ..=w).contains(&x), "x {x} outside 0..{w}");
628 assert!((0. ..=h).contains(&top), "top {top} outside 0..{h}");
629 assert!(
630 (0. ..=h).contains(&bottom),
631 "bottom {bottom} outside 0..{h}"
632 );
633 // Never inverted, and never a polygon with no area: silence has to
634 // read as a line rather than as nothing at all.
635 assert!(
636 bottom - top >= 1.,
637 "column {top}..{bottom} is thinner than a pixel"
638 );
639 }
640 // The ramp is drawn as a ramp: the last column is taller than the first.
641 let height = |&(_, top, bottom): &(f32, f32, f32)| bottom - top;
642 assert!(height(cols.last().unwrap()) > height(cols.first().unwrap()) + 5.);
643 // Degenerate inputs draw nothing rather than panicking.
644 assert!(envelope(&[], 0., 1., w, h).is_empty());
645 assert!(envelope(&peaks, 0., 1., 0., h).is_empty());
646 // A clip whose range runs past the peaks clamps to the last bucket.
647 assert!(!envelope(&peaks, 0., 99., w, h).is_empty());
648}
649
650/// A box laid out wider than any screen -- a long clip at a deep zoom -- is
651/// still one screen's worth of columns: the path a repaint has to build is
652/// bounded by what can be seen, not by what the layout says the box is.
653/// Unbounded, a 5 s clip zoomed to the frame is a path of millions of points
654/// per frame, and the repaint that stalls on it is the waveform that
655/// "disappeared".
656#[test]
657fn an_envelope_never_costs_more_points_than_a_screen_can_show() {
658 let peaks: Vec<(f32, f32)> = (0..200).map(|i| (-(i as f32) / 199., 1.)).collect();
659 // The width a 5 s clip is laid out at when the bed shows 8 frames of it.
660 let huge = 5. * 30. / 8. * 1200.;
661 let cols = envelope(&peaks, 0., 5., huge, 30.);
662 assert!(
663 cols.len() <= WAVE_COLS_MAX + 1,
664 "{} columns for a {huge} px box",
665 cols.len()
666 );
667 // ...and the slice actually painted is the part of the box on the bed,
668 // which is where that width stops mattering: a column per two visible
669 // pixels, at every zoom.
670 let (x, w) = visible_slice(-huge / 2., huge, 1200.);
671 assert_eq!((x, w), (huge / 2., 1200.));
672 assert_eq!(envelope(&peaks, 0., 5., w, 30.).len(), 601);
673 // A box entirely off the bed has no slice, and one that has never been
674 // measured is drawn whole -- what was drawn before there was a bed.
675 assert_eq!(visible_slice(2000., 500., 1200.), (0., 0.));
676 assert_eq!(visible_slice(-3000., 500., 1200.), (500., 0.));
677 assert_eq!(visible_slice(-40., 500., 0.), (0., 500.));
678 // Half on, at either edge.
679 assert_eq!(visible_slice(-100., 500., 1200.), (100., 400.));
680 assert_eq!(visible_slice(1000., 500., 1200.), (0., 200.));
681}
682
683/// The box a trim draws is the box its release commits, at every speed. The
684/// preview used to hand the *timeline* frame count to a source-frame field:
685/// at 2x a tail moved twice as fast as the pointer and snapped back on
686/// release, and a head drag moved the clip's other edge.
687#[test]
688fn a_trim_preview_lands_where_the_release_commits() {
689 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
690 session.set_gain(0.0);
691 for permille in SPEED_PRESETS {
692 // Live, so the loop owes it no undo step: the speeds are the axis
693 // this walks, and the trims below are what is undone.
694 session
695 .set_speed_live(Lane::V1, 0, Speed::from_permille(permille))
696 .expect("a clip alone on its lane may be speeded");
697 for edge in [Edge::Start, Edge::End] {
698 let clip = session.lane_clips(Lane::V1)[0];
699 let (lo, hi) = session
700 .trim_room(Lane::V1, 0, edge)
701 .expect("clip 0 is there");
702 // Both walls and the middle of the room: the whole range a
703 // pointer can be clamped to.
704 for to in [lo, (lo + hi) / 2, hi] {
705 let preview = trimmed_clip(clip, edge, to, false);
706 // The drag is one edit and one undo step, so the next `to`
707 // is measured from the same clip this one was.
708 if session.trim_clip(Lane::V1, 0, edge, to) {
709 assert_eq!(
710 preview,
711 session.lane_clips(Lane::V1)[0],
712 "{edge:?} to {to} at {permille} per mille"
713 );
714 assert!(session.undo(), "the trim is one undo step");
715 } else {
716 // An edge already where it was asked to go is not an
717 // edit, and the preview draws the clip unchanged.
718 assert_eq!(preview, clip, "{edge:?} to {to} at {permille} per mille");
719 }
720 assert_eq!(session.lane_clips(Lane::V1)[0], clip, "back where it was");
721 }
722 }
723 }
724}
725
726/// The caption a drag is showing lands where the release commits -- the
727/// subtitle twin of the trim preview above -- and the two contracts the boxes
728/// on the lanes rest on: `place_sub`'s `at` wins over the placement's own
729/// `start`, and a gesture that changed nothing is `Ok` and not a refusal, so a
730/// front-end that toasted every `Ok` would toast a pick-up-put-back.
731#[test]
732fn a_caption_trim_preview_lands_where_the_release_commits() {
733 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
734 session.set_gain(0.0);
735 let fps = session.meta().frame_rate;
736 let srt = Path::new(env!("CARGO_MANIFEST_DIR"))
737 .join("../engine/tests/data/test_subs.srt")
738 .canonicalize()
739 .expect("the subtitle fixture");
740 session.import_subtitles(&srt).expect("the .srt imports");
741 let lane = session.add_lane(LaneKind::Subtitle);
742 // The whole track as a placement, exactly as `Player::sub_of_track` builds
743 // one from a palette row.
744 let out_us = session.subtitles()[0]
745 .cues
746 .iter()
747 .map(|c| c.end_us)
748 .max()
749 .expect("the fixture has cues");
750 let whole = SubClip {
751 start: 0,
752 frames: frames_of_us(out_us, fps),
753 track: 0,
754 in_us: 0,
755 out_us,
756 link: None,
757 };
758 session
759 .place_sub(lane, 30, whole)
760 .expect("an empty subtitle lane takes it");
761 assert_eq!(
762 session.sub_lane(lane)[0].start,
763 30,
764 "the frame the hand let go on wins over the placement's own start"
765 );
766 for edge in [Edge::Start, Edge::End] {
767 let (lo, hi) = session
768 .trim_sub_room(lane, 0, edge)
769 .expect("placement 0 is there");
770 for to in [lo, (lo + hi) / 2, hi] {
771 let placed = session.sub_lane(lane)[0];
772 let preview = trimmed_sub(placed, edge, to);
773 session
774 .trim_sub(lane, 0, edge, to)
775 .expect("an edge inside its own room is never refused");
776 let now = session.sub_lane(lane)[0];
777 assert_eq!(
778 (preview.start, preview.frames),
779 (now.start, now.frames),
780 "{edge:?} to {to}"
781 );
782 // One edit, one undo step -- and none at all where the edge was
783 // already there, which is the `Ok` that must stay silent.
784 if (now.start, now.frames) != (placed.start, placed.frames) {
785 assert!(session.undo(), "the trim is one undo step");
786 }
787 }
788 }
789 // Picked up and put back down: `Ok`, nothing moved, nothing to say.
790 let before = session.sub_lane(lane)[0];
791 session
792 .move_sub(lane, 0, lane, before.start)
793 .expect("a drop that changes nothing is not a refusal");
794 assert_eq!(session.sub_lane(lane)[0], before);
795 // ...and two captions over one frame are refused in words, which is what
796 // the notice shows verbatim.
797 let over = session
798 .place_sub(lane, before.start, whole)
799 .expect_err("two captions may not cover one frame");
800 assert!(over.to_string().contains("already covers"), "{over}");
801}
802
803/// A still trims the same way, and the preview knows it: its head grows
804/// forward from source frame 0 -- every frame of it is the same picture --
805/// so the box stretches instead of sliding left.
806#[test]
807fn a_stills_trim_preview_grows_forward_like_the_commit() {
808 let mut session = PlaybackSession::open(asset("test_still.png")).expect("a picture opens");
809 for edge in [Edge::Start, Edge::End] {
810 let clip = session.lane_clips(Lane::V1)[0];
811 let (lo, hi) = session
812 .trim_room(Lane::V1, 0, edge)
813 .expect("clip 0 is there");
814 for to in [lo, (lo + hi) / 2, hi] {
815 let preview = trimmed_clip(clip, edge, to, true);
816 match session.trim_clip(Lane::V1, 0, edge, to) {
817 true => {
818 assert_eq!(
819 preview,
820 session.lane_clips(Lane::V1)[0],
821 "a still {edge:?} to {to}"
822 );
823 assert!(session.undo(), "the trim is one undo step");
824 }
825 false => assert_eq!(preview, clip, "a still {edge:?} to {to}"),
826 }
827 assert_eq!(session.lane_clips(Lane::V1)[0], clip, "back where it was");
828 }
829 }
830}
831
832/// gpui freezes a drag's payload for the whole gesture, and nothing stops a
833/// stroke from editing the lane under it: the drop has to find the clip that
834/// was picked up, not whatever slid into its index.
835#[test]
836fn a_drop_moves_the_clip_that_was_picked_up_not_its_old_index() {
837 let at = |start: u32| Clip {
838 fade_in: 0,
839 fade_out: 0,
840 transition_out: 0,
841 start,
842 in_frame: 0,
843 out_frame: 30,
844 source: 0,
845 link: None,
846 eq: None,
847 color: None,
848 transform: None,
849 fit: FitPolicy::Fit,
850 speed: Speed::NORMAL,
851 };
852 let lane = [at(0), at(30), at(60)];
853 let dragged = lane[2];
854 assert_eq!(live_idx(&lane, 2, dragged), Some(2), "nothing moved");
855 // A delete in front of it: the clip is now index 1, and the index the
856 // drag froze names a clip nobody grabbed.
857 let after = [at(0), at(60)];
858 assert_eq!(live_idx(&after, 2, dragged), Some(1));
859 assert_eq!(live_idx(&after, 1, dragged), Some(1));
860 // Deleted mid-drag: there is nothing to move, and moving its neighbour
861 // instead is exactly the bug this exists for.
862 assert_eq!(live_idx(&[at(0)], 2, dragged), None);
863 assert_eq!(live_idx(&[], 0, dragged), None);
864}
865
866#[test]
867fn a_quiet_source_still_draws_as_a_shape() {
868 // An eighth of full scale, which is about where the fixtures sit.
869 let quiet: Vec<(f32, f32)> = vec![(-0.125, 0.125), (-0.0625, 0.0625)];
870 let loud = normalise(quiet.clone());
871 assert_eq!(loud[0], (-1., 1.));
872 assert_eq!(loud[1], (-0.5, 0.5));
873 // Digital silence has no loudest sample to scale to; it must not divide
874 // by zero and must stay flat.
875 assert_eq!(normalise(vec![(0., 0.)]), vec![(0., 0.)]);
876 assert!(normalise(Vec::new()).is_empty());
877}
878
879/// The whole waveform path, from the file on disk to the columns that get
880/// painted: what no screenshot can assert about the shape.
881#[test]
882fn the_fixtures_waveform_reaches_the_lane_as_a_shape() {
883 let asset = |name: &str| {
884 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
885 .join("../../assets")
886 .join(name)
887 };
888 let peaks = normalise(
889 engine::waveform::peaks(asset("test_av.mp4"), 0, WAVE_BPS)
890 .expect("open the fixture")
891 .expect("test_av.mp4 has audio"),
892 );
893 // 5 s of source at the rate the lane asks for.
894 assert!(peaks.len().abs_diff(5 * WAVE_BPS as usize) <= WAVE_BPS as usize);
895 let cols = envelope(&peaks, 0., 5., 600., 30.);
896 let height = |&(_, top, bottom): &(f32, f32, f32)| bottom - top;
897 let tallest = cols.iter().map(height).fold(0., f32::max);
898 let flattest = cols.iter().map(height).fold(f32::MAX, f32::min);
899 // The fixture's 1 Hz pulse: a full-scale peak and a near-silent dip in
900 // every second, so the drawn envelope is a shape and not a bar.
901 assert!(tallest > 25., "loudest column only {tallest} px of 30");
902 assert!(
903 flattest < 8.,
904 "quietest column {flattest} px -- no dips drawn"
905 );
906 // A video-only source draws no waveform at all rather than a flat fake.
907 assert!(
908 engine::waveform::peaks(asset("test_baseline.mp4"), 0, WAVE_BPS)
909 .expect("open the fixture")
910 .is_none()
911 );
912}
913
914#[test]
915fn every_mark_on_a_clip_is_legible_on_it() {
916 // The body a name and a waveform are drawn on is the clip's kind
917 // ([`clip_kind`]); the source tint is the border and the library
918 // swatch, and is measured for telling itself apart rather than for
919 // carrying text.
920 // Every palette a person can pick, not merely the one in force.
921 for id in crate::ui::theme::PaletteId::ALL {
922 let p = id.palette();
923 for (i, tint) in [p.CLIP_VIDEO, p.CLIP_AUDIO, p.CLIP_IMAGE, p.CLIP_TEXT]
924 .iter()
925 .enumerate()
926 {
927 // WCAG 1.4.3: the clip's name is body text on its tint.
928 assert!(
929 contrast(p.FG_PRIMARY, *tint) >= 4.5,
930 "{id:?} source {i}: label contrast {:.2}",
931 contrast(p.FG_PRIMARY, *tint)
932 );
933 // WCAG 1.4.11: the waveform is a non-text graphic on it.
934 assert!(
935 contrast(p.FG_SECONDARY, *tint) >= 3.,
936 "{id:?} source {i}: waveform contrast {:.2}",
937 contrast(p.FG_SECONDARY, *tint)
938 );
939 }
940 // A selected clip's bed is the same two marks on a different colour.
941 assert!(contrast(p.FG_PRIMARY, p.BG_SELECTED) >= 4.5, "{id:?}");
942 assert!(contrast(p.FG_SECONDARY, p.BG_SELECTED) >= 3., "{id:?}");
943 // The bed a gap shows through has to read as a hole in the lane --
944 // the clip is the object, the bed is the hole -- and the playhead
945 // has to be findable on both.
946 assert!(contrast(p.CLIP_VIDEO, p.BG_TIMELINE) >= 1.5, "{id:?}");
947 assert!(contrast(p.ACCENT_PLAYHEAD, p.BG_TIMELINE) >= 3., "{id:?}");
948 assert!(contrast(p.ACCENT_PLAYHEAD, p.CLIP_VIDEO) >= 3., "{id:?}");
949 }
950 // The sanity check on the ratio itself: black on white is 21:1.
951 assert!((contrast(0xffffff, 0x000000) - 21.).abs() < 0.01);
952}
953
954#[test]
955fn source_tints_differ_per_source_and_cycle() {
956 // The bug: the first entry *was* `BG_RAISED`, so the first file imported
957 // -- the one every session has -- wore the panel's own background and
958 // had no visible swatch at all.
959 assert_ne!(source_tint(0), BG_RAISED());
960 // ...in every family, since the swatch is drawn on whichever panel is
961 // in force (`ui::theme`) and a tint that vanished into one of them is a
962 // file with no colour at all.
963 for id in crate::ui::theme::PaletteId::ALL {
964 let p = id.palette();
965 for (i, &tint) in p.SOURCE_TINTS.iter().enumerate() {
966 assert_ne!(tint, p.BG_RAISED, "{id:?} tint {i} is the panel");
967 }
968 }
969 // Neighbouring sources must not share one, or an import is invisible.
970 assert_ne!(source_tint(0), source_tint(1));
971 assert_ne!(source_tint(1), source_tint(2));
972 assert_ne!(source_tint(2), source_tint(3));
973 // Past the palette it wraps -- never an index panic.
974 assert_eq!(source_tint(4), source_tint(0));
975 assert_eq!(source_tint(9), source_tint(1));
976 assert_eq!(source_tint(usize::MAX), SOURCE_TINTS()[usize::MAX % 4]);
977}
978
979/// Not "they are different numbers" -- different *enough to see*, against
980/// each other and against the surface a swatch is drawn on. The palette is
981/// deliberately dark and low-saturation, so the margin is thin and a new
982/// tint picked by eye can land inside it without anyone noticing.
983#[test]
984fn source_tints_are_all_discernible() {
985 // Summed channel distance: `BG_RAISED` to the warm tint is 18, and that
986 // step is the one already accepted as readable on a lane.
987 let apart = |a: u32, b: u32| {
988 (0..3)
989 .map(|i| {
990 let shift = i * 8;
991 ((a >> shift) & 0xff).abs_diff((b >> shift) & 0xff)
992 })
993 .sum::<u32>()
994 };
995 // Every family, not the one in force: a palette is picked at runtime
996 // now, and four tints tuned by eye on one ground are exactly where a
997 // pair lands inside the margin on another.
998 for id in crate::ui::theme::PaletteId::ALL {
999 let p = id.palette();
1000 for (i, &tint) in p.SOURCE_TINTS.iter().enumerate() {
1001 assert!(
1002 apart(tint, p.BG_RAISED) >= 16,
1003 "{id:?} tint {i} is {} from the panel it sits on",
1004 apart(tint, p.BG_RAISED)
1005 );
1006 for (j, &other) in p.SOURCE_TINTS.iter().enumerate().skip(i + 1) {
1007 // The eleven non-darkroom families still cycle four tuned
1008 // tints through the 12-wide wheel (`source_tint`'s own `%
1009 // len()` reads them back identically either way) -- a
1010 // literal repeat there is the intended cycle, not a
1011 // collision, so it is skipped rather than failed. Darkroom's
1012 // own twelve (DESIGN §2) are twelve *different* hues and
1013 // never repeat, so a real collision there still fails this.
1014 if tint == other {
1015 continue;
1016 }
1017 assert!(
1018 apart(tint, other) >= 16,
1019 "{id:?} tints {i} and {j} are only {} apart",
1020 apart(tint, other)
1021 );
1022 }
1023 }
1024 // The two a person sees side by side first must be further apart
1025 // than the floor: source 0 and source 1 are the first import and
1026 // the second.
1027 assert!(apart(p.SOURCE_TINTS[0], p.SOURCE_TINTS[1]) >= 32, "{id:?}");
1028 }
1029 // Darkroom's own 12-hue wheel (DESIGN §2/§12 step 5's hook): every one
1030 // of the twelve is a genuinely different hue, not four repeated three
1031 // times like the other families still cycle -- a hue accidentally
1032 // reintroduced by a future edit here is the "four shades of grey" bug
1033 // this task exists to fix, so it fails loudly rather than skip past the
1034 // `tint == other` escape hatch above.
1035 let dr = crate::ui::theme::PaletteId::Darkroom.palette();
1036 for (i, &a) in dr.SOURCE_TINTS.iter().enumerate() {
1037 for (j, &b) in dr.SOURCE_TINTS.iter().enumerate().skip(i + 1) {
1038 assert_ne!(a, b, "darkroom tints {i} and {j} collide");
1039 }
1040 }
1041}
1042
1043/// A `.srt` dropped on the window is nobody's stream: it has no source
1044/// entry, and the lookup that used to fall back to index 0 painted it with
1045/// the first file's colour -- a swatch saying it came out of a film it
1046/// never touched.
1047#[test]
1048fn a_standalone_subtitle_wears_no_file_tint() {
1049 let sources = [
1050 Source {
1051 path: PathBuf::from("/films/a.mkv"),
1052 audio_stream: 0,
1053 },
1054 Source {
1055 path: PathBuf::from("/films/b.mp4"),
1056 audio_stream: 0,
1057 },
1058 // A second stream of the first file is a second source and the
1059 // same colour.
1060 Source {
1061 path: PathBuf::from("/films/a.mkv"),
1062 audio_stream: 1,
1063 },
1064 ];
1065 assert_eq!(
1066 file_tint(&sources, Path::new("/films/a.mkv")),
1067 Some(source_tint(0))
1068 );
1069 assert_eq!(
1070 file_tint(&sources, Path::new("/films/b.mp4")),
1071 Some(source_tint(1))
1072 );
1073 assert_eq!(file_tint(&sources, Path::new("/subs/a.eng.srt")), None);
1074 assert_eq!(file_tint(&[], Path::new("/films/a.mkv")), None);
1075 // The same file under two spellings is one file and one colour: a
1076 // source is stored symlink-resolved, everything else as it was typed.
1077 let here = std::fs::canonicalize(".").expect("the crate directory");
1078 let sources = [Source {
1079 path: here.join("Cargo.toml"),
1080 audio_stream: 0,
1081 }];
1082 assert_eq!(
1083 file_tint(&sources, Path::new("Cargo.toml")),
1084 Some(source_tint(0)),
1085 "a relative spelling of the source file wears the source's colour"
1086 );
1087}
1088
1089/// A film's two ASS tracks with the timeline trimmed to twenty seconds:
1090/// one of them still has cues there and one has none, and the card said
1091/// nothing whatever about the second while the Subtitles list went on
1092/// showing it with its eighty-three cues.
1093///
1094/// And the 25 GB remux's thirty-five: naming those wrapped the row to ten
1095/// lines and pushed Destination under the fold, so past the value box's
1096/// three lines the same line counts instead.
1097#[test]
1098fn the_card_names_the_subtitle_it_leaves_off_and_counts_them_when_it_cannot() {
1099 let film = "/films/An Episode 01.mkv";
1100 let two = [
1101 sub(film, Some(1), "[ASS]"),
1102 sub(film, Some(2), "[ASS] [FOR DUB]"),
1103 ];
1104 // What the engine answers about the one pick that reached it, and what
1105 // this side knows about the row that did not.
1106 let named = subtitle_plan("[ASS] → embedded".to_string(), &two, &[0]);
1107 assert_eq!(named, "[ASS] → embedded; [ASS] [FOR DUB] — in the palette, on no track");
1108 assert!(
1109 named.chars().count() <= SUB_PLAN_CHARS,
1110 "two tracks fit the value box: {named}"
1111 );
1112 // Thirty-five off one file: twenty-two carry cues here, nine are
1113 // pictures, one could not be read, three have nothing on this timeline.
1114 let many: Vec<_> = (0..35)
1115 .map(|i| {
1116 let mut track = sub("/films/A Remux.mkv", Some(i), "eng — Subtitles");
1117 track.bitmap = (22..31).contains(&i);
1118 track.refused = (i == 31).then(|| "VobSub is pictures".to_string());
1119 track
1120 })
1121 .collect();
1122 // The picks are every track with a cue on the timeline: the twenty-two
1123 // and the nine picture ones, which the engine drops itself.
1124 let picks: Vec<usize> = (0..31usize).collect();
1125 let counted = subtitle_plan("22 tracks → embedded (…)".to_string(), &many, &picks);
1126 assert_eq!(
1127 counted,
1128 "22 of 35 → embedded; 9 pictures; 1 unread; 3 in the palette, on no track"
1129 );
1130 assert!(
1131 counted.chars().count() <= SUB_PLAN_CHARS,
1132 "thirty-five tracks still fit the value box: {counted}"
1133 );
1134 // Nothing on the timeline at all is still the engine's word for it.
1135 assert_eq!(subtitle_plan("none".to_string(), &[], &[]), "none");
1136 // The lanes are what an export writes once anything is placed on one, and
1137 // the engine words that whole ([`engine::export::planned_subtitles`]) --
1138 // including the lanes it carries *nothing* of, which is a sentence with no
1139 // pick behind it at all. That used to be dropped on the floor: the card said
1140 // "[ASS] — no cues here" twice and never said what became of the lane.
1141 let placed = "S1 [ASS] — past the last picture".to_string();
1142 assert_eq!(
1143 subtitle_plan(placed.clone(), &two, &[]),
1144 "S1 [ASS] — past the last picture; [ASS] [FOR DUB] — in the palette, on no track"
1145 );
1146 // ...and the row that sentence speaks for gets no clause of its own: a line
1147 // that names a lane's track and then calls the same track unplaced is the
1148 // card contradicting itself in one breath.
1149 assert!(!subtitle_plan(placed, &two[..1], &[]).contains("in the palette"));
1150}
1151
1152/// The list is in the order tracks were added, which is not the order a
1153/// person reads it in: importing a second film puts its tracks after the
1154/// first film's, and importing a third `.srt` for the first film puts that
1155/// one last of all. The rows still read as three sources.
1156#[test]
1157fn subtitle_rows_group_a_source_however_they_were_added() {
1158 let tracks = [
1159 sub("/films/a.mkv", Some(1), "eng"),
1160 sub("/films/b.mkv", Some(1), "eng"),
1161 sub("/films/a.mkv", Some(2), "fre"),
1162 sub("/subs/late.srt", None, "late.srt"),
1163 sub("/films/b.mkv", Some(3), "ger"),
1164 ];
1165 let groups = subtitle_rows(&tracks);
1166 assert_eq!(
1167 groups.iter().map(|g| g.name.as_str()).collect::<Vec<_>>(),
1168 ["a", "b", "late"],
1169 "one group per file, in the order the files first appear"
1170 );
1171 assert_eq!(
1172 groups
1173 .iter()
1174 .map(|g| g.rows.iter().map(|r| r.label.as_str()).collect::<Vec<_>>())
1175 .collect::<Vec<_>>(),
1176 [vec!["eng", "fre"], vec!["eng", "ger"], vec!["late.srt"]],
1177 "a file's tracks are contiguous and in add order"
1178 );
1179 // Numbered within the file, the way `row_name` numbers audio streams:
1180 // two tracks that both say "eng" are told apart by nothing else.
1181 assert_eq!(
1182 groups
1183 .iter()
1184 .map(|g| g.rows.iter().map(|r| r.number).collect::<Vec<_>>())
1185 .collect::<Vec<_>>(),
1186 [vec![1, 2], vec![1, 2], vec![1]]
1187 );
1188 // The swatch key is the file, so a group and that file's media rows
1189 // wear one colour -- and the standalone one has none.
1190 let sources = [Source {
1191 path: PathBuf::from("/films/a.mkv"),
1192 audio_stream: 0,
1193 }];
1194 assert_eq!(
1195 file_tint(&sources, &groups[0].path),
1196 Some(source_tint(0)),
1197 "the group carries the path the tint is asked by"
1198 );
1199 assert_eq!(file_tint(&sources, &groups[2].path), None);
1200 // What a header's "N tracks" says: the group's own row count, which is
1201 // 2, 2, 1 here -- a film that gave several tracks and a standalone
1202 // `.srt` that gave exactly one.
1203 assert_eq!(
1204 groups.iter().map(|g| g.rows.len()).collect::<Vec<_>>(),
1205 [2, 2, 1]
1206 );
1207 // A standalone `.srt` is already its own group, named after its own
1208 // file ("late", not lumped under some catch-all "External" bucket) --
1209 // there is no sourceless case for a header to special-case.
1210 assert_eq!(groups[2].name, "late");
1211 assert_eq!(groups[2].path, PathBuf::from("/subs/late.srt"));
1212}
1213
1214/// The fold a click on a header sets is keyed by [`SubGroup::path`]
1215/// (`Player::sub_folded`), so it has to survive the very thing regrouping
1216/// is for: a second track landing on a file already in the list, or one
1217/// being removed from it. The group's path is the fold's whole identity,
1218/// so it must not move under either.
1219#[test]
1220fn a_groups_fold_key_survives_a_track_arriving_or_leaving_its_file() {
1221 let before = [
1222 sub("/films/a.mkv", Some(1), "eng"),
1223 sub("/films/b.mkv", Some(1), "eng"),
1224 ];
1225 let after_add = [
1226 sub("/films/a.mkv", Some(1), "eng"),
1227 sub("/films/b.mkv", Some(1), "eng"),
1228 sub("/films/a.mkv", Some(2), "fre"),
1229 ];
1230 let (before_groups, after_groups) = (subtitle_rows(&before), subtitle_rows(&after_add));
1231 assert_eq!(before_groups[0].path, after_groups[0].path, "a's key held");
1232 assert_eq!(before_groups[1].path, after_groups[1].path, "b's key held");
1233 // The group a second track landed on grew; the other did not move.
1234 assert_eq!(after_groups[0].rows.len(), 2);
1235 assert_eq!(after_groups[1].rows.len(), 1);
1236 // Removing that same track back off leaves the original key and count.
1237 let after_remove = subtitle_rows(&before);
1238 assert_eq!(after_remove[0].path, before_groups[0].path);
1239 assert_eq!(after_remove[0].rows.len(), 1);
1240}
1241
1242/// What the strip header, the section heading and the toggle's notice all
1243/// say. Two films each carrying an "eng" track are one word apart until the
1244/// film is in the name; a film carrying two is one word apart from itself.
1245#[test]
1246fn the_picked_subtitle_is_named_with_the_film_it_came_out_of() {
1247 let tracks = [
1248 sub("/films/a.mkv", Some(1), "eng"),
1249 sub("/films/b.mkv", Some(1), "eng"),
1250 sub("/films/a.mkv", Some(2), "eng"),
1251 sub("/films/b.mkv", Some(2), "und"),
1252 sub("/subs/late.srt", None, "late.srt"),
1253 ];
1254 let name = |track| sub_pick_name(&tracks, track).expect("a track that is there");
1255 // The two "eng"s of two films: one file gave several so its tracks are
1256 // numbered, the other gave one so it is not.
1257 assert_eq!(name(0), "eng 1 — a");
1258 assert_eq!(name(2), "eng 2 — a");
1259 assert_eq!(name(1), "eng 1 — b");
1260 assert_ne!(name(0), name(1), "two films' eng tracks read apart");
1261 for picked in [name(0), name(1), name(2)] {
1262 assert!(picked.contains(" — a") || picked.contains(" — b"));
1263 }
1264 // "und" is the tag for "nobody said", humanised once by
1265 // `subtitle_rows` and not again here.
1266 assert_eq!(name(3), "unknown language 2 — b");
1267 // A standalone `.srt` is its own file and its label already says so:
1268 // one track, so no number, and no stem after it saying it again.
1269 assert_eq!(name(4), "late.srt");
1270 // The silence a row left over from a timeline that is gone gets.
1271 assert_eq!(sub_pick_name(&tracks, 5), None);
1272 assert_eq!(sub_pick_name(&[], 0), None);
1273}
1274
1275/// What the toggle covers is what is *placed*, so what it says is a lane fact:
1276/// naming the palette row the list happens to mark named a track the stroke
1277/// never touched ("SUBTITLES OFF — one.srt is still on the timeline" for a
1278/// one.srt nobody dragged anywhere).
1279#[test]
1280fn the_subtitles_toggle_says_what_is_placed_and_never_the_picked_row() {
1281 for on in [true, false] {
1282 let text = subtitle_toggle_notice(on, 2);
1283 assert!(text.contains('2'), "{text} counts the captions placed");
1284 assert!(
1285 !text.contains("track(s)") && !text.contains(" — a"),
1286 "{text} names no palette row"
1287 );
1288 }
1289 // Off leaves them on the lanes; that is the half a person needs told.
1290 assert!(subtitle_toggle_notice(false, 2).contains("still placed"));
1291 // An empty timeline says the move instead of a count that reads as broken.
1292 let none = subtitle_toggle_notice(true, 0);
1293 assert!(!none.contains('0'), "{none} counts nothing at nothing");
1294 assert!(none.contains("drag"), "{none} says the next move");
1295}
1296
1297/// The door this editor answers "don't make me import the film again" with,
1298/// and it is in the panel where the tracks it adds are listed: the Text
1299/// tab's own button reads a file's subtitle tracks onto the open timeline
1300/// -- a release's `.mkv`, an `.srt` beside it -- while the file itself
1301/// joins nothing. It is the *action* and not a second implementation of it,
1302/// so the button, the stroke and the actions card cannot drift apart, and
1303/// it is oracle-gated like every other action button, so with no timeline
1304/// open it dims and says why instead of opening a chooser for nothing.
1305#[test]
1306fn the_text_tab_carries_the_add_subtitles_door() {
1307 let library = src_text("ui/library.rs");
1308 let at = library
1309 .find("\"add-subtitles\"")
1310 .expect("no add-subtitles control in the library column");
1311 let block = &library[at..(at + 1600).min(library.len())];
1312 assert!(
1313 block.contains("ActionId::ImportSubtitles"),
1314 "the button is a door of its own rather than the action: {block}"
1315 );
1316 assert!(
1317 block.contains("pick_and_add_subtitles"),
1318 "the button does not open the subtitle chooser: {block}"
1319 );
1320 // `action_control` is the oracle-gated one: dimmed with the refusal in
1321 // the oracle's own words. `control` alone would be lit with no timeline.
1322 assert!(
1323 library[..at].ends_with("self.action_control(\n "),
1324 "the add-subtitles button is not oracle-gated"
1325 );
1326 // ...and the empty tab names that button, rather than pointing at a
1327 // toolbar the person is not looking at.
1328 assert!(
1329 crate::LibraryTab::Text.empty().contains("Add subtitles"),
1330 "{}",
1331 crate::LibraryTab::Text.empty()
1332 );
1333}
1334
1335/// A source's group header in the library must not vanish on a short
1336/// window: it is drawn whenever there is more than one source
1337/// (`several_files`), never gated on the viewport's height, and the list
1338/// under it is what scrolls instead ([`SUB_ROWS_H`]). And it has to be a
1339/// real fold, not the click-cycling pattern this codebase has already
1340/// thrown out once: one click toggles `sub_folded` shut or open, it never
1341/// steps through more than those two states.
1342#[test]
1343fn a_subtitle_group_header_is_never_gated_on_window_height() {
1344 let timeline = src_text("ui/timeline.rs");
1345 assert!(
1346 !timeline.contains("sub_headers_fit"),
1347 "the header is still gated on the viewport's height"
1348 );
1349 let at = timeline
1350 .find("let headed = ")
1351 .expect("no `headed` computed in subtitle_section");
1352 let line = &timeline[at..(at + 80).min(timeline.len())];
1353 assert!(
1354 line.contains("several_files") && !line.contains("viewport"),
1355 "headed depends on something other than the file count: {line}"
1356 );
1357 // The header is a click target that flips membership in a set --
1358 // `remove` else `insert` -- not a value stepped through several states.
1359 let head_at = timeline
1360 .find("subtitle-group-head")
1361 .expect("no id on the group header");
1362 let block = &timeline[head_at..(head_at + 2400).min(timeline.len())];
1363 assert!(block.contains("sub_folded.remove"), "no fold-open path: {block}");
1364 assert!(block.contains("sub_folded.insert"), "no fold-shut path: {block}");
1365 assert!(
1366 block.contains("\"1 track\"") || block.contains("tracks"),
1367 "the header does not say how many tracks it holds: {block}"
1368 );
1369}
1370
1371/// The one thing regrouping must not break: `sub_track` is a flat index
1372/// into the add-order list, a click sets it and a save writes it into the
1373/// `.edith`. Every row must still name the track it was made from -- rows
1374/// for refused tracks included, because they take a number in that list
1375/// whether or not anyone can pick them.
1376#[test]
1377fn a_subtitle_row_names_the_flat_track_it_was_made_from() {
1378 let mut tracks = vec![
1379 sub("/films/a.mkv", Some(1), "eng"),
1380 sub("/films/b.mkv", Some(1), "eng"),
1381 sub("/films/a.mkv", Some(2), "fre"),
1382 ];
1383 // Track 1 of b is pictures: still a row, still index 1 of the list.
1384 tracks[1].bitmap = true;
1385 tracks[1].refused = Some("PGS subtitles are pictures".to_string());
1386 let groups = subtitle_rows(&tracks);
1387 let flat: Vec<(usize, &str)> = groups
1388 .iter()
1389 .flat_map(|g| g.rows.iter().map(|r| (r.track, r.label.as_str())))
1390 .collect();
1391 assert_eq!(flat, [(0, "eng"), (2, "fre"), (1, "eng")]);
1392 for (track, label) in flat {
1393 assert_eq!(
1394 tracks[track].label, label,
1395 "row {track} picks the track it names"
1396 );
1397 }
1398 // (c) The refused one is here, saying why, and greyable by that alone.
1399 let refused = &groups[1].rows[0];
1400 assert_eq!(
1401 refused.refused.as_deref(),
1402 Some("PGS subtitles are pictures")
1403 );
1404 assert_eq!(refused.detail, "PGS subtitles are pictures");
1405 assert!(refused.bitmap);
1406 // ...and it was counted: the row after it in add order is still 2.
1407 assert_eq!(groups[0].rows[1].track, 2);
1408}
1409
1410/// The × on a row shifts every track after it down one, and the pick is
1411/// what an export writes into the file -- so a pick that stayed put would
1412/// silently change which track the next export carries. Every relation
1413/// between the pick and the row that went, on a list of three.
1414#[test]
1415fn removing_a_subtitle_row_carries_the_pick_with_it() {
1416 // A row *before* the pick: the same track stays picked, one index down.
1417 assert_eq!(sub_pick_after_removal(2, 0, 2), 1);
1418 assert_eq!(sub_pick_after_removal(2, 1, 2), 1);
1419 // A row *after* it: the pick has not moved and neither has its index.
1420 assert_eq!(sub_pick_after_removal(0, 2, 2), 0);
1421 assert_eq!(sub_pick_after_removal(1, 2, 2), 1);
1422 // The picked row itself: the one that slid into its place...
1423 assert_eq!(sub_pick_after_removal(1, 1, 2), 1);
1424 // ...and the last row when the picked one was the last, since there is
1425 // nothing after it to slide.
1426 assert_eq!(sub_pick_after_removal(2, 2, 2), 1);
1427 // The last row of all: an emptied list is legal for subtitles, and the
1428 // section is not drawn at all at that point.
1429 assert_eq!(sub_pick_after_removal(0, 0, 0), 0);
1430}
1431
1432/// The same claim from the click's end, on the order imports actually
1433/// arrive in: two films opened one after the other and an `.srt` dropped
1434/// last interleave in the flat list, and the display reorders them. What a
1435/// click sets is the row's own `track`, so the *n*th row on screen has to
1436/// pick the track it shows and the echoes have to name that same file.
1437#[test]
1438fn a_click_on_a_regrouped_row_picks_the_track_that_row_shows() {
1439 let tracks = [
1440 sub("/films/a.mkv", Some(1), "eng"),
1441 sub("/films/b.mkv", Some(1), "eng"),
1442 sub("/films/a.mkv", Some(2), "fre"),
1443 sub("/subs/late.srt", None, "late.srt"),
1444 sub("/films/b.mkv", Some(3), "ger"),
1445 ];
1446 let rows: Vec<_> = subtitle_rows(&tracks)
1447 .into_iter()
1448 .flat_map(|group| {
1449 group
1450 .rows
1451 .into_iter()
1452 .map(move |row| (group.path.clone(), row))
1453 })
1454 .collect();
1455 // Read top to bottom, the rows are no longer in add order...
1456 assert_eq!(
1457 rows.iter().map(|(_, row)| row.track).collect::<Vec<_>>(),
1458 [0, 2, 1, 4, 3]
1459 );
1460 for (path, row) in &rows {
1461 // ...and what the click writes into `sub_track` -- and a save into
1462 // the `.edith` -- still lands on the track the row is showing.
1463 let picked = &tracks[row.track];
1464 assert_eq!(&picked.path, path, "row {} picks another file", row.track);
1465 assert_eq!(lang_human(&picked.label), row.label);
1466 // And the heading, the strip and the notice name that same file
1467 // back, so a click cannot leave the echoes pointing elsewhere.
1468 let echo = sub_pick_name(&tracks, row.track).expect("the row's own track");
1469 let stem = path.file_stem().expect("a fixture path").to_string_lossy();
1470 assert!(
1471 echo.contains(&*stem),
1472 "picked {}, echoed {echo}",
1473 path.display()
1474 );
1475 }
1476}
1477
1478/// "und" is what a muxer writes when nobody said what the language is. A
1479/// row showing it verbatim names a language nobody speaks.
1480#[test]
1481fn an_untagged_language_says_it_is_unknown() {
1482 assert_eq!(lang_human("und"), "unknown language");
1483 assert_eq!(lang_human("eng"), "eng");
1484 assert_eq!(lang_human("fre — Commentary"), "fre — Commentary");
1485 // Reaching the subtitle rows too: a track whose only name was the tag.
1486 let groups = subtitle_rows(&[sub("/films/a.mkv", Some(1), "und")]);
1487 assert_eq!(groups[0].rows[0].label, "unknown language");
1488 // The pair, read as the pair: the row title comes off `language` and
1489 // `name` and never out of the flattened label, which is what let an
1490 // "und" beside a title through as a language nobody speaks. A refused
1491 // track states neither and keeps its label.
1492 let titled = |language: &str, name: &str, label: &str| engine::subtitle::SubtitleTrack {
1493 path: PathBuf::from("/films/a.mkv"),
1494 track: Some(1),
1495 language: language.into(),
1496 name: name.into(),
1497 label: label.into(),
1498 cues: Vec::new(),
1499 bitmap: false,
1500 refused: None,
1501 };
1502 for (language, name, label, title) in [
1503 ("fra", "Signs", "fra — Signs", "fra — Signs"),
1504 ("und", "Signs", "Signs", "Signs"),
1505 ("und", "", "und", "unknown language"),
1506 ("", "late.srt", "late.srt", "late.srt"),
1507 ("", "", "eng", "eng"),
1508 ] {
1509 let rows = subtitle_rows(&[titled(language, name, label)]);
1510 assert_eq!(rows[0].rows[0].label, title, "{language:?} {name:?}");
1511 }
1512}
1513
1514/// The bug: an empty timeline is end-of-stream from its one black frame
1515/// onward, so the pump had `done` set before anything was ever pressed --
1516/// and the transport's restart branch read that as "played out, start from
1517/// the top". It started a clock against a zero-length timeline, which was
1518/// `done` again by the next repaint, so every further press restarted it
1519/// too: the button read "Pause" and no press of it ever paused.
1520///
1521/// What holds it now is one predicate, checked here against real sessions
1522/// on both sides -- the emptied one refuses, a timeline with clips on it
1523/// does not.
1524#[test]
1525fn an_empty_timeline_has_nothing_to_play() {
1526 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1527 // Silent like the engine suite: this opens the real device.
1528 session.set_gain(0.0);
1529 // A timeline with clips on it plays, and always did: the guard must not
1530 // touch that side.
1531 assert!(!session.is_empty());
1532 assert!(!nothing_to_play(Some(&session)));
1533
1534 // Every clip taken off, which is a state and not a failure.
1535 while session.delete_clip(Lane::V1, 0) {}
1536 while session.delete_clip(Lane::A1, 0) {}
1537 assert!(session.is_empty(), "the timeline is empty");
1538 assert_eq!(session.timeline_duration(), 0.0);
1539
1540 // What the pump does every render, and what set `done` before the fix:
1541 // the black frame goes by and the session is at its end at once.
1542 for _ in 0..40 {
1543 while session.try_frame().is_some() {}
1544 std::thread::sleep(Duration::from_millis(10));
1545 }
1546 assert!(
1547 session.is_eos(),
1548 "an empty timeline is done before it starts"
1549 );
1550
1551 // So the press is refused rather than sent down the restart branch --
1552 // and with no session at all it is the same refusal.
1553 assert!(nothing_to_play(Some(&session)));
1554 assert!(nothing_to_play(None));
1555 assert!(!session.is_playing(), "and nothing was started");
1556}
1557
1558/// The slider writes the same numbers the keys do, and mute is not one of
1559/// them: dragging while muted picks the level unmuting comes back to.
1560#[test]
1561fn the_slider_lands_on_the_grid_the_keys_move_on() {
1562 let mut volume = Volume::default();
1563 // Both ends exactly, and clamped past them.
1564 volume.set_along(0.);
1565 assert_eq!(volume.gain(), 0.0);
1566 assert_eq!(volume.label(), "Vol 0%");
1567 volume.set_along(1.5);
1568 assert_eq!(volume.gain(), 1.0);
1569 assert_eq!(volume.along(), 1.0);
1570
1571 // Halfway is 50%, and a key press from there is 5% -- the same step
1572 // count as before, on a finer grid.
1573 volume.set_along(0.5);
1574 assert_eq!(volume.label(), "Vol 50%");
1575 volume.step(true);
1576 assert_eq!(volume.label(), "Vol 55%");
1577 volume.step(false);
1578 assert_eq!(volume.gain(), 0.5);
1579
1580 // A number no step lands on comes back as the nearest one, so the label
1581 // and the fill are the same value the device was handed.
1582 volume.set_along(0.333);
1583 assert_eq!(volume.label(), "Vol 33%");
1584 assert_eq!(volume.along(), 0.33);
1585
1586 // Muted, the drag moves the level and nothing comes out.
1587 volume.muted = true;
1588 volume.set_along(0.8);
1589 assert_eq!(volume.gain(), 0.0);
1590 assert_eq!(volume.label(), "Muted 80%");
1591 volume.muted = false;
1592 assert_eq!(volume.gain(), 0.8);
1593}
1594
1595/// The slider lands where it paints: the arithmetic `Player::drag_volume`
1596/// runs over the bar's own painted width, which is the one thing a test of
1597/// it can share without re-deriving it.
1598#[test]
1599fn the_volume_slider_lands_where_it_paints() {
1600 let bar = Bounds {
1601 origin: point(px(420.), px(508.)),
1602 size: size(px(VOLUME_W), px(CONTROL_H)),
1603 };
1604 let at = |x: f32| {
1605 let mut volume = Volume::default();
1606 volume.set_along(frac_along(px(x), bar));
1607 volume
1608 };
1609 assert_eq!(at(420.).gain(), 0.0, "the left end is silence");
1610 assert_eq!(at(420. + VOLUME_W).gain(), 1.0, "the right end is full");
1611 assert_eq!(at(-4000.).gain(), 0.0, "off the left clamps");
1612 assert_eq!(at(9999.).gain(), 1.0, "off the right clamps");
1613 // Every pixel along it: a level the keys could also reach, painted back
1614 // where the hand pressed to within the half step the rounding costs.
1615 for step in 0..=(VOLUME_W as u32) {
1616 let along = step as f32 / VOLUME_W;
1617 let volume = at(420. + along * VOLUME_W);
1618 let painted = volume.along();
1619 let slack = 0.5 / f32::from(Volume::MAX_STEPS) + 1e-4;
1620 assert!(
1621 (painted - along).abs() <= slack,
1622 "pressed at {along}, paints at {painted}"
1623 );
1624 }
1625}
1626
1627/// The three seams a hand may move, and the two ends neither of them may be
1628/// dragged past: a panel dragged to nothing is a panel nobody can get back, and
1629/// a picture squeezed out by its two neighbours is that same loss from the
1630/// other side of the window.
1631#[test]
1632fn a_dragged_divider_stops_before_either_panel_disappears() {
1633 use crate::ui::theme::INSPECTOR_MIN_W;
1634 use crate::{
1635 SIDE_MAX_FRAC, SPLIT_W, Split, TIMELINE_MAX_SHARE, TOOLBAR_H, inspector_w, library_w,
1636 split_drag_size, split_size, timeline_fixed_h, timeline_h,
1637 };
1638 use gpui::{point, px, size};
1639
1640 let window = size(px(1280.), px(720.));
1641 // Untouched, every region is still the share the window gives it. The
1642 // timeline's answer is stated for both of its faces: the timeline fits
1643 // the bed with nothing to scroll to, and zoomed in past that line the
1644 // strip's row joins the furniture.
1645 assert_eq!(split_size(Split::Library, None, 2, window, false), library_w(1280.));
1646 assert_eq!(
1647 split_size(Split::Inspector, None, 2, window, false),
1648 inspector_w(1280.)
1649 );
1650 assert_eq!(
1651 split_size(Split::Timeline, None, 2, window, false),
1652 timeline_h(2, false).min(720. * TIMELINE_SHARE)
1653 );
1654 assert_eq!(
1655 split_size(Split::Timeline, None, 2, window, true),
1656 timeline_h(2, true).min(720. * TIMELINE_SHARE)
1657 );
1658 // Dragged, it is what the hand asked for...
1659 assert_eq!(split_size(Split::Library, Some(300.), 2, window, false), 300.);
1660 assert_eq!(split_size(Split::Timeline, Some(300.), 2, window, false), 300.);
1661 // ...and never past either end of it.
1662 assert_eq!(
1663 split_size(Split::Library, Some(0.), 2, window, false),
1664 LIBRARY_MIN_W
1665 );
1666 assert_eq!(
1667 split_size(Split::Library, Some(9000.), 2, window, false),
1668 1280. * SIDE_MAX_FRAC
1669 );
1670 assert_eq!(
1671 split_size(Split::Inspector, Some(-40.), 2, window, false),
1672 INSPECTOR_MIN_W
1673 );
1674 // The timeline's own floor is a floor with a whole lane *drawn* in it. At
1675 // that height the column shows one row of a two-track project, so the line
1676 // saying the rest are below is drawn too -- out of the region's pixels,
1677 // not out of the lane's. Left unbudgeted the header came out 27 px of its
1678 // 48 and the track's name, its subtitle dot and its × were cut in half.
1679 // Stated for the strip-bearing face, the taller of the two -- that is the
1680 // one the clamp has to hold at the 640x360 floor.
1681 let floor = split_size(Split::Timeline, Some(0.), 2, window, true);
1682 assert_eq!(floor, timeline_fixed_h(true) + LANE_H + LABEL_H + 8.);
1683 // The same arithmetic the timeline lays the column out with
1684 // ([`Player::timeline`]): what the affordance costs comes off the box, and
1685 // a whole lane is still standing under it.
1686 let lanes_box = floor - timeline_fixed_h(true);
1687 assert!(
1688 2 > lanes_shown_mixed(&[LaneKind::Video, LaneKind::Audio], lanes_box),
1689 "no line to pay for at the floor"
1690 );
1691 assert!(
1692 lanes_box - LABEL_H - 8. >= LANE_H,
1693 "the floor leaves {} px for a {LANE_H} px lane",
1694 lanes_box - LABEL_H - 8.
1695 );
1696 // A lone track has nothing below it and pays nothing for the line -- the
1697 // floor is a floor, not a reserved corridor.
1698 assert_eq!(
1699 split_size(Split::Timeline, Some(0.), 1, window, true),
1700 timeline_fixed_h(true) + LANE_H
1701 );
1702 // A size dragged with one track and kept while a second arrives is raised
1703 // to the new floor as it is read, not silently drawn under it.
1704 assert_eq!(split_size(Split::Timeline, Some(126.), 2, window, true), floor);
1705 // And the floor still fits the share the shortest window gives the region.
1706 assert!(floor <= 360. * TIMELINE_SHARE, "{floor} px will not fit");
1707 assert_eq!(
1708 split_size(Split::Timeline, Some(9000.), 2, window, true),
1709 720. * TIMELINE_MAX_SHARE
1710 );
1711 // A window too narrow to honour both ends keeps the floor rather than
1712 // panicking inside `clamp`, which is what a ceiling under its own floor
1713 // does.
1714 let narrow = size(px(600.), px(360.));
1715 assert_eq!(
1716 split_size(Split::Inspector, Some(9000.), 2, narrow, false),
1717 INSPECTOR_MIN_W
1718 );
1719
1720 // The pointer turned into a size: the panel follows the hand, and the two
1721 // that do not start at the window's own edge are measured from the far one.
1722 // Half a strip off each, because the strip is grabbed by its middle.
1723 assert_eq!(
1724 split_drag_size(Split::Library, point(px(300.), px(400.)), window),
1725 300. - SPLIT_W / 2.
1726 );
1727 assert_eq!(
1728 split_drag_size(Split::Inspector, point(px(1000.), px(400.)), window),
1729 280. - SPLIT_W / 2.
1730 );
1731 // The seam sits above the fixed toolbar, so what the pointer leaves under
1732 // it is that strip and the timeline together.
1733 assert_eq!(
1734 split_drag_size(Split::Timeline, point(px(300.), px(500.)), window),
1735 220. - TOOLBAR_H - SPLIT_W / 2.
1736 );
1737}
1738
1739/// The darkroom's own two seams (`Split::Dock`, `Split::Bench`): a hand may
1740/// not drag either past its floor or its ceiling, the same promise
1741/// [`a_dragged_divider_stops_before_either_panel_disappears`] makes for the
1742/// legacy three.
1743#[test]
1744fn the_darkroom_seams_stop_before_either_side_disappears() {
1745 use crate::ui::theme::INSPECTOR_MIN_W;
1746 use crate::{BENCH_MIN_H, SIDE_MAX_FRAC, SPLIT_W, Split, split_bounds, split_drag_size, split_size};
1747 use gpui::{point, px, size};
1748
1749 let window = size(px(1280.), px(720.));
1750 // Untouched, each answers its own stance default.
1751 assert_eq!(
1752 split_size(Split::Dock, None, 2, window, false),
1753 crate::ui::stance::DOCK_W
1754 );
1755 assert_eq!(
1756 split_size(Split::Bench, None, 2, window, false),
1757 crate::ui::stance::BENCH_H
1758 );
1759 // Dragged, it is what the hand asked for...
1760 assert_eq!(split_size(Split::Dock, Some(400.), 2, window, false), 400.);
1761 assert_eq!(split_size(Split::Bench, Some(300.), 2, window, false), 300.);
1762 // ...and never past the floor...
1763 assert_eq!(
1764 split_size(Split::Dock, Some(0.), 2, window, false),
1765 INSPECTOR_MIN_W
1766 );
1767 assert_eq!(
1768 split_size(Split::Bench, Some(0.), 2, window, false),
1769 BENCH_MIN_H
1770 );
1771 // ...nor the ceiling. The bench's is not a window-share one -- it leaves
1772 // the screen and time band a fixed 160px, [`split_bounds`]'s own reason.
1773 assert_eq!(
1774 split_size(Split::Dock, Some(9000.), 2, window, false),
1775 1280. * SIDE_MAX_FRAC
1776 );
1777 let (_, bench_max) = split_bounds(Split::Bench, 2, window, false);
1778 assert_eq!(
1779 split_size(Split::Bench, Some(9000.), 2, window, false),
1780 bench_max
1781 );
1782 assert!(bench_max < 720.);
1783 // The pointer turned into a size, half a strip off for the same reason
1784 // the legacy seams read it that way.
1785 assert_eq!(
1786 split_drag_size(Split::Dock, point(px(1000.), px(400.)), window),
1787 280. - SPLIT_W / 2.
1788 );
1789 assert_eq!(
1790 split_drag_size(Split::Bench, point(px(300.), px(500.)), window),
1791 220. - crate::ui::stance::LEDGER_H - SPLIT_W / 2.
1792 );
1793}
1794
1795/// At the bench's floor, both default lanes' rows actually fit inside the
1796/// `bench-lanes` column `bench_stance::render` gives them -- not just each
1797/// row's own clamped height, but their *sum plus the gap between them*,
1798/// since `bench-lanes` scrolls rather than clipping visibly and a sum that
1799/// overruns the column loses its bottom row's pixels off-screen, unscrolled
1800/// (this session's F1: the A1 lane's clip-bar border and status dot, cut by
1801/// ~2px at the old `BENCH_MIN_H = 80.`).
1802#[test]
1803fn both_default_lanes_fit_the_bench_at_its_floor() {
1804 use crate::BENCH_MIN_H;
1805 use crate::ui::bench_stance::{LANE_MIN_H, ROW_GAP, RULER_H, row_h};
1806 use crate::ui::stance::BENCH_CHROME_H;
1807
1808 let box_h = BENCH_MIN_H - BENCH_CHROME_H;
1809 let avail = box_h - RULER_H - ROW_GAP;
1810 let h = row_h(2, avail);
1811 // Not an exact `LANE_MIN_H` any more: `BENCH_MIN_H` now carries one spare
1812 // row (`layout::LEDGER_SEAM_CLEARANCE`) so the last lane's own last pixel
1813 // never shares a row with the ledger's border, which lands here as
1814 // `avail` being a touch over the two-rows-plus-gap tight fit.
1815 assert!(h >= LANE_MIN_H, "the floor should give both lanes at least their own minimum ({h} < {LANE_MIN_H})");
1816 let content = 2. * h + ROW_GAP;
1817 assert!(
1818 content <= avail + 1e-4,
1819 "the two lane rows ({content}px) overrun the column ({avail}px) -- \
1820 the bottom lane's pixels get cut, unscrolled"
1821 );
1822}
1823
1824/// `BENCH_CHROME_H` on its own: the previous test's `box_h = BENCH_MIN_H -
1825/// BENCH_CHROME_H` line trusts `BENCH_CHROME_H` to already be correct, so it
1826/// cannot catch `BENCH_CHROME_H` itself drifting -- which is exactly how the
1827/// third clip (this session's) survived it: the constant undercounted the
1828/// section head's real line box by 1px and this test's predecessor never
1829/// looked. Recomputes what `ui::stance::bench` actually draws above
1830/// `bench_stance::render`'s content -- the div's own `.border_t_1()` (1px)
1831/// + its `py(4.)` top padding + the section head's real line box at gpui's
1832/// golden-ratio line-height, not the label's bare font size (the same trap
1833/// `a_lane_row_fits_what_its_own_head_draws` already checks for the lane
1834/// heads) -- and then checks the *whole* stack -- chrome, ruler, both gaps,
1835/// both lanes, and the clear row the ledger's own fixed-position border
1836/// needs (`LEDGER_SEAM_CLEARANCE`, not exported, so this recomputes it as
1837/// `BENCH_MIN_H` minus every other named term) -- fits inside `BENCH_MIN_H`
1838/// with nothing left over uncounted. This binary carries no `TestAppContext`
1839/// to mount `ui::stance::bench` and `ui::stance::ledger` for real and read
1840/// painted bounds back, so it stays geometry-only, same as its neighbours.
1841#[test]
1842fn the_whole_bench_stack_fits_its_own_floor_with_the_ledger_seam_clear() {
1843 use crate::BENCH_MIN_H;
1844 use crate::ui::bench_stance::{LANE_MIN_H, ROW_GAP, RULER_H};
1845 use crate::ui::stance::BENCH_CHROME_H;
1846 use crate::ui::type_scale::SECTION_HEAD_PX;
1847
1848 const BENCH_BORDER_T: f32 = 1.;
1849 const BENCH_PY_TOP: f32 = 4.;
1850 let section_head_line_h = (SECTION_HEAD_PX * 1.618_034).round();
1851 let real_chrome = BENCH_BORDER_T + BENCH_PY_TOP + section_head_line_h;
1852 assert_eq!(
1853 BENCH_CHROME_H, real_chrome,
1854 "BENCH_CHROME_H ({BENCH_CHROME_H}) does not match what `stance::bench` \
1855 actually draws above the content ({real_chrome}px: {BENCH_BORDER_T}px \
1856 border + {BENCH_PY_TOP}px padding + {section_head_line_h}px label line \
1857 box) -- bench_stance::render gets handed the wrong box_h and lays its \
1858 rows out past its own real space"
1859 );
1860
1861 // The ledger's own fixed-position border needs one more clear row below
1862 // the last lane, on top of chrome + ruler + both gaps + both lanes --
1863 // recomputed here rather than importing the private
1864 // `layout::LEDGER_SEAM_CLEARANCE`, so this test fails if that term is
1865 // ever silently dropped from `BENCH_MIN_H`'s own sum.
1866 let content_need = real_chrome + RULER_H + ROW_GAP + 2. * LANE_MIN_H + ROW_GAP;
1867 let ledger_seam_clearance = BENCH_MIN_H - content_need;
1868 assert!(
1869 ledger_seam_clearance >= 1. - 1e-4,
1870 "BENCH_MIN_H ({BENCH_MIN_H}) leaves only {ledger_seam_clearance}px \
1871 between the last lane row and the ledger's own top border -- driven \
1872 at exactly the content's need (0px clearance) the border still won \
1873 the shared pixel and clipped the last lane's status dot"
1874 );
1875}
1876
1877/// The previous test asserted lane ROWS fit the bench column -- not that a
1878/// lane's own CONTENT fits its row, which is how the defect it fixed
1879/// survived it: at the old `LANE_MIN_H` of `18.` both lanes fit the bench
1880/// exactly while V1's status dot silently overflowed into A1's row (masked)
1881/// and A1's overflowed into the ledger (visible, since A1 has no next row).
1882/// This binary carries no `TestAppContext` to mount a real `lane_row` and
1883/// read its painted bounds back, so this recomputes the label's own line
1884/// box from the constants `lane_row` actually draws with (gpui's default
1885/// `TextStyle::line_height` is the golden ratio, not 1x the font size --
1886/// see `LANE_MIN_H`'s own doc comment) rather than a literal, so a future
1887/// shrink of `LANE_MIN_H` or growth of the label size fails this instead of
1888/// silently clipping the last lane again.
1889#[test]
1890fn a_lane_row_fits_what_its_own_head_draws() {
1891 use crate::ui::bench_stance::{LANE_DOT_D, LANE_HEAD_GAP, LANE_MIN_H};
1892 use crate::ui::type_scale::CHORD_METADATA_MIN_PX;
1893
1894 let label_line_h = (CHORD_METADATA_MIN_PX * 1.618_034).round();
1895 let content = label_line_h + LANE_HEAD_GAP + LANE_DOT_D;
1896 assert!(
1897 LANE_MIN_H >= content,
1898 "LANE_MIN_H ({LANE_MIN_H}) is shorter than what a lane head actually \
1899 draws ({content}px: {label_line_h}px label line box + \
1900 {LANE_HEAD_GAP}px gap + {LANE_DOT_D}px dot) -- the status dot \
1901 would spill past the row, invisible until it is the last lane \
1902 with no next row to spill into"
1903 );
1904}
1905
1906/// The notice plate's own anchor ([`crate::ui::stance::notice_bottom_offset`])
1907/// keeps it off the bench, at *any* bench height -- not merely the floor --
1908/// because its bottom offset always lands at or above the bench's own top
1909/// edge. `Player`'s live tree has no `TestAppContext` in this binary to mount
1910/// a real `notice_plate` in and read its painted bounds back, so this checks
1911/// the pure geometry the anchor is built from instead (F2: previously the
1912/// plate sat at a fixed `LEDGER_H + 6.` off the ledger and covered the
1913/// V1/A1 lane chips whenever the bench was short enough for the plate's own
1914/// height to reach past it).
1915#[test]
1916fn the_notice_plate_cannot_reach_the_bench_at_any_height() {
1917 use crate::BENCH_MIN_H;
1918 use crate::ui::stance::{BENCH_H, LEDGER_H, notice_bottom_offset};
1919
1920 for bench_h in [BENCH_MIN_H, BENCH_H, 400.] {
1921 let notice_bottom = notice_bottom_offset(bench_h);
1922 // The bench sits directly above the ledger in the centre column, so
1923 // its own top edge (measured the same way, from the column's foot)
1924 // is exactly `LEDGER_H + bench_h`.
1925 let bench_top = LEDGER_H + bench_h;
1926 assert!(
1927 notice_bottom >= bench_top,
1928 "notice bottom {notice_bottom} sits below the bench's top {bench_top} \
1929 at bench_h={bench_h} -- the plate can cover a lane row"
1930 );
1931 }
1932}
1933
1934/// A round trip through the file: what is saved is what the next load reads
1935/// back, one seam touched and the other left at its default -- a scratch
1936/// path, not the real config, the same isolation `keymap::tests`' own
1937/// `load_from`/`save_to` already takes.
1938#[test]
1939fn a_saved_seam_survives_a_reload() {
1940 use crate::{Split, Splits, load_stance_splits_from, save_stance_splits_to};
1941
1942 let dir = engine::scratch::Scratch::dir("edith-stance-splits");
1943 let path = dir.join("stance-splits");
1944
1945 let mut splits = Splits::default();
1946 splits.set(Split::Dock, 333.);
1947 save_stance_splits_to(&splits, &path);
1948 let loaded = load_stance_splits_from(&path);
1949 assert_eq!(loaded.get(Split::Dock), Some(333.));
1950 assert_eq!(loaded.get(Split::Bench), None);
1951}
1952
1953/// The guard [`crate::split_drag_owes_save`] runs at the moment a drag ends
1954/// with no further pointer event ever coming (`Player::drag_left_window`,
1955/// wired to a live `MouseExitEvent` a `TestAppContext`-less test binary
1956/// cannot raise -- see `tests/media.rs`'s own note on the same limit, and
1957/// the harness drive `D2` in this session's report for the wiring itself).
1958/// What *is* checkable here without a window: exactly the two persisted
1959/// seams owe that save, the same set `Split::PERSISTED` already names, and a
1960/// drag that never started (`None`) owes nothing.
1961#[test]
1962fn only_the_two_persisted_seams_owe_a_save_when_a_drag_loses_the_window() {
1963 use crate::{Split, player::timeline_edit::split_drag_owes_save};
1964
1965 assert!(split_drag_owes_save(Some(Split::Dock)));
1966 assert!(split_drag_owes_save(Some(Split::Bench)));
1967 assert!(!split_drag_owes_save(Some(Split::Library)));
1968 assert!(!split_drag_owes_save(Some(Split::Inspector)));
1969 assert!(!split_drag_owes_save(Some(Split::Timeline)));
1970 assert!(!split_drag_owes_save(None));
1971}
1972
1973/// A missing file leaves every region at its default -- the silent fallback
1974/// `load_stance_splits`'s doc comment promises.
1975#[test]
1976fn a_missing_stance_splits_file_leaves_every_region_at_its_default() {
1977 use crate::{Split, load_stance_splits_from};
1978
1979 let dir = engine::scratch::Scratch::dir("edith-stance-splits-missing");
1980 let splits = load_stance_splits_from(&dir.join("nothing-here"));
1981 assert_eq!(splits.get(Split::Dock), None);
1982 assert_eq!(splits.get(Split::Bench), None);
1983}
1984
1985/// Every seam in the main layout has a handle on it, and every region draws
1986/// itself at the size that handle sets: a region still measuring itself off the
1987/// window's own share is a panel whose divider moves nothing.
1988#[test]
1989fn every_seam_in_the_layout_has_a_divider_on_it() {
1990 let render = src_text("render.rs");
1991 for split in ["Split::Library", "Split::Inspector", "Split::Timeline"] {
1992 assert!(
1993 render.contains(&format!("divider({split}")),
1994 "{split} has no divider to drag"
1995 );
1996 }
1997 let stance = src_text("ui/stance.rs");
1998 for split in ["Split::Dock", "Split::Bench"] {
1999 assert!(
2000 stance.contains(&format!("divider({split}")),
2001 "{split} has no divider to drag"
2002 );
2003 }
2004 // The strip is drawn wide enough to hit and says which way it moves --
2005 // an invisible hairline is a feature nobody finds.
2006 let interact = src_text("interact.rs");
2007 assert!(
2008 interact.contains("cursor_col_resize") && interact.contains("cursor_row_resize"),
2009 "a divider with no resize cursor on it"
2010 );
2011 // ...and nothing lays a region out off the untouched share any more.
2012 for (file, stale) in [
2013 ("ui/inspector.rs", "inspector_w("),
2014 ("ui/toolbar.rs", "library_w("),
2015 ("render.rs", "library_w("),
2016 ] {
2017 assert!(
2018 !src_text(file).contains(stale),
2019 "{file} still measures a panel with {stale}"
2020 );
2021 }
2022}
2023
2024/// DESIGN.md §12 step 2: the stance skeleton draws its six regions -- spine,
2025/// screen, time band, bench, ledger, dock -- in the order §5's diagram lays
2026/// them out, and `Player::render` actually reaches it when the flag is on.
2027#[test]
2028fn the_stance_renders_its_six_regions_in_the_documented_order() {
2029 let stance = src_text("ui/stance.rs");
2030 let order = [
2031 "stance-spine",
2032 "stance-screen",
2033 "stance-time-band",
2034 "stance-bench",
2035 "stance-ledger",
2036 "stance-dock",
2037 ];
2038 let defined: Vec<usize> = order
2039 .iter()
2040 .map(|id| {
2041 stance
2042 .find(&format!("\"{id}\""))
2043 .unwrap_or_else(|| panic!("no {id} region in the stance"))
2044 })
2045 .collect();
2046 assert!(
2047 defined.windows(2).all(|w| w[0] < w[1]),
2048 "the six regions are not defined in DESIGN §5's order: {defined:?}"
2049 );
2050
2051 // Defined in order is not composed in order -- `render()` has to call
2052 // them in it too, or the geometry above is dead prose.
2053 let render_body =
2054 &stance[stance.find("pub(crate) fn render(").expect("the stance's entry point")..];
2055 // Open paren only, no close: DESIGN §12 steps 3 and 4 hand most of the
2056 // regions player/window state to read, so their call sites carry
2057 // arguments now. Order is what this asserts, not arity.
2058 let calls = ["spine(", "screen(", "time_band(", "bench(", "ledger(", "dock("];
2059 let composed: Vec<usize> = calls
2060 .iter()
2061 .map(|c| {
2062 render_body
2063 .find(c)
2064 .unwrap_or_else(|| panic!("render() never calls {c}"))
2065 })
2066 .collect();
2067 assert!(
2068 composed.windows(2).all(|w| w[0] < w[1]),
2069 "render() does not compose the six regions in DESIGN §5's order: {composed:?}"
2070 );
2071
2072 // The flag has to reach it, or the skeleton is dead code behind a door
2073 // nobody opens. Darkroom is the default room now (`OLD_GUI=1` is the
2074 // opt-out) -- `Player::darkroom` is still the field render.rs reads.
2075 let render_rs = src_text("render.rs");
2076 assert!(
2077 render_rs.contains("if self.darkroom") && render_rs.contains("ui::stance::render("),
2078 "Player::darkroom never reaches ui::stance::render"
2079 );
2080}
2081
2082/// The picture is letterboxed, never stretched: both the picture region and
2083/// the subtitle picture overlay paint through [`letterboxed_image`] (the
2084/// `canvas()` element that hands `ObjectFit::Contain::get_bounds` a real
2085/// resolved size) rather than a plain `img().object_fit(...)`, which reads
2086/// right by hand but never gets a fitted box from taffy in this pin -- see
2087/// `render.rs`'s own doc comment on the function for the measured dead end.
2088/// A regression back to `img(...).object_fit(` in either caller is the
2089/// stretch-to-fill bug returning silently.
2090#[test]
2091fn the_picture_letterboxes_through_a_canvas_never_a_plain_img_object_fit() {
2092 let render_rs = src_text("render.rs");
2093 assert!(
2094 render_rs.contains("pub(crate) fn letterboxed_image"),
2095 "the letterbox helper moved or was renamed"
2096 );
2097 assert!(
2098 render_rs.contains("ObjectFit::Contain.get_bounds(bounds, image.size(0))"),
2099 "letterboxed_image no longer computes the Contain rect by hand"
2100 );
2101 for (file, needle) in [
2102 ("render.rs", "letterboxed_image(i)"),
2103 ("ui/preview.rs", "letterboxed_image(image)"),
2104 ] {
2105 let text = src_text(file);
2106 assert!(
2107 text.contains(needle),
2108 "{file} no longer paints through letterboxed_image"
2109 );
2110 assert!(
2111 !text.contains(".object_fit(gpui::ObjectFit::Contain)"),
2112 "{file} reintroduced the stretched img().object_fit(Contain) dead end"
2113 );
2114 }
2115}
2116
2117/// DESIGN §8: "No full-width bars, no covering the picture, ever." The
2118/// darkroom stance (`ui::stance::screen`) draws
2119/// [`Player::picture_area`](crate::Player::picture_area) directly, so a
2120/// notice surface that reaches into that method unconditionally reaches the
2121/// picture on the darkroom path too -- measured live covering the bottom 10%
2122/// of the frame (rows 300-333 of 335) *underneath* the stance's own
2123/// §8-conformant plate (`ui::stance::notice_plate`), which drew the same
2124/// notice a second time above the ledger. The legacy (non-darkroom) room
2125/// keeps its full-width `notice_bar` exactly as it always has -- this only
2126/// pins the darkroom path off it.
2127#[test]
2128fn the_darkroom_path_never_lets_a_notice_surface_reach_the_picture() {
2129 let body = fn_body("picture_area");
2130 assert!(
2131 body.contains("self.notice_bar(cx)"),
2132 "picture_area no longer draws notice_bar at all; re-check the darkroom gate still applies"
2133 );
2134 let at = body.find("self.notice_bar(cx)").expect("checked above");
2135 // Whatever gates the call, it has to name `darkroom` and it has to be
2136 // upstream of the call itself -- a gate written after the call, or one
2137 // that never mentions the flag, is not a gate on this method.
2138 let before = &body[..at];
2139 assert!(
2140 before.contains("self.darkroom") || before.contains("!self.darkroom"),
2141 "notice_bar in picture_area is not gated on self.darkroom any more -- \
2142 the darkroom stance would paint it over the picture again"
2143 );
2144}
2145
2146/// DESIGN §5/§11 check 6, the fourth occlusion defect (notice bar, export
2147/// card, preview badge, now menus): every floating menu that can open above
2148/// the picture -- the clip context menu, the picker, the library menu -- must
2149/// size its scrolling list against `stance::menu_floor`'s room, not the raw
2150/// window. Sizing against the whole viewport is exactly the bug that shipped:
2151/// a menu taller than the bench/ledger/dock footprint got clamped by
2152/// `menu_at`'s own bottom-edge fit back up over the picture, because nothing
2153/// had told the list it only had the footprint to grow into. This pins the
2154/// general rule so the next surface someone floats -- a fourth menu, a fifth
2155/// occlusion -- cannot silently reintroduce `menu_rows_h(rows.len(),
2156/// viewport)` in its place.
2157#[test]
2158fn every_darkroom_menu_sizes_its_list_against_the_floor_room_not_the_raw_viewport() {
2159 for file in ["ui/overlays.rs", "ui/library.rs"] {
2160 let text = src_text(file);
2161 assert!(
2162 !text.contains("menu_rows_h(rows.len(), viewport)"),
2163 "{file} sizes a menu's list against the raw viewport again -- \
2164 route it through stance::menu_floor's room instead, or a tall \
2165 menu will climb back over the picture"
2166 );
2167 let floors = text.matches("menu_floor(").count();
2168 let sizings = text.matches("menu_rows_h(rows.len(),").count();
2169 assert_eq!(
2170 floors, sizings,
2171 "{file} has a menu list-sizing call not paired with a menu_floor \
2172 call -- every darkroom menu must clamp both its anchor and its \
2173 list room together"
2174 );
2175 assert!(sizings > 0, "{file} no longer opens any menu -- update this guard");
2176 }
2177}
2178
2179/// The settings page's own organising rule: PROJECT rows open only the
2180/// doors that write into the `.edith` file ([`Player::open_picker`],
2181/// [`Player::open_mix`]), and EDITOR rows open only the doors that do not
2182/// ([`Player::toggle_proxies`], [`Player::toggle_auto_proxies`],
2183/// [`Player::open_subtitle_style`]) -- never the config-file writers
2184/// (`ui::dock_stance::config_path`/`ui::theme::config_path`/
2185/// `keymap::Keymap::config_path`) directly, which every editor-side row
2186/// already routes around through its own opener. A row wired to the wrong
2187/// section's opener is exactly the regression a page organised around two
2188/// headings invites; this pins each half to its own doors so the two lists
2189/// cannot cross.
2190#[test]
2191fn settings_project_and_editor_sections_open_disjoint_doors() {
2192 let source = src_text("ui/settings_stance.rs");
2193 let project_start = source.find("fn project_section(").expect("the project section");
2194 let editor_start = source.find("fn editor_section(").expect("the editor section");
2195 let render_start = source.find("pub(crate) fn render(").expect("the page's render fn");
2196 assert!(project_start < editor_start && editor_start < render_start, "the three fns moved; this scan is blind");
2197 let project_body = &source[project_start..editor_start];
2198 let editor_body = &source[editor_start..render_start];
2199
2200 for door in ["open_picker(", "open_mix("] {
2201 assert!(project_body.contains(door), "PROJECT section no longer opens {door} -- update this guard");
2202 assert!(
2203 !editor_body.contains(door),
2204 "EDITOR section opens {door}, a project-file door -- that value belongs in PROJECT, not here"
2205 );
2206 }
2207 for door in ["toggle_proxies(", "toggle_auto_proxies(", "open_subtitle_style("] {
2208 assert!(editor_body.contains(door), "EDITOR section no longer opens {door} -- update this guard");
2209 assert!(
2210 !project_body.contains(door),
2211 "PROJECT section opens {door}, an editor-only door -- that value belongs in EDITOR, not here"
2212 );
2213 }
2214 // Neither section writes a config file straight from a row: both go
2215 // through an opener, which is the one place a config-file write (the
2216 // subtitle style card's Save, this window's next project load) is
2217 // allowed to live.
2218 for path_fn in ["dock_stance::config_path", "theme::config_path", "Keymap::config_path"] {
2219 assert!(!project_body.contains(path_fn), "PROJECT section touches {path_fn} directly");
2220 assert!(!editor_body.contains(path_fn), "EDITOR section touches {path_fn} directly");
2221 }
2222}
2223
2224/// D1's own class, pinned per row rather than per section: a row's hint can
2225/// claim a `~/.config/edith` default (the section header claims nothing on
2226/// its own since [`settings_project_and_editor_sections_open_disjoint_doors`]'s
2227/// commit, so a lying section head no longer slips past a reviewer -- but a
2228/// lying *row* hint did, on Proxies, because nothing scanned row text at all).
2229/// For every row whose own hint text names that file, this requires the
2230/// matching `save_*_pref`/`load_*_pref` pair to actually exist in
2231/// `player/library.rs` -- the exact gap Proxies shipped with: a hint promising
2232/// a default the row's own door never wrote.
2233#[test]
2234fn settings_row_hints_naming_config_edith_have_a_matching_pref_pair() {
2235 let source = src_text("ui/settings_stance.rs");
2236 let library = src_text("player/library.rs");
2237 // (row id, the stem its pref functions are named after)
2238 for (row_id, stem) in [("settings-proxies", "proxies"), ("settings-auto-proxies", "auto_proxies")] {
2239 let row_start = source.find(&format!("\"{row_id}\"")).unwrap_or_else(|| panic!("{row_id} row moved or renamed -- update this guard"));
2240 let row_end = source[row_start..].find(",\n ))").map_or(source.len(), |i| row_start + i);
2241 let row_text = &source[row_start..row_end];
2242 if !row_text.contains("~/.config/edith") {
2243 continue;
2244 }
2245 for prefix in ["save_", "load_"] {
2246 let fn_name = format!("{prefix}{stem}_pref");
2247 assert!(
2248 library.contains(&format!("fn {fn_name}(")),
2249 "{row_id}'s hint claims a ~/.config/edith default but \
2250 player/library.rs has no `{fn_name}` -- the hint promises \
2251 storage the row does not have"
2252 );
2253 }
2254 }
2255}
2256
2257/// With no project open, a PROJECT row must not fall back to a bare noun
2258/// ("Size"/"Rate"/"HDR") standing in the value slot -- it reads as a value
2259/// while carrying none. This binary has no `TestAppContext` to actually
2260/// render the page with `player.session` empty, so this is a source scan
2261/// for the fallback strings the bug shipped as, same as the guard above it.
2262#[test]
2263fn settings_project_rows_have_no_bare_noun_placeholder() {
2264 let source = src_text("ui/settings_stance.rs");
2265 let project_start = source.find("fn project_section(").expect("the project section");
2266 let editor_start = source.find("fn editor_section(").expect("the editor section");
2267 let project_body = &source[project_start..editor_start];
2268 for placeholder in ["\"Size\".to_string()", "\"Rate\".to_string()", "\"HDR\".to_string()"] {
2269 assert!(
2270 !project_body.contains(placeholder),
2271 "a PROJECT row fell back to the bare noun {placeholder} -- it reads as a value with no project open"
2272 );
2273 }
2274}
2275
2276/// The HDR reference rows must read the file's own declared numbers off
2277/// [`engine::colorspace::ContentLight`] -- not invent a monitor override the
2278/// engine has nowhere to persist -- and must fall back to the page's one
2279/// established empty state (a bare `—` in `INK4`, [`row_ink`]/[`row_static`]'s
2280/// own idiom) rather than a second placeholder idiom. No `TestAppContext`
2281/// here either, so this is the same source-scan the guard above it is.
2282#[test]
2283fn hdr_reference_rows_read_content_light_and_use_the_established_empty_state() {
2284 let source = src_text("ui/settings_stance.rs");
2285 let project_start = source.find("fn project_section(").expect("the project section");
2286 let editor_start = source.find("fn editor_section(").expect("the editor section");
2287 let project_body = &source[project_start..editor_start];
2288
2289 assert!(project_body.contains("settings-hdr-reference"), "the HDR reference row is missing");
2290 assert!(project_body.contains("settings-content-light"), "the content-light row is missing");
2291
2292 // Reads the real declared numbers, not an invented default or a fixed
2293 // string standing in for one.
2294 for field in ["mastering_max", "max_cll", "max_fall"] {
2295 assert!(project_body.contains(field), "the HDR reference rows do not read ContentLight::{field}");
2296 }
2297
2298 // No override field exists on the engine side to write one into, so the
2299 // row must never claim a picker/opener the way every other PROJECT row
2300 // does -- it is built with `row_static`, not `row`/`row_ink`.
2301 assert!(project_body.contains("row_static(\n \"settings-hdr-reference\""), "the HDR reference row must be read-only (row_static), not a picker");
2302 assert!(project_body.contains("row_static(\n \"settings-content-light\""), "the content-light row must be read-only (row_static), not a picker");
2303
2304 // The established empty state: a bare "—" reused, never a second idiom
2305 // ("N/A", "None", "Unknown"...) invented for the same absence.
2306 assert!(project_body.contains("\"—\".to_string()"), "the HDR reference rows must reuse the page's own empty-state dash");
2307}
2308/// The parity class this user has reported four separate times: "some
2309/// options are only reachable via keyboard shortcut". A source scan (this
2310/// binary has no `TestAppContext` to click through) over every darkroom
2311/// surface -- the spine, the dock, the bench/timeband transport, the
2312/// settings page, the maximized cards and the clip context menu
2313/// (`menus.rs`'s `MENU_ITEMS`, rendered mouse-and-chord-visible by
2314/// `overlays.rs`) -- for a literal `ActionId::<variant>` mention. An
2315/// [`ActionId`] reachable by chord ([`Keymap::defaults`]) but absent from
2316/// every one of those texts has no mouse door into the darkroom at all,
2317/// which is exactly this bug's shape (`Fit` and `Redo` shipped that way
2318/// until this commit).
2319///
2320/// [`ActionId::Resolution`] and [`ActionId::SubtitleStyle`] are the two
2321/// deliberate exceptions: their settings-page rows open them through
2322/// `Pick::Resolution` and `open_subtitle_style(cx)` respectively, never
2323/// spelling the action name itself, so each is matched on its own door
2324/// string instead.
2325///
2326/// [`ALLOWED_CHORD_ONLY`] is the honest remainder: fine-grained playhead/edit
2327/// strokes with no button in the *legacy* tree either (`toolbar.rs`,
2328/// `inspector.rs`, `library.rs` were all swept for the same names and come
2329/// up equally empty) -- not a regression this task closes, just an existing
2330/// keyboard-only stroke this editor has never given a face.
2331#[test]
2332fn every_chord_bound_action_has_a_darkroom_affordance_or_is_named_chord_only() {
2333 use crate::ActionId;
2334 const ALLOWED_CHORD_ONLY: &[ActionId] = &[
2335 ActionId::StepBack,
2336 ActionId::StepForward,
2337 ActionId::GoStart,
2338 ActionId::GoEnd,
2339 ActionId::PrevSyncPoint,
2340 ActionId::NextSyncPoint,
2341 ActionId::WalkCutNext10,
2342 ActionId::WalkCutPrev10,
2343 ActionId::SetIn,
2344 ActionId::SetOut,
2345 ActionId::ClearRange,
2346 ActionId::SelectAll,
2347 ActionId::RemoveVideoLane,
2348 ActionId::RemoveAudioLane,
2349 ActionId::Crossfade,
2350 ];
2351 let darkroom = [
2352 "ui/bench_stance.rs",
2353 "ui/cards.rs",
2354 "ui/dock_stance.rs",
2355 "ui/overlays.rs",
2356 "ui/settings_stance.rs",
2357 "ui/spine_stance.rs",
2358 "ui/stance.rs",
2359 "ui/timeband_stance.rs",
2360 "ui/timeline.rs",
2361 "menus.rs",
2362 ]
2363 .map(src_text)
2364 .join("\n");
2365 for action in ActionId::ALL {
2366 if ALLOWED_CHORD_ONLY.contains(&action) {
2367 continue;
2368 }
2369 let name = format!("{action:?}");
2370 let mentioned = darkroom.contains(&format!("ActionId::{name}"))
2371 || (action == ActionId::Resolution && darkroom.contains("Pick::Resolution"))
2372 || (action == ActionId::SubtitleStyle && darkroom.contains("open_subtitle_style(cx)"));
2373 assert!(
2374 mentioned,
2375 "ActionId::{name} is bound to a chord but has no visible affordance \
2376 anywhere in the darkroom tree -- either mount it (see Fit/Redo, this \
2377 commit) or add it to ALLOWED_CHORD_ONLY with a reason"
2378 );
2379 }
2380}