forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBef5832fTahinli3 months ago597 commits

layout.rs1713 lines, 74.0 KiBHistoryRawDownload
1//! What is drawn and where: the toolbar, the theme, the notices, the lanes
2//! and their marks, the tints, the subtitle rows and the sliders.
3
4use super::*;
5
6/// The edit toolbar against the 640x360 floor the whole editor is measured
7/// at. It does not fit and cannot be made to -- so what it may never do is
8/// *hide* the tail: the row scrolls, and the door to everything scrolled
9/// off it is pinned outside the scrolling box.
10#[test]
11fn toolbar_fits_the_smallest_window() {
12 let toolbar = src_text("ui/toolbar.rs");
13 let row = &toolbar[toolbar.find("pub(crate) fn toolbar(").expect("the toolbar")..];
14 // Every button in the row is a hit target, so none of them is narrower
15 // than `HIT_MIN`, and they sit in 8 px gaps inside the row's own 12 px
16 // padding.
17 let buttons = row.matches("action_control(").count();
18 assert!(buttons >= 11, "the row's buttons moved; this scan is blind");
19 // The row is shorter than it was -- the project's own settings (size,
20 // rate, HDR) are the inspector's now and the transport is the
21 // picture's -- so whether it fits at 640 px depends on the words in it
22 // and is not something this scan can measure. What it can hold to is
23 // the rule: "it scrolls" is not "it can be found", so the door to
24 // whatever is off the right edge is pinned outside the scrolling box
25 // and the card it opens carries every action there is
26 // (`every_action_is_on_the_actions_card`).
27 assert!(
28 row.contains("\"controls-more\""),
29 "nothing pinned beside the scrolling row: the tail is unreachable at 640 px"
30 );
31 assert_eq!(row.matches("overflow_x_scroll").count(), 1);
32 assert!(
33 row.find("\"controls-more\"") > row.find("overflow_x_scroll"),
34 "the pinned door is inside the row it is meant to outlive"
35 );
36 // ...and nothing in the row decides for itself whether it can act: the
37 // oracle does, once, for the key and the button alike. A raw `control(`
38 // in here is a button that can go dead while its stroke still fires --
39 // the bug this redesign was called in for.
40 assert_eq!(
41 row.matches("\n .child(control(").count(),
42 0,
43 "a toolbar button bypassing the availability oracle"
44 );
45}
46
47/// The whole reason `ui/theme.rs` exists: a colour written anywhere else is
48/// a colour the next palette sweep will miss, which is exactly how 186 grey
49/// calls survived every previous attempt at this.
50#[test]
51fn no_colour_is_written_outside_the_theme() {
52 let source = ui_source();
53 let stray: Vec<&str> = source
54 .lines()
55 .filter(|l| l.contains("rgb(0x") || l.contains("rgba(0x"))
56 .collect();
57 assert!(stray.is_empty(), "colour written outside the theme: {stray:?}");
58}
59
60/// "It scrolls" is not "it can be found": at the 640x360 floor the timeline
61/// takes its share and no more, so a third track is behind a scroll -- and
62/// the line that says so has to keep telling the truth *while* the column is
63/// being scrolled, or it is an instruction nobody can carry out.
64#[test]
65fn the_line_about_what_is_below_the_fold_counts_what_is_still_below_it() {
66
67 // The timeline is a region and not the window: its chrome -- the
68 // scrollbar strip's row included, which is the larger of the two the
69 // zoom can leave in it -- and one whole lane fit the share it may take
70 // at the floor.
71 let floor = 360. * TIMELINE_SHARE;
72 assert!(
73 timeline_fixed_h(true) + LANE_H <= floor,
74 "{} px of chrome and a lane will not fit {floor} px",
75 timeline_fixed_h(true)
76 );
77 // The lane questions, asked of the mixed math the render actually walks
78 // (the uniform lanes_shown/rows_below pair went with their last caller;
79 // a lane in the stack may be a thinner
80 // caption one: a uniform stack answers exactly what the plain
81 // functions above do, and a mixed one answers off the real heights,
82 // never the media one alone.
83 let uniform = [LaneKind::Video, LaneKind::Audio];
84 assert_eq!(lanes_h_mixed(&uniform), lanes_h(2));
85 assert_eq!(lanes_shown_mixed(&uniform, LANE_H), 1);
86 let mixed = [LaneKind::Video, LaneKind::Audio, LaneKind::Subtitle];
87 assert_eq!(
88 lanes_h_mixed(&mixed),
89 2. * LANE_H + SUB_LANE_H + 2. * 8.,
90 "a caption lane is not counted as a full LANE_H row"
91 );
92 // A box exactly tall enough for the two media lanes and no more: the
93 // thinner third lane still does not fit above it.
94 assert_eq!(lanes_shown_mixed(&mixed, lanes_h(2)), 2);
95 // ...and with room for the caption lane too, all three show and
96 // nothing is below the fold.
97 assert_eq!(lanes_shown_mixed(&mixed, lanes_h_mixed(&mixed)), 3);
98 assert_eq!(rows_below_mixed(&mixed, lanes_h_mixed(&mixed), 0.), 0);
99 assert_eq!(rows_below_mixed(&mixed, lanes_h(2), 0.), 1);
100
101 // The inspector's rows are not one height, so its own line is measured
102 // in pixels off the scroll instead: gpui keeps the offset negative going
103 // down, and at the bottom the two cancel out exactly.
104 assert_eq!(px_below(120., 0.), 120.);
105 assert_eq!(px_below(120., -40.), 80.);
106 assert_eq!(px_below(120., -120.), 0.);
107 assert_eq!(px_below(0., 0.), 0.);
108}
109
110/// The failure a user never learns about is the one that was answered by
111/// another failure: two imports failing back to back are two messages, in
112/// the order they happened, and the second does not overwrite the first
113/// before a frame has drawn it.
114#[test]
115fn a_second_message_queues_behind_the_first_instead_of_erasing_it() {
116 let mut q = std::collections::VecDeque::new();
117 push_notice(&mut q, "NOTHING ADDED — no video stream".into());
118 push_notice(&mut q, "NOTHING ADDED — the file is not there".into());
119 assert_eq!(q.len(), 2);
120 assert_eq!(q.front().map(|n: &gpui::SharedString| n.as_ref()), Some("NOTHING ADDED — no video stream"));
121
122 // A held key that refuses says its one sentence once: the count on the
123 // bar is a count of messages, not of how long the key was held.
124 push_notice(&mut q, "NOTHING ADDED — the file is not there".into());
125 assert_eq!(q.len(), 2);
126
127 // ...and the ceiling drops the oldest rather than the newest: the thing
128 // that just happened is the thing worth reading.
129 for i in 0..NOTICES_MAX + 3 {
130 push_notice(&mut q, format!("SCAN FAILED: {i}").into());
131 }
132 assert_eq!(q.len(), NOTICES_MAX);
133 assert_eq!(q.back().map(|n: &gpui::SharedString| n.as_ref()), Some("SCAN FAILED: 10"));
134
135 // Answering the bar brings the next one up, oldest first.
136 let front = q.pop_front();
137 assert_ne!(front, q.front().cloned());
138}
139
140/// An export's own outcome is what a person started it to read, so it must
141/// never sit behind two progress lines queued while it ran: it jumps to the
142/// front and is the one showing the moment it arrives.
143#[test]
144fn an_export_outcome_jumps_the_queue() {
145 let mut q = std::collections::VecDeque::new();
146 push_notice(&mut q, "PROXY READY for a.mp4 — Proxies on cuts on it".into());
147 push_notice(&mut q, "SUBTITLES b.srt — 1 track(s) in the palette".into());
148 push_notice(&mut q, format!("{EXPORT_DONE}out.mp4").into());
149 assert_eq!(q.len(), 3);
150 assert_eq!(
151 q.front().map(|n: &gpui::SharedString| n.as_ref()),
152 Some(format!("{EXPORT_DONE}out.mp4")).as_deref(),
153 "the export's result must be the notice showing, not third in line"
154 );
155
156 // A failed export is the same class: the outcome, whichever it was.
157 let mut q = std::collections::VecDeque::new();
158 push_notice(&mut q, "PROXY READY for a.mp4 — Proxies on cuts on it".into());
159 push_notice(&mut q, "EXPORT FAILED: disk full".into());
160 assert_eq!(
161 q.front().map(|n: &gpui::SharedString| n.as_ref()),
162 Some("EXPORT FAILED: disk full")
163 );
164}
165
166/// The bar colours itself off the words the message already opens with, so
167/// the tone cannot disagree with the sentence it labels.
168#[test]
169fn a_message_wears_the_colour_its_own_words_say() {
170 assert_eq!(notice_tone("SCAN FAILED: no audio"), STATUS_ERROR());
171 assert_eq!(notice_tone(&format!("{EXPORT_DONE}out.mp4")), STATUS_SUCCESS());
172 assert_eq!(notice_tone("NOTHING DETACHED — not grouped"), STATUS_WARNING());
173 assert_eq!(notice_tone("SNAP ON"), ACCENT_PRIMARY());
174}
175
176/// The cards are sections of the inspector, not sheets over the timeline:
177/// adjusting a clip must never hide the clip. Structural, because that is
178/// where the rule lives -- a card rendered from the root again would be an
179/// overlay again, whatever it looked like on the day it was written.
180#[test]
181fn an_inspector_section_occludes_no_timeline() {
182 let inspector = src_text("ui/inspector.rs");
183 // Whichever file the root render has come to live in, from the impl to the
184 // end of it -- found rather than named, so moving the root does not quietly
185 // leave this rule reading a file the render is no longer in.
186 let render = source_from("impl Render for Player");
187 for card in [
188 "eq_card", "color_card", "speed_card", "silence_card", "mix_card", "subtitle_style_card",
189 ] {
190 assert!(
191 inspector.contains(&format!("self.{card}(")),
192 "{card} is not a section of the inspector"
193 );
194 assert!(
195 !render.contains(&format!("self.{card}(")),
196 "{card} is drawn from the root again -- it is an overlay over the timeline"
197 );
198 }
199 // The docked cards are placed against the inspector's own box, which is
200 // what turns `scrim()` (`absolute().inset_0()`) from a window-wide sheet
201 // into this column.
202 assert!(
203 inspector.contains(".relative()"),
204 "the inspector is not a positioning context: its cards would cover the window"
205 );
206}
207
208/// MUST 1, on the two named offenders: the button that relabels itself
209/// mid-export and the one that used to read "Muted 80%". Both live in a
210/// rect that is reserved once, so the words change and the box does not.
211#[test]
212fn a_stateful_button_keeps_its_rect() {
213 use crate::ui::toolbar::{EXPORT_SLOT_W, SNAP_SLOT_W, VOLUME_SLOT_W};
214 // Widest word each slot can hold, at the 12 px text this window is set
215 // in -- ~7 px a character plus the 16 px of padding.
216 let fits = |slot: f32, word: &str| slot >= word.chars().count() as f32 * 7. + 16.;
217 for word in ["Export", "Cancel"] {
218 assert!(fits(EXPORT_SLOT_W, word), "{word} overflows its rect");
219 }
220 for word in ["Snap on", "Snap off", "No subs", "Subs off"] {
221 assert!(fits(SNAP_SLOT_W, word), "{word} overflows its rect");
222 }
223 for word in ["100%", "× 100%"] {
224 assert!(fits(VOLUME_SLOT_W, word), "{word} overflows its rect");
225 }
226 // And the rect is passed, not hoped for: every stateful control in the
227 // three chrome rows names its width.
228 let toolbar = src_text("ui/toolbar.rs");
229 for (id, slot) in [
230 ("\"export\"", "EXPORT_SLOT_W"),
231 ("\"snap\"", "SNAP_SLOT_W"),
232 ("\"subs\"", "SNAP_SLOT_W"),
233 ("\"volume\"", "VOLUME_SLOT_W"),
234 ("\"zoom-fit\"", "ZOOM_SLOT_W"),
235 ] {
236 let at = toolbar.find(id).unwrap_or_else(|| panic!("no {id} button"));
237 assert!(
238 toolbar[at..at + 120].contains(slot),
239 "{id} does not reserve {slot}"
240 );
241 }
242}
243
244#[test]
245fn nothing_clickable_is_smaller_than_the_wcag_minimum() {
246 // Every hit target in the panel, including the scrub strip -- whose bar
247 // is 6 px to look at and whose click area must not be.
248 assert!(CONTROL_H >= HIT_MIN);
249 assert!(RULER_HIT_H >= HIT_MIN);
250 assert!(LANE_H >= HIT_MIN);
251 // A caption lane's header carries exactly one hit target now (the
252 // show/hide eye; remove moved to its right button), and that target
253 // fills the whole row -- so the row is never allowed to undercut the
254 // target it *is*.
255 assert!(SUB_LANE_H >= HIT_MIN);
256 // A clip box is a hit target too, and its two trim strips occlude it:
257 // on a box narrower than the pair there is no body left to press, so
258 // the clip cannot be selected, dragged or menued at all -- which is
259 // every clip a jumpcut leaves at a normal zoom. Below three handles
260 // there are no strips.
261 assert!(!trims(0.));
262 assert!(!trims(EDGE_W));
263 assert!(!trims(2. * EDGE_W), "a box that is all handle and no clip");
264 assert!(!trims(3. * EDGE_W - 0.1));
265 // And where they are drawn, what is left between them is a hit target
266 // in its own right -- a whole handle's width of clip.
267 for width in [3. * EDGE_W, 24., 100., 4000.] {
268 assert!(trims(width));
269 assert!(
270 width - 2. * EDGE_W >= EDGE_W,
271 "{width} px of box leaves no middle"
272 );
273 }
274}
275
276#[test]
277fn a_lane_row_is_a_fixed_header_and_a_bed_that_can_be_hit() {
278 // The header column is what the ruler is offset by as well, so both
279 // numbers are shared rather than repeated per row (A-MUST1/A-MUST2).
280 assert!(HEADER_W > 0. && HEADER_GAP >= 0.);
281 // Two lanes, a ruler, a button row and the timecode line, inside the
282 // panel the window is sized for.
283 assert!(
284 CONTROL_H + RULER_HIT_H + 2. * LANE_H + 17. + 4. * 8. + 16. <= PANEL_H,
285 "the second lane does not fit the panel"
286 );
287 // Headers and clip boxes are as tall as the lane, and the lane is a
288 // click target (WCAG 2.5.8).
289 assert!(LANE_H >= HIT_MIN);
290 // A label row that ate the whole lane would leave no waveform.
291 assert!(LABEL_H < LANE_H / 2.);
292 // An added track adds its own row to the panel, and the two a project
293 // starts with leave it exactly the height it has always been.
294 assert_eq!(panel_h(2), PANEL_H);
295 assert_eq!(panel_h(1), PANEL_H);
296 assert_eq!(panel_h(3), PANEL_H + LANE_H + 8.);
297 assert_eq!(
298 panel_h(LANES_MAX),
299 PANEL_H + lanes_h(LANES_MAX) - lanes_h(2)
300 );
301 // Past the cap the column scrolls instead: the panel stops growing, so
302 // no number of tracks can push the picture off the window.
303 assert_eq!(panel_h(LANES_MAX + 1), panel_h(LANES_MAX));
304 assert_eq!(panel_h(50), panel_h(LANES_MAX));
305 assert_eq!(lanes_h(0), 0.);
306 assert_eq!(lanes_h(1), LANE_H);
307 assert_eq!(lanes_h(2), 2. * LANE_H + 8.);
308}
309
310/// The scrollbar's thumb: the visible share of the timeline at its own
311/// place on the track, full width with nothing to scroll, never narrower than
312/// a hand can hold, and never off the ends.
313#[test]
314fn the_scroll_thumb_is_the_visible_share_at_its_own_place() {
315 use crate::scroll_thumb;
316 use crate::SCROLL_THUMB_MIN;
317
318 // Nothing to scroll: the strip fills and says so.
319 assert_eq!(scroll_thumb(400., 10., 0., 12.), (0., 400.));
320 assert_eq!(scroll_thumb(400., 0., 0., 0.), (0., 400.));
321 // Half the timeline on the bed: a half-width thumb, halfway along for a
322 // window starting halfway in.
323 assert_eq!(scroll_thumb(400., 20., 0., 10.), (0., 200.));
324 assert_eq!(scroll_thumb(400., 20., 10., 10.), (200., 200.));
325 // The floor width: however long the timeline, the thumb stays holdable --
326 // and the clamp keeps it on the track, not the caller.
327 let (x, w) = scroll_thumb(400., 1_000_000., 999_000., 100.);
328 assert_eq!(w, SCROLL_THUMB_MIN);
329 assert_eq!(x, 400. - SCROLL_THUMB_MIN);
330 assert_eq!(scroll_thumb(400., 1_000_000., 0., 100.).0, 0.);
331}
332
333/// A press beside the time axis's thumb jumps so the thumb's middle is under
334/// the pointer, and the drag that carries on from the press must land exactly
335/// where the jump left the view: both are read through the track's own
336/// proportion (a jump worked out in pixels at the view's pps used to land at
337/// span-over-duration of the target, and the snap on the first move was the
338/// drag correcting it). The equality below is the no-snap invariant, at the
339/// thumb's own width and at its floor width alike.
340#[test]
341fn a_beside_thumb_press_jumps_by_the_tracks_own_proportion() {
342 use crate::scroll_thumb;
343
344 let bed = 400.;
345 // The mapping both halves of the gesture share: a place on the track is
346 // that share of the drawn duration.
347 let jump = |at: f32, thumb_w: f32| (at - thumb_w / 2.).max(0.) / bed;
348 for (duration, span) in [(100_f32, 20_f32), (1_000_000_f32, 100_f32)] {
349 let (_, thumb_w) = scroll_thumb(bed, f64::from(duration), 0., f64::from(span));
350 let at = 3. * bed / 4.;
351 let start = jump(at, thumb_w) * duration;
352 // The jump centres the thumb on the press (the far end of a million
353 // seconds is the clamp's to hold, so the pin is measured from the
354 // thumb the track actually shows).
355 let (x, w) = scroll_thumb(bed, f64::from(duration), f64::from(start), f64::from(span));
356 let centre = (x + w / 2.).min(bed - w / 2.);
357 assert!(
358 (centre - at.min(bed - w / 2.)).abs() < 1.,
359 "thumb centre {centre} not at the press {at}"
360 );
361 // The drag's first sample from that press -- the grabbed middle, the
362 // same track proportion -- is the same start, whatever the width.
363 let grab = thumb_w / 2.;
364 assert_eq!(jump(at, 2. * grab) * duration, start);
365 }
366}
367
368/// The strip's row is furniture only while there is somewhere to scroll to:
369/// zoomed out to the whole timeline the strip is not drawn and neither is its
370/// height -- out of every budget at once (the region, the box the lanes are
371/// laid out against, and the seam's floor), or the lanes would gain or lose a
372/// strip's row at the zoom boundary without the strip to show for it.
373#[test]
374fn the_scroll_strip_row_comes_and_goes_with_the_zoom() {
375 use crate::{SCROLL_HIT, Split, lanes_h, split_size, timeline_fixed_h, timeline_h};
376 use gpui::{px, size};
377
378 // The strip's row, and only the strip's row, is what the two faces differ
379 // by -- the gap above it and its own hit height.
380 assert_eq!(
381 timeline_fixed_h(true) - timeline_fixed_h(false),
382 8. + SCROLL_HIT
383 );
384 let window = size(px(1280.), px(720.));
385 for scroll in [false, true] {
386 // Whatever the strip is doing, the lanes keep exactly the room they
387 // had: the region grows by the strip's row when it appears, by
388 // exactly the row the lanes would otherwise lose to it.
389 assert_eq!(timeline_h(2, scroll) - timeline_fixed_h(scroll), lanes_h(2));
390 assert_eq!(
391 timeline_h(6, scroll) - timeline_fixed_h(scroll),
392 lanes_h(6)
393 );
394 // ...and the floor keeps a whole lane standing under the line, on
395 // either face of the zoom boundary.
396 let floor = split_size(Split::Timeline, Some(0.), 2, window, scroll);
397 let box_h = floor - timeline_fixed_h(scroll);
398 assert!(
399 2 > lanes_shown_mixed(&[LaneKind::Video, LaneKind::Audio], box_h),
400 "no line to pay for at the floor"
401 );
402 assert!(
403 box_h - LABEL_H - 8. >= LANE_H,
404 "the floor leaves {} px for a {LANE_H} px lane",
405 box_h - LABEL_H - 8.
406 );
407 // The two floors land the lanes in the same place: whichever face
408 // the zoom is on, a timeline held at its floor shows the same whole
409 // lane under the same line -- the strip's row comes and goes with
410 // the floor, not out of the lane. (A size dragged into the interior
411 // stays the hand's across the boundary, and the lanes are simply
412 // given the row back.)
413 assert_eq!(box_h, LANE_H + LABEL_H + 8.);
414 }
415 // The share covers the taller floor, strip in -- the one the clamp would
416 // otherwise overrule at the 640x360 floor, saying the panel takes less of
417 // a short window than it does.
418 assert!(
419 timeline_fixed_h(true) + LANE_H + LABEL_H + 8. <= 360. * TIMELINE_SHARE,
420 "the strip-bearing floor will not fit the share"
421 );
422}
423
424/// The lane stack's thumb: the visible share of the rows at their own place
425/// on the track, the time axis's own thumb turned through a right angle.
426#[test]
427fn the_lane_thumb_is_the_visible_share_of_the_stack() {
428 use crate::lanes_thumb;
429 use crate::SCROLL_THUMB_MIN;
430
431 // Whole stack on screen: the track fills and there is nothing to scroll.
432 assert_eq!(lanes_thumb(200., 104., 200., 0.), (0., 200.));
433 assert_eq!(lanes_thumb(200., 0., 0., 0.), (0., 200.));
434 // Half the stack visible, taken halfway down: a half-height thumb at the
435 // halfway mark.
436 assert_eq!(lanes_thumb(200., 400., 200., 100.), (50., 100.));
437 assert_eq!(lanes_thumb(200., 400., 200., 0.), (0., 100.));
438 // The floor height: however tall the stack, the thumb stays holdable --
439 // and the clamp keeps it on the track, not the caller.
440 let (y, h) = lanes_thumb(200., 2000., 200., 1800.);
441 assert_eq!(h, SCROLL_THUMB_MIN);
442 assert_eq!(y, 200. - SCROLL_THUMB_MIN);
443 assert_eq!(lanes_thumb(200., 2000., 200., 0.).0, 0.);
444 assert_eq!(lanes_thumb(200., 1_000_000., 200., 0.).0, 0.);
445}
446
447/// A caption's box wears the rate its window plays at, derived off the
448/// placement itself: unity placements -- including odd widths whose frames
449/// came off `frames_of_us` rounding -- do not badge, and a re-rate does, with
450/// the rate surviving the group coming apart.
451#[test]
452fn a_caption_box_wears_the_rate_its_window_plays_at() {
453 use crate::caption_rate;
454
455 let sub = |frames: u32, out_us: i64| SubClip {
456 start: 0,
457 frames,
458 track: 0,
459 in_us: 0,
460 out_us,
461 link: None,
462 };
463 // Unity, exact and rounded: neither is a re-timing.
464 assert_eq!(caption_rate(sub(300, 10_000_000), 30.), None);
465 assert_eq!(
466 caption_rate(sub(100, 3_333_333), 30.),
467 None,
468 "placement rounding is not a re-timing"
469 );
470 // ...and rounding on SHORT tracks, where half a frame is a large share of
471 // the window: `frames_of_us` of 1,016,667µs gives 31 frames (16,667µs of
472 // error -- 16 permille, but half a frame), and of 5,015,000µs gives 150
473 // (15,000µs). Both are unity; a relative gate badges one 0.98x and the
474 // other a self-contradicting 1.00x.
475 assert_eq!(
476 caption_rate(sub(31, 1_016_667), 30.),
477 None,
478 "half a frame off a one-second window is still unity"
479 );
480 assert_eq!(
481 caption_rate(sub(150, 5_015_000), 30.),
482 None,
483 "a hair under five seconds rounds to 150 frames and stays unity"
484 );
485 // A 2x re-rate: a 5s span holding the same 10s of words.
486 assert_eq!(
487 caption_rate(sub(150, 10_000_000), 30.).map(|s| s.permille()),
488 Some(2000)
489 );
490 // ...and a slowed one -- a 20s span for the same words -- which the badge
491 // keeps after any detach: the proportion is the placement's own.
492 assert_eq!(
493 caption_rate(sub(600, 10_000_000), 30.).map(|s| s.permille()),
494 Some(500)
495 );
496}
497
498/// The selection itself: clicks in order, the anchor under the hand, the
499/// toggle that assembles a group, and the plain click that replaces it all.
500#[test]
501fn a_selection_holds_its_picks_in_click_order_and_anchors_the_last() {
502 use crate::Selection;
503
504 let mut sel = Selection::new();
505 assert!(sel.is_empty());
506 assert_eq!(sel.anchor(), None);
507
508 let (v, a, cap) = (
509 (Lane::V1, 0),
510 (Lane::A1, 1),
511 (Lane::new(LaneKind::Subtitle, 0), 0),
512 );
513 sel.set_one(v);
514 assert_eq!(sel.len(), 1);
515 assert_eq!(sel.anchor(), Some(v));
516
517 // Ctrl-clicks join, in the order they were made.
518 sel.toggle(a);
519 sel.toggle(cap);
520 assert_eq!(sel.picks(), &[v, a, cap]);
521 assert_eq!(sel.anchor(), Some(cap), "the last pick is the anchor");
522 assert!(sel.contains(a));
523
524 // ...and a ctrl-click on a pick already held takes it back out, leaving
525 // the others where they were.
526 sel.toggle(a);
527 assert_eq!(sel.picks(), &[v, cap]);
528 assert!(!sel.contains(a));
529
530 // A plain click is the whole selection, one pick: whatever was held gives
531 // way to the thing just named.
532 sel.set_one(a);
533 assert_eq!(sel.picks(), &[a]);
534
535 // `add` joins without disturbing -- Select All's builder.
536 let mut all = Selection::new();
537 all.add(v);
538 all.add(a);
539 all.add(v);
540 assert_eq!(all.picks(), &[v, a], "a pick is never held twice");
541
542 sel.clear();
543 assert!(sel.is_empty());
544 assert_eq!(sel.anchor(), None);
545}
546
547#[test]
548fn a_click_marks_the_whole_group_and_nothing_else() {
549 let (v, a) = ((Lane::V1, 0), (Lane::A1, 0));
550 // Clicking the video half of group 1 marks the audio half with it -- the
551 // pick, and everything sharing its link.
552 assert!(marked(v, Some(1), &[v], &[Some(1)]));
553 assert!(marked(a, Some(1), &[v], &[Some(1)]));
554 // Another group's clips stay unmarked, in either lane.
555 assert!(!marked((Lane::V1, 1), Some(2), &[v], &[Some(1)]));
556 assert!(!marked((Lane::A1, 1), Some(2), &[v], &[Some(1)]));
557 // A half a lift left behind has no group: it marks itself only, which
558 // is what makes it separately deletable. Two ungrouped clips must not
559 // mark each other by both being ungrouped.
560 assert!(marked(a, None, &[a], &[None]));
561 assert!(!marked(v, None, &[a], &[None]));
562 // A caption ctrl-clicked into the selection marks the clip it was pinned
563 // to, and the caption is marked by the clip's pick just the same.
564 let cap = (Lane::new(LaneKind::Subtitle, 0), 0);
565 assert!(marked(cap, Some(1), &[cap, v], &[None, Some(1)]));
566 assert!(marked(a, Some(1), &[cap, v], &[None, Some(1)]));
567 // Nothing selected marks nothing.
568 assert!(!marked(v, Some(1), &[], &[]));
569}
570
571#[test]
572fn a_name_is_dropped_rather_than_smeared_across_a_thin_clip() {
573 assert!(show_label(LABEL_MIN_W));
574 assert!(show_label(400.));
575 assert!(!show_label(LABEL_MIN_W - 0.1));
576 // The label test is the box's own width in pixels now, which is what
577 // the scale hands it -- no bed width, and so nothing to be zero.
578 let scale = Scale::default();
579 assert!(show_label(scale.width_px(LABEL_MIN_W as f64 / PPS_DEFAULT)));
580 assert!(!show_label(scale.width_px(0.)));
581}
582
583#[test]
584fn an_envelope_stays_inside_the_box_it_is_drawn_in() {
585 // A ramp: silence at the start, full scale at the end.
586 let peaks: Vec<(f32, f32)> = (0..40)
587 .map(|i| (-(i as f32) / 39., i as f32 / 39.))
588 .collect();
589 let (w, h) = (100., 30.);
590 let cols = envelope(&peaks, 0., 1., w, h);
591 assert_eq!(cols.len(), (w / WAVE_COL) as usize + 1);
592 for &(x, top, bottom) in &cols {
593 assert!((0. ..=w).contains(&x), "x {x} outside 0..{w}");
594 assert!((0. ..=h).contains(&top), "top {top} outside 0..{h}");
595 assert!(
596 (0. ..=h).contains(&bottom),
597 "bottom {bottom} outside 0..{h}"
598 );
599 // Never inverted, and never a polygon with no area: silence has to
600 // read as a line rather than as nothing at all.
601 assert!(
602 bottom - top >= 1.,
603 "column {top}..{bottom} is thinner than a pixel"
604 );
605 }
606 // The ramp is drawn as a ramp: the last column is taller than the first.
607 let height = |&(_, top, bottom): &(f32, f32, f32)| bottom - top;
608 assert!(height(cols.last().unwrap()) > height(cols.first().unwrap()) + 5.);
609 // Degenerate inputs draw nothing rather than panicking.
610 assert!(envelope(&[], 0., 1., w, h).is_empty());
611 assert!(envelope(&peaks, 0., 1., 0., h).is_empty());
612 // A clip whose range runs past the peaks clamps to the last bucket.
613 assert!(!envelope(&peaks, 0., 99., w, h).is_empty());
614}
615
616/// A box laid out wider than any screen -- a long clip at a deep zoom -- is
617/// still one screen's worth of columns: the path a repaint has to build is
618/// bounded by what can be seen, not by what the layout says the box is.
619/// Unbounded, a 5 s clip zoomed to the frame is a path of millions of points
620/// per frame, and the repaint that stalls on it is the waveform that
621/// "disappeared".
622#[test]
623fn an_envelope_never_costs_more_points_than_a_screen_can_show() {
624 let peaks: Vec<(f32, f32)> = (0..200).map(|i| (-(i as f32) / 199., 1.)).collect();
625 // The width a 5 s clip is laid out at when the bed shows 8 frames of it.
626 let huge = 5. * 30. / 8. * 1200.;
627 let cols = envelope(&peaks, 0., 5., huge, 30.);
628 assert!(
629 cols.len() <= WAVE_COLS_MAX + 1,
630 "{} columns for a {huge} px box",
631 cols.len()
632 );
633 // ...and the slice actually painted is the part of the box on the bed,
634 // which is where that width stops mattering: a column per two visible
635 // pixels, at every zoom.
636 let (x, w) = visible_slice(-huge / 2., huge, 1200.);
637 assert_eq!((x, w), (huge / 2., 1200.));
638 assert_eq!(envelope(&peaks, 0., 5., w, 30.).len(), 601);
639 // A box entirely off the bed has no slice, and one that has never been
640 // measured is drawn whole -- what was drawn before there was a bed.
641 assert_eq!(visible_slice(2000., 500., 1200.), (0., 0.));
642 assert_eq!(visible_slice(-3000., 500., 1200.), (500., 0.));
643 assert_eq!(visible_slice(-40., 500., 0.), (0., 500.));
644 // Half on, at either edge.
645 assert_eq!(visible_slice(-100., 500., 1200.), (100., 400.));
646 assert_eq!(visible_slice(1000., 500., 1200.), (0., 200.));
647}
648
649/// The box a trim draws is the box its release commits, at every speed. The
650/// preview used to hand the *timeline* frame count to a source-frame field:
651/// at 2x a tail moved twice as fast as the pointer and snapped back on
652/// release, and a head drag moved the clip's other edge.
653#[test]
654fn a_trim_preview_lands_where_the_release_commits() {
655 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
656 session.set_gain(0.0);
657 for permille in SPEED_PRESETS {
658 // Live, so the loop owes it no undo step: the speeds are the axis
659 // this walks, and the trims below are what is undone.
660 session
661 .set_speed_live(Lane::V1, 0, Speed::from_permille(permille))
662 .expect("a clip alone on its lane may be speeded");
663 for edge in [Edge::Start, Edge::End] {
664 let clip = session.lane_clips(Lane::V1)[0];
665 let (lo, hi) = session
666 .trim_room(Lane::V1, 0, edge)
667 .expect("clip 0 is there");
668 // Both walls and the middle of the room: the whole range a
669 // pointer can be clamped to.
670 for to in [lo, (lo + hi) / 2, hi] {
671 let preview = trimmed_clip(clip, edge, to, false);
672 // The drag is one edit and one undo step, so the next `to`
673 // is measured from the same clip this one was.
674 if session.trim_clip(Lane::V1, 0, edge, to) {
675 assert_eq!(
676 preview,
677 session.lane_clips(Lane::V1)[0],
678 "{edge:?} to {to} at {permille} per mille"
679 );
680 assert!(session.undo(), "the trim is one undo step");
681 } else {
682 // An edge already where it was asked to go is not an
683 // edit, and the preview draws the clip unchanged.
684 assert_eq!(preview, clip, "{edge:?} to {to} at {permille} per mille");
685 }
686 assert_eq!(session.lane_clips(Lane::V1)[0], clip, "back where it was");
687 }
688 }
689 }
690}
691
692/// The caption a drag is showing lands where the release commits -- the
693/// subtitle twin of the trim preview above -- and the two contracts the boxes
694/// on the lanes rest on: `place_sub`'s `at` wins over the placement's own
695/// `start`, and a gesture that changed nothing is `Ok` and not a refusal, so a
696/// front-end that toasted every `Ok` would toast a pick-up-put-back.
697#[test]
698fn a_caption_trim_preview_lands_where_the_release_commits() {
699 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
700 session.set_gain(0.0);
701 let fps = session.meta().frame_rate;
702 let srt = Path::new(env!("CARGO_MANIFEST_DIR"))
703 .join("../engine/tests/data/test_subs.srt")
704 .canonicalize()
705 .expect("the subtitle fixture");
706 session.import_subtitles(&srt).expect("the .srt imports");
707 let lane = session.add_lane(LaneKind::Subtitle);
708 // The whole track as a placement, exactly as `Player::sub_of_track` builds
709 // one from a palette row.
710 let out_us = session.subtitles()[0]
711 .cues
712 .iter()
713 .map(|c| c.end_us)
714 .max()
715 .expect("the fixture has cues");
716 let whole = SubClip {
717 start: 0,
718 frames: frames_of_us(out_us, fps),
719 track: 0,
720 in_us: 0,
721 out_us,
722 link: None,
723 };
724 session
725 .place_sub(lane, 30, whole)
726 .expect("an empty subtitle lane takes it");
727 assert_eq!(
728 session.sub_lane(lane)[0].start,
729 30,
730 "the frame the hand let go on wins over the placement's own start"
731 );
732 for edge in [Edge::Start, Edge::End] {
733 let (lo, hi) = session
734 .trim_sub_room(lane, 0, edge)
735 .expect("placement 0 is there");
736 for to in [lo, (lo + hi) / 2, hi] {
737 let placed = session.sub_lane(lane)[0];
738 let preview = trimmed_sub(placed, edge, to);
739 session
740 .trim_sub(lane, 0, edge, to)
741 .expect("an edge inside its own room is never refused");
742 let now = session.sub_lane(lane)[0];
743 assert_eq!(
744 (preview.start, preview.frames),
745 (now.start, now.frames),
746 "{edge:?} to {to}"
747 );
748 // One edit, one undo step -- and none at all where the edge was
749 // already there, which is the `Ok` that must stay silent.
750 if (now.start, now.frames) != (placed.start, placed.frames) {
751 assert!(session.undo(), "the trim is one undo step");
752 }
753 }
754 }
755 // Picked up and put back down: `Ok`, nothing moved, nothing to say.
756 let before = session.sub_lane(lane)[0];
757 session
758 .move_sub(lane, 0, lane, before.start)
759 .expect("a drop that changes nothing is not a refusal");
760 assert_eq!(session.sub_lane(lane)[0], before);
761 // ...and two captions over one frame are refused in words, which is what
762 // the notice shows verbatim.
763 let over = session
764 .place_sub(lane, before.start, whole)
765 .expect_err("two captions may not cover one frame");
766 assert!(over.to_string().contains("already covers"), "{over}");
767}
768
769/// A still trims the same way, and the preview knows it: its head grows
770/// forward from source frame 0 -- every frame of it is the same picture --
771/// so the box stretches instead of sliding left.
772#[test]
773fn a_stills_trim_preview_grows_forward_like_the_commit() {
774 let mut session = PlaybackSession::open(asset("test_still.png")).expect("a picture opens");
775 for edge in [Edge::Start, Edge::End] {
776 let clip = session.lane_clips(Lane::V1)[0];
777 let (lo, hi) = session
778 .trim_room(Lane::V1, 0, edge)
779 .expect("clip 0 is there");
780 for to in [lo, (lo + hi) / 2, hi] {
781 let preview = trimmed_clip(clip, edge, to, true);
782 match session.trim_clip(Lane::V1, 0, edge, to) {
783 true => {
784 assert_eq!(
785 preview,
786 session.lane_clips(Lane::V1)[0],
787 "a still {edge:?} to {to}"
788 );
789 assert!(session.undo(), "the trim is one undo step");
790 }
791 false => assert_eq!(preview, clip, "a still {edge:?} to {to}"),
792 }
793 assert_eq!(session.lane_clips(Lane::V1)[0], clip, "back where it was");
794 }
795 }
796}
797
798/// gpui freezes a drag's payload for the whole gesture, and nothing stops a
799/// stroke from editing the lane under it: the drop has to find the clip that
800/// was picked up, not whatever slid into its index.
801#[test]
802fn a_drop_moves_the_clip_that_was_picked_up_not_its_old_index() {
803 let at = |start: u32| Clip {
804 fade_in: 0,
805 fade_out: 0,
806 transition_out: 0,
807 start,
808 in_frame: 0,
809 out_frame: 30,
810 source: 0,
811 link: None,
812 eq: None,
813 color: None,
814 transform: None,
815 fit: FitPolicy::Fit,
816 speed: Speed::NORMAL,
817 };
818 let lane = [at(0), at(30), at(60)];
819 let dragged = lane[2];
820 assert_eq!(live_idx(&lane, 2, dragged), Some(2), "nothing moved");
821 // A delete in front of it: the clip is now index 1, and the index the
822 // drag froze names a clip nobody grabbed.
823 let after = [at(0), at(60)];
824 assert_eq!(live_idx(&after, 2, dragged), Some(1));
825 assert_eq!(live_idx(&after, 1, dragged), Some(1));
826 // Deleted mid-drag: there is nothing to move, and moving its neighbour
827 // instead is exactly the bug this exists for.
828 assert_eq!(live_idx(&[at(0)], 2, dragged), None);
829 assert_eq!(live_idx(&[], 0, dragged), None);
830}
831
832#[test]
833fn a_quiet_source_still_draws_as_a_shape() {
834 // An eighth of full scale, which is about where the fixtures sit.
835 let quiet: Vec<(f32, f32)> = vec![(-0.125, 0.125), (-0.0625, 0.0625)];
836 let loud = normalise(quiet.clone());
837 assert_eq!(loud[0], (-1., 1.));
838 assert_eq!(loud[1], (-0.5, 0.5));
839 // Digital silence has no loudest sample to scale to; it must not divide
840 // by zero and must stay flat.
841 assert_eq!(normalise(vec![(0., 0.)]), vec![(0., 0.)]);
842 assert!(normalise(Vec::new()).is_empty());
843}
844
845/// The whole waveform path, from the file on disk to the columns that get
846/// painted: what no screenshot can assert about the shape.
847#[test]
848fn the_fixtures_waveform_reaches_the_lane_as_a_shape() {
849 let asset = |name: &str| {
850 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
851 .join("../../assets")
852 .join(name)
853 };
854 let peaks = normalise(
855 engine::waveform::peaks(asset("test_av.mp4"), 0, WAVE_BPS)
856 .expect("open the fixture")
857 .expect("test_av.mp4 has audio"),
858 );
859 // 5 s of source at the rate the lane asks for.
860 assert!(peaks.len().abs_diff(5 * WAVE_BPS as usize) <= WAVE_BPS as usize);
861 let cols = envelope(&peaks, 0., 5., 600., 30.);
862 let height = |&(_, top, bottom): &(f32, f32, f32)| bottom - top;
863 let tallest = cols.iter().map(height).fold(0., f32::max);
864 let flattest = cols.iter().map(height).fold(f32::MAX, f32::min);
865 // The fixture's 1 Hz pulse: a full-scale peak and a near-silent dip in
866 // every second, so the drawn envelope is a shape and not a bar.
867 assert!(tallest > 25., "loudest column only {tallest} px of 30");
868 assert!(
869 flattest < 8.,
870 "quietest column {flattest} px -- no dips drawn"
871 );
872 // A video-only source draws no waveform at all rather than a flat fake.
873 assert!(
874 engine::waveform::peaks(asset("test_baseline.mp4"), 0, WAVE_BPS)
875 .expect("open the fixture")
876 .is_none()
877 );
878}
879
880#[test]
881fn every_mark_on_a_clip_is_legible_on_it() {
882 // The body a name and a waveform are drawn on is the clip's kind
883 // ([`clip_kind`]); the source tint is the border and the library
884 // swatch, and is measured for telling itself apart rather than for
885 // carrying text.
886 // Every palette a person can pick, not merely the one in force.
887 for id in crate::ui::theme::PaletteId::ALL {
888 let p = id.palette();
889 for (i, tint) in [p.CLIP_VIDEO, p.CLIP_AUDIO, p.CLIP_IMAGE, p.CLIP_TEXT]
890 .iter()
891 .enumerate()
892 {
893 // WCAG 1.4.3: the clip's name is body text on its tint.
894 assert!(
895 contrast(p.FG_PRIMARY, *tint) >= 4.5,
896 "{id:?} source {i}: label contrast {:.2}",
897 contrast(p.FG_PRIMARY, *tint)
898 );
899 // WCAG 1.4.11: the waveform is a non-text graphic on it.
900 assert!(
901 contrast(p.FG_SECONDARY, *tint) >= 3.,
902 "{id:?} source {i}: waveform contrast {:.2}",
903 contrast(p.FG_SECONDARY, *tint)
904 );
905 }
906 // A selected clip's bed is the same two marks on a different colour.
907 assert!(contrast(p.FG_PRIMARY, p.BG_SELECTED) >= 4.5, "{id:?}");
908 assert!(contrast(p.FG_SECONDARY, p.BG_SELECTED) >= 3., "{id:?}");
909 // The bed a gap shows through has to read as a hole in the lane --
910 // the clip is the object, the bed is the hole -- and the playhead
911 // has to be findable on both.
912 assert!(contrast(p.CLIP_VIDEO, p.BG_TIMELINE) >= 1.5, "{id:?}");
913 assert!(contrast(p.ACCENT_PLAYHEAD, p.BG_TIMELINE) >= 3., "{id:?}");
914 assert!(contrast(p.ACCENT_PLAYHEAD, p.CLIP_VIDEO) >= 3., "{id:?}");
915 }
916 // The sanity check on the ratio itself: black on white is 21:1.
917 assert!((contrast(0xffffff, 0x000000) - 21.).abs() < 0.01);
918}
919
920#[test]
921fn source_tints_differ_per_source_and_cycle() {
922 // The bug: the first entry *was* `BG_RAISED`, so the first file imported
923 // -- the one every session has -- wore the panel's own background and
924 // had no visible swatch at all.
925 assert_ne!(source_tint(0), BG_RAISED());
926 // ...in every family, since the swatch is drawn on whichever panel is
927 // in force (`ui::theme`) and a tint that vanished into one of them is a
928 // file with no colour at all.
929 for id in crate::ui::theme::PaletteId::ALL {
930 let p = id.palette();
931 for (i, &tint) in p.SOURCE_TINTS.iter().enumerate() {
932 assert_ne!(tint, p.BG_RAISED, "{id:?} tint {i} is the panel");
933 }
934 }
935 // Neighbouring sources must not share one, or an import is invisible.
936 assert_ne!(source_tint(0), source_tint(1));
937 assert_ne!(source_tint(1), source_tint(2));
938 assert_ne!(source_tint(2), source_tint(3));
939 // Past the palette it wraps -- never an index panic.
940 assert_eq!(source_tint(4), source_tint(0));
941 assert_eq!(source_tint(9), source_tint(1));
942 assert_eq!(source_tint(usize::MAX), SOURCE_TINTS()[usize::MAX % 4]);
943}
944
945/// Not "they are different numbers" -- different *enough to see*, against
946/// each other and against the surface a swatch is drawn on. The palette is
947/// deliberately dark and low-saturation, so the margin is thin and a new
948/// tint picked by eye can land inside it without anyone noticing.
949#[test]
950fn source_tints_are_all_discernible() {
951 // Summed channel distance: `BG_RAISED` to the warm tint is 18, and that
952 // step is the one already accepted as readable on a lane.
953 let apart = |a: u32, b: u32| {
954 (0..3)
955 .map(|i| {
956 let shift = i * 8;
957 ((a >> shift) & 0xff).abs_diff((b >> shift) & 0xff)
958 })
959 .sum::<u32>()
960 };
961 // Every family, not the one in force: a palette is picked at runtime
962 // now, and four tints tuned by eye on one ground are exactly where a
963 // pair lands inside the margin on another.
964 for id in crate::ui::theme::PaletteId::ALL {
965 let p = id.palette();
966 for (i, &tint) in p.SOURCE_TINTS.iter().enumerate() {
967 assert!(
968 apart(tint, p.BG_RAISED) >= 16,
969 "{id:?} tint {i} is {} from the panel it sits on",
970 apart(tint, p.BG_RAISED)
971 );
972 for (j, &other) in p.SOURCE_TINTS.iter().enumerate().skip(i + 1) {
973 assert!(
974 apart(tint, other) >= 16,
975 "{id:?} tints {i} and {j} are only {} apart",
976 apart(tint, other)
977 );
978 }
979 }
980 // The two a person sees side by side first must be further apart
981 // than the floor: source 0 and source 1 are the first import and
982 // the second.
983 assert!(apart(p.SOURCE_TINTS[0], p.SOURCE_TINTS[1]) >= 32, "{id:?}");
984 }
985}
986
987/// A `.srt` dropped on the window is nobody's stream: it has no source
988/// entry, and the lookup that used to fall back to index 0 painted it with
989/// the first file's colour -- a swatch saying it came out of a film it
990/// never touched.
991#[test]
992fn a_standalone_subtitle_wears_no_file_tint() {
993 let sources = [
994 Source {
995 path: PathBuf::from("/films/a.mkv"),
996 audio_stream: 0,
997 },
998 Source {
999 path: PathBuf::from("/films/b.mp4"),
1000 audio_stream: 0,
1001 },
1002 // A second stream of the first file is a second source and the
1003 // same colour.
1004 Source {
1005 path: PathBuf::from("/films/a.mkv"),
1006 audio_stream: 1,
1007 },
1008 ];
1009 assert_eq!(
1010 file_tint(&sources, Path::new("/films/a.mkv")),
1011 Some(source_tint(0))
1012 );
1013 assert_eq!(
1014 file_tint(&sources, Path::new("/films/b.mp4")),
1015 Some(source_tint(1))
1016 );
1017 assert_eq!(file_tint(&sources, Path::new("/subs/a.eng.srt")), None);
1018 assert_eq!(file_tint(&[], Path::new("/films/a.mkv")), None);
1019 // The same file under two spellings is one file and one colour: a
1020 // source is stored symlink-resolved, everything else as it was typed.
1021 let here = std::fs::canonicalize(".").expect("the crate directory");
1022 let sources = [Source {
1023 path: here.join("Cargo.toml"),
1024 audio_stream: 0,
1025 }];
1026 assert_eq!(
1027 file_tint(&sources, Path::new("Cargo.toml")),
1028 Some(source_tint(0)),
1029 "a relative spelling of the source file wears the source's colour"
1030 );
1031}
1032
1033/// A film's two ASS tracks with the timeline trimmed to twenty seconds:
1034/// one of them still has cues there and one has none, and the card said
1035/// nothing whatever about the second while the Subtitles list went on
1036/// showing it with its eighty-three cues.
1037///
1038/// And the 25 GB remux's thirty-five: naming those wrapped the row to ten
1039/// lines and pushed Destination under the fold, so past the value box's
1040/// three lines the same line counts instead.
1041#[test]
1042fn the_card_names_the_subtitle_it_leaves_off_and_counts_them_when_it_cannot() {
1043 let film = "/films/An Episode 01.mkv";
1044 let two = [
1045 sub(film, Some(1), "[ASS]"),
1046 sub(film, Some(2), "[ASS] [FOR DUB]"),
1047 ];
1048 // What the engine answers about the one pick that reached it, and what
1049 // this side knows about the row that did not.
1050 let named = subtitle_plan("[ASS] → embedded".to_string(), &two, &[0]);
1051 assert_eq!(named, "[ASS] → embedded; [ASS] [FOR DUB] — in the palette, on no track");
1052 assert!(
1053 named.chars().count() <= SUB_PLAN_CHARS,
1054 "two tracks fit the value box: {named}"
1055 );
1056 // Thirty-five off one file: twenty-two carry cues here, nine are
1057 // pictures, one could not be read, three have nothing on this timeline.
1058 let many: Vec<_> = (0..35)
1059 .map(|i| {
1060 let mut track = sub("/films/A Remux.mkv", Some(i), "eng — Subtitles");
1061 track.bitmap = (22..31).contains(&i);
1062 track.refused = (i == 31).then(|| "VobSub is pictures".to_string());
1063 track
1064 })
1065 .collect();
1066 // The picks are every track with a cue on the timeline: the twenty-two
1067 // and the nine picture ones, which the engine drops itself.
1068 let picks: Vec<usize> = (0..31usize).collect();
1069 let counted = subtitle_plan("22 tracks → embedded (…)".to_string(), &many, &picks);
1070 assert_eq!(
1071 counted,
1072 "22 of 35 → embedded; 9 pictures; 1 unread; 3 in the palette, on no track"
1073 );
1074 assert!(
1075 counted.chars().count() <= SUB_PLAN_CHARS,
1076 "thirty-five tracks still fit the value box: {counted}"
1077 );
1078 // Nothing on the timeline at all is still the engine's word for it.
1079 assert_eq!(subtitle_plan("none".to_string(), &[], &[]), "none");
1080 // The lanes are what an export writes once anything is placed on one, and
1081 // the engine words that whole ([`engine::export::planned_subtitles`]) --
1082 // including the lanes it carries *nothing* of, which is a sentence with no
1083 // pick behind it at all. That used to be dropped on the floor: the card said
1084 // "[ASS] — no cues here" twice and never said what became of the lane.
1085 let placed = "S1 [ASS] — past the last picture".to_string();
1086 assert_eq!(
1087 subtitle_plan(placed.clone(), &two, &[]),
1088 "S1 [ASS] — past the last picture; [ASS] [FOR DUB] — in the palette, on no track"
1089 );
1090 // ...and the row that sentence speaks for gets no clause of its own: a line
1091 // that names a lane's track and then calls the same track unplaced is the
1092 // card contradicting itself in one breath.
1093 assert!(!subtitle_plan(placed, &two[..1], &[]).contains("in the palette"));
1094}
1095
1096/// The list is in the order tracks were added, which is not the order a
1097/// person reads it in: importing a second film puts its tracks after the
1098/// first film's, and importing a third `.srt` for the first film puts that
1099/// one last of all. The rows still read as three sources.
1100#[test]
1101fn subtitle_rows_group_a_source_however_they_were_added() {
1102 let tracks = [
1103 sub("/films/a.mkv", Some(1), "eng"),
1104 sub("/films/b.mkv", Some(1), "eng"),
1105 sub("/films/a.mkv", Some(2), "fre"),
1106 sub("/subs/late.srt", None, "late.srt"),
1107 sub("/films/b.mkv", Some(3), "ger"),
1108 ];
1109 let groups = subtitle_rows(&tracks);
1110 assert_eq!(
1111 groups.iter().map(|g| g.name.as_str()).collect::<Vec<_>>(),
1112 ["a", "b", "late"],
1113 "one group per file, in the order the files first appear"
1114 );
1115 assert_eq!(
1116 groups
1117 .iter()
1118 .map(|g| g.rows.iter().map(|r| r.label.as_str()).collect::<Vec<_>>())
1119 .collect::<Vec<_>>(),
1120 [vec!["eng", "fre"], vec!["eng", "ger"], vec!["late.srt"]],
1121 "a file's tracks are contiguous and in add order"
1122 );
1123 // Numbered within the file, the way `row_name` numbers audio streams:
1124 // two tracks that both say "eng" are told apart by nothing else.
1125 assert_eq!(
1126 groups
1127 .iter()
1128 .map(|g| g.rows.iter().map(|r| r.number).collect::<Vec<_>>())
1129 .collect::<Vec<_>>(),
1130 [vec![1, 2], vec![1, 2], vec![1]]
1131 );
1132 // The swatch key is the file, so a group and that file's media rows
1133 // wear one colour -- and the standalone one has none.
1134 let sources = [Source {
1135 path: PathBuf::from("/films/a.mkv"),
1136 audio_stream: 0,
1137 }];
1138 assert_eq!(
1139 file_tint(&sources, &groups[0].path),
1140 Some(source_tint(0)),
1141 "the group carries the path the tint is asked by"
1142 );
1143 assert_eq!(file_tint(&sources, &groups[2].path), None);
1144 // What a header's "N tracks" says: the group's own row count, which is
1145 // 2, 2, 1 here -- a film that gave several tracks and a standalone
1146 // `.srt` that gave exactly one.
1147 assert_eq!(
1148 groups.iter().map(|g| g.rows.len()).collect::<Vec<_>>(),
1149 [2, 2, 1]
1150 );
1151 // A standalone `.srt` is already its own group, named after its own
1152 // file ("late", not lumped under some catch-all "External" bucket) --
1153 // there is no sourceless case for a header to special-case.
1154 assert_eq!(groups[2].name, "late");
1155 assert_eq!(groups[2].path, PathBuf::from("/subs/late.srt"));
1156}
1157
1158/// The fold a click on a header sets is keyed by [`SubGroup::path`]
1159/// (`Player::sub_folded`), so it has to survive the very thing regrouping
1160/// is for: a second track landing on a file already in the list, or one
1161/// being removed from it. The group's path is the fold's whole identity,
1162/// so it must not move under either.
1163#[test]
1164fn a_groups_fold_key_survives_a_track_arriving_or_leaving_its_file() {
1165 let before = [
1166 sub("/films/a.mkv", Some(1), "eng"),
1167 sub("/films/b.mkv", Some(1), "eng"),
1168 ];
1169 let after_add = [
1170 sub("/films/a.mkv", Some(1), "eng"),
1171 sub("/films/b.mkv", Some(1), "eng"),
1172 sub("/films/a.mkv", Some(2), "fre"),
1173 ];
1174 let (before_groups, after_groups) = (subtitle_rows(&before), subtitle_rows(&after_add));
1175 assert_eq!(before_groups[0].path, after_groups[0].path, "a's key held");
1176 assert_eq!(before_groups[1].path, after_groups[1].path, "b's key held");
1177 // The group a second track landed on grew; the other did not move.
1178 assert_eq!(after_groups[0].rows.len(), 2);
1179 assert_eq!(after_groups[1].rows.len(), 1);
1180 // Removing that same track back off leaves the original key and count.
1181 let after_remove = subtitle_rows(&before);
1182 assert_eq!(after_remove[0].path, before_groups[0].path);
1183 assert_eq!(after_remove[0].rows.len(), 1);
1184}
1185
1186/// What the strip header, the section heading and the toggle's notice all
1187/// say. Two films each carrying an "eng" track are one word apart until the
1188/// film is in the name; a film carrying two is one word apart from itself.
1189#[test]
1190fn the_picked_subtitle_is_named_with_the_film_it_came_out_of() {
1191 let tracks = [
1192 sub("/films/a.mkv", Some(1), "eng"),
1193 sub("/films/b.mkv", Some(1), "eng"),
1194 sub("/films/a.mkv", Some(2), "eng"),
1195 sub("/films/b.mkv", Some(2), "und"),
1196 sub("/subs/late.srt", None, "late.srt"),
1197 ];
1198 let name = |track| sub_pick_name(&tracks, track).expect("a track that is there");
1199 // The two "eng"s of two films: one file gave several so its tracks are
1200 // numbered, the other gave one so it is not.
1201 assert_eq!(name(0), "eng 1 — a");
1202 assert_eq!(name(2), "eng 2 — a");
1203 assert_eq!(name(1), "eng 1 — b");
1204 assert_ne!(name(0), name(1), "two films' eng tracks read apart");
1205 for picked in [name(0), name(1), name(2)] {
1206 assert!(picked.contains(" — a") || picked.contains(" — b"));
1207 }
1208 // "und" is the tag for "nobody said", humanised once by
1209 // `subtitle_rows` and not again here.
1210 assert_eq!(name(3), "unknown language 2 — b");
1211 // A standalone `.srt` is its own file and its label already says so:
1212 // one track, so no number, and no stem after it saying it again.
1213 assert_eq!(name(4), "late.srt");
1214 // The silence a row left over from a timeline that is gone gets.
1215 assert_eq!(sub_pick_name(&tracks, 5), None);
1216 assert_eq!(sub_pick_name(&[], 0), None);
1217}
1218
1219/// What the toggle covers is what is *placed*, so what it says is a lane fact:
1220/// naming the palette row the list happens to mark named a track the stroke
1221/// never touched ("SUBTITLES OFF — one.srt is still on the timeline" for a
1222/// one.srt nobody dragged anywhere).
1223#[test]
1224fn the_subtitles_toggle_says_what_is_placed_and_never_the_picked_row() {
1225 for on in [true, false] {
1226 let text = subtitle_toggle_notice(on, 2);
1227 assert!(text.contains('2'), "{text} counts the captions placed");
1228 assert!(
1229 !text.contains("track(s)") && !text.contains(" — a"),
1230 "{text} names no palette row"
1231 );
1232 }
1233 // Off leaves them on the lanes; that is the half a person needs told.
1234 assert!(subtitle_toggle_notice(false, 2).contains("still placed"));
1235 // An empty timeline says the move instead of a count that reads as broken.
1236 let none = subtitle_toggle_notice(true, 0);
1237 assert!(!none.contains('0'), "{none} counts nothing at nothing");
1238 assert!(none.contains("drag"), "{none} says the next move");
1239}
1240
1241/// The door this editor answers "don't make me import the film again" with,
1242/// and it is in the panel where the tracks it adds are listed: the Text
1243/// tab's own button reads a file's subtitle tracks onto the open timeline
1244/// -- a release's `.mkv`, an `.srt` beside it -- while the file itself
1245/// joins nothing. It is the *action* and not a second implementation of it,
1246/// so the button, the stroke and the actions card cannot drift apart, and
1247/// it is oracle-gated like every other action button, so with no timeline
1248/// open it dims and says why instead of opening a chooser for nothing.
1249#[test]
1250fn the_text_tab_carries_the_add_subtitles_door() {
1251 let library = src_text("ui/library.rs");
1252 let at = library
1253 .find("\"add-subtitles\"")
1254 .expect("no add-subtitles control in the library column");
1255 let block = &library[at..(at + 1600).min(library.len())];
1256 assert!(
1257 block.contains("ActionId::ImportSubtitles"),
1258 "the button is a door of its own rather than the action: {block}"
1259 );
1260 assert!(
1261 block.contains("pick_and_add_subtitles"),
1262 "the button does not open the subtitle chooser: {block}"
1263 );
1264 // `action_control` is the oracle-gated one: dimmed with the refusal in
1265 // the oracle's own words. `control` alone would be lit with no timeline.
1266 assert!(
1267 library[..at].ends_with("self.action_control(\n "),
1268 "the add-subtitles button is not oracle-gated"
1269 );
1270 // ...and the empty tab names that button, rather than pointing at a
1271 // toolbar the person is not looking at.
1272 assert!(
1273 crate::LibraryTab::Text.empty().contains("Add subtitles"),
1274 "{}",
1275 crate::LibraryTab::Text.empty()
1276 );
1277}
1278
1279/// A source's group header in the library must not vanish on a short
1280/// window: it is drawn whenever there is more than one source
1281/// (`several_files`), never gated on the viewport's height, and the list
1282/// under it is what scrolls instead ([`SUB_ROWS_H`]). And it has to be a
1283/// real fold, not the click-cycling pattern this codebase has already
1284/// thrown out once: one click toggles `sub_folded` shut or open, it never
1285/// steps through more than those two states.
1286#[test]
1287fn a_subtitle_group_header_is_never_gated_on_window_height() {
1288 let timeline = src_text("ui/timeline.rs");
1289 assert!(
1290 !timeline.contains("sub_headers_fit"),
1291 "the header is still gated on the viewport's height"
1292 );
1293 let at = timeline
1294 .find("let headed = ")
1295 .expect("no `headed` computed in subtitle_section");
1296 let line = &timeline[at..(at + 80).min(timeline.len())];
1297 assert!(
1298 line.contains("several_files") && !line.contains("viewport"),
1299 "headed depends on something other than the file count: {line}"
1300 );
1301 // The header is a click target that flips membership in a set --
1302 // `remove` else `insert` -- not a value stepped through several states.
1303 let head_at = timeline
1304 .find("subtitle-group-head")
1305 .expect("no id on the group header");
1306 let block = &timeline[head_at..(head_at + 2400).min(timeline.len())];
1307 assert!(block.contains("sub_folded.remove"), "no fold-open path: {block}");
1308 assert!(block.contains("sub_folded.insert"), "no fold-shut path: {block}");
1309 assert!(
1310 block.contains("\"1 track\"") || block.contains("tracks"),
1311 "the header does not say how many tracks it holds: {block}"
1312 );
1313}
1314
1315/// The one thing regrouping must not break: `sub_track` is a flat index
1316/// into the add-order list, a click sets it and a save writes it into the
1317/// `.edith`. Every row must still name the track it was made from -- rows
1318/// for refused tracks included, because they take a number in that list
1319/// whether or not anyone can pick them.
1320#[test]
1321fn a_subtitle_row_names_the_flat_track_it_was_made_from() {
1322 let mut tracks = vec![
1323 sub("/films/a.mkv", Some(1), "eng"),
1324 sub("/films/b.mkv", Some(1), "eng"),
1325 sub("/films/a.mkv", Some(2), "fre"),
1326 ];
1327 // Track 1 of b is pictures: still a row, still index 1 of the list.
1328 tracks[1].bitmap = true;
1329 tracks[1].refused = Some("PGS subtitles are pictures".to_string());
1330 let groups = subtitle_rows(&tracks);
1331 let flat: Vec<(usize, &str)> = groups
1332 .iter()
1333 .flat_map(|g| g.rows.iter().map(|r| (r.track, r.label.as_str())))
1334 .collect();
1335 assert_eq!(flat, [(0, "eng"), (2, "fre"), (1, "eng")]);
1336 for (track, label) in flat {
1337 assert_eq!(
1338 tracks[track].label, label,
1339 "row {track} picks the track it names"
1340 );
1341 }
1342 // (c) The refused one is here, saying why, and greyable by that alone.
1343 let refused = &groups[1].rows[0];
1344 assert_eq!(
1345 refused.refused.as_deref(),
1346 Some("PGS subtitles are pictures")
1347 );
1348 assert_eq!(refused.detail, "PGS subtitles are pictures");
1349 assert!(refused.bitmap);
1350 // ...and it was counted: the row after it in add order is still 2.
1351 assert_eq!(groups[0].rows[1].track, 2);
1352}
1353
1354/// The × on a row shifts every track after it down one, and the pick is
1355/// what an export writes into the file -- so a pick that stayed put would
1356/// silently change which track the next export carries. Every relation
1357/// between the pick and the row that went, on a list of three.
1358#[test]
1359fn removing_a_subtitle_row_carries_the_pick_with_it() {
1360 // A row *before* the pick: the same track stays picked, one index down.
1361 assert_eq!(sub_pick_after_removal(2, 0, 2), 1);
1362 assert_eq!(sub_pick_after_removal(2, 1, 2), 1);
1363 // A row *after* it: the pick has not moved and neither has its index.
1364 assert_eq!(sub_pick_after_removal(0, 2, 2), 0);
1365 assert_eq!(sub_pick_after_removal(1, 2, 2), 1);
1366 // The picked row itself: the one that slid into its place...
1367 assert_eq!(sub_pick_after_removal(1, 1, 2), 1);
1368 // ...and the last row when the picked one was the last, since there is
1369 // nothing after it to slide.
1370 assert_eq!(sub_pick_after_removal(2, 2, 2), 1);
1371 // The last row of all: an emptied list is legal for subtitles, and the
1372 // section is not drawn at all at that point.
1373 assert_eq!(sub_pick_after_removal(0, 0, 0), 0);
1374}
1375
1376/// The same claim from the click's end, on the order imports actually
1377/// arrive in: two films opened one after the other and an `.srt` dropped
1378/// last interleave in the flat list, and the display reorders them. What a
1379/// click sets is the row's own `track`, so the *n*th row on screen has to
1380/// pick the track it shows and the echoes have to name that same file.
1381#[test]
1382fn a_click_on_a_regrouped_row_picks_the_track_that_row_shows() {
1383 let tracks = [
1384 sub("/films/a.mkv", Some(1), "eng"),
1385 sub("/films/b.mkv", Some(1), "eng"),
1386 sub("/films/a.mkv", Some(2), "fre"),
1387 sub("/subs/late.srt", None, "late.srt"),
1388 sub("/films/b.mkv", Some(3), "ger"),
1389 ];
1390 let rows: Vec<_> = subtitle_rows(&tracks)
1391 .into_iter()
1392 .flat_map(|group| {
1393 group
1394 .rows
1395 .into_iter()
1396 .map(move |row| (group.path.clone(), row))
1397 })
1398 .collect();
1399 // Read top to bottom, the rows are no longer in add order...
1400 assert_eq!(
1401 rows.iter().map(|(_, row)| row.track).collect::<Vec<_>>(),
1402 [0, 2, 1, 4, 3]
1403 );
1404 for (path, row) in &rows {
1405 // ...and what the click writes into `sub_track` -- and a save into
1406 // the `.edith` -- still lands on the track the row is showing.
1407 let picked = &tracks[row.track];
1408 assert_eq!(&picked.path, path, "row {} picks another file", row.track);
1409 assert_eq!(lang_human(&picked.label), row.label);
1410 // And the heading, the strip and the notice name that same file
1411 // back, so a click cannot leave the echoes pointing elsewhere.
1412 let echo = sub_pick_name(&tracks, row.track).expect("the row's own track");
1413 let stem = path.file_stem().expect("a fixture path").to_string_lossy();
1414 assert!(
1415 echo.contains(&*stem),
1416 "picked {}, echoed {echo}",
1417 path.display()
1418 );
1419 }
1420}
1421
1422/// "und" is what a muxer writes when nobody said what the language is. A
1423/// row showing it verbatim names a language nobody speaks.
1424#[test]
1425fn an_untagged_language_says_it_is_unknown() {
1426 assert_eq!(lang_human("und"), "unknown language");
1427 assert_eq!(lang_human("eng"), "eng");
1428 assert_eq!(lang_human("fre — Commentary"), "fre — Commentary");
1429 // Reaching the subtitle rows too: a track whose only name was the tag.
1430 let groups = subtitle_rows(&[sub("/films/a.mkv", Some(1), "und")]);
1431 assert_eq!(groups[0].rows[0].label, "unknown language");
1432 // The pair, read as the pair: the row title comes off `language` and
1433 // `name` and never out of the flattened label, which is what let an
1434 // "und" beside a title through as a language nobody speaks. A refused
1435 // track states neither and keeps its label.
1436 let titled = |language: &str, name: &str, label: &str| engine::subtitle::SubtitleTrack {
1437 path: PathBuf::from("/films/a.mkv"),
1438 track: Some(1),
1439 language: language.into(),
1440 name: name.into(),
1441 label: label.into(),
1442 cues: Vec::new(),
1443 bitmap: false,
1444 refused: None,
1445 };
1446 for (language, name, label, title) in [
1447 ("fra", "Signs", "fra — Signs", "fra — Signs"),
1448 ("und", "Signs", "Signs", "Signs"),
1449 ("und", "", "und", "unknown language"),
1450 ("", "late.srt", "late.srt", "late.srt"),
1451 ("", "", "eng", "eng"),
1452 ] {
1453 let rows = subtitle_rows(&[titled(language, name, label)]);
1454 assert_eq!(rows[0].rows[0].label, title, "{language:?} {name:?}");
1455 }
1456}
1457
1458/// The bug: an empty timeline is end-of-stream from its one black frame
1459/// onward, so the pump had `done` set before anything was ever pressed --
1460/// and the transport's restart branch read that as "played out, start from
1461/// the top". It started a clock against a zero-length timeline, which was
1462/// `done` again by the next repaint, so every further press restarted it
1463/// too: the button read "Pause" and no press of it ever paused.
1464///
1465/// What holds it now is one predicate, checked here against real sessions
1466/// on both sides -- the emptied one refuses, a timeline with clips on it
1467/// does not.
1468#[test]
1469fn an_empty_timeline_has_nothing_to_play() {
1470 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1471 // Silent like the engine suite: this opens the real device.
1472 session.set_gain(0.0);
1473 // A timeline with clips on it plays, and always did: the guard must not
1474 // touch that side.
1475 assert!(!session.is_empty());
1476 assert!(!nothing_to_play(Some(&session)));
1477
1478 // Every clip taken off, which is a state and not a failure.
1479 while session.delete_clip(Lane::V1, 0) {}
1480 while session.delete_clip(Lane::A1, 0) {}
1481 assert!(session.is_empty(), "the timeline is empty");
1482 assert_eq!(session.timeline_duration(), 0.0);
1483
1484 // What the pump does every render, and what set `done` before the fix:
1485 // the black frame goes by and the session is at its end at once.
1486 for _ in 0..40 {
1487 while session.try_frame().is_some() {}
1488 std::thread::sleep(Duration::from_millis(10));
1489 }
1490 assert!(
1491 session.is_eos(),
1492 "an empty timeline is done before it starts"
1493 );
1494
1495 // So the press is refused rather than sent down the restart branch --
1496 // and with no session at all it is the same refusal.
1497 assert!(nothing_to_play(Some(&session)));
1498 assert!(nothing_to_play(None));
1499 assert!(!session.is_playing(), "and nothing was started");
1500}
1501
1502/// The slider writes the same numbers the keys do, and mute is not one of
1503/// them: dragging while muted picks the level unmuting comes back to.
1504#[test]
1505fn the_slider_lands_on_the_grid_the_keys_move_on() {
1506 let mut volume = Volume::default();
1507 // Both ends exactly, and clamped past them.
1508 volume.set_along(0.);
1509 assert_eq!(volume.gain(), 0.0);
1510 assert_eq!(volume.label(), "Vol 0%");
1511 volume.set_along(1.5);
1512 assert_eq!(volume.gain(), 1.0);
1513 assert_eq!(volume.along(), 1.0);
1514
1515 // Halfway is 50%, and a key press from there is 5% -- the same step
1516 // count as before, on a finer grid.
1517 volume.set_along(0.5);
1518 assert_eq!(volume.label(), "Vol 50%");
1519 volume.step(true);
1520 assert_eq!(volume.label(), "Vol 55%");
1521 volume.step(false);
1522 assert_eq!(volume.gain(), 0.5);
1523
1524 // A number no step lands on comes back as the nearest one, so the label
1525 // and the fill are the same value the device was handed.
1526 volume.set_along(0.333);
1527 assert_eq!(volume.label(), "Vol 33%");
1528 assert_eq!(volume.along(), 0.33);
1529
1530 // Muted, the drag moves the level and nothing comes out.
1531 volume.muted = true;
1532 volume.set_along(0.8);
1533 assert_eq!(volume.gain(), 0.0);
1534 assert_eq!(volume.label(), "Muted 80%");
1535 volume.muted = false;
1536 assert_eq!(volume.gain(), 0.8);
1537}
1538
1539/// The slider lands where it paints: the arithmetic `Player::drag_volume`
1540/// runs over the bar's own painted width, which is the one thing a test of
1541/// it can share without re-deriving it.
1542#[test]
1543fn the_volume_slider_lands_where_it_paints() {
1544 let bar = Bounds {
1545 origin: point(px(420.), px(508.)),
1546 size: size(px(VOLUME_W), px(CONTROL_H)),
1547 };
1548 let at = |x: f32| {
1549 let mut volume = Volume::default();
1550 volume.set_along(frac_along(px(x), bar));
1551 volume
1552 };
1553 assert_eq!(at(420.).gain(), 0.0, "the left end is silence");
1554 assert_eq!(at(420. + VOLUME_W).gain(), 1.0, "the right end is full");
1555 assert_eq!(at(-4000.).gain(), 0.0, "off the left clamps");
1556 assert_eq!(at(9999.).gain(), 1.0, "off the right clamps");
1557 // Every pixel along it: a level the keys could also reach, painted back
1558 // where the hand pressed to within the half step the rounding costs.
1559 for step in 0..=(VOLUME_W as u32) {
1560 let along = step as f32 / VOLUME_W;
1561 let volume = at(420. + along * VOLUME_W);
1562 let painted = volume.along();
1563 let slack = 0.5 / f32::from(Volume::MAX_STEPS) + 1e-4;
1564 assert!(
1565 (painted - along).abs() <= slack,
1566 "pressed at {along}, paints at {painted}"
1567 );
1568 }
1569}
1570
1571/// The three seams a hand may move, and the two ends neither of them may be
1572/// dragged past: a panel dragged to nothing is a panel nobody can get back, and
1573/// a picture squeezed out by its two neighbours is that same loss from the
1574/// other side of the window.
1575#[test]
1576fn a_dragged_divider_stops_before_either_panel_disappears() {
1577 use crate::ui::theme::INSPECTOR_MIN_W;
1578 use crate::{
1579 SIDE_MAX_FRAC, SPLIT_W, Split, TIMELINE_MAX_SHARE, TOOLBAR_H, inspector_w, library_w,
1580 split_drag_size, split_size, timeline_fixed_h, timeline_h,
1581 };
1582 use gpui::{point, px, size};
1583
1584 let window = size(px(1280.), px(720.));
1585 // Untouched, every region is still the share the window gives it. The
1586 // timeline's answer is stated for both of its faces: the timeline fits
1587 // the bed with nothing to scroll to, and zoomed in past that line the
1588 // strip's row joins the furniture.
1589 assert_eq!(split_size(Split::Library, None, 2, window, false), library_w(1280.));
1590 assert_eq!(
1591 split_size(Split::Inspector, None, 2, window, false),
1592 inspector_w(1280.)
1593 );
1594 assert_eq!(
1595 split_size(Split::Timeline, None, 2, window, false),
1596 timeline_h(2, false).min(720. * TIMELINE_SHARE)
1597 );
1598 assert_eq!(
1599 split_size(Split::Timeline, None, 2, window, true),
1600 timeline_h(2, true).min(720. * TIMELINE_SHARE)
1601 );
1602 // Dragged, it is what the hand asked for...
1603 assert_eq!(split_size(Split::Library, Some(300.), 2, window, false), 300.);
1604 assert_eq!(split_size(Split::Timeline, Some(300.), 2, window, false), 300.);
1605 // ...and never past either end of it.
1606 assert_eq!(
1607 split_size(Split::Library, Some(0.), 2, window, false),
1608 LIBRARY_MIN_W
1609 );
1610 assert_eq!(
1611 split_size(Split::Library, Some(9000.), 2, window, false),
1612 1280. * SIDE_MAX_FRAC
1613 );
1614 assert_eq!(
1615 split_size(Split::Inspector, Some(-40.), 2, window, false),
1616 INSPECTOR_MIN_W
1617 );
1618 // The timeline's own floor is a floor with a whole lane *drawn* in it. At
1619 // that height the column shows one row of a two-track project, so the line
1620 // saying the rest are below is drawn too -- out of the region's pixels,
1621 // not out of the lane's. Left unbudgeted the header came out 27 px of its
1622 // 48 and the track's name, its subtitle dot and its × were cut in half.
1623 // Stated for the strip-bearing face, the taller of the two -- that is the
1624 // one the clamp has to hold at the 640x360 floor.
1625 let floor = split_size(Split::Timeline, Some(0.), 2, window, true);
1626 assert_eq!(floor, timeline_fixed_h(true) + LANE_H + LABEL_H + 8.);
1627 // The same arithmetic the timeline lays the column out with
1628 // ([`Player::timeline`]): what the affordance costs comes off the box, and
1629 // a whole lane is still standing under it.
1630 let lanes_box = floor - timeline_fixed_h(true);
1631 assert!(
1632 2 > lanes_shown_mixed(&[LaneKind::Video, LaneKind::Audio], lanes_box),
1633 "no line to pay for at the floor"
1634 );
1635 assert!(
1636 lanes_box - LABEL_H - 8. >= LANE_H,
1637 "the floor leaves {} px for a {LANE_H} px lane",
1638 lanes_box - LABEL_H - 8.
1639 );
1640 // A lone track has nothing below it and pays nothing for the line -- the
1641 // floor is a floor, not a reserved corridor.
1642 assert_eq!(
1643 split_size(Split::Timeline, Some(0.), 1, window, true),
1644 timeline_fixed_h(true) + LANE_H
1645 );
1646 // A size dragged with one track and kept while a second arrives is raised
1647 // to the new floor as it is read, not silently drawn under it.
1648 assert_eq!(split_size(Split::Timeline, Some(126.), 2, window, true), floor);
1649 // And the floor still fits the share the shortest window gives the region.
1650 assert!(floor <= 360. * TIMELINE_SHARE, "{floor} px will not fit");
1651 assert_eq!(
1652 split_size(Split::Timeline, Some(9000.), 2, window, true),
1653 720. * TIMELINE_MAX_SHARE
1654 );
1655 // A window too narrow to honour both ends keeps the floor rather than
1656 // panicking inside `clamp`, which is what a ceiling under its own floor
1657 // does.
1658 let narrow = size(px(600.), px(360.));
1659 assert_eq!(
1660 split_size(Split::Inspector, Some(9000.), 2, narrow, false),
1661 INSPECTOR_MIN_W
1662 );
1663
1664 // The pointer turned into a size: the panel follows the hand, and the two
1665 // that do not start at the window's own edge are measured from the far one.
1666 // Half a strip off each, because the strip is grabbed by its middle.
1667 assert_eq!(
1668 split_drag_size(Split::Library, point(px(300.), px(400.)), window),
1669 300. - SPLIT_W / 2.
1670 );
1671 assert_eq!(
1672 split_drag_size(Split::Inspector, point(px(1000.), px(400.)), window),
1673 280. - SPLIT_W / 2.
1674 );
1675 // The seam sits above the fixed toolbar, so what the pointer leaves under
1676 // it is that strip and the timeline together.
1677 assert_eq!(
1678 split_drag_size(Split::Timeline, point(px(300.), px(500.)), window),
1679 220. - TOOLBAR_H - SPLIT_W / 2.
1680 );
1681}
1682
1683/// Every seam in the main layout has a handle on it, and every region draws
1684/// itself at the size that handle sets: a region still measuring itself off the
1685/// window's own share is a panel whose divider moves nothing.
1686#[test]
1687fn every_seam_in_the_layout_has_a_divider_on_it() {
1688 let render = src_text("render.rs");
1689 for split in ["Split::Library", "Split::Inspector", "Split::Timeline"] {
1690 assert!(
1691 render.contains(&format!("divider({split}")),
1692 "{split} has no divider to drag"
1693 );
1694 }
1695 // The strip is drawn wide enough to hit and says which way it moves --
1696 // an invisible hairline is a feature nobody finds.
1697 let interact = src_text("interact.rs");
1698 assert!(
1699 interact.contains("cursor_col_resize") && interact.contains("cursor_row_resize"),
1700 "a divider with no resize cursor on it"
1701 );
1702 // ...and nothing lays a region out off the untouched share any more.
1703 for (file, stale) in [
1704 ("ui/inspector.rs", "inspector_w("),
1705 ("ui/toolbar.rs", "library_w("),
1706 ("render.rs", "library_w("),
1707 ] {
1708 assert!(
1709 !src_text(file).contains(stale),
1710 "{file} still measures a panel with {stale}"
1711 );
1712 }
1713}