//! Where a moment is drawn: drops and snaps, the zoom and the scroll, the //! paths a file is written to, and the strokes the handler answers. use super::*; /// The preview's one cached cue picture is keyed by the *cue* and not only by /// where it happens to sit: a lane and a start microsecond are not an identity -- /// lift a bitmap caption off a lane, drop another track's caption at the same /// frame, and a key of those two matched the cache, painting the picture of the /// cue that is gone over the one that is up. The picture's own allocation is the /// rest of the key, and an identical repeat still hits, which is the whole cache. #[test] fn a_cached_cue_picture_is_keyed_by_the_cue_not_only_its_moment() { use crate::ui::preview::sub_image_key; let (lane, other) = (Lane::S1, Lane::A1); // Two cues that share the lane and the start, and nothing else: one lifted, // one placed at the same frame. let a = sub_image_key(lane, 1_000_000, 3_000_000, 0x1000); let b = sub_image_key(lane, 1_000_000, 3_000_000, 0x2000); assert_ne!( a, b, "two different cues at one moment on one lane are one cache key again, so \ the second paints the first's picture" ); // The same cue repainted: still a hit. assert_eq!( a, sub_image_key(lane, 1_000_000, 3_000_000, 0x1000), "the cache misses on every repaint of the same cue, so it decodes an 8 MB \ display set per frame" ); // The same picture recut over the same start is a different cue. assert_ne!( a, sub_image_key(lane, 1_000_000, 2_500_000, 0x1000), "a cue's own end is no part of the key, so a recut cue serves the old window" ); // And the other half of the old key still holds: the four PGS tracks of a // remux start at the same microsecond, so the lane separates them. assert_ne!( a, sub_image_key(other, 1_000_000, 3_000_000, 0x1000), "the lane is no longer part of the key, so a lane's eye shut leaves the \ other lane's caption on screen" ); // And the door builds its key this way, out of the cue's own picture: the // cache is only keyed by the cue while the lookup goes through this // constructor, and a test of the constructor alone would pass with the door // still keying on `(lane, start_us)`. let preview_rs = src_text("ui/preview.rs"); assert!( preview_rs.contains( "let key = sub_image_key(lane, start_us, end_us, Arc::as_ptr(image) as usize);" ), "the cue picture is cached under a key that is not the cue's own" ); assert!( preview_rs.contains("*up == key"), "the cache no longer compares the key it built" ); } /// What a drop reads: the frame under the pointer, through the same scale /// the boxes are drawn through. Zoomed in, the same pixel is a different /// frame -- which is the whole reason `Player::frame_under` goes through /// [`Scale`] rather than through the duration alone. #[test] fn a_drop_reads_the_frame_under_the_pointer_at_every_zoom() { // A 200 px bed inset by the panel's padding, 10 seconds at 30 fps. let bed: Bounds = Bounds { origin: point(px(12.), px(400.)), size: size(px(200.), px(6.)), }; let fps = 30.; // The frame a pointer at window `x` names, exactly as `frame_under` // composes it. let under = |scale: Scale, x: f32| frame_at(scale.time_at(px_along(px(x), bed)), fps); // The whole 10 s timeline across the 200 px bed: 20 px to the second, // so halfway along is frame 150. let fit = Scale { pps: 20., start: 0., }; assert_eq!(under(fit, 12.), 0); assert_eq!(under(fit, 112.), 150); assert_eq!(under(fit, 212.), 300); // Four times in, starting at second 5: the same middle pixel is now the // frame in the middle of seconds 5..7.5, and the left edge is not 0. let zoomed = Scale { pps: 80., start: 5., }; assert_eq!(under(zoomed, 12.), 150); assert_eq!(under(zoomed, 112.), 187); assert_eq!(under(zoomed, 212.), 225); // ...and a pointer that slid off either end of the bed names an end of // the bed, never a pixel outside it. assert_eq!(under(zoomed, 0.), 150); assert_eq!(under(fit, 9999.), 300); } /// The snap: a clip let go a few frames off a neighbour's edge lands *on* /// it, by whichever of its own ends is nearer, and a clip let go in open bed /// stays exactly where the hand left it. #[test] fn a_dropped_clip_snaps_to_the_edges_worth_landing_on() { // A neighbour covering [100, 160) and the playhead at 300. let marks = [100, 160, 300, 0]; // Head a frame short of the neighbour's tail: laid end to end with it. assert_eq!(snapped(158, 40, 4, &marks), 160); // Tail a frame into its head: pulled back so the two meet exactly. assert_eq!(snapped(62, 40, 4, &marks), 60); // The playhead is an edge like any other. assert_eq!(snapped(298, 40, 4, &marks), 300); // Outside the tolerance nothing moves -- a gap the hand meant to leave // is a gap. assert_eq!(snapped(150, 40, 4, &marks), 150); // No tolerance at all (zoomed right in, where a few pixels are worth // less than a frame) is no snap: single frames are placed by hand. assert_eq!(snapped(158, 40, 0, &marks), 158); // The nearer edge wins when two are in reach. assert_eq!(snapped(101, 40, 8, &marks), 100); // ...and a mark closer to the head than `len` cannot pull the clip to a // negative start. assert_eq!(snapped(2, 40, 4, &marks), 0); } /// The shadow a drag draws and the drop that commits are one answer: both /// ask [`landing`], so the box seen in flight is the box the release leaves /// behind. What this pins down is the composition around the snap -- the /// grab offset comes off *before* the magnet, or a clip taken by its tail /// would land a boxful late. #[test] fn a_ghost_and_a_drop_are_one_landing() { // A neighbour covering [100, 160), the playhead at 300, and a 40 frame // clip taken hold of 12 frames in. let marks = [100, 160, 300, 0]; let (len, grab, tol) = (40, 12, 4); // Pointer at frame 170: the head is 12 frames behind it, at 158, which // is a frame short of the neighbour's tail -- so both the ghost and the // drop say 160, and the line stands on the mark that pulled it. assert_eq!(landing(170, grab, len, true, tol, &marks), (160, Some(160))); // Without the grab taken off first, the same pointer would land the // box at 170 and no mark would be in reach: the offset is not cosmetic. assert_eq!(landing(170, 0, len, true, tol, &marks), (170, None)); // A library row carries no grab and no length the engine has measured, // which is how `Player::place_frame` asks: only its head lands, on the // playhead here. assert_eq!(landing(298, 0, 0, true, tol, &marks), (300, Some(300))); // The magnet off, ghost and drop agree on the raw frame and no line is // drawn -- the frame-by-frame placement the switch is for. assert_eq!(landing(170, grab, len, false, tol, &marks), (158, None)); // A pointer nearer the bed's start than the hand is into the box cannot // pull a head below zero. assert_eq!(landing(3, grab, len, true, tol, &marks), (0, Some(0))); } /// Which lanes tint that shadow as refused: the two kinds of file a lane /// cannot hold, in the words the release would say them in -- one rule, so /// what is shown as impossible is exactly what is refused. #[test] fn a_lane_refuses_the_files_it_cannot_hold_before_the_release_says_so() { let (video, audio) = (Lane::V1, Lane::A1); let sound = Path::new("/media/take.mp3"); let still = Path::new("/media/card.png"); let movie = Path::new("/media/take.mp4"); assert_eq!( lane_refuses(sound, video, false).as_deref(), Some("Not on V1 — take.mp3 has no picture") ); assert_eq!( lane_refuses(still, audio, true).as_deref(), Some("Not on A1 — card.png is a still image") ); // ...and every lane a file *can* go on says nothing at all, which is a // ghost drawn in the file's own colour. assert_eq!(lane_refuses(sound, audio, false), None); assert_eq!(lane_refuses(still, video, true), None); assert_eq!(lane_refuses(movie, video, true), None); // A file with a picture is not refused by an audio lane here: the // engine takes its sound onto one, and the words for a video-only file // are its own. assert_eq!(lane_refuses(movie, audio, true), None); // The extension lies and the probe corrects it: a song muxed into an // `.mp4` still names a video lane refused, in the exact words the .mp3 // twin above got -- `has_video` is what decides it now, not the suffix. assert_eq!( lane_refuses(movie, video, false).as_deref(), Some("Not on V1 — take.mp4 has no picture") ); // ...and a subtitle lane holds none of the three: a caption comes off the // Subtitles list, which is where the refusal points. for (file, has_video) in [(sound, false), (still, true), (movie, true)] { let why = lane_refuses(file, Lane::S1, has_video).expect("a subtitle lane takes no media"); assert!(why.starts_with("Not on S1 — "), "{why}"); assert!(why.contains("Subtitles list"), "{why}"); } // How the two clocks a caption has meet, which is what a palette row's // length is worked out with: a second of words at 30 fps is 30 frames, // and a track shorter than one frame is still a caption to place. assert_eq!(frames_of_us(1_000_000, 30.), 30); assert_eq!(frames_of_us(500_000, 24.), 12); assert_eq!(frames_of_us(1_000, 30.), 1); assert_eq!(frames_of_us(1_000_000, 0.), 1); } /// Where those edges come from: every lane, not the one being dropped on -- /// and never the clip in the hand or the half of it one track down. #[test] fn the_marks_are_every_lane_the_playhead_and_the_start() { let clip = |start: u32, frames: u32, link| Clip { speed_keys: Vec::new(), reversed: false, stabilise: None, deinterlace: Default::default(), mark: Default::default(), angle: Default::default(), fade_in: 0, fade_out: 0, transition_out: 0, transition_kind: Default::default(), visualizer: 0, viz_paint: 0, gain_db: 0.0, gain_keys: Vec::new(), pan: 0, pitch: 0.0, transform_keys: Vec::new(), opacity_keys: Vec::new(), color_keys: Vec::new(), effects: Vec::new(), start, in_frame: 0, out_frame: frames, source: 0, link, eq: None, color: None, transform: None, fit: Default::default(), speed: Default::default(), }; // A grouped take across two lanes at 100..160, and a lone one on the // audio lane at 400..430. let video = [clip(100, 60, Some(7))]; let audio = [clip(100, 60, Some(7)), clip(400, 30, None)]; let lanes: [&[Clip]; 2] = [&video, &audio]; // Nothing in the hand: both lanes' edges, the playhead, and 0. let mut all = snap_marks(&lanes, None, None, 300, None, &[]); all.sort_unstable(); assert_eq!(all, [0, 100, 100, 160, 160, 300, 400, 430]); // The video half in the hand, with its group named as the caller reads it // off the pick: its own edges are gone, and so are its group's on the // other lane -- both boxes travel with the drag. The lone audio clip is // still a target, which is the whole point: a take being carried on V1 // lands flush with a sound on A1. let mut carried = snap_marks(&lanes, Some((0, 0)), Some(7), 300, None, &[]); carried.sort_unstable(); assert_eq!(carried, [0, 300, 400, 430]); // An index that names no clip skips nothing and still answers. assert_eq!(snap_marks(&[], Some((3, 9)), None, 0, None, &[]), [0, 0]); } /// The line the bed draws, and the switch that turns the whole thing off. #[test] fn the_snap_names_the_mark_it_landed_on_unless_it_is_switched_off() { let marks = [100, 160, 300, 0]; // Pulled by the tail: the clip lands at 60 and the line stands on the // edge its *tail* met, 100 -- not on the head it happens to have. assert_eq!(snap_cue(true, 62, 40, 4, &marks), (60, Some(100))); // Pulled by the head: line and landing are the same frame. assert_eq!(snap_cue(true, 158, 40, 4, &marks), (160, Some(160))); // A trim carries no length, so only its own edge lands. assert_eq!(snap_cue(true, 298, 0, 4, &marks), (300, Some(300))); // Open bed: nothing moves and nothing is drawn. assert_eq!(snap_cue(true, 200, 40, 4, &marks), (200, None)); // Switched off, a gesture that would have snapped lands raw and draws // no line -- the frame-by-frame placement the toggle is for. assert_eq!(snap_cue(false, 158, 40, 4, &marks), (158, None)); } /// A stream's rate is one number in the unit its size asks for, and a stated /// rate never reads as a zero: every decade from one bit a second up, and the /// edges of each unit switch. #[test] fn a_stated_rate_never_renders_as_a_zero() { let edges: Vec = (0..12) .flat_map(|e| { let decade = 10_u64.pow(e); [decade, decade * 4, decade * 5, decade * 9] }) .chain([999, 1_000, 999_999, 1_000_000, 4_998, 113, 2_400, 8_432_000]) .collect(); for bits in edges { let line = bits_label(bits); let number: f64 = line .split(' ') .next() .and_then(|n| n.parse().ok()) .unwrap_or_else(|| panic!("no number in {line:?}")); assert!(number > 0., "{bits} bits a second rendered as {line:?}"); } } #[test] fn a_rate_is_said_in_the_unit_its_size_asks_for() { assert_eq!(bits_label(113), "113 b/s"); assert_eq!(bits_label(4_998), "5.0 kb/s"); assert_eq!(bits_label(128_000), "128.0 kb/s"); assert_eq!(bits_label(8_432_000), "8.4 Mb/s"); } #[test] fn a_size_reads_in_the_largest_unit_that_keeps_a_decimal() { assert_eq!(size_human(1_200_000_000), "1.2 GB"); assert_eq!(size_human(840_000_000), "840 MB"); assert_eq!(size_human(512), "512 B"); } #[test] fn a_picture_names_its_height_the_way_people_do() { assert_eq!(resolution_label(1080), "1080p"); assert_eq!(resolution_label(720), "720p"); assert_eq!(resolution_label(2160), "4K"); } #[test] fn a_picture_track_says_only_what_its_header_states() { let video = engine::VideoFacts { codec: engine::Codec::H264, width: 1920, height: 1080, frame_rate: Some(29.97), bit_depth: None, matrix_assumed: false, profile: None, interlaced: None, }; assert_eq!( video_detail(&video, Some(5_200_000)), "H.264 · 1920×1080 · 29.97 fps · 5.2 Mb/s" ); let ten_bit = engine::VideoFacts { codec: engine::Codec::Hevc, bit_depth: Some(10), matrix_assumed: false, frame_rate: None, ..video }; assert_eq!(video_detail(&ten_bit, None), "HEVC · 1920×1080 · 10-bit"); let bare = engine::VideoFacts { width: 0, height: 0, ..ten_bit }; assert_eq!(video_detail(&bare, None), "HEVC · 10-bit"); } #[test] fn a_sound_track_says_its_codec_rate_layout_depth_and_bitrate() { let info = StreamInfo { index: 0, codec: "mp4a".to_string(), channels: 2, sample_rate: 48_000, lang: None, decodable: true, bit_depth: None, bitrate: Some(128_000), }; assert_eq!(audio_detail(&info), "mp4a · 48 kHz · stereo · 128.0 kb/s"); let unnamed = StreamInfo { codec: "unknown".to_string(), channels: 0, sample_rate: 0, bitrate: None, ..info }; assert_eq!(audio_detail(&unnamed), ""); } #[test] fn a_plate_lists_the_file_then_each_track_and_leaves_out_what_is_unknown() { use crate::MediaBitrate; let path = std::path::Path::new("/media/take-3.mp4"); let facts = engine::MediaFacts { container: Some("mp4".to_string()), bytes: Some(1_200_000_000), video: Some(engine::VideoFacts { codec: engine::Codec::H264, width: 1920, height: 1080, frame_rate: Some(29.97), bit_depth: None, matrix_assumed: false, profile: None, interlaced: None, }), duration_secs: None, streams: Vec::new(), attached_pic: false, }; let rate = MediaBitrate { total: Some(8_432_000), video: Some(7_918_000), audio: None, }; let track = StreamInfo { index: 0, codec: "mp4a".to_string(), channels: 2, sample_rate: 48_000, lang: None, decodable: true, bit_depth: None, bitrate: None, }; let rows = file_properties(path, Some(&facts), std::slice::from_ref(&track), Some(rate)); let labels: Vec<&str> = rows.iter().map(|(label, _)| label.as_str()).collect(); assert_eq!( labels, ["File", "Path", "Container", "Size", "Video", "Audio"] ); assert_eq!(rows[0].1, "take-3.mp4"); assert_eq!(rows[3].1, "1.2 GB · 8.4 Mb/s"); assert_eq!(rows[4].1, "H.264 · 1920×1080 · 29.97 fps · 7.9 Mb/s"); assert_eq!(rows[5].1, "mp4a · 48 kHz · stereo"); // Two sound tracks are told apart by which one of how many each is. let second = StreamInfo { index: 1, ..track.clone() }; let two = file_properties(path, None, &[track, second], None); let labels: Vec<&str> = two.iter().map(|(label, _)| label.as_str()).collect(); assert_eq!(labels, ["File", "Path", "Audio 1 of 2", "Audio 2 of 2"]); // Before the probe answers there is the file and nothing it has not said. assert_eq!(file_properties(path, None, &[], None).len(), 2); } #[test] fn timecode_counts_frames_inside_the_second() { assert_eq!(timecode(0., 30.), "00:00:00:00"); assert_eq!(timecode(-1., 30.), "00:00:00:00"); // clamped, never negative assert_eq!(timecode(4.9667, 30.), "00:00:04:29"); // last frame of a 5 s clip assert_eq!(timecode(5., 30.), "00:00:05:00"); assert_eq!(timecode(3661.5, 30.), "01:01:01:15"); // Rounding must not spill into a frame the second does not have. assert_eq!(timecode(1. - f64::EPSILON, 30.), "00:00:00:29"); assert_eq!(timecode(0.999, 29.97), "00:00:00:29"); } #[test] fn scrub_seeks_only_on_a_new_frame_and_only_every_100ms() { let (slow, fast) = (Duration::from_millis(100), Duration::from_millis(99)); // Both halves must hold: a moved pointer that has not crossed a frame // boundary would reopen the decoder for the same picture. assert!(scrub_due(31, 30, slow)); assert!(!scrub_due(30, 30, slow)); assert!(!scrub_due(31, 30, fast)); assert!(!scrub_due(30, 30, fast)); // Exactly at the gap counts, and a long stall never blocks. assert!(scrub_due(1, 0, Duration::from_secs(9))); } #[test] fn the_picture_is_restarted_only_when_it_is_really_behind_and_not_twice() { // A quantum's worth of lateness is what every playing frame has; only a // gap an eye reads as out of sync answers with a reopen. assert!(!should_resync(0., None)); assert!(!should_resync(LATE_RESYNC, None)); assert!(should_resync(LATE_RESYNC + 0.1, None)); // ...and a decoder that is still behind right after a restart -- the // usual case, since it was too slow to begin with -- waits out the gap // instead of reopening at every repaint. assert!(!should_resync(9., Some(Instant::now()))); assert!(should_resync( 9., Some(Instant::now() - RESYNC_GAP - Duration::from_millis(1)) )); } #[test] fn the_default_export_is_never_a_source_and_never_beside_one() { use crate::player::library::default_export_path; use std::path::Path; let src = Path::new("/no-such-edith-dir/speech.mp4"); // A saved project is named after itself, and its name is not the source's. let project = Path::new("/no-such-edith-dir/speech.edith"); let out = default_export_path(project, true, Some("speech"), &[src], Format::Mp4); // With no Videos folder (a bare CI home) the default sits beside the // project, which is the source's folder here, so " (2)" keeps it off it. let beside = out.parent() == src.parent(); let want = if beside { "speech (2).mp4" } else { "speech.mp4" }; assert!(out.to_string_lossy().ends_with(want), "{out:?}"); assert_ne!(out, src); // The file it would clash with is a source: " (2)" takes its place. // The taken names sit in the same folder the default lands in. let plain = out.with_file_name("speech.mp4"); let two = default_export_path(project, true, Some("speech"), &[plain.as_path()], Format::Mp4); assert!(two.to_string_lossy().ends_with("speech (2).mp4"), "{two:?}"); let three = default_export_path(project, true, Some("speech"), &[plain.as_path(), two.as_path()], Format::Mp4); assert!(three.to_string_lossy().ends_with("speech (3).mp4"), "{three:?}"); // Untitled: the first clip's name plus " edit", in the chosen format. let untitled = default_export_path(Path::new(""), false, Some("speech"), &[src], Format::Webm); assert!(untitled.to_string_lossy().ends_with("speech edit.webm"), "{untitled:?}"); // Nothing at all: "Untitled". let none = default_export_path(Path::new(""), false, None, &[], Format::Mp4); assert!(none.to_string_lossy().ends_with("Untitled.mp4"), "{none:?}"); } #[test] fn the_first_save_lands_beside_the_media() { assert_eq!( project_path("assets/test_av.mp4"), std::path::Path::new("assets/test_av.edith") ); // The same rule an export follows: only the last extension moves. assert_eq!( project_path("a.export.mp4"), std::path::Path::new("a.export.edith") ); assert_eq!(project_path("clip"), std::path::Path::new("clip.edith")); // Saving a loaded project writes the file it came from, not a second. assert_eq!(project_path("a.edith"), std::path::Path::new("a.edith")); } #[test] fn only_an_exact_edith_extension_is_a_project() { let p = std::path::Path::new; assert!(is_project(p("a.edith"))); // A dotted directory must not decide it -- the file name does. assert!(is_project(p("/v.mp4/a.edith"))); assert!(!is_project(p("a.mp4"))); assert!(!is_project(p("/v.edith/a.mp4"))); // Exactly what `save_project` writes: a dropped `.EDITH` goes to the // demuxer and is refused there, not parsed as a project. assert!(!is_project(p("a.EDITH"))); // An extension, never a bare name. assert!(!is_project(p("edith"))); assert!(!is_project(p("a.edith.mp4"))); } /// The keys menu is the registry drawn, so a *bindable* stroke cannot go /// missing from it by construction. The strokes the modal cards read for /// themselves are the ones that could: this reads the key handler's own /// source and fails on any key it answers to that the menu never mentions. #[test] fn no_stroke_is_missing_from_the_keys_menu() { use keymap::{ActionId, Keymap}; // Every file the window is written in -- the handler, and the helpers // it asks, wherever they have been moved to. The tests below compare // keys too, and are not shortcuts. let handler = ui_source(); let handler = handler.as_str(); let keymap = Keymap::defaults(); let listed = |key: &str| { let pretty = keymap::Chord { key: key.to_string(), ctrl: false, shift: false, alt: false, } .pretty(); keymap.lookup(key, false, false, false).is_some() || keymap::FIXED.iter().any(|f| f.chord == pretty) }; let mut compared = 0; for (at, needle) in handler.match_indices("key == ") { let rest = &handler[at + needle.len()..]; let key = match rest.strip_prefix('"') { Some(literal) => literal[..literal.find('"').expect("unterminated key")].to_string(), // A named constant: the escape the cards get out by. None if rest.starts_with("ESCAPE") => crate::ESCAPE.to_string(), // The registry lookup compares a binding's key with the key it was given: a parameter, not a stroke. None if rest.starts_with("key") => continue, None => panic!("a key compared against something this cannot read: {rest:.20}"), }; assert!( listed(&key), "the handler answers to {key:?} and the keys menu never says so" ); compared += 1; } // The scan is only a guard while it still finds the comparisons: a // rewrite that spells them differently must come back here. assert!( compared >= 4, "the key comparisons moved; this scan is blind" ); // The one branch that is not a comparison -- any digit is a bitrate. assert!(handler.contains("key.parse::()")); assert!(keymap::FIXED.iter().any(|f| f.chord == "0–9")); // And every entry of both halves lands under a heading the menu draws. for action in ActionId::ALL { assert!(keymap::Category::ALL.contains(&action.category())); } for fixed in keymap::FIXED.iter() { assert!(keymap::Category::ALL.contains(&fixed.category)); } } /// The mapping the whole panel is drawn and clicked through: a moment goes /// to a pixel on the bed and comes back the same moment, at every zoom. #[test] fn a_moment_and_the_place_it_is_drawn_are_the_same_at_every_zoom() { let duration = 20.; // The fit, which is the only scale the content's own length picks: 20 s // across a 200 px bed is 10 px to the second, and a 5 s clip is a // quarter of the bed -- the answer the fractional view gave for it. let fit = test_view(Scale::default(), duration).fit(); assert_eq!(fit.pps, 10.); assert_eq!(fit.width_px(5.), TEST_BED * 0.25); for t in [0., 5., 12.5, 20.] { assert_eq!(fit.px_at(t), (t / duration) as f32 * TEST_BED, "fit at {t}"); } for scale in [ fit, Scale { pps: 20., start: 4., }, Scale { pps: 80., start: 12.5, }, Scale { pps: 375., start: 19., }, ] { let scale = test_view(scale, duration).settled(); for x in [0., 50., 100., TEST_BED] { let at = scale.time_at(x); assert!( (f64::from(scale.px_at(at)) - f64::from(x)).abs() < 1e-3, "{scale:?} round trip at {x}" ); } // A stretch as long as what is on the bed is as wide as the bed. assert!( (f64::from(scale.width_px(test_view(scale, duration).span())) - f64::from(TEST_BED)) .abs() < 1e-3, "{scale:?} spans the bed" ); } } /// The rule that makes a zoom usable: whatever was under the anchor is /// still under it afterwards -- the playhead for a key, the pointer for a /// ctrl+wheel. #[test] fn a_zoom_leaves_the_anchor_where_it_was_on_screen() { let duration = 20.; let mut scale = test_view(Scale::default(), duration).settled(); // The same three points along the bed the fractional view held: a half, // a quarter and nine tenths of 200 px. for anchor in [100f32, 50., 180.] { // Well past the zoom-in stop: the anchor holds at the clamp too, // which is where it used to slide (the clamp came after the offset). for _ in 0..30 { let at = scale.time_at(anchor); let view = test_view(scale, duration); let zoomed = view.zoomed(ZOOM_STEP, anchor); // Only where the anchor is not pinned by an edge of the // timeline: a view already against an end cannot slide further. let span = test_view(zoomed, duration).span(); let pinned = zoomed.start <= 0. || zoomed.start + span >= duration; if !pinned { assert!( (f64::from(zoomed.px_at(at)) - f64::from(anchor)).abs() < 1e-3, "{at} moved: {scale:?} -> {zoomed:?}" ); } assert!(zoomed.pps >= scale.pps, "and it did zoom in"); scale = zoomed; } } } /// Both stops. In is [`ZOOM_MIN_FRAMES`] across the bed; out, on a timeline /// far too short to be worth widening to, is a pixel to the second -- so a /// short import can be zoomed out of, a long one zoomed into, and neither /// can scroll off an end. #[test] fn zoom_stops_at_a_bedful_of_time_and_at_a_handful_of_frames() { let (duration, fps) = (20., 30.); let mut scale = Scale::default(); for _ in 0..200 { scale = test_view(scale, duration).zoomed(1. / ZOOM_STEP, 100.); } assert!( (test_view(scale, duration).span() - f64::from(TEST_BED) / PPS_MIN).abs() < 1e-6, "widest is a pixel to the second, not the 20 s that happen to be on it" ); for _ in 0..200 { scale = test_view(scale, duration).zoomed(ZOOM_STEP, 100.); } assert_eq!( (test_view(scale, duration).span() * fps).round(), ZOOM_MIN_FRAMES, "tightest is a handful of frames" ); // Against the far end, the slice still ends at the last frame. let end = test_view( Scale { start: 1e6, ..scale }, duration, ); let end = (end.settled(), end.span()); assert!((end.0.start + end.1 - duration).abs() < 1e-9); assert_eq!( test_view( Scale { start: -5., ..scale }, duration ) .settled() .start, 0. ); // The dead zone the fractional view had: a timeline of a handful of // frames could not be zoomed at all, because its own length was the // floor *and* the ceiling. Both keys work on it now. let tiny = test_view(Scale::default(), 0.1); assert!(tiny.zoomed(ZOOM_STEP, 100.).pps > PPS_DEFAULT); assert!(tiny.zoomed(1. / ZOOM_STEP, 100.).pps < PPS_DEFAULT); // A timeline with no length at all divides by nothing and scrolls // nowhere; the fit of one keeps the scale it had. let empty = test_view(Scale::default(), 0.); assert_eq!(empty.settled(), Scale::default()); assert_eq!(empty.fit(), Scale::default()); assert_eq!(Scale::default().px_at(0.), 0.); // A bed that was never painted clamps nothing -- there is nothing to // clamp against, and a zoom must survive the frame before the probe. let unpainted = View { bed: 0., ..test_view( Scale { pps: 4e6, start: 3., }, duration, ) }; assert_eq!(unpainted.settled().pps, 4e6); assert_eq!(unpainted.following(19.), unpainted.scale); } /// The bug a fixed far stop was: two two-and-a-half hour clips are five /// hours of timeline, longer than any stop measured in hours, so the end of /// the second one could not be brought on screen by any zoom. The stop is /// the timeline's own length now, so it can. #[test] fn zooming_out_reaches_the_end_of_a_timeline_however_long_it_is() { let bed = 900.; let view = |scale: Scale, duration: f64| View { scale, bed, duration, fps: 30., }; // As far out as the keys go, from the scale a fresh project is drawn at. let out = |duration: f64| { let mut scale = Scale::default(); for _ in 0..400 { scale = view(scale, duration).zoomed(1. / ZOOM_STEP, 0.); } scale }; let five_hours = 2. * 2.5 * 3600.; let wide = out(five_hours); // The whole five hours is on the bed, the last frame drawn inside the // window rather than against its edge. assert_eq!(wide.start, 0.); let end = wide.px_at(five_hours); assert!( end < bed, "the end of the timeline is off the bed at {end} px" ); assert!(end > bed * 0.9, "and not shrunk into a corner: {end} px"); assert!( (view(wide, five_hours).span() - five_hours * ZOOM_OUT_MARGIN).abs() < 1e-6, "the far stop is the timeline plus its margin" ); // Zooming back in still reaches the frame stop on a timeline that long: // the far stop moving does not drag the near one with it. let mut scale = wide; for _ in 0..400 { scale = view(scale, five_hours).zoomed(ZOOM_STEP, 0.); } assert_eq!( (view(scale, five_hours).span() * 30.).round(), ZOOM_MIN_FRAMES ); // And a ten second project is not zoomed out to four hours of empty // bed: short of a pixel to the second its own length is not worth // widening to, and that is 900 s of bed, not 14400. assert!((view(out(10.), 10.).span() - f64::from(bed) / PPS_MIN).abs() < 1e-6); // Whatever the length, the resting scale is nobody's content: the width // invariant, which a far stop measured off the content would break. assert_eq!(view(Scale::default(), 10.).settled(), Scale::default()); assert_eq!( view(Scale::default(), five_hours).settled(), Scale::default() ); // Shrinking the timeline pulls a fully zoomed out view in with it -- // what was showing all of the timeline still shows all of it. let shrunk = view(wide, 1800.).settled(); assert!((view(shrunk, 1800.).span() - 1800. * ZOOM_OUT_MARGIN).abs() < 1e-6); assert!(shrunk.px_at(1800.) < bed); // Growing it does not: a scale the user zoomed to is still legal, and // the stop it stopped at is one press further out. assert_eq!(view(wide, 2. * five_hours).settled().pps, wide.pps); assert!(view(wide, 2. * five_hours).zoomed(1. / ZOOM_STEP, 0.).pps < wide.pps); } /// The bare wheel's own move: the view slides along the timeline, what is /// drawn where slides with it, the scale never changes, and both ends stop /// against the content rather than scrolling it off the bed. #[test] fn a_scroll_slides_the_view_without_zooming_it() { let duration = 60.; // Zoomed in far enough that there is somewhere to scroll to: 10 s of a // 60 s timeline on the bed. let start = test_view( Scale { pps: f64::from(TEST_BED) / 10., start: 0., }, duration, ) .settled(); let notch = TEST_BED * SCROLL_NOTCH_SHARE; let on = test_view(start, duration).scrolled(notch); // A tenth of the bed later, and drawn a tenth of the bed to the left -- // the two halves of one move. assert_eq!(on.pps, start.pps, "a scroll is not a zoom"); assert!( (on.start - (start.start + 1.)).abs() < 1e-9, "one notch is a tenth of the 10 s on the bed: {on:?}" ); assert!( (f64::from(start.px_at(20.) - on.px_at(20.)) - f64::from(notch)).abs() < 1e-3, "and what was drawn moved with it: {on:?}" ); // Back the other way, from the same place, is the same distance. let back = test_view(on, duration).scrolled(-notch); assert!((back.start - start.start).abs() < 1e-9, "{back:?}"); // Neither end can be scrolled off: the head stops at zero, and the tail // stops with the last frame on the bed -- the clamp is the timeline's // own length, not a number. let mut scale = start; for _ in 0..200 { scale = test_view(scale, duration).scrolled(notch); } assert_eq!(scale.pps, start.pps); assert!( (scale.start - (duration - 10.)).abs() < 1e-6, "the tail stops with the end on the bed: {scale:?}" ); for _ in 0..200 { scale = test_view(scale, duration).scrolled(-notch); } assert_eq!(scale.start, 0., "and the head stops at the head: {scale:?}"); // A view already showing all of it has nowhere to go. let whole = test_view(Scale::default(), duration).fit(); assert_eq!(test_view(whole, duration).scrolled(notch), whole); } /// What makes a zoomed timeline follow the playing head: off the bed at /// either end pulls the view onto it, and on the bed it never moves -- a /// view that jumped every frame would be unreadable. #[test] fn the_view_follows_a_playhead_that_runs_off_the_bed() { let duration = 20.; // 5 s on a 200 px bed: 40 px to the second, starting at second 5. let view = test_view( Scale { pps: 40., start: 5., }, duration, ); let scale = view.settled(); assert_eq!(view.span(), 5.); // Inside: untouched, whichever part of the slice it is in. for at in [5., 7.5, 10.] { assert_eq!(view.following(at), scale, "{at} is on the bed"); } // Past the right edge, as playback does it: the head comes back on the // bed, and the scale is not changed by the scroll. let moved = view.following(12.); assert_eq!(moved.pps, scale.pps); assert!(moved.start > scale.start, "scrolled forward"); assert!( moved.px_at(12.) > 0. && moved.px_at(12.) < TEST_BED, "and the playhead is on screen" ); // A seek back behind the slice does the same the other way. let back = view.following(1.); assert!(back.start < scale.start); assert!(back.px_at(1.) >= 0.); // With the whole timeline on the bed there is nothing to follow. let whole = test_view(Scale::default(), duration); let fit = whole.fit(); for at in [0., 10., 20.] { assert_eq!( test_view(fit, duration).following(at), fit, "the fit never scrolls" ); } } /// The wheel during playback. A scroll away from the playing head used to /// be undone by the follow on the very next frame -- with a second, longer /// media on the timeline making it scrollable at all, one notch in five /// reached the screen and the wheel looked dead. The hand keeps the view /// now, and the follow takes it back by itself when the head runs into what /// the hand is looking at. #[test] fn a_scroll_during_playback_wins_until_the_head_catches_up() { let duration = 80.; let mut scale = test_view( Scale { pps: 40., start: 0., }, duration, ) .settled(); // The render's arbitration, in the two lines it is there: a panned view // is left where the hand put it, and the pan ends where the head is // back on the bed. let frame = |scale: Scale, panned: &mut bool, at: f64| { let scale = match *panned { true => test_view(scale, duration).settled(), false => test_view(scale, duration).following(at), }; if *panned && test_view(scale, duration).shows(at) { *panned = false; } scale }; // Playing at second one, five notches of the wheel: every one of them // moves the view, and none is taken back by the head being off the bed. let notch = f64::from(TEST_BED * SCROLL_NOTCH_SHARE); let mut panned = false; for n in 1..=5 { scale = test_view(scale, duration).scrolled(TEST_BED * SCROLL_NOTCH_SHARE); panned = true; scale = frame(scale, &mut panned, 1.); // ...and the pan is only *held* while the head is off the bed: the // first notches still show it, so the follow has the view back for // free and would not have moved anything anyway. assert_eq!(panned, scale.start > 1., "held while the head is off"); assert!( (scale.start - notch * f64::from(n) / 40.).abs() < 1e-6, "notch {n} reached the screen: {scale:?}" ); } // The head runs into it: the pan is given back with nothing pressed... let span = test_view(scale, duration).span(); let start = frame(scale, &mut panned, scale.start + span / 2.).start; assert!(!panned, "the follow has the view back"); assert_eq!(start, scale.start, "and it did not jump to take it"); // ...and the next head that runs off the bed pulls the view again. let ran_off = frame(scale, &mut panned, start + span + 1.); assert!( ran_off.start > start, "the follow follows again: {ran_off:?}" ); // A paused hand is untouched by any of this: with no follow asking, // `shows` is the only thing the pan is ever released by. assert!(test_view(scale, duration).shows(scale.start)); assert!(!test_view(scale, duration).shows(scale.start + span + 0.5)); } /// The bug this mapping exists for: the first import used to fill the whole /// track whatever it was, because the bed *was* the timeline -- so a 5 s /// clip was 100% of the lane, zooming out did nothing, and adding a second /// clip silently halved the first one's box. #[test] fn a_clip_is_drawn_the_same_width_whatever_else_is_on_the_timeline() { let bed = 900.; let of = |duration: f64| View { scale: Scale::default(), bed, duration, fps: 30., }; // One 5 s import, then a second clip after it: 20 s of timeline where // there were 5, and the first box has not moved or narrowed. let (alone, joined) = (of(5.).settled(), of(20.).settled()); assert_eq!(alone, joined); assert_eq!(alone.width_px(5.), joined.width_px(5.)); assert_eq!(joined.px_at(5.), alone.width_px(5.)); // And it does not fill the track: a short clip reads as short. assert!( alone.width_px(5.) < bed / 2., "5 s at {} px/s is {} px of a {bed} px bed", alone.pps, alone.width_px(5.) ); // Zooming out visibly shrinks it, however short the timeline is -- the // press that used to be a no-op. let out = of(5.).zoomed(1. / ZOOM_STEP, 0.); assert!( out.width_px(5.) < alone.width_px(5.), "{} px is not smaller than {} px", out.width_px(5.), alone.width_px(5.) ); // The way back to "the whole timeline across the bed" is still one key. assert_eq!(of(5.).fit().width_px(5.), bed); } /// What the zoom button says: how much timeline is on the bed, in a unit /// that tells two zooms apart. #[test] fn the_zoom_button_says_how_much_is_on_the_bed() { // A frame of quiet at 60 fps, which the silence card says out loud. assert_eq!(secs_label(1. / 60.), "0.02s"); assert_eq!(secs_label(4.5), "4.5s"); } /// Keyboard focus v1 (`ui::stance::{Surface, next_surface, is_focus_cycle_key}`): /// Tab walks dock -> bench -> inspector -> dock, wrapping; Shift-Tab walks /// it backward. No gpui window harness exists in this crate to drive a real /// `KeyDownEvent` through -- this exercises the exact pure function every /// surface's `on_key_down` calls, which is where the cycle order actually /// lives. #[test] fn tab_cycles_dock_bench_inspector_and_wraps() { use crate::ui::stance::{Surface, next_surface}; assert_eq!(next_surface(Surface::Dock, false), Surface::Bench); assert_eq!(next_surface(Surface::Bench, false), Surface::Inspector); assert_eq!(next_surface(Surface::Inspector, false), Surface::Dock); // Shift-Tab is the exact reverse at every step. assert_eq!(next_surface(Surface::Dock, true), Surface::Inspector); assert_eq!(next_surface(Surface::Inspector, true), Surface::Bench); assert_eq!(next_surface(Surface::Bench, true), Surface::Dock); } /// The defect this closes: the dock mounts only one of its two tabs at a /// time (`dock_stance::render`'s `match src_active`), so focusing /// `focus_dock`/`focus_inspector` while the other tab is showing lands on a /// handle with no tree node -- gpui then dispatches no key listener at all, /// keyboard input is dead until a mouse click. `Player::focus_surface` /// (`ui::stance.rs`) flips the tab first via this pure decision so the /// surface being entered is always the one mounted. #[test] fn surface_wants_src_active_mounts_the_tab_before_focus_lands_on_it() { use crate::ui::stance::{Surface, surface_wants_src_active}; assert_eq!(surface_wants_src_active(Surface::Dock), Some(true)); assert_eq!(surface_wants_src_active(Surface::Inspector), Some(false)); // Bench has no dock tab of its own -- entering it must not disturb // whichever tab the dock was last left on. assert_eq!(surface_wants_src_active(Surface::Bench), None); } /// The root fallback guarantee (main.rs:1054's "every keybind hangs off the /// root FocusHandle"): a surface's own `on_key_down` answers Tab/Shift-Tab /// and nothing else -- `cx.stop_propagation()` is only ever reached from /// that one branch (`ui::stance::is_focus_cycle_key`), so every other key, /// still-pressed while a surface is focused, is left un-stopped and bubbles /// up the dispatch tree to the root's own `on_key_down` /// (gpui-0.2.2 `window.rs`'s `dispatch_key_down_up_event`, `Bubble` phase, /// walks the focused node's ancestors and stops only at /// `cx.stop_propagation()` -- verified by reading that function, not /// assumed). This asserts the gate itself: only "tab" is ever intercepted, /// so a keybind like space (play/pause) or "s" (split) is provably never /// swallowed by a focused surface. #[test] fn only_tab_is_intercepted_by_a_focused_surface_everything_else_reaches_root() { use crate::ui::stance::is_focus_cycle_key; assert!(is_focus_cycle_key("tab")); for key in [ "space", "escape", "s", "c", "left", "right", "enter", "delete", "?", ] { assert!(!is_focus_cycle_key(key), "{key} must bubble to the root"); } } /// The ring's other door, escape: [`ui::stance::is_focus_exit_key`] is the /// one branch a focused surface's `on_key_down` calls to hand focus back to /// the root (`Player::focus`) instead of letting escape bubble there on its /// own -- same pure-function-level check as the Tab gate above, since this /// crate has no window harness to drive a real `KeyDownEvent` through. #[test] fn escape_is_the_only_key_a_focused_surface_uses_to_leave_the_ring() { use crate::ui::stance::is_focus_exit_key; assert!(is_focus_exit_key("escape")); for key in [ "tab", "space", "s", "c", "left", "right", "enter", "delete", "?", ] { assert!(!is_focus_exit_key(key), "{key} must not exit the ring"); } } /// [`ActionId::FocusPanels`] is what starts the ring in the first place /// (`Player::act`'s `self.focus_surface(Surface::Dock, ..)`) -- without a /// bound key reaching it, `next_surface`/`is_focus_cycle_key` above are /// unreachable dead code, exactly the defect this action closes. #[test] fn focus_panels_is_bound_and_lands_on_the_dock() { use keymap::{ActionId, Keymap}; let k = Keymap::defaults(); assert_eq!(k.lookup("f6", false, false, false), Some(ActionId::FocusPanels)); // Bare Tab must still mean Select at the root -- FocusPanels must not // have stolen it. assert_eq!(k.lookup("tab", false, false, false), Some(ActionId::Select)); } /// A card is not a key-eating black box: the room-wide chords that act on the /// document -- the edit history, the project file, the clipboard -- must reach /// `Player::act` while any card is open. `param_card_key` answers `true` for /// *every* stroke once one of the seven is up, so the dispatch has to stand in /// front of it, not only in front of the blanket modal guard under it; and the /// blanket guard's own `card_open()` has to read after that dispatch too, or a /// chord that got past `param_card_key` (a menu dismiss comes to mind) would /// still never reach the keymap. /// /// A scan of the handler's own source, for the reason every handler scan here /// gives: this binary has no window harness to press `ctrl+z` through. #[test] fn an_open_card_does_not_swallow_the_document_chords() { use crate::ui::stance::card_safe_action; use keymap::ActionId; // The five the room answers through a card, and the reason each is on the // list: history, file, clipboard. for action in [ ActionId::Undo, ActionId::Redo, ActionId::Save, ActionId::Copy, ActionId::Paste, ] { assert!( card_safe_action(action), "{action:?} is a document chord and a card must not eat it" ); } // ...and the strokes the cards' own branch list claims stay theirs: // escape is every card's way out, `s` is the equalizer's spectrum, `x` its // band removal, `m` every card's maximize, and tab picks a band. for action in [ ActionId::Deselect, ActionId::Cut, ActionId::Delete, ActionId::ToggleMute, ActionId::Equalizer, ActionId::Color, ActionId::Loop, ActionId::TrimIn, ] { assert!( !card_safe_action(action), "{action:?} is a card's own stroke and the card must keep it" ); } // The chords are real bindings, not a list of actions nothing reaches. let keys = keymap::Keymap::defaults(); for (key, ctrl, action) in [ ("z", true, ActionId::Undo), ("y", true, ActionId::Redo), ("s", true, ActionId::Save), ("c", true, ActionId::Copy), ("v", true, ActionId::Paste), ] { assert_eq!( keys.lookup(key, ctrl, false, false), Some(action), "the keymap no longer binds {action:?}" ); } // And the dispatch stands where it has to: inside the root handler, ahead // of the cards' own branches and ahead of the blanket modal guard. let stance_rs = src_text("ui/stance.rs"); let dispatch = stance_rs.find("card_safe_action(action)").expect( "the root key handler no longer asks which chords a card does not take -- an open card \ eats every stroke again", ); assert!( stance_rs[..dispatch].contains("this.keymap.lookup(key, ctrl, shift, alt)"), "the dispatch no longer goes through the keymap, so a rebind would leave it behind" ); // The *statement* that dispatches, not just some `keymap.lookup` before it: // the hold gate at the top of the handler resolves the same pair, so a needle // that only asks for the lookup is satisfied by a dispatch resolving the // action some other way entirely. let resolve = stance_rs .find("if let Some(action) = this.keymap.lookup(key, ctrl, shift, alt)") .expect("the dispatch no longer resolves an action through the keymap"); let stmt = &stance_rs[resolve..]; let stmt = &stmt[..stmt.find('{').expect("the dispatch statement has no block")]; assert!( stmt.contains("card_safe_action("), "the dispatch resolves an action and never asks whether a card may take \ it, so an open card eats the document chords again" ); for (guard, label) in [ ("if this.param_card_key(", "the cards' own key branches"), ("if this.card_open()", "the blanket modal guard"), ] { let at = stance_rs .find(guard) .unwrap_or_else(|| panic!("{label} moved or was renamed")); assert!( dispatch < at, "{label} reads before the document dispatch -- an open card would \ swallow undo, redo, save and the clipboard pair again" ); } } /// Play Around (Shift+K) is its own key, and the run it plays is the two seconds on /// either side of the playhead, clamped to the timeline at both ends. #[test] fn play_around_is_shift_k_and_runs_two_seconds_either_side() { use crate::timeline_math::{PLAY_AROUND_PAD, play_around_span}; let km = crate::keymap::Keymap::defaults(); assert_eq!(km.lookup("k", false, true, false), Some(ActionId::PlayAround)); assert_eq!(km.lookup("k", false, false, false), Some(ActionId::ShuttleStop), "plain K still stops"); assert_eq!(PLAY_AROUND_PAD, 2.0); assert_eq!(play_around_span(10., 60.), (8., 12.)); assert_eq!(play_around_span(1., 60.), (0., 3.), "the lead-in stops at the start"); assert_eq!(play_around_span(59., 60.), (57., 60.), "the run-on stops at the end"); assert_eq!(play_around_span(0., 0.), (0., 0.), "an empty timeline has no run"); } /// Snap targets include the comment markers' edges and the chapter starts, so a /// clip let go a frame off one of them lands on it; the list the timeline builds /// from the project is the same list `snap_marks` takes. #[test] fn a_drop_snaps_to_a_marker_or_a_chapter_edge() { // Markers at 250 (a point) and 380..400 (a span), chapters at 500. let notes = [250, 250, 380, 400, 500]; let marks = snap_marks(&[], None, None, 0, None, ¬es); for mark in [250, 380, 400, 500] { assert!(marks.contains(&mark), "{mark} is a snap target"); } assert_eq!(snapped(248, 40, 4, &marks), 250, "a head a frame short of a marker meets it"); assert_eq!(snapped(497, 0, 4, &marks), 500, "a chapter start pulls the clip onto it"); assert_eq!(snapped(150, 40, 4, &marks), 150, "open bed beside them stays where it was"); }