forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

cards.rs3800 lines, 165.1 KiBHistoryRawDownload
1//! The cards the window opens over itself: the keys, the equaliser, the
2//! colour and speed bars, the silence scan, the choices and the export.
3
4use super::*;
5use crate::audio_cards::EQ_GRAPH_MAX_H;
6use crate::Player;
7use crate::eq_ui::{eq_band_changes, eq_takes_gain, EQ_KINDS};
8use crate::player::cards::{speed_fraction, speed_on_bar};
9use crate::ui::dock_stance::transition_of;
10use std::sync::atomic::Ordering;
11
12/// FAULT 2's general shape (not just the source dot's menu): `overlaid()`
13/// refuses every key while `context_menu`/`library_menu`/`picker` is `Some`,
14/// so each of the three needs *both* a place to paint in the stance and a way
15/// for any key to clear it -- otherwise the state `overlaid()` names becomes
16/// an invisible, unrecoverable modal the moment something sets it. A live
17/// harness proved the bug (right-click the source dot, every key but escape
18/// went dead); this pins the fix as a standing structural rule rather than a
19/// one-off repro, the same way `the_darkroom_path_never_lets_a_notice_surface_reach_the_picture`
20/// pins its own render-order fault.
21#[test]
22fn no_overlaid_state_in_the_stance_goes_modal_without_painting_something() {
23 let stance = src_text("ui/stance.rs");
24 let render_body = &stance[stance
25 .find("pub(crate) fn render(")
26 .expect("the stance's entry point")..];
27 for menu in ["context_card(", "library_card(", "picker_card("] {
28 assert!(
29 render_body.contains(menu),
30 "ui::stance::render never mounts Player::{menu} -- overlaid() can refuse \
31 every key for a menu the room never draws"
32 );
33 }
34 let guard_at = stance
35 .find("if this.card_open()\n || this.context_menu.is_some()")
36 .expect("the stance's modal guard");
37 // Wide enough to span the whole guard block -- escape's
38 // `escape_closes_overlay` branch and its commentary sit above the
39 // any-key clears, and a scan window that ends before them read as the
40 // clears having been deleted (2026-08-27).
41 let guard = &stance[guard_at..guard_at + 3000];
42 assert!(
43 guard.contains("escape_closes_overlay"),
44 "the modal guard's escape branch no longer routes through \
45 Player::escape_closes_overlay -- the focus rings' own escape \
46 branches call that same door, and the two must not diverge"
47 );
48 for field in [
49 "this.context_menu = None",
50 "this.library_menu = None",
51 "this.picker = None",
52 ] {
53 assert!(
54 guard.contains(field),
55 "the overlaid() branch no longer clears {field} on every key -- \
56 a menu can go modal and unrecoverable again (FAULT 2)"
57 );
58 }
59}
60
61#[test]
62fn every_modal_field_has_a_mounted_surface_somewhere_in_the_darkroom() {
63 // Every field/method `Player::modal()` reads, pulled from its own body
64 // rather than hand-copied -- a hand-copied list is exactly the shape
65 // that let three cards go modal with nothing mounted (GAP 2): the field
66 // was in `modal()` and nowhere in this test.
67 // `modal()` is just `card_open()` now: a running export no longer makes
68 // the room modal (the oracle refuses what it must, action by action), so
69 // every field this test pins lives in `card_open()`.
70 let modal_body = fn_body("card_open");
71 let mut fields = Vec::<String>::new();
72 for chunk in modal_body.split("self.").skip(1) {
73 let name: String = chunk
74 .chars()
75 .take_while(|c| c.is_alphanumeric() || *c == '_')
76 .collect();
77 if !name.is_empty() && !fields.contains(&name) {
78 fields.push(name);
79 }
80 }
81 assert!(
82 fields.len() >= 9,
83 "modal()'s own field list looks too short to have been parsed: {fields:?}"
84 );
85 // The mounted-surface function each field's own card draws, by the
86 // convention the param cards already follow (`x_open` -> `x_card(` --
87 // `Player::eq_card`/`color_card`/... in `ui/cards/`).
88 // `export_open` doesn't follow that convention (it mounts `export_panel`),
89 // so it is named explicitly. Anything else unmapped panics loudly -- the
90 // point is that a ninth card has to earn a line here, not just a mount,
91 // or this test cannot see it.
92 let mount_for = |field: &str| -> &'static str {
93 match field {
94 "export_open" => "export_panel(",
95 "eq_open" => "eq_card(",
96 "color_open" => "color_card(",
97 "transform_open" => "transform_card(",
98 "speed_open" => "speed_card(",
99 "effects_open" => "effects_card(",
100 "silence_open" => "silence_card(",
101 "beats_open" => "beats_card(",
102 "mix_open" => "mix_card(",
103 "markers_open" => "markers_card(",
104 "history_open" => "history_card(",
105 "tools" => "tools_card(",
106 "subtitle_style_open" => "subtitle_style_card(",
107 "settings_open" => "settings_stance::render(",
108 "proj_dialog" => "project_dialog_card(",
109 other => panic!(
110 "Player::modal() now reads `self.{other}` with no entry in this test's \
111 mount_for map -- add one naming the function that mounts its surface in \
112 the darkroom (ui/stance.rs or ui/dock_stance.rs), or the room can go modal \
113 over it with nothing drawn (the silence/mix/subtitle-style bug, GAP 2)."
114 ),
115 }
116 };
117 let haystack = format!(
118 "{}\n{}",
119 src_text("ui/stance.rs"),
120 src_text("ui/dock_stance.rs")
121 );
122 for field in &fields {
123 let mount = mount_for(field);
124 assert!(
125 haystack.contains(mount),
126 "Player::modal()'s `self.{field}` makes overlaid() true, but the darkroom never \
127 mounts `{mount}` in ui/stance.rs or ui/dock_stance.rs -- pressing its key opens \
128 an invisible modal (GAP 2)."
129 );
130 }
131}
132
133/// D2's class: an action refused while a modal is up used to be sworn to
134/// silence, because the stance's own key guard ate the keystroke before
135/// `enable()`/`act()` ever saw it -- driven live with `ctrl+,` mid-export
136/// (no card open, only `exporting()` true): no notice plate, ledger reading
137/// `—`. `ActionId::Settings`'s own refusal string (`oracle.rs`) was sound and
138/// simply never reachable.
139///
140/// The fix lives in the guard, not in Settings alone (the charter this test
141/// pins is explicit that a per-action patch would leave every *other* action
142/// refused during a bare export equally mute): [`Player::modal`] no longer
143/// reads `exporting()` at all, and the stance's guard reads `card_open()` --
144/// never `overlaid()`/`modal()` directly, so the guard's own list stays the
145/// cards, menus and pickers. This is a source scan, the same kind the guard above it
146/// already is: this binary has no `TestAppContext` to actually press `ctrl+,`
147/// mid-export and read the notice plate back.
148#[test]
149fn the_stances_key_guard_does_not_swallow_a_bare_export_before_the_oracle_is_asked() {
150 let stance = src_text("ui/stance.rs");
151 let guard_at = stance
152 .find("if this.card_open()\n || this.context_menu.is_some()")
153 .expect("the stance's modal guard moved -- update this test's search string");
154 let guard_line = &stance[guard_at..guard_at + 200];
155 assert!(
156 !guard_line.contains("overlaid()") && !guard_line.contains("this.modal()"),
157 "the stance's key guard reads overlaid()/modal() again, which folds `exporting()` \
158 back in and re-mutes every refusal an export-only moment should be able to speak (D2)"
159 );
160 // The guard trusts card_open() to mean "an actual card owns the keyboard",
161 // so neither it nor modal() may grow an exporting read -- either would
162 // silently regain the same mute.
163 for body in [fn_body("card_open"), fn_body("modal")] {
164 assert!(
165 !body.contains("exporting"),
166 "Player::card_open()/modal() now reads `exporting` -- that reintroduces the \
167 swallow `the_stances_key_guard_does_not_swallow_a_bare_export_before_the_oracle_is_asked` \
168 exists to keep out; an export is refused by the oracle, not by the modal"
169 );
170 }
171}
172
173/// The whole point of the card: there is no action a pointer cannot reach.
174/// It renders [`keys_rows`] and nothing else, so this reads the same list
175/// the card does -- add an `ActionId` and forget to surface it and this
176/// fails, which is the only way that stays true as the editor grows.
177#[test]
178fn every_action_is_on_the_actions_card() {
179 use keymap::{ActionId, Category};
180 let rows = keys_rows();
181 let listed: Vec<ActionId> = rows
182 .iter()
183 .filter_map(|r| match r {
184 KeyRow::Act(a) => Some(*a),
185 _ => None,
186 })
187 .collect();
188 // The angles 2 to 9 share the one "angle 1-9" row, so they are not listed of their own.
189 for action in ActionId::ALL.into_iter().filter(|a| a.angle_number().is_none_or(|n| n == 1)) {
190 assert_eq!(
191 listed.iter().filter(|a| **a == action).count(),
192 1,
193 "{action:?} is not on the card exactly once"
194 );
195 }
196 assert_eq!(listed.len(), ActionId::ALL.len() - 8);
197 // Under its own heading, in the registry's order: every row after a
198 // heading belongs to that heading until the next one.
199 let mut heading = None;
200 let mut heads = 0;
201 for row in &rows {
202 match row {
203 KeyRow::Head(category) => {
204 heading = Some(*category);
205 heads += 1;
206 }
207 KeyRow::Act(action) => assert_eq!(Some(action.category()), heading, "{action:?}"),
208 KeyRow::Fixed(i) => assert_eq!(Some(keymap::FIXED[*i].category), heading),
209 }
210 }
211 assert_eq!(heads, Category::ALL.len(), "a heading per category");
212 // The card-local strokes are still all there beside them.
213 assert_eq!(
214 rows.iter()
215 .filter(|r| matches!(r, KeyRow::Fixed(_)))
216 .count(),
217 keymap::FIXED.len()
218 );
219 // Both columns say something: the label does the action, the stroke
220 // beside it changes that stroke, and neither may read blank.
221 let keymap = keymap::Keymap::defaults();
222 // DESIGN §10.2's menu-only rows: the mock leaves them without a stroke on
223 // purpose, and the menu is their door.
224 let menu_only = [
225 ActionId::MarkerHere,
226 ActionId::TrackSmall,
227 ActionId::TrackMedium,
228 ActionId::TrackLarge,
229 ActionId::PlayheadHere,
230 ActionId::PasteFilePath,
231 ActionId::AddVideoLane,
232 ActionId::AddAudioLane,
233 ActionId::RemoveVideoLane,
234 ActionId::RemoveAudioLane,
235 ActionId::AddSubtitleLane,
236 ActionId::RemoveSubtitleLane,
237 ActionId::ToggleAutoProxies,
238 ActionId::Theme,
239 ActionId::AccentColour,
240 // The viewer header owns these four; no stroke, menu and palette are the doors.
241 ActionId::ViewZoom,
242 ActionId::PlaybackQuality,
243 ActionId::GuideStyle,
244 ActionId::GuideMask,
245 // No stroke by decision: a key that throws away edits is pressed by accident.
246 ActionId::ReloadProject,
247 ActionId::SaveVersion,
248 ActionId::SaveTemplate,
249 ActionId::ExportCaptions,
250 ActionId::NewProject,
251 ActionId::Versions,
252 ActionId::CollectMedia,
253 ActionId::ProjectNotes,
254 // The transition kinds are palette commands and the Clip tab's picker.
255 ActionId::TransitionDissolve,
256 ActionId::TransitionDipBlack,
257 ActionId::TransitionDipWhite,
258 ActionId::TransitionWipeLeft,
259 ActionId::TransitionWipeRight,
260 ActionId::TransitionWipeUp,
261 ActionId::TransitionWipeDown,
262 ActionId::TransitionSlideLeft,
263 ActionId::TransitionSlideRight,
264 ActionId::TransitionSlideUp,
265 ActionId::TransitionSlideDown,
266 ActionId::TransitionPushLeft,
267 ActionId::TransitionPushRight,
268 ActionId::TransitionPushUp,
269 ActionId::TransitionPushDown,
270 ActionId::TransitionZoom,
271 // The cards' stopwatch diamonds are their doors; the menu lists the same four.
272 ActionId::KeyPlacement,
273 ActionId::KeyOpacity,
274 ActionId::KeyColor,
275 ActionId::KeyEasing,
276 // The creator tools: menu and palette, no chord yet.
277 // The speed ramp's shapes and key verbs live on the palette, the Clip menu
278 // and the speed card; the card is `j`.
279 ActionId::SpeedRampUp,
280 ActionId::SpeedRampDown,
281 ActionId::SpeedRampSlowFastSlow,
282 ActionId::SpeedRampFastSlowFast,
283 ActionId::SpeedRampKey,
284 ActionId::SpeedRampClear,
285 // Auto reframe is a menu row and a transform-card row, with no stroke.
286 ActionId::Reframe,
287 ActionId::About,
288 // Sequences and compound clips are menu rows and tabs, with no stroke.
289 ActionId::NestClips,
290 ActionId::BreakApart,
291 ActionId::OpenCompound,
292 ActionId::CloseCompound,
293 ActionId::NewSequence,
294 ActionId::DuplicateSequence,
295 ActionId::RenameSequence,
296 ActionId::DeleteSequence,
297 // Multicam: menu rows, with no stroke.
298 ActionId::CreateMulticam,
299 ActionId::FlattenMulticam,
300 ActionId::RenameLane,
301 ActionId::PasteColor,
302 ActionId::PasteEffects,
303 ActionId::PasteTransform,
304 ActionId::PasteSpeed,
305 ActionId::PasteAudio,
306 ActionId::ClipLabel,
307 ActionId::NewSolid,
308 ActionId::NewGradient,
309 ActionId::NewCountdown,
310 ActionId::NewBars,
311 ActionId::NewTone,
312 ActionId::NewBarsAndTone,
313 ActionId::NewAdjustment,
314 ActionId::NewBin,
315 ActionId::NewBinInside,
316 ActionId::RenameBin,
317 ActionId::RemoveBin,
318 ActionId::ToggleFavourite,
319 ActionId::MoveToBin,
320 ActionId::ShowFavourites,
321 ActionId::ShowAllMedia,
322 ActionId::NewRectangle,
323 ActionId::NewEllipse,
324 ActionId::NewLine,
325 ActionId::NewArrow,
326 // The transcript's cut: a Clip row and the palette, no stroke (Delete does it in the transcript).
327 ActionId::CutSelectedWords,
328 // The ruler's marker menu: rows with no stroke.
329 ActionId::RenameMarker,
330 ActionId::DeleteMarker,
331 // The View menu's switch: no NLE convention gives it a key.
332 ActionId::ToggleWaveforms,
333 // The View menu's audible-scrub switch: likewise.
334 ActionId::ToggleScrubAudio,
335 // Edit > History opens its card from the menu: no stroke.
336 ActionId::History,
337 // Compare grade and the colour card's Auto and Save look: no NLE key gives them one.
338 ActionId::CompareOff,
339 ActionId::CompareSplit,
340 ActionId::CompareSide,
341 ActionId::AutoColour,
342 ActionId::SaveLook,
343 // Track mask: a Clip row with no stroke; the effects card's Track row is its surface.
344 ActionId::TrackMask,
345 // Timeline > Record voice-over: a sheet, and no NLE convention gives it a key.
346 ActionId::RecordVoiceover,
347 // The video output window and its display: menu rows, no NLE key.
348 ActionId::ToggleOutputWindow,
349 ActionId::OutputDisplay,
350 // The timeline interchange rows: File menu entries with no stroke.
351 ActionId::ExportTimelineOtio,
352 ActionId::ExportTimelineFcpxml,
353 ActionId::ExportTimelineEdl,
354 ActionId::ImportTimelineOtio,
355 // The render preview rows in the Timeline menu's submenu: no stroke for the last three.
356 ActionId::RenderAll,
357 ActionId::CancelRender,
358 ActionId::DeleteRenderFiles,
359 ];
360 for action in ActionId::ALL {
361 assert!(!action.label().is_empty(), "{action:?}");
362 if menu_only.contains(&action) {
363 assert_eq!(keymap.display(action), "unbound", "{action:?}");
364 } else {
365 assert_ne!(keymap.display(action), "unbound", "{action:?}");
366 }
367 }
368 // Both halves of a row are click targets, so WCAG 2.5.8 binds them.
369 const {
370 assert!(KEYS_ROW_H >= HIT_MIN);
371 }
372}
373
374/// What a keystroke means to that box: a letter is a letter, and a word
375/// gpui reports for a key that prints nothing is not typed letter by
376/// letter into the search.
377#[test]
378fn only_a_printable_stroke_types_into_the_search() {
379 assert_eq!(typed("a"), Some('a'));
380 assert_eq!(typed("-"), Some('-'));
381 assert_eq!(typed("1"), Some('1'));
382 // The one printable key gpui reports by name.
383 assert_eq!(typed("space"), Some(' '));
384 for word in ["left", "escape", "f1", "backspace", "tab", "delete", "home"] {
385 assert_eq!(typed(word), None, "{word}");
386 }
387}
388
389#[test]
390fn keys_search_keeps_matching_rows_and_drops_empty_heads() {
391 let km = keymap::Keymap::defaults();
392 let cut = keys_rows_matching("split", &km);
393 assert!(cut.iter().any(|r| matches!(r, KeyRow::Act(ActionId::Cut))));
394 assert!(!cut.iter().any(|r| matches!(r, KeyRow::Act(ActionId::Play))));
395 assert!(cut.iter().any(|r| matches!(r, KeyRow::Head(_))));
396 assert!(keys_rows_matching("xyzzy-no-such", &km).is_empty());
397}
398
399#[test]
400fn the_keybindings_card_fits_the_smallest_window() {
401 // The row list is capped and scrolls, so the card's height no longer
402 // depends on how many actions there are: a title, a status line, the
403 // search box and the viewport, inside the 640x360 the rest of the
404 // layout is sized for.
405 let title = 17.; // 13 px text on its own line
406 let status = 28.; // 11 px text, two lines: a refusal wraps
407 let search = 15.; // 11 px text, one line: it never wraps
408 let gaps = 4. * 2.;
409 let padding = 24.;
410 // The line the list scrolls under: margin, rule, padding.
411 let separator = 4. + 1. + 4.;
412 assert!(
413 title + status + search + separator + 10. * KEYS_ROW_H + gaps + padding <= 360.,
414 "card too tall"
415 );
416 const {
417 assert!(KEYS_W <= 640., "card too wide");
418 }
419 // The rows are clickable, so WCAG 2.5.8 binds them like every other
420 // target in this window.
421 const {
422 assert!(KEYS_ROW_H >= HIT_MIN);
423 }
424}
425
426/// The equalizer's band rows: a cut shows no gain because it has none to set,
427/// every kind has exactly one chip, and a number reads as changed only once it
428/// has left the layout the clip opens on -- so the ink says what was moved.
429#[test]
430fn eq_rows_show_only_the_numbers_a_band_uses_and_mark_what_moved() {
431 use engine::eq::{BandKind, EqParams};
432
433 assert!(!eq_takes_gain(BandKind::LowCut) && !eq_takes_gain(BandKind::HighCut));
434 assert!(
435 eq_takes_gain(BandKind::LowShelf)
436 && eq_takes_gain(BandKind::Peak)
437 && eq_takes_gain(BandKind::HighShelf)
438 );
439
440 let kinds = [
441 BandKind::LowCut,
442 BandKind::LowShelf,
443 BandKind::Peak,
444 BandKind::HighShelf,
445 BandKind::HighCut,
446 ];
447 assert_eq!(EQ_KINDS.len(), kinds.len());
448 for kind in kinds {
449 assert_eq!(
450 EQ_KINDS.iter().filter(|(k, _, _)| *k == kind).count(),
451 1,
452 "{kind:?} needs exactly one chip"
453 );
454 }
455
456 let layout = EqParams::default_layout();
457 assert_eq!(
458 eq_band_changes(&layout.bands[0], 0),
459 (false, false, false),
460 "a band at its layout default reads ink3 on every number"
461 );
462 let mut moved = layout.bands[1];
463 moved.freq_hz *= 1.2;
464 assert_eq!(eq_band_changes(&moved, 1), (true, false, false));
465 let mut moved = layout.bands[1];
466 moved.gain_db = 3.;
467 assert_eq!(eq_band_changes(&moved, 1), (false, true, false));
468 let mut moved = layout.bands[1];
469 moved.q = 2.;
470 assert_eq!(eq_band_changes(&moved, 1), (false, false, true));
471 assert!(
472 eq_band_changes(&layout.bands[1], 7).0,
473 "a band past the layout has no default, so its frequency reads as moved"
474 );
475}
476
477/// The equalizer card's graph: where a band lands on it, that a drag reads
478/// back as the gain it painted -- the two are one mapping and its inverse,
479/// which is what makes a handle follow the pointer -- and that the card
480/// still fits the window the other two are sized for.
481#[test]
482fn the_equalizer_graph_puts_a_band_where_a_drag_reads_it_and_fits_the_smallest_window() {
483 use engine::eq::{Band, BandKind, EqParams};
484 // Flat is the middle of the box: a band nobody has touched must not
485 // look like one that has been turned down.
486 assert_eq!(eq_y(0.), 0.5);
487 // Full boost is the top edge, full cut the bottom one -- y grows down.
488 assert_eq!(eq_y(EQ_GAIN_LIMIT), 0.);
489 assert_eq!(eq_y(-EQ_GAIN_LIMIT), 1.);
490 assert_eq!(eq_y(EQ_GAIN_LIMIT / 2.), 0.25);
491 // A file may carry a gain past what this card offers (the format writes
492 // any finite value): it paints on the edge, never off the box.
493 assert_eq!(eq_y(400.), 0.);
494 assert_eq!(eq_y(-400.), 1.);
495
496 // A pointer reads back as the gain that paints where it landed, which
497 // is what makes a drag land under the hand ([`Player::drag_band`]).
498 for gain in [-12., -6., 0., 6., 12.] {
499 let read = (0.5 - eq_y(gain)) * 2. * EQ_GAIN_LIMIT;
500 assert!((read - gain).abs() < 1e-4, "{gain} read back as {read}");
501 }
502
503 // The frequency axis is logarithmic and spans the audible range: the
504 // ends are the ends, and the decade at 200 Hz is as wide as the one at
505 // 2 kHz -- the whole reason a bass band is reachable at all.
506 assert_eq!(eq_x(EQ_FREQ_LOW), 0.);
507 assert_eq!(eq_x(EQ_FREQ_HIGH), 1.);
508 assert!((eq_x(200.) - 1. / 3.).abs() < 1e-4);
509 assert!(((eq_x(2000.) - eq_x(200.)) - (eq_x(20000.) - eq_x(2000.))).abs() < 1e-4);
510 // Off either end clamps rather than painting outside the box.
511 assert_eq!(eq_x(1.), 0.);
512 assert_eq!(eq_x(96_000.), 1.);
513 // Every tick the card names is on the axis it is drawn against.
514 for (freq, label) in EQ_TICKS {
515 assert!(
516 (EQ_FREQ_LOW..=EQ_FREQ_HIGH).contains(&freq),
517 "tick {label} is off the axis"
518 );
519 }
520 // The default bands all land inside it too, spread out enough that the
521 // nearest-band pick (`Player::nearest_band`) has something to pick.
522 let xs: Vec<f32> = EqParams::default_layout()
523 .bands
524 .iter()
525 .map(|b| eq_x(b.freq_hz))
526 .collect();
527 for pair in xs.windows(2) {
528 assert!(pair[1] - pair[0] > 0.1, "bands too close to aim at: {xs:?}");
529 }
530
531 // Every default band says what it is, and a shelf says so: "12 kHz"
532 // alone would not tell anyone it tilts the whole top octave.
533 let labels: Vec<String> = EqParams::default_layout()
534 .bands
535 .iter()
536 .map(band_label)
537 .collect();
538 assert_eq!(
539 labels,
540 [
541 "80 Hz low shelf",
542 "250 Hz",
543 "1 kHz",
544 "4 kHz",
545 "12 kHz high shelf"
546 ]
547 );
548 // A band moved off a round number reads as where it *is*: a keystroke
549 // that changes the filter and not the number on the card is a keystroke
550 // nobody can aim.
551 assert_eq!(
552 band_label(&Band {
553 freq_hz: 2600.,
554 gain_db: 0.,
555 q: 1.,
556 kind: BandKind::Peak
557 }),
558 "2.6 kHz"
559 );
560 assert_eq!(eq_freq_label(1122.), "1.12 kHz");
561 assert_eq!(eq_freq_label(12000.), "12 kHz", "no zeroes to read past");
562 assert_eq!(eq_freq_label(80.), "80 Hz");
563
564 // The card fits the smallest window and takes the room a bigger one has
565 // -- it is a graph, and the width *is* the frequency resolution.
566 assert!(
567 eq_card_w(640., false) <= 640. - 24.,
568 "card too wide for 640"
569 );
570 assert!(
571 eq_card_w(1280., false) > eq_card_w(640., false),
572 "card ignores the window"
573 );
574 assert_eq!(eq_card_w(1920., false), EQ_W_MAX, "card grows without end");
575 assert!(
576 eq_card_w(320., false) >= KEYS_W,
577 "card narrower than a row of text"
578 );
579 // At the smallest window the graph is still a graph: three across for
580 // one down, so an octave is wide enough to put a handle in.
581 assert!(
582 eq_card_w(640., false) - 24. >= 3. * EQ_GRAPH_H,
583 "graph too square to aim at"
584 );
585
586 // The same shape as the other two cards, so it fits where they do: the
587 // graph stands where the export card's rows do, and is shorter than
588 // they are. The numbers row is a row of buttons now, so it is one of
589 // those tall rather than one line of text.
590 let (title, status, gaps, padding) = (17., 28., 4. * 2., 24.);
591 assert!(
592 title + status + EQ_GRAPH_H + HIT_MIN + gaps + padding + CONTROL_H <= 360.,
593 "card too tall"
594 );
595 const {
596 assert!(
597 EQ_GRAPH_H <= (8. * KEYS_ROW_H),
598 "graph taller than a card of rows"
599 );
600 }
601 // What is dragged is the whole graph -- the handle is a 10 px dot, but
602 // a press anywhere in the box takes the band nearest it -- so WCAG
603 // 2.5.8 is satisfied by the box, which is far past the minimum.
604 const {
605 assert!(EQ_GRAPH_H >= HIT_MIN);
606 }
607 const {
608 assert!(
609 EQ_HANDLE < HIT_MIN,
610 "a dot that size would want its own hitbox"
611 );
612 }
613 const {
614 assert!(KEYS_ROW_H >= HIT_MIN);
615 }
616}
617
618/// Editing a band, which is what the card is *for*: the pointer reads a
619/// frequency off the axis the same way the axis draws one, a new band lands
620/// in the gap beside the picked one rather than on top of it, and every band
621/// the card will hold has a digit that picks it.
622#[test]
623fn a_band_can_be_moved_added_and_reached() {
624 use engine::eq::{Band, BandKind, EqParams};
625 // Across the graph and back: a drag sets the frequency the handle is
626 // then drawn at, so the two mappings have to be one another's inverse or
627 // the handle walks away from the pointer.
628 for freq in [20., 80., 250., 1000., 4000., 12000., 20000.] {
629 let read = eq_freq(eq_x(freq));
630 assert!(
631 (read / freq - 1.).abs() < 1e-3,
632 "{freq} Hz read back as {read}"
633 );
634 }
635 // Off the box either end stops at the axis, never past it.
636 assert_eq!(eq_freq(-1.), EQ_FREQ_LOW);
637 assert_eq!(eq_freq(2.), EQ_FREQ_HIGH);
638
639 // A step of the frequency keys is a real move on screen -- a keystroke
640 // that changes nothing visible is a keystroke that reads as broken --
641 // and small enough to aim with.
642 let step = eq_x(1000. * EQ_FREQ_STEP) - eq_x(1000.);
643 assert!(step > 0.01 && step < 0.06, "frequency key steps {step}");
644
645 // A new band lands between the picked one and the next one up, in
646 // octaves: 250 Hz and 1 kHz put it at 500, which is a gap on screen.
647 let bands = EqParams::default_layout().bands;
648 let added = inserted_band(&bands, 1);
649 assert!((added.freq_hz - 500.).abs() < 1., "landed at {added:?}");
650 assert_eq!(added.gain_db, 0., "a new band changes nothing until moved");
651 assert_eq!(added.kind, BandKind::Peak, "a new band is not a shelf");
652 assert!(eq_x(added.freq_hz) - eq_x(bands[1].freq_hz) > 0.1);
653 // Above the topmost band the gap is the rest of the axis, and the band
654 // still lands on it rather than off the end.
655 let top = inserted_band(&bands, bands.len() - 1);
656 assert!(
657 top.freq_hz > bands[4].freq_hz && top.freq_hz <= EQ_FREQ_HIGH,
658 "landed at {top:?}"
659 );
660 // Bands out of frequency order (a drag may cross two over) still get a
661 // sane neighbour: the next one *up*, not the next one along the list.
662 let crossed = vec![
663 Band {
664 freq_hz: 4000.,
665 gain_db: 0.,
666 q: 1.,
667 kind: BandKind::Peak,
668 },
669 Band {
670 freq_hz: 100.,
671 gain_db: 0.,
672 q: 1.,
673 kind: BandKind::Peak,
674 },
675 ];
676 let between = inserted_band(&crossed, 1);
677 assert!(
678 (between.freq_hz - 632.).abs() < 2.,
679 "landed at {between:?}, not between 100 and 4000"
680 );
681
682 assert!(EQ_BANDS_MAX > EqParams::default_layout().bands.len());
683 // The Q range holds the default, so a file's band never opens out of
684 // range and needs dragging back in before it can be edited.
685 assert!((EQ_Q_LOW..=EQ_Q_HIGH).contains(&0.707));
686 const {
687 assert!(EQ_Q_STEP > 1.);
688 }
689}
690
691/// The analyser drawn behind the curve: a tone has to land on its own
692/// frequency, or the backdrop is a decoration rather than a reading of what
693/// is playing -- and someone shaping a band against it would be aiming at
694/// the wrong octave.
695#[test]
696fn the_spectrum_puts_a_tone_under_its_own_frequency() {
697 use std::f32::consts::TAU;
698 let rate = 48_000u32;
699 let sine = |hz: f32, amp: f32| -> Vec<f32> {
700 (0..EQ_FFT)
701 .map(|i| amp * (TAU * hz * i as f32 / rate as f32).sin())
702 .collect()
703 };
704
705 // Silence is the floor of the box everywhere, not a band of noise.
706 let quiet = eq_spectrum(&vec![0.; EQ_FFT], rate);
707 assert_eq!(quiet.len(), EQ_CURVE_STEPS + 1);
708 assert!(quiet.iter().all(|&l| l == 0.), "silence drew something");
709
710 // A tone peaks over its own frequency, and the columns two octaves
711 // either side of it are near the floor. "Over" to within a bin down low
712 // and a column up high, which is all a 1024-point transform on a log
713 // axis can promise: at 200 Hz a whole column is a fraction of a bin
714 // wide, so the peak sits on the bin the tone fell in.
715 let column = |freq: f32| (eq_x(freq) * EQ_CURVE_STEPS as f32).round() as usize;
716 let freq_at = |col: usize| {
717 let along = col as f32 / EQ_CURVE_STEPS as f32;
718 EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along)
719 };
720 for hz in [200., 1000., 5000.] {
721 let levels = eq_spectrum(&sine(hz, 0.05), rate);
722 let (at, top) =
723 levels
724 .iter()
725 .enumerate()
726 .fold((0, 0f32), |best, (i, &l)| match l > best.1 {
727 true => (i, l),
728 false => best,
729 });
730 let slack = 1.5 * rate as f32 / EQ_FFT as f32 + 0.04 * hz;
731 assert!(
732 (freq_at(at) - hz).abs() <= slack,
733 "{hz} Hz peaked at {:.0} Hz (column {at})",
734 freq_at(at)
735 );
736 // -26 dBFS, which is where a 0.05 tone sits on the axis.
737 let want =
738 (20. * 0.05f32.log10() - EQ_SPECTRUM_DB.0) / (EQ_SPECTRUM_DB.1 - EQ_SPECTRUM_DB.0);
739 assert!(
740 (top - want).abs() < 0.05,
741 "a -26 dBFS tone drew {top} of the box, not {want}"
742 );
743 // Two octaves off is far enough down the box that the hump reads as
744 // one hump: 0.4 of the axis is a little over 30 dB.
745 for off in [hz / 4., hz * 4.] {
746 let away = levels[column(off).min(EQ_CURVE_STEPS)];
747 assert!(
748 top - away > 0.4,
749 "{hz} Hz drew {top} but still {away} at {off} Hz"
750 );
751 }
752 }
753
754 // Level reads as level: 40 dB quieter sits lower by the fraction of the
755 // axis those 40 dB are.
756 let loud = eq_spectrum(&sine(1000., 0.05), rate);
757 let soft = eq_spectrum(&sine(1000., 0.0005), rate);
758 let at = column(1000.);
759 let drop = loud[at] - soft[at];
760 let (floor, ceiling) = EQ_SPECTRUM_DB;
761 assert!(
762 (drop - 40. / (ceiling - floor)).abs() < 0.05,
763 "40 dB quieter moved the analyser {drop} of the box"
764 );
765
766 // A tap the engine has not filled yet (right after a seek) draws
767 // nothing at all rather than a transform of half a window.
768 assert!(eq_spectrum(&[0.; 16], rate).is_empty());
769}
770
771/// The speed bar is the same round trip -- pixels -> rate -> fill -- with
772/// one thing the colour sliders do not have to promise: **exactly 1.00x has
773/// to be reachable**, by a hand as well as by the reset. A grid that missed
774/// it would leave a clip nobody could put back.
775#[test]
776fn the_speed_bar_lands_where_it_paints_and_real_time_is_reachable() {
777 let bar = Bounds {
778 origin: point(px(180.), px(240.)),
779 size: size(px(COLOR_BAR_W), px(KEYS_ROW_H)),
780 };
781 // The same arithmetic `Player::drag_speed` runs, which is the one thing
782 // a test of it can share without re-deriving it.
783 let at = |x: f32| speed_on_bar(frac_along(px(x), bar));
784 assert_eq!(at(180.), Speed::MIN, "the left end is a quarter speed");
785 assert_eq!(at(180. + COLOR_BAR_W), Speed::MAX, "the right end is 4x");
786 assert_eq!(at(-4000.), Speed::MIN, "off the left clamps");
787 assert_eq!(at(9999.), Speed::MAX, "off the right clamps");
788 let mut hits_real_time = false;
789 for step in 0..=240 {
790 let along = step as f32 / 240.;
791 let speed = at(180. + along * COLOR_BAR_W);
792 hits_real_time |= speed == Speed::NORMAL;
793 assert_eq!(
794 i32::from(speed.permille()) % SPEED_STEP,
795 0,
796 "{speed} is off the {SPEED_STEP} grid the keys move on"
797 );
798 // What the bar paints from that rate is where the pointer was, to
799 // within half a grid step's width on the log scale.
800 let p = f32::from(speed.permille());
801 let painted = speed_fraction(p);
802 let half = SPEED_STEP as f32 / 2.;
803 // The press can be anywhere in the cell this rate stands for, which
804 // runs from the bar where `p - half` sits to where `p + half` sits.
805 // `painted` is the middle of that cell only while neither edge is
806 // clamped: `speed_fraction` clamps the lower edge to the bar's start,
807 // so at `Speed::MIN` the cell is one-sided and the paint sits on its
808 // edge. The slack is the distance to the far edge, not half of the
809 // whole cell, so both cases are covered.
810 let slack = (speed_fraction(p + half) - painted)
811 .max(painted - speed_fraction(p - half))
812 + 1e-4;
813 assert!(
814 (painted - along).abs() <= slack,
815 "pressed at {along}, paints at {painted}"
816 );
817 }
818 assert!(hits_real_time, "a drag can land on exactly 1.00x");
819 // ...and every preset the card offers is a rate the bar can also reach.
820 for permille in SPEED_PRESETS {
821 assert_eq!(Speed::from_permille(permille).permille(), permille);
822 assert_eq!(i32::from(permille) % SPEED_STEP, 0);
823 }
824 assert!(SPEED_PRESETS.contains(&Speed::NORMAL.permille()), "reset");
825}
826
827/// The speed bar is logarithmic: every doubling takes the same travel, so the
828/// quarter-to-half stretch is as long as the two-to-four one, and real time
829/// sits in the middle of the bar where a person expects it.
830#[test]
831fn the_speed_bar_gives_every_doubling_the_same_travel() {
832 let quarter_to_half = speed_fraction(500.) - speed_fraction(250.);
833 let two_to_four = speed_fraction(4000.) - speed_fraction(2000.);
834 assert!((quarter_to_half - two_to_four).abs() < 1e-5);
835 assert!((speed_fraction(1000.) - 0.5).abs() < 1e-5, "1.00x is mid-bar");
836 assert!(speed_fraction(250.).abs() < 1e-5);
837 assert!((speed_fraction(4000.) - 1.).abs() < 1e-5);
838}
839
840/// A colour slider is dragged straight to a value, so where the pointer
841/// lands and where the bar then paints have to be the same place: this is
842/// the round trip [`Player::drag_color`] makes, pixels -> value -> fill.
843#[test]
844fn a_colour_drag_lands_where_it_paints_and_the_card_fits_the_smallest_window() {
845 // A bar as laid out, somewhere that is not the window's origin -- a
846 // mapping that forgot the offset would pass at zero.
847 let bar = Bounds {
848 origin: point(px(180.), px(240.)),
849 size: size(px(COLOR_BAR_W), px(KEYS_ROW_H)),
850 };
851 for &(label, low, high) in &COLOR_BANDS {
852 // The ends are the ends: the left of the bar is the bottom of the
853 // range and the right is the top, so a slider can be pulled to
854 // either without hunting for the last pixel.
855 let at = |x: f32| color_snap(low + frac_along(px(x), bar) * (high - low));
856 assert_eq!(at(180.), low, "{label} left end");
857 assert_eq!(at(180. + COLOR_BAR_W), high, "{label} right end");
858 // Off either end clamps rather than running past the range.
859 assert_eq!(at(-4000.), low, "{label} off the left");
860 assert_eq!(at(9999.), high, "{label} off the right");
861
862 for step in 0..=48 {
863 let along = step as f32 / 48.;
864 let value = at(180. + along * COLOR_BAR_W);
865 // Every stop is one the keyboard can also reach, which is what
866 // keeps "0.35" the number the file writes.
867 let steps = value / COLOR_STEP;
868 assert!(
869 (steps - steps.round()).abs() < 1e-3,
870 "{label}: {value} is off the {COLOR_STEP} grid"
871 );
872 assert!(
873 (low..=high).contains(&value),
874 "{label}: {value} outside {low}..{high}"
875 );
876 // What the row paints from that value is where the pointer was,
877 // to within the half step the snap costs.
878 let painted = (value - low) / (high - low);
879 let slack = COLOR_STEP / (high - low) / 2. + 1e-4;
880 assert!(
881 (painted - along).abs() <= slack,
882 "{label}: pressed at {along}, paints at {painted}"
883 );
884 }
885 }
886
887 // The shape the card opens in, inside a 360 px window: the graph, the two
888 // main sliders (each a label line, a gap and a track), the More fold, the
889 // compare line for a first clip, and the reset line. An open fold adds the
890 // two rare sliders below that, and the card grows past 360 px.
891 let (title, status, gaps, padding) = (17., 17., 6. * 2., 24.);
892 let slider = crate::ui::type_scale::LABEL_ROW_PX + 4. + HIT_MIN;
893 let rows = 2. * slider + 2. * HIT_MIN;
894 assert!(
895 title + status + HIST_H + rows + gaps + padding + CONTROL_H + 4. <= 360.,
896 "card too tall"
897 );
898 const {
899 assert!(COLOR_W <= 640., "card too wide");
900 }
901 // What is dragged is the whole track's height, not the 4 px the bar is
902 // drawn as (WCAG 2.5.8) -- the same split the ruler makes.
903 const {
904 assert!(KEYS_ROW_H >= HIT_MIN);
905 }
906}
907
908/// The graph over the sliders is the frame the grade already went through,
909/// so it has to count what is actually in those bytes -- the luma of each
910/// pixel, read off BGRA on the wire.
911#[test]
912fn the_histogram_counts_the_luma_of_the_frame_it_is_handed() {
913 // Half pure red, half mid grey: two known lumas, in two known bins.
914 let (w, h) = (64usize, 64usize);
915 let mut frame = Vec::with_capacity(w * h * 4);
916 for _ in 0..h {
917 for col in 0..w {
918 match col < w / 2 {
919 true => frame.extend_from_slice(&[0, 0, 255, 255]),
920 false => frame.extend_from_slice(&[128, 128, 128, 255]),
921 }
922 }
923 }
924 let bins = histogram(&frame);
925 let half = (w * h / 2) as u32;
926 // 64 bins over 256 codes. Pure red's luma is 0.2126 * 255, which is 53, in
927 // bin 13; grey 128 is exactly half, bin 32.
928 assert_eq!(bins[13], half, "the red half lands at luma 53");
929 assert_eq!(bins[32], half, "and the grey half sits mid-range");
930 assert_eq!(
931 bins.iter().filter(|&&n| n > 0).count(),
932 2,
933 "nothing else is counted"
934 );
935 // Nothing is counted twice and nothing is dropped: this frame is small
936 // enough to be read whole.
937 assert_eq!(bins.iter().sum::<u32>(), (w * h) as u32);
938
939 // A grade shifts it, which is the whole point of drawing it: the same
940 // frame darkened lands in lower bins.
941 let darker: Vec<u8> = frame.iter().map(|b| b / 2).collect();
942 let bins = histogram(&darker);
943 assert_eq!(bins[6], half, "red 127 is luma 26, bin 6");
944 assert_eq!(bins[16], half, "grey 64 is bin 16");
945
946 // A real frame is subsampled: a 1080p one is read every 253rd pixel, so
947 // the shape costs a thousandth of the reads and still counts thousands.
948 let big = vec![200u8; 1920 * 1080 * 4];
949 let bins = histogram(&big);
950 let counted = bins.iter().sum::<u32>();
951 let pixels = 1920 * 1080usize;
952 let expected = pixels.div_ceil(pixels / HIST_SAMPLES) as u32;
953 assert_eq!(counted, expected, "every strided pixel counted, once");
954 assert!(
955 (HIST_SAMPLES as u32..=HIST_SAMPLES as u32 + 64).contains(&counted),
956 "{counted} samples is not the budget"
957 );
958 assert_eq!(bins[200 * HIST_BINS / 256], counted, "all in one bin");
959
960 // An empty buffer is a flat graph rather than a panic: the card is open
961 // before the first frame is pumped.
962 assert_eq!(histogram(&[]), [0; HIST_BINS]);
963}
964
965/// Mute and level are one control with two states, and the whole point is
966/// that mute keeps the level: the user gets back what they had, not 100%.
967#[test]
968fn muting_keeps_the_level_it_comes_back_to() {
969 let mut volume = Volume::default();
970 assert_eq!(volume.gain(), 1.0);
971 assert_eq!(volume.label(), "Vol 100%");
972
973 // Four presses down, then muted: the gain is silence but the level is
974 // still what it was, and the button keeps saying so.
975 for _ in 0..4 {
976 volume.step(false);
977 }
978 assert_eq!(volume.gain(), 0.8);
979 volume.muted = true;
980 assert_eq!(volume.gain(), 0.0);
981 assert_eq!(volume.label(), "Muted 80%");
982
983 // Turning it down while muted stays muted -- the one thing a mute
984 // button must never do is get louder because you asked for quieter.
985 volume.step(false);
986 assert_eq!(volume.gain(), 0.0);
987 assert!(volume.muted);
988
989 // Unmute returns to the level, including the step taken while silent.
990 volume.muted = false;
991 assert_eq!(volume.gain(), 0.75);
992}
993
994/// The whole transport in one place: the clock keeps running past the last
995/// frame (wall time takes over at audio EOF), so "the clock is going" is
996/// not "this is playing" -- and a button that read the clock showed Pause
997/// on a timeline that had stopped moving. Ended is its own state, it draws
998/// Play, and the next press starts over from the top.
999#[test]
1000fn a_played_out_timeline_is_not_playing_and_the_next_press_starts_it_over() {
1001 assert_eq!(transport(true, false), Transport::Playing);
1002 assert_eq!(transport(false, false), Transport::Paused);
1003 // The transition the bug was about: the clock is still running and the
1004 // decoder is finished. Played out wins, however the clock reads.
1005 assert_eq!(transport(true, true), Transport::Ended);
1006 assert_eq!(transport(false, true), Transport::Ended);
1007
1008 // What the button draws, in each state. Two bars only while it moves.
1009 assert!(Transport::Playing.is_playing());
1010 for state in [Transport::Paused, Transport::Ended, Transport::Stopped] {
1011 assert!(!state.is_playing(), "{state:?} must draw the Play triangle");
1012 }
1013
1014 // And what a press does: start over at the end, plain toggle before it,
1015 // nothing with no timeline. Same answer for the key and the button --
1016 // both come through `Player::toggle_or_restart`.
1017 assert!(Transport::Ended.restarts());
1018 for state in [Transport::Playing, Transport::Paused, Transport::Stopped] {
1019 assert!(!state.restarts(), "{state:?} must toggle, not reseek");
1020 }
1021}
1022
1023/// The half of `Ended` the eye cannot see: the clock. Wall time takes over
1024/// at the last frame and nothing used to stop it, so the playhead walked off
1025/// the end of the timeline in real time -- and the playhead is what a cut, a
1026/// paste, an insert and the analyser all act at. `pump` pauses on the
1027/// crossing; this is the engine contract that rests on, driven exactly as
1028/// the pump drives it.
1029#[test]
1030fn the_clock_stops_where_the_timeline_does_and_the_end_still_restarts() {
1031 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1032 session.set_gain(0.0);
1033 // Start a breath short of the end: the tail is what this is about, and
1034 // playing the whole five seconds would say nothing more.
1035 session.seek(4.8);
1036 session.play();
1037
1038 // The pump's own loop -- tick, drain, ask where the transport is --
1039 // with a deadline so a fixture that will not decode fails as a failure
1040 // rather than as a hang. The first picture of a seek is a debug-build
1041 // software decode, and on a box whose cores are saturated by other work
1042 // it has taken 40-60s to arrive, so the bound is generous: the clock
1043 // running on wall time meanwhile is by design (see `halt_at_end`).
1044 let deadline = Instant::now() + Duration::from_secs(120);
1045 let mut state = transport(session.is_playing(), session.is_eos());
1046 while state != Transport::Ended {
1047 assert!(
1048 Instant::now() < deadline,
1049 "never reached the end of a 5s file"
1050 );
1051 session.tick();
1052 while session.try_frame().is_some() {}
1053 state = transport(session.is_playing(), session.is_eos());
1054 }
1055
1056 // What `pump` does on the crossing, and the whole point of it: the
1057 // position holds still afterwards instead of counting on past the end,
1058 // and it holds still *on the out point* -- where the timecode and the
1059 // playhead have been showing it. The clock at the moment the end is
1060 // recognised is not that: a slow renderer reaches EOF with the clock
1061 // seconds past the timeline, which is why this repositions rather than
1062 // only freezing.
1063 session.halt_at_end();
1064 let stopped_at = session.now();
1065 assert_eq!(stopped_at, session.timeline_duration());
1066 std::thread::sleep(Duration::from_millis(250));
1067 assert_eq!(session.now(), stopped_at, "the clock kept running past EOF");
1068 // And it is still the end: pausing must not spend the state the glyph
1069 // and the restart both read.
1070 assert!(session.is_eos());
1071 assert_eq!(
1072 transport(session.is_playing(), session.is_eos()),
1073 Transport::Ended
1074 );
1075
1076 // The restart path off that frozen end, which is what the button and
1077 // the play key do from `Ended`: back to the top, and running.
1078 session.seek(0.);
1079 session.play();
1080 assert!(!session.is_eos(), "a seek revives the session");
1081 assert!(session.now() < 1.0);
1082 assert_eq!(
1083 transport(session.is_playing(), session.is_eos()),
1084 Transport::Playing
1085 );
1086 session.pause();
1087}
1088
1089/// Both ends hold under a key held down: the ABI only accepts `0.0..=1.0`,
1090/// and a wrapped step count would hand it something else.
1091#[test]
1092fn the_volume_stops_at_both_ends() {
1093 let mut volume = Volume::default();
1094 for _ in 0..40 {
1095 volume.step(true);
1096 }
1097 assert_eq!(volume.gain(), 1.0);
1098 assert_eq!(volume.steps, Volume::MAX_STEPS);
1099
1100 for _ in 0..40 {
1101 volume.step(false);
1102 }
1103 assert_eq!(volume.gain(), 0.0);
1104 assert_eq!(volume.label(), "Vol 0%");
1105
1106 // Silent by the level rather than by the flag is still not muted: the
1107 // button says which, because only one of them survives a step up.
1108 assert!(!volume.muted);
1109 volume.step(true);
1110 assert_eq!(volume.gain(), 0.05);
1111}
1112
1113#[test]
1114fn the_budget_is_the_one_number_the_engine_gets() {
1115 // One explicit rate, always: the Auto/Low/Medium/High/Exact ladder is
1116 // gone, so there is nothing left that sends `None` and lets the encoder
1117 // pick a figure the row never showed.
1118 let settings = export_settings(
1119 6_500_000,
1120 Format::Mp4,
1121 DEFAULT_AUDIO_KBPS,
1122 EncoderSeat::Auto,
1123 );
1124 assert_eq!(settings.bitrate, Some(6_500_000));
1125 assert!(!settings.exact, "the copy path is off this surface");
1126 assert_eq!(settings.audio_kbps, Some(DEFAULT_AUDIO_KBPS));
1127 assert_eq!(settings.seat, EncoderSeat::Auto);
1128 // The picked format travels, or the moment would be a picture of a
1129 // choice the engine never hears about.
1130 for format in [Format::Mp4, Format::Wav, Format::Flac] {
1131 assert_eq!(
1132 export_settings(BPS_MIN, format, DEFAULT_AUDIO_KBPS, EncoderSeat::Auto).format,
1133 format
1134 );
1135 }
1136 // The lever's bounds are the engine's own (`MIN_BITRATE`,
1137 // `MAX_EXPLICIT_BITRATE`), so no reachable number is silently rewritten.
1138 assert_eq!(BPS_MIN, 100_000);
1139 assert_eq!(BPS_MAX, 50_000_000);
1140 // The default the lever opens on is the engine's automatic figure for
1141 // the picture that is open -- never the 0 Mbps the old `custom_mbps: 0`
1142 // put on screen.
1143 assert_eq!(auto_bps(1920, 1080, 30.), 6_220_800);
1144 assert_eq!(auto_bps(160, 120, 15.), BPS_MIN, "a tiny picture floors");
1145 assert!(
1146 auto_bps(7680, 4320, 60.) <= 20_000_000,
1147 "and a huge one caps"
1148 );
1149 for bps in [auto_bps(1920, 1080, 30.), auto_bps(320, 240, 24.)] {
1150 assert!((BPS_MIN..=BPS_MAX).contains(&bps));
1151 }
1152}
1153
1154#[test]
1155fn a_budget_is_said_four_ways_and_lands_inside_the_engines_range() {
1156 // A minute of film with 256 kbps of sound under it: the span and the
1157 // sound are what a *size* has to be converted through.
1158 let (seconds, audio) = (60., 256_000);
1159 // A rate in its own units, and a bare number in the row's (Mbps).
1160 assert_eq!(parse_budget("6.5M", seconds, audio), Some(6_500_000));
1161 assert_eq!(parse_budget("6.5", seconds, audio), Some(6_500_000));
1162 assert_eq!(parse_budget("6.5 mbps", seconds, audio), Some(6_500_000));
1163 assert_eq!(parse_budget("12M", seconds, audio), Some(12_000_000));
1164 // A sub-Mbps ask is a rate this row can say: 850 kbps travels as itself.
1165 assert_eq!(parse_budget("850k", seconds, audio), Some(850_000));
1166 // Under the engine's floor it lands *on* the floor -- clamped, and shown
1167 // clamped in the same keystroke.
1168 assert_eq!(parse_budget("50k", seconds, audio), Some(BPS_MIN));
1169 assert_eq!(parse_budget("2500k", seconds, audio), Some(2_500_000));
1170 // `G` is a target file size: 1.2 GB over a minute is 160 Mbit/s of file,
1171 // less the sound -- past the ceiling, so the ceiling is what is written.
1172 assert_eq!(parse_budget("1.2G", seconds, audio), Some(BPS_MAX));
1173 // ...and over an hour of film the same size is a rate that fits: the
1174 // sound's own bits come out of it, which is why it is not 2.67 Mbps.
1175 let hour = parse_budget("1.2G", 3600., audio).expect("a size over an hour");
1176 assert_eq!(hour, (1.2e9 * 8. / 3600.) as u64 - audio);
1177 // A size with no film to spread it over is not a rate.
1178 assert_eq!(parse_budget("1.2G", 0., audio), None);
1179 // Everything else is refused rather than guessed at, and the field stays
1180 // open on it.
1181 for text in ["", " ", "abc", "-4", "0", "M", "6.5.5"] {
1182 assert_eq!(parse_budget(text, seconds, audio), None, "{text}");
1183 }
1184 // Whatever is typed, what comes out is inside the engine's clamp.
1185 for text in ["1k", "999G", "50M", "51M", "0.5"] {
1186 if let Some(bps) = parse_budget(text, seconds, audio) {
1187 assert!((BPS_MIN..=BPS_MAX).contains(&bps), "{text} -> {bps}");
1188 }
1189 }
1190}
1191
1192#[test]
1193fn the_budget_lever_steps_by_a_tenth_and_a_whole_megabit() {
1194 // A notch is 0.1 Mbps and a notch with shift is 1 -- the readout has one
1195 // decimal, so the fine step is the smallest move it can show.
1196 assert_eq!(BPS_FINE, 100_000);
1197 assert_eq!(BPS_COARSE, 1_000_000);
1198 assert_eq!(rate_label(6_000_000 + BPS_FINE), "6.1");
1199 assert_eq!(rate_label(6_000_000 + BPS_COARSE), "7.0");
1200 // Forty-nine coarse notches carry the range with change left in the
1201 // fiftieth, which is what a wheel is for; the fine step would take five
1202 // hundred.
1203 assert_eq!((BPS_MAX - BPS_MIN) / BPS_COARSE, 49);
1204 // The step arithmetic itself, as `Player::nudge_budget` does it: a
1205 // saturating walk that stops at both ends rather than wrapping.
1206 let step = |at: u64, steps: i32, coarse: bool| {
1207 let by = i64::from(steps) * if coarse { BPS_COARSE } else { BPS_FINE } as i64;
1208 ((at as i64 + by).max(0) as u64).clamp(BPS_MIN, BPS_MAX)
1209 };
1210 assert_eq!(step(6_000_000, 5, false), 6_500_000);
1211 assert_eq!(step(6_000_000, -1, true), 5_000_000);
1212 assert_eq!(step(BPS_MIN, -9, true), BPS_MIN, "the floor holds");
1213 assert_eq!(step(BPS_MAX, 9, true), BPS_MAX, "and so does the ceiling");
1214}
1215
1216/// The sheet itself, read off its own source: presets first, then the range,
1217/// the destination and the summary, with the detailed settings behind the one
1218/// "More settings" disclosure -- and the scrim stops at the time band.
1219/// A source scan, like the stance guards above it -- this binary has no
1220/// `TestAppContext` to render a card and measure it.
1221#[test]
1222fn the_export_sheet_reads_presets_range_destination_summary_then_more() {
1223 let card = src_text("ui/cards/export.rs");
1224 let body = fn_body("sheet_settings");
1225 let order = [
1226 "self.sheet_preset(cx)",
1227 "self.sheet_destination(cx)",
1228 "self.sheet_range(cx)",
1229 "self.sheet_summary(",
1230 "more_toggle(more, cx)",
1231 "more.then(|| self.sheet_more(cx))",
1232 ];
1233 let at: Vec<usize> = order
1234 .iter()
1235 .map(|part| body.find(part).unwrap_or_else(|| panic!("{part} is not on the sheet")))
1236 .collect();
1237 assert!(at.windows(2).all(|w| w[0] < w[1]), "the sheet's sections are out of order");
1238 // The body scrolls on a short window rather than the sheet moving down.
1239 assert!(body.contains("overflow_y_scroll"), "a short sheet cannot scroll");
1240 // The disclosure is the folds file's own, so it is remembered.
1241 assert!(card.contains("toggle_fold(&mut this.folds, EXPORT_MORE_FOLD)"));
1242 assert!(card.contains(".child(\"Details\")"));
1243 // The panel is the dock's third tab, in flow: no scrim, no absolute box.
1244 let mount = fn_body("export_panel");
1245 assert!(!mount.contains("absolute()") && !mount.contains("scrim"));
1246 assert!(src_text("ui/dock_stance.rs").contains("player.export_panel(cx)"));
1247 assert!(src_text("ui/dock_stance.rs").contains("\"dock-tab-export\""));
1248 // Every press has a pointer door as well as a key.
1249 for id in [
1250 "export-confirm",
1251 "export-range-whole",
1252 "export-range-marks",
1253 "export-name",
1254 "export-folder",
1255 "export-destination",
1256 "export-preset",
1257 "export-overwrite-replace",
1258 "export-overwrite-keep",
1259 "export-overwrite-cancel",
1260 "export-cancel",
1261 "export-retry",
1262 "export-show-file",
1263 "export-play",
1264 ] {
1265 assert!(card.contains(&format!("\"{id}\"")), "{id} is on no control");
1266 }
1267 const {
1268 assert!(KEYS_ROW_H >= HIT_MIN);
1269 }
1270}
1271
1272/// The shipped defect: a chord the export surface answers (`n`) also reached
1273/// the room's keymap under it and toggled the timeline snap. The fix is that
1274/// the moment owns the keyboard while it is up -- every stroke is consumed,
1275/// and escape retreats one step at a time (the field, then the moment).
1276#[test]
1277fn a_chord_the_export_moment_answers_never_reaches_the_room() {
1278 // The leak was real: `n` is the room's own snap chord.
1279 let keymap = keymap::Keymap::defaults();
1280 assert_eq!(keymap.display(keymap::ActionId::ToggleSnap), "N");
1281 // One door, and it is asked *before* the stance's modal guard.
1282 let cards = src_text("player/cards.rs");
1283 assert!(
1284 cards.contains("if self.export_moment_key(key, shift, cx)"),
1285 "param_card_key no longer routes the moment's own strokes"
1286 );
1287 let body = fn_body("export_moment_key");
1288 let (guard, rest) = body
1289 .split_once("return false;")
1290 .expect("the one early out is `the moment is not open`");
1291 assert!(
1292 guard.contains("!self.export_open"),
1293 "the only way out of this handler must be that no moment is up"
1294 );
1295 assert!(
1296 !rest.contains("return false"),
1297 "a stroke fell through to the room's keymap again -- that is the `n` \
1298 toggling snap defect"
1299 );
1300 // Escape retreats one step at a time (DESIGN.md:146): the question and
1301 // the field are closed inside their own branches, the sheet only once
1302 // both are shut.
1303 let (asking, rest) = rest
1304 .split_once("return true;")
1305 .expect("the question branch returns before the chords below it");
1306 assert!(asking.contains("ESCAPE => self.answer_overwrite(Overwrite::Cancel, cx)"));
1307 let (typing, closed) = rest
1308 .split_once("return true;")
1309 .expect("the typing branch returns before the chords below it");
1310 assert!(
1311 typing.contains("self.budget_edit = None"),
1312 "esc leaves the field"
1313 );
1314 assert!(
1315 closed.contains("self.leave_sheet_face()"),
1316 "then esc closes the moment"
1317 );
1318 // Its chords, all of them consumed here rather than by the keymap.
1319 for chord in [
1320 "\"d\"",
1321 "\"n\"",
1322 "\"e\"",
1323 "\"enter\"",
1324 "\"left\"",
1325 "\"right\"",
1326 "\",\"",
1327 ] {
1328 assert!(closed.contains(chord), "{chord} is not the moment's own");
1329 }
1330}
1331
1332/// "Simplify it, not hide the things": every detailed setting is on the
1333/// sheet behind "Details" -- container and codec, encoder seat (software
1334/// first), bitrate, resolution, bit depth, sound rate, loudness, chapters and
1335/// captions. Each is a labelled row that opens a list of every value.
1336#[test]
1337fn details_holds_every_export_setting_as_direct_choices() {
1338 let more = fn_body("sheet_more");
1339 for (what, needle) in [
1340 ("the container", "ExportRow::Container"),
1341 ("the codec", "ExportRow::Codec"),
1342 ("the encoder", "ExportRow::Seat"),
1343 ("the bitrate", "ExportRow::Bitrate"),
1344 ("the size", "ExportRow::Size"),
1345 ("the bit depth", "ExportRow::Depth"),
1346 ("the sound rate", "ExportRow::Kbps"),
1347 ("the loudness", "ExportRow::Loudness"),
1348 ("the captions", "ExportRow::Captions"),
1349 ("the chapters", "s.chapters().len()"),
1350 ] {
1351 assert!(more.contains(needle), "Details lost {what}");
1352 }
1353 for cycle in ["cycle_export_picture", "cycle_audio_kbps", "cycle_encoder"] {
1354 assert!(!more.contains(cycle), "{cycle} is a press-to-cycle row again");
1355 }
1356 assert!(
1357 crate::export_ui::ENCODER_SEATS[0] == EncoderSeat::Software,
1358 "the software seat is not listed first"
1359 );
1360 let seats = fn_body("export_choices");
1361 assert!(seats.contains("ENCODER_SEATS"));
1362 // Hardware stays on the list, named plainly, and is never the default.
1363 assert!(crate::export_ui::seat_plain(EncoderSeat::Hardware).contains("GPU"));
1364}
1365
1366/// The budget is a video setting -- the engine's own word is that the bitrate
1367/// settings "mean nothing to the audio-only ones". Its Details row stays in
1368/// place (nothing shifts) but dims with its reason for a file with no picture,
1369/// and both doors into the number answer the same gate: a row the moment does
1370/// not show cannot have been changed.
1371#[test]
1372fn the_budget_row_and_its_doors_are_video_only() {
1373 let body = fn_body("sheet_more");
1374 // A sound-only file has no picture settings at all: the video group's rows
1375 // (the bitrate among them) are built only `if video`.
1376 let gate = body.find("if video {").expect("the picture rows are gated on a picture");
1377 assert!(
1378 body.find("\"export-d-bitrate\"").is_some_and(|at| at > gate),
1379 "the bitrate row is not behind the video gate"
1380 );
1381 // The `n` door: the moment's chord and the row's own click both funnel
1382 // through `edit_budget`, so its gate is the one gate -- and it must sit
1383 // ahead of the field it guards.
1384 let typing = fn_body("edit_budget");
1385 let (gate, _) = typing
1386 .split_once("self.budget_edit = Some")
1387 .expect("the typing field still opens");
1388 assert!(
1389 gate.contains("!self.format.has_video()"),
1390 "`n` opens the budget field for a format that writes no picture"
1391 );
1392 // The value itself: arrows, `+`/`-` and the wheel all funnel through
1393 // `nudge_budget` -- a lever nothing shows does not move either.
1394 let lever = fn_body("nudge_budget");
1395 let (gate, _) = lever
1396 .split_once("self.custom_bps =")
1397 .expect("the lever still sets the budget");
1398 assert!(
1399 gate.contains("!self.format.has_video()"),
1400 "the hidden budget lever moves again"
1401 );
1402}
1403
1404/// Exporting over an existing file must warn first, "same pattern as the
1405/// exit guard" (user 2026-09-11: "not just save but export too -- an export
1406/// named like an existing video overrides it"). The question as a value: a
1407/// target that is there and not this window's own asks; anything else just
1408/// writes.
1409#[test]
1410fn only_a_foreign_existing_target_asks_before_an_export_overwrites_it() {
1411 assert!(crate::Player::export_asks(true, false));
1412 assert!(
1413 !crate::Player::export_asks(false, false),
1414 "nothing there to clobber"
1415 );
1416 assert!(!crate::Player::export_asks(false, true));
1417 assert!(
1418 !crate::Player::export_asks(true, true),
1419 "a re-export over this window's own output is silent"
1420 );
1421}
1422
1423/// The guard's wiring: asked after every refusal (an export that cannot run
1424/// never asks), before the worker starts; the moment closes with the asking
1425/// (it overlays the strip the plate rises on); a started export marks the
1426/// target this window's own so a re-export stays silent; and the plate's
1427/// `enter` confirms the target before re-entering the door.
1428#[test]
1429fn the_export_overwrite_question_owns_the_door_and_the_keyboard() {
1430 let body = fn_body("start_export");
1431 assert!(
1432 body.contains("self.export_needs_answer()"),
1433 "start_export never asks before overwriting"
1434 );
1435 // The call is hoisted above the `&mut self.session` borrow (E0502); what
1436 // must sit after the refusals is the *check* of its answer.
1437 let (fences, rest) = body
1438 .split_once("if overwrite {")
1439 .expect("the guard's answer is never checked");
1440 assert!(
1441 fences.contains("format_refusal"),
1442 "the question comes before the refusals: a refused export would ask"
1443 );
1444 let (guard, started) = rest
1445 .split_once("export_to_with")
1446 .expect("the worker is still started from start_export");
1447 assert!(
1448 guard.contains("self.export_ask = true") && !guard.contains("self.close_card()"),
1449 "the question is asked inside the sheet, which stays up"
1450 );
1451 assert!(
1452 started.contains("self.export_known = Some(self.export_path.clone())"),
1453 "a started export does not mark the target this window's own"
1454 );
1455 let stance = src_text("ui/stance.rs");
1456 let (_, handler) = stance
1457 .split_once("if this.export_ask {")
1458 .expect("the export question is up with no key answering it");
1459 for answer in ["Overwrite::Replace", "Overwrite::KeepBoth", "Overwrite::Cancel"] {
1460 assert!(handler.contains(answer), "the question's keys lost {answer}");
1461 }
1462 let answer = fn_body("answer_overwrite");
1463 let (replace, _) = answer
1464 .split_once("Overwrite::KeepBoth")
1465 .expect("Keep both is an answer");
1466 assert!(
1467 replace.contains("self.export_known = Some(self.export_path.clone())"),
1468 "Replace does not confirm the target before re-entering the door"
1469 );
1470 assert!(answer.contains("unique_path(&self.export_path"));
1471 let sheet = fn_body("sheet_overwrite");
1472 assert!(
1473 sheet.contains("file_name(&self.export_path)"),
1474 "the question does not name the file it would overwrite"
1475 );
1476}
1477
1478/// The export panel's handler swallows every stroke so none reaches the room
1479/// under it; Settings has no Export tab.
1480#[test]
1481fn the_moment_and_the_room_wear_the_same_export_chords() {
1482 let handler = fn_body("export_moment_key");
1483 assert!(handler.contains("\"e\" | \"enter\" => self.start_export"));
1484 let settings = src_text("ui/settings_stance.rs");
1485 assert!(!settings.contains("SettingsTab::Export"), "Settings grew an Export tab again");
1486}
1487
1488/// The Sound row: what it offers, and that the pick travels to the engine
1489/// for a *video* export as much as for an MP3 -- both files carry sound, so
1490/// a row that only reached the audio formats would be half a control.
1491#[test]
1492fn the_sound_row_carries_its_rate_into_both_kinds_of_file() {
1493 // Sorted and unique, so a row that says "b for the next one" is stepping
1494 // up and not shuffling.
1495 assert!(AUDIO_KBPS.windows(2).all(|w| w[0] < w[1]));
1496 // The untouched figure is one of the offered rows, or the first press of
1497 // `b` would jump somewhere nobody chose.
1498 assert!(AUDIO_KBPS.contains(&DEFAULT_AUDIO_KBPS));
1499 // ...and it is what this program wrote before the row existed: the
1500 // export of a user who never opens it must not change under them.
1501 assert_eq!(DEFAULT_AUDIO_KBPS, 256);
1502 for format in [Format::Mp4, Format::Av1, Format::Hevc, Format::Mp3] {
1503 for kbps in AUDIO_KBPS {
1504 assert_eq!(
1505 export_settings(BPS_MIN, format, kbps, EncoderSeat::Auto).audio_kbps,
1506 Some(kbps),
1507 "{format:?} at {kbps} kbps"
1508 );
1509 }
1510 }
1511 // The pointer's door to the same field: one row per rate, the one in
1512 // force marked exactly once, and every row's small print short enough
1513 // to survive `MENU_W`'s truncation (the resolution list's own rule).
1514 let rows = audio_rate_choices(DEFAULT_AUDIO_KBPS);
1515 assert_eq!(rows.len(), AUDIO_KBPS.len());
1516 assert_eq!(rows.iter().filter(|(.., picked)| *picked).count(), 1);
1517 for ((choice, label, detail, picked), kbps) in rows.iter().zip(AUDIO_KBPS) {
1518 assert_eq!(*choice, Choice::AudioRate(kbps));
1519 assert_eq!(label.as_ref(), format!("{kbps} kb/s"));
1520 assert!(detail.chars().count() <= 26, "{detail} is too long to read");
1521 assert_eq!(*picked, kbps == DEFAULT_AUDIO_KBPS);
1522 }
1523 // A rate no row holds marks none of them, rather than the wrong one.
1524 assert!(audio_rate_choices(7).iter().all(|(.., picked)| !picked));
1525}
1526
1527/// The colour field (`ColorEdit`), the transition field's free-text sibling:
1528/// every spelling of one colour lands on the same pair, the pair is what the
1529/// row shows back as a hex, and text that is not a colour is refused in words
1530/// while the field goes on holding it -- never dropped in silence, never
1531/// guessed at, and never cleared by the refusal itself.
1532#[test]
1533fn a_typed_colour_is_read_in_every_spelling_and_anything_else_is_refused() {
1534 use engine::decode::{viz_color_from_text, viz_color_hex};
1535
1536 // One colour in every spelling the field takes: red as `#RRGGBB`, as bare
1537 // digits, as `rgb(..)`, and as `rgba(..)` with the alpha dropped. Two
1538 // spellings of one colour landing on different pairs would be a field
1539 // whose colour depends on how it was written.
1540 let red = viz_color_from_text("#FF0000").expect("red is a colour");
1541 for text in ["#FF0000", "FF0000", "rgb(255,0,0)", "rgba(255,0,0,255)"] {
1542 let mut edit = ColorEdit::new("");
1543 for c in text.chars() {
1544 edit.typed(c);
1545 }
1546 assert_eq!(edit.commit(), Some(red), "{text}");
1547 assert_eq!(edit.refusal, None, "{text} is a colour, not a refusal");
1548 }
1549
1550 // The round trip through what the row displays: the hex the row shows
1551 // reads back as the same pair, so opening the field on it and pressing
1552 // enter changes nothing. A seed taken from anywhere else -- or a hex
1553 // spelled by something other than the field's own reader -- shows up here.
1554 let hex = viz_color_hex(red.0, red.1);
1555 let mut edit = ColorEdit::new(&hex);
1556 assert_eq!(edit.text, hex, "the field opens on the row's own line");
1557 assert!(edit.detail().contains("enter commits"));
1558 assert_eq!(edit.commit(), Some(red));
1559 assert_eq!(edit.refusal, None);
1560
1561 // Text that is not a colour: refused in words that say what a colour
1562 // looks like, and the text survives the refusal -- a refusal that ate what
1563 // was typed would make the next try retype all of it.
1564 let mut edit = ColorEdit::new("");
1565 edit.typed('z');
1566 edit.typed('z');
1567 assert_eq!(edit.commit(), None);
1568 let why = edit.refusal.clone().expect("a refusal, not a silence");
1569 assert!(
1570 why.contains("#RRGGBB"),
1571 "the refusal says what a colour is: {why}"
1572 );
1573 assert_eq!(edit.text, "zz", "the refusal keeps the text it refused");
1574 assert!(
1575 edit.detail().contains("zz▏"),
1576 "the caret stays in the buffer"
1577 );
1578 // ...and the next stroke clears it: that reason described the text that is
1579 // no longer there.
1580 edit.typed('0');
1581 assert_eq!(edit.refusal, None);
1582 assert_eq!(edit.text, "zz0");
1583
1584 // Backspace erases the last character and the refusal with it, and the
1585 // buffer is capped out loud rather than growing without bound off a held
1586 // key.
1587 let mut edit = ColorEdit::new(&hex);
1588 edit.backspace();
1589 assert_eq!(edit.text.chars().count(), hex.chars().count() - 1);
1590 for _ in 0..64 {
1591 edit.typed('f');
1592 }
1593 assert_eq!(edit.text.chars().count(), 32);
1594 assert!(edit.refusal.is_some(), "the stroke past the cap says so");
1595
1596 // Why the commit compares before it writes: the field opens seeded with
1597 // `viz_color_hex(now)`, and that hex reads back as a *different* pair for
1598 // a good share of inks (the engine's round-trip canary counts 47 053 of
1599 // 65 536 exact), so "write whatever the parse gave" would take an undo
1600 // step for the colour the row was already showing. The fact is held here;
1601 // the gate that reads it is pinned below.
1602 let mut inexact = 0;
1603 for hue in 0..=255u8 {
1604 for sat in [0u8, 64, 160, 255] {
1605 let seed = viz_color_hex(hue, sat);
1606 match viz_color_from_text(&seed) {
1607 // Exact: entering the seed is already a no-op for the write
1608 // gate, whatever the gate says.
1609 Some(pair) if pair == (hue, sat) => {}
1610 // Inexact: this is the case the gate exists for -- without it
1611 // every one of these takes a committing write on an untouched
1612 // colour.
1613 Some(_) => inexact += 1,
1614 None => panic!("the row's own hex must be readable back: {seed}"),
1615 }
1616 }
1617 }
1618 assert!(
1619 inexact > 0,
1620 "no ink round-trips inexactly -- the commit's no-op gate would be dead weight"
1621 );
1622
1623 // The gate itself, in the door that has it (`Player::commit_viz_hex`): the
1624 // parse, then the comparison with the picked slot's own colour, and the
1625 // write only past it.
1626 let body = fn_body("commit_viz_hex");
1627 let gate = body
1628 .split_once("hue_sat(paint)")
1629 .expect("the commit no longer compares with the colour on the slot")
1630 .1;
1631 assert!(
1632 gate.contains("write_viz_hs("),
1633 "the commit writes before it has compared, so the row's own seed is an edit"
1634 );
1635}
1636
1637/// The look family's writes arm autosave, and therefore the ledger's `unsaved`
1638/// ghost and `Player::close_needs_answer`, which read the same flag: a colour
1639/// picked in the Clip tab that armed nothing could be closed away with no
1640/// prompt and no autosave.
1641///
1642/// A scan and not a drive: every one of these doors needs a `Player` and a
1643/// gpui `Context`, and this crate has no window harness (`tests/view.rs`'s own
1644/// note). What a scan can hold is the three doors themselves -- the two the
1645/// whole paint family shares (`set_viz_paint_with` is where the wheel, the
1646/// steppers and a typed colour all land) and the two writes that do not go
1647/// through it (the style chips and the `Fast` chip, which write
1648/// `clip.visualizer`). Pre-fix none of the three armed anything while every
1649/// other engine-writing door did (`write_color`, `write_transform`,
1650/// `set_eq`, the trim/place/fade doors).
1651#[test]
1652fn a_visualizer_look_write_arms_autosave() {
1653 for name in ["set_viz_style", "toggle_viz_flag"] {
1654 let body = fn_body(name);
1655 assert!(
1656 body.contains("session.set_visualizer"),
1657 "{name} no longer writes the clip's look at all"
1658 );
1659 assert!(
1660 body.contains("mark_dirty()"),
1661 "{name} writes a look and arms nothing"
1662 );
1663 }
1664 let body = fn_body("set_viz_paint_with");
1665 // The arm rides the write that took, not the call: a no-op press (the
1666 // colour under the hand already) is not an edit, and the ghost must stay
1667 // off it.
1668 let took = body
1669 .split_once("if took {")
1670 .expect("the paint door writes through a taken-write gate")
1671 .1;
1672 assert!(
1673 took.contains("mark_dirty()"),
1674 "the arm is outside the write gate, so a no-op press would dirty the project"
1675 );
1676 assert!(
1677 took.contains("reset_after_reseek()"),
1678 "the arm replaced the reseek bookkeeping instead of joining it"
1679 );
1680}
1681
1682/// The subtitle style card's caption animation rows write the project's caption style, so the
1683/// door arms autosave on the engine's own "it moved" answer, and every row has a keyboard step.
1684#[test]
1685fn the_caption_style_rows_write_the_project_and_step_from_the_keyboard() {
1686 let body = fn_body("edit_caption_style");
1687 assert!(body.contains("set_caption_style(cs)") && body.contains("mark_dirty()"));
1688 let step = fn_body("step_sub_field");
1689 for row in ["SUB_ROW_ANIM", "SUB_ROW_HIGHLIGHT", "SUB_ROW_HL_BOX", "SUB_ROW_UPPERCASE", "SUB_ROW_WORDS"] {
1690 assert!(step.contains(row), "{row} has no keyboard step");
1691 }
1692}
1693
1694/// The rest of the class the visualizer look family belonged to: every other
1695/// door that writes the project from a *click* and so has no action behind it
1696/// to arm autosave ([`Player::act`]'s list is the action doors only). Each arm
1697/// rides its own "the write took" gate -- a pick that changed nothing must not
1698/// dirty the project, or a window nobody has touched would ask to be saved.
1699#[test]
1700fn every_click_door_that_writes_the_project_arms_autosave() {
1701 // The doors the engine answers with a bool *that means "the value
1702 // moved"*: the arm goes inside it.
1703 for name in ["apply_resolution", "apply_frame_rate", "apply_tone"] {
1704 let body = fn_body(name);
1705 assert!(
1706 body.contains("mark_dirty()"),
1707 "{name} writes the project and arms nothing"
1708 );
1709 }
1710 // ...and the one whose bool does not mean that at all: `set_fit` says the
1711 // index existed, and the picker keeps the row already in force clickable,
1712 // so the arm rides the policy having moved -- on the engine's own bool it
1713 // would light the `unsaved` ghost over a project nobody touched.
1714 let body = fn_body("apply_fit");
1715 assert!(
1716 body.contains("fit_of(lane, idx) != fit"),
1717 "apply_fit arms on the engine's own bool again, which a no-op pick also answers true"
1718 );
1719 assert!(body.contains("mark_dirty()"), "apply_fit arms nothing");
1720 // The import path keeps no arm on purpose (the `autosave_armed` rule): its
1721 // only caller is `install_media`, so an arm there could only ever fire for
1722 // a project nobody has touched. The user's door is the two toggles.
1723 let body = fn_body("apply_proxies");
1724 assert!(
1725 body.find("mark_dirty").is_none(),
1726 "apply_proxies arms again -- its only caller is the import path"
1727 );
1728 // The doors whose setter takes no answer back, and the library row's
1729 // removal: the arm rides a local `changed` (or the removal having landed),
1730 // never the call.
1731 for (name, gate) in [
1732 ("apply_sample_rate", "if changed {"),
1733 ("apply_encoder", "if changed {"),
1734 ("toggle_proxies", "if changed {"),
1735 ("toggle_auto_proxies", "if changed {"),
1736 ("remove_source", "Some(Ok(idx))"),
1737 ] {
1738 let body = fn_body(name);
1739 let after = body
1740 .split_once(gate)
1741 .unwrap_or_else(|| panic!("{name} lost the gate its arm rides"))
1742 .1;
1743 assert!(
1744 after.contains("mark_dirty()"),
1745 "{name} arms outside its gate, so a no-op pick would dirty the project"
1746 );
1747 }
1748 // The drag-and-drop family on the timeline: the same class, and the same
1749 // rule. Every one of these doors can answer "nothing happened" -- a clip let
1750 // go where it was picked up, a caption dragged back to the frame it started
1751 // on, a trim, a fade or a `[`/`]` nudge released against the wall the edge
1752 // already stood on, a subtitle row dropped on an overlap ("Not placed") or a
1753 // caption that is not there any more ("Nothing lifted") -- and each one used
1754 // to arm the flag *before* the door was asked, so the ledger's `unsaved`
1755 // ghost, the autosave sidecar and the save-on-close question described a
1756 // project whose content was byte-for-byte what it was.
1757 //
1758 // Each arm now rides its own door's answer, or the one reading the door's
1759 // answer cannot give: a caption's own window before and after the trim
1760 // (`Project::trim_sub` answers `Ok` for an edge released at a wall it already
1761 // stood against) and the ramp's own value before and after the fade
1762 // (`set_fade_*` answer `true` for any index that exists).
1763 for (name, gate) in [
1764 ("move_clip_now", "match moved {"),
1765 (
1766 "place_sub",
1767 "let text = match (self.sub_of_track(track), &mut self.session) {",
1768 ),
1769 ("move_sub", "Some(Ok(())) => {"),
1770 ("lift_sub", "if lifted {"),
1771 ("commit_trim_now", "if trim.lane.kind == LaneKind::Subtitle {"),
1772 ("commit_fade", "if set {"),
1773 ("nudge_cut", "let to = nudge_edge(current, dir, lo, hi);"),
1774 (
1775 "trim_cut_to_playhead",
1776 "let to = frame_at(session.now(), self.fps);",
1777 ),
1778 ] {
1779 let body = fn_body(name);
1780 let (before, after) = body
1781 .split_once(gate)
1782 .unwrap_or_else(|| panic!("{name} lost the gate its arm rides"));
1783 assert!(
1784 after.contains("mark_dirty()"),
1785 "{name} arms outside its gate, so a stroke that changed nothing \
1786 would dirty the project"
1787 );
1788 assert!(
1789 !before.contains("mark_dirty()"),
1790 "{name} still arms ahead of its gate, so a refusal -- or a drag let \
1791 go where it started -- leaves the project looking edited"
1792 );
1793 }
1794 // The history pair is the one place the action table does not arm early:
1795 // the door's own answer ("there was a step to take") is the gate, so `^z`
1796 // with an empty history leaves the flag -- and the close question -- clear.
1797 let act = fn_body("run_action");
1798 for (gate, next) in [
1799 ("if self.undo(cx) {", "ActionId::Redo =>"),
1800 ("if self.redo(cx) {", "ActionId::AddVideoLane =>"),
1801 ] {
1802 let arm = act
1803 .split_once(gate)
1804 .unwrap_or_else(|| panic!("{gate} is gone from the action table"))
1805 .1;
1806 // Cut at the arm *after* this one: "everything from here on" is
1807 // satisfied by the sibling's arm, so deleting Undo's own would ship
1808 // green.
1809 let arm = arm.split_once(next).map_or(arm, |(arm, _)| arm);
1810 assert!(
1811 arm.contains("mark_dirty()"),
1812 "the arm behind `{gate}` arms nothing, so a real step back is \
1813 invisible to autosave, the unsaved ghost and the close question"
1814 );
1815 }
1816 // ...and the answer the arm reads is the door's own: the session's bool, not
1817 // a bare call that would arm for an undo with nothing to undo.
1818 for name in ["undo", "redo"] {
1819 let body = fn_body(name);
1820 assert!(
1821 body.contains("PlaybackSession::") && body.contains("stepped"),
1822 "Player::{name} no longer answers whether there was a step to take"
1823 );
1824 assert!(
1825 !body.contains("mark_dirty"),
1826 "Player::{name} arms its own flag, so the arm in `act` is a second \
1827 one for the same step"
1828 );
1829 }
1830 // The mix card's own doors. Both answer "the value moved" -- a fader
1831 // already against its wall, a ceiling already at its clamp, a limiter
1832 // switch whose value is the one in force are each `false` -- so the arm
1833 // rides the bool, and `nudge_mix` does not arm before the ask the way it
1834 // did: a held arrow key at the top of the fader lit `unsaved`, wrote a
1835 // sidecar and put the close prompt up over a project whose bytes had not
1836 // moved.
1837 let body = fn_body("nudge_mix");
1838 for door in ["set_lane_gain_db", "set_limiter"] {
1839 assert!(
1840 body.contains(door),
1841 "nudge_mix no longer goes through {door}"
1842 );
1843 }
1844 let arm = body
1845 .split_once("if took {")
1846 .expect("the mix arm no longer rides the door's own answer")
1847 .1;
1848 assert!(
1849 arm.contains("mark_dirty()"),
1850 "nudge_mix arms outside its gate, so a fader held against its wall \
1851 would dirty the project"
1852 );
1853 let before = body.split_once("if took {").unwrap().0;
1854 assert!(
1855 !before.contains("mark_dirty()"),
1856 "nudge_mix still arms ahead of the door, so a clamped no-op nudge \
1857 leaves the project looking edited"
1858 );
1859 // The equalizer card's commit, the same rule against a door whose bool is
1860 // the WEAKER of the two shapes: `set_eq` answers "the index was there and
1861 // the curve is finite" and rewrites the very slot it already holds for a
1862 // curve already in force, so the arm needs the comparison too -- the same
1863 // pair of conditions `apply_fit` rides.
1864 let body = fn_body("commit_eq");
1865 let arm = body
1866 .split_once("if moved && session.set_eq(lane, idx, params) {")
1867 .expect("the EQ commit no longer rides the curve having moved and then the door")
1868 .1;
1869 assert!(
1870 arm.contains("mark_dirty()"),
1871 "commit_eq arms outside its gate, so re-committing the curve already \
1872 in force would dirty the project"
1873 );
1874 assert!(
1875 body.contains("session.eq_of(lane, idx).cloned() != params"),
1876 "commit_eq rides the engine's bool alone, which is true for a \
1877 re-commit of the curve already in force"
1878 );
1879 // ...and the reseek bookkeeping rides with the arm, not instead of it.
1880 assert!(
1881 arm.contains("reset_after_reseek()"),
1882 "commit_eq's reseek flags no longer clear on a write that took"
1883 );
1884 let before = body
1885 .split_once("if moved && session.set_eq(lane, idx, params) {")
1886 .unwrap()
1887 .0;
1888 assert!(
1889 !before.contains("mark_dirty()"),
1890 "commit_eq still arms ahead of the door"
1891 );
1892}
1893
1894/// The transition doors, which are the class's other shape: both engine
1895/// setters ([`engine::project::Project::set_transition_out`],
1896/// [`engine::project::Project::crossfade`]) answer `true` for any two
1897/// adjacent clips, snapshot and clamp included -- so a step past the
1898/// successor's length, or a number retyped into the field, wrote the value the
1899/// join already carried and still said yes. [`Player::set_transition_frames`]
1900/// reads the join's own edges back and rides those, and the crossfade side
1901/// compares *both* edges: it writes the anchor's `fade_out` and the
1902/// neighbour's `fade_in`, and a comparison of the anchor alone would miss a
1903/// neighbour-side no-op.
1904#[test]
1905fn a_transition_step_or_a_retyped_number_arms_only_what_moved() {
1906 let body = fn_body("set_transition_frames");
1907 for door in ["set_transition_out", "crossfade"] {
1908 assert!(
1909 body.contains(door),
1910 "the duration doors no longer include {door}"
1911 );
1912 }
1913 let gate = "if ok && self.transition_edges(lane, idx) != before {";
1914 let arm = body
1915 .split_once(gate)
1916 .unwrap_or_else(|| panic!("the transition arm no longer rides the join's own edges"))
1917 .1;
1918 assert!(
1919 arm.contains("mark_dirty()"),
1920 "the transition arm is outside its gate, so a step past the cap or a \
1921 retyped number would dirty an unchanged project"
1922 );
1923 let before = body.split_once(gate).unwrap().0;
1924 assert!(
1925 !before.contains("mark_dirty()"),
1926 "the transition arm is still ahead of the comparison"
1927 );
1928 assert!(
1929 body.contains("let before = self.transition_edges(lane, idx);"),
1930 "the join's edges are no longer read before the write"
1931 );
1932 // The helper both sides call, and the pair it must compare: an anchor-only
1933 // comparison cannot see the neighbour's `fade_in` not moving.
1934 let helper = fn_body("transition_edges");
1935 assert!(
1936 helper.contains("clips.get(idx)?.fade_out")
1937 && helper.contains("clips.get(idx + 1)?.fade_in"),
1938 "the edge reader no longer reads both sides of the join, so a \
1939 crossfade that only moves the neighbour is invisible"
1940 );
1941}
1942
1943/// The three doors the action table used to arm on their behalf. The table
1944/// fires *before* any door is asked, so an entry for a door that can refuse
1945/// dirties an untouched project -- and the dissolve is the sharpest case,
1946/// because the clip-menu row reaches [`Player::dissolve_selected`] directly
1947/// ([`crate::ui::bench_stance`]) and so was armed by nothing at all while the
1948/// key chord beside it armed on every press, refused or not.
1949///
1950/// The engine half of the premise is not a scan but a run: see
1951/// `engine::project::tests::a_transition_door_says_yes_to_a_write_that_moved_nothing`,
1952/// which drives `set_transition_out` and `crossfade` and shows they answer
1953/// `true` for a write that changed nothing. That is why these three need a
1954/// before/after comparison and not just the door's own answer.
1955#[test]
1956fn the_action_table_arms_nothing_a_door_answers_for_itself() {
1957 // The two transition doors, in the same shape as the duration row's.
1958 for (name, door) in [
1959 ("crossfade_selected", "session.crossfade(lane, idx, frames)"),
1960 (
1961 "dissolve_selected",
1962 "session.set_transition_out(lane, idx, frames)",
1963 ),
1964 ] {
1965 let body = fn_body(name);
1966 assert!(body.contains(door), "{name} no longer goes through {door}");
1967 let gate = "if took && self.transition_edges(lane, idx) != before {";
1968 let arm = body
1969 .split_once(gate)
1970 .unwrap_or_else(|| panic!("{name} no longer arms on the write that took"))
1971 .1;
1972 assert!(
1973 arm.contains("mark_dirty()"),
1974 "{name} arms outside its gate, so a crossfade already at the room \
1975 the two clips offer would dirty an unchanged project"
1976 );
1977 let before = body.split_once(gate).unwrap().0;
1978 assert!(
1979 !before.contains("mark_dirty()"),
1980 "{name} still arms ahead of the comparison"
1981 );
1982 }
1983 // ...and the two actions are out of the table's list, or the key path is
1984 // armed twice over and the menu path not at all.
1985 let act = fn_body("run_action");
1986 let listed = act
1987 .split_once("if matches!(")
1988 .unwrap()
1989 .1
1990 .split_once(") {")
1991 .unwrap()
1992 .0;
1993 for gone in ["ActionId::Crossfade", "ActionId::Dissolve"] {
1994 assert!(
1995 !listed.contains(gone),
1996 "{gone} is back in the pre-arm list, so the key path arms before \
1997 the door is asked while the clip-menu row arms by nothing"
1998 );
1999 }
2000 // The track removal, whose two callers are a key and a header button.
2001 let body = fn_body("remove_lane");
2002 let arm = body
2003 .split_once("Some(Ok(())) => {")
2004 .expect("the track door no longer answers which arm means the track went")
2005 .1;
2006 assert!(
2007 arm.contains("mark_dirty()"),
2008 "a track that went arms nothing, so the removal is invisible to \
2009 autosave, the unsaved ghost and the close question"
2010 );
2011 // ...and the header door no longer arms on its own before asking, which
2012 // would be a second arm for the same step.
2013 let lane_act = fn_body("act_lane");
2014 assert!(
2015 !lane_act.contains("mark_dirty"),
2016 "act_lane arms before remove_lane, so a track still holding clips \
2017 refuses with the unsaved ghost already lit"
2018 );
2019 assert!(
2020 lane_act.contains(
2021 "ActionId::RemoveVideoLane | ActionId::RemoveAudioLane => self.remove_lane(lane, cx)"
2022 ),
2023 "act_lane no longer routes the header's remove to the one armed door"
2024 );
2025}
2026
2027/// [`crate::ui::dock_stance::transition_of`]: the dock's duration row
2028/// appears only for an anchor that actually carries a dissolve or a
2029/// crossfade, and the room it offers is capped at what the successor clip
2030/// actually has -- the same clamp [`engine::project::Project::set_transition_out`]/
2031/// [`engine::project::Project::crossfade`] enforce, read back here without
2032/// either engine call so the row can never claim more than a step could land
2033/// in.
2034#[test]
2035fn a_duration_row_shows_only_for_a_transition_and_its_room_is_the_successors() {
2036 // `len` is the clip's own source length (`out_frame`, `in_frame` fixed at
2037 // 0, `speed` 1x, so `Clip::frames()` reads back exactly `len`).
2038 fn clip(start: u32, len: u32, transition_out: u32, fade_in: u32, fade_out: u32) -> Clip {
2039 Clip {
2040 speed_keys: Vec::new(),
2041 reversed: false,
2042 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
2043 angle: Default::default(),
2044 start,
2045 in_frame: 0,
2046 out_frame: len,
2047 source: 0,
2048 link: None,
2049 eq: None,
2050 color: None,
2051 transform: None,
2052 fit: FitPolicy::default(),
2053 speed: Speed::NORMAL,
2054 fade_in,
2055 fade_out,
2056 transition_out,
2057 transition_kind: Default::default(),
2058 visualizer: 0,
2059 viz_paint: 0,
2060 gain_db: 0.0,
2061 gain_keys: Vec::new(),
2062 pan: 0,
2063 pitch: 0.0,
2064 transform_keys: Vec::new(),
2065 opacity_keys: Vec::new(),
2066 color_keys: Vec::new(),
2067 effects: Vec::new(),
2068 }
2069 }
2070 // A plain cut carries neither field, so the row has nothing to show.
2071 let plain = clip(0, 10, 0, 0, 0);
2072 let plain_next = clip(10, 15, 0, 0, 0);
2073 assert_eq!(
2074 transition_of(LaneKind::Video, &plain, Some(&plain_next)),
2075 None
2076 );
2077
2078 // A dissolve: video lane, `transition_out` set, an adjacent successor.
2079 // The room offered is the shorter of the two -- here the successor's own
2080 // 5-frame length, less than the anchor's 10.
2081 let a = clip(0, 10, 4, 0, 0);
2082 let b = clip(10, 5, 0, 0, 0);
2083 assert_eq!(
2084 transition_of(LaneKind::Video, &a, Some(&b)),
2085 Some(("Dissolve", 4, 5))
2086 );
2087 // No successor, or a gap before one: no row, same as no transition.
2088 assert_eq!(transition_of(LaneKind::Video, &a, None), None);
2089 let gap = clip(11, 5, 0, 0, 0);
2090 assert_eq!(transition_of(LaneKind::Video, &a, Some(&gap)), None);
2091
2092 // A crossfade: audio lane, both ends of the join set
2093 // ([`Project::crossfade`]'s own signature) -- a one-sided fade (the
2094 // successor's `fade_in` still 0) is not one, and stays a plain fade.
2095 let a = clip(0, 10, 0, 0, 3);
2096 let b = clip(10, 2, 0, 3, 0);
2097 assert_eq!(
2098 transition_of(LaneKind::Audio, &a, Some(&b)),
2099 Some(("Crossfade", 3, 2)),
2100 "capped at the successor's own 2-frame length, though 3 was asked for"
2101 );
2102 let one_sided = clip(10, 2, 0, 0, 0);
2103 assert_eq!(transition_of(LaneKind::Audio, &a, Some(&one_sided)), None);
2104
2105 // A dissolve field on an audio lane, or a fade-only pair on a video
2106 // lane, name no transition either -- each kind reads only its own lane.
2107 let dissolving = clip(0, 10, 4, 0, 0);
2108 assert_eq!(transition_of(LaneKind::Audio, &dissolving, Some(&b)), None);
2109}
2110
2111/// The transition kinds: sixteen palette actions (one per kind and direction,
2112/// each naming the kind it sets once), the card's title follows the clip's kind,
2113/// and the kind door arms only on a write that changed the join, as the
2114/// dissolve's does.
2115#[test]
2116fn the_transition_kinds_are_palette_actions_and_set_through_a_gated_door() {
2117 use engine::transitions::{Dir, TransitionKind};
2118 let kinds: Vec<TransitionKind> = ActionId::ALL
2119 .into_iter()
2120 .filter_map(|a| a.transition_kind())
2121 .collect();
2122 assert_eq!(kinds.len(), 16, "dissolve, two dips, three shapes x four ways, zoom");
2123 for (i, k) in kinds.iter().enumerate() {
2124 assert!(!kinds[..i].contains(k), "{k:?} is set by two actions");
2125 }
2126 assert!(kinds.contains(&TransitionKind::Push(Dir::Left)));
2127 assert!(ActionId::TransitionWipeUp.label().contains("Wipe up"));
2128
2129 let body = fn_body("set_transition_kind");
2130 assert!(body.contains("session.set_transition(lane, idx, kind, frames)"));
2131 let gate = "if took && self.transition_edges(lane, idx) != before {";
2132 let (ahead, arm) = body
2133 .split_once(gate)
2134 .expect("set_transition_kind no longer arms on the write that took");
2135 assert!(arm.contains("mark_dirty()") && !ahead.contains("mark_dirty()"));
2136 // The edge reader tells two kinds apart, or a kind change would not arm.
2137 assert!(fn_body("transition_edges").contains("transition_kind_of(lane, idx)"));
2138
2139 let mut a = Clip {
2140 opacity_keys: Vec::new(),
2141 color_keys: Vec::new(),
2142 effects: Vec::new(),
2143 speed_keys: Vec::new(),
2144 reversed: false,
2145 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
2146 angle: Default::default(),
2147 start: 0,
2148 in_frame: 0,
2149 out_frame: 10,
2150 source: 0,
2151 link: None,
2152 eq: None,
2153 color: None,
2154 transform: None,
2155 fit: FitPolicy::default(),
2156 speed: Speed::NORMAL,
2157 fade_in: 0,
2158 fade_out: 0,
2159 transition_out: 4,
2160 transition_kind: TransitionKind::Push(Dir::Left),
2161 visualizer: 0,
2162 viz_paint: 0,
2163 gain_db: 0.0,
2164 gain_keys: Vec::new(),
2165 pan: 0,
2166 pitch: 0.0,
2167 transform_keys: Vec::new(),
2168 };
2169 let mut b = a.clone();
2170 b.start = 10;
2171 b.transition_out = 0;
2172 assert_eq!(transition_of(LaneKind::Video, &a, Some(&b)), Some(("Push", 4, 10)));
2173 a.transition_kind = TransitionKind::DipBlack;
2174 assert_eq!(
2175 transition_of(LaneKind::Video, &a, Some(&b)),
2176 Some(("Dip to black", 4, 10))
2177 );
2178}
2179
2180#[test]
2181fn a_clip_with_no_sound_is_refused_in_the_same_words_whichever_kind_it_is() {
2182 // A still and a video with no audio track are one answer to one
2183 // question: the lane and index that were picked, the file, and which of
2184 // the two soundless things it is. What must never reach the bar is the
2185 // demuxer's own words -- a png handed to the mp4 reader answers "a box
2186 // with a larger size than it", which is true of a container and useless
2187 // to a person.
2188 assert_eq!(
2189 unscannable(Lane::V1, 1, std::path::Path::new("/tmp/shot.png")),
2190 "V1 clip 2 has no audio to scan — shot.png is a picture"
2191 );
2192 assert_eq!(
2193 unscannable(
2194 Lane::new(LaneKind::Audio, 1),
2195 0,
2196 std::path::Path::new("/tmp/test_baseline.mp4")
2197 ),
2198 "A2 clip 1 has no audio to scan — test_baseline.mp4 is silent"
2199 );
2200}
2201
2202/// The hold gate: a value runs, everything else still means one press one
2203/// action -- which is the whole invariant the blanket `is_held` filter used
2204/// to carry on its own.
2205#[test]
2206fn a_held_key_moves_a_value_and_nothing_else() {
2207 use keymap::ActionId;
2208 // A card's four arrows, whichever card it is.
2209 for key in ["up", "down", "left", "right"] {
2210 assert!(repeats(Repeat::Card, key, None), "{key} on a card");
2211 }
2212 // The card's own one-shots: flatten every band, cut forty places, play
2213 // them fast, close. None of them on a hold.
2214 for key in ["r", "enter", "f", "1", "escape"] {
2215 assert!(!repeats(Repeat::Card, key, None), "{key} on a card");
2216 }
2217 // Outside a card the keymap answers, and only the volume pair is a
2218 // value being moved.
2219 assert!(repeats(Repeat::Keymap, "up", Some(ActionId::VolumeUp)));
2220 assert!(repeats(Repeat::Keymap, "down", Some(ActionId::VolumeDown)));
2221 // ...and the zoom pair, which runs the view the way they run the level.
2222 assert!(repeats(Repeat::Keymap, "=", Some(ActionId::ZoomIn)));
2223 assert!(!repeats(Repeat::Keymap, "0", Some(ActionId::ZoomFit)));
2224 for action in ActionId::ALL {
2225 let held = repeats(Repeat::Keymap, "k", Some(action));
2226 assert_eq!(
2227 held,
2228 matches!(
2229 action,
2230 ActionId::VolumeUp | ActionId::VolumeDown | ActionId::ZoomIn | ActionId::ZoomOut
2231 ),
2232 "{action:?} on a hold"
2233 );
2234 }
2235 // An arrow with nothing bound to it moves nothing on the timeline.
2236 assert!(!repeats(Repeat::Keymap, "left", None));
2237 // And a stroke being captured, an export, or the overlays: nothing at
2238 // all, or the hold would bind a key and then fire what it just bound.
2239 for key in ["up", "left", "escape", "5"] {
2240 assert!(!repeats(Repeat::Nothing, key, Some(ActionId::VolumeUp)));
2241 }
2242}
2243
2244#[test]
2245fn the_silence_card_fits_the_smallest_window_and_never_slows_a_silence_down() {
2246 // The same 640x360 floor, and this card starts below the header: a
2247 // title, the scope chips, three slider rows (the threshold, the forgiveness
2248 // and the rate), the `More …` fold, the status line beside the keep-only
2249 // switch, and the two apply buttons. Help is the head's `?`, not a line.
2250 // The fold's rows are behind a click, so the floor is the closed card.
2251 let (title, label_line, slider_gap) = (17., 17., 4.);
2252 let slider_row_h = label_line + slider_gap + HIT_MIN;
2253 let gaps = 6. * 6.;
2254 let padding = 24.;
2255 assert!(
2256 HEADER_H
2257 + 8.
2258 + title
2259 + KEYS_ROW_H
2260 + 3. * slider_row_h
2261 + HIT_MIN
2262 + CONTROL_H
2263 + CONTROL_H
2264 + gaps
2265 + padding
2266 <= 360.,
2267 "card too tall"
2268 );
2269 // The closed card shows the four main rows; the rest are the fold's.
2270 assert_eq!(Player::SILENCE_MAIN_ROWS.len(), 4);
2271 assert_eq!(
2272 Player::SILENCE_MAIN_ROWS.len() + Player::SILENCE_MORE_ROWS.len(),
2273 SILENCE_ROWS
2274 );
2275 // Its rows, its bars and its buttons are clicked, so WCAG 2.5.8 binds
2276 // them: a row's hit is `HIT_MIN` tall.
2277 const {
2278 assert!(KEYS_ROW_H >= HIT_MIN);
2279 }
2280 // ...and the pair of them fits beside the widest value the card prints.
2281 const {
2282 assert!(2. * HIT_MIN + 4. < COLOR_W / 2., "steppers crowd the value");
2283 }
2284 // A "speed-up" is never a slow-down: the rate stops above real time at
2285 // one end and at what a clip can hold at the other, whatever the keys
2286 // ask for. A silence played *slower* would make the timeline longer,
2287 // which is the one thing neither button may do.
2288 assert!(silence_rate(0) > Speed::NORMAL);
2289 assert!(silence_rate(1000) > Speed::NORMAL);
2290 assert_eq!(silence_rate(i32::MAX), Speed::MAX);
2291 assert_eq!(silence_rate(4000), Speed::MAX);
2292}
2293
2294/// Each silence slider reads its own range, snaps to its own grid and opens
2295/// at a value inside that range -- the three things a press and a Reset
2296/// button both lean on. The rate's floor is real time plus one step, the
2297/// same floor [`silence_rate`] clamps to, so a press at the left end is a
2298/// speed-up and never a slow-down.
2299#[test]
2300fn the_silence_sliders_snap_to_their_grids_and_open_inside_their_ranges() {
2301 // The two rows that are choices are not sliders at all.
2302 assert_eq!(Player::silence_snap(0, 0.5), None);
2303 assert_eq!(Player::silence_snap(2, 0.5), None);
2304 // The threshold sweeps -80..0 dB on whole decibels.
2305 assert_eq!(Player::silence_snap(1, 0.), Some(-80.));
2306 assert_eq!(Player::silence_snap(1, 1.), Some(0.));
2307 assert_eq!(Player::silence_snap(1, 0.5), Some(-40.));
2308 // The durations sweep 0..5 s on a twentieth of a second.
2309 let forgive = Player::silence_snap(3, 0.1).expect("a slider");
2310 assert!((forgive - 0.5).abs() < 1e-9, "{forgive}");
2311 let padding = Player::silence_snap(4, 0.333).expect("a slider");
2312 assert!((padding / 0.05 - (padding / 0.05).round()).abs() < 1e-9);
2313 // The rate sweeps from one step above real time to the top, in steps.
2314 let floor = f64::from(Speed::NORMAL.permille()) + f64::from(SPEED_STEP);
2315 assert_eq!(Player::silence_snap(6, 0.), Some(floor));
2316 assert_eq!(Player::silence_snap(6, 1.), Some(4000.));
2317 assert!(silence_rate(floor as i32) > Speed::NORMAL);
2318 // A value a press can name is never outside its range, whatever the
2319 // track's end it came from.
2320 for field in [1, 3, 4, 5, 6] {
2321 let (lo, hi, _) = Player::silence_range(field).expect("a slider");
2322 for along in [-1., 0., 0.37, 1., 2.] {
2323 let at = Player::silence_snap(field, along).expect("a slider");
2324 assert!((lo..=hi).contains(&at), "field {field} at {along}: {at}");
2325 }
2326 // Every row opens inside its own range, so the bar starts on the track.
2327 let default = Player::silence_default(field);
2328 assert!(
2329 (lo..=hi).contains(&default),
2330 "field {field} opens at {default}"
2331 );
2332 }
2333 // A fresh card's rate is the top of the range: the speed-up plays at four.
2334 assert_eq!(Player::silence_default(6), 4000.);
2335}
2336
2337/// The choice lists that replaced two click-to-cycle surfaces: every value
2338/// on offer at once, exactly one of them marked as the one in force, the
2339/// same order the stroke steps through, and the open list inside the
2340/// 640x360 floor with every row a `HIT_MIN` target.
2341#[test]
2342fn a_choice_list_offers_every_value_and_fits_the_smallest_window() {
2343 // Odd media: its own size is on the ladder, in its place by area, and
2344 // nothing else moved.
2345 let native = (1440, 1080);
2346 let ladder = resolution_ladder(native);
2347 assert_eq!(
2348 ladder,
2349 [
2350 (3840, 2160),
2351 (2560, 1440),
2352 (1920, 1080),
2353 (1080, 1920),
2354 (1440, 1080),
2355 (1080, 1080),
2356 (1280, 720),
2357 (854, 480)
2358 ]
2359 );
2360 for size in RESOLUTIONS {
2361 assert!(ladder.contains(&size), "{size:?} is not on offer");
2362 }
2363 // Media already at a listed size is on the ladder once, not twice.
2364 assert_eq!(resolution_ladder((1920, 1080)).len(), RESOLUTIONS.len());
2365
2366 // The rows say the same thing the ladder does, and mark the one in
2367 // force -- exactly one row, whichever rung the project is on.
2368 let rows = resolution_choices((1280, 720), native);
2369 assert_eq!(rows.len(), ladder.len());
2370 assert_eq!(rows.iter().filter(|(.., picked)| *picked).count(), 1);
2371 for ((choice, label, detail, picked), size) in rows.iter().zip(&ladder) {
2372 assert_eq!(*choice, Choice::Size(size.0, size.1));
2373 assert_eq!(label.as_ref(), size_row_label(size.0, size.1));
2374 // A tall or square row names its shape, not its numbers, unless it is the media's own.
2375 assert_eq!(detail.is_empty(), size.0 <= size.1 && *size != native, "{size:?}");
2376 assert_eq!(*picked, *size == (1280, 720));
2377 }
2378 // The media's own size says so, in plain words: it is the one rung a person
2379 // cannot read off a number they chose.
2380 let (.., native_detail, _) = rows.iter().find(|r| r.0 == Choice::Size(native.0, native.1)).expect("the media's own rung");
2381 assert!(native_detail.ends_with("(matches your media)"), "{native_detail}");
2382 // A project at a size nobody listed still gets the whole list, with
2383 // nothing marked rather than a wrong row marked.
2384 assert!(
2385 resolution_choices((1000, 1000), native)
2386 .iter()
2387 .all(|(.., picked)| !picked)
2388 );
2389
2390 // The fit list, on a clip: all four policies, in the order the stroke
2391 // lists them, the clip's own marked and every row naming the
2392 // canvas it would place the picture on.
2393 let fits = fit_choices(Lane::V1, 3, FITS[2], (1920, 1080));
2394 assert_eq!(fits.len(), FITS.len());
2395 assert_eq!(fits.iter().filter(|(.., picked)| *picked).count(), 1);
2396 assert_eq!(fits[2].0, Choice::Fit(Lane::V1, 3, FITS[2]));
2397 assert!(fits[2].3, "the clip's own policy is not marked");
2398 assert!(fits[0].2.contains("1920x1080"), "{}", fits[0].2);
2399
2400 // The rate list, the other setting the project has of its own: every
2401 // rate on offer, the media's own cycled in at its place by speed and
2402 // said so, and the one the timeline is cut at marked. The value carried
2403 // is the `f64` the engine conforms to, not the rounded label -- 23.976
2404 // is not 24000/1001, and a rate the timescales cannot name is refused.
2405 let ntsc = 24_000. / 1001.;
2406 let rates = frame_rate_ladder(25.);
2407 assert_eq!(rates.len(), FRAME_RATES.len(), "25 is already on the list");
2408 let odd = frame_rate_ladder(48.);
2409 assert_eq!(odd[5], 48., "the media's own, in its place by speed");
2410 assert_eq!(odd.len(), FRAME_RATES.len() + 1);
2411 let fps = fps_choices(ntsc, 48.);
2412 assert_eq!(fps.len(), odd.len());
2413 assert_eq!(fps.iter().filter(|(.., picked)| *picked).count(), 1);
2414 assert_eq!(fps[0].0, Choice::Fps(ntsc), "the ratio, not 23.976");
2415 assert_eq!(fps[0].1.as_ref(), "23.976 fps (NTSC film)");
2416 assert!(fps[0].3, "the rate in force is not marked");
2417 assert!(fps[5].2.contains("Match the media"), "{}", fps[5].2);
2418 for (.., detail, _) in &fps {
2419 assert!(detail.chars().count() < 26, "{detail} loses its tail");
2420 }
2421
2422 // The HDR list, the third project setting: all three renditions in the
2423 // order they brighten, the one in force marked, and every row saying
2424 // what it is in words that fit beside the label.
2425 let tones = tone_choices(Preset::Standard);
2426 assert_eq!(tones.len(), Preset::ALL.len());
2427 assert_eq!(tones.iter().filter(|(.., picked)| *picked).count(), 1);
2428 for (row, preset) in tones.iter().zip(Preset::ALL) {
2429 assert_eq!(row.0, Choice::Tone(preset));
2430 assert_eq!(row.1.as_ref(), tone_label(preset));
2431 assert!(!row.2.is_empty(), "{preset:?} says nothing about itself");
2432 assert!(row.2.chars().count() < 26, "{} loses its tail", row.2);
2433 }
2434 assert!(tones[1].3, "the rendition in force is not marked");
2435
2436 // The encoder list, the export card's own: all three seats, the one in
2437 // force marked, and a row each saying what it does. The AV1 warning
2438 // belongs to exactly one pair -- the GPU on an AV1 file -- so it cannot
2439 // become a line nobody reads.
2440 let seats = encoder_choices(EncoderSeat::Software);
2441 assert_eq!(seats.len(), EncoderSeat::ALL.len());
2442 assert_eq!(seats.iter().filter(|(.., picked)| *picked).count(), 1);
2443 for (row, seat) in seats.iter().zip(EncoderSeat::ALL) {
2444 assert_eq!(row.0, Choice::Encoder(seat));
2445 assert_eq!(row.1.as_ref(), encoder_label(seat));
2446 assert!(!row.2.is_empty(), "{seat:?} says nothing about itself");
2447 assert!(row.2.chars().count() < 26, "{} loses its tail", row.2);
2448 }
2449 assert!(seats[2].3, "the seat in force is not marked");
2450 for format in [Format::Av1, Format::Av1Mp4] {
2451 assert!(av1_hw_warning(format, EncoderSeat::Hardware).is_some());
2452 for seat in [EncoderSeat::Auto, EncoderSeat::Software] {
2453 assert_eq!(
2454 av1_hw_warning(format, seat),
2455 None,
2456 "{seat:?} is the safe seat"
2457 );
2458 }
2459 }
2460 for format in [Format::Mp4, Format::Hevc, Format::HevcMp4, Format::Wav] {
2461 assert_eq!(
2462 av1_hw_warning(format, EncoderSeat::Hardware),
2463 None,
2464 "{format:?} is not the encoder that reset the driver"
2465 );
2466 }
2467
2468 // The open list fits the floor the menus are measured against: the
2469 // longest of them is the rate ladder with an odd rate cycled in, and it
2470 // hangs at the pointer with every row on screen. Rows are click targets
2471 // (WCAG 2.5.8).
2472 const {
2473 assert!(MENU_ROW_H >= HIT_MIN);
2474 }
2475 assert!(odd.len() > ladder.len(), "the longest list moved");
2476 assert!(MENU_PAD * 2. + odd.len() as f32 * MENU_ROW_H <= 360.);
2477 let tall = MENU_PAD * 2. + ladder.len() as f32 * MENU_ROW_H;
2478 assert!(tall <= 360., "the list is taller than the floor");
2479 assert_eq!(
2480 menu_at(point(px(600.), px(340.)), size(px(640.), px(360.)), tall),
2481 (
2482 640. - crate::layout::MENU_EDGE - MENU_W,
2483 360. - crate::layout::MENU_EDGE - tall
2484 ),
2485 "the list would hang off the smallest window"
2486 );
2487}
2488
2489/// The two settings a resolution/rate pick reaches with no file open yet:
2490/// the plain list, since there is no media size to cycle in beside it, with
2491/// nothing marked until a pending pick exists and exactly that row marked
2492/// once it does -- the same shape [`resolution_choices`]/[`fps_choices`]
2493/// have once a session exists, minus the media's own rung.
2494#[test]
2495fn the_resolution_and_rate_lists_work_before_any_file_is_open() {
2496 let none = pending_resolution_choices(None);
2497 assert_eq!(none.len(), RESOLUTIONS.len());
2498 assert!(
2499 none.iter().all(|(.., picked)| !picked),
2500 "nothing picked yet"
2501 );
2502 for ((choice, label, detail, _), size) in none.iter().zip(RESOLUTIONS) {
2503 assert_eq!(*choice, Choice::Size(size.0, size.1));
2504 assert_eq!(label.as_ref(), size_row_label(size.0, size.1));
2505 let landscape = size.0 > size.1;
2506 assert_eq!(detail.as_ref(), if landscape { format!("{}x{}", size.0, size.1) } else { String::new() });
2507 }
2508 let picked = pending_resolution_choices(Some(RESOLUTIONS[2]));
2509 assert_eq!(picked.iter().filter(|(.., picked)| *picked).count(), 1);
2510 assert!(picked[2].3);
2511
2512 let none = pending_fps_choices(None);
2513 assert_eq!(none.len(), FRAME_RATES.len());
2514 assert!(none.iter().all(|(.., picked)| !picked));
2515 let picked = pending_fps_choices(Some(FRAME_RATES[3]));
2516 assert_eq!(picked.iter().filter(|(.., picked)| *picked).count(), 1);
2517 assert!(picked[3].3);
2518}
2519
2520/// The sample-rate list: "source" first and marked whenever nothing is
2521/// picked -- true both before any file is open ([`Player::pending_settings`])
2522/// and once a session exists with no override ([`PlaybackSession::sample_rate`]
2523/// returning `None`) -- then every offered rate, exactly one marked once one
2524/// is picked.
2525#[test]
2526fn the_sample_rate_list_marks_source_with_nothing_picked() {
2527 let none = sample_rate_choices(None);
2528 assert_eq!(none.len(), SAMPLE_RATES.len() + 1);
2529 assert_eq!(none[0].0, Choice::SampleRate(None));
2530 assert!(none[0].3, "source is the row in force with nothing picked");
2531 assert_eq!(
2532 none.iter().filter(|(.., picked)| *picked).count(),
2533 1,
2534 "exactly one row marked"
2535 );
2536 for ((choice, label, ..), rate) in none.iter().skip(1).zip(SAMPLE_RATES) {
2537 assert_eq!(*choice, Choice::SampleRate(Some(rate)));
2538 assert_eq!(label.as_ref(), format!("{rate} Hz"));
2539 }
2540
2541 let picked = sample_rate_choices(Some(SAMPLE_RATES[1]));
2542 assert!(!picked[0].3, "source no longer in force");
2543 assert_eq!(picked.iter().filter(|(.., picked)| *picked).count(), 1);
2544 assert!(picked[2].3);
2545}
2546
2547/// The progress line's two clocks, driven the way a repaint drives them:
2548/// steady work, a stall where hardware hands over to software, then steady
2549/// work again. The estimate may not whipsaw, may not vanish once it has
2550/// been given, and must meet the elapsed clock at the end.
2551#[test]
2552fn the_export_estimate_rides_out_a_stall_and_converges() {
2553 let (mut marks, mut elapsed, mut progress) = (Vec::new(), 0f32, 0f32);
2554 // 2%/s, a 12 s stall at 40% -- longer than the window, so the window
2555 // alone would have nothing left to measure -- and the same rate to the
2556 // end: 62 s of wall clock for 50 s of work.
2557 let rate = 0.02;
2558 let (mut quiet, mut before_stall, mut after_stall, mut last) = (0f32, 0., 0., f32::MAX);
2559 while progress < 1. {
2560 let stalled = (20. ..32.).contains(&elapsed);
2561 note_progress(&mut marks, elapsed, progress);
2562 // What is really left, to hold every guess against.
2563 let truth = (1. - progress) / rate + if stalled { 32. - elapsed } else { 0. };
2564 match eta_secs(&marks, elapsed, progress) {
2565 // "estimating…" is only allowed before there is a span to
2566 // measure, and never again after the first number.
2567 None => {
2568 assert!(elapsed < ETA_SPAN + 1., "estimate vanished at {elapsed}");
2569 quiet = elapsed;
2570 }
2571 Some(left) => {
2572 // No guess is ever wilder than four times the truth: that
2573 // is the eightfold spike a raw window rate throws on either
2574 // edge of the stall.
2575 assert!(left <= truth * 4., "at {elapsed}s: {left} vs {truth}");
2576 // While the rate holds, the answer is the true one and it
2577 // only ever counts down.
2578 if (5. ..20.).contains(&elapsed) {
2579 assert!((left - truth).abs() <= truth * 0.15, "{elapsed}s: {left}");
2580 assert!(left < last, "estimate grew while the rate held");
2581 }
2582 // Eight seconds past the stall it has caught up again.
2583 if elapsed >= 40. {
2584 assert!((left - truth).abs() <= truth * 0.25, "{elapsed}s: {left}");
2585 assert!(left < last + 0.001, "estimate grew after the stall");
2586 }
2587 if (20. ..20.25).contains(&elapsed) {
2588 before_stall = left;
2589 }
2590 if (31.5..31.75).contains(&elapsed) {
2591 after_stall = left;
2592 }
2593 last = left;
2594 }
2595 }
2596 // A window's worth of marks and no more, however long the encode.
2597 assert!(marks.len() <= 20, "{} marks", marks.len());
2598 elapsed += 0.25;
2599 if !stalled {
2600 progress = (progress + rate * 0.25).min(1.);
2601 }
2602 }
2603 assert!(quiet > 0. && quiet < ETA_SPAN + 1.);
2604 // The stall stretched the guess instead of erasing it, and by more than
2605 // the stopped clock adds on its own.
2606 assert!(
2607 after_stall > before_stall + 12.,
2608 "{before_stall} -> {after_stall}"
2609 );
2610 // Both clocks meet: a finished pass has nothing left.
2611 assert_eq!(eta_secs(&marks, elapsed, 1.), Some(0.));
2612 assert!((elapsed - 62.).abs() < 1., "{elapsed}");
2613 assert_eq!(clock(83.4), "1:23");
2614 assert_eq!(clock(114.), "1:54");
2615 assert_eq!(clock(-1.), "0:00");
2616}
2617
2618/// The two shapes that made the countdown lie rather than guess: a bar that
2619/// went backwards, and a division that could reach infinity. The engine no
2620/// longer pulls its bar back (`export`'s `fetch_max`), which is why this asks
2621/// the estimator directly -- it is handed the marks a re-run used to leave.
2622#[test]
2623fn the_export_estimate_answers_a_bar_that_went_backwards_with_a_guess() {
2624 // 93% at 400 s, then the hardware encoder dies and the mark stands while
2625 // the software one writes the film again from the first frame.
2626 let marks = vec![(392., 0.93), (396., 0.93), (400., 0.93)];
2627 let stalled = eta_secs(&marks, 400., 0.93).expect("a stall is still estimated");
2628 assert!(stalled > 0., "a running export has time left: {stalled}");
2629 // The old shape: the same marks against a bar that had been put back to
2630 // zero. The rate cannot be negative, so what is left cannot be either --
2631 // and it is never the "~0:00 left" that read as an export about to finish.
2632 let backwards = eta_secs(&marks, 400., 0.05).expect("a backward bar still estimates");
2633 assert!(
2634 backwards >= stalled,
2635 "a bar at 5% claimed less left than one at 93%: {backwards} vs {stalled}"
2636 );
2637 assert!(backwards > 1., "the countdown read as good as finished");
2638 // Nothing it can be handed prints as an infinite clock.
2639 for (marks, elapsed, progress) in [
2640 (vec![(0., 0.)], f32::MAX, f32::MIN_POSITIVE),
2641 (vec![(0., f32::MAX)], 3., 0.5),
2642 (Vec::new(), f32::MAX, 0.5),
2643 ] {
2644 let left = eta_secs(&marks, elapsed, progress);
2645 assert!(
2646 left.is_none_or(f32::is_finite),
2647 "{left:?} would be printed as a clock"
2648 );
2649 }
2650}
2651
2652/// The stacking-scrims bug: opening the speed card while the colour card was
2653/// up left both up at once, because each `open_*` cleared a different
2654/// hand-picked subset of the other flags rather than all of them. The fix is
2655/// one path (`Player::close_card`, the single list of every flag that means
2656/// "a card is up") that every opener calls before setting its own -- so this
2657/// pins that *every* opener routes through it, found by name in the source
2658/// rather than hand-listed, which is what let a seventh and eighth card slip
2659/// through the ad-hoc version unnoticed.
2660#[test]
2661fn every_card_opener_closes_every_other_card_through_one_path() {
2662 let cards_src = src_text("player/cards.rs");
2663 let mut openers = Vec::new();
2664 let mut rest = cards_src.as_str();
2665 let mut scanned_from = 0usize;
2666 while let Some(at) = rest.find("fn open_") {
2667 let after = &rest[at + "fn ".len()..];
2668 let name_end = after.find('(').expect("a fn's parens");
2669 openers.push(after[..name_end].to_string());
2670 scanned_from += at + "fn ".len() + name_end;
2671 rest = &cards_src[scanned_from..];
2672 }
2673 // `open_picker` opens a small dropdown (a resolution/fps/fit choice
2674 // list), not one of the seven full-window plates `close_card` lists --
2675 // it is not part of this invariant.
2676 openers.retain(|name| name != "open_picker");
2677 assert!(
2678 openers.len() >= 7,
2679 "expected at least the seven card openers (eq/color/transform/speed/silence/mix/subtitle_style), found {openers:?}"
2680 );
2681 for name in &openers {
2682 let body = fn_body(name);
2683 assert!(
2684 body.contains("self.close_card();") || body.contains("self.close_other_cards();"),
2685 "{name} never calls close_card() -- it may be clearing its own \
2686 hand-picked subset of the other cards again, which is exactly \
2687 what let two cards stack on screen at once (open speed, then \
2688 colour, and both stayed up)"
2689 );
2690 }
2691}
2692
2693/// Regression: a builder moved every card's how-to prose off the card body
2694/// onto a `?` glyph tooltip on the card head (`dark_card_head`), to answer
2695/// the complaint that the body read "like a terminal screen". But `Tip`
2696/// stands aside for *every* tooltip while `OVERLAID` is set, and a card
2697/// being open is exactly what sets `OVERLAID` -- so the `?`'s own help could
2698/// never paint while the card that owns it was on screen (driven proof:
2699/// dwelling the pointer on it for 5-6s at four coordinates changed zero
2700/// pixels). `OverlayTip`/`tip_may_paint` is the fix: a tip anchored on the
2701/// overlay itself is exempt. This pins both halves so an eighth card can't
2702/// reintroduce either half of the bug.
2703#[test]
2704fn a_cards_own_help_paints_while_the_card_is_open_but_the_ui_under_it_stays_quiet() {
2705 OVERLAID.store(true, Ordering::Relaxed);
2706 assert!(
2707 tip_may_paint(true),
2708 "a tip anchored on the overlay itself (a card head's own `?`) must \
2709 still paint while its own card is open, or the help nobody wanted \
2710 permanent becomes help nobody can ever read"
2711 );
2712 assert!(
2713 !tip_may_paint(false),
2714 "a tip on the *underlying* UI must still stand aside while a card/menu \
2715 is up over it -- OVERLAID's original purpose, which the overlay \
2716 exemption must not weaken"
2717 );
2718 OVERLAID.store(false, Ordering::Relaxed);
2719 assert!(
2720 tip_may_paint(false),
2721 "with nothing overlaid, an ordinary tip paints too"
2722 );
2723
2724 // Structural half: every card routes its head through `dark_card_head`,
2725 // so checking its one help-tooltip call site covers all seven cards (and
2726 // any future eighth) at once -- it must build an `OverlayTip`, not a
2727 // plain `Tip`, or this whole fix is undone by construction.
2728 let cards_src = src_text("ui/cards");
2729 let head_fn_at = cards_src
2730 .find("fn dark_card_head(")
2731 .expect("dark_card_head");
2732 // Bound the inspected source by the next item, not a byte count: rustfmt
2733 // may legitimately reflow this function without moving its tooltip out of
2734 // scope.
2735 let head_fn_end = cards_src[head_fn_at..]
2736 .find("\n/// A ghost action row")
2737 .expect("dark_card_head's following item");
2738 let head_fn = &cards_src[head_fn_at..head_fn_at + head_fn_end];
2739 assert!(
2740 head_fn.contains("OverlayTip(h.clone())"),
2741 "dark_card_head's own `?` tooltip no longer builds an OverlayTip -- the \
2742 card-head help is unreadable again while its card is open"
2743 );
2744}
2745
2746/// Structural guard only: this binary has no `TestAppContext`, so it cannot
2747/// mount the card, aim at its hint, wheel it, or read painted movement. A
2748/// driving pass must still prove a wheel over the hint changes card pixels.
2749/// This pins the declaration-level invariant that the EQ card's outer
2750/// container, which also owns the hint sibling, owns `eq_scroll`; putting the
2751/// handle back on `eq-card-rows` recreates that hint's dead zone.
2752#[test]
2753fn eq_cards_scroll_handle_belongs_to_the_container_that_also_holds_its_hint() {
2754 let card = fn_body("eq_card");
2755 let card_at = card.find(".id(\"eq-card\")").expect("EQ card container");
2756 let rows_at = card.find(".id(\"eq-card-rows\")").expect("EQ card rows");
2757 let container = &card[card_at..rows_at];
2758
2759 assert!(
2760 container.contains(".overflow_y_scroll()")
2761 && container.contains(".track_scroll(&self.eq_scroll)"),
2762 "eq_scroll must belong to eq-card, the container that also holds the \
2763 below-fold hint, rather than a body-only child"
2764 );
2765
2766 let rows = &card[rows_at..];
2767 assert!(
2768 !rows.contains(".track_scroll(&self.eq_scroll)"),
2769 "eq-card-rows owns eq_scroll again -- its sibling hint becomes a \
2770 wheel dead zone"
2771 );
2772 assert!(
2773 rows.contains("more below — scroll the card"),
2774 "the below-fold hint disappeared; this guard must cover the child it \
2775 keeps in the card's wheel surface"
2776 );
2777}
2778
2779/// "Maximize a card in place" changes size only, never the relative
2780/// semantics a value is drawn against: `eq_x`/`eq_y` map into `0..1` of
2781/// whatever box they are given, so a wider/taller EQ card is genuinely more
2782/// dB/Hz resolution, not the same graph stretched. This is the layout half
2783/// of that claim -- `eq_x`/`eq_y` themselves take no size argument at all
2784/// (they answer in `0..1`), so there is nothing about them a maximize could
2785/// have broken; what a maximize is allowed to touch is `eq_card_w`/
2786/// `eq_graph_h`'s own ceiling.
2787#[test]
2788fn maximizing_a_card_grows_its_box_without_moving_where_a_value_sits_in_it() {
2789 // Below the old EQ_W_MAX ceiling, maximized and not agree -- there is
2790 // room for both without the ceiling mattering yet.
2791 assert_eq!(eq_card_w(600., false), eq_card_w(600., true));
2792 // Past it, only the maximized card keeps growing: the ceiling this
2793 // session's fix drops.
2794 assert!(
2795 eq_card_w(1920., true) > eq_card_w(1920., false),
2796 "maximized EQ card no longer drops the EQ_W_MAX ceiling"
2797 );
2798 assert_eq!(
2799 eq_graph_h(true),
2800 EQ_GRAPH_MAX_H,
2801 "maximized EQ graph no longer grows to EQ_GRAPH_MAX_H"
2802 );
2803 assert!(
2804 eq_graph_h(true) > eq_graph_h(false),
2805 "maximized EQ graph is not actually taller than the resting one"
2806 );
2807 // The mapping itself never sees "maximized" -- a bigger box is more
2808 // resolution because the same 0..1 fraction now spans more pixels, not
2809 // because the fraction itself moved.
2810 assert_eq!(eq_x(1000.), eq_x(1000.));
2811 assert_eq!(eq_y(0.), eq_y(0.));
2812}
2813
2814/// The regression the previous test could not see: `eq_card_w`/`eq_graph_h`
2815/// growing with `maximized` proved nothing about where the box that receives
2816/// those numbers actually sits. It sat inside `dock_stance.rs`'s
2817/// "dock-clip-rows" -- a ~280-390px, less-than-window-tall strip -- and an
2818/// absolutely-positioned child is sized against its own *immediate* parent
2819/// regardless of any `.relative()` marker upstream, so `below_picture_floor`
2820/// (a window-space y) landed inside that short box and shoved the card to a
2821/// ~120px sliver at the bottom. Every one of `eq_card_w`/`card_max_w`'s own
2822/// unit tests stayed green throughout, because none of them knew a
2823/// containing box existed at all -- the same class of gap as `canvas()`
2824/// silently rendering black under a `Block` parent.
2825///
2826/// This binary has no `TestAppContext` to mount `dock_stance::clip_tab` /
2827/// `ui::stance::render` for real and read painted rects back, so it cannot
2828/// see the div nesting itself -- only driving the app and screenshotting it
2829/// proves the fix actually lands on screen (this is that admission, not a
2830/// substitute for it). What this test *can* pin down in pure values is the
2831/// room each mount site is fed after the fix: [`dock_stance`]'s un-maximized
2832/// mount is handed the dock's own real width (not the window's, the "480 in
2833/// 280" shape of the width-clip bug), and a maximized card is handed
2834/// `stance-centre`'s width -- the window minus the dock it
2835/// escaped -- which must come out *larger*, not smaller, than the docked
2836/// room it replaces. A future change that re-nests the maximize mount back
2837/// inside the dock, or hands it the dock's width again, fails this.
2838#[test]
2839fn a_maximized_cards_room_is_bigger_than_the_docked_rooms_not_smaller() {
2840 use crate::SPLIT_W;
2841 use crate::layout::{Split, split_size};
2842
2843 // `layout::SPLIT_W` is the one divider between `stance-centre` and the
2844 // dock; the 56px rail that used to eat the centre's left edge is gone
2845 // (2026-09-09, "option C"), so the centre is everything but the dock.
2846
2847 for window_w in [960., 1280., 1920.] {
2848 let window = size(px(window_w), px(720.));
2849 // `split_size`'s own default/floor/ceiling for the dock, with no
2850 // hand having dragged the seam -- the exact width `dock_stance.rs`
2851 // now feeds its un-maximized cards as their "room".
2852 let dock_w = split_size(Split::Dock, None, 2, window, false);
2853 let docked_room_w = dock_w;
2854 let maximized_room_w = window_w - SPLIT_W - dock_w;
2855
2856 assert!(
2857 maximized_room_w > docked_room_w,
2858 "at a {window_w}px window a maximized card's room ({maximized_room_w}px, \
2859 stance-centre) is not wider than the docked room it escaped \
2860 ({docked_room_w}px, dock-clip-rows) -- maximize would be making \
2861 the card smaller again"
2862 );
2863 assert!(
2864 maximized_room_w <= window_w,
2865 "a maximized card's room ({maximized_room_w}px) exceeds the whole \
2866 window ({window_w}px) -- it is being measured in the wrong space"
2867 );
2868 // The concrete pixel gain a driving agent should actually see: the
2869 // EQ graph's own width formula, fed each mount's real room.
2870 assert!(
2871 eq_card_w(maximized_room_w, true) > eq_card_w(docked_room_w, false),
2872 "maximizing the EQ card at a {window_w}px window does not grow \
2873 eq_card_w's output"
2874 );
2875 }
2876}
2877
2878/// DESIGN's "a maximized scrim covers only the bench/ledger/time-band band,
2879/// never the picture": the floor a maximized card's `.top()` is pinned to
2880/// must leave exactly the picture's own height above it, for any bench
2881/// height a hand has dragged the seam to -- not just the untouched
2882/// `BENCH_H` default. `below_picture_floor` takes the live bench height as
2883/// its own second argument (the seam feature merged onto this branch), so
2884/// this checks the real two-argument signature rather than a stale one-arg
2885/// assumption.
2886#[test]
2887fn a_maximized_card_can_never_rise_above_the_picture_no_matter_the_bench_height() {
2888 use crate::ui::stance::{LEDGER_H, TIME_BAND_H, below_picture_floor};
2889 let viewport_h = 1080.;
2890 for bench_h in [140., 200., 400.] {
2891 assert_eq!(
2892 below_picture_floor(viewport_h, bench_h) + TIME_BAND_H + bench_h + LEDGER_H,
2893 viewport_h,
2894 "below_picture_floor's floor plus the band below the picture no \
2895 longer adds back up to the window -- a maximized scrim could rise \
2896 into the picture"
2897 );
2898 }
2899 // A bench dragged tall enough to eat the whole window still clamps at
2900 // zero rather than going negative and reporting free room that is not
2901 // there.
2902 assert_eq!(below_picture_floor(300., 5000.), 0.);
2903}
2904
2905/// The maximize flag's own small round trip (`dock_stance.rs`'s own doc
2906/// comment: "the same small-file round trip as the dock tab pick", "a room
2907/// reopens exactly as left"): saved, read back, and silently defaulted to
2908/// `false` on a corrupt or absent file -- never a startup crash or notice
2909/// over the user's own work, the same rule `load_subtitle_style`'s own test
2910/// (`tests/media.rs`) already pins for its sibling config file. `XDG_CONFIG_HOME`
2911/// is the existing scratch-path override every config-round-trip test in
2912/// this crate already uses; there is no maximize-specific override to
2913/// invent.
2914#[test]
2915fn a_maximized_card_reopens_exactly_as_left_across_a_restart() {
2916 let _config_env = config_env_lock();
2917
2918 let dir = std::env::temp_dir().join(format!(
2919 "edith-test-maximized-{}-{}",
2920 std::process::id(),
2921 std::time::SystemTime::now()
2922 .duration_since(std::time::UNIX_EPOCH)
2923 .unwrap()
2924 .as_nanos()
2925 ));
2926 std::fs::create_dir_all(&dir).unwrap();
2927 // `config_env_lock` serializes every test that changes this process-wide
2928 // path.
2929 crate::keymap::set_test_config_home(Some(dir.clone()));
2930
2931 // Nothing written yet: the default (not maximized), not a crash on a
2932 // missing file.
2933 assert!(!crate::ui::dock_stance::load_maximized());
2934
2935 crate::ui::dock_stance::save_maximized(true);
2936 assert!(crate::ui::dock_stance::load_maximized());
2937
2938 crate::ui::dock_stance::save_maximized(false);
2939 assert!(!crate::ui::dock_stance::load_maximized());
2940
2941 // A file from a future/corrupt version leaves the default in force
2942 // rather than failing the room that opens over it.
2943 std::fs::write(
2944 crate::ui::dock_stance::maximized_config_path(),
2945 "not a bool\n",
2946 )
2947 .unwrap();
2948 assert!(!crate::ui::dock_stance::load_maximized());
2949
2950 crate::keymap::set_test_config_home(None);
2951 std::fs::remove_dir_all(&dir).ok();
2952}
2953
2954/// Source preview must retain the mouse doors beside its `esc` stop chord:
2955/// `screen` routes the Darkroom through `picture_area`, and that shared
2956/// picture mounts the scrub bar whose press starts the root-tracked drag.
2957#[test]
2958fn darkroom_preview_mounts_stop_and_drag_scrub() {
2959 let stance = src_text("ui/stance.rs");
2960 let screen = &stance[stance.find("fn screen(").expect("the Darkroom screen")..];
2961 assert!(
2962 screen.contains(".children(player.source_strip(window, cx))"),
2963 "the Darkroom screen no longer mounts the source strip"
2964 );
2965 assert!(
2966 screen.contains("player.picture_area(position, window, cx).into_any_element()"),
2967 "the Darkroom screen no longer routes through the shared picture"
2968 );
2969
2970 let preview = src_text("ui/preview.rs");
2971 assert!(
2972 preview.contains("this.preview_scrubbing = true")
2973 && preview.contains("this.preview_scrub_to(event.position.x, true, cx)"),
2974 "the mounted preview scrub no longer starts its drag-and-seek gesture"
2975 );
2976}
2977
2978/// Source management must stay reachable in the Darkroom itself: pointer
2979/// Add-at-playhead alongside its `↵` chord on the row, and -- since cleanse
2980/// round 2 (2026-09-10) took the `▷` and `○` ghosts off the row -- preview
2981/// and the per-file stand-in in the row's own right-click menu, each still
2982/// calling the one implementation it always called. The test reads the
2983/// mounted dock source because this binary has no `TestAppContext` to inspect
2984/// GPUI's painted controls.
2985#[test]
2986fn darkroom_source_rows_keep_proxy_add_and_preview_doors() {
2987 let dock = src_text("ui/dock_stance.rs");
2988 let row_at = dock.find("fn source_row(").expect("Darkroom source row");
2989 let row = &dock[row_at..];
2990 for needle in [
2991 "dock-add-at-playhead",
2992 "Append to timeline end",
2993 "this.append_source(",
2994 ] {
2995 assert!(
2996 row.contains(needle),
2997 "Darkroom source row lost `{needle}`: a source must keep its \
2998 mouse-reachable Add-at-playhead path"
2999 );
3000 }
3001 // The two former ghosts, in the menu the same row opens.
3002 assert!(
3003 crate::ROW_ITEMS.contains(&crate::RowItem::Preview)
3004 && crate::ROW_ITEMS.contains(&crate::RowItem::Proxy),
3005 "the row menu lost Preview or Proxy"
3006 );
3007 let actions = src_text("player/actions.rs");
3008 for needle in [
3009 "self.open_preview(&menu.path, menu.stream, cx);",
3010 "self.toggle_proxy(&menu.path, stops, cx);",
3011 ] {
3012 assert!(
3013 actions.contains(needle),
3014 "the row menu's `{needle}` is a second implementation, not the door"
3015 );
3016 }
3017 // One list, no sub-tabs: a row says its kind on its own metadata line.
3018 for gone in [
3019 "LIBRARY_TABS",
3020 "library_tab",
3021 "dock-source-filter",
3022 "dock.sort.cycle",
3023 ] {
3024 assert!(
3025 !dock.contains(gone),
3026 "the dock still carries `{gone}`: Sources is one list now"
3027 );
3028 }
3029}
3030
3031/// DEBT #91: a click-to-stop while a stand-in's header is still being read
3032/// must reach the flag the read itself polls (`engine::proxy::started`), not
3033/// only relabel the row. Read off the source and not run, the way the row
3034/// above it is -- there is no `TestAppContext` in this binary to construct a
3035/// `Context<Player>` and call `toggle_proxy` on. On the state this fix
3036/// replaced, `start_proxy_for` handed the header read a flag nothing outside
3037/// it could reach and `Proxy::Asked` carried no field to store a stop into,
3038/// so `library.find("Proxy::Asked(cancel)")` below has nothing to find.
3039#[test]
3040fn toggle_proxy_wakes_the_asked_phase_it_stops() {
3041 let library = src_text("player/library.rs");
3042 let start = &library[library
3043 .find("fn start_proxy_for(")
3044 .expect("start_proxy_for")..];
3045 assert!(
3046 start.contains("generate_if_wanted(&path, &cancel)"),
3047 "start_proxy_for no longer hands the header read a cancel flag anyone can reach"
3048 );
3049 let toggle = &library[library.find("fn toggle_proxy(").expect("toggle_proxy")..];
3050 let asked_arm = &toggle[toggle
3051 .find("Proxy::Asked(cancel)")
3052 .expect("the Asked arm's own flag")..];
3053 assert!(
3054 asked_arm.contains("cancel.store(true"),
3055 "a stop asked during Asked no longer sets the flag the header read polls"
3056 );
3057}
3058
3059/// A wheel notch on the budget must not re-ask the seat probe. The probe opens
3060/// a real VA-API encoder (ten opens for ten notches before this, 5-32 ms of GPU
3061/// work each, against the player's own decoder) and its answer -- GPU seat or
3062/// software, copy or encode -- does not depend on the bitrate at all. So the
3063/// settings it is keyed on carry no budget, and the budget still reaches the
3064/// export itself, which is the one place it changes a file.
3065#[test]
3066fn the_seat_probe_is_not_keyed_on_the_budget() {
3067 let seat = EncoderSeat::default();
3068 let asked = crate::probe_settings(Format::Mp4, DEFAULT_AUDIO_KBPS, seat);
3069 assert_eq!(asked.bitrate, None, "no budget is in the probe's question");
3070 // What still *is* a new question: the format the file is written in.
3071 assert_ne!(
3072 asked,
3073 crate::probe_settings(Format::Av1, DEFAULT_AUDIO_KBPS, seat),
3074 "a format change must re-probe"
3075 );
3076 let cache = fn_body("cache_export_seat");
3077 assert!(
3078 cache.contains("probe_settings(") && !cache.contains("budget_bps()"),
3079 "the seat cache is keyed on the budget again"
3080 );
3081 // ...and the number the wheel moves is still what the export is given.
3082 assert!(
3083 fn_body("export_settings_now").contains("self.budget_bps()"),
3084 "the export no longer writes at the budget on the row"
3085 );
3086}
3087
3088/// DESIGN §8, the class behind the user's "word cut" (2026-09-09): a picker
3089/// row's tail is a *state word* -- at most two -- because the plate is
3090/// `MENU_W` wide and prose loses its last word to the truncation on exactly
3091/// the row a reader is looking at (the resolution list's checked row read
3092/// "3840x2160 · the medi…"). The same rule for the settings page's own row
3093/// values: a value slot carries the state, never the door's noun elided to
3094/// an ellipsis ("Subtitle font Font…", "Mix Tracks…").
3095#[test]
3096fn picker_row_tails_are_state_words_and_settings_values_carry_no_ellipsis() {
3097 let lists = [
3098 resolution_choices((1280, 720), (3840, 2160)),
3099 pending_resolution_choices(Some(RESOLUTIONS[1])),
3100 pending_fps_choices(Some(FRAME_RATES[0])),
3101 sample_rate_choices(None),
3102 ];
3103 for (.., detail, _) in lists.iter().flatten() {
3104 let words = detail.split_whitespace().count();
3105 // The media's own rung says what it matches in words: a state, not prose.
3106 let state = detail.ends_with("(matches your media)") || detail == "matches your media";
3107 assert!(
3108 words <= 2 || state,
3109 "picker row tail {detail:?} is {words} words -- `MENU_W` cuts prose"
3110 );
3111 assert!(
3112 !detail.contains('\u{2026}') && !detail.contains('\u{b7}'),
3113 "picker row tail {detail:?} carries prose punctuation"
3114 );
3115 }
3116 // Code lines only: the comments above the two rows this fixed quote the
3117 // strings the bug shipped as.
3118 let settings = src_text("ui/settings_stance.rs");
3119 for line in settings
3120 .lines()
3121 .filter(|l| !l.trim_start().starts_with("//"))
3122 {
3123 assert!(
3124 !line.contains('\u{2026}'),
3125 "a settings row value is elided with an ellipsis again: {line}"
3126 );
3127 }
3128}
3129
3130/// D1: the project's own settings are the project's -- the resolution, the
3131/// rate, the encoder seat, the mix rate and the two proxy switches ride in
3132/// the same history entry the lanes do, so every one of those picks is a
3133/// single `ctrl+z`. Before this, pressing `z` after any of them did nothing.
3134#[test]
3135fn a_settings_pick_undoes_and_redoes_like_a_cut() {
3136 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
3137 let (w, h) = session.resolution();
3138
3139 assert!(session.set_resolution(w / 2, h / 2));
3140 assert_eq!(session.resolution(), (w / 2, h / 2));
3141 assert!(session.undo(), "the resolution pick is one step");
3142 assert_eq!(session.resolution(), (w, h), "and the canvas comes back");
3143 assert!(session.redo(), "redo walks the same branch");
3144 assert_eq!(session.resolution(), (w / 2, h / 2));
3145 assert!(session.undo(), "back to where the test started");
3146
3147 // The encoder seat, which nothing reseeks and nothing shows until an
3148 // export starts.
3149 let seat = session.encoder_seat();
3150 assert_ne!(seat, EncoderSeat::Software);
3151 session.set_encoder_seat(EncoderSeat::Software);
3152 assert_eq!(session.encoder_seat(), EncoderSeat::Software);
3153 assert!(session.undo(), "the encoder pick is one step");
3154 assert_eq!(session.encoder_seat(), seat, "and the seat comes back");
3155 assert!(session.redo());
3156 assert_eq!(session.encoder_seat(), EncoderSeat::Software);
3157 assert!(session.undo());
3158
3159 // The mix rate, and the switches beside it.
3160 session.set_sample_rate(Some(44_100));
3161 assert_eq!(session.sample_rate(), Some(44_100));
3162 assert!(session.undo(), "the mix rate is one step");
3163 assert_eq!(session.sample_rate(), None, "back to the derived rate");
3164 let proxies = session.proxies();
3165 session.set_proxies(!proxies);
3166 assert_eq!(session.proxies(), !proxies);
3167 assert!(session.undo(), "the proxy switch is one step");
3168 assert_eq!(session.proxies(), proxies, "and the switch comes back");
3169 let auto = session.auto_proxies();
3170 session.set_auto_proxies(!auto);
3171 assert_eq!(session.auto_proxies(), !auto);
3172 assert!(session.undo(), "and so is the auto switch");
3173 assert_eq!(session.auto_proxies(), auto, "which comes back too");
3174
3175 // ...and a lane edit still undoes the way it always did, settings and all
3176 // in the same stack.
3177 let clips = session.lane_clips(Lane::V1).len();
3178 assert_eq!(clips, 1, "one take to start with");
3179 assert!(session.delete_clip(Lane::V1, 0));
3180 assert_eq!(session.lane_clips(Lane::V1).len(), 0);
3181 assert!(session.undo(), "the delete is one step");
3182 assert_eq!(session.lane_clips(Lane::V1).len(), clips);
3183}
3184
3185// The mix panel's meters, solo set and slider maths -- the parts of the card
3186// that are not drawn, so they can be pinned without a window.
3187
3188#[test]
3189fn a_meter_rises_at_once_and_falls_at_a_fixed_rate() {
3190 use crate::player::cards::{METER_FLOOR_DB, MixMeter};
3191 let t0 = Instant::now();
3192 let mut meter = MixMeter::default();
3193 assert_eq!(meter.level_db, METER_FLOOR_DB, "a new meter reads silence");
3194 meter.feed(1.0, t0);
3195 assert!(
3196 meter.level_db.abs() < 1e-3,
3197 "full scale reads 0 dBFS at once"
3198 );
3199 // Half a second of silence, read every tenth of one, falls 10 dB at 20 dB
3200 // a second. (A read is capped at a quarter second, so one long gap would
3201 // fall 5 dB at most -- which is the point of the cap.)
3202 for step in 1..=5 {
3203 meter.feed(0.0, t0 + Duration::from_millis(100 * step));
3204 }
3205 assert!((meter.level_db + 10.).abs() < 0.01, "{}", meter.level_db);
3206 // A long pause between two reads is capped, not a drop through the floor.
3207 meter.feed(0.0, t0 + Duration::from_secs(60));
3208 assert!(meter.level_db > -16., "{}", meter.level_db);
3209}
3210
3211#[test]
3212fn a_meter_holds_its_peak_for_a_second_then_lets_it_fall() {
3213 use crate::player::cards::MixMeter;
3214 let t0 = Instant::now();
3215 let mut meter = MixMeter::default();
3216 meter.feed(1.0, t0);
3217 meter.feed(0.0, t0 + Duration::from_millis(900));
3218 assert!(meter.hold_db.abs() < 1e-3, "still held at 0.9 s");
3219 meter.feed(0.0, t0 + Duration::from_secs(2));
3220 assert!(
3221 (meter.hold_db + 5.).abs() < 0.01,
3222 "the marker falls once the hold is over: {}",
3223 meter.hold_db
3224 );
3225 meter.reset();
3226 assert_eq!(meter, MixMeter::default(), "a reset meter reads silence");
3227}
3228
3229#[test]
3230fn meter_db_is_dbfs_floored_at_the_bottom_of_the_bar() {
3231 use crate::player::cards::{METER_FLOOR_DB, meter_db};
3232 assert!(meter_db(1.0).abs() < 1e-4);
3233 assert!((meter_db(0.1) + 20.).abs() < 1e-3);
3234 assert_eq!(meter_db(0.), METER_FLOOR_DB);
3235 assert_eq!(meter_db(1e-9), METER_FLOOR_DB, "below the floor pins to it");
3236}
3237
3238#[test]
3239fn solo_toggles_a_lane_in_and_out_and_keeps_the_order() {
3240 use crate::player::cards::solo_toggled;
3241 let (a1, a2, a3) = (
3242 Lane::new(LaneKind::Audio, 0),
3243 Lane::new(LaneKind::Audio, 1),
3244 Lane::new(LaneKind::Audio, 2),
3245 );
3246 let solo = solo_toggled(&[], a2);
3247 assert_eq!(solo, vec![a2]);
3248 let solo = solo_toggled(&solo, a1);
3249 assert_eq!(solo, vec![a2, a1], "joins at the end");
3250 assert_eq!(
3251 solo_toggled(&solo, a2),
3252 vec![a1],
3253 "a second press lets it go"
3254 );
3255 assert!(solo_toggled(&solo_toggled(&[], a3), a3).is_empty());
3256}
3257
3258#[test]
3259fn a_meter_reads_the_audio_lane_the_engine_levels_index() {
3260 use crate::player::cards::meter_slot_in;
3261 let (a1, a2, a3) = (
3262 Lane::new(LaneKind::Audio, 0),
3263 Lane::new(LaneKind::Audio, 1),
3264 Lane::new(LaneKind::Audio, 2),
3265 );
3266 // A1 is empty: the engine's levels have no slot for it.
3267 let sounding = [a2, a3];
3268 assert_eq!(meter_slot_in(&sounding, a2), Some(0));
3269 assert_eq!(meter_slot_in(&sounding, a3), Some(1));
3270 assert_eq!(meter_slot_in(&sounding, a1), None);
3271 // With no sound at all the engine plays A1 as its one slot.
3272 assert_eq!(meter_slot_in(&[], Lane::A1), Some(0));
3273 assert_eq!(meter_slot_in(&[], a2), None);
3274}
3275
3276#[test]
3277fn a_slider_press_maps_onto_its_range_and_clamps() {
3278 use crate::player::cards::{bar_fraction, value_at};
3279 use engine::project::{MAX_GAIN_DB, MIN_GAIN_DB};
3280 assert_eq!(value_at(0., MIN_GAIN_DB, MAX_GAIN_DB), MIN_GAIN_DB);
3281 assert_eq!(value_at(1., MIN_GAIN_DB, MAX_GAIN_DB), MAX_GAIN_DB);
3282 assert!((value_at(0.5, -60., 12.) + 24.).abs() < 1e-4);
3283 assert_eq!(value_at(2., -60., 12.), 12., "past the end pins to it");
3284 assert_eq!(value_at(-1., -60., 12.), -60.);
3285 // A bar that has not been drawn yet answers nothing rather than dividing.
3286 assert_eq!(bar_fraction(Bounds::default(), px(10.)), None);
3287 let bar = Bounds::new(point(px(0.), px(0.)), size(px(200.), px(4.)));
3288 assert_eq!(bar_fraction(bar, px(50.)), Some(0.25));
3289}
3290
3291/// Export follow-ups (X1): an export no longer makes the room modal, so what
3292/// it must refuse is refused by the oracle and says why -- these pin the
3293/// wiring of each piece by source, the way the guards above do, since there is
3294/// no window here to press the keys.
3295#[test]
3296fn an_export_done_toast_offers_play_then_show_in_folder() {
3297 let actions = src_text("player/actions.rs");
3298 assert!(
3299 actions.contains(
3300 "ToastAction::Play(path.clone()),\n ToastAction::ShowInFolder(path),"
3301 ),
3302 "the export-done toast no longer carries Play then Show in folder"
3303 );
3304 assert!(
3305 actions.contains("xdg-open") && actions.contains("ToastAction::Play(path) =>"),
3306 "Play no longer opens the file in the default player off the UI thread"
3307 );
3308 let stance = src_text("ui/stance.rs");
3309 assert!(
3310 stance.contains("toast.actions.iter().enumerate()")
3311 && stance.contains("ToastAction::Play(_) => \"Play\""),
3312 "the toast draws one button per action, Play included"
3313 );
3314}
3315
3316#[test]
3317fn a_running_export_is_refused_by_the_oracle_not_by_the_modal() {
3318 let body = fn_body("modal");
3319 assert!(
3320 !body.contains("exporting"),
3321 "modal() reads exporting() again -- an export would swallow the keyboard"
3322 );
3323 // The picked-row Add is a second door to the edit list: it asks the row
3324 // oracle, which refuses it while an export reads the list.
3325 let actions = src_text("player/actions.rs");
3326 assert!(
3327 actions.contains("crate::oracle::row_enable(item, self.row_ctx(&path, stream))"),
3328 "the media panel's Add no longer asks the row oracle during an export"
3329 );
3330 // Escape is Deselect and an export refuses it, so the press says what does
3331 // cancel instead of doing nothing.
3332 let stance = src_text("ui/stance.rs");
3333 assert!(
3334 stance.contains("if key == ESCAPE && !ctrl && this.exporting().is_some()")
3335 && stance.contains("Esc keeps the export running."),
3336 "Esc during an export no longer says that the export keeps running"
3337 );
3338}
3339
3340#[test]
3341fn a_webm_export_says_why_the_subtitles_do_not_travel() {
3342 let card = src_text("ui/cards/export.rs");
3343 assert!(
3344 card.contains(".filter(|_| self.format == Format::Webm)")
3345 && card.contains("s.planned_subtitles(self.format, 0..s.subtitles().len())")
3346 && card.contains(".filter(|why| why != \"none\")"),
3347 "the export card no longer shows the engine's subtitle reason for WebM"
3348 );
3349}
3350
3351#[test]
3352fn the_gui_opens_on_the_software_seat_and_keeps_a_hardware_pick() {
3353 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
3354 // The engine's own default (and every old saved project) is Auto, which can
3355 // resolve to VA-API encode; the window never starts there.
3356 assert_eq!(session.encoder_seat(), EncoderSeat::Auto);
3357 gui_default_seat(&mut session);
3358 assert_eq!(session.encoder_seat(), EncoderSeat::Software);
3359 session.set_encoder_seat(EncoderSeat::Hardware);
3360 gui_default_seat(&mut session);
3361 assert_eq!(session.encoder_seat(), EncoderSeat::Hardware, "an explicit pick stays");
3362 // Auto and Hardware are named as the GPU encoder in the list.
3363 let rows = encoder_choices(EncoderSeat::Software);
3364 assert!(rows[0].2.contains("GPU encoder") && rows[1].2.contains("GPU encoder"));
3365}
3366
3367#[test]
3368fn a_marked_span_says_how_long_it_is() {
3369 assert_eq!(span_word(1, 30.), "1 frame");
3370 assert_eq!(span_word(12, 30.), "12 frames");
3371 assert_eq!(span_word(1140, 30.), "38 s");
3372 assert_eq!(span_word(2340, 30.), "1 min 18 s");
3373}
3374
3375/// The keyframe doors: four actions on the Clip menu and the palette, a diamond
3376/// and the easing chips on the cards, and the sliders writing a key (not the
3377/// clip's single value) once the clip is keyed.
3378#[test]
3379fn the_cards_carry_keyframe_diamonds_and_keyed_writes() {
3380 let act = source_from("pub(crate) fn act(");
3381 for arm in [
3382 "ActionId::KeyPlacement => self.toggle_key_here(engine::project::KeyKind::Placement, cx)",
3383 "ActionId::KeyOpacity => self.toggle_key_here(engine::project::KeyKind::Opacity, cx)",
3384 "ActionId::KeyColor => self.toggle_key_here(engine::project::KeyKind::Color, cx)",
3385 "ActionId::KeyEasing => self.open_key_easing(self.ledger_anchor(LedgerItem::Clip), cx)",
3386 ] {
3387 assert!(act.contains(arm), "act() lacks `{arm}`");
3388 }
3389 let ui = ui_source();
3390 for id in ["key-diamond", "key-ease", "transform-opacity"] {
3391 assert!(ui.contains(&format!("\"{id}\"")), "{id} is on no card");
3392 }
3393 for a in [ActionId::KeyPlacement, ActionId::KeyOpacity, ActionId::KeyColor, ActionId::KeyEasing] {
3394 assert!(
3395 ui.contains(&format!("Act(ActionId::{a:?})")) || ui.contains(&format!("Choice(ActionId::{a:?})")),
3396 "{a:?} is on no menu"
3397 );
3398 }
3399 assert!(fn_body("write_transform_now").contains("put_transform_key_at("));
3400 assert!(fn_body("write_transform_now").contains("put_opacity_key_at("));
3401 assert!(fn_body("write_color_now").contains("put_color_key_at("));
3402}
3403
3404// The mix card's dynamics sliders: each one reads and writes exactly its own
3405// setting, snapped to its step, and every processor's sliders are listed.
3406
3407#[test]
3408fn voice_sliders_read_and_write_their_own_setting_and_snap_to_the_step() {
3409 use crate::player::cards::{VoiceParam, VoiceProc};
3410 use engine::voice::VoiceFx;
3411 let mut fx = VoiceFx::default();
3412 for which in VoiceProc::ALL {
3413 assert!(!which.params().is_empty(), "{which:?} has no slider");
3414 for &param in which.params() {
3415 let (lo, hi, step) = param.range();
3416 let before = fx.clone();
3417 param.set(&mut fx, hi + 100.);
3418 assert!((param.get(&fx) - hi).abs() < 1e-4, "{param:?} clamps to {hi}");
3419 param.set(&mut fx, lo - 100.);
3420 assert!((param.get(&fx) - lo).abs() < 1e-4, "{param:?} clamps to {lo}");
3421 param.set(&mut fx, lo + step * 2.4);
3422 assert!(((param.get(&fx) - lo) / step - 2.).abs() < 1e-3, "{param:?} snaps");
3423 assert!(!param.text(param.get(&fx)).is_empty());
3424 fx = before;
3425 }
3426 }
3427 // A slider moves its own setting and not the processor's switch.
3428 VoiceParam::CompRatio.set(&mut fx, 6.);
3429 assert_eq!(fx.comp.ratio, 6.);
3430 assert!(!fx.comp.on && !fx.is_default());
3431 // A hand-set makeup turns the automatic makeup off.
3432 fx.comp.auto_makeup = true;
3433 VoiceParam::CompMakeup.set(&mut fx, 4.);
3434 assert!(!fx.comp.auto_makeup && (fx.comp.makeup() - 4.).abs() < 1e-4);
3435}
3436
3437// ---- the speed card's ramp editor ------------------------------------------
3438
3439fn ramp_key(at: u32, permille: u16) -> engine::project::SpeedKey {
3440 engine::project::SpeedKey {
3441 at,
3442 speed: Speed::from_permille(permille),
3443 }
3444}
3445
3446/// Every shape the card and the palette offer is a ramp the engine takes, on any clip
3447/// long enough to hold its keys a frame apart -- and one that is not long enough is
3448/// refused by the shape, not by an engine error the hand cannot act on.
3449#[test]
3450fn every_ramp_preset_is_keys_the_engine_takes() {
3451 use crate::audio_cards::RampPreset;
3452 for preset in RampPreset::ALL {
3453 for frames in [1u32, 2, 3, 30, 150] {
3454 match preset.keys(frames) {
3455 Some(keys) => {
3456 assert!(engine::project::valid_speed_keys(&keys), "{preset:?} over {frames}");
3457 assert_eq!(keys[0].at, 0, "{preset:?} starts with the clip");
3458 assert_eq!(keys.last().map(|k| k.at), Some(frames), "{preset:?} spans it");
3459 }
3460 None => assert!(frames < 2, "{preset:?} refuses {frames} frames"),
3461 }
3462 }
3463 }
3464 // The shapes are the ones their names say.
3465 let speeds = |p: RampPreset| -> Vec<u16> {
3466 p.keys(60)
3467 .expect("long enough")
3468 .iter()
3469 .map(|k| k.speed.permille())
3470 .collect()
3471 };
3472 assert_eq!(speeds(RampPreset::Up), [1000, 2000]);
3473 assert_eq!(speeds(RampPreset::Down), [2000, 1000]);
3474 assert_eq!(speeds(RampPreset::SlowFastSlow), [500, 2000, 500]);
3475 assert_eq!(speeds(RampPreset::FastSlowFast), [2000, 500, 2000]);
3476}
3477
3478/// The preset through the session the card writes to: the clip takes the keys, its
3479/// footprint is the ramp's, and one undo takes the whole thing back.
3480#[test]
3481fn a_ramp_preset_lands_on_a_clip_in_one_undo_step() {
3482 use crate::audio_cards::RampPreset;
3483 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
3484 session.set_gain(0.0);
3485 let before = session.lane_clips(Lane::V1)[0].clone();
3486 for preset in RampPreset::ALL {
3487 let keys = preset.keys(before.frames()).expect("the fixture is long");
3488 session
3489 .set_speed_ramp(Lane::V1, 0, &keys)
3490 .expect("a clip alone on its lane takes a ramp");
3491 let clip = session.lane_clips(Lane::V1)[0].clone();
3492 assert_eq!(clip.speed_keys, keys, "{preset:?}");
3493 assert_eq!(
3494 clip.frames(),
3495 engine::project::ramp_frames(&keys, clip.len()),
3496 "{preset:?}: the footprint is the ramp's"
3497 );
3498 assert!(session.undo(), "{preset:?} is one undo step");
3499 assert_eq!(session.lane_clips(Lane::V1)[0], before, "{preset:?} undone");
3500 }
3501}
3502
3503/// Adding a key slots it in order, replaces one at the same frame, and stops at the
3504/// engine's cap; removing the last key leaves no ramp; a stepper moves a quarter and
3505/// stays inside what a speed can hold.
3506#[test]
3507fn ramp_key_edits_keep_the_keys_in_order_and_inside_their_limits() {
3508 use crate::audio_cards::{ramp_key_stepped, ramp_with_key, ramp_without_key};
3509 let base = vec![ramp_key(0, 1000), ramp_key(60, 2000)];
3510 let inserted = ramp_with_key(&base, 30, Speed::from_permille(500)).expect("room");
3511 assert_eq!(inserted, [ramp_key(0, 1000), ramp_key(30, 500), ramp_key(60, 2000)]);
3512 assert_eq!(
3513 ramp_with_key(&inserted, 30, Speed::from_permille(750)).expect("replaces"),
3514 [ramp_key(0, 1000), ramp_key(30, 750), ramp_key(60, 2000)]
3515 );
3516 assert_eq!(
3517 ramp_with_key(&base, 90, Speed::NORMAL).expect("room"),
3518 [ramp_key(0, 1000), ramp_key(60, 2000), ramp_key(90, 1000)],
3519 "past the last key"
3520 );
3521 assert!(engine::project::valid_speed_keys(&inserted));
3522 let mut full: Vec<_> = (0..engine::project::MAX_SPEED_KEYS as u32)
3523 .map(|i| ramp_key(i * 10, 1000))
3524 .collect();
3525 assert!(ramp_with_key(&full, 5, Speed::NORMAL).is_none(), "a ninth key is refused");
3526 assert!(ramp_with_key(&full, 10, Speed::from_permille(500)).is_some(), "but a replace is not");
3527 full.truncate(1);
3528 assert!(ramp_without_key(&full, 0).is_empty(), "the last key out clears the ramp");
3529 assert_eq!(ramp_without_key(&base, 0), [ramp_key(60, 2000)]);
3530 let stepped = ramp_key_stepped(&base, 1, 1);
3531 assert_eq!(stepped[1].speed.permille(), 2250);
3532 assert_eq!(ramp_key_stepped(&base, 0, -10)[0].speed, Speed::MIN);
3533 assert_eq!(ramp_key_stepped(&base, 1, 100)[1].speed, Speed::MAX);
3534}
3535
3536/// A clip's box wears its ramp: the keys joined by arrows, shortened past three, and
3537/// nothing at all for a clip at real time.
3538#[test]
3539fn the_clip_label_shows_the_ramp() {
3540 use crate::audio_cards::speed_chip_text;
3541 let mut clip = Clip::source_range(0, 0, 100);
3542 assert_eq!(speed_chip_text(&clip), None);
3543 clip.speed = Speed::from_permille(2000);
3544 assert_eq!(speed_chip_text(&clip).as_deref(), Some("2×"));
3545 clip.speed_keys = vec![ramp_key(0, 1000), ramp_key(60, 2000)];
3546 assert_eq!(speed_chip_text(&clip).as_deref(), Some("1×→2×"));
3547 clip.speed_keys = vec![ramp_key(0, 500), ramp_key(30, 2000), ramp_key(60, 500)];
3548 assert_eq!(speed_chip_text(&clip).as_deref(), Some("0.5×→2×→0.5×"));
3549 clip.speed_keys = (0..5).map(|i| ramp_key(i * 10, 1000 + 250 * i as u16)).collect();
3550 assert_eq!(speed_chip_text(&clip).as_deref(), Some("1×→2× (5 keys)"));
3551}
3552
3553/// The curve the card draws starts and ends on the ramp's first and last speeds, passes
3554/// through a key's height at the key, and sits level for a clip without a ramp.
3555#[test]
3556fn the_ramp_curve_runs_through_its_keys() {
3557 use crate::audio_cards::ramp_curve;
3558 let keys = [ramp_key(0, 500), ramp_key(30, 2000), ramp_key(60, 500)];
3559 let curve = ramp_curve(&keys, Speed::NORMAL, 60, 60);
3560 assert_eq!(curve.len(), 61);
3561 assert!((curve[0].1 - speed_fraction(500.)).abs() < 1e-6);
3562 assert!((curve[30].1 - speed_fraction(2000.)).abs() < 1e-6, "the middle key");
3563 assert!((curve[60].1 - speed_fraction(500.)).abs() < 1e-6);
3564 assert!((curve[60].0 - 1.).abs() < 1e-6);
3565 let level = ramp_curve(&[], Speed::from_permille(1500), 60, 8);
3566 assert!(level.iter().all(|&(_, y)| (y - speed_fraction(1500.)).abs() < 1e-6));
3567}
3568
3569/// The palette's entries for the ramp: each is a real action in the Clips category with
3570/// a label that says what it does, and is handled by the table that runs
3571/// actions -- an entry the table forgot would be a row that does nothing.
3572#[test]
3573fn the_ramp_actions_are_in_the_palette_and_run() {
3574 use crate::keymap::{ActionId, Category};
3575 let ramp = [
3576 ActionId::SpeedRampUp,
3577 ActionId::SpeedRampDown,
3578 ActionId::SpeedRampSlowFastSlow,
3579 ActionId::SpeedRampFastSlowFast,
3580 ActionId::SpeedRampKey,
3581 ActionId::SpeedRampClear,
3582 ];
3583 let actions = src_text("player/actions.rs");
3584 for action in ramp {
3585 assert!(ActionId::ALL.contains(&action));
3586 assert_eq!(action.category(), Category::Clips, "{action:?}");
3587 assert!(action.label().to_lowercase().contains("speed"), "{action:?}: {}", action.label());
3588 assert!(
3589 actions.contains(&format!("ActionId::{action:?} =>")),
3590 "{action:?} is in the palette and does nothing"
3591 );
3592 }
3593}
3594
3595/// The effects card writes a whole stack at a time, so each act on it is one
3596/// `set_effects` call and one undo step; a slider drag is held as a draft and is
3597/// one call when the hand lets go.
3598#[test]
3599fn every_effects_card_act_is_one_undo_step() {
3600 use crate::player::effects::{ParamShape, param_shape, snap_param};
3601 use engine::effects::{Effect, EffectKind};
3602 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
3603 let lane = Lane::V1;
3604 let depth = |s: &PlaybackSession| s.undo_depth();
3605 let step = |s: &mut PlaybackSession, stack: Vec<Effect>, what: &str| {
3606 let before = depth(s);
3607 assert!(s.set_effects(lane, 0, stack), "{what} changed nothing");
3608 assert_eq!(depth(s), before + 1, "{what} is not one undo step");
3609 };
3610 // Add, at the end.
3611 let mut stack = session.effects_of(lane, 0).to_vec();
3612 stack.push(Effect::new(EffectKind::Blur));
3613 step(&mut session, stack.clone(), "adding a blur");
3614 stack.push(Effect::new(EffectKind::Vignette));
3615 step(&mut session, stack.clone(), "adding a vignette");
3616 // Switch off.
3617 stack[0].on = false;
3618 step(&mut session, stack.clone(), "switching off");
3619 // Move down.
3620 stack.swap(0, 1);
3621 step(&mut session, stack.clone(), "moving down");
3622 assert_eq!(session.effects_of(lane, 0)[1].kind, EffectKind::Blur);
3623 // A slider drag: the draft is the card's, the clip is written once.
3624 let spec = EffectKind::Blur.params()[0];
3625 let before = depth(&session);
3626 let mut draft = stack.clone();
3627 for raw in [3., 17.3, 42.26] {
3628 draft[1].values[0] = snap_param(&spec, raw);
3629 }
3630 assert_eq!(depth(&session), before, "a held bar writes nothing");
3631 assert!(session.set_effects(lane, 0, draft));
3632 assert_eq!(depth(&session), before + 1);
3633 assert_eq!(session.effects_of(lane, 0)[1].values[0], 42.5);
3634 // Remove.
3635 stack.remove(0);
3636 step(&mut session, stack, "removing");
3637 // The shapes: a switch is a step of 1 over 0..1, the blend mode is words.
3638 let shape = |kind: EffectKind, name: &str| {
3639 let spec = kind.params().iter().find(|p| p.name == name).unwrap();
3640 param_shape(kind, spec)
3641 };
3642 assert_eq!(shape(EffectKind::RectMask, "invert"), ParamShape::Switch);
3643 assert_eq!(shape(EffectKind::Blend, "mode"), ParamShape::Mode);
3644 assert_eq!(shape(EffectKind::Blur, "radius"), ParamShape::Bar);
3645}
3646
3647/// The card has a Clip menu-bar row, a palette command and the dock's verb, and it is a
3648/// picture card: refused over a sound.
3649#[test]
3650fn the_effects_card_is_reachable_and_for_pictures() {
3651 use crate::oracle::{Ctx, Enable, enable};
3652 assert!(ActionId::ALL.contains(&ActionId::Effects));
3653 assert_eq!(ActionId::Effects.label(), "Effects…");
3654 assert!(crate::ui::menubar::Title::Clip.entries().contains(&crate::ui::menubar::Entry::Act(ActionId::Effects)));
3655 let picture = Ctx { clip: Some((Clip::source_range(0, 0, 10), Lane::V1)), timeline: true, playable: true, ..Ctx::default() };
3656 let sound = Ctx { clip: Some((Clip::source_range(0, 0, 10), Lane::A1)), timeline: true, playable: true, ..Ctx::default() };
3657 assert!(!matches!(enable(ActionId::Effects, picture), Enable::Hidden(_)));
3658 assert!(matches!(enable(ActionId::Effects, sound), Enable::Hidden(_)));
3659}
3660
3661#[test]
3662fn colour_sections_cover_every_band_once_and_their_bands_round_trip() {
3663 use crate::color_ui::{
3664 band_neutral, band_spec, band_value, section_bands, set_band, ColorSection, COLOR_SLOTS,
3665 };
3666 let sections = [ColorSection::Basic, ColorSection::Wheels, ColorSection::Curves, ColorSection::Lut];
3667 let all: Vec<usize> = sections.iter().flat_map(|&s| section_bands(s)).collect();
3668 assert_eq!(all, (0..COLOR_SLOTS).collect::<Vec<_>>());
3669
3670 let neutral = engine::color::ColorParams::default();
3671 for band in 0..COLOR_SLOTS {
3672 let (name, lo, hi, _) = band_spec(band);
3673 // Neutral reads as neutral, for every wheel and curve pick.
3674 for pick in 0..3 {
3675 let v = band_value(&neutral, band, pick, pick);
3676 assert!((v - band_neutral(band)).abs() < 1e-4, "{name}: {v}");
3677 }
3678 // A value written reads back, and leaves the rest alone.
3679 let target = lo + 0.3 * (hi - lo);
3680 let mut p = neutral;
3681 set_band(&mut p, band, 1, 2, target);
3682 assert!((band_value(&p, band, 1, 2) - target).abs() < 2e-3, "{name}");
3683 // (An intensity with no LUT to mix is still the identity.)
3684 assert!(band == COLOR_SLOTS - 1 || !p.is_identity(), "{name} changed nothing");
3685 // Putting the neutral back is the identity grade again.
3686 set_band(&mut p, band, 1, 2, band_neutral(band));
3687 assert!(p.is_identity(), "{name} did not reset");
3688 }
3689}
3690
3691/// N5: no card changes its layout when a value changes. The shared slider row
3692/// keeps its Reset on the row whether or not the value is off its default (dimmed
3693/// and inert at rest), and no card hands a row a Reset only once it has changed.
3694#[test]
3695fn a_slider_rows_reset_never_comes_and_goes_with_its_value() {
3696 let widgets = src_text("ui/widgets.rs");
3697 let row = &widgets[widgets.find("pub(crate) fn slider_row").unwrap()..];
3698 let row = &row[..row.find("pub(crate) fn more_fold").unwrap()];
3699 assert!(!row.contains("changed.then_some"), "Reset must not depend on `changed`");
3700 assert!(row.contains("on_reset.map("), "Reset is drawn whenever the card gives one");
3701 for card in ["speed", "color", "mix", "silence", "transform", "substyle", "effects"] {
3702 let src = src_text(&format!("ui/cards/{card}.rs"));
3703 assert!(
3704 !src.contains("changed.then(") && !src.contains("changed.then_some"),
3705 "{card}: a Reset handed over only when changed shifts the layout"
3706 );
3707 }
3708}
3709
3710/// N5, per card: the rows whose presence follows a value are drawn in a slot of
3711/// fixed height (stabilise's Stop/Measure) or are overlays (meter hold, analyser
3712/// note), and the card sources carry no `Reset` row built from `when(changed`.
3713#[test]
3714fn every_card_keeps_its_rows_when_a_value_changes() {
3715 for card in ["speed", "color", "effects", "tools", "transform", "silence", "mix", "eq", "markers", "substyle", "keys", "export"] {
3716 let src = src_text(&format!("ui/cards/{card}.rs"));
3717 assert!(!src.contains(".when(changed"), "{card}: a row appears when a value changes");
3718 assert!(!src.contains(".when(!changed"), "{card}: a row disappears when a value changes");
3719 }
3720 assert!(src_text("ui/cards/transform.rs").contains(".min_h(px(CONTROL_H))"), "stabilise's action slot keeps its height");
3721}
3722
3723/// N9: the Tools card's loudness chips wrap instead of clipping at the card edge.
3724#[test]
3725fn the_tools_loudness_chips_wrap() {
3726 let src = src_text("ui/cards/tools.rs");
3727 // The presets are one equal-width segmented row: three short names that always fit.
3728 assert!(src.contains("segmented_equal(\n \"tools-preset\""));
3729}
3730
3731/// N7: the puck's place and the RGB offsets the sliders hold are one mapping.
3732#[test]
3733fn a_wheel_puck_and_its_rgb_offsets_round_trip() {
3734 use crate::color_ui::{wheel_offsets, wheel_puck, WHEEL_REACH};
3735 for (x, y) in [(0., 0.), (0.5, 0.), (-0.3, 0.6), (0., -0.9), (0.6, 0.6)] {
3736 let [r, g, b] = wheel_offsets(x, y);
3737 assert!((r + g + b).abs() < 1e-6, "tints do not move the master");
3738 let (px, py) = wheel_puck(r, g, b);
3739 assert!((px - x).abs() < 1e-5 && (py - y).abs() < 1e-5, "({x},{y}) -> ({px},{py})");
3740 }
3741 // Past the rim the puck stays on it.
3742 let [r, ..] = wheel_offsets(3., 0.);
3743 assert!((r - WHEEL_REACH).abs() < 1e-6);
3744 // Red sits at 3 o'clock.
3745 let [r, g, b] = wheel_offsets(1., 0.);
3746 assert!(r > 0. && g < 0. && b < 0.);
3747}
3748
3749/// N7: the scope tabs are short, and the curve editor has a square of its own
3750/// rather than being drawn over the scope.
3751#[test]
3752fn the_colour_card_has_short_scope_tabs_and_a_curve_square_of_its_own() {
3753 use crate::color_ui::SCOPE_VIEWS;
3754 assert!(SCOPE_VIEWS.iter().all(|(_, n)| n.len() <= 11));
3755 let src = src_text("ui/cards/color.rs");
3756 assert!(!src.contains("graph_curve"), "no curve drawn over the scope");
3757 assert!(src.contains("color-curve-graph"));
3758}
3759
3760#[test]
3761fn a_pan_scrub_sits_on_a_grid_catches_the_centre_and_stays_in_range() {
3762 use crate::player::pan::{pan_text, scrub_pan_at};
3763 assert_eq!(scrub_pan_at(0., 50., 0.01), 0.5);
3764 assert_eq!(scrub_pan_at(0.5, -50., 0.01), 0., "the centre is caught");
3765 assert_eq!(scrub_pan_at(0., 2., 0.01), 0., "within 3% of the middle is the middle");
3766 assert_eq!(scrub_pan_at(0.9, 500., 0.01), 1.);
3767 assert_eq!(scrub_pan_at(-0.9, -500., 0.01), -1.);
3768 assert_eq!(pan_text(0.), "Centre");
3769 assert_eq!(pan_text(-0.4), "40% L");
3770 assert_eq!(pan_text(0.25), "25% R");
3771}
3772
3773#[test]
3774fn the_master_meter_reads_at_30_hz_latches_clips_and_falls_when_paused() {
3775 use crate::player::cards::{CLIP_LAMP_S, MasterMeter};
3776 use std::time::{Duration, Instant};
3777 let t0 = Instant::now();
3778 let mut m = MasterMeter::default();
3779 let mut asked = 0;
3780 m.step(true, || { asked += 1; [0.5, 0.1] }, t0);
3781 m.step(true, || { asked += 1; [1.0, 1.0] }, t0 + Duration::from_millis(10));
3782 assert_eq!(asked, 1, "a second read inside 33 ms is not taken");
3783 assert!(m.lr[0].level_db > m.lr[1].level_db, "left is louder than right");
3784 assert!(!m.clipped(t0));
3785 m.step(true, || [1.0, 0.2], t0 + Duration::from_millis(40));
3786 assert!(m.clipped(t0 + Duration::from_millis(41)), "a full-scale peak lights the lamp");
3787 assert!(!m.clipped(t0 + Duration::from_secs_f32(CLIP_LAMP_S + 0.1)), "and it goes out");
3788 m.step(false, || [0.0; 2], t0 + Duration::from_millis(80));
3789 assert_eq!(m.lr[0], crate::player::cards::MixMeter::default());
3790 assert!(!m.clipped(t0 + Duration::from_millis(81)));
3791}
3792
3793#[test]
3794fn the_loop_hover_names_what_it_loops() {
3795 use crate::ui::timeband_stance::{loop_tip_hint, loop_tip_name};
3796 assert_eq!(loop_tip_name(Some((10, 40))), "Loop playback");
3797 assert_eq!(loop_tip_name(None), "Loop playback");
3798 assert!(loop_tip_hint(Some((10, 40))).contains("Between In and Out"));
3799 assert!(loop_tip_hint(None).contains("Set In and Out"));
3800}