forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

view.rs1262 lines, 51.9 KiBHistoryRawDownload
1//! Where a moment is drawn: drops and snaps, the zoom and the scroll, the
2//! paths a file is written to, and the strokes the handler answers.
3
4use super::*;
5
6/// The preview's one cached cue picture is keyed by the *cue* and not only by
7/// where it happens to sit: a lane and a start microsecond are not an identity --
8/// lift a bitmap caption off a lane, drop another track's caption at the same
9/// frame, and a key of those two matched the cache, painting the picture of the
10/// cue that is gone over the one that is up. The picture's own allocation is the
11/// rest of the key, and an identical repeat still hits, which is the whole cache.
12#[test]
13fn a_cached_cue_picture_is_keyed_by_the_cue_not_only_its_moment() {
14 use crate::ui::preview::sub_image_key;
15 let (lane, other) = (Lane::S1, Lane::A1);
16 // Two cues that share the lane and the start, and nothing else: one lifted,
17 // one placed at the same frame.
18 let a = sub_image_key(lane, 1_000_000, 3_000_000, 0x1000);
19 let b = sub_image_key(lane, 1_000_000, 3_000_000, 0x2000);
20 assert_ne!(
21 a, b,
22 "two different cues at one moment on one lane are one cache key again, so \
23 the second paints the first's picture"
24 );
25 // The same cue repainted: still a hit.
26 assert_eq!(
27 a,
28 sub_image_key(lane, 1_000_000, 3_000_000, 0x1000),
29 "the cache misses on every repaint of the same cue, so it decodes an 8 MB \
30 display set per frame"
31 );
32 // The same picture recut over the same start is a different cue.
33 assert_ne!(
34 a,
35 sub_image_key(lane, 1_000_000, 2_500_000, 0x1000),
36 "a cue's own end is no part of the key, so a recut cue serves the old window"
37 );
38 // And the other half of the old key still holds: the four PGS tracks of a
39 // remux start at the same microsecond, so the lane separates them.
40 assert_ne!(
41 a,
42 sub_image_key(other, 1_000_000, 3_000_000, 0x1000),
43 "the lane is no longer part of the key, so a lane's eye shut leaves the \
44 other lane's caption on screen"
45 );
46 // And the door builds its key this way, out of the cue's own picture: the
47 // cache is only keyed by the cue while the lookup goes through this
48 // constructor, and a test of the constructor alone would pass with the door
49 // still keying on `(lane, start_us)`.
50 let preview_rs = src_text("ui/preview.rs");
51 assert!(
52 preview_rs.contains(
53 "let key = sub_image_key(lane, start_us, end_us, Arc::as_ptr(image) as usize);"
54 ),
55 "the cue picture is cached under a key that is not the cue's own"
56 );
57 assert!(
58 preview_rs.contains("*up == key"),
59 "the cache no longer compares the key it built"
60 );
61}
62
63/// What a drop reads: the frame under the pointer, through the same scale
64/// the boxes are drawn through. Zoomed in, the same pixel is a different
65/// frame -- which is the whole reason `Player::frame_under` goes through
66/// [`Scale`] rather than through the duration alone.
67#[test]
68fn a_drop_reads_the_frame_under_the_pointer_at_every_zoom() {
69 // A 200 px bed inset by the panel's padding, 10 seconds at 30 fps.
70 let bed: Bounds<Pixels> = Bounds {
71 origin: point(px(12.), px(400.)),
72 size: size(px(200.), px(6.)),
73 };
74 let fps = 30.;
75 // The frame a pointer at window `x` names, exactly as `frame_under`
76 // composes it.
77 let under = |scale: Scale, x: f32| frame_at(scale.time_at(px_along(px(x), bed)), fps);
78
79 // The whole 10 s timeline across the 200 px bed: 20 px to the second,
80 // so halfway along is frame 150.
81 let fit = Scale {
82 pps: 20.,
83 start: 0.,
84 };
85 assert_eq!(under(fit, 12.), 0);
86 assert_eq!(under(fit, 112.), 150);
87 assert_eq!(under(fit, 212.), 300);
88
89 // Four times in, starting at second 5: the same middle pixel is now the
90 // frame in the middle of seconds 5..7.5, and the left edge is not 0.
91 let zoomed = Scale {
92 pps: 80.,
93 start: 5.,
94 };
95 assert_eq!(under(zoomed, 12.), 150);
96 assert_eq!(under(zoomed, 112.), 187);
97 assert_eq!(under(zoomed, 212.), 225);
98 // ...and a pointer that slid off either end of the bed names an end of
99 // the bed, never a pixel outside it.
100 assert_eq!(under(zoomed, 0.), 150);
101 assert_eq!(under(fit, 9999.), 300);
102}
103
104/// The snap: a clip let go a few frames off a neighbour's edge lands *on*
105/// it, by whichever of its own ends is nearer, and a clip let go in open bed
106/// stays exactly where the hand left it.
107#[test]
108fn a_dropped_clip_snaps_to_the_edges_worth_landing_on() {
109 // A neighbour covering [100, 160) and the playhead at 300.
110 let marks = [100, 160, 300, 0];
111 // Head a frame short of the neighbour's tail: laid end to end with it.
112 assert_eq!(snapped(158, 40, 4, &marks), 160);
113 // Tail a frame into its head: pulled back so the two meet exactly.
114 assert_eq!(snapped(62, 40, 4, &marks), 60);
115 // The playhead is an edge like any other.
116 assert_eq!(snapped(298, 40, 4, &marks), 300);
117 // Outside the tolerance nothing moves -- a gap the hand meant to leave
118 // is a gap.
119 assert_eq!(snapped(150, 40, 4, &marks), 150);
120 // No tolerance at all (zoomed right in, where a few pixels are worth
121 // less than a frame) is no snap: single frames are placed by hand.
122 assert_eq!(snapped(158, 40, 0, &marks), 158);
123 // The nearer edge wins when two are in reach.
124 assert_eq!(snapped(101, 40, 8, &marks), 100);
125 // ...and a mark closer to the head than `len` cannot pull the clip to a
126 // negative start.
127 assert_eq!(snapped(2, 40, 4, &marks), 0);
128}
129
130/// The shadow a drag draws and the drop that commits are one answer: both
131/// ask [`landing`], so the box seen in flight is the box the release leaves
132/// behind. What this pins down is the composition around the snap -- the
133/// grab offset comes off *before* the magnet, or a clip taken by its tail
134/// would land a boxful late.
135#[test]
136fn a_ghost_and_a_drop_are_one_landing() {
137 // A neighbour covering [100, 160), the playhead at 300, and a 40 frame
138 // clip taken hold of 12 frames in.
139 let marks = [100, 160, 300, 0];
140 let (len, grab, tol) = (40, 12, 4);
141 // Pointer at frame 170: the head is 12 frames behind it, at 158, which
142 // is a frame short of the neighbour's tail -- so both the ghost and the
143 // drop say 160, and the line stands on the mark that pulled it.
144 assert_eq!(landing(170, grab, len, true, tol, &marks), (160, Some(160)));
145 // Without the grab taken off first, the same pointer would land the
146 // box at 170 and no mark would be in reach: the offset is not cosmetic.
147 assert_eq!(landing(170, 0, len, true, tol, &marks), (170, None));
148 // A library row carries no grab and no length the engine has measured,
149 // which is how `Player::place_frame` asks: only its head lands, on the
150 // playhead here.
151 assert_eq!(landing(298, 0, 0, true, tol, &marks), (300, Some(300)));
152 // The magnet off, ghost and drop agree on the raw frame and no line is
153 // drawn -- the frame-by-frame placement the switch is for.
154 assert_eq!(landing(170, grab, len, false, tol, &marks), (158, None));
155 // A pointer nearer the bed's start than the hand is into the box cannot
156 // pull a head below zero.
157 assert_eq!(landing(3, grab, len, true, tol, &marks), (0, Some(0)));
158}
159
160/// Which lanes tint that shadow as refused: the two kinds of file a lane
161/// cannot hold, in the words the release would say them in -- one rule, so
162/// what is shown as impossible is exactly what is refused.
163#[test]
164fn a_lane_refuses_the_files_it_cannot_hold_before_the_release_says_so() {
165 let (video, audio) = (Lane::V1, Lane::A1);
166 let sound = Path::new("/media/take.mp3");
167 let still = Path::new("/media/card.png");
168 let movie = Path::new("/media/take.mp4");
169 assert_eq!(
170 lane_refuses(sound, video, false).as_deref(),
171 Some("Not on V1 — take.mp3 has no picture")
172 );
173 assert_eq!(
174 lane_refuses(still, audio, true).as_deref(),
175 Some("Not on A1 — card.png is a still image")
176 );
177 // ...and every lane a file *can* go on says nothing at all, which is a
178 // ghost drawn in the file's own colour.
179 assert_eq!(lane_refuses(sound, audio, false), None);
180 assert_eq!(lane_refuses(still, video, true), None);
181 assert_eq!(lane_refuses(movie, video, true), None);
182 // A file with a picture is not refused by an audio lane here: the
183 // engine takes its sound onto one, and the words for a video-only file
184 // are its own.
185 assert_eq!(lane_refuses(movie, audio, true), None);
186 // The extension lies and the probe corrects it: a song muxed into an
187 // `.mp4` still names a video lane refused, in the exact words the .mp3
188 // twin above got -- `has_video` is what decides it now, not the suffix.
189 assert_eq!(
190 lane_refuses(movie, video, false).as_deref(),
191 Some("Not on V1 — take.mp4 has no picture")
192 );
193 // ...and a subtitle lane holds none of the three: a caption comes off the
194 // Subtitles list, which is where the refusal points.
195 for (file, has_video) in [(sound, false), (still, true), (movie, true)] {
196 let why = lane_refuses(file, Lane::S1, has_video).expect("a subtitle lane takes no media");
197 assert!(why.starts_with("Not on S1 — "), "{why}");
198 assert!(why.contains("Subtitles list"), "{why}");
199 }
200 // How the two clocks a caption has meet, which is what a palette row's
201 // length is worked out with: a second of words at 30 fps is 30 frames,
202 // and a track shorter than one frame is still a caption to place.
203 assert_eq!(frames_of_us(1_000_000, 30.), 30);
204 assert_eq!(frames_of_us(500_000, 24.), 12);
205 assert_eq!(frames_of_us(1_000, 30.), 1);
206 assert_eq!(frames_of_us(1_000_000, 0.), 1);
207}
208
209/// Where those edges come from: every lane, not the one being dropped on --
210/// and never the clip in the hand or the half of it one track down.
211#[test]
212fn the_marks_are_every_lane_the_playhead_and_the_start() {
213 let clip = |start: u32, frames: u32, link| Clip {
214 speed_keys: Vec::new(),
215 reversed: false,
216 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
217 angle: Default::default(),
218 fade_in: 0,
219 fade_out: 0,
220 transition_out: 0,
221 transition_kind: Default::default(),
222 visualizer: 0,
223 viz_paint: 0,
224 gain_db: 0.0,
225 gain_keys: Vec::new(),
226 pan: 0,
227 pitch: 0.0,
228 transform_keys: Vec::new(),
229 opacity_keys: Vec::new(),
230 color_keys: Vec::new(),
231 effects: Vec::new(),
232 start,
233 in_frame: 0,
234 out_frame: frames,
235 source: 0,
236 link,
237 eq: None,
238 color: None,
239 transform: None,
240 fit: Default::default(),
241 speed: Default::default(),
242 };
243 // A grouped take across two lanes at 100..160, and a lone one on the
244 // audio lane at 400..430.
245 let video = [clip(100, 60, Some(7))];
246 let audio = [clip(100, 60, Some(7)), clip(400, 30, None)];
247 let lanes: [&[Clip]; 2] = [&video, &audio];
248
249 // Nothing in the hand: both lanes' edges, the playhead, and 0.
250 let mut all = snap_marks(&lanes, None, None, 300, None, &[]);
251 all.sort_unstable();
252 assert_eq!(all, [0, 100, 100, 160, 160, 300, 400, 430]);
253
254 // The video half in the hand, with its group named as the caller reads it
255 // off the pick: its own edges are gone, and so are its group's on the
256 // other lane -- both boxes travel with the drag. The lone audio clip is
257 // still a target, which is the whole point: a take being carried on V1
258 // lands flush with a sound on A1.
259 let mut carried = snap_marks(&lanes, Some((0, 0)), Some(7), 300, None, &[]);
260 carried.sort_unstable();
261 assert_eq!(carried, [0, 300, 400, 430]);
262
263 // An index that names no clip skips nothing and still answers.
264 assert_eq!(snap_marks(&[], Some((3, 9)), None, 0, None, &[]), [0, 0]);
265}
266
267/// The line the bed draws, and the switch that turns the whole thing off.
268#[test]
269fn the_snap_names_the_mark_it_landed_on_unless_it_is_switched_off() {
270 let marks = [100, 160, 300, 0];
271 // Pulled by the tail: the clip lands at 60 and the line stands on the
272 // edge its *tail* met, 100 -- not on the head it happens to have.
273 assert_eq!(snap_cue(true, 62, 40, 4, &marks), (60, Some(100)));
274 // Pulled by the head: line and landing are the same frame.
275 assert_eq!(snap_cue(true, 158, 40, 4, &marks), (160, Some(160)));
276 // A trim carries no length, so only its own edge lands.
277 assert_eq!(snap_cue(true, 298, 0, 4, &marks), (300, Some(300)));
278 // Open bed: nothing moves and nothing is drawn.
279 assert_eq!(snap_cue(true, 200, 40, 4, &marks), (200, None));
280 // Switched off, a gesture that would have snapped lands raw and draws
281 // no line -- the frame-by-frame placement the toggle is for.
282 assert_eq!(snap_cue(false, 158, 40, 4, &marks), (158, None));
283}
284
285/// A stream's rate is one number in the unit its size asks for, and a stated
286/// rate never reads as a zero: every decade from one bit a second up, and the
287/// edges of each unit switch.
288#[test]
289fn a_stated_rate_never_renders_as_a_zero() {
290 let edges: Vec<u64> = (0..12)
291 .flat_map(|e| {
292 let decade = 10_u64.pow(e);
293 [decade, decade * 4, decade * 5, decade * 9]
294 })
295 .chain([999, 1_000, 999_999, 1_000_000, 4_998, 113, 2_400, 8_432_000])
296 .collect();
297 for bits in edges {
298 let line = bits_label(bits);
299 let number: f64 = line
300 .split(' ')
301 .next()
302 .and_then(|n| n.parse().ok())
303 .unwrap_or_else(|| panic!("no number in {line:?}"));
304 assert!(number > 0., "{bits} bits a second rendered as {line:?}");
305 }
306}
307
308#[test]
309fn a_rate_is_said_in_the_unit_its_size_asks_for() {
310 assert_eq!(bits_label(113), "113 b/s");
311 assert_eq!(bits_label(4_998), "5.0 kb/s");
312 assert_eq!(bits_label(128_000), "128.0 kb/s");
313 assert_eq!(bits_label(8_432_000), "8.4 Mb/s");
314}
315
316#[test]
317fn a_size_reads_in_the_largest_unit_that_keeps_a_decimal() {
318 assert_eq!(size_human(1_200_000_000), "1.2 GB");
319 assert_eq!(size_human(840_000_000), "840 MB");
320 assert_eq!(size_human(512), "512 B");
321}
322
323#[test]
324fn a_picture_names_its_height_the_way_people_do() {
325 assert_eq!(resolution_label(1080), "1080p");
326 assert_eq!(resolution_label(720), "720p");
327 assert_eq!(resolution_label(2160), "4K");
328}
329
330#[test]
331fn a_picture_track_says_only_what_its_header_states() {
332 let video = engine::VideoFacts {
333 codec: engine::Codec::H264,
334 width: 1920,
335 height: 1080,
336 frame_rate: Some(29.97),
337 bit_depth: None,
338 matrix_assumed: false,
339 profile: None,
340 interlaced: None,
341 };
342 assert_eq!(
343 video_detail(&video, Some(5_200_000)),
344 "H.264 · 1920×1080 · 29.97 fps · 5.2 Mb/s"
345 );
346 let ten_bit = engine::VideoFacts {
347 codec: engine::Codec::Hevc,
348 bit_depth: Some(10),
349 matrix_assumed: false,
350 frame_rate: None,
351 ..video
352 };
353 assert_eq!(video_detail(&ten_bit, None), "HEVC · 1920×1080 · 10-bit");
354 let bare = engine::VideoFacts {
355 width: 0,
356 height: 0,
357 ..ten_bit
358 };
359 assert_eq!(video_detail(&bare, None), "HEVC · 10-bit");
360}
361
362#[test]
363fn a_sound_track_says_its_codec_rate_layout_depth_and_bitrate() {
364 let info = StreamInfo {
365 index: 0,
366 codec: "mp4a".to_string(),
367 channels: 2,
368 sample_rate: 48_000,
369 lang: None,
370 decodable: true,
371 bit_depth: None,
372 bitrate: Some(128_000),
373 };
374 assert_eq!(audio_detail(&info), "mp4a · 48 kHz · stereo · 128.0 kb/s");
375 let unnamed = StreamInfo {
376 codec: "unknown".to_string(),
377 channels: 0,
378 sample_rate: 0,
379 bitrate: None,
380 ..info
381 };
382 assert_eq!(audio_detail(&unnamed), "");
383}
384
385#[test]
386fn a_plate_lists_the_file_then_each_track_and_leaves_out_what_is_unknown() {
387 use crate::MediaBitrate;
388 let path = std::path::Path::new("/media/take-3.mp4");
389 let facts = engine::MediaFacts {
390 container: Some("mp4".to_string()),
391 bytes: Some(1_200_000_000),
392 video: Some(engine::VideoFacts {
393 codec: engine::Codec::H264,
394 width: 1920,
395 height: 1080,
396 frame_rate: Some(29.97),
397 bit_depth: None,
398 matrix_assumed: false,
399 profile: None,
400 interlaced: None,
401 }),
402 duration_secs: None,
403 streams: Vec::new(),
404 attached_pic: false,
405 };
406 let rate = MediaBitrate {
407 total: Some(8_432_000),
408 video: Some(7_918_000),
409 audio: None,
410 };
411 let track = StreamInfo {
412 index: 0,
413 codec: "mp4a".to_string(),
414 channels: 2,
415 sample_rate: 48_000,
416 lang: None,
417 decodable: true,
418 bit_depth: None,
419 bitrate: None,
420 };
421 let rows = file_properties(path, Some(&facts), std::slice::from_ref(&track), Some(rate));
422 let labels: Vec<&str> = rows.iter().map(|(label, _)| label.as_str()).collect();
423 assert_eq!(
424 labels,
425 ["File", "Path", "Container", "Size", "Video", "Audio"]
426 );
427 assert_eq!(rows[0].1, "take-3.mp4");
428 assert_eq!(rows[3].1, "1.2 GB · 8.4 Mb/s");
429 assert_eq!(rows[4].1, "H.264 · 1920×1080 · 29.97 fps · 7.9 Mb/s");
430 assert_eq!(rows[5].1, "mp4a · 48 kHz · stereo");
431
432 // Two sound tracks are told apart by which one of how many each is.
433 let second = StreamInfo {
434 index: 1,
435 ..track.clone()
436 };
437 let two = file_properties(path, None, &[track, second], None);
438 let labels: Vec<&str> = two.iter().map(|(label, _)| label.as_str()).collect();
439 assert_eq!(labels, ["File", "Path", "Audio 1 of 2", "Audio 2 of 2"]);
440
441 // Before the probe answers there is the file and nothing it has not said.
442 assert_eq!(file_properties(path, None, &[], None).len(), 2);
443}
444
445#[test]
446fn timecode_counts_frames_inside_the_second() {
447 assert_eq!(timecode(0., 30.), "00:00:00:00");
448 assert_eq!(timecode(-1., 30.), "00:00:00:00"); // clamped, never negative
449 assert_eq!(timecode(4.9667, 30.), "00:00:04:29"); // last frame of a 5 s clip
450 assert_eq!(timecode(5., 30.), "00:00:05:00");
451 assert_eq!(timecode(3661.5, 30.), "01:01:01:15");
452 // Rounding must not spill into a frame the second does not have.
453 assert_eq!(timecode(1. - f64::EPSILON, 30.), "00:00:00:29");
454 assert_eq!(timecode(0.999, 29.97), "00:00:00:29");
455}
456
457#[test]
458fn scrub_seeks_only_on_a_new_frame_and_only_every_100ms() {
459 let (slow, fast) = (Duration::from_millis(100), Duration::from_millis(99));
460 // Both halves must hold: a moved pointer that has not crossed a frame
461 // boundary would reopen the decoder for the same picture.
462 assert!(scrub_due(31, 30, slow));
463 assert!(!scrub_due(30, 30, slow));
464 assert!(!scrub_due(31, 30, fast));
465 assert!(!scrub_due(30, 30, fast));
466 // Exactly at the gap counts, and a long stall never blocks.
467 assert!(scrub_due(1, 0, Duration::from_secs(9)));
468}
469
470#[test]
471fn the_picture_is_restarted_only_when_it_is_really_behind_and_not_twice() {
472 // A quantum's worth of lateness is what every playing frame has; only a
473 // gap an eye reads as out of sync answers with a reopen.
474 assert!(!should_resync(0., None));
475 assert!(!should_resync(LATE_RESYNC, None));
476 assert!(should_resync(LATE_RESYNC + 0.1, None));
477 // ...and a decoder that is still behind right after a restart -- the
478 // usual case, since it was too slow to begin with -- waits out the gap
479 // instead of reopening at every repaint.
480 assert!(!should_resync(9., Some(Instant::now())));
481 assert!(should_resync(
482 9.,
483 Some(Instant::now() - RESYNC_GAP - Duration::from_millis(1))
484 ));
485}
486
487#[test]
488fn the_default_export_is_never_a_source_and_never_beside_one() {
489 use crate::player::library::default_export_path;
490 use std::path::Path;
491 let src = Path::new("/no-such-edith-dir/speech.mp4");
492 // A saved project is named after itself, and its name is not the source's.
493 let project = Path::new("/no-such-edith-dir/speech.edith");
494 let out = default_export_path(project, true, Some("speech"), &[src], Format::Mp4);
495 // With no Videos folder (a bare CI home) the default sits beside the
496 // project, which is the source's folder here, so " (2)" keeps it off it.
497 let beside = out.parent() == src.parent();
498 let want = if beside { "speech (2).mp4" } else { "speech.mp4" };
499 assert!(out.to_string_lossy().ends_with(want), "{out:?}");
500 assert_ne!(out, src);
501 // The file it would clash with is a source: " (2)" takes its place.
502 // The taken names sit in the same folder the default lands in.
503 let plain = out.with_file_name("speech.mp4");
504 let two = default_export_path(project, true, Some("speech"), &[plain.as_path()], Format::Mp4);
505 assert!(two.to_string_lossy().ends_with("speech (2).mp4"), "{two:?}");
506 let three = default_export_path(project, true, Some("speech"), &[plain.as_path(), two.as_path()], Format::Mp4);
507 assert!(three.to_string_lossy().ends_with("speech (3).mp4"), "{three:?}");
508 // Untitled: the first clip's name plus " edit", in the chosen format.
509 let untitled = default_export_path(Path::new(""), false, Some("speech"), &[src], Format::Webm);
510 assert!(untitled.to_string_lossy().ends_with("speech edit.webm"), "{untitled:?}");
511 // Nothing at all: "Untitled".
512 let none = default_export_path(Path::new(""), false, None, &[], Format::Mp4);
513 assert!(none.to_string_lossy().ends_with("Untitled.mp4"), "{none:?}");
514}
515
516#[test]
517fn the_first_save_lands_beside_the_media() {
518 assert_eq!(
519 project_path("assets/test_av.mp4"),
520 std::path::Path::new("assets/test_av.edith")
521 );
522 // The same rule an export follows: only the last extension moves.
523 assert_eq!(
524 project_path("a.export.mp4"),
525 std::path::Path::new("a.export.edith")
526 );
527 assert_eq!(project_path("clip"), std::path::Path::new("clip.edith"));
528 // Saving a loaded project writes the file it came from, not a second.
529 assert_eq!(project_path("a.edith"), std::path::Path::new("a.edith"));
530}
531
532#[test]
533fn only_an_exact_edith_extension_is_a_project() {
534 let p = std::path::Path::new;
535 assert!(is_project(p("a.edith")));
536 // A dotted directory must not decide it -- the file name does.
537 assert!(is_project(p("/v.mp4/a.edith")));
538 assert!(!is_project(p("a.mp4")));
539 assert!(!is_project(p("/v.edith/a.mp4")));
540 // Exactly what `save_project` writes: a dropped `.EDITH` goes to the
541 // demuxer and is refused there, not parsed as a project.
542 assert!(!is_project(p("a.EDITH")));
543 // An extension, never a bare name.
544 assert!(!is_project(p("edith")));
545 assert!(!is_project(p("a.edith.mp4")));
546}
547
548/// The keys menu is the registry drawn, so a *bindable* stroke cannot go
549/// missing from it by construction. The strokes the modal cards read for
550/// themselves are the ones that could: this reads the key handler's own
551/// source and fails on any key it answers to that the menu never mentions.
552#[test]
553fn no_stroke_is_missing_from_the_keys_menu() {
554 use keymap::{ActionId, Keymap};
555 // Every file the window is written in -- the handler, and the helpers
556 // it asks, wherever they have been moved to. The tests below compare
557 // keys too, and are not shortcuts.
558 let handler = ui_source();
559 let handler = handler.as_str();
560 let keymap = Keymap::defaults();
561 let listed = |key: &str| {
562 let pretty = keymap::Chord {
563 key: key.to_string(),
564 ctrl: false,
565 shift: false,
566 alt: false,
567 }
568 .pretty();
569 keymap.lookup(key, false, false, false).is_some()
570 || keymap::FIXED.iter().any(|f| f.chord == pretty)
571 };
572 let mut compared = 0;
573 for (at, needle) in handler.match_indices("key == ") {
574 let rest = &handler[at + needle.len()..];
575 let key = match rest.strip_prefix('"') {
576 Some(literal) => literal[..literal.find('"').expect("unterminated key")].to_string(),
577 // A named constant: the escape the cards get out by.
578 None if rest.starts_with("ESCAPE") => crate::ESCAPE.to_string(),
579 // The registry lookup compares a binding's key with the key it was given: a parameter, not a stroke.
580 None if rest.starts_with("key") => continue,
581 None => panic!("a key compared against something this cannot read: {rest:.20}"),
582 };
583 assert!(
584 listed(&key),
585 "the handler answers to {key:?} and the keys menu never says so"
586 );
587 compared += 1;
588 }
589 // The scan is only a guard while it still finds the comparisons: a
590 // rewrite that spells them differently must come back here.
591 assert!(
592 compared >= 4,
593 "the key comparisons moved; this scan is blind"
594 );
595 // The one branch that is not a comparison -- any digit is a bitrate.
596 assert!(handler.contains("key.parse::<u32>()"));
597 assert!(keymap::FIXED.iter().any(|f| f.chord == "0–9"));
598 // And every entry of both halves lands under a heading the menu draws.
599 for action in ActionId::ALL {
600 assert!(keymap::Category::ALL.contains(&action.category()));
601 }
602 for fixed in keymap::FIXED.iter() {
603 assert!(keymap::Category::ALL.contains(&fixed.category));
604 }
605}
606
607/// The mapping the whole panel is drawn and clicked through: a moment goes
608/// to a pixel on the bed and comes back the same moment, at every zoom.
609#[test]
610fn a_moment_and_the_place_it_is_drawn_are_the_same_at_every_zoom() {
611 let duration = 20.;
612 // The fit, which is the only scale the content's own length picks: 20 s
613 // across a 200 px bed is 10 px to the second, and a 5 s clip is a
614 // quarter of the bed -- the answer the fractional view gave for it.
615 let fit = test_view(Scale::default(), duration).fit();
616 assert_eq!(fit.pps, 10.);
617 assert_eq!(fit.width_px(5.), TEST_BED * 0.25);
618 for t in [0., 5., 12.5, 20.] {
619 assert_eq!(fit.px_at(t), (t / duration) as f32 * TEST_BED, "fit at {t}");
620 }
621 for scale in [
622 fit,
623 Scale {
624 pps: 20.,
625 start: 4.,
626 },
627 Scale {
628 pps: 80.,
629 start: 12.5,
630 },
631 Scale {
632 pps: 375.,
633 start: 19.,
634 },
635 ] {
636 let scale = test_view(scale, duration).settled();
637 for x in [0., 50., 100., TEST_BED] {
638 let at = scale.time_at(x);
639 assert!(
640 (f64::from(scale.px_at(at)) - f64::from(x)).abs() < 1e-3,
641 "{scale:?} round trip at {x}"
642 );
643 }
644 // A stretch as long as what is on the bed is as wide as the bed.
645 assert!(
646 (f64::from(scale.width_px(test_view(scale, duration).span())) - f64::from(TEST_BED))
647 .abs()
648 < 1e-3,
649 "{scale:?} spans the bed"
650 );
651 }
652}
653
654/// The rule that makes a zoom usable: whatever was under the anchor is
655/// still under it afterwards -- the playhead for a key, the pointer for a
656/// ctrl+wheel.
657#[test]
658fn a_zoom_leaves_the_anchor_where_it_was_on_screen() {
659 let duration = 20.;
660 let mut scale = test_view(Scale::default(), duration).settled();
661 // The same three points along the bed the fractional view held: a half,
662 // a quarter and nine tenths of 200 px.
663 for anchor in [100f32, 50., 180.] {
664 // Well past the zoom-in stop: the anchor holds at the clamp too,
665 // which is where it used to slide (the clamp came after the offset).
666 for _ in 0..30 {
667 let at = scale.time_at(anchor);
668 let view = test_view(scale, duration);
669 let zoomed = view.zoomed(ZOOM_STEP, anchor);
670 // Only where the anchor is not pinned by an edge of the
671 // timeline: a view already against an end cannot slide further.
672 let span = test_view(zoomed, duration).span();
673 let pinned = zoomed.start <= 0. || zoomed.start + span >= duration;
674 if !pinned {
675 assert!(
676 (f64::from(zoomed.px_at(at)) - f64::from(anchor)).abs() < 1e-3,
677 "{at} moved: {scale:?} -> {zoomed:?}"
678 );
679 }
680 assert!(zoomed.pps >= scale.pps, "and it did zoom in");
681 scale = zoomed;
682 }
683 }
684}
685
686/// Both stops. In is [`ZOOM_MIN_FRAMES`] across the bed; out, on a timeline
687/// far too short to be worth widening to, is a pixel to the second -- so a
688/// short import can be zoomed out of, a long one zoomed into, and neither
689/// can scroll off an end.
690#[test]
691fn zoom_stops_at_a_bedful_of_time_and_at_a_handful_of_frames() {
692 let (duration, fps) = (20., 30.);
693 let mut scale = Scale::default();
694 for _ in 0..200 {
695 scale = test_view(scale, duration).zoomed(1. / ZOOM_STEP, 100.);
696 }
697 assert!(
698 (test_view(scale, duration).span() - f64::from(TEST_BED) / PPS_MIN).abs() < 1e-6,
699 "widest is a pixel to the second, not the 20 s that happen to be on it"
700 );
701 for _ in 0..200 {
702 scale = test_view(scale, duration).zoomed(ZOOM_STEP, 100.);
703 }
704 assert_eq!(
705 (test_view(scale, duration).span() * fps).round(),
706 ZOOM_MIN_FRAMES,
707 "tightest is a handful of frames"
708 );
709 // Against the far end, the slice still ends at the last frame.
710 let end = test_view(
711 Scale {
712 start: 1e6,
713 ..scale
714 },
715 duration,
716 );
717 let end = (end.settled(), end.span());
718 assert!((end.0.start + end.1 - duration).abs() < 1e-9);
719 assert_eq!(
720 test_view(
721 Scale {
722 start: -5.,
723 ..scale
724 },
725 duration
726 )
727 .settled()
728 .start,
729 0.
730 );
731 // The dead zone the fractional view had: a timeline of a handful of
732 // frames could not be zoomed at all, because its own length was the
733 // floor *and* the ceiling. Both keys work on it now.
734 let tiny = test_view(Scale::default(), 0.1);
735 assert!(tiny.zoomed(ZOOM_STEP, 100.).pps > PPS_DEFAULT);
736 assert!(tiny.zoomed(1. / ZOOM_STEP, 100.).pps < PPS_DEFAULT);
737 // A timeline with no length at all divides by nothing and scrolls
738 // nowhere; the fit of one keeps the scale it had.
739 let empty = test_view(Scale::default(), 0.);
740 assert_eq!(empty.settled(), Scale::default());
741 assert_eq!(empty.fit(), Scale::default());
742 assert_eq!(Scale::default().px_at(0.), 0.);
743 // A bed that was never painted clamps nothing -- there is nothing to
744 // clamp against, and a zoom must survive the frame before the probe.
745 let unpainted = View {
746 bed: 0.,
747 ..test_view(
748 Scale {
749 pps: 4e6,
750 start: 3.,
751 },
752 duration,
753 )
754 };
755 assert_eq!(unpainted.settled().pps, 4e6);
756 assert_eq!(unpainted.following(19.), unpainted.scale);
757}
758
759/// The bug a fixed far stop was: two two-and-a-half hour clips are five
760/// hours of timeline, longer than any stop measured in hours, so the end of
761/// the second one could not be brought on screen by any zoom. The stop is
762/// the timeline's own length now, so it can.
763#[test]
764fn zooming_out_reaches_the_end_of_a_timeline_however_long_it_is() {
765 let bed = 900.;
766 let view = |scale: Scale, duration: f64| View {
767 scale,
768 bed,
769 duration,
770 fps: 30.,
771 };
772 // As far out as the keys go, from the scale a fresh project is drawn at.
773 let out = |duration: f64| {
774 let mut scale = Scale::default();
775 for _ in 0..400 {
776 scale = view(scale, duration).zoomed(1. / ZOOM_STEP, 0.);
777 }
778 scale
779 };
780 let five_hours = 2. * 2.5 * 3600.;
781 let wide = out(five_hours);
782 // The whole five hours is on the bed, the last frame drawn inside the
783 // window rather than against its edge.
784 assert_eq!(wide.start, 0.);
785 let end = wide.px_at(five_hours);
786 assert!(
787 end < bed,
788 "the end of the timeline is off the bed at {end} px"
789 );
790 assert!(end > bed * 0.9, "and not shrunk into a corner: {end} px");
791 assert!(
792 (view(wide, five_hours).span() - five_hours * ZOOM_OUT_MARGIN).abs() < 1e-6,
793 "the far stop is the timeline plus its margin"
794 );
795 // Zooming back in still reaches the frame stop on a timeline that long:
796 // the far stop moving does not drag the near one with it.
797 let mut scale = wide;
798 for _ in 0..400 {
799 scale = view(scale, five_hours).zoomed(ZOOM_STEP, 0.);
800 }
801 assert_eq!(
802 (view(scale, five_hours).span() * 30.).round(),
803 ZOOM_MIN_FRAMES
804 );
805 // And a ten second project is not zoomed out to four hours of empty
806 // bed: short of a pixel to the second its own length is not worth
807 // widening to, and that is 900 s of bed, not 14400.
808 assert!((view(out(10.), 10.).span() - f64::from(bed) / PPS_MIN).abs() < 1e-6);
809 // Whatever the length, the resting scale is nobody's content: the width
810 // invariant, which a far stop measured off the content would break.
811 assert_eq!(view(Scale::default(), 10.).settled(), Scale::default());
812 assert_eq!(
813 view(Scale::default(), five_hours).settled(),
814 Scale::default()
815 );
816 // Shrinking the timeline pulls a fully zoomed out view in with it --
817 // what was showing all of the timeline still shows all of it.
818 let shrunk = view(wide, 1800.).settled();
819 assert!((view(shrunk, 1800.).span() - 1800. * ZOOM_OUT_MARGIN).abs() < 1e-6);
820 assert!(shrunk.px_at(1800.) < bed);
821 // Growing it does not: a scale the user zoomed to is still legal, and
822 // the stop it stopped at is one press further out.
823 assert_eq!(view(wide, 2. * five_hours).settled().pps, wide.pps);
824 assert!(view(wide, 2. * five_hours).zoomed(1. / ZOOM_STEP, 0.).pps < wide.pps);
825}
826
827/// The bare wheel's own move: the view slides along the timeline, what is
828/// drawn where slides with it, the scale never changes, and both ends stop
829/// against the content rather than scrolling it off the bed.
830#[test]
831fn a_scroll_slides_the_view_without_zooming_it() {
832 let duration = 60.;
833 // Zoomed in far enough that there is somewhere to scroll to: 10 s of a
834 // 60 s timeline on the bed.
835 let start = test_view(
836 Scale {
837 pps: f64::from(TEST_BED) / 10.,
838 start: 0.,
839 },
840 duration,
841 )
842 .settled();
843 let notch = TEST_BED * SCROLL_NOTCH_SHARE;
844 let on = test_view(start, duration).scrolled(notch);
845 // A tenth of the bed later, and drawn a tenth of the bed to the left --
846 // the two halves of one move.
847 assert_eq!(on.pps, start.pps, "a scroll is not a zoom");
848 assert!(
849 (on.start - (start.start + 1.)).abs() < 1e-9,
850 "one notch is a tenth of the 10 s on the bed: {on:?}"
851 );
852 assert!(
853 (f64::from(start.px_at(20.) - on.px_at(20.)) - f64::from(notch)).abs() < 1e-3,
854 "and what was drawn moved with it: {on:?}"
855 );
856 // Back the other way, from the same place, is the same distance.
857 let back = test_view(on, duration).scrolled(-notch);
858 assert!((back.start - start.start).abs() < 1e-9, "{back:?}");
859 // Neither end can be scrolled off: the head stops at zero, and the tail
860 // stops with the last frame on the bed -- the clamp is the timeline's
861 // own length, not a number.
862 let mut scale = start;
863 for _ in 0..200 {
864 scale = test_view(scale, duration).scrolled(notch);
865 }
866 assert_eq!(scale.pps, start.pps);
867 assert!(
868 (scale.start - (duration - 10.)).abs() < 1e-6,
869 "the tail stops with the end on the bed: {scale:?}"
870 );
871 for _ in 0..200 {
872 scale = test_view(scale, duration).scrolled(-notch);
873 }
874 assert_eq!(scale.start, 0., "and the head stops at the head: {scale:?}");
875 // A view already showing all of it has nowhere to go.
876 let whole = test_view(Scale::default(), duration).fit();
877 assert_eq!(test_view(whole, duration).scrolled(notch), whole);
878}
879
880/// What makes a zoomed timeline follow the playing head: off the bed at
881/// either end pulls the view onto it, and on the bed it never moves -- a
882/// view that jumped every frame would be unreadable.
883#[test]
884fn the_view_follows_a_playhead_that_runs_off_the_bed() {
885 let duration = 20.;
886 // 5 s on a 200 px bed: 40 px to the second, starting at second 5.
887 let view = test_view(
888 Scale {
889 pps: 40.,
890 start: 5.,
891 },
892 duration,
893 );
894 let scale = view.settled();
895 assert_eq!(view.span(), 5.);
896 // Inside: untouched, whichever part of the slice it is in.
897 for at in [5., 7.5, 10.] {
898 assert_eq!(view.following(at), scale, "{at} is on the bed");
899 }
900 // Past the right edge, as playback does it: the head comes back on the
901 // bed, and the scale is not changed by the scroll.
902 let moved = view.following(12.);
903 assert_eq!(moved.pps, scale.pps);
904 assert!(moved.start > scale.start, "scrolled forward");
905 assert!(
906 moved.px_at(12.) > 0. && moved.px_at(12.) < TEST_BED,
907 "and the playhead is on screen"
908 );
909 // A seek back behind the slice does the same the other way.
910 let back = view.following(1.);
911 assert!(back.start < scale.start);
912 assert!(back.px_at(1.) >= 0.);
913 // With the whole timeline on the bed there is nothing to follow.
914 let whole = test_view(Scale::default(), duration);
915 let fit = whole.fit();
916 for at in [0., 10., 20.] {
917 assert_eq!(
918 test_view(fit, duration).following(at),
919 fit,
920 "the fit never scrolls"
921 );
922 }
923}
924
925/// The wheel during playback. A scroll away from the playing head used to
926/// be undone by the follow on the very next frame -- with a second, longer
927/// media on the timeline making it scrollable at all, one notch in five
928/// reached the screen and the wheel looked dead. The hand keeps the view
929/// now, and the follow takes it back by itself when the head runs into what
930/// the hand is looking at.
931#[test]
932fn a_scroll_during_playback_wins_until_the_head_catches_up() {
933 let duration = 80.;
934 let mut scale = test_view(
935 Scale {
936 pps: 40.,
937 start: 0.,
938 },
939 duration,
940 )
941 .settled();
942 // The render's arbitration, in the two lines it is there: a panned view
943 // is left where the hand put it, and the pan ends where the head is
944 // back on the bed.
945 let frame = |scale: Scale, panned: &mut bool, at: f64| {
946 let scale = match *panned {
947 true => test_view(scale, duration).settled(),
948 false => test_view(scale, duration).following(at),
949 };
950 if *panned && test_view(scale, duration).shows(at) {
951 *panned = false;
952 }
953 scale
954 };
955 // Playing at second one, five notches of the wheel: every one of them
956 // moves the view, and none is taken back by the head being off the bed.
957 let notch = f64::from(TEST_BED * SCROLL_NOTCH_SHARE);
958 let mut panned = false;
959 for n in 1..=5 {
960 scale = test_view(scale, duration).scrolled(TEST_BED * SCROLL_NOTCH_SHARE);
961 panned = true;
962 scale = frame(scale, &mut panned, 1.);
963 // ...and the pan is only *held* while the head is off the bed: the
964 // first notches still show it, so the follow has the view back for
965 // free and would not have moved anything anyway.
966 assert_eq!(panned, scale.start > 1., "held while the head is off");
967 assert!(
968 (scale.start - notch * f64::from(n) / 40.).abs() < 1e-6,
969 "notch {n} reached the screen: {scale:?}"
970 );
971 }
972 // The head runs into it: the pan is given back with nothing pressed...
973 let span = test_view(scale, duration).span();
974 let start = frame(scale, &mut panned, scale.start + span / 2.).start;
975 assert!(!panned, "the follow has the view back");
976 assert_eq!(start, scale.start, "and it did not jump to take it");
977 // ...and the next head that runs off the bed pulls the view again.
978 let ran_off = frame(scale, &mut panned, start + span + 1.);
979 assert!(
980 ran_off.start > start,
981 "the follow follows again: {ran_off:?}"
982 );
983 // A paused hand is untouched by any of this: with no follow asking,
984 // `shows` is the only thing the pan is ever released by.
985 assert!(test_view(scale, duration).shows(scale.start));
986 assert!(!test_view(scale, duration).shows(scale.start + span + 0.5));
987}
988
989/// The bug this mapping exists for: the first import used to fill the whole
990/// track whatever it was, because the bed *was* the timeline -- so a 5 s
991/// clip was 100% of the lane, zooming out did nothing, and adding a second
992/// clip silently halved the first one's box.
993#[test]
994fn a_clip_is_drawn_the_same_width_whatever_else_is_on_the_timeline() {
995 let bed = 900.;
996 let of = |duration: f64| View {
997 scale: Scale::default(),
998 bed,
999 duration,
1000 fps: 30.,
1001 };
1002 // One 5 s import, then a second clip after it: 20 s of timeline where
1003 // there were 5, and the first box has not moved or narrowed.
1004 let (alone, joined) = (of(5.).settled(), of(20.).settled());
1005 assert_eq!(alone, joined);
1006 assert_eq!(alone.width_px(5.), joined.width_px(5.));
1007 assert_eq!(joined.px_at(5.), alone.width_px(5.));
1008 // And it does not fill the track: a short clip reads as short.
1009 assert!(
1010 alone.width_px(5.) < bed / 2.,
1011 "5 s at {} px/s is {} px of a {bed} px bed",
1012 alone.pps,
1013 alone.width_px(5.)
1014 );
1015 // Zooming out visibly shrinks it, however short the timeline is -- the
1016 // press that used to be a no-op.
1017 let out = of(5.).zoomed(1. / ZOOM_STEP, 0.);
1018 assert!(
1019 out.width_px(5.) < alone.width_px(5.),
1020 "{} px is not smaller than {} px",
1021 out.width_px(5.),
1022 alone.width_px(5.)
1023 );
1024 // The way back to "the whole timeline across the bed" is still one key.
1025 assert_eq!(of(5.).fit().width_px(5.), bed);
1026}
1027
1028/// What the zoom button says: how much timeline is on the bed, in a unit
1029/// that tells two zooms apart.
1030#[test]
1031fn the_zoom_button_says_how_much_is_on_the_bed() {
1032 // A frame of quiet at 60 fps, which the silence card says out loud.
1033 assert_eq!(secs_label(1. / 60.), "0.02s");
1034 assert_eq!(secs_label(4.5), "4.5s");
1035}
1036
1037/// Keyboard focus v1 (`ui::stance::{Surface, next_surface, is_focus_cycle_key}`):
1038/// Tab walks dock -> bench -> inspector -> dock, wrapping; Shift-Tab walks
1039/// it backward. No gpui window harness exists in this crate to drive a real
1040/// `KeyDownEvent` through -- this exercises the exact pure function every
1041/// surface's `on_key_down` calls, which is where the cycle order actually
1042/// lives.
1043#[test]
1044fn tab_cycles_dock_bench_inspector_and_wraps() {
1045 use crate::ui::stance::{Surface, next_surface};
1046
1047 assert_eq!(next_surface(Surface::Dock, false), Surface::Bench);
1048 assert_eq!(next_surface(Surface::Bench, false), Surface::Inspector);
1049 assert_eq!(next_surface(Surface::Inspector, false), Surface::Dock);
1050
1051 // Shift-Tab is the exact reverse at every step.
1052 assert_eq!(next_surface(Surface::Dock, true), Surface::Inspector);
1053 assert_eq!(next_surface(Surface::Inspector, true), Surface::Bench);
1054 assert_eq!(next_surface(Surface::Bench, true), Surface::Dock);
1055}
1056
1057/// The defect this closes: the dock mounts only one of its two tabs at a
1058/// time (`dock_stance::render`'s `match src_active`), so focusing
1059/// `focus_dock`/`focus_inspector` while the other tab is showing lands on a
1060/// handle with no tree node -- gpui then dispatches no key listener at all,
1061/// keyboard input is dead until a mouse click. `Player::focus_surface`
1062/// (`ui::stance.rs`) flips the tab first via this pure decision so the
1063/// surface being entered is always the one mounted.
1064#[test]
1065fn surface_wants_src_active_mounts_the_tab_before_focus_lands_on_it() {
1066 use crate::ui::stance::{Surface, surface_wants_src_active};
1067
1068 assert_eq!(surface_wants_src_active(Surface::Dock), Some(true));
1069 assert_eq!(surface_wants_src_active(Surface::Inspector), Some(false));
1070 // Bench has no dock tab of its own -- entering it must not disturb
1071 // whichever tab the dock was last left on.
1072 assert_eq!(surface_wants_src_active(Surface::Bench), None);
1073}
1074
1075/// The root fallback guarantee (main.rs:1054's "every keybind hangs off the
1076/// root FocusHandle"): a surface's own `on_key_down` answers Tab/Shift-Tab
1077/// and nothing else -- `cx.stop_propagation()` is only ever reached from
1078/// that one branch (`ui::stance::is_focus_cycle_key`), so every other key,
1079/// still-pressed while a surface is focused, is left un-stopped and bubbles
1080/// up the dispatch tree to the root's own `on_key_down`
1081/// (gpui-0.2.2 `window.rs`'s `dispatch_key_down_up_event`, `Bubble` phase,
1082/// walks the focused node's ancestors and stops only at
1083/// `cx.stop_propagation()` -- verified by reading that function, not
1084/// assumed). This asserts the gate itself: only "tab" is ever intercepted,
1085/// so a keybind like space (play/pause) or "s" (split) is provably never
1086/// swallowed by a focused surface.
1087#[test]
1088fn only_tab_is_intercepted_by_a_focused_surface_everything_else_reaches_root() {
1089 use crate::ui::stance::is_focus_cycle_key;
1090
1091 assert!(is_focus_cycle_key("tab"));
1092 for key in [
1093 "space", "escape", "s", "c", "left", "right", "enter", "delete", "?",
1094 ] {
1095 assert!(!is_focus_cycle_key(key), "{key} must bubble to the root");
1096 }
1097}
1098
1099/// The ring's other door, escape: [`ui::stance::is_focus_exit_key`] is the
1100/// one branch a focused surface's `on_key_down` calls to hand focus back to
1101/// the root (`Player::focus`) instead of letting escape bubble there on its
1102/// own -- same pure-function-level check as the Tab gate above, since this
1103/// crate has no window harness to drive a real `KeyDownEvent` through.
1104#[test]
1105fn escape_is_the_only_key_a_focused_surface_uses_to_leave_the_ring() {
1106 use crate::ui::stance::is_focus_exit_key;
1107
1108 assert!(is_focus_exit_key("escape"));
1109 for key in [
1110 "tab", "space", "s", "c", "left", "right", "enter", "delete", "?",
1111 ] {
1112 assert!(!is_focus_exit_key(key), "{key} must not exit the ring");
1113 }
1114}
1115
1116/// [`ActionId::FocusPanels`] is what starts the ring in the first place
1117/// (`Player::act`'s `self.focus_surface(Surface::Dock, ..)`) -- without a
1118/// bound key reaching it, `next_surface`/`is_focus_cycle_key` above are
1119/// unreachable dead code, exactly the defect this action closes.
1120#[test]
1121fn focus_panels_is_bound_and_lands_on_the_dock() {
1122 use keymap::{ActionId, Keymap};
1123
1124 let k = Keymap::defaults();
1125 assert_eq!(k.lookup("f6", false, false, false), Some(ActionId::FocusPanels));
1126 // Bare Tab must still mean Select at the root -- FocusPanels must not
1127 // have stolen it.
1128 assert_eq!(k.lookup("tab", false, false, false), Some(ActionId::Select));
1129}
1130
1131/// A card is not a key-eating black box: the room-wide chords that act on the
1132/// document -- the edit history, the project file, the clipboard -- must reach
1133/// `Player::act` while any card is open. `param_card_key` answers `true` for
1134/// *every* stroke once one of the seven is up, so the dispatch has to stand in
1135/// front of it, not only in front of the blanket modal guard under it; and the
1136/// blanket guard's own `card_open()` has to read after that dispatch too, or a
1137/// chord that got past `param_card_key` (a menu dismiss comes to mind) would
1138/// still never reach the keymap.
1139///
1140/// A scan of the handler's own source, for the reason every handler scan here
1141/// gives: this binary has no window harness to press `ctrl+z` through.
1142#[test]
1143fn an_open_card_does_not_swallow_the_document_chords() {
1144 use crate::ui::stance::card_safe_action;
1145 use keymap::ActionId;
1146 // The five the room answers through a card, and the reason each is on the
1147 // list: history, file, clipboard.
1148 for action in [
1149 ActionId::Undo,
1150 ActionId::Redo,
1151 ActionId::Save,
1152 ActionId::Copy,
1153 ActionId::Paste,
1154 ] {
1155 assert!(
1156 card_safe_action(action),
1157 "{action:?} is a document chord and a card must not eat it"
1158 );
1159 }
1160 // ...and the strokes the cards' own branch list claims stay theirs:
1161 // escape is every card's way out, `s` is the equalizer's spectrum, `x` its
1162 // band removal, `m` every card's maximize, and tab picks a band.
1163 for action in [
1164 ActionId::Deselect,
1165 ActionId::Cut,
1166 ActionId::Delete,
1167 ActionId::ToggleMute,
1168 ActionId::Equalizer,
1169 ActionId::Color,
1170 ActionId::Loop,
1171 ActionId::TrimIn,
1172 ] {
1173 assert!(
1174 !card_safe_action(action),
1175 "{action:?} is a card's own stroke and the card must keep it"
1176 );
1177 }
1178 // The chords are real bindings, not a list of actions nothing reaches.
1179 let keys = keymap::Keymap::defaults();
1180 for (key, ctrl, action) in [
1181 ("z", true, ActionId::Undo),
1182 ("y", true, ActionId::Redo),
1183 ("s", true, ActionId::Save),
1184 ("c", true, ActionId::Copy),
1185 ("v", true, ActionId::Paste),
1186 ] {
1187 assert_eq!(
1188 keys.lookup(key, ctrl, false, false),
1189 Some(action),
1190 "the keymap no longer binds {action:?}"
1191 );
1192 }
1193 // And the dispatch stands where it has to: inside the root handler, ahead
1194 // of the cards' own branches and ahead of the blanket modal guard.
1195 let stance_rs = src_text("ui/stance.rs");
1196 let dispatch = stance_rs.find("card_safe_action(action)").expect(
1197 "the root key handler no longer asks which chords a card does not take -- an open card \
1198 eats every stroke again",
1199 );
1200 assert!(
1201 stance_rs[..dispatch].contains("this.keymap.lookup(key, ctrl, shift, alt)"),
1202 "the dispatch no longer goes through the keymap, so a rebind would leave it behind"
1203 );
1204 // The *statement* that dispatches, not just some `keymap.lookup` before it:
1205 // the hold gate at the top of the handler resolves the same pair, so a needle
1206 // that only asks for the lookup is satisfied by a dispatch resolving the
1207 // action some other way entirely.
1208 let resolve = stance_rs
1209 .find("if let Some(action) = this.keymap.lookup(key, ctrl, shift, alt)")
1210 .expect("the dispatch no longer resolves an action through the keymap");
1211 let stmt = &stance_rs[resolve..];
1212 let stmt = &stmt[..stmt.find('{').expect("the dispatch statement has no block")];
1213 assert!(
1214 stmt.contains("card_safe_action("),
1215 "the dispatch resolves an action and never asks whether a card may take \
1216 it, so an open card eats the document chords again"
1217 );
1218 for (guard, label) in [
1219 ("if this.param_card_key(", "the cards' own key branches"),
1220 ("if this.card_open()", "the blanket modal guard"),
1221 ] {
1222 let at = stance_rs
1223 .find(guard)
1224 .unwrap_or_else(|| panic!("{label} moved or was renamed"));
1225 assert!(
1226 dispatch < at,
1227 "{label} reads before the document dispatch -- an open card would \
1228 swallow undo, redo, save and the clipboard pair again"
1229 );
1230 }
1231}
1232
1233/// Play Around (Shift+K) is its own key, and the run it plays is the two seconds on
1234/// either side of the playhead, clamped to the timeline at both ends.
1235#[test]
1236fn play_around_is_shift_k_and_runs_two_seconds_either_side() {
1237 use crate::timeline_math::{PLAY_AROUND_PAD, play_around_span};
1238 let km = crate::keymap::Keymap::defaults();
1239 assert_eq!(km.lookup("k", false, true, false), Some(ActionId::PlayAround));
1240 assert_eq!(km.lookup("k", false, false, false), Some(ActionId::ShuttleStop), "plain K still stops");
1241 assert_eq!(PLAY_AROUND_PAD, 2.0);
1242 assert_eq!(play_around_span(10., 60.), (8., 12.));
1243 assert_eq!(play_around_span(1., 60.), (0., 3.), "the lead-in stops at the start");
1244 assert_eq!(play_around_span(59., 60.), (57., 60.), "the run-on stops at the end");
1245 assert_eq!(play_around_span(0., 0.), (0., 0.), "an empty timeline has no run");
1246}
1247
1248/// Snap targets include the comment markers' edges and the chapter starts, so a
1249/// clip let go a frame off one of them lands on it; the list the timeline builds
1250/// from the project is the same list `snap_marks` takes.
1251#[test]
1252fn a_drop_snaps_to_a_marker_or_a_chapter_edge() {
1253 // Markers at 250 (a point) and 380..400 (a span), chapters at 500.
1254 let notes = [250, 250, 380, 400, 500];
1255 let marks = snap_marks(&[], None, None, 0, None, &notes);
1256 for mark in [250, 380, 400, 500] {
1257 assert!(marks.contains(&mark), "{mark} is a snap target");
1258 }
1259 assert_eq!(snapped(248, 40, 4, &marks), 250, "a head a frame short of a marker meets it");
1260 assert_eq!(snapped(497, 0, 4, &marks), 500, "a chapter start pulls the clip onto it");
1261 assert_eq!(snapped(150, 40, 4, &marks), 150, "open bed beside them stays where it was");
1262}