forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

editing.rs3973 lines, 164.4 KiBHistoryRawDownload
1//! Importing, the library column, the menus, and every edit a clip or a
2//! track can be handed.
3
4use super::*;
5use crate::GapPick;
6use crate::player::timeline_edit::live_gap;
7use crate::ui::stance::{clip_readout, fps_label, gap_readout};
8
9/// What the file manager is handed: the parts a path keeps as they are, and
10/// the ones the bus would otherwise read as something else.
11#[test]
12fn file_uri_encodes_what_a_path_carries() {
13 assert_eq!(
14 file_uri(std::path::Path::new("/a/b.mp4")),
15 "file:///a/b.mp4"
16 );
17 assert_eq!(
18 file_uri(std::path::Path::new("/home/x/out dir/my export.mp4")),
19 "file:///home/x/out%20dir/my%20export.mp4"
20 );
21 assert_eq!(
22 file_uri(std::path::Path::new("/tmp/ünlü#1?.mp4")),
23 "file:///tmp/%C3%BCnl%C3%BC%231%3F.mp4"
24 );
25}
26
27/// An import fills the *library* and nothing else -- the whole point of
28/// this door: the row is there at the file's own length before any clip
29/// plays it, wearing the tint the lanes will tint that clip with, and the
30/// timeline is exactly as long as it was. Placing it is the drag, and the
31/// drag is a separate act.
32#[test]
33fn an_import_adds_a_row_at_its_own_length_and_leaves_the_lanes_alone() {
34 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
35 session.set_gain(0.0);
36 let before = session.timeline_duration();
37 let clips: Vec<usize> = session
38 .lanes()
39 .into_iter()
40 .map(|lane| session.lane_clips(lane).len())
41 .collect();
42 session.import(&asset("test_av2.mp4")).expect("av2 matches");
43 assert_eq!(session.sources().len(), 2, "the library grew");
44 assert_eq!(
45 session.timeline_duration(),
46 before,
47 "an import must not place a clip"
48 );
49 assert_eq!(
50 session
51 .lanes()
52 .into_iter()
53 .map(|lane| session.lane_clips(lane).len())
54 .collect::<Vec<_>>(),
55 clips,
56 "no lane moved"
57 );
58 // The rows the panel draws: one per source, each its file's own length
59 // -- source 1 has no clip anywhere and is still 4 s at 30 fps.
60 let rows = library_rows(
61 session.sources(),
62 &HashMap::new(),
63 &HashMap::new(),
64 None,
65 |path| session.file_frames(path),
66 );
67 assert_eq!(rows.len(), 2);
68 assert_eq!(rows[0].frames, 150, "5 s at 30 fps");
69 assert_eq!(rows[1].frames, 120, "4 s at 30 fps, never placed");
70 // The swatch is the clip colour, by the same index and the same
71 // function -- what makes the panel and the lanes one association.
72 for (row, r) in rows.iter().enumerate() {
73 assert_eq!(r.tint, row);
74 assert_eq!(source_tint(row), SOURCE_TINTS()[row % SOURCE_TINTS().len()]);
75 }
76}
77
78/// The window opened on a song and nothing else -- the launch argument, the
79/// drop on an empty window and the Import button all end in the same
80/// `PlaybackSession::open`. The library lists it placeable, the lane door
81/// the Add button and a drag share puts it on `A1`, and the one format that
82/// needs a picture says so on its own row instead of failing at the end of
83/// an export.
84#[test]
85fn a_song_opens_the_window_by_itself() {
86 let mut session = PlaybackSession::open(asset("test_tone.mp3")).expect("a song is a timeline");
87 session.set_gain(0.0);
88 // The source's own path, which is the canonical one a row carries.
89 let path = session.sources()[0].path.clone();
90 assert!(session.lane_clips(Lane::V1).is_empty(), "no picture");
91 assert_eq!(session.lane_clips(Lane::A1).len(), 1);
92
93 // The library row: probed like any other source, and not greyed --
94 // `unusable` is what the panel dims a row with.
95 let streams = HashMap::from([(
96 path.clone(),
97 engine::AudioSession::probe_streams(&path).expect("probe the song"),
98 )]);
99 let rate = streams[&path]
100 .iter()
101 .find(|s| s.index == session.sources()[0].audio_stream)
102 .map(|s| (s.sample_rate, s.channels));
103 let frames = session.file_frames(&path);
104 let rows = library_rows(session.sources(), &streams, &HashMap::new(), rate, |_| {
105 frames
106 });
107 assert_eq!(rows.len(), 1);
108 assert_eq!(rows[0].name, "test_tone.mp3");
109 assert_eq!(rows[0].unusable, None, "the row is placeable");
110 assert_eq!(rows[0].frames, 90, "3 s at the audio-only 30 fps");
111
112 // ...and it places, on the audio lane, through the door `insert_source`
113 // uses: a second copy of the song at the playhead.
114 session.seek(1.0);
115 assert!(
116 session
117 .place_stream_at(1.0, &path, 0, Some(Lane::A1))
118 .expect("its own file is on this timeline")
119 );
120 assert_eq!(session.lane_clips(Lane::A1).len(), 2);
121 assert!(session.lane_clips(Lane::V1).is_empty(), "still no picture");
122
123 // The Matroska and WebM rows carry the reason rather than the format's
124 // detail line, each naming itself. The mp4 rows are not refused: the engine
125 // writes an mp4 of a picture-less timeline as the sound alone. The audio
126 // formats are what this timeline is and are never refused.
127 assert_eq!(
128 format_refusal(&session, Format::Av1).as_deref(),
129 Some("no picture — an AV1 Matroska would be black; export an mp4, M4A, WAV, FLAC, MP3 or Ogg")
130 );
131 assert_eq!(
132 format_refusal(&session, Format::Webm).as_deref(),
133 Some("no picture — a WebM would be black; export an mp4, M4A, WAV, FLAC, MP3 or Ogg")
134 );
135 assert_eq!(format_refusal(&session, Format::Mp4), None, "an mp4 of it is the sound alone");
136 assert_eq!(format_refusal(&session, Format::Av1Mp4), None, "an AV1 mp4 of it is the sound alone");
137 assert_eq!(format_refusal(&session, Format::M4a), None);
138 assert_eq!(format_refusal(&session, Format::Wav), None);
139 assert_eq!(format_refusal(&session, Format::Flac), None);
140 assert_eq!(format_refusal(&session, Format::Mp3), None);
141}
142
143/// A file's every audio track gets a row: the ones the timeline can take
144/// are placeable, the ones it cannot are listed greyed with the reason.
145/// Which rows exist at all is the branchy part of the panel, so it is
146/// planned as data and checked here rather than through the pointer.
147#[test]
148fn every_audio_stream_of_a_file_is_a_row_usable_or_not() {
149 let multi = PathBuf::from("/m/movie.mp4");
150 let sources = [source("/m/movie.mp4", 0)];
151 let mut streams = HashMap::new();
152 streams.insert(
153 multi.clone(),
154 vec![
155 info(0, 44_100, 2, None, true),
156 info(1, 44_100, 2, Some("fra"), true),
157 info(2, 22_050, 1, Some("deu"), true),
158 info(3, 0, 0, None, false),
159 ],
160 );
161 let rows = library_rows(
162 &sources,
163 &streams,
164 &HashMap::new(),
165 Some((44_100, 2)),
166 |_| 90,
167 );
168 assert_eq!(
169 rows.iter().map(|r| r.stream).collect::<Vec<_>>(),
170 [0, 1, 2, 3],
171 "one row per audio stream, in file order"
172 );
173 assert!(
174 rows.iter().all(|r| r.path == multi && r.tint == 0),
175 "every stream of one file wears the file's own tint"
176 );
177 assert_eq!(rows[0].name, "movie.mp4 [audio 1]");
178 assert_eq!(rows[1].name, "movie.mp4 [audio 2]");
179 assert_eq!(rows[1].detail, "fra 44.1 kHz stereo");
180 // Placeable: the one already on the timeline, and the one that matches
181 // it. The mono track cannot join a stereo timeline -- one device and one
182 // copied AAC track for the whole of it -- and the codec we cannot read
183 // cannot join anything. Both say which. Its 22 kHz is *not* part of that
184 // any more: a rate of its own is resampled at the decoder's door, and a
185 // row greyed for one the engine accepts is this picker telling a lie.
186 assert_eq!((&rows[0].unusable, &rows[1].unusable), (&None, &None));
187 assert_eq!(rows[2].unusable.as_deref(), Some("the timeline is stereo"));
188 assert_eq!(
189 unusable(&info(9, 48_000, 2, None, true), Some((44_100, 2))),
190 None,
191 "48 kHz stereo joins a 44.1 kHz stereo timeline"
192 );
193 assert_eq!(rows[3].unusable.as_deref(), Some("unsupported codec"));
194 assert_eq!(
195 rows[3].detail, "",
196 "a stream we cannot parse claims nothing"
197 );
198 // Every row is the same file, so every row is that file's length.
199 assert!(rows.iter().all(|r| r.frames == 90));
200
201 // The single-stream case is exactly one row and no stream tag: no
202 // regression for the media everything else in the world is.
203 let plain = [source("/m/plain.mp4", 0)];
204 let mut one = HashMap::new();
205 one.insert(
206 PathBuf::from("/m/plain.mp4"),
207 vec![info(0, 44_100, 2, None, true)],
208 );
209 let rows = library_rows(&plain, &one, &HashMap::new(), Some((44_100, 2)), |_| 90);
210 assert_eq!(rows.len(), 1);
211 assert_eq!(rows[0].name, "plain.mp4");
212 assert_eq!(
213 rows[0].detail, "",
214 "one audio track is the row it has always been: name and length"
215 );
216 // ...as is a silent file, and a file not probed yet.
217 let mut silent = HashMap::new();
218 silent.insert(PathBuf::from("/m/plain.mp4"), Vec::new());
219 for probe in [silent, HashMap::new()] {
220 let rows = library_rows(&plain, &probe, &HashMap::new(), None, |_| 90);
221 assert_eq!(rows.len(), 1);
222 assert_eq!(rows[0].name, "plain.mp4");
223 assert_eq!(rows[0].detail, "");
224 }
225
226 // A second stream *placed* on the timeline is a source entry of its
227 // own: it keeps its row, no duplicate appears for it, and the rows of
228 // one file stay together whatever order the entries came in.
229 let placed = [
230 source("/m/movie.mp4", 0),
231 source("/m/other.mp4", 0),
232 source("/m/movie.mp4", 2),
233 ];
234 streams.insert(
235 PathBuf::from("/m/other.mp4"),
236 vec![info(0, 44_100, 2, None, true)],
237 );
238 let rows = library_rows(
239 &placed,
240 &streams,
241 &HashMap::new(),
242 Some((44_100, 2)),
243 |_| 90,
244 );
245 assert_eq!(
246 rows.iter()
247 .map(|r| (file_name(&r.path), r.stream))
248 .collect::<Vec<_>>(),
249 [
250 ("movie.mp4".to_string(), 0),
251 ("other.mp4".to_string(), 0),
252 ("movie.mp4".to_string(), 2),
253 ("movie.mp4".to_string(), 1),
254 ("movie.mp4".to_string(), 3),
255 ]
256 );
257 assert!(
258 rows[2].unusable.is_none(),
259 "a stream already on the timeline is playing, whatever a probe says"
260 );
261 assert_eq!(rows[1].tint, 1, "the other file is the other tint");
262}
263
264/// A file the decoder refuses says so on its own row, in the decoder's own
265/// words. The refusal is the only thing a person can act on for a file that
266/// will not play, and before this the row drew an empty second line -- the
267/// same line a song draws, which claims nothing and means nothing.
268///
269/// Dumped through the real [`engine::decode::probe`], not a hand-written
270/// `Err`: a `.mkv` that is not a container is refused by the demuxer, with no
271/// plugin and no hardware involved, so the words under test are the ones the
272/// engine really produces.
273#[test]
274fn a_refused_file_names_the_refusal_on_its_row() {
275 let junk = std::env::temp_dir().join(format!("edith-lane-j-refused-{}.mkv", std::process::id()));
276 std::fs::write(&junk, b"not a container, and never will be").expect("write the junk file");
277 let words = engine::decode::probe(&junk)
278 .expect_err("a file that is not a stream is refused")
279 .to_string();
280 assert!(
281 !words.is_empty(),
282 "a refusal that says nothing says nothing"
283 );
284
285 let mut decoders = HashMap::new();
286 decoders.insert(junk.clone(), Decoder::from(engine::decode::probe(&junk)));
287 let rows = library_rows(
288 &[Source {
289 path: junk.clone(),
290 audio_stream: 0, ..Default::default()
291 }],
292 &HashMap::new(),
293 &decoders,
294 None,
295 |_| 0,
296 );
297 assert_eq!(
298 rows[0].detail, words,
299 "the row carries the refusal verbatim"
300 );
301
302 // A probe still running says nothing, and must keep saying nothing: an
303 // empty second line is a real answer here, not a missing one.
304 let mut pending = HashMap::new();
305 pending.insert(junk.clone(), Decoder::Pending);
306 let rows = library_rows(
307 &[Source {
308 path: junk.clone(),
309 audio_stream: 0, ..Default::default()
310 }],
311 &HashMap::new(),
312 &pending,
313 None,
314 |_| 0,
315 );
316 assert_eq!(rows[0].detail, "", "an unasked decoder claims nothing");
317
318 std::fs::remove_file(&junk).ok();
319}
320
321/// What the clip menu offers, and where it hangs. The two items that act on
322/// the playhead rather than on the clicked clip are the ones that can be
323/// inapplicable, and a menu at the edge of the window has to come back inside
324/// it or its last item cannot be clicked at all.
325///
326/// A caption's own menu, opened on a box that is not a clip: the rows that act
327/// on it -- Delete, which routes to `Player::lift_sub`, and the group pair now
328/// that a caption may be grouped by hand -- the timeline's global items beside
329/// them, and nothing else drawn at all. What a placed subtitle used to have no
330/// menu, and no stroke, to do.
331#[test]
332fn a_caption_is_deleted_by_the_same_row_and_stroke_every_box_is() {
333 use keymap::ActionId;
334 // A subtitle lane holds no `Clip`, so this is what the player reads off a
335 // right-clicked caption: nothing in the clip index space, and `caption`.
336 let cap = Ctx {
337 caption: true,
338 timeline: true,
339 ..Ctx::default()
340 };
341 assert!(cap.clip.is_none(), "a caption is never a clip");
342 assert_eq!(
343 enable(ActionId::Delete, cap.clone()),
344 Enable::Yes,
345 "the one thing a placed caption could always be asked to do",
346 );
347 // The clip rows are refusals of *kind* on a caption, so the menu leaves
348 // them out rather than drawing "nothing selected" over a clicked box.
349 for clip_only in [ActionId::Copy, ActionId::Lift, ActionId::Equalizer] {
350 assert_eq!(
351 enable(clip_only, cap.clone()),
352 Enable::Hidden("this is a caption"),
353 "{clip_only:?} is not a row on a caption",
354 );
355 }
356 // The group rows are the caption's now: a caption out of any group says so
357 // in the detach's own words, and Group over one pick is the partner hunt.
358 assert_eq!(
359 enable(ActionId::Detach, cap.clone()),
360 Enable::No("this caption is not grouped")
361 );
362 assert_eq!(enable(ActionId::Group, cap.clone()), Enable::Yes);
363 // ...and a caption in a group detaches like a clip does.
364 let grouped = Ctx {
365 caption: true,
366 caption_link: Some(3),
367 timeline: true,
368 ..Ctx::default()
369 };
370 assert_eq!(enable(ActionId::Detach, grouped), Enable::Yes);
371 // ...and the playhead's actions are *not* refusals: the split and the
372 // regroup act at the line and the cards fall back to the clip under it, so
373 // a caption in hand is no reason for them to go dead -- which, hidden, is
374 // exactly what they went: `Player::act` returns without a word on `Hidden`,
375 // and no click on the bed clears the mark that put them there.
376 for playhead in [
377 ActionId::Cut,
378 ActionId::Regroup,
379 ActionId::Color,
380 ActionId::Speed,
381 ActionId::Fit,
382 ActionId::Silence,
383 ] {
384 assert_eq!(
385 enable(playhead, cap.clone()),
386 Enable::Yes,
387 "{playhead:?} is about the playhead and not about the mark",
388 );
389 }
390 // ...but live is not *listed*: every one of those rows reaches the clip
391 // under the playhead and not the caption, and a menu opened on a caption
392 // that offered a grade would read as the caption's. The caption's menu is
393 // its own rows and the global pair the card already names as global.
394 assert_eq!(
395 menu_items(cap.clone()),
396 vec![
397 ActionId::Paste,
398 ActionId::Group,
399 ActionId::Detach,
400 // Below the rule line the render draws before it, like every
401 // other row that takes something away (DESIGN §9).
402 ActionId::Delete,
403 ],
404 "the caption's menu is its removal, the group pair, and paste",
405 );
406 // ...and the same reading with a clip under it is the clip menu, untouched:
407 // the flag is off wherever a `Clip` was clicked.
408 assert!(
409 menu_items(Ctx {
410 timeline: true,
411 ..Ctx::default()
412 })
413 .contains(&ActionId::Cut)
414 );
415}
416
417/// A timeline with a subtitle palette and an empty subtitle lane: what a
418/// caption is placed on, at the fixture's own rate.
419fn with_subtitle_lane() -> (PlaybackSession, Lane) {
420 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
421 session.set_gain(0.0);
422 subtitle_notice(&mut session, &asset("test_subs.mkv")).expect("the mkv carries subtitles");
423 let lane = session.add_lane(LaneKind::Subtitle);
424 (session, lane)
425}
426
427/// A second of palette track 0, to be placed wherever the test drops it.
428fn one_second(start: u32) -> SubClip {
429 SubClip {
430 start,
431 frames: 30,
432 track: 0,
433 in_us: 0,
434 out_us: 1_000_000,
435 link: None,
436 }
437}
438
439/// A drop the engine *refuses* moves nothing -- so it must move no mark either.
440/// A drag towards the left edge saturates to frame 0 (`landing`), and reading
441/// the mark back off the frame the drop asked for handed it to whatever caption
442/// already covered frame 0: the next Delete then lifted a caption the hand never
443/// touched. The mark stays on the caption that did not move.
444#[test]
445fn a_refused_caption_drop_leaves_the_mark_where_it_was() {
446 use crate::sub_mark;
447 let (mut session, lane) = with_subtitle_lane();
448 session
449 .place_sub(lane, 0, one_second(0))
450 .expect("A goes down");
451 session
452 .place_sub(lane, 60, one_second(0))
453 .expect("B goes down after it");
454 let before = session.sub_lane(lane).to_vec();
455 // The mark is on B, the caption in hand: index 1 of the lane.
456 assert_eq!(sub_mark(session.sub_lane(lane), 60), Some(1));
457
458 let err = session
459 .move_sub(lane, 1, lane, 0)
460 .expect_err("A already covers frame 0");
461 assert!(err.to_string().contains("already covers"), "{err}");
462 assert_eq!(session.sub_lane(lane), before, "a refusal moved nothing");
463 // The trap this pins: the frame the drop *asked* for names A, so the old
464 // re-read marked A -- the caption nobody dragged -- and `x` lifted it.
465 assert_eq!(
466 sub_mark(session.sub_lane(lane), 0),
467 Some(0),
468 "frame 0 is A's, which is why a refused drop must not re-read the mark",
469 );
470 // Nothing was renumbered, so B is still index 1 and still the marked one.
471 assert_eq!(sub_mark(session.sub_lane(lane), 60), Some(1));
472}
473
474/// A lane inserts its captions in start order (`Project::place_sub`), so one
475/// placed *before* the marked caption slides it one along: the mark left on its
476/// old index would name the caption that just arrived, and `x` would lift that
477/// one instead. The mark is kept by the caption's start frame, which is its name
478/// on its lane, so it follows the caption it was on.
479#[test]
480fn a_caption_placed_before_the_marked_one_leaves_the_mark_on_the_original() {
481 use crate::sub_mark;
482 let (mut session, lane) = with_subtitle_lane();
483 session
484 .place_sub(lane, 100, one_second(0))
485 .expect("A goes down");
486 let marked = session.sub_lane(lane)[0].start;
487 assert_eq!(sub_mark(session.sub_lane(lane), marked), Some(0));
488
489 session
490 .place_sub(lane, 0, one_second(0))
491 .expect("the new one goes down before it");
492 assert_eq!(
493 session
494 .sub_lane(lane)
495 .iter()
496 .map(|s| s.start)
497 .collect::<Vec<_>>(),
498 [0, 100],
499 "the lane holds them in start order",
500 );
501 // What the player does with the mark across that placement.
502 let mark = sub_mark(session.sub_lane(lane), marked).expect("A is still there");
503 assert_eq!(mark, 1, "A slid one along and the mark went with it");
504
505 // ...and the Delete that stroke reaches takes A, not the caption that
506 // arrived: `Player::delete_selected` routes a caption's mark to `lift_sub`.
507 assert!(session.lift_sub(lane, mark));
508 assert_eq!(
509 session
510 .sub_lane(lane)
511 .iter()
512 .map(|s| s.start)
513 .collect::<Vec<_>>(),
514 [0],
515 "the caption the user marked is the one that died",
516 );
517}
518
519/// A caption a hand grouped with a clip pairs it for the whole-take question:
520/// deleting the picture takes the group, because the group -- not the lane's
521/// kind -- is what pairs. The engine door is the one the menu's Group row
522/// reaches (`group_all`), tested here from the selection's own side of it.
523#[test]
524fn a_caption_grouped_with_a_clip_pairs_it_for_the_whole_take_question() {
525 let (mut session, lane) = with_subtitle_lane();
526 session
527 .place_sub(lane, 0, one_second(0))
528 .expect("the caption goes down");
529 session
530 .group_all(&[(Lane::V1, 0), (lane, 0)])
531 .expect("a clip and a caption are a group");
532 // Paired through the caption it was grouped with, and the question is the
533 // picture's to answer.
534 assert!(
535 whole_take(&session, Lane::V1, 0),
536 "the caption the clip was grouped with pairs it"
537 );
538 // ...and the ungroup keeps the picture with its take: the caption comes
539 // off, the clip stays linked to what it was grouped with.
540 assert!(session.ungroup(lane, 0));
541 assert!(
542 whole_take(&session, Lane::V1, 0),
543 "ungrouped, the clip stays linked: the take stays linked"
544 );
545}
546
547/// An ungrouped clip on a further lane (ord >= 1) is a layer, not a take: it
548/// sits over the timeline rather than in it, so deleting it lifts a hole
549/// rather than rippling one closed. Pins the `(_, 1..) => false` arm
550/// `whole_take` answers before it ever reaches the video/audio arms below.
551#[test]
552fn an_ungrouped_clip_on_a_further_lane_is_a_layer_not_a_take() {
553 use engine::project::LaneKind;
554
555 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
556 session.set_gain(0.0);
557 let v2 = session.add_lane(LaneKind::Video);
558 assert!(session.move_clip_to(Lane::V1, 0, v2, 0), "V1 -> V2");
559 // Its old pairing with A1 came along with the move -- detach it, an
560 // ungrouped clip is exactly the case this arm is for.
561 assert!(session.ungroup(v2, 0));
562 assert!(
563 !whole_take(&session, v2, 0),
564 "an ungrouped clip on ord >= 1 is a layer, not a take"
565 );
566 // ...and its delete lifts, leaving the hole under it open: the take
567 // beneath (there is none here, but the lane) is untouched.
568 assert!(session.lift_clip(v2, 0));
569 assert!(session.lane_clips(v2).is_empty());
570}
571
572/// A caption anchor names the media half of its group: the video member for
573/// the cards that are about the picture, the audio member for the ones about
574/// the sound. A caption in no group names nothing -- which is what the cards'
575/// new refusals say out loud.
576#[test]
577fn a_caption_anchor_names_the_media_half_of_its_group() {
578 use crate::caption_media_half;
579
580 let (mut session, lane) = with_subtitle_lane();
581 session
582 .place_sub(lane, 0, one_second(0))
583 .expect("the caption goes down");
584 // Ungrouped: no pictures and no sound behind the words.
585 assert_eq!(
586 caption_media_half(&session, (lane, 0), LaneKind::Video),
587 None
588 );
589 assert_eq!(
590 caption_media_half(&session, (lane, 0), LaneKind::Audio),
591 None
592 );
593 // Grouped with the take -- whose sound rides along unasked -- both halves
594 // answer by lane and index.
595 session
596 .group_all(&[(Lane::V1, 0), (lane, 0)])
597 .expect("a clip and a caption are a group");
598 assert_eq!(
599 caption_media_half(&session, (lane, 0), LaneKind::Video),
600 Some((Lane::V1, 0))
601 );
602 assert_eq!(
603 caption_media_half(&session, (lane, 0), LaneKind::Audio),
604 Some((Lane::A1, 0))
605 );
606}
607
608/// The manual group's oracle question: a selection of placements, one per lane.
609/// Two picks on two lanes is a group waiting to happen; a lane picked twice is
610/// the one thing a group may never hold; a single pick is the partner hunt.
611#[test]
612fn group_is_live_over_a_multi_selection_and_words_a_repeated_lane() {
613 use keymap::ActionId;
614 let distinct = Ctx {
615 timeline: true,
616 picks: 2,
617 pick_lanes: 2,
618 ..Ctx::default()
619 };
620 assert_eq!(enable(ActionId::Group, distinct), Enable::Yes);
621 let twice = Ctx {
622 timeline: true,
623 picks: 2,
624 pick_lanes: 1,
625 ..Ctx::default()
626 };
627 assert_eq!(
628 enable(ActionId::Group, twice),
629 Enable::No("a lane is picked twice")
630 );
631 // One pick and none at all: the partner hunt and its own refusal, which
632 // the player words rather than the oracle.
633 let one = Ctx {
634 timeline: true,
635 picks: 1,
636 pick_lanes: 1,
637 ..Ctx::default()
638 };
639 assert_eq!(enable(ActionId::Group, one), Enable::Yes);
640 // Nothing picked at all, on an open timeline: the partner hunt's own
641 // refusal, worded by the player rather than the oracle.
642 let none = Ctx {
643 timeline: true,
644 ..Ctx::default()
645 };
646 assert_eq!(enable(ActionId::Group, none), Enable::Yes);
647 // Stale picks (an edit moved the indices) count as none.
648 let stale = Ctx {
649 timeline: true,
650 picks: 0,
651 pick_lanes: 0,
652 ..Ctx::default()
653 };
654 assert_eq!(enable(ActionId::Group, stale), Enable::Yes);
655}
656
657/// The playhead's actions with a caption marked: live, and doing what they say.
658/// Hidden, they were dead *and* silent -- `Player::act` says nothing on a class
659/// refusal -- from the first click on a caption until something else was
660/// clicked, and no click on the bed clears that mark.
661#[test]
662fn the_playhead_actions_still_work_with_a_caption_marked() {
663 use keymap::ActionId;
664 let cap = Ctx {
665 caption: true,
666 timeline: true,
667 ..Ctx::default()
668 };
669 assert_eq!(enable(ActionId::Cut, cap.clone()), Enable::Yes);
670 assert_eq!(enable(ActionId::Regroup, cap.clone()), Enable::Yes);
671
672 // And the edits themselves, on a timeline holding a placed caption: the
673 // split at the playhead and the rejoin at the seam it leaves.
674 let (mut session, lane) = with_subtitle_lane();
675 session
676 .place_sub(lane, 0, one_second(0))
677 .expect("it goes down");
678 let clips = session.lane_clips(Lane::V1).len();
679 assert!(session.cut_at(2.0), "the playhead splits the clip under it");
680 assert_eq!(session.lane_clips(Lane::V1).len(), clips + 1);
681 // The refusal is a real state and not a defence against nothing: the
682 // playhead is standing on the seam the split just left, which is exactly the
683 // stroke `Player::cut` words as "Nothing to split — the playhead is already
684 // on a cut".
685 assert!(
686 !session.cut_at(2.0),
687 "a second split on the seam is refused, which is the state the door's \
688 selection gate is about"
689 );
690 assert_eq!(
691 session.lane_clips(Lane::V1).len(),
692 clips + 1,
693 "and adds none"
694 );
695 assert!(session.regroup_at(2.0), "and the seam rejoins");
696 assert_eq!(session.lane_clips(Lane::V1).len(), clips);
697 assert_eq!(session.sub_lane(lane).len(), 1, "the caption is untouched");
698}
699
700#[test]
701fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() {
702 use keymap::{ActionId, Keymap};
703 // Frames 30..90 of the timeline, taken from the head of its source.
704 let clip = Clip {
705 speed_keys: Vec::new(),
706 reversed: false,
707 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
708 angle: Default::default(),
709 fade_in: 0,
710 fade_out: 0,
711 transition_out: 0,
712 transition_kind: Default::default(),
713 visualizer: 0,
714 viz_paint: 0,
715 gain_db: 0.0,
716 gain_keys: Vec::new(),
717 pan: 0,
718 pitch: 0.0,
719 transform_keys: Vec::new(),
720 opacity_keys: Vec::new(),
721 color_keys: Vec::new(),
722 effects: Vec::new(),
723 start: 30,
724 in_frame: 0,
725 out_frame: 60,
726 source: 0,
727 link: None,
728 eq: None,
729 color: None,
730 transform: None,
731 fit: FitPolicy::default(),
732 speed: Speed::NORMAL,
733 };
734 assert_eq!(clip.end(), 90);
735 let a1 = Lane::A1;
736 let v1 = Lane::V1;
737 // The question the clip menu asks: a timeline is open and the menu was
738 // opened on this clip, at this playhead.
739 let on = |clip: &Clip, lane, action, playhead| {
740 enable(
741 action,
742 Ctx {
743 clip: Some((clip.clone(), lane)),
744 playhead,
745 timeline: true,
746 ..Ctx::default()
747 },
748 )
749 };
750 let offered = |clip: &Clip, lane, action, playhead| on(clip, lane, action, playhead).yes();
751 // Cut splits from inside only: neither edge has anything to split off.
752 assert!(offered(&clip, v1, ActionId::Cut, 31));
753 assert!(offered(&clip, v1, ActionId::Cut, 89));
754 assert!(!offered(&clip, v1, ActionId::Cut, 30));
755 assert!(!offered(&clip, v1, ActionId::Cut, 90));
756 assert!(!offered(&clip, v1, ActionId::Cut, 200));
757 // A slowed clip refuses more than the edges do, and it may not say the
758 // edges' words while doing it: at a quarter speed each of its sixty
759 // source frames is on screen four timeline frames, and only the first of
760 // the four is a frame the file has. The three between are inside the
761 // clip by any reading of the playhead, so "only from inside a clip"
762 // there is a refusal claiming something the screen contradicts.
763 let slow = Clip {
764 fade_in: 0,
765 fade_out: 0,
766 speed: Speed::MIN,
767 ..clip.clone()
768 };
769 assert_eq!(slow.frames(), 240, "a quarter speed is four times as long");
770 assert!(
771 offered(&slow, v1, ActionId::Cut, 34),
772 "34 is a source frame"
773 );
774 assert!(!offered(&slow, v1, ActionId::Cut, 35));
775 assert_eq!(
776 on(&slow, v1, ActionId::Cut, 35).why(),
777 Some("this speed holds one frame here"),
778 );
779 assert_eq!(
780 on(&slow, v1, ActionId::Cut, 30).why(),
781 Some("only from inside a clip"),
782 "the head is still the edge's refusal, speed or no speed",
783 );
784 // Regroup is the other way round: only where this clip meets another.
785 assert!(offered(&clip, v1, ActionId::Regroup, 30));
786 assert!(offered(&clip, v1, ActionId::Regroup, 90));
787 assert!(!offered(&clip, v1, ActionId::Regroup, 60));
788 // Detach is the clip's own business: nothing to take apart in one that
789 // names no group, and whether the group still has another half is the
790 // engine's question. Group is offered on every clip, for that reason.
791 assert!(!offered(&clip, v1, ActionId::Detach, 0));
792 let grouped = Clip {
793 fade_in: 0,
794 fade_out: 0,
795 link: Some(3),
796 ..clip.clone()
797 };
798 assert!(offered(&grouped, v1, ActionId::Detach, 60));
799 assert!(offered(&clip, a1, ActionId::Group, 0));
800 // The equalizer is the one item the *lane* decides: it filters samples,
801 // and a video clip has none of its own. Never the playhead's business.
802 assert!(offered(&clip, a1, ActionId::Equalizer, 0));
803 assert!(offered(&clip, a1, ActionId::Equalizer, 60));
804 assert!(!offered(&clip, v1, ActionId::Equalizer, 60));
805 // The rest act on the clip that was clicked, so they always mean
806 // something -- the engine words its own refusals.
807 for action in [ActionId::Delete, ActionId::Lift, ActionId::ToggleMute] {
808 assert!(offered(&clip, v1, action, 0));
809 assert!(offered(&clip, a1, action, 60));
810 }
811 // Except the grade, which is a picture setting: offered on a video
812 // clip wherever the playhead is, dimmed on a waveform.
813 assert!(offered(&clip, v1, ActionId::Color, 0));
814 assert!(!offered(&clip, a1, ActionId::Color, 60));
815 // The transition kinds are the dissolve's family: picture only, so the
816 // palette offers all sixteen over a picture clip and none over a waveform.
817 for action in ActionId::ALL.into_iter().filter(|a| a.transition_kind().is_some()) {
818 assert!(offered(&clip, v1, action, 0), "{action:?} on picture");
819 assert!(!offered(&clip, a1, action, 60), "{action:?} on sound");
820 }
821 // The two kinds of no, which is what the row is told apart by: a grade
822 // on a waveform is a *class* answer -- an audio clip has no picture and
823 // never will, so the menu leaves the item out entirely -- where a cut at
824 // the clip's edge is this moment's answer and the next click of the
825 // playhead changes it, so that one is drawn, dimmed, and says why.
826 //
827 // What the menu draws for a clip of each kind, in order: the render
828 // loop's `continue`, as a list.
829 let menu = |lane, image, playhead| {
830 MENU_ITEMS
831 .into_iter()
832 .filter(|&action| {
833 enable(
834 action,
835 Ctx {
836 clip: Some((clip.clone(), lane)),
837 image,
838 playhead,
839 timeline: true,
840 ..Ctx::default()
841 },
842 )
843 .listed()
844 })
845 .collect::<Vec<_>>()
846 };
847 // Sound: no grade and no fit policy, and the equalizer that is the
848 // whole reason an audio clip has a menu of its own.
849 let sound = menu(a1, false, 60);
850 assert!(!sound.contains(&ActionId::Color), "{sound:?}");
851 assert!(!sound.contains(&ActionId::Fit), "{sound:?}");
852 assert!(!sound.contains(&ActionId::Reframe), "a sound clip has no subject to follow: {sound:?}");
853 assert!(sound.contains(&ActionId::Equalizer));
854 assert!(sound.contains(&ActionId::Silence));
855 assert!(sound.contains(&ActionId::Visualizer));
856 // Either half of a take reverses the take.
857 assert!(sound.contains(&ActionId::Reverse), "{sound:?}");
858 // Picture: the mirror of it. The sound of a take is the audio lane's,
859 // clip for clip, so the equalizer is not this clip's business -- but the
860 // silence scan is, because it opens on the half it is grouped with.
861 let picture = menu(v1, false, 60);
862 assert!(!picture.contains(&ActionId::Equalizer), "{picture:?}");
863 assert!(picture.contains(&ActionId::Visualizer), "{picture:?}");
864 assert!(picture.contains(&ActionId::Color));
865 assert!(picture.contains(&ActionId::Fit));
866 assert!(picture.contains(&ActionId::Reframe), "{picture:?}");
867 assert!(picture.contains(&ActionId::Silence));
868 assert!(picture.contains(&ActionId::Reverse), "{picture:?}");
869 // A still: picture with no sound anywhere, ever. Graded, fitted and
870 // re-timed like any other clip (a speed reaches a still through the same
871 // rewrite), scanned like none.
872 let still = menu(v1, true, 60);
873 assert!(!still.contains(&ActionId::Silence), "{still:?}");
874 assert!(!still.contains(&ActionId::Visualizer), "{still:?}");
875 assert!(!still.contains(&ActionId::Equalizer), "{still:?}");
876 assert!(!still.contains(&ActionId::Reframe), "a still has no motion to follow: {still:?}");
877 assert!(still.contains(&ActionId::Color));
878 assert!(still.contains(&ActionId::Fit));
879 assert!(still.contains(&ActionId::Speed));
880 assert!(!still.contains(&ActionId::Reverse), "a still has no footage to reverse: {still:?}");
881 // Mix is not in the clip menu, but it wears the same class refusal the
882 // dock's verb row hides it by (`ui::dock_stance::ghost_verb`): nothing to
883 // mix for a picture with no sound at all, live everywhere else.
884 let mix_ctx = |lane, image| Ctx {
885 clip: Some((clip.clone(), lane)),
886 image,
887 playhead: 60,
888 timeline: true,
889 ..Ctx::default()
890 };
891 assert!(!enable(ActionId::Mix, mix_ctx(v1, true)).listed());
892 assert!(enable(ActionId::Mix, mix_ctx(v1, false)).listed());
893 assert!(enable(ActionId::Mix, mix_ctx(a1, false)).listed());
894 // A silent video (no still, but its source's stream table is empty)
895 // refuses Mix and Silence the same way, by `no_sound` rather than `image`.
896 let mute_video = Ctx {
897 clip: Some((clip.clone(), v1)),
898 no_sound: true,
899 playhead: 60,
900 timeline: true,
901 ..Ctx::default()
902 };
903 assert!(!enable(ActionId::Mix, mute_video.clone()).listed());
904 assert!(!enable(ActionId::Silence, mute_video).listed());
905 // ...and the state refusals are on all three, dimmed rather than gone:
906 // at 30 the playhead is on this clip's head, where a cut has nothing to
907 // split off -- a row the next click of the playhead lights.
908 for rows in [menu(a1, false, 30), menu(v1, false, 30), menu(v1, true, 30)] {
909 assert!(rows.contains(&ActionId::Cut), "{rows:?}");
910 }
911 // The actions card is the other half of the rule: it lists the whole
912 // registry, so a class refusal is dimmed there with its reason and never
913 // dropped -- an action missing from the one surface that lists
914 // everything would read as an action that does not exist.
915 let listed: Vec<ActionId> = keys_rows()
916 .into_iter()
917 .filter_map(|r| match r {
918 KeyRow::Act(action) => Some(action),
919 _ => None,
920 })
921 .collect();
922 for (lane, action) in [
923 (a1, ActionId::Color),
924 (a1, ActionId::Fit),
925 (v1, ActionId::Equalizer),
926 ] {
927 assert!(matches!(on(&clip, lane, action, 60), Enable::Hidden(_)));
928 assert!(listed.contains(&action), "{action:?} left the actions card");
929 assert!(on(&clip, lane, action, 60).why().is_some());
930 }
931 assert!(matches!(on(&clip, v1, ActionId::Cut, 30), Enable::No(_)));
932 assert!(matches!(
933 on(&clip, v1, ActionId::Regroup, 60),
934 Enable::No(_)
935 ));
936 assert!(matches!(on(&clip, v1, ActionId::Detach, 0), Enable::No(_)));
937 // Every refusal says something, and says it short enough to sit in the
938 // menu's right-hand column beside a label -- the still's included, which
939 // the card dims with while the menu leaves the row out.
940 for action in MENU_ITEMS {
941 for (lane, image) in [(v1, false), (a1, false), (v1, true)] {
942 for playhead in [0, 30, 60, 90] {
943 let refusal = enable(
944 action,
945 Ctx {
946 clip: Some((clip.clone(), lane)),
947 image,
948 playhead,
949 timeline: true,
950 ..Ctx::default()
951 },
952 );
953 if let Some(why) = refusal.why() {
954 assert!(!why.is_empty() && why.len() <= 30, "{action:?}: {why:?}");
955 }
956 }
957 }
958 }
959 assert!(matches!(
960 enable(
961 ActionId::Silence,
962 Ctx {
963 clip: Some((clip.clone(), v1)),
964 image: true,
965 playhead: 60,
966 timeline: true,
967 ..Ctx::default()
968 }
969 ),
970 Enable::Hidden(_)
971 ));
972 // A video clip the probed stream table says has no audio track at all --
973 // the row is hidden rather than offered and refused after a scan comes
974 // back with nothing to report (`Player::start_silence_scan`'s `Ok(None)`).
975 assert!(matches!(
976 enable(
977 ActionId::Silence,
978 Ctx {
979 clip: Some((clip, v1)),
980 no_sound: true,
981 playhead: 60,
982 timeline: true,
983 ..Ctx::default()
984 }
985 ),
986 Enable::Hidden(_)
987 ));
988 // The editor as a whole, which is how the actions card asks: with no
989 // timeline nothing is offered, an export leaves only its own cancel,
990 // and the three that act on the marked clip say so when none is.
991 let whole = |action, ctx| enable(action, ctx);
992 assert_eq!(
993 whole(ActionId::Play, Ctx::default()),
994 Enable::No("no timeline open")
995 );
996 let live = Ctx {
997 timeline: true,
998 playable: true,
999 ..Ctx::default()
1000 };
1001 assert!(whole(ActionId::Play, live.clone()).yes());
1002 // ...and an open timeline with nothing on its lanes refuses the
1003 // transport in the oracle rather than in the button, which is what
1004 // makes the key and the button say the same thing.
1005 assert_eq!(
1006 whole(
1007 ActionId::Play,
1008 Ctx {
1009 playable: false,
1010 ..live.clone()
1011 }
1012 ),
1013 Enable::No("the timeline is empty")
1014 );
1015 // The magnet and the monitoring level are the editor's own and answer
1016 // with no timeline at all -- the keyboard always fired them there, and
1017 // now so does the toolbar.
1018 //
1019 // ...and so do the two stand-in switches, which is not a nicety: they are
1020 // *import* options -- what an arriving film gets made for it, and what its
1021 // picture is then decoded from -- so a person answers them before the first
1022 // file, and a switch that waited for one was a switch that came too late to
1023 // stop the encode it was about.
1024 // ...and so do the project settings: they decide what the next file
1025 // scaffolds as (`pending_settings`), so a gate that waited for a timeline
1026 // refused them exactly when they mean the most.
1027 for editor_wide in [
1028 ActionId::ToggleSnap,
1029 ActionId::ToggleMute,
1030 ActionId::VolumeUp,
1031 ActionId::VolumeDown,
1032 ActionId::ToggleProxies,
1033 ActionId::ToggleAutoProxies,
1034 ActionId::Resolution,
1035 ] {
1036 assert!(
1037 whole(editor_wide, Ctx::default()).yes(),
1038 "{editor_wide:?} is dead with no file open while its key still fires"
1039 );
1040 }
1041 assert!(!whole(ActionId::Delete, live.clone()).yes());
1042 assert!(!whole(ActionId::Paste, live.clone()).yes());
1043 assert!(
1044 whole(
1045 ActionId::Paste,
1046 Ctx {
1047 clipboard: true,
1048 ..live.clone()
1049 }
1050 )
1051 .yes()
1052 );
1053 assert!(!whole(ActionId::CancelExport, live.clone()).yes());
1054 let busy = Ctx {
1055 exporting: true,
1056 ..live.clone()
1057 };
1058 assert!(whole(ActionId::CancelExport, busy.clone()).yes());
1059 for action in ActionId::ALL {
1060 // Nothing may touch the edit list while an export is reading it --
1061 // and the palette does not: it repaints this window and writes one
1062 // word to the user's own config file, which is why it is one of the
1063 // actions besides the cancel that stay live here. Fullscreen is the
1064 // same kind of thing: the platform's own window toggle, touching no
1065 // edit list either. Settings is NOT among them, on purpose: it opens
1066 // the same modal slot the exporting card is already standing in
1067 // (`Player::open_settings`), so a permission granted here would be
1068 // one nobody could ever act on -- driven and confirmed: both the `,`
1069 // chord and the spine glyph leave the exporting card on screen.
1070 let allowed = action == ActionId::CancelExport
1071 || action == ActionId::Theme
1072 || action == ActionId::AccentColour
1073 || action == ActionId::ViewZoom
1074 || action == ActionId::PlaybackQuality
1075 || action == ActionId::GuideStyle
1076 || action == ActionId::GuideMask
1077 || action == ActionId::Fullscreen
1078 || action == ActionId::SubtitleStyle
1079 // Moving the ring touches no edit list either -- same kind of
1080 // thing as Fullscreen right above it.
1081 || action == ActionId::FocusPanels
1082 // The shortcuts sheet opens a dock tab and touches no edit list.
1083 || action == ActionId::ShowKeys
1084 || action == ActionId::About
1085 // The video output window and its display: a second window onto the picture.
1086 || action == ActionId::ToggleOutputWindow
1087 || action == ActionId::OutputDisplay;
1088 assert_eq!(
1089 whole(action, busy.clone()).yes(),
1090 allowed,
1091 "{action:?} while an export reads the edit list"
1092 );
1093 }
1094 // The playhead frame is the engine's own rule, boundary included.
1095 assert_eq!(frame_at(1.0, 30.), 30);
1096 assert_eq!(frame_at(0.0, 30.), 0);
1097 assert_eq!(frame_at(-1.0, 30.), 0);
1098 // Where it hangs: at the pointer when it fits, back inside when not.
1099 let viewport = size(px(800.), px(400.));
1100 assert_eq!(menu_at(point(px(10.), px(10.)), viewport, 150.), (10., 10.));
1101 assert_eq!(
1102 menu_at(point(px(700.), px(380.)), viewport, 150.),
1103 (
1104 800. - crate::layout::MENU_EDGE - MENU_W,
1105 400. - crate::layout::MENU_EDGE - 150.
1106 )
1107 );
1108 // A window smaller than the menu loses its bottom, never its top: the
1109 // top-left margin wins over the bottom-right one, because the items are
1110 // at the top.
1111 assert_eq!(
1112 menu_at(point(px(90.), px(40.)), size(px(100.), px(50.)), 150.),
1113 (crate::layout::MENU_EDGE, crate::layout::MENU_EDGE)
1114 );
1115 // Every item is an action the registry knows, so the menu and the keys
1116 // menu say the same thing about it -- and none of them is unreachable
1117 // by keyboard, which is what makes the hint column worth drawing.
1118 let keymap = Keymap::defaults();
1119 for action in MENU_ITEMS {
1120 assert!(ActionId::ALL.contains(&action), "{action:?} is not listed");
1121 // The Effects opener has a menu row and no stroke; the popup prints
1122 // no hint for a row without one.
1123 if !matches!(
1124 action,
1125 ActionId::Effects
1126 | ActionId::TrackMask
1127 | ActionId::Reframe
1128 | ActionId::NestClips
1129 | ActionId::BreakApart
1130 | ActionId::OpenCompound
1131 | ActionId::FlattenMulticam
1132 | ActionId::ClipLabel
1133 ) {
1134 assert_ne!(keymap.display(action), "unbound", "{action:?}");
1135 }
1136 }
1137 // ...and the whole card still fits the 640x360 floor, however many items
1138 // it grows to: the list is what scrolls where the window is too short
1139 // for it, never the card that grows.
1140 let items = MENU_ITEMS.len() + 1; // Properties
1141 let floor = size(px(640.), px(360.));
1142 assert!(
1143 MENU_PAD * 2. + menu_rows_h(items, floor) <= 360.,
1144 "too tall"
1145 );
1146 assert!(
1147 menu_rows_h(items, floor) / MENU_ROW_H >= 12.,
1148 "too few items visible to scan on the smallest window"
1149 );
1150 assert_eq!(
1151 menu_at(point(px(0.), px(0.)), floor, {
1152 MENU_PAD * 2. + menu_rows_h(items, floor)
1153 }),
1154 (crate::layout::MENU_EDGE, crate::layout::MENU_EDGE)
1155 );
1156 // The picker is the same card and the longest list in it is the palette
1157 // family list, which grows every time somebody asks for more colours.
1158 // Twelve of them still stand on screen *whole* at the floor -- so the
1159 // list's `overflow_y_scroll` is a safety net rather than something a
1160 // person has to find. The day a family makes this fail is the day the
1161 // card owes the affordance line the inspector and the cards carry
1162 // ("more below — scroll the …"): a row nobody knows is under the fold
1163 // is a row that is not there, and no scroll bar says it.
1164 let families = crate::ui::theme::PaletteId::ALL.len();
1165 // With 28px rows (REDESIGN §3.1) the floor shows all but a couple of them and the
1166 // list scrolls, as every menu does at that height.
1167 assert!(
1168 menu_rows_h(families, floor) >= 11. * MENU_ROW_H,
1169 "the picker shows fewer than eleven palettes at 640x360"
1170 );
1171 // ...and the detail beside each one is short enough to survive the
1172 // right-hand column at that width instead of being truncated mid-word.
1173 for id in crate::ui::theme::PaletteId::ALL {
1174 assert!(id.detail().len() <= 30, "{id:?}: {:?}", id.detail());
1175 }
1176}
1177
1178/// Both menus, at the two things they can be opened on, and the box each
1179/// one is drawn in. Two rules, and the render obeys them by *calling* what
1180/// this calls -- [`menu_items`] and [`row_items`] are the only lists either
1181/// menu is built from, and [`menu_rows_h`] is the height each is both placed
1182/// by and drawn to:
1183///
1184/// 1. a row exists only where the oracle lists the action for the very thing
1185/// that was right-clicked, so an item can never offer a video action on a
1186/// waveform (the complaint this comes from) and a new action added to
1187/// `MENU_ITEMS` cannot appear where it does not apply;
1188/// 2. the whole card is inside the window, wherever it was opened and
1189/// however long the list -- a menu drawn past the bottom edge is a menu
1190/// whose last items nobody can click.
1191#[test]
1192fn a_menu_offers_only_what_applies_and_is_drawn_inside_the_window() {
1193 use keymap::ActionId;
1194 let clip = Clip {
1195 speed_keys: Vec::new(),
1196 reversed: false,
1197 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
1198 angle: Default::default(),
1199 fade_in: 0,
1200 fade_out: 0,
1201 transition_out: 0,
1202 transition_kind: Default::default(),
1203 visualizer: 0,
1204 viz_paint: 0,
1205 gain_db: 0.0,
1206 gain_keys: Vec::new(),
1207 pan: 0,
1208 pitch: 0.0,
1209 transform_keys: Vec::new(),
1210 opacity_keys: Vec::new(),
1211 color_keys: Vec::new(),
1212 effects: Vec::new(),
1213 start: 30,
1214 in_frame: 0,
1215 out_frame: 60,
1216 source: 0,
1217 link: Some(1),
1218 eq: None,
1219 color: None,
1220 transform: None,
1221 fit: FitPolicy::default(),
1222 speed: Speed::NORMAL,
1223 };
1224 let ctx = |lane, image| Ctx {
1225 clip: Some((clip.clone(), lane)),
1226 image,
1227 playhead: 60,
1228 timeline: true,
1229 ..Ctx::default()
1230 };
1231 // The oracle is the whole of what the menu draws: every item it lists is
1232 // one the oracle would list, and every item it leaves out is one the
1233 // oracle hides -- there is no third answer, and no hand-written list.
1234 for (lane, image) in [(Lane::V1, false), (Lane::A1, false), (Lane::V1, true)] {
1235 let ctx = ctx(lane, image);
1236 let rows = menu_items(ctx.clone());
1237 for action in MENU_ITEMS {
1238 assert_eq!(
1239 rows.contains(&action),
1240 enable(action, ctx.clone()).listed(),
1241 "{action:?} on {lane:?}, image={image}"
1242 );
1243 }
1244 }
1245 // Sound has no picture settings; picture has no equalizer of its own; a
1246 // still has no sound to scan. The user's own words: an audio clip must
1247 // not be offered what only a picture can be given.
1248 let sound = menu_items(ctx(Lane::A1, false));
1249 assert!(!sound.contains(&ActionId::Color), "{sound:?}");
1250 assert!(!sound.contains(&ActionId::Fit), "{sound:?}");
1251 assert!(sound.contains(&ActionId::Equalizer));
1252 let picture = menu_items(ctx(Lane::V1, false));
1253 assert!(!picture.contains(&ActionId::Equalizer), "{picture:?}");
1254 assert!(picture.contains(&ActionId::Color));
1255 assert!(!menu_items(ctx(Lane::V1, true)).contains(&ActionId::Silence));
1256 // The library menu is the same rule on the other panel: its items come
1257 // off `row_items` and nothing else, and the two that change the timeline
1258 // say why rather than being clicked and refused afterwards.
1259 let live = RowCtx {
1260 timeline: true,
1261 usable: true,
1262 ..RowCtx::default()
1263 };
1264 for ctx in [
1265 live,
1266 RowCtx {
1267 usable: false,
1268 ..live
1269 },
1270 RowCtx { placed: 2, ..live },
1271 RowCtx {
1272 exporting: true,
1273 ..live
1274 },
1275 RowCtx::default(),
1276 ] {
1277 let rows = row_items(ctx);
1278 for item in ROW_ITEMS {
1279 assert_eq!(rows.contains(&item), row_enable(item, ctx).listed());
1280 }
1281 // Whatever the state, the two that need neither timeline nor edit
1282 // list are offered: a file is always describable and findable.
1283 assert!(row_enable(RowItem::Reveal, ctx).yes());
1284 assert!(row_enable(RowItem::Properties, ctx).yes());
1285 }
1286 assert!(row_enable(RowItem::Add, live).yes());
1287 assert!(
1288 !row_enable(
1289 RowItem::Add,
1290 RowCtx {
1291 usable: false,
1292 ..live
1293 }
1294 )
1295 .yes(),
1296 "a file that cannot join this timeline is not an Add anybody can ask for"
1297 );
1298 assert!(!row_enable(RowItem::Remove, RowCtx { placed: 1, ..live }).yes());
1299 // The two removes are both listed (DESIGN §6.7) and exactly one of them
1300 // answers yes: a placed source takes "with its clips", an unplaced one the
1301 // plain remove, and the other is refused with its reason rather than
1302 // hidden. Before this pair existed a placed source had no reachable way
1303 // out of the library at all (user 2026-08-21: "can not remove a media from
1304 // library").
1305 let placed = RowCtx { placed: 2, ..live };
1306 let items = row_items(placed);
1307 assert!(items.contains(&RowItem::RemoveWithClips) && items.contains(&RowItem::Remove));
1308 assert!(row_enable(RowItem::RemoveWithClips, placed).yes());
1309 assert!(!row_enable(RowItem::Remove, placed).yes());
1310 let unplaced = row_items(live);
1311 assert!(unplaced.contains(&RowItem::Remove) && unplaced.contains(&RowItem::RemoveWithClips));
1312 assert!(row_enable(RowItem::Remove, live).yes());
1313 assert_eq!(
1314 row_enable(RowItem::RemoveWithClips, live).why(),
1315 Some("no clip uses it")
1316 );
1317 assert!(
1318 !row_enable(
1319 RowItem::RemoveWithClips,
1320 RowCtx {
1321 exporting: true,
1322 ..placed
1323 }
1324 )
1325 .yes()
1326 );
1327 assert!(!row_enable(RowItem::Add, RowCtx::default()).yes());
1328 // Every refusal is short enough to sit in the hint column beside its
1329 // label, the clip menu's rule.
1330 for item in ROW_ITEMS {
1331 for ctx in [live, RowCtx::default()] {
1332 if let Some(why) = row_enable(item, ctx).why() {
1333 assert!(!why.is_empty() && why.len() <= 30, "{why:?}");
1334 }
1335 }
1336 }
1337 // ...and the box. Every window from the floor up, every corner of it,
1338 // and every list length either menu can have: the card is placed by
1339 // `MENU_PAD * 2 + menu_rows_h` and drawn to it, so this is the card.
1340 for viewport in [
1341 size(px(640.), px(360.)),
1342 size(px(800.), px(600.)),
1343 size(px(1280.), px(690.)),
1344 // Smaller than the floor the layout is sized for: it still may not
1345 // draw outside the window it has.
1346 size(px(320.), px(200.)),
1347 ] {
1348 for rows in 1..=MENU_ITEMS.len() + 1 {
1349 let h = MENU_PAD * 2. + menu_rows_h(rows, viewport);
1350 for at in [
1351 point(px(0.), px(0.)),
1352 point(px(10.), px(10.)),
1353 // The click that started all this: low in the window, where
1354 // the menu used to hang off the bottom edge.
1355 point(px(0.), viewport.height - px(4.)),
1356 point(viewport.width - px(4.), viewport.height - px(4.)),
1357 point(viewport.width * 2., viewport.height * 2.),
1358 ] {
1359 let (x, y) = menu_at(at, viewport, h);
1360 assert!(x >= 0. && y >= 0., "{x},{y} outside {viewport:?}");
1361 assert!(
1362 x + MENU_W <= f32::from(viewport.width) + 0.01,
1363 "{rows} rows at {at:?} hang off the right of {viewport:?}"
1364 );
1365 assert!(
1366 y + h <= f32::from(viewport.height) + 0.01,
1367 "{rows} rows at {at:?} hang off the bottom of {viewport:?}"
1368 );
1369 }
1370 }
1371 }
1372 // On any window with the room, the whole list is drawn rather than
1373 // twelve rows of it and a scroll nobody is told about.
1374 // The compound verbs fold into one "Compound" row and the card openers into one "Adjust"
1375 // row, so the top level counts each of those folds once.
1376 let items = MENU_ITEMS.iter().filter(|a| !crate::menus::compound_item(**a) && !crate::menus::adjust_item(**a)).count() + 2;
1377 let real = size(px(1280.), px(820.));
1378 assert_eq!(menu_rows_h(items, real), items as f32 * MENU_ROW_H);
1379 assert!(menu_rows_h(items, size(px(640.), px(360.))) < items as f32 * MENU_ROW_H);
1380}
1381
1382/// Defects 2 and 3 of the menu-placement lane, as source guards -- this binary
1383/// has no `VisualTestContext`, so where an element *mounts* and what its dim
1384/// column *says* are read off the source the way every other layout scan here
1385/// is.
1386///
1387/// 1. All three hanging menus mount on the room's ROOT. Mounted inside
1388/// `stance-centre` the clip menu's window-coordinate anchor was laid out
1389/// from the centre column's own origin and painted under the dock, which is
1390/// the "chords cut mid-word" the user photographed.
1391/// 2. The library menu hangs a row clear of the pointer, so it cannot cover the
1392/// row it is about.
1393/// 3. The library rows carry chords, not prose. DESIGN §4 puts the stroke in
1394/// that column and §8 forbids the instructional copy that used to sit there.
1395#[test]
1396fn the_hanging_menus_mount_at_the_room_root_and_their_rows_wear_chords_not_prose() {
1397 // Whitespace-collapsed, so the call still matches however rustfmt wraps it.
1398 let stance = src_text("ui/stance.rs")
1399 .split_whitespace()
1400 .collect::<Vec<_>>()
1401 .join(" ");
1402 let (centre, root) = stance
1403 .split_once(".child(divider( Split::Dock,")
1404 .expect("the dock seam splits the centre column from the room root");
1405 for menu in [
1406 "children(player.context_card(",
1407 "children(player.library_card(",
1408 "children(player.picker_card(",
1409 ] {
1410 assert!(
1411 root.contains(menu),
1412 "{menu} must mount after the dock, on the room root"
1413 );
1414 assert!(
1415 !centre.contains(menu),
1416 "{menu} mounted inside stance-centre paints under the dock"
1417 );
1418 }
1419 let library = src_text("ui/library.rs");
1420 assert!(
1421 library.contains("menu_at_w(at, viewport, pw, h)")
1422 && !library.contains("ROW_CLEAR"),
1423 "the library menu opens with its corner on the pointer, like every context menu"
1424 );
1425 // Two rows wear a chord: the add, which is the stroke `ui/stance.rs`'s
1426 // `enter` branch answers, and preview. Every other row's column is empty.
1427 for item in ROW_ITEMS {
1428 let hint = item.hint();
1429 match item {
1430 RowItem::Add => {
1431 assert_eq!(hint, "");
1432 }
1433 RowItem::Preview => assert_eq!(hint, "↵"),
1434 _ => assert!(hint.is_empty(), "{:?} prints prose: {hint:?}", item.label()),
1435 }
1436 // §9: no junk drawer. A label that fits the plate whole beside its
1437 // chord, and never a sentence.
1438 assert!(
1439 item.label().split_whitespace().count() <= 4,
1440 "{}",
1441 item.label()
1442 );
1443 }
1444 // The two removes must not read as the same verb now that the column
1445 // beside them is empty.
1446 assert_ne!(RowItem::Remove.label(), RowItem::RemoveWithClips.label());
1447 // The destructive rows are the tail of the list, under the one rule, and
1448 // the rule is the clip menu's seam token -- not a second hairline colour.
1449 let first = ROW_ITEMS.iter().position(|i| i.destructive()).unwrap();
1450 assert!(ROW_ITEMS[first..].iter().all(|i| i.destructive()));
1451 // The rule is the shared popup rule (the seam token lives in `ui/popup.rs`).
1452 assert!(library.contains("popup_rule()"));
1453 assert!(src_text("ui/popup.rs").contains("bg(rgba(crate::ui::theme::tokens().line))"));
1454 assert!(
1455 !library.contains("DARK_HAIRLINE"),
1456 "the Media menu's rule drifted from the clip menu's"
1457 );
1458}
1459
1460/// The other half of the keys menu's guarantee, and the audit this batch was
1461/// asked for kept as a test: no action may be a stroke and nothing else.
1462/// The actions card answers it for all of them at once -- its rows come off
1463/// [`ActionId::ALL`], so a fortieth action is on it the moment it exists and
1464/// there is no hand-written list here to fall behind.
1465#[test]
1466fn every_action_is_reachable_without_the_keyboard() {
1467 use keymap::ActionId;
1468 let source = ui_source();
1469 let source = source.as_str();
1470 let element = |id: &str| source.contains(&format!("\"{id}\""));
1471 let listed: Vec<ActionId> = keys_rows()
1472 .iter()
1473 .filter_map(|r| match r {
1474 KeyRow::Act(a) => Some(*a),
1475 _ => None,
1476 })
1477 .collect();
1478 for action in ActionId::ALL {
1479 // Angles 2 to 9 share the one "angle 1–9" row (see `keys_rows`).
1480 if action.angle_number().is_some_and(|n| n > 1) {
1481 continue;
1482 }
1483 assert_eq!(
1484 listed.iter().filter(|a| **a == action).count(),
1485 1,
1486 "{action:?} is reachable by keyboard only"
1487 );
1488 }
1489 assert_eq!(
1490 listed.iter().filter(|a| a.angle_number().is_some()).count(),
1491 1,
1492 "the angles are one row on the keys card"
1493 );
1494 // The snap's own door was the rail's `⌗` glyph, and the rail is deleted
1495 // (DESIGN §5 as amended 2026-09-09, user decision "option C"). Its
1496 // replacement landed with the ruler's right-click menu ([`BENCH_ITEMS`]),
1497 // which carries the snap with its state in the label. A menu row wears a
1498 // *generated* hitmap id (`menu.{action:?}`, overlays.rs), so the door is
1499 // asserted on the list the row is built from rather than on a literal id
1500 // no source file spells any more.
1501 assert!(
1502 BENCH_ITEMS.contains(&ActionId::ToggleSnap),
1503 "no pointer door for the snap"
1504 );
1505 // And the card is a door the pointer can open: the panel's own button.
1506 assert!(element("menubar-search"), "no way to open the command palette");
1507 // The card-local strokes have the same rule, and each of them is a thing
1508 // on its card: the graph and its two buttons, the colour bars and their
1509 // reset, the speed bar and its presets, and the silence card's threshold
1510 // bar and scope chips -- the bar is the pointer's only way to a threshold.
1511 for id in [
1512 "eq-graph",
1513 "eq-reset",
1514 "eq-spectrum",
1515 "color-bar",
1516 "color-reset",
1517 "speed-bar",
1518 "speed-preset",
1519 "speed-mode",
1520 "ramp-preset",
1521 "ramp-add-key",
1522 "ramp-key-remove",
1523 "ramp-key-step",
1524 "ramp-clear",
1525 "silence-threshold",
1526 "silence-scope",
1527 "mix-row",
1528 "eq-gain-field",
1529 "silence-apply",
1530 "export-confirm",
1531 ] {
1532 assert!(element(id), "{id} is not on any card");
1533 }
1534 // ...and each one is named by the row that carries its stroke, so a
1535 // card-local key added to `FIXED` with nothing to click fails here
1536 // instead of being noticed by whoever tries to use the card without a
1537 // keyboard. `KeyRow::Fixed` is "shown and never offered", which used to
1538 // mean the twenty-eight rows below were the one part of this editor no
1539 // reachability test read.
1540 for fixed in keymap::FIXED.iter() {
1541 match fixed.reach {
1542 keymap::Reach::Click(id) => assert!(
1543 element(id),
1544 "{:?} ({}) points at {id}, which is on no card",
1545 fixed.chord,
1546 fixed.label
1547 ),
1548 // Nothing to click by decision, not by omission: getting out of
1549 // a card, and the hold that repeats what a drag already does.
1550 keymap::Reach::Gesture => {}
1551 }
1552 }
1553}
1554
1555/// The other half of "getting out of a card is a `Reach::Gesture`": the
1556/// gesture has to exist. Every card's scrim closes it on a press, so a hand
1557/// that never touches the keyboard can shut every one of them -- for seven
1558/// cards `esc` was the only exit, which is the same complaint as an action
1559/// reachable by stroke alone, said about the way out instead of the way in.
1560///
1561/// Read off [`Player::modal`] rather than off a list written here: a card
1562/// counted there and not closed by [`Player::close_card`] fails this test
1563/// the day it is added, which is the only way the two stay in step.
1564#[test]
1565fn every_card_closes_without_the_keyboard() {
1566 for card in [
1567 "eq_card",
1568 "color_card",
1569 "speed_card",
1570 "effects_card",
1571 "mix_card",
1572 "silence_card",
1573 "subtitle_style_card",
1574 ] {
1575 // Every clip card is one shared frame: its head carries the back
1576 // and close buttons (`this.close_card()`), and its outer element is
1577 // `card_outer`, which swallows nothing a control needs.
1578 let src = fn_body(card);
1579 assert!(
1580 src.contains("self.card_outer(") && (src.contains("dark_card_head") || src.contains("section_header_row")),
1581 "{card} is not built on the shared card frame"
1582 );
1583 assert!(
1584 src.contains("MouseButton::Left, swallow"),
1585 "{card}'s body does not swallow its own presses, so a press on \
1586 one of its controls would close the card under itself"
1587 );
1588 }
1589 let common = src_text("ui/cards/common.rs");
1590 // REDESIGN §3.9: the card's back/close buttons are gone; its section head
1591 // in the Clip inspector folds it (`this.close_card()`), `esc` still closes it.
1592 let _ = common;
1593 assert!(src_text("ui/dock_stance.rs").contains("this.close_card()"));
1594 // ...and every state that makes the window modal is a state that press
1595 // clears. `exporting()` is not one of them: a running export is a job
1596 // with a cancel button, not a card with a scrim.
1597 let close = fn_body("close_card");
1598 for field in fn_body("modal").split("self.").skip(1).filter_map(|rest| {
1599 let name: String = rest
1600 .chars()
1601 .take_while(|c| c.is_alphanumeric() || *c == '_')
1602 .collect();
1603 (!rest[name.len()..].starts_with('(')).then_some(name)
1604 }) {
1605 assert!(
1606 close.contains(&format!("self.{field}")),
1607 "{field} makes the window modal and `close_card` leaves it set: \
1608 that card cannot be closed by pointer"
1609 );
1610 }
1611}
1612
1613/// A clip too short to hit is still a clip: at a far zoom-out its box is
1614/// drawn [`HIT_MIN`] wide rather than the fraction of a pixel it is worth,
1615/// because a box nobody can put a pointer on cannot be selected, dragged,
1616/// trimmed or given a menu -- and an invisible unselectable take is strictly
1617/// worse than one drawn a few pixels too wide.
1618#[test]
1619fn a_clip_box_is_never_narrower_than_its_target() {
1620 // Two seconds on a bed showing an hour: a fifth of a pixel.
1621 let far = Scale {
1622 pps: 0.1,
1623 start: 0.,
1624 };
1625 assert!(
1626 far.width_px(2.) < 1.,
1627 "the fixture is not zoomed out enough"
1628 );
1629 assert_eq!(clip_width(far.width_px(2.)), HIT_MIN);
1630 // Zero is the floor's own case: a clip trimmed to nothing, and the
1631 // width a lane draws before its first frame is measured.
1632 assert_eq!(clip_width(0.), HIT_MIN);
1633 // What is already wide enough keeps its own width, to the pixel: the
1634 // floor is a floor and never a resize.
1635 let near = Scale::default();
1636 assert_eq!(clip_width(near.width_px(5.)), near.width_px(5.));
1637 // ...and the padding is not trimmable: the strips are asked of the
1638 // clip's own width, so a box drawn wider than its length keeps all of
1639 // that box as a body to select and drag by ([`trims`]).
1640 assert!(!trims(far.width_px(2.)));
1641 assert!(clip_width(far.width_px(2.)) >= HIT_MIN);
1642}
1643
1644/// What the Detach and Group items do to a real timeline: a music video's
1645/// sound comes off its picture, Delete on the loose half takes that half
1646/// only, undo puts both back, and Group makes the two one take again --
1647/// whole-take delete and all.
1648#[test]
1649fn a_detached_half_is_removed_alone_and_groups_again() {
1650 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1651 session.set_gain(0.0);
1652 assert!(whole_take(&session, Lane::V1, 0), "one take to start with");
1653 assert!(whole_take(&session, Lane::A1, 0));
1654 let frames = session.lane_clips(Lane::V1)[0].len();
1655
1656 // Detach audio: neither half is a whole take any more, so Delete on
1657 // either leaves the other exactly where it is.
1658 assert!(session.ungroup(Lane::V1, 0));
1659 assert!(
1660 !whole_take(&session, Lane::A1, 0),
1661 "the sound is a half now"
1662 );
1663 assert!(!whole_take(&session, Lane::V1, 0), "and so is the picture");
1664 assert!(session.lift_clip(Lane::A1, 0));
1665 assert!(session.lane_clips(Lane::A1).is_empty(), "the sound went");
1666 assert_eq!(session.lane_clips(Lane::V1).len(), 1, "the picture stayed");
1667 assert_eq!(session.lane_clips(Lane::V1)[0].len(), frames, "untrimmed");
1668
1669 // One undo per edit, the removal then the detach.
1670 assert!(session.undo());
1671 assert_eq!(session.lane_clips(Lane::A1).len(), 1, "the sound is back");
1672 assert!(session.undo());
1673 assert!(whole_take(&session, Lane::A1, 0), "one take again");
1674
1675 // Group: the partner is the clip covering these very frames on the
1676 // other track, which is what the item hands the engine.
1677 assert!(session.ungroup(Lane::V1, 0));
1678 assert_eq!(span_partner(&session, Lane::V1, 0), Some((Lane::A1, 0)));
1679 session
1680 .group(Lane::V1, 0, Lane::A1, 0)
1681 .expect("both halves still cover the same frames");
1682 assert!(
1683 whole_take(&session, Lane::A1, 0),
1684 "a take that ripples again"
1685 );
1686 assert_eq!(
1687 span_partner(&session, Lane::V1, 0),
1688 None,
1689 "and nothing left on another track to group with"
1690 );
1691}
1692
1693/// Which clip Group reaches when more than one covers the span: the sound,
1694/// whatever order the lanes are stored in. A project file may hold them in
1695/// any order -- a video layer *before* the audio lane among them -- and
1696/// "group this" means the other half of the take, never the layer above it.
1697#[test]
1698fn group_reaches_the_sound_before_a_video_layer_over_it() {
1699 use engine::project::LaneKind;
1700
1701 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1702 session.set_gain(0.0);
1703 let v2 = session.add_lane(LaneKind::Video);
1704 // A bare layer, through the one-lane door: a *drop* on V2 brings the
1705 // file's sound down with it and would put a third clip over this span.
1706 let whole = session.lane_clips(Lane::V1)[0].clone();
1707 assert!(
1708 session.place_at(v2, 0.0, whole),
1709 "a layer covering the same frames as the take"
1710 );
1711
1712 // Saved and loaded back with the lanes in the order a hand-written
1713 // project may hold them: the sound last, behind the layer.
1714 let dir = engine::scratch::Scratch::dir("ve_group");
1715 let file = dir.join("lanes.edith");
1716 session.save_project(&file).expect("save the project");
1717 let text = std::fs::read_to_string(&file).expect("read it back");
1718 let (sound, rest): (Vec<&str>, Vec<&str>) = text.lines().partition(|l| l.starts_with("audio "));
1719 std::fs::write(
1720 &file,
1721 format!("{}\n{}\n", rest.join("\n"), sound.join("\n")),
1722 )
1723 .expect("write the reordered project");
1724 let mut session = PlaybackSession::open_project(&file).expect("it loads as it stands");
1725 std::fs::remove_dir_all(&dir).ok();
1726 assert_eq!(
1727 session.lanes(),
1728 vec![Lane::V1, v2, Lane::A1],
1729 "the sound is the last lane there"
1730 );
1731
1732 // Detached, so Group has a choice to get wrong: the layer covers these
1733 // frames too, and it is the lane the walk meets first.
1734 assert!(session.ungroup(Lane::V1, 0));
1735 // Group on the picture reaches the sound, not that layer.
1736 assert_eq!(span_partner(&session, Lane::V1, 0), Some((Lane::A1, 0)));
1737 session
1738 .group(Lane::V1, 0, Lane::A1, 0)
1739 .expect("the two halves cover the same frames");
1740 // ...and a lane of its own kind is still groupable, once the sound is
1741 // spoken for: two video lanes may be one take.
1742 assert_eq!(
1743 span_partner(&session, Lane::V1, 0),
1744 Some((v2, 0)),
1745 "the layer is what is left to group with"
1746 );
1747}
1748
1749/// The refusal path, end to end against the real files: an incompatible
1750/// import changes nothing, and the library mirrors `sources()` 1:1, so a
1751/// refused file cannot leave a row behind.
1752#[test]
1753fn a_refused_import_leaves_no_row_and_an_accepted_one_is_whole() {
1754 // A mono timeline. Audio no longer refuses on channel count: every
1755 // multichannel track is folded to stereo at the decoder's door and a
1756 // stereo pair is narrowed onto mono (`engine::audio::widen`), so 5.1 and
1757 // stereo sources both join. What is still refused is a file that is not
1758 // media at all, here a text file named `.edith`.
1759 let mut session = PlaybackSession::open(asset("test_ac3.mp4")).expect("open the fixture");
1760 // Silent like the engine suite: this opens the real device.
1761 session.set_gain(0.0);
1762 assert_eq!(session.sources().len(), 1);
1763 // 640x360 joins now (the project canvas places it), and so does a file
1764 // with no sound (it plays silence over its span).
1765 let refusal = session
1766 .import(&asset("test_h264.edith"))
1767 .expect_err("a text file is not media and must not join")
1768 .to_string();
1769 assert!(!refusal.is_empty(), "a refusal must say why");
1770 assert_eq!(session.sources().len(), 1, "a refusal added a row");
1771 // An accepted one does add a row, and it reads as the whole file: 3 s
1772 // at 30 fps, its own length and not one taken off the lanes.
1773 session
1774 .import(&asset("test_audio_only.mp4"))
1775 .expect("mono matches mono");
1776 assert_eq!(session.sources().len(), 2);
1777 let second = session.sources()[1].path.clone();
1778 assert_eq!(session.file_frames(&second), 90);
1779 assert_eq!(timecode(90. / 30., 30.), "00:00:03:00");
1780}
1781
1782/// What the Add button and a dropped row both do, minus the pointer: the
1783/// clip [`Player::insert_source`] builds, put in where the playhead is. One
1784/// call, so what a drop does cannot drift from what the button does.
1785#[test]
1786fn adding_a_row_drops_the_whole_source_in_at_the_playhead() {
1787 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1788 session.set_gain(0.0);
1789 session.import(&asset("test_av2.mp4")).expect("av2 matches");
1790 // In the library only: the 5 s the fixture is, still.
1791 assert_eq!(session.timeline_duration(), 5.0);
1792 // Two seconds in, which is inside the first take: the insert splits it.
1793 session.seek(2.0);
1794 let second = session.sources()[1].path.clone();
1795 let frames = session.file_frames(&second);
1796 // Through the engine door `insert_source` uses, with the row's own
1797 // stream: the button, the drop and this are one call.
1798 assert!(
1799 session
1800 .place_stream_at(2.0, &second, 0, None)
1801 .expect("av2 is already on the timeline")
1802 );
1803 // The whole of source 1 went in and nothing was painted over: the
1804 // timeline is longer by exactly that file.
1805 assert_eq!(session.timeline_duration(), 9.0);
1806 let (video, audio) = (session.lane_clips(Lane::V1), session.lane_clips(Lane::A1));
1807 // One take, not a video clip with no sound under it: both lanes hold
1808 // the same clip at the same place, in the same group.
1809 let at = |lane: &[Clip]| {
1810 lane
1811 .iter()
1812 .find(|c| c.start == 60)
1813 .expect("inserted at 2 s")
1814 .clone()
1815 };
1816 assert_eq!(at(video), at(audio));
1817 assert_eq!(at(video).source, 1);
1818 assert_eq!(at(video).len(), frames);
1819 assert!(at(video).link.is_some());
1820 assert_eq!(video.len(), audio.len());
1821
1822 // The same door with a *second audio stream* of a file already there:
1823 // a new source entry, the same picture, and the row that was dragged
1824 // is what plays. This is the whole user-facing point of the slice.
1825 let mut session = PlaybackSession::open(asset("test_multilang.mp4")).expect("open the fixture");
1826 session.set_gain(0.0);
1827 let path = session.sources()[0].path.clone();
1828 let frames = session.file_frames(&path);
1829 let end = session.timeline_duration();
1830 assert!(
1831 session
1832 .place_stream_at(end, &path, 1, None)
1833 .expect("the French track shares the timeline's parameters")
1834 );
1835 assert_eq!(session.sources()[1].audio_stream, 1);
1836 assert_eq!(session.timeline_duration(), end * 2.0);
1837 // Both rows are the same file, so both rows are that file's length --
1838 // the second one before any clip of its own existed.
1839 assert_eq!(session.file_frames(&path), frames);
1840}
1841
1842/// The drop a hand actually makes: a library row let go on the *empty* bed
1843/// past the last clip, which is most of the bed on any timeline shorter
1844/// than the window. The whole chain the release runs, minus gpui's own
1845/// pointer read -- [`Player::place_frame`]'s [`landing`], the frame back
1846/// through the rate as [`Player::insert_source`] hands it over, and the one
1847/// engine door a row goes through -- and the head lands on the frame the
1848/// ghost was drawn on, black in front of it. It used to be swallowed by the
1849/// clipboard's clamp inside `Project::paste` and appended after the last
1850/// clip wherever it was let go, which is the bug this pins.
1851#[test]
1852fn a_row_dropped_on_the_open_bed_lands_under_the_pointer() {
1853 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1854 session.set_gain(0.0);
1855 session.import(&asset("test_av2.mp4")).expect("av2 matches");
1856 let second = session.sources()[1].path.clone();
1857 let fps = session.meta().frame_rate;
1858 assert_eq!(session.timeline_duration(), 5.0);
1859 // 5 s of timeline on a bed 30 s wide: the open bed past the last clip
1860 // is five sixths of it.
1861 let bed: Bounds<Pixels> = Bounds {
1862 origin: point(px(12.), px(400.)),
1863 size: size(px(600.), px(LANE_H)),
1864 };
1865 let scale = Scale {
1866 pps: 20.,
1867 start: 0.,
1868 };
1869
1870 // What `Player::place_frame` answers for a pointer 200 px along the
1871 // bed: ten seconds in, five seconds past the end of the timeline, and
1872 // no mark anywhere near enough to pull it back.
1873 let clips = [session.lane_clips(Lane::V1), session.lane_clips(Lane::A1)];
1874 let marks = snap_marks(&clips, None, None, frame_at(session.now(), fps), None, &[]);
1875 let under = frame_at(scale.time_at(px_along(px(212.), bed)), fps);
1876 // The drop's own magnet, not the trims' finer one -- `Player::place_frame`
1877 // ships `drop_snap_frames`, and a test computing with `snap_frames` stops
1878 // mirroring production the moment the two differ.
1879 let (at, cue) = landing(under, 0, 0, true, scale.drop_snap_frames(fps), &marks);
1880 assert_eq!((at, cue), (300, None), "the pointer is on frame 300");
1881
1882 // ...and what the release does with it: the frame back through the same
1883 // rate every box is drawn at, into the door the Add button uses too.
1884 assert!(
1885 session
1886 .place_stream_at(f64::from(at) / fps, &second, 0, None)
1887 .expect("av2 is already on this timeline")
1888 );
1889 let head = |lane| {
1890 session
1891 .lane_clips(lane)
1892 .last()
1893 .cloned()
1894 .expect("the dropped clip")
1895 };
1896 assert_eq!(
1897 head(Lane::V1).start,
1898 at,
1899 "the drop landed somewhere other than under the pointer"
1900 );
1901 assert_eq!(head(Lane::A1).start, at, "...and its sound with it");
1902 assert!(head(Lane::V1).link.is_some(), "one grouped take");
1903 assert_eq!(head(Lane::V1).link, head(Lane::A1).link);
1904 // The bed in front of it stays black: nothing was stretched to reach
1905 // it, and the 4 s file is the whole of what was added.
1906 assert_eq!(session.timeline_duration(), 14.0);
1907}
1908
1909/// Remove from library, through the door the menu item uses
1910/// ([`Player::remove_source`] calls exactly this): refused by name while
1911/// clips play from the file, and once they do not the row leaves the list.
1912#[test]
1913fn removing_a_row_is_refused_while_it_plays_and_takes_the_row_away() {
1914 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1915 session.set_gain(0.0);
1916 // Imported, then dragged onto the end: an import alone fills the
1917 // library, and a row with no clip is removable without any refusal to
1918 // test. This one has to have a take on the timeline.
1919 session.import(&asset("test_av2.mp4")).expect("av2 matches");
1920 let second = session.sources()[1].path.clone();
1921 let end = session.timeline_duration();
1922 assert!(
1923 session
1924 .place_stream_at(end, &second, 0, None)
1925 .expect("a file just imported is on this timeline")
1926 );
1927 let streams = HashMap::new();
1928 let rows = |session: &PlaybackSession| {
1929 library_rows(session.sources(), &streams, &HashMap::new(), None, |_| 0).len()
1930 };
1931 assert_eq!(rows(&session), 2, "a row per source");
1932
1933 let refusal = session
1934 .remove_source(&second, 0)
1935 .expect_err("its take is still on the timeline")
1936 .to_string();
1937 assert!(refusal.contains("still plays"), "{refusal}");
1938 assert!(
1939 refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
1940 "the refusal names the lanes to clear: {refusal}"
1941 );
1942 assert_eq!(rows(&session), 2, "and the row is still there");
1943
1944 // Delete that take -- the whole group, from either half -- and the file
1945 // can go. The list is what says so.
1946 let last = session.lane_clips(Lane::V1).len() - 1;
1947 assert!(session.delete_clip(Lane::V1, last));
1948 session
1949 .remove_source(&second, 0)
1950 .expect("nothing plays av2 any more");
1951 assert_eq!(rows(&session), 1, "the row went with it");
1952 assert_eq!(session.sources().len(), 1);
1953 // The one file left is held to the same rule and no other: its own take
1954 // is still on the lanes, so it stays...
1955 let first = session.sources()[0].path.clone();
1956 let refusal = session
1957 .remove_source(&first, 0)
1958 .expect_err("its take is still on the timeline")
1959 .to_string();
1960 assert!(refusal.contains("still plays"), "{refusal}");
1961 // ...and once nothing plays it, the *last* row goes too. What is left
1962 // is the empty library `Player::close_session` turns back into the
1963 // window the editor launches as -- the user-reported bug was that this
1964 // very removal was refused, leaving a row that could never be taken
1965 // out.
1966 assert!(session.delete_clip(Lane::V1, 0));
1967 session
1968 .remove_source(&first, 0)
1969 .expect("the only row goes like any other");
1970 assert_eq!(rows(&session), 0, "an empty library");
1971 assert!(session.sources().is_empty());
1972 // And it is still a session: silent, empty, and asked for its length
1973 // rather than panicking on a source list that is not there.
1974 assert_eq!(session.timeline_duration(), 0.0);
1975 assert!(
1976 session.save_project(&asset("nothing.edith")).is_err(),
1977 "a project naming no file could never be opened again, so it is not written"
1978 );
1979 // A row this timeline never had is refused, not panicked on.
1980 assert!(session.remove_source(&second, 0).is_err());
1981}
1982
1983/// The clipboard after a library removal. A copied clip names its file by
1984/// index and a removal renumbers the list, so this is the difference
1985/// between pasting the take that was copied and pasting **another file**
1986/// over the same range ([`clipboard_after_remove`], called by
1987/// [`Player::remove_source`]).
1988#[test]
1989fn a_copied_clip_is_renumbered_or_dropped_when_a_row_leaves_the_library() {
1990 let clip = |source: usize| Clip {
1991 speed_keys: Vec::new(),
1992 reversed: false,
1993 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
1994 angle: Default::default(),
1995 fade_in: 0,
1996 fade_out: 0,
1997 transition_out: 0,
1998 transition_kind: Default::default(),
1999 visualizer: 0,
2000 viz_paint: 0,
2001 gain_db: 0.0,
2002 gain_keys: Vec::new(),
2003 pan: 0,
2004 pitch: 0.0,
2005 transform_keys: Vec::new(),
2006 opacity_keys: Vec::new(),
2007 color_keys: Vec::new(),
2008 effects: Vec::new(),
2009 start: 0,
2010 in_frame: 0,
2011 out_frame: 30,
2012 source,
2013 link: None,
2014 eq: None,
2015 color: None,
2016 transform: None,
2017 fit: Default::default(),
2018 speed: Default::default(),
2019 };
2020 // Copied from source 2, source 0 removed: the same file is source 1 now.
2021 assert_eq!(
2022 clipboard_after_remove(vec![(Lane::V1, clip(2))], 0)
2023 .into_iter()
2024 .map(|(_, c)| c.source)
2025 .collect::<Vec<_>>(),
2026 vec![1],
2027 "the clipboard follows its file down the list"
2028 );
2029 // Copied from a source *before* the one that went: untouched.
2030 assert_eq!(
2031 clipboard_after_remove(vec![(Lane::V1, clip(0))], 2)
2032 .into_iter()
2033 .map(|(_, c)| c.source)
2034 .collect::<Vec<_>>(),
2035 vec![0]
2036 );
2037 // Copied from the row that was just removed: there is nothing left to
2038 // paste, and pasting the next file along would be a lie.
2039 assert!(clipboard_after_remove(vec![(Lane::V1, clip(1))], 1).is_empty());
2040 assert!(clipboard_after_remove(Vec::new(), 0).is_empty());
2041 // A set with one member's file gone loses only that member -- the rest
2042 // of the set survives to be pasted, gaps and lanes intact.
2043 let trimmed = clipboard_after_remove(vec![(Lane::V1, clip(1)), (Lane::A1, clip(2))], 1);
2044 assert_eq!(
2045 trimmed
2046 .into_iter()
2047 .map(|(_, c)| c.source)
2048 .collect::<Vec<_>>(),
2049 vec![1]
2050 );
2051}
2052
2053/// The trim-a-clip path through the doors the edge drag uses:
2054/// [`Player::trim_to`] clamps the pointer with `trim_room` and
2055/// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less
2056/// of its file, the sound linked to it follows, the head trim moves the
2057/// in-point, and one undo takes a whole gesture back.
2058///
2059/// The routing *to* these doors -- the 6 px edge strip claiming the press
2060/// the clip's own body-drag would otherwise take -- is gpui hitbox
2061/// behaviour (`occlude`) and is not reachable without a window.
2062#[test]
2063fn a_clip_trimmed_by_its_edge_plays_less_of_its_file() {
2064 use engine::project::Edge;
2065
2066 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
2067 session.set_gain(0.0);
2068 let whole = session.lane_clips(Lane::V1)[0].clone();
2069 let full = session.timeline_duration();
2070 assert_eq!(
2071 session.trim_room(Lane::V1, 0, Edge::End),
2072 Some((whole.start + 1, whole.end())),
2073 "the file's own last frame is how far the tail goes"
2074 );
2075 assert!(
2076 !session.trim_clip(Lane::V1, 0, Edge::End, 9_999),
2077 "it already plays all of it"
2078 );
2079
2080 // Pulled in by a third: the timeline ends earlier and the sound with it.
2081 let shorter = whole.end() - whole.len() / 3;
2082 assert!(session.trim_clip(Lane::V1, 0, Edge::End, shorter));
2083 assert_eq!(session.lane_clips(Lane::V1)[0].end(), shorter);
2084 assert_eq!(
2085 session.lane_clips(Lane::A1)[0].end(),
2086 shorter,
2087 "the linked sound was trimmed with the picture"
2088 );
2089 assert!(session.timeline_duration() < full, "and plays out earlier");
2090
2091 // ...and dragged back out, as far as the file goes and no further.
2092 assert!(session.trim_clip(Lane::V1, 0, Edge::End, 9_999));
2093 assert_eq!(
2094 session.lane_clips(Lane::V1)[0],
2095 whole,
2096 "the whole take back"
2097 );
2098
2099 // The head takes the in-point with it, so what plays at the new start
2100 // is source frame 10 rather than source frame 0.
2101 assert!(session.trim_clip(Lane::V1, 0, Edge::Start, 10));
2102 let head = session.lane_clips(Lane::V1)[0].clone();
2103 assert_eq!((head.start, head.in_frame), (10, 10));
2104 assert_eq!(session.lane_clips(Lane::A1)[0].in_frame, 10, "sound too");
2105 assert_eq!(
2106 session.trim_room(Lane::V1, 0, Edge::Start).map(|r| r.0),
2107 Some(0),
2108 "and it may be pulled back out to the file's first frame"
2109 );
2110
2111 assert!(session.undo(), "one step for the whole drag");
2112 assert_eq!(session.lane_clips(Lane::V1)[0], whole);
2113}
2114
2115/// Trim-to-playhead (debt #42): [`Player::trim_cut_to_playhead`] reads
2116/// `frame_at(session.now(), fps)` and calls exactly the [`PlaybackSession::
2117/// trim_clip`] primitive [`Player::commit_trim`]'s pointer path does, so
2118/// this exercises that same door at the playhead's own frame -- the clip's
2119/// start moves to where the playhead rests, one undo step takes it back.
2120#[test]
2121fn trim_to_playhead_moves_the_selected_clips_edge_and_undoes_in_one_step() {
2122 use engine::project::Edge;
2123
2124 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
2125 session.set_gain(0.0);
2126 let whole = session.lane_clips(Lane::V1)[0].clone();
2127 let fps = session.meta().frame_rate;
2128
2129 // Playhead mid-clip, a second in on a five-second timeline.
2130 session.seek(1.0);
2131 let playhead = frame_at(session.now(), fps);
2132 assert!(playhead > whole.start && playhead < whole.end(), "mid-clip");
2133
2134 // Trim-in: the head follows the playhead, same as a pointer drag would
2135 // stop there.
2136 assert!(session.trim_clip(Lane::V1, 0, Edge::Start, playhead));
2137 assert_eq!(session.lane_clips(Lane::V1)[0].start, playhead);
2138 assert!(session.undo(), "one step for the whole press");
2139 assert_eq!(session.lane_clips(Lane::V1)[0], whole, "the head is back");
2140
2141 // Trim-out: the same door, the tail this time.
2142 session.seek(4.0);
2143 let playhead = frame_at(session.now(), fps);
2144 assert!(playhead > whole.start && playhead < whole.end(), "mid-clip");
2145 assert!(session.trim_clip(Lane::V1, 0, Edge::End, playhead));
2146 assert_eq!(session.lane_clips(Lane::V1)[0].end(), playhead);
2147 assert!(session.undo(), "one step for the whole press");
2148 assert_eq!(session.lane_clips(Lane::V1)[0], whole, "the tail is back");
2149}
2150
2151/// The window's own copy of the rate and the two switches follows the
2152/// *session* across `^z` and `^y`: a history entry carries the project's
2153/// settings beside its lanes ([`engine::Project::snapshot`]), so a step puts
2154/// them back -- and a window that kept its old copies counts every cut, step
2155/// and fade in the rate it just undid, keeps showing a switch the session no
2156/// longer has (`settings_stance`), and pushes that switch at the next session
2157/// it makes.
2158#[test]
2159fn the_windows_settings_caches_follow_the_session_across_undo_and_redo() {
2160 use crate::player::actions::{HistoryBefore, SessionCaches, history_step};
2161
2162 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
2163 session.set_gain(0.0);
2164 let native = session.meta().frame_rate;
2165 let (proxies, auto) = (!session.proxies(), !session.auto_proxies());
2166
2167 // The three picks as the window makes them, with the copies it keeps beside
2168 // them (`Player::apply_frame_rate`'s own write, both toggle doors').
2169 assert!(session.set_frame_rate(native * 2.0), "the rate pick");
2170 session.set_proxies(proxies);
2171 session.set_auto_proxies(auto);
2172 let mut caches = SessionCaches {
2173 fps: session.meta().frame_rate,
2174 proxies_on: proxies,
2175 auto_proxies_on: auto,
2176 };
2177 assert_ne!(
2178 caches.fps, native,
2179 "the test needs a rate that really moved"
2180 );
2181
2182 // Back, one step at a time: after each one the window's copies are the
2183 // session's, never the pick's.
2184 for step in 0..3 {
2185 let before = HistoryBefore::of(session.subtitles(), 0);
2186 let out = history_step(&before, &mut caches, &mut session, PlaybackSession::undo)
2187 .expect("a pick behind this one");
2188 assert_eq!(
2189 caches.fps,
2190 session.meta().frame_rate,
2191 "undo {step}: the rate"
2192 );
2193 assert_eq!(
2194 caches.proxies_on,
2195 session.proxies(),
2196 "undo {step}: the switch"
2197 );
2198 assert_eq!(
2199 caches.auto_proxies_on,
2200 session.auto_proxies(),
2201 "undo {step}: the auto switch"
2202 );
2203 assert!(!out.drop_sub_image, "undo {step}: no palette moved");
2204 }
2205 assert_eq!(caches.fps, native, "the rate pick is undone");
2206 assert_eq!(
2207 (caches.proxies_on, caches.auto_proxies_on),
2208 (!proxies, !auto),
2209 "and both switches are back where they were"
2210 );
2211
2212 // ...and forward again, where the picks come home.
2213 for step in 0..3 {
2214 let before = HistoryBefore::of(session.subtitles(), 0);
2215 history_step(&before, &mut caches, &mut session, PlaybackSession::redo)
2216 .expect("a pick in front of this one");
2217 assert_eq!(
2218 caches.fps,
2219 session.meta().frame_rate,
2220 "redo {step}: the rate"
2221 );
2222 assert_eq!(
2223 caches.proxies_on,
2224 session.proxies(),
2225 "redo {step}: the switch"
2226 );
2227 }
2228 assert_eq!(caches.fps, native * 2.0, "the pick's own rate is back");
2229 assert_eq!(caches.proxies_on, proxies, "and its switch");
2230}
2231
2232/// Rows above the picked subtitle move the pick down with them
2233/// ([`sub_pick_after_removal`]), and a `^z` of that removal has to move it back
2234/// up: the palette comes home out of the entry, the pick is an *index* into it,
2235/// and an index left where it was highlights one row and names another. The
2236/// plate over the picture goes too, not because it is keyed by the pick -- it is
2237/// keyed by where a cue sits -- but because the step moves the cues under it.
2238#[test]
2239fn the_subtitle_pick_follows_its_track_across_an_undo_of_a_removal() {
2240 use crate::player::actions::{HistoryBefore, SessionCaches, history_step};
2241
2242 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
2243 session.set_gain(0.0);
2244 assert_eq!(
2245 session.add_subtitle_tracks(vec![
2246 sub("/subs/one.srt", None, "one.srt"),
2247 sub("/subs/two.srt", None, "two.srt"),
2248 sub("/subs/three.srt", None, "three.srt"),
2249 ]),
2250 3,
2251 "the palette"
2252 );
2253 let mut caches = SessionCaches {
2254 fps: session.meta().frame_rate,
2255 proxies_on: session.proxies(),
2256 auto_proxies_on: session.auto_proxies(),
2257 };
2258 // The last row picked, which is where a click on it leaves the pick.
2259 let pick = 2;
2260 let picked = sub_pick_name(session.subtitles(), pick).expect("a name for the pick");
2261
2262 // The row *above* it goes, through the removal door's own fixup.
2263 session
2264 .remove_subtitles(0)
2265 .expect("a row with nothing on it");
2266 let pick = sub_pick_after_removal(pick, 0, session.subtitles().len());
2267 assert_eq!(pick, 1, "the pick slid down with the rows");
2268 assert_eq!(
2269 sub_pick_name(session.subtitles(), pick).as_deref(),
2270 Some(picked.as_str()),
2271 "and still names the same track"
2272 );
2273
2274 let before = HistoryBefore::of(session.subtitles(), pick);
2275 let out = history_step(&before, &mut caches, &mut session, PlaybackSession::undo)
2276 .expect("the removal is a step like any other cut");
2277 assert_eq!(session.subtitles().len(), 3, "the palette is back");
2278 assert_eq!(
2279 out.sub_track, 2,
2280 "the row came back above the pick, so the pick moves up"
2281 );
2282 assert_eq!(
2283 sub_pick_name(session.subtitles(), out.sub_track).as_deref(),
2284 Some(picked.as_str()),
2285 "and still names the same track"
2286 );
2287 assert_ne!(
2288 sub_pick_name(session.subtitles(), pick).as_deref(),
2289 Some(picked.as_str()),
2290 "which is what the index left where it was would have named"
2291 );
2292 assert!(
2293 out.drop_sub_image,
2294 "the drawn plate went through the pick that moved"
2295 );
2296
2297 // ...and forward again: the removal, with the fixup it does at its own door.
2298 let before = HistoryBefore::of(session.subtitles(), out.sub_track);
2299 let out = history_step(&before, &mut caches, &mut session, PlaybackSession::redo)
2300 .expect("the removal is in front of this one");
2301 assert_eq!(
2302 out.sub_track, 1,
2303 "the removal slides the pick down with the rows"
2304 );
2305 assert_eq!(
2306 sub_pick_name(session.subtitles(), out.sub_track).as_deref(),
2307 Some(picked.as_str())
2308 );
2309 assert!(out.drop_sub_image, "and the plate goes with it");
2310}
2311
2312/// The app-level write-back of a history step is not reachable from this binary
2313/// -- `Player` needs a `TestAppContext` this one has none of -- so the wiring is
2314/// pinned where it can be read: both keyboard doors route through
2315/// [`Player::step_history`], and its body still keeps the three session caches
2316/// and the pick, and still drops the plate. What those values *are* is pinned
2317/// against a real session by the two tests above ([`history_step`] is the free
2318/// function they drive); this is the copy back into the window's own fields,
2319/// which no test can call.
2320#[test]
2321fn a_history_step_still_takes_its_settings_and_its_pick_back_up() {
2322 let actions = src_text("player/actions.rs");
2323 for needle in [
2324 "self.step_history(PlaybackSession::undo);",
2325 "self.step_history(PlaybackSession::redo);",
2326 ] {
2327 assert!(
2328 actions.contains(needle),
2329 "a history door stopped routing through Player::step_history: {needle}"
2330 );
2331 }
2332 let body = fn_body("step_history");
2333 // The state the step is asked about, and the answer taken back up: every one
2334 // of these deleted leaves a cache or the pick stale for the next cut, the
2335 // next frame count, or the next repaint.
2336 for needle in [
2337 "let mut caches = SessionCaches {",
2338 "HistoryBefore::of(",
2339 "self.fps = caches.fps;",
2340 "self.proxies_on = caches.proxies_on;",
2341 "self.auto_proxies_on = caches.auto_proxies_on;",
2342 "self.sub_track = outcome.sub_track;",
2343 "if outcome.drop_sub_image {",
2344 "self.sub_image = None;",
2345 "self.reset_after_reseek();",
2346 ] {
2347 assert!(
2348 body.contains(needle),
2349 "Player::step_history no longer carries `{needle}` -- a history step \
2350 leaves it behind (the app suite cannot see this: it has no \
2351 TestAppContext to call the door)"
2352 );
2353 }
2354}
2355
2356/// The oracle side of trim-to-playhead (debt #42): needs a subject cut *and*
2357/// the playhead actually resting on it, unlike the nudge pair above it which
2358/// only needs a cut -- the "spot" a keyless drag would snap to has to be on
2359/// the clip at all.
2360#[test]
2361fn trim_to_playhead_needs_a_subject_cut_with_the_playhead_on_it() {
2362 let clip = Clip {
2363 speed_keys: Vec::new(),
2364 reversed: false,
2365 stabilise: None, deinterlace: Default::default(), mark: Default::default(),
2366 angle: Default::default(),
2367 fade_in: 0,
2368 fade_out: 0,
2369 transition_out: 0,
2370 transition_kind: Default::default(),
2371 visualizer: 0,
2372 viz_paint: 0,
2373 gain_db: 0.0,
2374 gain_keys: Vec::new(),
2375 pan: 0,
2376 pitch: 0.0,
2377 transform_keys: Vec::new(),
2378 opacity_keys: Vec::new(),
2379 color_keys: Vec::new(),
2380 effects: Vec::new(),
2381 start: 100,
2382 in_frame: 0,
2383 out_frame: 60,
2384 source: 0,
2385 link: None,
2386 eq: None,
2387 color: None,
2388 transform: None,
2389 fit: FitPolicy::default(),
2390 speed: Speed::NORMAL,
2391 };
2392 assert_eq!(
2393 enable(
2394 ActionId::TrimInToPlayhead,
2395 Ctx {
2396 timeline: true,
2397 ..Ctx::default()
2398 }
2399 ),
2400 Enable::No("no clip is selected"),
2401 "nothing marked"
2402 );
2403 let off = Ctx {
2404 clip: Some((clip.clone(), Lane::V1)),
2405 playhead: 5,
2406 timeline: true,
2407 ..Ctx::default()
2408 };
2409 assert_eq!(
2410 enable(ActionId::TrimOutToPlayhead, off),
2411 Enable::No("the playhead is off this clip")
2412 );
2413 let on = Ctx {
2414 clip: Some((clip.clone(), Lane::V1)),
2415 playhead: clip.start,
2416 timeline: true,
2417 ..Ctx::default()
2418 };
2419 assert_eq!(enable(ActionId::TrimInToPlayhead, on.clone()), Enable::Yes);
2420 assert_eq!(enable(ActionId::TrimOutToPlayhead, on), Enable::Yes);
2421}
2422
2423/// The move-a-clip-between-tracks path through the door the drop uses
2424/// ([`Player::move_clip`] calls exactly this): the clip changes row, the
2425/// *picture* comes from the new row afterwards -- which is what "it plays
2426/// from there" means -- and one undo puts it back.
2427#[test]
2428fn a_clip_dragged_onto_another_track_plays_from_it() {
2429 use engine::project::LaneKind;
2430
2431 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
2432 session.set_gain(0.0);
2433 let v2 = session.add_lane(LaneKind::Video);
2434 assert_eq!(session.video_clip_at(0.0), Some((Lane::V1, 0)));
2435
2436 assert!(session.move_clip_to(Lane::V1, 0, v2, 0), "V1 -> V2");
2437 assert!(session.lane_clips(Lane::V1).is_empty(), "it left V1");
2438 assert_eq!(session.lane_clips(v2).len(), 1, "and landed on V2");
2439 assert_eq!(
2440 session.video_clip_at(0.0),
2441 Some((v2, 0)),
2442 "the picture now comes from V2"
2443 );
2444 assert_eq!(session.lane_clips(Lane::A1).len(), 1, "its sound stayed");
2445
2446 // Dropped on a lane of the other kind it is refused and nothing moves --
2447 // the notice the front-end shows for it says which kind of lane to use.
2448 // (The other refusal, landing on another clip, is the engine's own test
2449 // `move_clip_keeps_the_frames_and_refuses_the_rest`.)
2450 assert!(!session.move_clip_to(v2, 0, Lane::A1, 0), "picture on A1");
2451 assert_eq!(session.lane_clips(v2).len(), 1, "and it stayed on V2");
2452 assert!(
2453 session.move_clip_to(v2, 0, Lane::V1, 0),
2454 "dragged back down"
2455 );
2456
2457 // One undo per move, and each is a single step.
2458 assert!(session.undo(), "the drag back");
2459 assert_eq!(session.video_clip_at(0.0), Some((v2, 0)));
2460 assert!(session.undo(), "the drag up");
2461 assert_eq!(session.video_clip_at(0.0), Some((Lane::V1, 0)));
2462 assert!(session.lane_clips(v2).is_empty());
2463}
2464
2465/// The add-a-track path end to end through the doors the buttons and the
2466/// drop use: `+ V` adds a row, a library row let go over it lands there and
2467/// nowhere else, Delete on it leaves the lanes under it where they are, and
2468/// undo takes the whole thing back one step at a time.
2469#[test]
2470fn a_track_can_be_added_dropped_on_edited_and_taken_back() {
2471 use engine::project::LaneKind;
2472
2473 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
2474 session.set_gain(0.0);
2475 assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1]);
2476 // What the `+ V` button asks for, and what the row it draws is called.
2477 let v2 = session.add_lane(LaneKind::Video);
2478 assert_eq!(v2.label(), "V2");
2479 assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1, v2]);
2480 assert!(session.lane_clips(v2).is_empty());
2481 // A library row let go over that row: the same door the Add button
2482 // uses, told which lane it was let go over.
2483 let path = session.sources()[0].path.clone();
2484 assert!(
2485 session
2486 .place_stream_at(1.0, &path, 0, Some(v2))
2487 .expect("its own file is on this timeline")
2488 );
2489 assert_eq!(session.lane_clips(v2).len(), 1, "the drop landed on V2");
2490 assert_eq!(session.lane_clips(v2)[0].start, 30, "at the playhead");
2491 // ...with the sound it came with, on the row of its own the drop added:
2492 // a file with audio dropped on a layer used to land silent.
2493 let a2 = Lane::new(LaneKind::Audio, 1);
2494 assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1, v2, a2]);
2495 assert_eq!(session.lane_clips(a2), session.lane_clips(v2), "same take");
2496 assert_eq!(
2497 session.lane_clips(v2)[0].link,
2498 session.lane_clips(a2)[0].link,
2499 "grouped, so a drag moves both"
2500 );
2501 // And nowhere else: the first pair is exactly as it was, one take each.
2502 assert_eq!(session.lane_clips(Lane::V1).len(), 1);
2503 assert_eq!(session.lane_clips(Lane::A1).len(), 1);
2504 // ...and it is a project that saves and opens again as it stands: a
2505 // grouped pair on a further row is what the file has to carry.
2506 let dir = engine::scratch::Scratch::dir("ve_layer");
2507 let file = dir.join("layer.edith");
2508 session.save_project(&file).expect("save the project");
2509 let back = PlaybackSession::open_project(&file).expect("it loads as it stands");
2510 std::fs::remove_dir_all(&dir).ok();
2511 assert_eq!(back.lanes(), session.lanes());
2512 for lane in back.lanes() {
2513 assert_eq!(back.lane_clips(lane), session.lane_clips(lane), "{lane:?}");
2514 }
2515 // The drop grouped `V2` with the `A2` it added -- a take, same as the
2516 // first pair's, just on an added row -- so Delete would close both their
2517 // own lanes too (`Project::delete_members`), not drag the first pair out
2518 // of step: `delete_members` ripples only a member's own lane. Lift is
2519 // tested directly here instead, to check its own hole-left-open law
2520 // without going through the Delete key's routing.
2521 assert!(whole_take(&session, v2, 0));
2522 assert!(whole_take(&session, Lane::V1, 0));
2523 assert!(whole_take(&session, Lane::A1, 0));
2524 assert_eq!(a2.label(), "A2");
2525 assert!(session.lift_clip(v2, 0));
2526 assert!(session.lane_clips(v2).is_empty());
2527 assert_eq!(session.lane_clips(Lane::V1).len(), 1, "V1 stayed put");
2528 assert_eq!(
2529 session.lane_clips(a2).len(),
2530 1,
2531 "a lift takes the half it names: the sound is still there to lift"
2532 );
2533 assert!(session.lift_clip(a2, 0));
2534
2535 // A second audio lane used to be what an mp4 export could not write --
2536 // it copied one AAC track and a mix is not a copy. It mixes now
2537 // (`export::copy_audio`), so no row is greyed by a count of lanes.
2538 for format in [Format::Mp4, Format::Av1, Format::Av1Mp4] {
2539 assert_eq!(
2540 format_refusal(&session, format),
2541 None,
2542 "two audio lanes are a mix, not a refusal"
2543 );
2544 }
2545
2546 // Undo, one edit at a time and backwards: the lift of the sound, the
2547 // lift of the picture, the drop on V2 with the lane A2 it added, and
2548 // last the lane V2 -- an added track is one step like every other edit.
2549 for lanes in [4, 4, 3, 2] {
2550 assert!(session.undo());
2551 assert_eq!(session.lanes().len(), lanes);
2552 }
2553 assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1]);
2554 assert_eq!(session.lane_clips(Lane::V1).len(), 1);
2555 assert_eq!(format_refusal(&session, Format::Mp4), None);
2556}
2557
2558/// [`PlaybackSession::move_selection_to`], the door a selection drag uses
2559/// ([`Player::move_clip`]'s set path): three picks across two lanes, one of
2560/// them the dragged clip, all travel the *same* frame delta in one call --
2561/// the same all-or-nothing clamp [`Project::move_room`] already gave a
2562/// linked group, generalised to an arbitrary selection.
2563#[test]
2564fn a_selection_drag_moves_every_pick_by_the_same_delta() {
2565 use engine::project::LaneKind;
2566
2567 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
2568 session.set_gain(0.0);
2569 let path = session.sources()[0].path.clone();
2570 session.import(&asset("test_av2.mp4")).expect("av2 matches");
2571 let second = session.sources()[1].path.clone();
2572
2573 // clip0 on V1 at the fixture's own start; clip1 on V1 ten seconds in,
2574 // appended to the open bed and rippling nothing.
2575 assert!(
2576 session
2577 .place_stream_at(10.0, &second, 0, None)
2578 .expect("av2 is on this timeline")
2579 );
2580 let clip0 = session.lane_clips(Lane::V1)[0].clone();
2581 let clip1 = session.lane_clips(Lane::V1)[1].clone();
2582 assert_eq!((clip0.start, clip1.start), (0, 300));
2583
2584 // clipC on a second video row, well past both of the above.
2585 let v2 = session.add_lane(LaneKind::Video);
2586 assert!(
2587 session
2588 .place_stream_at(20.0, &path, 0, Some(v2))
2589 .expect("test_av.mp4 is on this timeline")
2590 );
2591 let clip_c = session.lane_clips(v2)[0].clone();
2592 assert_eq!(clip_c.start, 600);
2593
2594 let picks = [(Lane::V1, 0), (Lane::V1, 1), (v2, 0)];
2595 // Drag clip1 fifty frames along its own lane -- the other two picks own
2596 // no neighbours of their own here, so nothing narrows the room and the
2597 // full fifty-frame ask goes through for all three.
2598 assert!(session.move_selection_to(&picks, Lane::V1, 1, Lane::V1, clip1.start + 50));
2599 assert_eq!(session.lane_clips(Lane::V1)[0].start, clip0.start + 50);
2600 assert_eq!(session.lane_clips(Lane::V1)[1].start, clip1.start + 50);
2601 assert_eq!(session.lane_clips(v2)[0].start, clip_c.start + 50);
2602 // Every pick still names the clip it named: found again by the frame it
2603 // now starts at -- exactly the lookup `Player::remap_selection` makes
2604 // once the move lands, which is what keeps a set-move's selection alive
2605 // rather than clearing it.
2606 assert_eq!(
2607 session.lane_clips(Lane::V1)[0],
2608 Clip {
2609 start: clip0.start + 50,
2610 ..clip0
2611 }
2612 );
2613 assert_eq!(
2614 session.lane_clips(v2)[0],
2615 Clip {
2616 start: clip_c.start + 50,
2617 ..clip_c
2618 }
2619 );
2620
2621 assert!(session.undo(), "one step for the whole set-move");
2622 assert_eq!(session.lane_clips(Lane::V1)[0].start, clip0.start);
2623 assert_eq!(session.lane_clips(Lane::V1)[1].start, clip1.start);
2624 assert_eq!(session.lane_clips(v2)[0].start, clip_c.start);
2625}
2626
2627/// One pick with nowhere to go refuses the whole set: the walk onto another
2628/// clip's own span that already refuses a lone drag
2629/// (`move_clip_keeps_the_frames_and_refuses_the_rest`, in this crate's own
2630/// engine tests) refuses a selection drag exactly the same way, and every
2631/// *other* pick -- which had all the room in the world -- stays exactly
2632/// where it was rather than moving on its own.
2633#[test]
2634fn a_selection_drag_refuses_as_one_set_when_any_pick_cannot_land() {
2635 use engine::project::LaneKind;
2636
2637 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
2638 session.set_gain(0.0);
2639 let path = session.sources()[0].path.clone();
2640 session.import(&asset("test_av2.mp4")).expect("av2 matches");
2641 let second = session.sources()[1].path.clone();
2642
2643 assert!(
2644 session
2645 .place_stream_at(10.0, &second, 0, None)
2646 .expect("av2 is on this timeline")
2647 );
2648 let clip0 = session.lane_clips(Lane::V1)[0].clone();
2649 let clip1 = session.lane_clips(Lane::V1)[1].clone();
2650
2651 let v2 = session.add_lane(LaneKind::Video);
2652 assert!(
2653 session
2654 .place_stream_at(0.0, &path, 0, Some(v2))
2655 .expect("test_av.mp4 is on this timeline")
2656 );
2657 let clip_c = session.lane_clips(v2)[0].clone();
2658 // A clip clip1 is not picked, blocking the road on V2 the drag is about
2659 // to try: clip1 dragged onto V2 lands its head inside this one.
2660 assert!(
2661 session
2662 .place_stream_at(10.0, &second, 0, Some(v2))
2663 .expect("av2 is on this timeline")
2664 );
2665 let blocker = session.lane_clips(v2)[1].clone();
2666 assert_eq!(blocker.start, 300);
2667
2668 let picks = [(Lane::V1, 0), (Lane::V1, 1), (v2, 0)];
2669 // Dragged onto V2 at a frame inside the blocker: refused outright, the
2670 // way a lone drag onto another clip already is.
2671 assert!(!session.move_selection_to(&picks, Lane::V1, 1, v2, blocker.start + 10));
2672 // Nothing moved -- not clip1 clamped short of the blocker, and not the
2673 // two picks that had all the room to spare.
2674 assert_eq!(session.lane_clips(Lane::V1)[0], clip0);
2675 assert_eq!(session.lane_clips(Lane::V1)[1], clip1);
2676 assert_eq!(session.lane_clips(v2)[0], clip_c);
2677 assert_eq!(session.lane_clips(v2)[1], blocker);
2678}
2679
2680/// A plain click's copy is one clipboard entry, and one entry still takes
2681/// [`PlaybackSession::paste_at`] -- the door it always has, unchanged by a
2682/// set ever being able to ride [`PlaybackSession::paste_set_at`] instead.
2683#[test]
2684fn a_single_pick_copy_paste_round_trips_unchanged() {
2685 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
2686 session.set_gain(0.0);
2687 // `open` seeds V1 with the whole fixture as its own clip -- what a plain
2688 // click would copy.
2689 let copied = session.lane_clips(Lane::V1)[0].clone();
2690
2691 let at = session.timeline_duration();
2692 assert!(session.paste_at(at, copied.clone()), "a free spot always takes it");
2693 let pasted = session.lane_clips(Lane::V1)[1].clone();
2694 assert_eq!(
2695 (pasted.source, pasted.in_frame, pasted.out_frame),
2696 (copied.source, copied.in_frame, copied.out_frame),
2697 "the pasted clip plays the same source frames the copy did"
2698 );
2699
2700 assert!(session.undo(), "one step for the paste");
2701 assert_eq!(session.lane_clips(Lane::V1).len(), 1);
2702}
2703
2704/// [`PlaybackSession::paste_set_at`], the set-copy's own door
2705/// ([`Player::paste`]'s multi-entry path): three picks across two lanes, some
2706/// distance apart, keep that same distance and the same lane each landed on
2707/// -- the offset [`Project::paste_set`] moves every item by is the one from
2708/// the earliest pick to `at`, not a collapse onto `V1`/`A1`.
2709#[test]
2710fn a_three_pick_copy_paste_preserves_gaps_and_lane_assignment() {
2711 use engine::project::LaneKind;
2712
2713 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
2714 session.set_gain(0.0);
2715 let path = session.sources()[0].path.clone();
2716 session.import(&asset("test_av2.mp4")).expect("av2 matches");
2717 let second = session.sources()[1].path.clone();
2718
2719 assert!(
2720 session
2721 .place_stream_at(10.0, &second, 0, None)
2722 .expect("av2 is on this timeline")
2723 );
2724 let clip0 = session.lane_clips(Lane::V1)[0].clone();
2725 let clip1 = session.lane_clips(Lane::V1)[1].clone();
2726
2727 let v2 = session.add_lane(LaneKind::Video);
2728 assert!(
2729 session
2730 .place_stream_at(20.0, &path, 0, Some(v2))
2731 .expect("test_av.mp4 is on this timeline")
2732 );
2733 let clip_c = session.lane_clips(v2)[0].clone();
2734
2735 // Copied in click order, out of the lanes each was clicked in -- exactly
2736 // what `Player::copy_selected` builds.
2737 let items = [(Lane::V1, clip0.clone()), (Lane::V1, clip1.clone()), (v2, clip_c.clone())];
2738 let at = session.timeline_duration();
2739 assert!(
2740 session.paste_set_at(at, &items),
2741 "a free spot takes the set"
2742 );
2743
2744 let new0 = session.lane_clips(Lane::V1)[2].clone();
2745 let new1 = session.lane_clips(Lane::V1)[3].clone();
2746 let new_c = session.lane_clips(v2)[1].clone();
2747 // The gaps between picks survive the trip untouched.
2748 assert_eq!(new1.start - new0.start, clip1.start - clip0.start);
2749 assert_eq!(new_c.start - new0.start, clip_c.start - clip0.start);
2750 // And each still plays the source frames it was copied with, off the
2751 // lane it was copied off of.
2752 assert_eq!(
2753 (new0.source, new0.in_frame, new0.out_frame),
2754 (clip0.source, clip0.in_frame, clip0.out_frame)
2755 );
2756 assert_eq!(
2757 (new_c.source, new_c.in_frame, new_c.out_frame),
2758 (clip_c.source, clip_c.in_frame, clip_c.out_frame)
2759 );
2760
2761 assert!(session.undo(), "one step for the whole set-paste");
2762 assert_eq!(session.lane_clips(Lane::V1).len(), 2);
2763 assert_eq!(session.lane_clips(v2).len(), 1);
2764}
2765
2766/// A set-paste never ripples the bed: a landing that would overlap so much
2767/// as one existing clip on its own lane refuses the *whole* set, exactly as
2768/// [`Project::paste_set`] documents, leaving the project as it was rather
2769/// than placing the picks that had room to spare.
2770#[test]
2771fn a_colliding_set_paste_refuses_whole() {
2772 use engine::project::LaneKind;
2773
2774 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
2775 session.set_gain(0.0);
2776 let path = session.sources()[0].path.clone();
2777 session.import(&asset("test_av2.mp4")).expect("av2 matches");
2778 let second = session.sources()[1].path.clone();
2779
2780 assert!(
2781 session
2782 .place_stream_at(10.0, &second, 0, None)
2783 .expect("av2 is on this timeline")
2784 );
2785 let clip0 = session.lane_clips(Lane::V1)[0].clone();
2786 let clip1 = session.lane_clips(Lane::V1)[1].clone();
2787
2788 let v2 = session.add_lane(LaneKind::Video);
2789 assert!(
2790 session
2791 .place_stream_at(20.0, &path, 0, Some(v2))
2792 .expect("test_av.mp4 is on this timeline")
2793 );
2794 let clip_c = session.lane_clips(v2)[0].clone();
2795
2796 let items = [(Lane::V1, clip0.clone()), (Lane::V1, clip1.clone()), (v2, clip_c.clone())];
2797 // A blocker sat right where the V1 half of the set would land: pasting
2798 // at the timeline's own start walks every item straight back onto the
2799 // lanes it was copied off of, colliding with everything already there.
2800 assert!(!session.paste_set_at(0.0, &items));
2801
2802 assert_eq!(session.lane_clips(Lane::V1)[0], clip0);
2803 assert_eq!(session.lane_clips(Lane::V1)[1], clip1);
2804 assert_eq!(session.lane_clips(v2)[0], clip_c);
2805 assert_eq!(session.lane_clips(Lane::V1).len(), 2);
2806 assert_eq!(session.lane_clips(v2).len(), 1);
2807}
2808
2809/// The refactor `move_clip` -> `move_selection` owes: a clip dragged from
2810/// outside the selection (or with nothing else selected) moves exactly as it
2811/// always has -- `move_clip_to`'s own door and `move_selection_to`'s
2812/// selection-of-one both walk the same code, so they cannot drift apart.
2813#[test]
2814fn a_lone_clip_drag_is_unchanged_by_the_selection_path() {
2815 use engine::project::LaneKind;
2816
2817 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
2818 session.set_gain(0.0);
2819 let v2 = session.add_lane(LaneKind::Video);
2820
2821 assert!(session.move_clip_to(Lane::V1, 0, v2, 0), "V1 -> V2");
2822 assert!(session.lane_clips(Lane::V1).is_empty());
2823 assert_eq!(session.lane_clips(v2).len(), 1);
2824
2825 // The other kind of lane is refused exactly as before.
2826 assert!(!session.move_clip_to(v2, 0, Lane::A1, 0));
2827 // A drop back where it was picked up is a click, still refused.
2828 let clip = session.lane_clips(v2)[0].clone();
2829 assert!(!session.move_clip_to(v2, 0, v2, clip.start));
2830}
2831
2832/// A caption grouped with a clip on an *added* lane closes its lane's hole
2833/// too, not just the first pair's: the same law commit `cdc53a6` gave `V1`
2834/// (`whole_take` -> `Project::delete_members`) has to hold from every anchor
2835/// a Delete can be clicked from, or a grouped caption on `V2`/subtitle
2836/// survives its clip as an orphan link. `whole_take` used to answer `false`
2837/// for any lane with `ord >= 1` no matter what it was grouped with, which
2838/// routed `Player::delete_selected` to `lift_clip` -- the clip's own lane
2839/// left a hole, and the caption it was grouped with was never touched at
2840/// all.
2841#[test]
2842fn a_grouped_clip_on_an_added_lane_closes_its_hole_with_its_caption() {
2843 use engine::project::LaneKind;
2844
2845 let (mut session, sub_lane) = with_subtitle_lane();
2846 let v2 = session.add_lane(LaneKind::Video);
2847 let path = session.sources()[0].path.clone();
2848 assert!(
2849 session
2850 .place_stream_at(0.0, &path, 0, Some(v2))
2851 .expect("its own file is on this timeline")
2852 );
2853 session
2854 .place_sub(sub_lane, 0, one_second(0))
2855 .expect("the caption goes down");
2856 session
2857 .group_all(&[(v2, 0), (sub_lane, 0)])
2858 .expect("a clip on an added lane and a caption are a group");
2859
2860 // The group pairs the clip for the whole-take question from its own
2861 // lane, `ord >= 1` or not.
2862 assert!(whole_take(&session, v2, 0));
2863
2864 // Two clips after the group's own -- something to close the hole
2865 // against on the caption's lane too.
2866 session
2867 .place_sub(sub_lane, 60, one_second(60))
2868 .expect("a second caption after it");
2869 assert_eq!(session.sub_lane(sub_lane).len(), 2);
2870
2871 // `Player::delete_selected` calls exactly this door once `whole_take`
2872 // says yes -- the fix is that it now reaches it from `v2` too.
2873 assert!(session.delete_clip(v2, 0));
2874 assert!(session.lane_clips(v2).is_empty(), "the clip is gone");
2875 assert_eq!(
2876 session.sub_lane(sub_lane).len(),
2877 1,
2878 "its grouped caption went with it, not left as an orphan"
2879 );
2880 assert_eq!(
2881 session.sub_lane(sub_lane)[0].start,
2882 30,
2883 "and the hole under it closed: the caption after it slid up"
2884 );
2885}
2886
2887#[test]
2888fn a_source_is_only_ever_asked_for_its_peaks_once() {
2889 let (a, b) = (asset("test_av.mp4"), asset("test_av2.mp4"));
2890 // Two files, and two streams of the first: three envelopes, because
2891 // one file's two audio tracks are two different waveforms.
2892 let sources = [
2893 Source {
2894 path: a.clone(),
2895 audio_stream: 0, ..Default::default()
2896 },
2897 Source {
2898 path: a.clone(),
2899 audio_stream: 1, ..Default::default()
2900 },
2901 Source {
2902 path: b.clone(),
2903 audio_stream: 0, ..Default::default()
2904 },
2905 ];
2906 let keys = |s: &[Source]| {
2907 s.iter()
2908 .map(|s| (s.path.clone(), s.audio_stream))
2909 .collect::<Vec<_>>()
2910 };
2911 let mut waves: HashMap<(PathBuf, usize), Wave> = HashMap::new();
2912 assert_eq!(
2913 unseen_sources(&sources, &waves, std::time::Instant::now()),
2914 keys(&sources)
2915 );
2916 // The entry goes in when the decode *starts*, so the sixty repaints a
2917 // second that happen while it runs must not start it again -- which is
2918 // what this asserts about a key whose value is not an answer yet.
2919 waves.insert((a.clone(), 0), Wave::Loading);
2920 assert_eq!(
2921 unseen_sources(&sources, &waves, std::time::Instant::now()),
2922 keys(&sources[1..]),
2923 "the file's other stream is a key of its own"
2924 );
2925 // A file with no audio is an answer like any other: never re-asked.
2926 waves.insert((a, 1), Wave::Silent);
2927 waves.insert((b.clone(), 0), Wave::Silent);
2928 assert!(unseen_sources(&sources, &waves, std::time::Instant::now()).is_empty());
2929 // A decode that *failed* is not an answer: the reason may have gone away
2930 // (the file was still being copied when it arrived), so it is asked again
2931 // -- once the stamp is older than the cooldown, so sixty repaints a second
2932 // do not become sixty decodes.
2933 let now = std::time::Instant::now();
2934 waves.insert((b.clone(), 0), Wave::Failed(now));
2935 assert!(
2936 unseen_sources(&sources, &waves, now).is_empty(),
2937 "a failure that just landed is not re-asked at once"
2938 );
2939 assert_eq!(
2940 unseen_sources(&sources, &waves, now + crate::subs::WAVE_RETRY),
2941 keys(&sources[2..]),
2942 "and is asked again once the cooldown is out"
2943 );
2944 // The stream probe is per *file*: the two entries of `a` ask once.
2945 let mut streams: HashMap<PathBuf, Vec<StreamInfo>> = HashMap::new();
2946 assert_eq!(
2947 unseen_paths(&sources, &streams),
2948 vec![asset("test_av.mp4"), b]
2949 );
2950 streams.insert(asset("test_av.mp4"), Vec::new());
2951 assert_eq!(unseen_paths(&sources, &streams).len(), 1);
2952}
2953
2954/// The auto switch, which is the whole of what an import asks: with it off no
2955/// film is handed to [`engine::proxy`] at all, and turning Proxies on is what
2956/// asks for the ones the project is missing -- there is no other door, so a
2957/// project that never wants a stand-in never spends a minute encoding one.
2958#[test]
2959fn a_project_that_makes_no_proxies_by_itself_starts_none_until_it_is_cut_on_them() {
2960 let sources = [Source {
2961 path: asset("test_av.mp4"),
2962 audio_stream: 0, ..Default::default()
2963 }];
2964 let none: HashMap<PathBuf, ()> = HashMap::new();
2965 let one = vec![asset("test_av.mp4")];
2966 // Today's behaviour, both ways round: auto on starts them whether or not
2967 // the picture is cut on them -- the cache is warmed for later.
2968 assert_eq!(proxies_to_start(true, false, &sources, &none), one);
2969 assert_eq!(proxies_to_start(true, true, &sources, &none), one);
2970 // Auto off and not cut on them: nothing is started at all.
2971 assert!(
2972 proxies_to_start(false, false, &sources, &none).is_empty(),
2973 "an import started a stand-in the project asked it not to"
2974 );
2975 // ...and the switch is the ask: the film comes through the moment Proxies
2976 // goes on, because it was left unseen rather than marked done.
2977 assert_eq!(proxies_to_start(false, true, &sources, &none), one);
2978 // One start per film either way: a film already in the map is one already
2979 // asked about, sixty repaints a second notwithstanding.
2980 let seen: HashMap<PathBuf, ()> = HashMap::from([(asset("test_av.mp4"), ())]);
2981 assert!(proxies_to_start(true, true, &sources, &seen).is_empty());
2982}
2983
2984#[test]
2985fn the_media_column_never_takes_the_picture_over() {
2986 for window in [360., 640., 1280., 1920., 3840.] {
2987 let w = crate::library_w(window);
2988 // The whole point of the budget: the picture keeps the majority of
2989 // the row at every size a window can be.
2990 assert!(w <= window / 3., "{window}px window gave the list {w}px");
2991 assert!(w >= LIBRARY_MIN_W.min(window / 3.), "{window}px: {w}px");
2992 assert!(w <= LIBRARY_MAX_W);
2993 }
2994 // It yields: a narrower window gives the list less, never the same.
2995 assert!(crate::library_w(640.) < crate::library_w(1280.));
2996}
2997
2998#[test]
2999fn the_window_is_named_after_the_program_and_what_is_open() {
3000 assert_eq!(window_title("test_av.mp4"), "test_av.mp4 — edith");
3001 // An empty window is the program, not "no file open — edith".
3002 assert_eq!(window_title(NO_FILE), "edith");
3003}
3004
3005#[test]
3006fn frac_along_measures_from_the_elements_own_left_edge() {
3007 // A ruler inset by the panel's 12 px padding: window x is not bar x.
3008 let bar: Bounds<Pixels> = Bounds {
3009 origin: point(px(12.), px(400.)),
3010 size: size(px(200.), px(6.)),
3011 };
3012 assert_eq!(frac_along(px(12.), bar), 0.);
3013 assert_eq!(frac_along(px(112.), bar), 0.5);
3014 assert_eq!(frac_along(px(212.), bar), 1.);
3015 // Outside the bar (a click that slid off) clamps, never extrapolates.
3016 assert_eq!(frac_along(px(0.), bar), 0.);
3017 assert_eq!(frac_along(px(9999.), bar), 1.);
3018 // Never painted: no division by zero, no NaN reaching seek().
3019 assert_eq!(frac_along(px(50.), Bounds::default()), 0.);
3020
3021 // The equalizer's axis is the other one, and reads the same way.
3022 let graph: Bounds<Pixels> = Bounds {
3023 origin: point(px(12.), px(60.)),
3024 size: size(px(296.), px(EQ_GRAPH_H)),
3025 };
3026 assert_eq!(frac_down(px(60.), graph), 0.);
3027 assert_eq!(frac_down(px(60. + EQ_GRAPH_H / 2.), graph), 0.5);
3028 assert_eq!(frac_down(px(9999.), graph), 1.);
3029 // Never painted reads as flat: an unpainted graph must not slam a band
3030 // to +12 dB on the first press.
3031 assert_eq!(frac_down(px(50.), Bounds::default()), 0.5);
3032}
3033
3034/// A fade handle's pixels turn into frames at the bed's own scale, and a
3035/// degenerate scale (nothing painted) turns into no movement at all.
3036#[test]
3037fn a_fade_drag_converts_pixels_to_frames_at_the_beds_scale() {
3038 use crate::timeline_math::fade_delta_frames;
3039 // 100 px/s at 25 fps: one second of pixels is one second of frames.
3040 assert_eq!(fade_delta_frames(100., 100., 25.), 25);
3041 // Signed: dragging back shrinks the fade by the same conversion.
3042 assert_eq!(fade_delta_frames(-50., 100., 25.), -13);
3043 // Nothing drawn to drag against moves nothing.
3044 assert_eq!(fade_delta_frames(40., 0., 25.), 0);
3045 assert_eq!(fade_delta_frames(40., -1., 25.), 0);
3046}
3047
3048/// The cut odometer (DESIGN.md §6): `,` `.` walk it one cut at a time, shift
3049/// strides ten, and either end holds rather than wrapping.
3050#[test]
3051fn walk_cut_strides_and_clamps_at_either_end() {
3052 use crate::timeline_math::walk_cut;
3053 assert_eq!(walk_cut(3, 10, true, 1), 4);
3054 assert_eq!(walk_cut(3, 10, false, 1), 2);
3055 assert_eq!(walk_cut(3, 10, true, 10), 9, "clamps at the last cut");
3056 assert_eq!(walk_cut(3, 10, false, 10), 0, "clamps at the first cut");
3057 assert_eq!(walk_cut(9, 10, true, 1), 9, "already at the end holds");
3058 assert_eq!(walk_cut(0, 10, false, 1), 0, "already at the start holds");
3059 // No cuts at all: nothing to land on.
3060 assert_eq!(walk_cut(0, 0, true, 1), 0);
3061}
3062
3063/// The no-aim trim (DESIGN.md §6): a frame detent clamped to the room the
3064/// engine already answered, in either direction, and never past it.
3065#[test]
3066fn nudge_edge_moves_one_frame_and_clamps_to_the_room() {
3067 use crate::timeline_math::nudge_edge;
3068 assert_eq!(nudge_edge(50, 1, 0, 100), 51);
3069 assert_eq!(nudge_edge(50, -1, 0, 100), 49);
3070 assert_eq!(nudge_edge(0, -1, 0, 100), 0, "the room's own floor holds");
3071 assert_eq!(
3072 nudge_edge(100, 1, 0, 100),
3073 100,
3074 "the room's own ceiling holds"
3075 );
3076 // A 4px-wide clip's room can be one frame wide: still clamps, never
3077 // panics on the narrow end.
3078 assert_eq!(nudge_edge(5, 1, 5, 5), 5);
3079}
3080
3081/// Loop-trim's restart (DESIGN.md §6): only once the window's far edge is
3082/// reached, and never with the mode off.
3083#[test]
3084fn should_loop_restart_only_at_the_windows_far_edge() {
3085 use crate::timeline_math::should_loop_restart;
3086 assert!(!should_loop_restart(40, Some((30, 60))));
3087 assert!(should_loop_restart(60, Some((30, 60))));
3088 assert!(
3089 should_loop_restart(61, Some((30, 60))),
3090 "past it restarts too"
3091 );
3092 assert!(
3093 !should_loop_restart(60, None),
3094 "loop-trim off restarts nothing"
3095 );
3096}
3097
3098/// The paused-then-started repro this predicate was blamed for and cleared
3099/// of: `should_loop_restart` takes no play/pause state at all, so resting
3100/// exactly at the window's far edge -- as a transport paused after playing
3101/// through the cut once, or paused right on arrival by a scrub -- reads
3102/// "restart" from the predicate alone regardless. The bug that froze a
3103/// paused-then-`space`d transport at the loop's start frame was not this: it
3104/// was `Player::toggle_loop_trim` forcing `session.play()` on arm, so the
3105/// user's own next `space` toggled straight back to paused. It is
3106/// `Player::pump`'s `session.is_playing()` guard around this call that must
3107/// hold a paused transport off the seek until playback actually starts.
3108#[test]
3109fn should_loop_restart_is_play_state_blind_the_pump_gates_it() {
3110 use crate::timeline_math::should_loop_restart;
3111 assert!(
3112 should_loop_restart(60, Some((30, 60))),
3113 "the predicate alone can't tell paused-at-the-edge from playing-\
3114 into-it -- that distinction is pump's is_playing() guard, not this"
3115 );
3116}
3117
3118/// This binary has no `TestAppContext` to press a live escape through, so the
3119/// guard reads the ordering `render.rs`'s key listener actually runs: every
3120/// card/menu/list close returns before the fallthrough that dispatches
3121/// `ActionId::Deselect` ever runs, so escape with one of them open closes it
3122/// and never touches `self.selected` -- the picks made before the card opened
3123/// are still there once it is gone.
3124#[test]
3125fn escape_closes_a_card_before_it_can_ever_reach_deselect() {
3126 // The legacy handler this test named (`render.rs`) is gone; the same
3127 // ordering now lives in the darkroom's own root key handler
3128 // (`ui::stance::render`'s `on_key_down`). Player fullscreen is no
3129 // longer a "picture-only" layout escape leaves a special way -- it is
3130 // real OS fullscreen now (`ActionId::Fullscreen`, toggled on `f11`),
3131 // so that guard has nothing left to name here.
3132 let stance_rs = src_text("ui/stance.rs");
3133 let dispatch = stance_rs
3134 .find("if let Some(action) = this.keymap.lookup(key, ctrl, shift, alt) {")
3135 .expect("the keymap fallthrough that fires Deselect");
3136 for (guard, label) in [
3137 ("this.text_field_key(event, window, cx)", "the open text fields (one dispatch point)"),
3138 (
3139 "if this.param_card_key(key, event.keystroke.modifiers.shift, cx) {",
3140 "a param card",
3141 ),
3142 (
3143 "if this.card_open()",
3144 "a card (keys overlay/export/eq/color/...)",
3145 ),
3146 (
3147 "|| this.context_menu.is_some()",
3148 "the clip/row menu or a list",
3149 ),
3150 (
3151 "if key == ESCAPE && !ctrl && this.preview_session.is_some() {",
3152 "an open preview",
3153 ),
3154 ] {
3155 let at = stance_rs
3156 .find(guard)
3157 .unwrap_or_else(|| panic!("{label}'s own escape guard moved or was renamed"));
3158 assert!(
3159 at < dispatch,
3160 "{label}'s guard reads after the Deselect dispatch -- escape would \
3161 clear the selection before this card ever got a look at the key"
3162 );
3163 }
3164}
3165
3166/// A refused split is not an edit, so it may not drop the clip in hand: the
3167/// refused stroke is worded ("Nothing to split — the playhead is already on a
3168/// cut") and the pick is still what the next `x`, `delete` or clip-menu row acts
3169/// on. The clear rides the door's own answer, the way [`Player::regroup`]'s
3170/// always has -- a split that happened is the other way round: the seam it
3171/// leaves renumbers the lane, so a pick kept across it names the wrong clip.
3172///
3173/// A scan and not a drive: `self.selected` lives on `Player`, which needs a gpui
3174/// `Context` this binary has no harness for. The state itself is driven in
3175/// `the_playhead_actions_still_work_with_a_caption_marked`, which holds the real
3176/// `cut_at` refusal this gate is about.
3177#[test]
3178fn a_refused_split_keeps_the_clip_in_hand() {
3179 let body = fn_body("cut");
3180 let (before, after) = body
3181 .split_once("if cut {")
3182 .expect("the split door no longer gates anything on its own answer");
3183 // The door's own branch, cut apart at its `else`: "runs after `if cut {`" is
3184 // satisfied by the shape this fix replaced as well, because the clear sat
3185 // below the whole if/else and so inside everything that followed the gate --
3186 // a revert of the fix would have shipped green. What the arm has to be is
3187 // inside the then-branch, and nothing that follows the branch may hold one.
3188 let then = after
3189 .split_once("} else {")
3190 .expect("the split door no longer branches on what the cut answered")
3191 .0;
3192 // One arm's worth of clear, counted with `matches`: `split(..).count()`
3193 // counts the pieces *between* matches, so a single occurrence reads as two
3194 // there and the guard fails on the fix it is guarding.
3195 let extra_clear = after.matches("self.selected.clear()").count() > 1;
3196 assert!(
3197 !before.contains("self.selected.clear()"),
3198 "the split drops the selection before it knows the cut happened, so a \
3199 refused split leaves the user with nothing picked and nothing told"
3200 );
3201 assert!(
3202 then.contains("self.selected.clear()") && !extra_clear,
3203 "the clear does not ride the split's own success branch: a split that \
3204 happened leaves the mark naming a different clip across the seam, and a \
3205 refused one must leave it naming the clip it named"
3206 );
3207}
3208
3209/// The other half: with nothing on screen to claim the key, bare escape falls
3210/// all the way through to `Player::act`, whose `ActionId::Deselect` arm is
3211/// the one place `self.selected` is emptied by a bare stroke rather than by
3212/// picking something else.
3213#[test]
3214fn escape_with_nothing_open_empties_the_selection() {
3215 let actions_rs = src_text("player/actions.rs");
3216 let view_rs = src_text("player/view.rs");
3217 assert!(
3218 actions_rs.contains("ActionId::Deselect => self.clear_picks(cx),")
3219 && view_rs.contains("self.selected = Selection::new();"),
3220 "the Deselect arm no longer clears the selection through clear_picks"
3221 );
3222 let k = keymap::Keymap::defaults();
3223 assert_eq!(
3224 k.lookup("escape", false, false, false),
3225 Some(ActionId::Deselect),
3226 "bare escape must still route to Deselect for that arm to ever run"
3227 );
3228}
3229
3230/// The gate that keeps "option C" honest. The spine rail is gone -- nothing on
3231/// screen lists these verbs any more -- so every verb it used to carry has to
3232/// be a row on the menu of the thing it acts on, or it is a verb only a person
3233/// who already knows its chord can reach. Listed by action id rather than by
3234/// label, so a reworded row cannot make this pass while the door is gone.
3235///
3236/// And the rule line's own half of DESIGN §9: the destructive rows come last
3237/// in every list here, which is what lets the render draw one seam before the
3238/// first of them instead of scattering seams through the plate.
3239#[test]
3240fn every_verb_the_spine_carried_is_a_right_click_row() {
3241 use keymap::ActionId;
3242 // The heads a project can have, so the removes are checked on the lane
3243 // each of them belongs to.
3244 let heads: Vec<ActionId> = [Lane::V1, Lane::A1, Lane::S1]
3245 .into_iter()
3246 .flat_map(lane_items)
3247 .collect();
3248 for (action, menu) in [
3249 // EDIT
3250 (ActionId::Cut, "clip"),
3251 (ActionId::Lift, "clip"),
3252 (ActionId::Undo, "bench"),
3253 (ActionId::Redo, "bench"),
3254 // CUT
3255 (ActionId::WalkCutPrev, "bench"),
3256 (ActionId::WalkCutNext, "bench"),
3257 (ActionId::WalkCutPrev10, "bench"),
3258 (ActionId::WalkCutNext10, "bench"),
3259 (ActionId::TrimIn, "clip"),
3260 (ActionId::TrimOut, "clip"),
3261 // The trim-to-playhead pair is *not* in this list: `^[` and `^]` are
3262 // the keyboard's version of dragging a clip edge to a spot, a gesture
3263 // the pointer already has, so the clip menu leaves them out (DESIGN §9,
3264 // "Never a junk drawer"). They keep their chords and their KEYS rows,
3265 // which is what the layout sweep's exemption for them names.
3266 (ActionId::LoopTrim, "clip"),
3267 // VIEW
3268 (ActionId::ZoomOut, "bench"),
3269 (ActionId::ZoomIn, "bench"),
3270 (ActionId::ZoomFit, "bench"),
3271 (ActionId::ToggleSnap, "bench"),
3272 // TRACK
3273 (ActionId::AddVideoLane, "lane head"),
3274 (ActionId::AddAudioLane, "lane head"),
3275 (ActionId::AddSubtitleLane, "lane head"),
3276 (ActionId::RemoveVideoLane, "lane head"),
3277 (ActionId::RemoveAudioLane, "lane head"),
3278 (ActionId::RemoveSubtitleLane, "lane head"),
3279 ] {
3280 assert!(
3281 MENU_ITEMS.contains(&action)
3282 || BENCH_ITEMS.contains(&action)
3283 || heads.contains(&action),
3284 "{action:?} reaches no menu: the spine listed it and the {menu} menu does not"
3285 );
3286 }
3287 // Every menu is a list of actions the keyboard already reaches, so every
3288 // row can wear its chord (DESIGN §4): a row built here out of an id the
3289 // registry never files would print an empty column.
3290 for action in MENU_ITEMS
3291 .into_iter()
3292 .chain(BENCH_ITEMS)
3293 .chain(heads.iter().copied())
3294 {
3295 assert!(
3296 ActionId::ALL.contains(&action),
3297 "{action:?} is a menu row and not a registered action"
3298 );
3299 }
3300 for list in [
3301 MENU_ITEMS.to_vec(),
3302 BENCH_ITEMS.to_vec(),
3303 lane_items(Lane::A1),
3304 ] {
3305 let first = list.iter().position(|&a| destructive(a));
3306 if let Some(first) = first {
3307 assert!(
3308 list[first..].iter().all(|&a| destructive(a)),
3309 "a safe row sits below the rule line: {list:?}"
3310 );
3311 }
3312 }
3313}
3314
3315/// The first import into an empty timeline is placed on it, and that placement
3316/// is one undo step: the library line that stands behind it is not. What
3317/// `take_import` does for a file that lands on an empty timeline, minus the
3318/// window (DESIGN §7).
3319#[test]
3320fn a_first_import_placed_on_an_empty_timeline_is_one_undo_step() {
3321 let mut session =
3322 PlaybackSession::open_library(asset("test_av.mp4")).expect("open the fixture");
3323 session.set_gain(0.0);
3324 assert!(
3325 session.is_empty(),
3326 "the library holds the file, the lanes do not"
3327 );
3328 let path = session.sources()[0].path.clone();
3329 assert!(
3330 session
3331 .place_stream_at(0.0, &path, 0, None)
3332 .expect("the file is on this timeline")
3333 );
3334 assert!(!session.is_empty());
3335 assert_eq!(session.timeline_duration(), 5.0);
3336 assert!(session.undo(), "the placement is an undo step");
3337 assert!(session.is_empty(), "undo takes the placement back");
3338 assert!(!session.undo(), "the import itself is not an undo step");
3339}
3340
3341/// DESIGN §7's gap door, below the window: a picked hole is what Delete
3342/// closes, one undo step gives it back, and an undo that takes the hole away
3343/// leaves a pick that no longer names one.
3344#[test]
3345fn a_picked_gap_closes_in_one_undo_step_and_a_stale_pick_is_dropped() {
3346 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
3347 session.set_gain(0.0);
3348 let path = session.sources()[0].path.clone();
3349 let c0 = session.lane_clips(Lane::V1)[0].clone();
3350 assert!(
3351 session
3352 .place_stream_at(20.0, &path, 0, None)
3353 .expect("test_av.mp4 is on this timeline")
3354 );
3355 let c1 = session.lane_clips(Lane::V1)[1].clone();
3356 let (start, frames) = (c0.end(), c1.start - c0.end());
3357 assert!(
3358 frames > 0,
3359 "the second placement leaves a hole behind the first"
3360 );
3361 let pick = GapPick {
3362 lane: Lane::V1,
3363 start,
3364 frames,
3365 };
3366 assert_eq!(live_gap(&session, pick), Some(pick));
3367
3368 // Delete's door: the same close a right-click gives, and the ripple moves
3369 // the placement after the hole.
3370 let scope = session
3371 .gap_take_scope(Lane::V1, start, frames)
3372 .expect("a scope");
3373 session
3374 .cut_regions(&[(start, frames)], &scope)
3375 .expect("the hole closes");
3376 assert_eq!(live_gap(&session, pick), None, "a closed hole is no hole");
3377 assert!(session.lane_clips(Lane::V1)[1].start < c1.start);
3378 assert!(session.undo(), "the close is one undo step");
3379 assert_eq!(session.lane_clips(Lane::V1)[1].start, c1.start);
3380 assert_eq!(live_gap(&session, pick), Some(pick));
3381
3382 // An undo that takes the placement away takes the hole with it.
3383 assert!(session.undo(), "the placement is undoable");
3384 assert_eq!(session.lane_clips(Lane::V1).len(), 1);
3385 assert_eq!(live_gap(&session, pick), None);
3386}
3387
3388/// Delete over a picked gap is live with nothing marked; the clip-only rows
3389/// beside it stay refused.
3390#[test]
3391fn delete_is_enabled_over_a_picked_gap() {
3392 let gap = Ctx {
3393 gap: true,
3394 timeline: true,
3395 ..Ctx::default()
3396 };
3397 assert_eq!(enable(ActionId::Delete, gap.clone()), Enable::Yes);
3398 let bare = Ctx {
3399 timeline: true,
3400 ..Ctx::default()
3401 };
3402 assert!(matches!(enable(ActionId::Delete, bare), Enable::No(_)));
3403 assert!(matches!(enable(ActionId::Copy, gap), Enable::No(_)));
3404}
3405
3406/// The ledger's gap readout: both ends as timecodes and the length in seconds.
3407#[test]
3408fn the_gap_readout_names_both_ends_and_the_length() {
3409 assert_eq!(
3410 gap_readout(100, 62, 25.0),
3411 "Gap · 2.5 s · starts at 0:04"
3412 );
3413}
3414
3415/// The ledger's clip readout (DESIGN §6.9): the source's stem, the clip's
3416/// first and last frame as timecodes and its length in seconds.
3417#[test]
3418fn the_clip_readout_names_the_source_both_ends_and_the_length() {
3419 assert_eq!(
3420 clip_readout("city_dusk", 0, 285, 30.0),
3421 "city_dusk · 9.5 s · starts at 0:00"
3422 );
3423}
3424
3425/// The status bar's frame rate: whole rates lose their decimals, fractional
3426/// ones keep two.
3427#[test]
3428fn the_status_bar_writes_a_frame_rate_without_trailing_zeros() {
3429 assert_eq!(fps_label(30.0), "30");
3430 assert_eq!(fps_label(29.97), "29.97");
3431 assert_eq!(fps_label(24.0), "24");
3432}
3433
3434/// DESIGN §7: a locked lane refuses the edits to its items, and the oracle says
3435/// why in the words the toast uses. Selection, playback and the editor's own
3436/// switches are not edits and stay live.
3437#[test]
3438fn a_locked_lane_refuses_its_edits_with_the_lock_reason() {
3439 use keymap::ActionId;
3440 let locked = Ctx {
3441 timeline: true,
3442 locked: true,
3443 playable: true,
3444 ..Ctx::default()
3445 };
3446 for edit in [
3447 ActionId::Cut,
3448 ActionId::Delete,
3449 ActionId::Lift,
3450 ActionId::Paste,
3451 ActionId::Crossfade,
3452 ActionId::TrimIn,
3453 ActionId::Mix,
3454 ] {
3455 assert_eq!(
3456 enable(edit, locked.clone()),
3457 Enable::No("The track is locked"),
3458 "{edit:?} changes a locked lane's item",
3459 );
3460 }
3461 assert_eq!(enable(ActionId::Play, locked.clone()), Enable::Yes);
3462 assert_eq!(enable(ActionId::ToggleSnap, locked.clone()), Enable::Yes);
3463 // Unlocked, the same question is the one it always was: with nothing marked,
3464 // Delete says there is nothing to delete, not that a lock is on.
3465 let open = Ctx {
3466 locked: false,
3467 ..locked
3468 };
3469 assert_eq!(
3470 enable(ActionId::Delete, open),
3471 Enable::No("nothing selected")
3472 );
3473}
3474
3475/// An insert onto a locked lane is refused with the lock's own toast before it
3476/// places anything. The auto-pick is the same question: with no lane named the
3477/// insert writes `V1` and `A1` (or `A1` alone for a song), and the lock is asked
3478/// about each of those. Needs a window to run, so the pick and the order of the
3479/// door are pinned here from the source.
3480#[test]
3481fn an_insert_onto_a_locked_lane_is_refused_with_the_lock_reason() {
3482 let picture = Path::new("/media/clip.mp4");
3483 let song = Path::new("/media/song.mp3");
3484 let still = Path::new("/media/still.png");
3485 assert_eq!(
3486 crate::Player::insert_lanes(picture, None),
3487 vec![Lane::V1, Lane::A1],
3488 "an unnamed picture is the grouped take on V1 and A1"
3489 );
3490 assert_eq!(crate::Player::insert_lanes(song, None), vec![Lane::A1]);
3491 assert_eq!(crate::Player::insert_lanes(still, None), vec![Lane::V1]);
3492 let v2 = Lane::new(LaneKind::Video, 1);
3493 let a2 = Lane::new(LaneKind::Audio, 1);
3494 assert_eq!(
3495 crate::Player::insert_lanes(picture, Some(v2)),
3496 vec![v2, a2],
3497 "a picture named onto V2 takes its sound on A2"
3498 );
3499 assert_eq!(crate::Player::insert_lanes(song, Some(a2)), vec![a2]);
3500
3501 let body = fn_body("place_source");
3502 let door = body
3503 .find("lane_locked_refusal(")
3504 .expect("insert_source asks the lock");
3505 let place = body
3506 .find("session.place_stream_at(")
3507 .expect("insert_source places the stream");
3508 assert!(
3509 body.contains("Self::insert_lanes(path, onto)") && door < place,
3510 "insert_source places the stream before it asks whether the lane is locked"
3511 );
3512 assert!(
3513 fn_body("lane_locked_refusal").contains("is locked"),
3514 "the refusal must say the lane is locked"
3515 );
3516}
3517
3518/// The lock's refusals are the Player's, and they need a window to run, so the
3519/// doors are pinned by their source: each edit entry point asks the one lock
3520/// helper before it touches the timeline, and the toast offers the way out.
3521#[test]
3522fn every_edit_door_asks_the_lock_before_it_touches_the_timeline() {
3523 for func in [
3524 "move_clip_now",
3525 "move_sub",
3526 "place_sub",
3527 "lift_sub",
3528 "start_trim",
3529 "start_pro",
3530 "cut",
3531 "delete_selected",
3532 "lift_selected",
3533 "paste",
3534 "place_source",
3535 ] {
3536 assert!(
3537 fn_body(func).contains("lane_locked_refusal(")
3538 || fn_body(func).contains("marked_locked_lane()"),
3539 "{func} edits a lane without asking whether it is locked"
3540 );
3541 }
3542 for func in ["select", "pick"] {
3543 assert!(
3544 fn_body(func).contains("lane_locked_refusal(target.0)"),
3545 "{func} selects an item on a locked lane"
3546 );
3547 }
3548 let stance = src_text("ui/stance.rs");
3549 assert!(
3550 stance.contains("ToastAction::Unlock(_) => \"Unlock\""),
3551 "the locked toast has no Unlock button"
3552 );
3553 assert!(
3554 src_text("player/actions.rs").contains("ToastAction::Unlock(lane) =>"),
3555 "the Unlock button does nothing"
3556 );
3557}
3558
3559/// The inline cue editor ends on a press anywhere outside its plate, as Enter
3560/// does: the root hears the press, and the plate stops its own presses from
3561/// reaching it. Pinned on source, since a window is not available here.
3562#[test]
3563fn a_press_off_the_cue_plate_commits_the_edit_and_a_press_on_it_does_not() {
3564 let root = src_text("ui/stance.rs");
3565 assert!(
3566 root.contains("cx.listener(Player::cue_edit_press_outside)"),
3567 "the root does not commit an open cue edit on a press"
3568 );
3569 assert!(
3570 src_text("player/timeline_edit.rs")
3571 .contains("if self.cue_edit.is_some() {\n self.commit_cue_edit(cx);"),
3572 "a press outside the plate does not commit the open edit"
3573 );
3574 let plate = src_text("ui/bench_stance/sub.rs");
3575 let start = plate
3576 .find("fn cue_edit_plate(")
3577 .expect("the cue edit plate");
3578 assert!(
3579 plate[start..].contains("cx.stop_propagation()"),
3580 "the cue edit plate lets its own presses reach the root"
3581 );
3582}
3583
3584// ---- three-point edits from the library (F9 insert, F10 overwrite) ----
3585
3586fn ask<'a>(lanes: &'a [(Lane, bool)]) -> crate::SourceEditAsk<'a> {
3587 crate::SourceEditAsk {
3588 fps: 30.0,
3589 lanes,
3590 playhead: 60,
3591 range: None,
3592 marks: (None, None),
3593 source: 1,
3594 total: 150,
3595 picture: true,
3596 sound: true,
3597 still: false,
3598 video_patch: None,
3599 audio_patch: None,
3600 }
3601}
3602
3603/// The plan reads the marks the way an editor does: the source's own in..out
3604/// when marked, the whole item when not, at the playhead.
3605#[test]
3606fn the_plan_is_the_marked_range_at_the_playhead() {
3607 let lanes = [(Lane::V1, false), (Lane::A1, false)];
3608 let (at, items) = crate::plan_source_edit(&ask(&lanes)).expect("plans");
3609 assert_eq!(at, 60);
3610 let shape: Vec<_> = items.iter().map(|(l, c)| (*l, c.source, c.in_frame, c.out_frame)).collect();
3611 assert_eq!(shape, vec![(Lane::V1, 1, 0, 150), (Lane::A1, 1, 0, 150)], "no marks: the whole item");
3612 let marked = crate::SourceEditAsk { marks: (Some(1.0), Some(2.5)), ..ask(&lanes) };
3613 let (_, items) = crate::plan_source_edit(&marked).expect("plans");
3614 assert!(items.iter().all(|(_, c)| (c.in_frame, c.out_frame) == (30, 75)));
3615 // An out mark past the file is held to its end; an in mark alone runs to the end.
3616 let tail = crate::SourceEditAsk { marks: (Some(4.0), None), ..ask(&lanes) };
3617 let (_, items) = crate::plan_source_edit(&tail).expect("plans");
3618 assert!(items.iter().all(|(_, c)| (c.in_frame, c.out_frame) == (120, 150)));
3619 let empty = crate::SourceEditAsk { marks: (Some(2.0), Some(2.0)), ..ask(&lanes) };
3620 assert!(crate::plan_source_edit(&empty).is_err());
3621 // The source patch sends each half to its own lane, when that lane is there.
3622 let (v2, a2) = (Lane::new(LaneKind::Video, 1), Lane::new(LaneKind::Audio, 1));
3623 let lanes = [(Lane::V1, false), (Lane::A1, false), (v2, false), (a2, false)];
3624 let patched = crate::SourceEditAsk { video_patch: Some(v2), audio_patch: Some(a2), ..ask(&lanes) };
3625 let (_, items) = crate::plan_source_edit(&patched).expect("plans");
3626 let lanes_hit: Vec<_> = items.iter().map(|(l, _)| *l).collect();
3627 assert_eq!(lanes_hit, vec![v2, a2]);
3628}
3629
3630/// Classic three-point: the source's in plus the timeline's in and out. The
3631/// timeline's in mark is where it lands, its length is how long; a source out
3632/// mark wins the length when both are set.
3633#[test]
3634fn the_timeline_range_sets_where_and_how_long_when_the_source_has_no_out() {
3635 let lanes = [(Lane::V1, false), (Lane::A1, false)];
3636 let three = crate::SourceEditAsk { range: Some((90, 120)), marks: (Some(1.0), None), ..ask(&lanes) };
3637 let (at, items) = crate::plan_source_edit(&three).expect("plans");
3638 assert_eq!(at, 90);
3639 assert!(items.iter().all(|(_, c)| (c.in_frame, c.out_frame) == (30, 60)));
3640 let both = crate::SourceEditAsk { range: Some((90, 120)), marks: (Some(1.0), Some(3.0)), ..ask(&lanes) };
3641 let (at, items) = crate::plan_source_edit(&both).expect("plans");
3642 assert_eq!(at, 90);
3643 assert!(items.iter().all(|(_, c)| (c.in_frame, c.out_frame) == (30, 90)));
3644}
3645
3646/// The first unlocked lane of each kind takes its half; a sound-only item and a
3647/// still take their one lane; every lane locked refuses by name.
3648#[test]
3649fn the_plan_picks_the_first_unlocked_lanes() {
3650 let v2 = Lane::new(LaneKind::Video, 1);
3651 let a2 = Lane::new(LaneKind::Audio, 1);
3652 let lanes = [(Lane::V1, true), (Lane::A1, false), (v2, false), (a2, false)];
3653 let (_, items) = crate::plan_source_edit(&ask(&lanes)).expect("plans");
3654 assert_eq!(items.iter().map(|(l, _)| *l).collect::<Vec<_>>(), vec![v2, Lane::A1]);
3655 let song = crate::SourceEditAsk { picture: false, ..ask(&lanes) };
3656 let (_, items) = crate::plan_source_edit(&song).expect("plans");
3657 assert_eq!(items.len(), 1);
3658 assert_eq!(items[0].0, Lane::A1);
3659 let still = crate::SourceEditAsk { picture: true, sound: false, still: true, total: 1, ..ask(&lanes) };
3660 let (_, items) = crate::plan_source_edit(&still).expect("plans");
3661 assert_eq!((items[0].0, items[0].1.out_frame), (v2, 150), "a still shows five seconds by default");
3662 let locked = [(Lane::V1, true), (Lane::A1, true)];
3663 assert!(crate::plan_source_edit(&ask(&locked)).unwrap_err().contains("locked"));
3664}
3665
3666/// The whole chain minus the keys: plan the marked range, then the engine edit.
3667/// An insert in the middle of the first take cuts and ripples it; an overwrite
3668/// replaces and moves nothing; each is one undo step.
3669#[test]
3670fn insert_and_overwrite_run_the_plan_through_the_engine_and_undo_in_one_step() {
3671 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
3672 session.set_gain(0.0);
3673 session.import(&asset("test_av2.mp4")).expect("av2 matches");
3674 let lanes: Vec<(Lane, bool)> = [Lane::V1, Lane::A1].into_iter().map(|l| (l, false)).collect();
3675 let before = (session.lane_clips(Lane::V1).to_vec(), session.lane_clips(Lane::A1).to_vec());
3676 let marked = crate::SourceEditAsk {
3677 playhead: 60,
3678 marks: (Some(1.0), Some(2.0)),
3679 total: session.file_frames(&session.sources()[1].path.clone()),
3680 ..ask(&lanes)
3681 };
3682 let (at, items) = crate::plan_source_edit(&marked).expect("plans");
3683 session
3684 .edit_from_source_at(engine::SourceEdit::Insert, f64::from(at) / 30.0, &items)
3685 .expect("inserts");
3686 let spans = |lane| {
3687 session.lane_clips(lane).iter().map(|c| (c.start, c.end(), c.source)).collect::<Vec<_>>()
3688 };
3689 assert_eq!(spans(Lane::V1), vec![(0, 60, 0), (60, 90, 1), (90, 180, 0)]);
3690 assert_eq!(spans(Lane::A1), spans(Lane::V1), "the sound went in with the picture");
3691 assert!(session.undo());
3692 assert_eq!((session.lane_clips(Lane::V1).to_vec(), session.lane_clips(Lane::A1).to_vec()), before);
3693 session
3694 .edit_from_source_at(engine::SourceEdit::Overwrite, f64::from(at) / 30.0, &items)
3695 .expect("overwrites");
3696 let spans = |lane| {
3697 session.lane_clips(lane).iter().map(|c| (c.start, c.end(), c.source)).collect::<Vec<_>>()
3698 };
3699 assert_eq!(spans(Lane::V1), vec![(0, 60, 0), (60, 90, 1), (90, 150, 0)]);
3700 assert!(session.undo());
3701 // A locked lane refuses with its name and costs no undo step.
3702 assert!(session.set_lane_locked(Lane::A1, true));
3703 let err = session
3704 .edit_from_source_at(engine::SourceEdit::Insert, 2.0, &items)
3705 .expect_err("A1 is locked");
3706 assert!(err.to_string().contains("A1 is locked"), "{err}");
3707}
3708
3709/// F9 and F10 are free (the comma and the period already walk the cuts), `I`
3710/// and `O` mark the previewed item while one is up, and the palette and the
3711/// keys card list both actions by name.
3712#[test]
3713fn the_source_edits_have_keys_marks_and_a_menu() {
3714 let keys = keymap::Keymap::defaults();
3715 assert_eq!(keys.lookup("f9", false, false, false), Some(ActionId::InsertSource));
3716 assert_eq!(keys.lookup("f10", false, false, false), Some(ActionId::OverwriteSource));
3717 assert_eq!(keys.lookup(".", false, false, false), Some(ActionId::WalkCutNext));
3718 assert_eq!(keys.lookup(",", false, false, false), Some(ActionId::WalkCutPrev));
3719 assert_eq!(ActionId::InsertSource.label(), "Insert source at playhead");
3720 assert_eq!(ActionId::OverwriteSource.label(), "Overwrite source at playhead");
3721 let act = source_from("pub(crate) fn act(");
3722 for arm in [
3723 "ActionId::SetIn if self.preview_session.is_some() => self.mark_source(true, cx)",
3724 "ActionId::SetOut if self.preview_session.is_some() => self.mark_source(false, cx)",
3725 "ActionId::ClearRange if self.preview_session.is_some() => self.clear_source_marks(cx)",
3726 "ActionId::InsertSource => self.source_edit(engine::SourceEdit::Insert, cx)",
3727 "ActionId::OverwriteSource => self.source_edit(engine::SourceEdit::Overwrite, cx)",
3728 ] {
3729 assert!(act.contains(arm), "act() lacks `{arm}`");
3730 }
3731 assert!(
3732 ui_source().contains("Act(ActionId::InsertSource)")
3733 && ui_source().contains("Act(ActionId::OverwriteSource)"),
3734 "the Edit menu carries both"
3735 );
3736 let rows = keys_rows();
3737 for a in [ActionId::InsertSource, ActionId::OverwriteSource] {
3738 assert!(rows.iter().any(|r| matches!(r, KeyRow::Act(x) if *x == a)), "{a:?} is on the keys card");
3739 }
3740 assert!(fn_body("source_edit_at").contains("edit_from_source_at("));
3741}
3742
3743/// The comment markers' doors: every one of the four actions has a stroke that is not a
3744/// taken one (bare `m` is the mute and stays it), a row on the ruler's right-click menu
3745/// and one in the Timeline menu, and the oracle answers them like the rest of the
3746/// timeline's actions -- live with a timeline, refused without.
3747#[test]
3748fn the_marker_actions_have_free_keys_menu_rows_and_an_oracle_answer() {
3749 use keymap::ActionId;
3750 let keymap = keymap::Keymap::defaults();
3751 assert_eq!(keymap.lookup("m", false, false, false), Some(ActionId::ToggleMute));
3752 assert_eq!(keymap.lookup("m", false, false, true), Some(ActionId::AddMarker));
3753 assert_eq!(keymap.lookup("m", false, true, false), Some(ActionId::NextMarker));
3754 assert_eq!(keymap.lookup("m", true, true, false), Some(ActionId::PrevMarker));
3755 assert_eq!(keymap.lookup("8", false, false, true), Some(ActionId::Markers));
3756 let mut chords: Vec<String> = keymap.entries().iter().map(|b| b.chord.pretty()).collect();
3757 let all = chords.len();
3758 chords.sort();
3759 chords.dedup();
3760 assert_eq!(chords.len(), all, "a default chord is bound twice");
3761 let timeline = Ctx { timeline: true, playable: true, ..Ctx::default() };
3762 assert!(BENCH_ITEMS.contains(&ActionId::MarkerHere), "the ruler menu drops a marker at the frame it names");
3763 for action in [ActionId::NextMarker, ActionId::PrevMarker, ActionId::Markers] {
3764 assert!(BENCH_ITEMS.contains(&action), "{action:?} has no ruler menu row");
3765 assert!(
3766 crate::ui::menubar::Title::Timeline
3767 .entries()
3768 .contains(&crate::ui::menubar::Entry::Act(action)),
3769 "{action:?} has no Timeline menu row"
3770 );
3771 assert_eq!(enable(action, timeline.clone()), Enable::Yes, "{action:?}");
3772 assert!(
3773 matches!(enable(action, Ctx::default()), Enable::No(_)),
3774 "{action:?} needs a timeline"
3775 );
3776 }
3777}
3778
3779/// Roll, slip and slide through the doors the shift-drags and the keys end at
3780/// ([`Player::pro_apply`] calls exactly these): each is one undo step, the
3781/// timeline keeps its length, and a gesture that moves nothing takes no step.
3782#[test]
3783fn roll_slip_and_slide_reach_the_engine_as_one_undoable_edit_each() {
3784 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
3785 session.set_gain(0.0);
3786 assert!(session.cut_at(1.0) && session.cut_at(3.0));
3787 let full = session.timeline_duration();
3788 let spans = |s: &PlaybackSession, lane: Lane| {
3789 s.lane_clips(lane)
3790 .iter()
3791 .map(|c| (c.start, c.end(), c.in_frame))
3792 .collect::<Vec<_>>()
3793 };
3794 let before = spans(&session, Lane::V1);
3795 let depth = session.undo_depth();
3796
3797 // Roll: the cut after clip 0, one detent later; the take rolls with it.
3798 assert_eq!(session.roll_clip(Lane::V1, 0, 31), Some(31));
3799 assert_eq!(spans(&session, Lane::V1)[..2], [(0, 31, 0), (31, 90, 31)]);
3800 assert_eq!(spans(&session, Lane::A1)[..2], [(0, 31, 0), (31, 90, 31)]);
3801 assert_eq!(session.undo_depth(), depth + 1);
3802 assert_eq!(session.timeline_duration(), full);
3803 // Pulled past the neighbour it is held a frame short of it.
3804 let (_, hi) = session.roll_room(Lane::V1, 0).expect("a cut");
3805 assert_eq!(session.roll_clip(Lane::V1, 0, 9_999), Some(hi));
3806 assert!(session.undo() && session.undo());
3807 assert_eq!(spans(&session, Lane::V1), before);
3808
3809 // Slip: the window moves, the slot does not.
3810 let by = session.slip_source_delta(Lane::V1, 1, 5).expect("a video clip");
3811 assert_eq!(by, 5);
3812 assert_eq!(session.slip_clip(Lane::V1, 1, by), Some(5));
3813 assert_eq!(spans(&session, Lane::V1)[1], (30, 90, 35));
3814 assert_eq!(session.slip_clip(Lane::V1, 1, 0), Some(0), "nothing moved");
3815 assert_eq!(session.undo_depth(), depth + 1, "and no step was taken");
3816 assert!(session.undo());
3817
3818 // Slide: the clip moves, its neighbours give and take the frames.
3819 assert_eq!(session.slide_clip(Lane::V1, 1, 40), Some(40));
3820 assert_eq!(
3821 spans(&session, Lane::V1),
3822 [(0, 40, 0), (40, 100, 30), (100, 150, 100)]
3823 );
3824 assert_eq!(session.timeline_duration(), full);
3825 assert_eq!(session.slide_clip(Lane::V1, 0, 5), None, "no clip before it");
3826 assert!(session.undo());
3827 assert_eq!(spans(&session, Lane::V1), before);
3828}
3829
3830/// The keys and the shift-drags only land inside the engine's room: the
3831/// drag's arithmetic is a clamp, never a wrap or a negative frame.
3832#[test]
3833fn a_pro_trim_target_is_held_inside_the_rooms_the_engine_answered() {
3834 assert_eq!(crate::timeline_math::pro_target(30, 5, 1, 89), 35);
3835 assert_eq!(crate::timeline_math::pro_target(30, 500, 1, 89), 89);
3836 assert_eq!(crate::timeline_math::pro_target(30, -500, 1, 89), 1);
3837 assert_eq!(crate::timeline_math::pro_target(0, -3, 0, 10), 0);
3838}
3839
3840/// The oracle's answers for the six keys: a clip is needed, a still has no
3841/// more footage to slip, and a locked lane refuses all of them.
3842#[test]
3843fn the_pro_trim_actions_need_a_clip_refuse_stills_and_obey_locks() {
3844 use keymap::ActionId::*;
3845 let all = [RollBack, RollForward, SlipBack, SlipForward, SlideBack, SlideForward];
3846 let bare = Ctx {
3847 timeline: true,
3848 ..Ctx::default()
3849 };
3850 for action in all {
3851 assert_eq!(enable(action, bare.clone()), Enable::No("no clip is selected"), "{action:?}");
3852 }
3853 let session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
3854 let clip = session.lane_clips(Lane::V1)[0].clone();
3855 let on = Ctx {
3856 clip: Some((clip, Lane::V1)),
3857 ..bare.clone()
3858 };
3859 for action in all {
3860 assert_eq!(enable(action, on.clone()), Enable::Yes, "{action:?}");
3861 assert_eq!(
3862 enable(action, Ctx { locked: true, ..on.clone() }),
3863 Enable::No("The track is locked"),
3864 "{action:?}"
3865 );
3866 }
3867 let still = Ctx {
3868 image: true,
3869 ..on
3870 };
3871 assert_eq!(enable(SlipBack, still.clone()), Enable::Hidden("this clip is a still"));
3872 assert_eq!(enable(SlideBack, still), Enable::Yes);
3873}
3874
3875/// The default chords reach the six, and the shift-drags are wired where the
3876/// pointer lands: the body and the edge strips route a shift press to
3877/// `start_pro`, the gpui move-drag the body also starts is told to stand
3878/// down, and the root follows and commits the gesture. Source pins, since a
3879/// window is not available here.
3880#[test]
3881fn the_pro_trims_have_chords_and_shift_drags() {
3882 use keymap::ActionId::*;
3883 let keys = keymap::Keymap::defaults();
3884 for (key, action) in [
3885 ("[", RollBack),
3886 ("]", RollForward),
3887 (",", SlipBack),
3888 (".", SlipForward),
3889 ("left", SlideBack),
3890 ("right", SlideForward),
3891 ] {
3892 assert_eq!(keys.lookup(key, false, false, true), Some(action), "alt+{key}");
3893 }
3894 let clip = src_text("ui/bench_stance/clip.rs");
3895 assert!(clip.contains("event.modifiers.shift"), "the shift press is not read");
3896 assert!(clip.contains("ProKind::Roll") && clip.contains("ProKind::Slide"));
3897 assert!(fn_body("move_clip_now").contains("pro_drag.is_some()"));
3898 let edit = src_text("player/timeline_edit.rs");
3899 assert!(edit.contains("self.pro_to(event.position.x, cx)"));
3900 assert!(edit.contains("self.commit_pro(cx)"));
3901}
3902
3903/// The J/K/L shuttle: L and J start at 1x and double to 4x on a repeat, the
3904/// other key turns round at 1x, and a stopped transport starts at 1x.
3905#[test]
3906fn the_shuttle_steps_one_two_four_and_turns_round_at_one() {
3907 use crate::player::transport::shuttle_rate;
3908 assert_eq!(shuttle_rate(true, false, 1.0), 1.0, "L from rest");
3909 assert_eq!(shuttle_rate(false, false, 1.0), -1.0, "J from rest");
3910 assert_eq!(shuttle_rate(true, true, 1.0), 2.0);
3911 assert_eq!(shuttle_rate(true, true, 2.0), 4.0);
3912 assert_eq!(shuttle_rate(true, true, 4.0), 4.0, "4x is the top");
3913 assert_eq!(shuttle_rate(false, true, -1.0), -2.0);
3914 assert_eq!(shuttle_rate(false, true, -2.0), -4.0);
3915 assert_eq!(shuttle_rate(false, true, -4.0), -4.0);
3916 assert_eq!(shuttle_rate(false, true, 2.0), -1.0, "J while forward turns round at 1x");
3917 assert_eq!(shuttle_rate(true, true, -4.0), 1.0, "L while backward turns round at 1x");
3918 assert_eq!(shuttle_rate(true, false, 2.0), 1.0, "a paused shuttle starts over");
3919}
3920
3921/// Backward a picture is due once the clock has come down to its frame.
3922#[test]
3923fn a_backward_picture_is_due_when_the_clock_comes_down_to_it() {
3924 use crate::player::transport::frame_due;
3925 assert!(frame_due(10, 10.5, false) && !frame_due(11, 10.5, false));
3926 assert!(frame_due(10, 10.5, true), "the frame under the clock is shown");
3927 assert!(frame_due(11, 10.5, true), "...and one above it is not held back");
3928 assert!(!frame_due(9, 10.5, true), "one below is still ahead of the clock");
3929}
3930
3931/// J is a live action wherever L is.
3932#[test]
3933fn j_is_enabled_wherever_l_is() {
3934 use keymap::ActionId;
3935 let live = Ctx {
3936 timeline: true,
3937 playable: true,
3938 ..Ctx::default()
3939 };
3940 assert!(enable(ActionId::ShuttleBack, live.clone()).yes());
3941 assert_eq!(
3942 enable(
3943 ActionId::ShuttleBack,
3944 Ctx {
3945 playable: false,
3946 ..live.clone()
3947 }
3948 ),
3949 enable(
3950 ActionId::ShuttleForward,
3951 Ctx {
3952 playable: false,
3953 ..live
3954 }
3955 ),
3956 );
3957}
3958
3959#[test]
3960fn sequence_actions_enable_only_where_they_can_work() {
3961 let lone = Ctx { sequences: 1, timeline: true, ..Ctx::default() };
3962 assert!(matches!(enable(ActionId::NewSequence, lone.clone()), Enable::Yes));
3963 assert!(matches!(enable(ActionId::DeleteSequence, lone.clone()), Enable::No(_)));
3964 assert!(matches!(enable(ActionId::CloseCompound, lone), Enable::No(_)));
3965 let two = Ctx { sequences: 2, timeline: true, ..Ctx::default() };
3966 assert!(matches!(enable(ActionId::DeleteSequence, two.clone()), Enable::Yes));
3967 let used = Ctx { sequence_used: true, ..two.clone() };
3968 assert!(matches!(enable(ActionId::DeleteSequence, used), Enable::No(_)));
3969 let child = Ctx { parent: true, ..two };
3970 assert!(matches!(enable(ActionId::CloseCompound, child), Enable::Yes));
3971 assert!(matches!(enable(ActionId::NestClips, Ctx::default()), Enable::No(_)));
3972 assert!(matches!(enable(ActionId::BreakApart, Ctx::default()), Enable::No(_)));
3973}