From e87ada1ff3ae01ee2b6c4036ab423af4198fcf85 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Thu, 13 Aug 2026 09:56:13 +0300 Subject: [PATCH] =?UTF-8?q?=F0=9F=94=A7=20chore(tests):=20the=20window's?= =?UTF-8?q?=20tests=20move=20out=20of=20the=20file=20they=20were=20testing?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Two thirds of `main.rs` was its own test module: sixteen thousand lines, of which six thousand were the tests. They are `src/tests/` now -- shared imports and fixtures in `mod.rs`, the tests themselves under the five headings they already fell into: editing, view, cards, media, layout. Pure motion, except for the scans. Several guards read the window's own source to hold a structural rule, and they read it with `include_str!` over a list of file names -- a list that goes quietly wrong the moment a region moves house, which is exactly what this commit does to six thousand lines and the next one will do to more. They walk `src/` at run time now: every `.rs` under it, found rather than named, so a rule cannot be passed by moving the code out from under it. A stray colour in a file nobody declared as a module is caught; under the old list it was not. --- crates/app/src/main.rs | 6081 +------------------------------ crates/app/src/tests/cards.rs | 1353 +++++++ crates/app/src/tests/editing.rs | 1592 ++++++++ crates/app/src/tests/layout.rs | 1093 ++++++ crates/app/src/tests/media.rs | 1035 ++++++ crates/app/src/tests/mod.rs | 219 ++ crates/app/src/tests/view.rs | 857 +++++ 7 files changed, 6150 insertions(+), 6080 deletions(-) create mode 100644 crates/app/src/tests/cards.rs create mode 100644 crates/app/src/tests/editing.rs create mode 100644 crates/app/src/tests/layout.rs create mode 100644 crates/app/src/tests/media.rs create mode 100644 crates/app/src/tests/mod.rs create mode 100644 crates/app/src/tests/view.rs diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index e105257..c89ec2f 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -10319,6086 +10319,7 @@ fn eta_secs(marks: &[(f32, f32)], elapsed: f32, progress: f32) -> Option { } #[cfg(test)] -mod tests { - use super::{ - ACCENT_PRIMARY, AUDIO_KBPS, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, Ctx, DEFAULT_AUDIO_KBPS, EQ_BANDS_MAX, - EQ_CURVE_STEPS, EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_FREQ_STEP, EQ_GAIN_LIMIT, EQ_GRAPH_H, - EQ_HANDLE, EQ_Q_HIGH, EQ_Q_LOW, EQ_Q_STEP, EQ_SPECTRUM_DB, EQ_TICKS, EQ_W_MAX, ESCAPE, - EXPORT_FIXED_H, EXPORT_ROWS_H, EXPORT_W, Enable, FORMATS, - Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, FG_PRIMARY, - FG_SECONDARY, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, KeyRow, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, - BG_CANVAS, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H, - MBPS_DIGITS, MBPS_MAX, MBPS_MIN, MB_FLOOR, MENU_W, NO_FILE, NumberEdit, PANEL_H, ROW_ITEMS, RowCtx, RowItem, - Quality, ROW_H, RULER_HIT_H, BG_SELECTED, SCROLL_NOTCH_SHARE, SILENCE_ROWS, - SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, BG_RAISED, SWATCH_W, Source, Speed, StreamInfo, - Transport, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, WAVE_COLS_MAX, Wave, band_label, - bitrate_detail, bitrate_refusal, can_add, cancels_export, clipboard_after_remove, color_snap, commit_mbps, - containers, - enable, envelope, eq_card_w, eq_freq, eq_freq_label, eq_spectrum, eq_x, eq_y, - estimated_bytes, export_path, export_settings, format_key, - format_line, format_refusal, fps_choices, fps_label, frac_along, frac_down, frame_at, - frame_rate_ladder, histogram, - inserted_band, is_bare_modifier, is_project, keymap, keys_filter, keys_rows, lanes_h, - marked, menu_at, menu_items, menu_rows_h, next_audio_kbps, next_container, normalise, nothing_to_play, panel_h, project_path, - LATE_RESYNC, RESYNC_GAP, should_resync, - retarget, row_enable, row_items, scrub_due, secs_label, show_label, silence_rate, size_label, snap_cue, snap_marks, snapped, - SUB_PLAN_CHARS, source_tint, span_partner, speed_at, sub_pick_after_removal, subtitle_plan, summary_head, summary_tail, timecode, transport, - EXPORT_DONE, NOTICES_MAX, STATUS_ERROR, TIMELINE_FIXED_H, TIMELINE_SHARE, lanes_shown, - px_below, rows_below, STATUS_SUCCESS, STATUS_WARNING, notice_tone, - push_notice, typed, unseen_paths, unseen_sources, - whole_take, window_title, - }; - use super::{ - Choice, EDGE_W, ETA_SPAN, Edge, FITS, FRAME_RATES, LaneKind, PPS_DEFAULT, PPS_MIN, Preset, RESOLUTIONS, Repeat, - Scale, View, - ZOOM_MIN_FRAMES, ZOOM_OUT_MARGIN, ZOOM_STEP, audio_rate_choices, clock, eta_secs, file_name, file_uri, - fit_choices, landing, lane_refuses, library_rows, live_idx, next_fit, next_resolution, - note_progress, px_along, - IMPORT_STALL, Import, ImportStage, SEEK_STALL, ScanKey, ScanPlan, SilenceScan, import_line, - Landing, arrival, launch_queue, - read_ahead, scan_plan, seek_line, silence_line, source_secs, stash_or_write, - repeats, resolution_choices, resolution_ladder, span_label, tone_choices, tone_label, - clip_width, trimmed_clip, trims, unscannable, unusable, - visible_slice, - }; - use super::{ - SUB_BOTTOM, SUB_CUE_MIN_W, SUB_HEAD_H, SUB_FG, SUB_LANE_H, SUB_LINE_H, SUB_ROWS_H, - SUB_STEM_SHARE, SUB_TEXT, clip_middle, cue_box, - carries_subtitles, cues_at, file_tint, is_subtitle, lang_human, row_text_w, sub_headers_fit, - Subs, subtitle_detail, subtitle_notice, subtitle_tail, - sub_pick_name, subtitle_rows, subtitle_strip_h, walk_subtitles, - }; - - /// What the file manager is handed: the parts a path keeps as they are, and - /// the ones the bus would otherwise read as something else. - #[test] - fn file_uri_encodes_what_a_path_carries() { - assert_eq!( - file_uri(std::path::Path::new("/a/b.mp4")), - "file:///a/b.mp4" - ); - assert_eq!( - file_uri(std::path::Path::new("/home/x/out dir/my export.mp4")), - "file:///home/x/out%20dir/my%20export.mp4" - ); - assert_eq!( - file_uri(std::path::Path::new("/tmp/ünlü#1?.mp4")), - "file:///tmp/%C3%BCnl%C3%BC%231%3F.mp4" - ); - } - use engine::PlaybackSession; - use engine::scale::FitPolicy; - use gpui::{Bounds, Pixels, point, px, size}; - use std::collections::HashMap; - use std::path::{Path, PathBuf}; - use std::time::{Duration, Instant}; - - /// Every line of UI source there is, as one string: the window used to be - /// one file and the scans below read it with `include_str!`. The regions - /// are modules now (`ui/`), so the scans read all of them -- a rule that - /// stopped at `main.rs` would pass by simply not looking where the pixels - /// moved to. - fn ui_source() -> String { - [ - include_str!("main.rs").split("#[cfg(test)]").next().unwrap(), - include_str!("ui/theme.rs"), - include_str!("ui/toolbar.rs"), - include_str!("ui/inspector.rs"), - include_str!("ui/timeline.rs"), - include_str!("ui/library.rs"), - include_str!("ui/preview.rs"), - include_str!("ui/cards.rs"), - include_str!("ui/overlays.rs"), - include_str!("ui/widgets.rs"), - ] - .concat() - } - - fn asset(name: &str) -> PathBuf { - Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../assets") - .join(name) - } - - /// A source entry for `path` on `stream`, as the project keeps them. - fn source(path: &str, stream: usize) -> Source { - Source { - path: PathBuf::from(path), - audio_stream: stream, - } - } - - /// An import fills the *library* and nothing else -- the whole point of - /// this door: the row is there at the file's own length before any clip - /// plays it, wearing the tint the lanes will tint that clip with, and the - /// timeline is exactly as long as it was. Placing it is the drag, and the - /// drag is a separate act. - #[test] - fn an_import_adds_a_row_at_its_own_length_and_leaves_the_lanes_alone() { - let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); - session.set_gain(0.0); - let before = session.timeline_duration(); - let clips: Vec = session - .lanes() - .into_iter() - .map(|lane| session.lane_clips(lane).len()) - .collect(); - session.import(&asset("test_av2.mp4")).expect("av2 matches"); - assert_eq!(session.sources().len(), 2, "the library grew"); - assert_eq!( - session.timeline_duration(), - before, - "an import must not place a clip" - ); - assert_eq!( - session - .lanes() - .into_iter() - .map(|lane| session.lane_clips(lane).len()) - .collect::>(), - clips, - "no lane moved" - ); - // The rows the panel draws: one per source, each its file's own length - // -- source 1 has no clip anywhere and is still 4 s at 30 fps. - let rows = library_rows( - session.sources(), - &HashMap::new(), - &HashMap::new(), - None, - |path| session.file_frames(path), - ); - assert_eq!(rows.len(), 2); - assert_eq!(rows[0].frames, 150, "5 s at 30 fps"); - assert_eq!(rows[1].frames, 120, "4 s at 30 fps, never placed"); - // The swatch is the clip colour, by the same index and the same - // function -- what makes the panel and the lanes one association. - for row in 0..rows.len() { - assert_eq!(rows[row].tint, row); - assert_eq!(source_tint(row), SOURCE_TINTS()[row % SOURCE_TINTS().len()]); - } - } - - /// The window opened on a song and nothing else -- the launch argument, the - /// drop on an empty window and the Import button all end in the same - /// `PlaybackSession::open`. The library lists it placeable, the lane door - /// the Add button and a drag share puts it on `A1`, and the one format that - /// needs a picture says so on its own row instead of failing at the end of - /// an export. - #[test] - fn a_song_opens_the_window_by_itself() { - let mut session = - PlaybackSession::open(asset("test_tone.mp3")).expect("a song is a timeline"); - session.set_gain(0.0); - // The source's own path, which is the canonical one a row carries. - let path = session.sources()[0].path.clone(); - assert!(session.lane_clips(Lane::V1).is_empty(), "no picture"); - assert_eq!(session.lane_clips(Lane::A1).len(), 1); - - // The library row: probed like any other source, and not greyed -- - // `unusable` is what the panel dims a row with. - let streams = HashMap::from([( - path.clone(), - engine::AudioSession::probe_streams(&path).expect("probe the song"), - )]); - let rate = streams[&path] - .iter() - .find(|s| s.index == session.sources()[0].audio_stream) - .map(|s| (s.sample_rate, s.channels)); - let frames = session.file_frames(&path); - let rows = library_rows(session.sources(), &streams, &HashMap::new(), rate, |_| { - frames - }); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].name, "test_tone.mp3"); - assert_eq!(rows[0].unusable, None, "the row is placeable"); - assert_eq!(rows[0].frames, 90, "3 s at the audio-only 30 fps"); - - // ...and it places, on the audio lane, through the door `insert_source` - // uses: a second copy of the song at the playhead. - session.seek(1.0); - assert!( - session - .place_stream_at(1.0, &path, 0, Some(Lane::A1)) - .expect("its own file is on this timeline") - ); - assert_eq!(session.lane_clips(Lane::A1).len(), 2); - assert!(session.lane_clips(Lane::V1).is_empty(), "still no picture"); - - // Both picture rows carry the reason rather than the format's detail - // line, each naming itself; the audio formats are what this timeline is - // and are never refused. - assert_eq!( - format_refusal(&session, Format::Mp4).as_deref(), - Some("no picture — an mp4 would be black; export WAV, FLAC, MP3 or OGG") - ); - assert_eq!( - format_refusal(&session, Format::Av1).as_deref(), - Some("no picture — an AV1 Matroska would be black; export WAV, FLAC, MP3 or OGG") - ); - assert_eq!( - format_refusal(&session, Format::Av1Mp4).as_deref(), - Some("no picture — an AV1 mp4 would be black; export WAV, FLAC, MP3 or OGG") - ); - assert_eq!(format_refusal(&session, Format::Wav), None); - assert_eq!(format_refusal(&session, Format::Flac), None); - assert_eq!(format_refusal(&session, Format::Mp3), None); - } - - fn info( - index: usize, - rate: u32, - channels: u16, - lang: Option<&str>, - decodable: bool, - ) -> StreamInfo { - StreamInfo { - index, - codec: if decodable { "aac" } else { "unknown" }.into(), - channels, - sample_rate: rate, - lang: lang.map(str::to_string), - decodable, - } - } - - /// A file's every audio track gets a row: the ones the timeline can take - /// are placeable, the ones it cannot are listed greyed with the reason. - /// Which rows exist at all is the branchy part of the panel, so it is - /// planned as data and checked here rather than through the pointer. - #[test] - fn every_audio_stream_of_a_file_is_a_row_usable_or_not() { - let multi = PathBuf::from("/m/movie.mp4"); - let sources = [source("/m/movie.mp4", 0)]; - let mut streams = HashMap::new(); - streams.insert( - multi.clone(), - vec![ - info(0, 44_100, 2, None, true), - info(1, 44_100, 2, Some("fra"), true), - info(2, 22_050, 1, Some("deu"), true), - info(3, 0, 0, None, false), - ], - ); - let rows = library_rows( - &sources, - &streams, - &HashMap::new(), - Some((44_100, 2)), - |_| 90, - ); - assert_eq!( - rows.iter().map(|r| r.stream).collect::>(), - [0, 1, 2, 3], - "one row per audio stream, in file order" - ); - assert!( - rows.iter().all(|r| r.path == multi && r.tint == 0), - "every stream of one file wears the file's own tint" - ); - assert_eq!(rows[0].name, "movie.mp4 [audio 1]"); - assert_eq!(rows[1].name, "movie.mp4 [audio 2]"); - assert_eq!(rows[1].detail, "fra 44.1 kHz stereo"); - // Placeable: the one already on the timeline, and the one that matches - // it. The mono track cannot join a stereo timeline -- one device and one - // copied AAC track for the whole of it -- and the codec we cannot read - // cannot join anything. Both say which. Its 22 kHz is *not* part of that - // any more: a rate of its own is resampled at the decoder's door, and a - // row greyed for one the engine accepts is this picker telling a lie. - assert_eq!((&rows[0].unusable, &rows[1].unusable), (&None, &None)); - assert_eq!(rows[2].unusable.as_deref(), Some("the timeline is stereo")); - assert_eq!( - unusable(&info(9, 48_000, 2, None, true), Some((44_100, 2))), - None, - "48 kHz stereo joins a 44.1 kHz stereo timeline" - ); - assert_eq!(rows[3].unusable.as_deref(), Some("unsupported codec")); - assert_eq!( - rows[3].detail, "", - "a stream we cannot parse claims nothing" - ); - // Every row is the same file, so every row is that file's length. - assert!(rows.iter().all(|r| r.frames == 90)); - - // The single-stream case is exactly one row and no stream tag: no - // regression for the media everything else in the world is. - let plain = [source("/m/plain.mp4", 0)]; - let mut one = HashMap::new(); - one.insert( - PathBuf::from("/m/plain.mp4"), - vec![info(0, 44_100, 2, None, true)], - ); - let rows = library_rows(&plain, &one, &HashMap::new(), Some((44_100, 2)), |_| 90); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].name, "plain.mp4"); - assert_eq!( - rows[0].detail, "", - "one audio track is the row it has always been: name and length" - ); - // ...as is a silent file, and a file not probed yet. - let mut silent = HashMap::new(); - silent.insert(PathBuf::from("/m/plain.mp4"), Vec::new()); - for probe in [silent, HashMap::new()] { - let rows = library_rows(&plain, &probe, &HashMap::new(), None, |_| 90); - assert_eq!(rows.len(), 1); - assert_eq!(rows[0].name, "plain.mp4"); - assert_eq!(rows[0].detail, ""); - } - - // A second stream *placed* on the timeline is a source entry of its - // own: it keeps its row, no duplicate appears for it, and the rows of - // one file stay together whatever order the entries came in. - let placed = [ - source("/m/movie.mp4", 0), - source("/m/other.mp4", 0), - source("/m/movie.mp4", 2), - ]; - streams.insert( - PathBuf::from("/m/other.mp4"), - vec![info(0, 44_100, 2, None, true)], - ); - let rows = library_rows( - &placed, - &streams, - &HashMap::new(), - Some((44_100, 2)), - |_| 90, - ); - assert_eq!( - rows.iter() - .map(|r| (file_name(&r.path), r.stream)) - .collect::>(), - [ - ("movie.mp4".to_string(), 0), - ("other.mp4".to_string(), 0), - ("movie.mp4".to_string(), 2), - ("movie.mp4".to_string(), 1), - ("movie.mp4".to_string(), 3), - ] - ); - assert!( - rows[2].unusable.is_none(), - "a stream already on the timeline is playing, whatever a probe says" - ); - assert_eq!(rows[1].tint, 1, "the other file is the other tint"); - } - - /// What the clip menu offers, and where it hangs. The two items that act on - /// the playhead rather than on the clicked clip are the ones that can be - /// inapplicable, and a menu at the edge of the window has to come back - /// inside it or its last item cannot be clicked at all. - #[test] - fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() { - use keymap::{ActionId, Keymap}; - // Frames 30..90 of the timeline, taken from the head of its source. - let clip = Clip { - start: 30, - in_frame: 0, - out_frame: 60, - source: 0, - link: None, - eq: None, - color: None, - fit: FitPolicy::default(), - speed: Speed::NORMAL, - }; - assert_eq!(clip.end(), 90); - let a1 = Lane::A1; - let v1 = Lane::V1; - // The question the clip menu asks: a timeline is open and the menu was - // opened on this clip, at this playhead. - let on = |clip: &Clip, lane, action, playhead| { - enable( - action, - Ctx { - clip: Some((*clip, lane)), - playhead, - timeline: true, - ..Ctx::default() - }, - ) - }; - let offered = |clip: &Clip, lane, action, playhead| on(clip, lane, action, playhead).yes(); - // Cut splits from inside only: neither edge has anything to split off. - assert!(offered(&clip, v1, ActionId::Cut, 31)); - assert!(offered(&clip, v1, ActionId::Cut, 89)); - assert!(!offered(&clip, v1, ActionId::Cut, 30)); - assert!(!offered(&clip, v1, ActionId::Cut, 90)); - assert!(!offered(&clip, v1, ActionId::Cut, 200)); - // A slowed clip refuses more than the edges do, and it may not say the - // edges' words while doing it: at a quarter speed each of its sixty - // source frames is on screen four timeline frames, and only the first of - // the four is a frame the file has. The three between are inside the - // clip by any reading of the playhead, so "only from inside a clip" - // there is a refusal claiming something the screen contradicts. - let slow = Clip { - speed: Speed::MIN, - ..clip - }; - assert_eq!(slow.frames(), 240, "a quarter speed is four times as long"); - assert!(offered(&slow, v1, ActionId::Cut, 34), "34 is a source frame"); - assert!(!offered(&slow, v1, ActionId::Cut, 35)); - assert_eq!( - on(&slow, v1, ActionId::Cut, 35).why(), - Some("this speed holds one frame here — step to the next"), - ); - assert_eq!( - on(&slow, v1, ActionId::Cut, 30).why(), - Some("only from inside a clip"), - "the head is still the edge's refusal, speed or no speed", - ); - // Regroup is the other way round: only where this clip meets another. - assert!(offered(&clip, v1, ActionId::Regroup, 30)); - assert!(offered(&clip, v1, ActionId::Regroup, 90)); - assert!(!offered(&clip, v1, ActionId::Regroup, 60)); - // Detach is the clip's own business: nothing to take apart in one that - // names no group, and whether the group still has another half is the - // engine's question. Group is offered on every clip, for that reason. - assert!(!offered(&clip, v1, ActionId::Detach, 0)); - let grouped = Clip { - link: Some(3), - ..clip - }; - assert!(offered(&grouped, v1, ActionId::Detach, 60)); - assert!(offered(&clip, a1, ActionId::Group, 0)); - // The equalizer is the one item the *lane* decides: it filters samples, - // and a video clip has none of its own. Never the playhead's business. - assert!(offered(&clip, a1, ActionId::Equalizer, 0)); - assert!(offered(&clip, a1, ActionId::Equalizer, 60)); - assert!(!offered(&clip, v1, ActionId::Equalizer, 60)); - // The rest act on the clip that was clicked, so they always mean - // something -- the engine words its own refusals. - for action in [ActionId::Delete, ActionId::Lift, ActionId::ToggleMute] { - assert!(offered(&clip, v1, action, 0)); - assert!(offered(&clip, a1, action, 60)); - } - // Except the grade, which is a picture setting: offered on a video - // clip wherever the playhead is, dimmed on a waveform. - assert!(offered(&clip, v1, ActionId::Color, 0)); - assert!(!offered(&clip, a1, ActionId::Color, 60)); - // The two kinds of no, which is what the row is told apart by: a grade - // on a waveform is a *class* answer -- an audio clip has no picture and - // never will, so the menu leaves the item out entirely -- where a cut at - // the clip's edge is this moment's answer and the next click of the - // playhead changes it, so that one is drawn, dimmed, and says why. - // - // What the menu draws for a clip of each kind, in order: the render - // loop's `continue`, as a list. - let menu = |lane, image, playhead| { - MENU_ITEMS - .into_iter() - .filter(|&action| { - enable( - action, - Ctx { - clip: Some((clip, lane)), - image, - playhead, - timeline: true, - ..Ctx::default() - }, - ) - .listed() - }) - .collect::>() - }; - // Sound: no grade and no fit policy, and the equalizer that is the - // whole reason an audio clip has a menu of its own. - let sound = menu(a1, false, 60); - assert!(!sound.contains(&ActionId::Color), "{sound:?}"); - assert!(!sound.contains(&ActionId::Fit), "{sound:?}"); - assert!(sound.contains(&ActionId::Equalizer)); - assert!(sound.contains(&ActionId::Silence)); - // Picture: the mirror of it. The sound of a take is the audio lane's, - // clip for clip, so the equalizer is not this clip's business -- but the - // silence scan is, because it opens on the half it is grouped with. - let picture = menu(v1, false, 60); - assert!(!picture.contains(&ActionId::Equalizer), "{picture:?}"); - assert!(picture.contains(&ActionId::Color)); - assert!(picture.contains(&ActionId::Fit)); - assert!(picture.contains(&ActionId::Silence)); - // A still: picture with no sound anywhere, ever. Graded, fitted and - // re-timed like any other clip (a speed reaches a still through the same - // rewrite), scanned like none. - let still = menu(v1, true, 60); - assert!(!still.contains(&ActionId::Silence), "{still:?}"); - assert!(!still.contains(&ActionId::Equalizer), "{still:?}"); - assert!(still.contains(&ActionId::Color)); - assert!(still.contains(&ActionId::Fit)); - assert!(still.contains(&ActionId::Speed)); - // ...and the state refusals are on all three, dimmed rather than gone: - // at 30 the playhead is on this clip's head, where a cut has nothing to - // split off -- a row the next click of the playhead lights. - for rows in [menu(a1, false, 30), menu(v1, false, 30), menu(v1, true, 30)] { - assert!(rows.contains(&ActionId::Cut), "{rows:?}"); - assert!(rows.contains(&ActionId::Detach), "{rows:?}"); - } - // The actions card is the other half of the rule: it lists the whole - // registry, so a class refusal is dimmed there with its reason and never - // dropped -- an action missing from the one surface that lists - // everything would read as an action that does not exist. - let listed: Vec = keys_rows() - .into_iter() - .filter_map(|r| match r { - KeyRow::Act(action) => Some(action), - _ => None, - }) - .collect(); - for (lane, action) in [ - (a1, ActionId::Color), - (a1, ActionId::Fit), - (v1, ActionId::Equalizer), - ] { - assert!(matches!(on(&clip, lane, action, 60), Enable::Hidden(_))); - assert!(listed.contains(&action), "{action:?} left the actions card"); - assert!(on(&clip, lane, action, 60).why().is_some()); - } - assert!(matches!(on(&clip, v1, ActionId::Cut, 30), Enable::No(_))); - assert!(matches!(on(&clip, v1, ActionId::Regroup, 60), Enable::No(_))); - assert!(matches!(on(&clip, v1, ActionId::Detach, 0), Enable::No(_))); - // Every refusal says something, and says it short enough to sit in the - // menu's right-hand column beside a label -- the still's included, which - // the card dims with while the menu leaves the row out. - for action in MENU_ITEMS { - for (lane, image) in [(v1, false), (a1, false), (v1, true)] { - for playhead in [0, 30, 60, 90] { - let refusal = enable( - action, - Ctx { - clip: Some((clip, lane)), - image, - playhead, - timeline: true, - ..Ctx::default() - }, - ); - if let Some(why) = refusal.why() { - assert!(!why.is_empty() && why.len() <= 30, "{action:?}: {why:?}"); - } - } - } - } - assert!(matches!( - enable( - ActionId::Silence, - Ctx { - clip: Some((clip, v1)), - image: true, - playhead: 60, - timeline: true, - ..Ctx::default() - } - ), - Enable::Hidden(_) - )); - // The editor as a whole, which is how the actions card asks: with no - // timeline nothing is offered, an export leaves only its own cancel, - // and the three that act on the marked clip say so when none is. - let whole = |action, ctx| enable(action, ctx); - assert_eq!( - whole(ActionId::Play, Ctx::default()), - Enable::No("no timeline open") - ); - let live = Ctx { - timeline: true, - playable: true, - ..Ctx::default() - }; - assert!(whole(ActionId::Play, live).yes()); - // ...and an open timeline with nothing on its lanes refuses the - // transport in the oracle rather than in the button, which is what - // makes the key and the button say the same thing. - assert_eq!( - whole( - ActionId::Play, - Ctx { - playable: false, - ..live - } - ), - Enable::No("put a clip on a lane first") - ); - // The magnet and the monitoring level are the editor's own and answer - // with no timeline at all -- the keyboard always fired them there, and - // now so does the toolbar. - for editor_wide in [ - ActionId::ToggleSnap, - ActionId::ToggleMute, - ActionId::VolumeUp, - ActionId::VolumeDown, - ] { - assert!( - whole(editor_wide, Ctx::default()).yes(), - "{editor_wide:?} is dead with no file open while its key still fires" - ); - } - assert!(!whole(ActionId::Delete, live).yes()); - assert!(!whole(ActionId::Paste, live).yes()); - assert!( - whole( - ActionId::Paste, - Ctx { - clipboard: true, - ..live - } - ) - .yes() - ); - assert!(!whole(ActionId::CancelExport, live).yes()); - let busy = Ctx { - exporting: true, - ..live - }; - assert!(whole(ActionId::CancelExport, busy).yes()); - for action in ActionId::ALL { - // Nothing may touch the edit list while an export is reading it -- - // and the palette does not: it repaints this window and writes one - // word to the user's own config file, which is why it is the one - // action besides the cancel that stays live here. - let allowed = action == ActionId::CancelExport || action == ActionId::Theme; - assert_eq!( - whole(action, busy).yes(), - allowed, - "{action:?} while an export reads the edit list" - ); - } - // The playhead frame is the engine's own rule, boundary included. - assert_eq!(frame_at(1.0, 30.), 30); - assert_eq!(frame_at(0.0, 30.), 0); - assert_eq!(frame_at(-1.0, 30.), 0); - // Where it hangs: at the pointer when it fits, back inside when not. - let viewport = size(px(800.), px(400.)); - assert_eq!(menu_at(point(px(10.), px(10.)), viewport, 150.), (10., 10.)); - assert_eq!( - menu_at(point(px(700.), px(380.)), viewport, 150.), - (800. - MENU_W, 250.) - ); - // A window smaller than the menu loses its bottom, never its top. - assert_eq!( - menu_at(point(px(90.), px(40.)), size(px(100.), px(50.)), 150.), - (0., 0.) - ); - // Every item is an action the registry knows, so the menu and the keys - // menu say the same thing about it -- and none of them is unreachable - // by keyboard, which is what makes the hint column worth drawing. - let keymap = Keymap::defaults(); - for action in MENU_ITEMS { - assert!(ActionId::ALL.contains(&action), "{action:?} is not listed"); - assert_ne!(keymap.display(action), "unbound", "{action:?}"); - } - // ...and the whole card still fits the 640x360 floor, however many items - // it grows to: the list is what scrolls where the window is too short - // for it, never the card that grows. - let items = MENU_ITEMS.len() + 1; // Properties - let floor = size(px(640.), px(360.)); - assert!(MENU_PAD * 2. + menu_rows_h(items, floor) <= 360., "too tall"); - assert!( - menu_rows_h(items, floor) / MENU_ROW_H >= 12., - "too few items visible to scan on the smallest window" - ); - assert_eq!( - menu_at(point(px(0.), px(0.)), floor, { - MENU_PAD * 2. + menu_rows_h(items, floor) - }), - (0., 0.) - ); - // The picker is the same card and the longest list in it is the palette - // family list, which grows every time somebody asks for more colours. - // Twelve of them still stand on screen *whole* at the floor -- so the - // list's `overflow_y_scroll` is a safety net rather than something a - // person has to find. The day a family makes this fail is the day the - // card owes the affordance line the inspector and the cards carry - // ("more below — scroll the …"): a row nobody knows is under the fold - // is a row that is not there, and no scroll bar says it. - let families = crate::ui::theme::PaletteId::ALL.len(); - assert_eq!( - menu_rows_h(families, floor), - families as f32 * MENU_ROW_H, - "{families} palettes no longer fit 640x360 -- the picker now needs \ - the 'more below' line and a keyboard cursor that scrolls into view" - ); - // ...and the detail beside each one is short enough to survive the - // right-hand column at that width instead of being truncated mid-word. - for id in crate::ui::theme::PaletteId::ALL { - assert!(id.detail().len() <= 30, "{id:?}: {:?}", id.detail()); - } - } - - /// Both menus, at the two things they can be opened on, and the box each - /// one is drawn in. Two rules, and the render obeys them by *calling* what - /// this calls -- [`menu_items`] and [`row_items`] are the only lists either - /// menu is built from, and [`menu_rows_h`] is the height each is both placed - /// by and drawn to: - /// - /// 1. a row exists only where the oracle lists the action for the very thing - /// that was right-clicked, so an item can never offer a video action on a - /// waveform (the complaint this comes from) and a new action added to - /// `MENU_ITEMS` cannot appear where it does not apply; - /// 2. the whole card is inside the window, wherever it was opened and - /// however long the list -- a menu drawn past the bottom edge is a menu - /// whose last items nobody can click. - #[test] - fn a_menu_offers_only_what_applies_and_is_drawn_inside_the_window() { - use keymap::ActionId; - let clip = Clip { - start: 30, - in_frame: 0, - out_frame: 60, - source: 0, - link: Some(1), - eq: None, - color: None, - fit: FitPolicy::default(), - speed: Speed::NORMAL, - }; - let ctx = |lane, image| Ctx { - clip: Some((clip, lane)), - image, - playhead: 60, - timeline: true, - ..Ctx::default() - }; - // The oracle is the whole of what the menu draws: every item it lists is - // one the oracle would list, and every item it leaves out is one the - // oracle hides -- there is no third answer, and no hand-written list. - for (lane, image) in [(Lane::V1, false), (Lane::A1, false), (Lane::V1, true)] { - let ctx = ctx(lane, image); - let rows = menu_items(ctx); - for action in MENU_ITEMS { - assert_eq!( - rows.contains(&action), - enable(action, ctx).listed(), - "{action:?} on {lane:?}, image={image}" - ); - } - } - // Sound has no picture settings; picture has no equalizer of its own; a - // still has no sound to scan. The user's own words: an audio clip must - // not be offered what only a picture can be given. - let sound = menu_items(ctx(Lane::A1, false)); - assert!(!sound.contains(&ActionId::Color), "{sound:?}"); - assert!(!sound.contains(&ActionId::Fit), "{sound:?}"); - assert!(sound.contains(&ActionId::Equalizer)); - let picture = menu_items(ctx(Lane::V1, false)); - assert!(!picture.contains(&ActionId::Equalizer), "{picture:?}"); - assert!(picture.contains(&ActionId::Color)); - assert!(!menu_items(ctx(Lane::V1, true)).contains(&ActionId::Silence)); - // The library menu is the same rule on the other panel: its items come - // off `row_items` and nothing else, and the two that change the timeline - // say why rather than being clicked and refused afterwards. - let live = RowCtx { - timeline: true, - usable: true, - ..RowCtx::default() - }; - for ctx in [ - live, - RowCtx { - usable: false, - ..live - }, - RowCtx { placed: 2, ..live }, - RowCtx { - exporting: true, - ..live - }, - RowCtx::default(), - ] { - let rows = row_items(ctx); - for item in ROW_ITEMS { - assert_eq!(rows.contains(&item), row_enable(item, ctx).listed()); - } - // Whatever the state, the two that need neither timeline nor edit - // list are offered: a file is always describable and findable. - assert!(row_enable(RowItem::Reveal, ctx).yes()); - assert!(row_enable(RowItem::Properties, ctx).yes()); - } - assert!(row_enable(RowItem::Add, live).yes()); - assert!( - !row_enable( - RowItem::Add, - RowCtx { - usable: false, - ..live - } - ) - .yes(), - "a file that cannot join this timeline is not an Add anybody can ask for" - ); - assert!(!row_enable(RowItem::Remove, RowCtx { placed: 1, ..live }).yes()); - assert!(!row_enable(RowItem::Add, RowCtx::default()).yes()); - // Every refusal is short enough to sit in the hint column beside its - // label, the clip menu's rule. - for item in ROW_ITEMS { - for ctx in [live, RowCtx::default()] { - if let Some(why) = row_enable(item, ctx).why() { - assert!(!why.is_empty() && why.len() <= 30, "{why:?}"); - } - } - } - // ...and the box. Every window from the floor up, every corner of it, - // and every list length either menu can have: the card is placed by - // `MENU_PAD * 2 + menu_rows_h` and drawn to it, so this is the card. - for viewport in [ - size(px(640.), px(360.)), - size(px(800.), px(600.)), - size(px(1280.), px(690.)), - // Smaller than the floor the layout is sized for: it still may not - // draw outside the window it has. - size(px(320.), px(200.)), - ] { - for rows in 1..=MENU_ITEMS.len() + 1 { - let h = MENU_PAD * 2. + menu_rows_h(rows, viewport); - for at in [ - point(px(0.), px(0.)), - point(px(10.), px(10.)), - // The click that started all this: low in the window, where - // the menu used to hang off the bottom edge. - point(px(0.), viewport.height - px(4.)), - point(viewport.width - px(4.), viewport.height - px(4.)), - point(viewport.width * 2., viewport.height * 2.), - ] { - let (x, y) = menu_at(at, viewport, h); - assert!(x >= 0. && y >= 0., "{x},{y} outside {viewport:?}"); - assert!( - x + MENU_W <= f32::from(viewport.width) + 0.01, - "{rows} rows at {at:?} hang off the right of {viewport:?}" - ); - assert!( - y + h <= f32::from(viewport.height) + 0.01, - "{rows} rows at {at:?} hang off the bottom of {viewport:?}" - ); - } - } - } - // On any window with the room, the whole list is drawn rather than - // twelve rows of it and a scroll nobody is told about. - let items = MENU_ITEMS.len() + 1; - let real = size(px(1280.), px(690.)); - assert_eq!(menu_rows_h(items, real), items as f32 * MENU_ROW_H); - assert!(menu_rows_h(items, size(px(640.), px(360.))) < items as f32 * MENU_ROW_H); - } - - /// The other half of the keys menu's guarantee, and the audit this batch was - /// asked for kept as a test: no action may be a stroke and nothing else. - /// The actions card answers it for all of them at once -- its rows come off - /// [`ActionId::ALL`], so a fortieth action is on it the moment it exists and - /// there is no hand-written list here to fall behind. - #[test] - fn every_action_is_reachable_without_the_keyboard() { - use keymap::ActionId; - let source = ui_source(); - let source = source.as_str(); - let element = |id: &str| source.contains(&format!("\"{id}\"")); - let listed: Vec = keys_rows() - .iter() - .filter_map(|r| match r { - KeyRow::Act(a) => Some(*a), - _ => None, - }) - .collect(); - for action in ActionId::ALL { - assert_eq!( - listed.iter().filter(|a| **a == action).count(), - 1, - "{action:?} is reachable by keyboard only" - ); - } - // The snap has a door of its own as well as its row on the card: the - // button beside the zoom, which says which way it is set as well as - // setting it. - assert!(element("snap"), "no snap button beside the zoom"); - // And the card is a door the pointer can open: the panel's own button. - assert!(element("keys"), "no way to open the actions card"); - // The card-local strokes have the same rule, and each of them is a thing - // on its card: the graph and its two buttons, the colour bars and their - // reset, the speed bar and its presets, and the silence card's rows -- - // whose steppers are the pointer's only way to a threshold. - for id in [ - "eq-graph", - "eq-reset", - "eq-spectrum", - "color-bar", - "color-reset", - "speed-bar", - "speed-preset", - "silence-row", - "silence-step", - "mix-row", - "mix-step", - "silence-apply", - "export-confirm", - ] { - assert!(element(id), "{id} is not on any card"); - } - // ...and each one is named by the row that carries its stroke, so a - // card-local key added to `FIXED` with nothing to click fails here - // instead of being noticed by whoever tries to use the card without a - // keyboard. `KeyRow::Fixed` is "shown and never offered", which used to - // mean the twenty-eight rows below were the one part of this editor no - // reachability test read. - for fixed in keymap::FIXED.iter() { - match fixed.reach { - keymap::Reach::Click(id) => assert!( - element(id), - "{:?} ({}) points at {id}, which is on no card", - fixed.chord, - fixed.label - ), - // Nothing to click by decision, not by omission: getting out of - // a card, and the hold that repeats what a drag already does. - keymap::Reach::Gesture => {} - } - } - } - - /// The other half of "getting out of a card is a `Reach::Gesture`": the - /// gesture has to exist. Every card's scrim closes it on a press, so a hand - /// that never touches the keyboard can shut every one of them -- for seven - /// cards `esc` was the only exit, which is the same complaint as an action - /// reachable by stroke alone, said about the way out instead of the way in. - /// - /// Read off [`Player::modal`] rather than off a list written here: a card - /// counted there and not closed by [`Player::close_card`] fails this test - /// the day it is added, which is the only way the two stay in step. - #[test] - fn every_card_closes_without_the_keyboard() { - let source = ui_source(); - let source = source.as_str(); - // A fn's source, up to the next one: enough of a body to scan. - let body = |name: &str| -> &str { - let at = source - .find(&format!("fn {name}(")) - .unwrap_or_else(|| panic!("no fn {name} in main.rs")); - let rest = &source[at..]; - &rest[..rest[1..].find("\n fn ").map_or(rest.len(), |e| e + 1)] - }; - for card in [ - "keys_overlay", - "export_card", - "eq_card", - "color_card", - "speed_card", - "mix_card", - "silence_card", - ] { - let src = body(card); - assert!( - src.contains("this.close_card()"), - "{card}'s scrim swallows the press without closing the card: \ - escape is the only way out of it" - ); - assert!( - src.contains("MouseButton::Left, swallow"), - "{card}'s body does not swallow its own presses, so a press on \ - one of its controls would close the card under itself" - ); - } - // ...and every state that makes the window modal is a state that press - // clears. `exporting()` is not one of them: a running export is a job - // with a cancel button, not a card with a scrim. - let close = body("close_card"); - for field in body("modal").split("self.").skip(1).filter_map(|rest| { - let name: String = rest - .chars() - .take_while(|c| c.is_alphanumeric() || *c == '_') - .collect(); - (!rest[name.len()..].starts_with('(')).then_some(name) - }) { - assert!( - close.contains(&format!("self.{field}")), - "{field} makes the window modal and `close_card` leaves it set: \ - that card cannot be closed by pointer" - ); - } - } - - /// A clip too short to hit is still a clip: at a far zoom-out its box is - /// drawn [`HIT_MIN`] wide rather than the fraction of a pixel it is worth, - /// because a box nobody can put a pointer on cannot be selected, dragged, - /// trimmed or given a menu -- and an invisible unselectable take is strictly - /// worse than one drawn a few pixels too wide. - #[test] - fn a_clip_box_is_never_narrower_than_its_target() { - // Two seconds on a bed showing an hour: a fifth of a pixel. - let far = Scale { - pps: 0.1, - start: 0., - }; - assert!(far.width_px(2.) < 1., "the fixture is not zoomed out enough"); - assert_eq!(clip_width(far.width_px(2.)), HIT_MIN); - // Zero is the floor's own case: a clip trimmed to nothing, and the - // width a lane draws before its first frame is measured. - assert_eq!(clip_width(0.), HIT_MIN); - // What is already wide enough keeps its own width, to the pixel: the - // floor is a floor and never a resize. - let near = Scale::default(); - assert_eq!(clip_width(near.width_px(5.)), near.width_px(5.)); - // ...and the padding is not trimmable: the strips are asked of the - // clip's own width, so a box drawn wider than its length keeps all of - // that box as a body to select and drag by ([`trims`]). - assert!(!trims(far.width_px(2.))); - assert!(clip_width(far.width_px(2.)) >= HIT_MIN); - } - - /// What the Detach and Group items do to a real timeline: a music video's - /// sound comes off its picture, Delete on the loose half takes that half - /// only, undo puts both back, and Group makes the two one take again -- - /// whole-take delete and all. - #[test] - fn a_detached_half_is_removed_alone_and_groups_again() { - let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); - session.set_gain(0.0); - assert!(whole_take(&session, Lane::V1, 0), "one take to start with"); - assert!(whole_take(&session, Lane::A1, 0)); - let frames = session.lane_clips(Lane::V1)[0].len(); - - // Detach audio: neither half is a whole take any more, so Delete on - // either leaves the other exactly where it is. - assert!(session.ungroup(Lane::V1, 0)); - assert!( - !whole_take(&session, Lane::A1, 0), - "the sound is a half now" - ); - assert!(!whole_take(&session, Lane::V1, 0), "and so is the picture"); - assert!(session.lift_clip(Lane::A1, 0)); - assert!(session.lane_clips(Lane::A1).is_empty(), "the sound went"); - assert_eq!(session.lane_clips(Lane::V1).len(), 1, "the picture stayed"); - assert_eq!(session.lane_clips(Lane::V1)[0].len(), frames, "untrimmed"); - - // One undo per edit, the removal then the detach. - assert!(session.undo()); - assert_eq!(session.lane_clips(Lane::A1).len(), 1, "the sound is back"); - assert!(session.undo()); - assert!(whole_take(&session, Lane::A1, 0), "one take again"); - - // Group: the partner is the clip covering these very frames on the - // other track, which is what the item hands the engine. - assert!(session.ungroup(Lane::V1, 0)); - assert_eq!(span_partner(&session, Lane::V1, 0), Some((Lane::A1, 0))); - session - .group(Lane::V1, 0, Lane::A1, 0) - .expect("both halves still cover the same frames"); - assert!( - whole_take(&session, Lane::A1, 0), - "a take that ripples again" - ); - assert_eq!( - span_partner(&session, Lane::V1, 0), - None, - "and nothing left on another track to group with" - ); - } - - /// Which clip Group reaches when more than one covers the span: the sound, - /// whatever order the lanes are stored in. A project file may hold them in - /// any order -- a video layer *before* the audio lane among them -- and - /// "group this" means the other half of the take, never the layer above it. - #[test] - fn group_reaches_the_sound_before_a_video_layer_over_it() { - use engine::project::LaneKind; - - let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); - session.set_gain(0.0); - let v2 = session.add_lane(LaneKind::Video); - // A bare layer, through the one-lane door: a *drop* on V2 brings the - // file's sound down with it and would put a third clip over this span. - let whole = session.lane_clips(Lane::V1)[0]; - assert!( - session.place_at(v2, 0.0, whole), - "a layer covering the same frames as the take" - ); - - // Saved and loaded back with the lanes in the order a hand-written - // project may hold them: the sound last, behind the layer. - let dir = engine::scratch::Scratch::dir("ve_group"); - let file = dir.join("lanes.edith"); - session.save_project(&file).expect("save the project"); - let text = std::fs::read_to_string(&file).expect("read it back"); - let (sound, rest): (Vec<&str>, Vec<&str>) = - text.lines().partition(|l| l.starts_with("audio ")); - std::fs::write( - &file, - format!("{}\n{}\n", rest.join("\n"), sound.join("\n")), - ) - .expect("write the reordered project"); - let mut session = PlaybackSession::open_project(&file).expect("it loads as it stands"); - std::fs::remove_dir_all(&dir).ok(); - assert_eq!( - session.lanes(), - vec![Lane::V1, v2, Lane::A1], - "the sound is the last lane there" - ); - - // Detached, so Group has a choice to get wrong: the layer covers these - // frames too, and it is the lane the walk meets first. - assert!(session.ungroup(Lane::V1, 0)); - // Group on the picture reaches the sound, not that layer. - assert_eq!(span_partner(&session, Lane::V1, 0), Some((Lane::A1, 0))); - session - .group(Lane::V1, 0, Lane::A1, 0) - .expect("the two halves cover the same frames"); - // ...and a lane of its own kind is still groupable, once the sound is - // spoken for: two video lanes may be one take. - assert_eq!( - span_partner(&session, Lane::V1, 0), - Some((v2, 0)), - "the layer is what is left to group with" - ); - } - - /// The refusal path, end to end against the real files: an incompatible - /// import changes nothing, and the library mirrors `sources()` 1:1, so a - /// refused file cannot leave a row behind. - #[test] - fn a_refused_import_leaves_no_row_and_an_accepted_one_is_whole() { - let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); - // Silent like the engine suite: this opens the real device. - session.set_gain(0.0); - assert_eq!(session.sources().len(), 1); - // 640x360 joins now (the project canvas places it), and so does a file - // with no sound (it plays silence over its span). What is left is one - // output device: a mono track cannot join a stereo timeline. - let refusal = session - .import(&asset("test_ac3.mp4")) - .expect_err("a mono track must not join a stereo timeline") - .to_string(); - assert!(refusal.contains("audio"), "refusal must name it: {refusal}"); - assert_eq!(session.sources().len(), 1, "a refusal added a row"); - // An accepted one does add a row, and it reads as the whole file: 4 s - // at 30 fps, its own length and not one taken off the lanes. - session.import(&asset("test_av2.mp4")).expect("av2 matches"); - assert_eq!(session.sources().len(), 2); - let second = session.sources()[1].path.clone(); - assert_eq!(session.file_frames(&second), 120); - assert_eq!(timecode(120. / 30., 30.), "00:00:04:00"); - } - - /// What the Add button and a dropped row both do, minus the pointer: the - /// clip [`Player::insert_source`] builds, put in where the playhead is. One - /// call, so what a drop does cannot drift from what the button does. - #[test] - fn adding_a_row_drops_the_whole_source_in_at_the_playhead() { - let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); - session.set_gain(0.0); - session.import(&asset("test_av2.mp4")).expect("av2 matches"); - // In the library only: the 5 s the fixture is, still. - assert_eq!(session.timeline_duration(), 5.0); - // Two seconds in, which is inside the first take: the insert splits it. - session.seek(2.0); - let second = session.sources()[1].path.clone(); - let frames = session.file_frames(&second); - // Through the engine door `insert_source` uses, with the row's own - // stream: the button, the drop and this are one call. - assert!( - session - .place_stream_at(2.0, &second, 0, None) - .expect("av2 is already on the timeline") - ); - // The whole of source 1 went in and nothing was painted over: the - // timeline is longer by exactly that file. - assert_eq!(session.timeline_duration(), 9.0); - let (video, audio) = (session.lane_clips(Lane::V1), session.lane_clips(Lane::A1)); - // One take, not a video clip with no sound under it: both lanes hold - // the same clip at the same place, in the same group. - let at = |lane: &[Clip]| { - *lane - .iter() - .find(|c| c.start == 60) - .expect("inserted at 2 s") - }; - assert_eq!(at(video), at(audio)); - assert_eq!(at(video).source, 1); - assert_eq!(at(video).len(), frames); - assert!(at(video).link.is_some()); - assert_eq!(video.len(), audio.len()); - - // The same door with a *second audio stream* of a file already there: - // a new source entry, the same picture, and the row that was dragged - // is what plays. This is the whole user-facing point of the slice. - let mut session = - PlaybackSession::open(asset("test_multilang.mp4")).expect("open the fixture"); - session.set_gain(0.0); - let path = session.sources()[0].path.clone(); - let frames = session.file_frames(&path); - let end = session.timeline_duration(); - assert!( - session - .place_stream_at(end, &path, 1, None) - .expect("the French track shares the timeline's parameters") - ); - assert_eq!(session.sources()[1].audio_stream, 1); - assert_eq!(session.timeline_duration(), end * 2.0); - // Both rows are the same file, so both rows are that file's length -- - // the second one before any clip of its own existed. - assert_eq!(session.file_frames(&path), frames); - } - - /// The drop a hand actually makes: a library row let go on the *empty* bed - /// past the last clip, which is most of the bed on any timeline shorter - /// than the window. The whole chain the release runs, minus gpui's own - /// pointer read -- [`Player::place_frame`]'s [`landing`], the frame back - /// through the rate as [`Player::insert_source`] hands it over, and the one - /// engine door a row goes through -- and the head lands on the frame the - /// ghost was drawn on, black in front of it. It used to be swallowed by the - /// clipboard's clamp inside `Project::paste` and appended after the last - /// clip wherever it was let go, which is the bug this pins. - #[test] - fn a_row_dropped_on_the_open_bed_lands_under_the_pointer() { - let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); - session.set_gain(0.0); - session.import(&asset("test_av2.mp4")).expect("av2 matches"); - let second = session.sources()[1].path.clone(); - let fps = session.meta().frame_rate; - assert_eq!(session.timeline_duration(), 5.0); - // 5 s of timeline on a bed 30 s wide: the open bed past the last clip - // is five sixths of it. - let bed: Bounds = Bounds { - origin: point(px(12.), px(400.)), - size: size(px(600.), px(LANE_H)), - }; - let scale = Scale { - pps: 20., - start: 0., - }; - - // What `Player::place_frame` answers for a pointer 200 px along the - // bed: ten seconds in, five seconds past the end of the timeline, and - // no mark anywhere near enough to pull it back. - let clips = [session.lane_clips(Lane::V1), session.lane_clips(Lane::A1)]; - let marks = snap_marks(&clips, None, frame_at(session.now(), fps)); - let under = frame_at(scale.time_at(px_along(px(212.), bed)), fps); - let (at, cue) = landing(under, 0, 0, true, scale.snap_frames(fps), &marks); - assert_eq!((at, cue), (300, None), "the pointer is on frame 300"); - - // ...and what the release does with it: the frame back through the same - // rate every box is drawn at, into the door the Add button uses too. - assert!( - session - .place_stream_at(f64::from(at) / fps, &second, 0, None) - .expect("av2 is already on this timeline") - ); - let head = |lane| { - session - .lane_clips(lane) - .last() - .copied() - .expect("the dropped clip") - }; - assert_eq!( - head(Lane::V1).start, - at, - "the drop landed somewhere other than under the pointer" - ); - assert_eq!(head(Lane::A1).start, at, "...and its sound with it"); - assert!(head(Lane::V1).link.is_some(), "one grouped take"); - assert_eq!(head(Lane::V1).link, head(Lane::A1).link); - // The bed in front of it stays black: nothing was stretched to reach - // it, and the 4 s file is the whole of what was added. - assert_eq!(session.timeline_duration(), 14.0); - } - - /// Remove from library, through the door the menu item uses - /// ([`Player::remove_source`] calls exactly this): refused by name while - /// clips play from the file, and once they do not the row leaves the list. - #[test] - fn removing_a_row_is_refused_while_it_plays_and_takes_the_row_away() { - let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); - session.set_gain(0.0); - // Imported, then dragged onto the end: an import alone fills the - // library, and a row with no clip is removable without any refusal to - // test. This one has to have a take on the timeline. - session.import(&asset("test_av2.mp4")).expect("av2 matches"); - let second = session.sources()[1].path.clone(); - let end = session.timeline_duration(); - assert!( - session - .place_stream_at(end, &second, 0, None) - .expect("a file just imported is on this timeline") - ); - let streams = HashMap::new(); - let rows = |session: &PlaybackSession| { - library_rows(session.sources(), &streams, &HashMap::new(), None, |_| 0).len() - }; - assert_eq!(rows(&session), 2, "a row per source"); - - let refusal = session - .remove_source(&second, 0) - .expect_err("its take is still on the timeline") - .to_string(); - assert!(refusal.contains("still plays"), "{refusal}"); - assert!( - refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"), - "the refusal names the lanes to clear: {refusal}" - ); - assert_eq!(rows(&session), 2, "and the row is still there"); - - // Delete that take -- the whole group, from either half -- and the file - // can go. The list is what says so. - let last = session.lane_clips(Lane::V1).len() - 1; - assert!(session.delete_clip(Lane::V1, last)); - session - .remove_source(&second, 0) - .expect("nothing plays av2 any more"); - assert_eq!(rows(&session), 1, "the row went with it"); - assert_eq!(session.sources().len(), 1); - // The one file left is held to the same rule and no other: its own take - // is still on the lanes, so it stays... - let first = session.sources()[0].path.clone(); - let refusal = session - .remove_source(&first, 0) - .expect_err("its take is still on the timeline") - .to_string(); - assert!(refusal.contains("still plays"), "{refusal}"); - // ...and once nothing plays it, the *last* row goes too. What is left - // is the empty library `Player::close_session` turns back into the - // window the editor launches as -- the user-reported bug was that this - // very removal was refused, leaving a row that could never be taken - // out. - assert!(session.delete_clip(Lane::V1, 0)); - session - .remove_source(&first, 0) - .expect("the only row goes like any other"); - assert_eq!(rows(&session), 0, "an empty library"); - assert!(session.sources().is_empty()); - // And it is still a session: silent, empty, and asked for its length - // rather than panicking on a source list that is not there. - assert_eq!(session.timeline_duration(), 0.0); - assert!( - session.save_project(&asset("nothing.edith")).is_err(), - "a project naming no file could never be opened again, so it is not written" - ); - // A row this timeline never had is refused, not panicked on. - assert!(session.remove_source(&second, 0).is_err()); - } - - /// The clipboard after a library removal. A copied clip names its file by - /// index and a removal renumbers the list, so this is the difference - /// between pasting the take that was copied and pasting **another file** - /// over the same range ([`clipboard_after_remove`], called by - /// [`Player::remove_source`]). - #[test] - fn a_copied_clip_is_renumbered_or_dropped_when_a_row_leaves_the_library() { - let clip = |source: usize| Clip { - start: 0, - in_frame: 0, - out_frame: 30, - source, - link: None, - eq: None, - color: None, - fit: Default::default(), - speed: Default::default(), - }; - // Copied from source 2, source 0 removed: the same file is source 1 now. - assert_eq!( - clipboard_after_remove(Some(clip(2)), 0).map(|c| c.source), - Some(1), - "the clipboard follows its file down the list" - ); - // Copied from a source *before* the one that went: untouched. - assert_eq!( - clipboard_after_remove(Some(clip(0)), 2).map(|c| c.source), - Some(0) - ); - // Copied from the row that was just removed: there is nothing left to - // paste, and pasting the next file along would be a lie. - assert!(clipboard_after_remove(Some(clip(1)), 1).is_none()); - assert!(clipboard_after_remove(None, 0).is_none()); - } - - /// The trim-a-clip path through the doors the edge drag uses: - /// [`Player::trim_to`] clamps the pointer with `trim_room` and - /// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less - /// of its file, the sound linked to it follows, the head trim moves the - /// in-point, and one undo takes a whole gesture back. - /// - /// The routing *to* these doors -- the 6 px edge strip claiming the press - /// the clip's own body-drag would otherwise take -- is gpui hitbox - /// behaviour (`occlude`) and is not reachable without a window. - #[test] - fn a_clip_trimmed_by_its_edge_plays_less_of_its_file() { - use engine::project::Edge; - - let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); - session.set_gain(0.0); - let whole = session.lane_clips(Lane::V1)[0]; - let full = session.timeline_duration(); - assert_eq!( - session.trim_room(Lane::V1, 0, Edge::End), - Some((whole.start + 1, whole.end())), - "the file's own last frame is how far the tail goes" - ); - assert!( - !session.trim_clip(Lane::V1, 0, Edge::End, 9_999), - "it already plays all of it" - ); - - // Pulled in by a third: the timeline ends earlier and the sound with it. - let shorter = whole.end() - whole.len() / 3; - assert!(session.trim_clip(Lane::V1, 0, Edge::End, shorter)); - assert_eq!(session.lane_clips(Lane::V1)[0].end(), shorter); - assert_eq!( - session.lane_clips(Lane::A1)[0].end(), - shorter, - "the linked sound was trimmed with the picture" - ); - assert!(session.timeline_duration() < full, "and plays out earlier"); - - // ...and dragged back out, as far as the file goes and no further. - assert!(session.trim_clip(Lane::V1, 0, Edge::End, 9_999)); - assert_eq!( - session.lane_clips(Lane::V1)[0], - whole, - "the whole take back" - ); - - // The head takes the in-point with it, so what plays at the new start - // is source frame 10 rather than source frame 0. - assert!(session.trim_clip(Lane::V1, 0, Edge::Start, 10)); - let head = session.lane_clips(Lane::V1)[0]; - assert_eq!((head.start, head.in_frame), (10, 10)); - assert_eq!(session.lane_clips(Lane::A1)[0].in_frame, 10, "sound too"); - assert_eq!( - session.trim_room(Lane::V1, 0, Edge::Start).map(|r| r.0), - Some(0), - "and it may be pulled back out to the file's first frame" - ); - - assert!(session.undo(), "one step for the whole drag"); - assert_eq!(session.lane_clips(Lane::V1)[0], whole); - } - - /// The move-a-clip-between-tracks path through the door the drop uses - /// ([`Player::move_clip`] calls exactly this): the clip changes row, the - /// *picture* comes from the new row afterwards -- which is what "it plays - /// from there" means -- and one undo puts it back. - #[test] - fn a_clip_dragged_onto_another_track_plays_from_it() { - use engine::project::LaneKind; - - let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); - session.set_gain(0.0); - let v2 = session.add_lane(LaneKind::Video); - assert_eq!(session.video_clip_at(0.0), Some((Lane::V1, 0))); - - assert!(session.move_clip_to(Lane::V1, 0, v2, 0), "V1 -> V2"); - assert!(session.lane_clips(Lane::V1).is_empty(), "it left V1"); - assert_eq!(session.lane_clips(v2).len(), 1, "and landed on V2"); - assert_eq!( - session.video_clip_at(0.0), - Some((v2, 0)), - "the picture now comes from V2" - ); - assert_eq!(session.lane_clips(Lane::A1).len(), 1, "its sound stayed"); - - // Dropped on a lane of the other kind it is refused and nothing moves -- - // the notice the front-end shows for it says which kind of lane to use. - // (The other refusal, landing on another clip, is the engine's own test - // `move_clip_keeps_the_frames_and_refuses_the_rest`.) - assert!(!session.move_clip_to(v2, 0, Lane::A1, 0), "picture on A1"); - assert_eq!(session.lane_clips(v2).len(), 1, "and it stayed on V2"); - assert!( - session.move_clip_to(v2, 0, Lane::V1, 0), - "dragged back down" - ); - - // One undo per move, and each is a single step. - assert!(session.undo(), "the drag back"); - assert_eq!(session.video_clip_at(0.0), Some((v2, 0))); - assert!(session.undo(), "the drag up"); - assert_eq!(session.video_clip_at(0.0), Some((Lane::V1, 0))); - assert!(session.lane_clips(v2).is_empty()); - } - - /// The add-a-track path end to end through the doors the buttons and the - /// drop use: `+ V` adds a row, a library row let go over it lands there and - /// nowhere else, Delete on it leaves the lanes under it where they are, and - /// undo takes the whole thing back one step at a time. - #[test] - fn a_track_can_be_added_dropped_on_edited_and_taken_back() { - use engine::project::LaneKind; - - let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); - session.set_gain(0.0); - assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1]); - // What the `+ V` button asks for, and what the row it draws is called. - let v2 = session.add_lane(LaneKind::Video); - assert_eq!(v2.label(), "V2"); - assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1, v2]); - assert!(session.lane_clips(v2).is_empty()); - // A library row let go over that row: the same door the Add button - // uses, told which lane it was let go over. - let path = session.sources()[0].path.clone(); - assert!( - session - .place_stream_at(1.0, &path, 0, Some(v2)) - .expect("its own file is on this timeline") - ); - assert_eq!(session.lane_clips(v2).len(), 1, "the drop landed on V2"); - assert_eq!(session.lane_clips(v2)[0].start, 30, "at the playhead"); - // ...with the sound it came with, on the row of its own the drop added: - // a file with audio dropped on a layer used to land silent. - let a2 = Lane::new(LaneKind::Audio, 1); - assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1, v2, a2]); - assert_eq!(session.lane_clips(a2), session.lane_clips(v2), "same take"); - assert_eq!( - session.lane_clips(v2)[0].link, - session.lane_clips(a2)[0].link, - "grouped, so a drag moves both" - ); - // And nowhere else: the first pair is exactly as it was, one take each. - assert_eq!(session.lane_clips(Lane::V1).len(), 1); - assert_eq!(session.lane_clips(Lane::A1).len(), 1); - // ...and it is a project that saves and opens again as it stands: a - // grouped pair on a further row is what the file has to carry. - let dir = engine::scratch::Scratch::dir("ve_layer"); - let file = dir.join("layer.edith"); - session.save_project(&file).expect("save the project"); - let back = PlaybackSession::open_project(&file).expect("it loads as it stands"); - std::fs::remove_dir_all(&dir).ok(); - assert_eq!(back.lanes(), session.lanes()); - for lane in back.lanes() { - assert_eq!(back.lane_clips(lane), session.lane_clips(lane), "{lane:?}"); - } - // Delete on the layer is a lift: it is laid over the timeline, so - // closing a hole under it would drag the take beneath out of step with - // it. The take on the first pair is still a take, and still ripples. - assert!(!whole_take(&session, v2, 0)); - assert!(whole_take(&session, Lane::V1, 0)); - assert!(whole_take(&session, Lane::A1, 0)); - assert_eq!(a2.label(), "A2"); - assert!(session.lift_clip(v2, 0)); - assert!(session.lane_clips(v2).is_empty()); - assert_eq!(session.lane_clips(Lane::V1).len(), 1, "V1 stayed put"); - assert_eq!( - session.lane_clips(a2).len(), - 1, - "a lift takes the half it names: the sound is still there to lift" - ); - assert!(session.lift_clip(a2, 0)); - - // A second audio lane used to be what an mp4 export could not write -- - // it copied one AAC track and a mix is not a copy. It mixes now - // (`export::copy_audio`), so no row is greyed by a count of lanes. - for format in [Format::Mp4, Format::Av1, Format::Av1Mp4] { - assert_eq!( - format_refusal(&session, format), - None, - "two audio lanes are a mix, not a refusal" - ); - } - - // Undo, one edit at a time and backwards: the lift of the sound, the - // lift of the picture, the drop on V2 with the lane A2 it added, and - // last the lane V2 -- an added track is one step like every other edit. - for lanes in [4, 4, 3, 2] { - assert!(session.undo()); - assert_eq!(session.lanes().len(), lanes); - } - assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1]); - assert_eq!(session.lane_clips(Lane::V1).len(), 1); - assert_eq!(format_refusal(&session, Format::Mp4), None); - } - - #[test] - fn a_source_is_only_ever_asked_for_its_peaks_once() { - let (a, b) = (asset("test_av.mp4"), asset("test_av2.mp4")); - // Two files, and two streams of the first: three envelopes, because - // one file's two audio tracks are two different waveforms. - let sources = [ - Source { - path: a.clone(), - audio_stream: 0, - }, - Source { - path: a.clone(), - audio_stream: 1, - }, - Source { - path: b.clone(), - audio_stream: 0, - }, - ]; - let keys = |s: &[Source]| { - s.iter() - .map(|s| (s.path.clone(), s.audio_stream)) - .collect::>() - }; - let mut waves: HashMap<(PathBuf, usize), Wave> = HashMap::new(); - assert_eq!(unseen_sources(&sources, &waves), keys(&sources)); - // The entry goes in when the decode *starts*, so the sixty repaints a - // second that happen while it runs must not start it again -- which is - // what this asserts about a key whose value is not an answer yet. - waves.insert((a.clone(), 0), Wave::Loading); - assert_eq!( - unseen_sources(&sources, &waves), - keys(&sources[1..]), - "the file's other stream is a key of its own" - ); - // A file with no audio is an answer like any other: never re-asked. - waves.insert((a, 1), Wave::Silent); - waves.insert((b.clone(), 0), Wave::Silent); - assert!(unseen_sources(&sources, &waves).is_empty()); - // The stream probe is per *file*: the two entries of `a` ask once. - let mut streams: HashMap> = HashMap::new(); - assert_eq!( - unseen_paths(&sources, &streams), - vec![asset("test_av.mp4"), b] - ); - streams.insert(asset("test_av.mp4"), Vec::new()); - assert_eq!(unseen_paths(&sources, &streams).len(), 1); - } - - #[test] - fn the_add_button_is_dead_unless_it_would_do_something() { - let picked = (PathBuf::from("/m/0.mp4"), 0); - assert!(can_add(Some(&picked), true, false)); - // Nothing picked, nothing to put it on, or an export reading the very - // edit list this would change. - assert!(!can_add(None, true, false)); - assert!(!can_add(Some(&picked), false, false)); - assert!(!can_add(Some(&picked), true, true)); - } - - #[test] - fn the_media_column_never_takes_the_picture_over() { - for window in [360., 640., 1280., 1920., 3840.] { - let w = super::library_w(window); - // The whole point of the budget: the picture keeps the majority of - // the row at every size a window can be. - assert!(w <= window / 3., "{window}px window gave the list {w}px"); - assert!(w >= LIBRARY_MIN_W.min(window / 3.), "{window}px: {w}px"); - assert!(w <= LIBRARY_MAX_W); - } - // It yields: a narrower window gives the list less, never the same. - assert!(super::library_w(640.) < super::library_w(1280.)); - // Rows are clickable, so WCAG 2.5.8 binds them like every other target, - // and a name over a timecode has to fit inside one. - assert!(ROW_H >= HIT_MIN); - assert!(SWATCH_W < LIBRARY_MIN_W); - } - - #[test] - fn the_window_is_named_after_the_program_and_what_is_open() { - assert_eq!(window_title("test_av.mp4"), "test_av.mp4 — edith"); - // An empty window is the program, not "no file open — edith". - assert_eq!(window_title(NO_FILE), "edith"); - } - - #[test] - fn frac_along_measures_from_the_elements_own_left_edge() { - // A ruler inset by the panel's 12 px padding: window x is not bar x. - let bar: Bounds = Bounds { - origin: point(px(12.), px(400.)), - size: size(px(200.), px(6.)), - }; - assert_eq!(frac_along(px(12.), bar), 0.); - assert_eq!(frac_along(px(112.), bar), 0.5); - assert_eq!(frac_along(px(212.), bar), 1.); - // Outside the bar (a click that slid off) clamps, never extrapolates. - assert_eq!(frac_along(px(0.), bar), 0.); - assert_eq!(frac_along(px(9999.), bar), 1.); - // Never painted: no division by zero, no NaN reaching seek(). - assert_eq!(frac_along(px(50.), Bounds::default()), 0.); - - // The equalizer's axis is the other one, and reads the same way. - let graph: Bounds = Bounds { - origin: point(px(12.), px(60.)), - size: size(px(296.), px(EQ_GRAPH_H)), - }; - assert_eq!(frac_down(px(60.), graph), 0.); - assert_eq!(frac_down(px(60. + EQ_GRAPH_H / 2.), graph), 0.5); - assert_eq!(frac_down(px(9999.), graph), 1.); - // Never painted reads as flat: an unpainted graph must not slam a band - // to +12 dB on the first press. - assert_eq!(frac_down(px(50.), Bounds::default()), 0.5); - } - - /// 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).as_deref(), - Some("NOT ON V1 — take.mp3 has no picture; drop it on an audio lane") - ); - assert_eq!( - lane_refuses(still, audio).as_deref(), - Some("NOT ON A1 — card.png is a still image; drop it on a video lane") - ); - // ...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), None); - assert_eq!(lane_refuses(still, video), None); - assert_eq!(lane_refuses(movie, video), 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), None); - } - - /// 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 { - start, - in_frame: 0, - out_frame: frames, - source: 0, - link, - eq: None, - color: 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, 300); - all.sort_unstable(); - assert_eq!(all, [0, 100, 100, 160, 160, 300, 400, 430]); - - // The video half in the hand: 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)), 300); - 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)), 0), [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)); - } - - /// The card's rate row: every component the container states and no other, - /// so a track the header is silent about is absent from the line rather - /// than sitting in it as a zero. - #[test] - fn a_rate_row_says_only_what_the_container_stated() { - use super::MediaBitrate; - let all = MediaBitrate { - total: Some(8_432_000), - video: Some(7_918_000), - audio: Some(128_000), - }; - assert_eq!( - bitrate_detail(Some(all), 1), - "8.4 Mb/s · 7.9 video · 0.13 sound" - ); - // A Matroska states no audio rate of its own: the sound is dropped from - // the line, never drawn as "0". - assert_eq!( - bitrate_detail( - Some(MediaBitrate { - audio: None, - ..all - }), - 1 - ), - "8.4 Mb/s · 7.9 video" - ); - // A still, or anything that would not open: the probe answered, and the - // answer is that nobody said. - assert_eq!( - bitrate_detail(Some(MediaBitrate::default()), 0), - "not stated" - ); - // Asked, not answered yet -- a 12 GB film's walk takes seconds. - assert_eq!(bitrate_detail(None, 2), "…"); - // A dual-audio file: the number is the track that plays, and the line - // says so rather than letting it stand for the AC-3 beside it. - assert_eq!( - bitrate_detail(Some(all), 2), - "8.4 Mb/s · 7.9 video · 0.13 1 of 2" - ); - // Every component of a tiny file is stated, and small: the line changes - // unit, so not one of them reads as the zero it is not. In megabits - // this file was "0.00 Mb/s · 0.00 video · 0.00 sound". - assert_eq!( - bitrate_detail( - Some(MediaBitrate { - total: Some(4_998), - video: Some(113), - audio: Some(2_400), - }), - 1 - ), - "5.0 kb/s · 0.11 video · 2.4 sound" - ); - } - - /// The invariant under the row above, over every rate a container can - /// state: a component the file *does* state never renders as a zero. The - /// probe leaves out what is unstated, so a "0.00" on this card would be it - /// saying a track that plays is silent. - #[test] - fn a_stated_rate_never_renders_as_a_zero() { - use super::MediaBitrate; - // Every decade from 1 bit a second to a 100 Mb/s master, the rounding - // edges of each unit switch, and every pair of them in one line: the - // line's unit is picked off its smallest component, so the widest - // spread is the one that could round the biggest away. - let edges: Vec = (0..12) - .flat_map(|e| { - let decade = 10_u64.pow(e); - [decade, decade * 4, decade * 5, decade * 9] - }) - .chain([MB_FLOOR - 1, MB_FLOOR, 999_999, 4_998, 113, 2_400]) - .collect(); - for &small in &edges { - for &big in &edges { - let line = bitrate_detail( - Some(MediaBitrate { - total: Some(small.max(big)), - video: Some(big), - audio: Some(small), - }), - 2, - ); - for number in line - .split(" · ") - .filter_map(|part| part.split(' ').next()) - .filter_map(|n| n.parse::().ok()) - { - assert!(number > 0., "{small}/{big} bits a second rendered as {line:?}"); - } - } - } - } - - #[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 export_lands_beside_the_source_and_never_on_it() { - // The whole point: the export of an .mp4 is never that .mp4. - assert_eq!( - export_path("assets/test_baseline.mp4"), - std::path::Path::new("assets/test_baseline.export.mp4") - ); - // A second export of an export is still not its own source. - assert_eq!( - export_path("a.export.mp4"), - std::path::Path::new("a.export.export.mp4") - ); - // Extensionless and dotted-directory names keep the directory intact. - assert_eq!(export_path("clip"), std::path::Path::new("clip.export.mp4")); - assert_eq!( - export_path("/v.1/clip.MP4"), - std::path::Path::new("/v.1/clip.export.mp4") - ); - } - - #[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}; - // Everything above the test module -- the handler, and the helpers it - // asks. The tests below compare keys too, and are not shortcuts. - let handler = include_str!("main.rs") - .split("#[cfg(test)]") - .next() - .unwrap(); - let keymap = Keymap::defaults(); - let listed = |key: &str| { - let pretty = keymap::Chord { - key: key.to_string(), - ctrl: false, - } - .pretty(); - keymap.lookup(key, 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") => super::ESCAPE.to_string(), - 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 bed the view tests are drawn on: 200 px at 30 fps, as the drop test - /// above uses. - const TEST_BED: f32 = 200.; - - /// A scale against that bed and a timeline `duration` seconds long. - fn test_view(scale: Scale, duration: f64) -> View { - View { - scale, - bed: TEST_BED, - duration, - fps: 30., - } - } - - /// 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() { - assert_eq!(span_label(4.5), "4.5s"); - assert_eq!(span_label(22.5), "22s"); - assert_eq!(span_label(90.), "1.5m"); - assert_eq!(span_label(3600.), "1.0h"); - // The span a five hour timeline is zoomed all the way out to. - assert_eq!(span_label(5. * 3600. * 1.05), "5.2h"); - // Before the first paint there is no bed and so no answer to give. - assert_eq!(span_label(0.), "—"); - assert_eq!(span_label(f64::NAN), "—"); - // A span under a second is a span: the tightest zoom is - // `ZOOM_MIN_FRAMES` across the bed, which on 240 fps slow-motion is - // 0.03s, and "0.0s" would be the pill saying nothing is on the bed. - for fps in [60., 120., 240., 1000.] { - let label = span_label(ZOOM_MIN_FRAMES / fps); - assert_ne!(label, "0.0s", "{fps} fps"); - assert_ne!(label, "0.00s", "{fps} fps"); - } - assert_eq!(span_label(ZOOM_MIN_FRAMES / 240.), "0.03s"); - // 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"); - } - - #[test] - fn escape_gets_out_of_an_export_whatever_is_held_with_it() { - use keymap::ActionId; - // The regression this guards: looking the stroke up in the keymap made - // ctrl+escape mean nothing, and an export that a modifier could trap - // the user inside of is worse than an unbound chord. - assert!(cancels_export("escape", None)); - assert!(cancels_export("escape", Some(ActionId::CancelExport))); - // A rebound cancel works as well -- it adds a way out, never replaces - // the one that always worked. - assert!(cancels_export("q", Some(ActionId::CancelExport))); - // Nothing else does, whatever it means outside an export. - assert!(!cancels_export("e", Some(ActionId::Export))); - assert!(!cancels_export("space", Some(ActionId::Play))); - assert!(!cancels_export("q", None)); - } - - #[test] - fn a_capture_waits_through_a_lone_modifier() { - // gpui delivers these on their own; taking one as a binding would make - // the action fire on the way to every chord that uses it. - for key in [ - "control", "shift", "alt", "super", "platform", "function", "fn", "meta", "command", - ] { - assert!(is_bare_modifier(key), "{key}"); - } - // Everything a binding is actually made of, escape included -- the - // capture branch turns that one away itself. - for key in ["c", "x", "space", "escape", "delete", "f1", "z"] { - assert!(!is_bare_modifier(key), "{key}"); - } - } - - /// The whole point of the card: there is no action a pointer cannot reach. - /// It renders [`keys_rows`] and nothing else, so this reads the same list - /// the card does -- add an `ActionId` and forget to surface it and this - /// fails, which is the only way that stays true as the editor grows. - #[test] - fn every_action_is_on_the_actions_card() { - use keymap::{ActionId, Category, Keymap}; - let rows = keys_rows(); - let listed: Vec = rows - .iter() - .filter_map(|r| match r { - KeyRow::Act(a) => Some(*a), - _ => None, - }) - .collect(); - for action in ActionId::ALL { - assert_eq!( - listed.iter().filter(|a| **a == action).count(), - 1, - "{action:?} is not on the card exactly once" - ); - } - assert_eq!(listed.len(), ActionId::ALL.len()); - // Under its own heading, in the registry's order: every row after a - // heading belongs to that heading until the next one. - let mut heading = None; - let mut heads = 0; - for row in &rows { - match row { - KeyRow::Head(category) => { - heading = Some(*category); - heads += 1; - } - KeyRow::Act(action) => assert_eq!(Some(action.category()), heading, "{action:?}"), - KeyRow::Fixed(i) => assert_eq!(Some(keymap::FIXED[*i].category), heading), - } - } - assert_eq!(heads, Category::ALL.len(), "a heading per category"); - // The card-local strokes are still all there beside them. - assert_eq!( - rows.iter() - .filter(|r| matches!(r, KeyRow::Fixed(_))) - .count(), - keymap::FIXED.len() - ); - // Both columns say something: the label does the action, the stroke - // beside it changes that stroke, and neither may read blank. - let keymap = Keymap::defaults(); - for action in ActionId::ALL { - assert!(!action.label().is_empty(), "{action:?}"); - assert_ne!(keymap.display(action), "unbound", "{action:?}"); - } - // The list scrolls inside a card the smallest window holds, so a - // thirty-fourth action costs no height at all. - assert!(rows.len() as f32 * KEYS_ROW_H > KEYS_ROWS_H, "no cap needed?"); - // Both halves of a row are click targets, so WCAG 2.5.8 binds them. - assert!(KEYS_ROW_H >= HIT_MIN); - } - - /// The search box: what a typed word leaves standing. Forty actions is more - /// than a 360 px window shows at once, so this is the card's answer to - /// "where is the one I want" -- and a heading with nothing under it would - /// be worse than no filter at all. - #[test] - fn a_search_leaves_the_rows_it_names_under_their_own_headings() { - use keymap::{ActionId, Category, Keymap}; - let keymap = Keymap::defaults(); - let acts = |found: &[(usize, KeyRow)]| -> Vec { - found - .iter() - .filter_map(|(_, r)| match r { - KeyRow::Act(a) => Some(*a), - _ => None, - }) - .collect() - }; - let heads = |found: &[(usize, KeyRow)]| -> Vec { - found - .iter() - .filter_map(|(_, r)| match r { - KeyRow::Head(c) => Some(*c), - _ => None, - }) - .collect() - }; - // Nothing typed hides nothing, and every row keeps its place in the - // unfiltered list: an element id must not move under a keystroke. - let all = keys_filter("", &keymap); - assert_eq!(all.len(), keys_rows().len()); - assert!(all.iter().enumerate().all(|(n, (i, _))| n == *i)); - // The word the user types is the word on the row. The mix card names - // the track volumes, so it is an honest hit; the fixed row about the - // volume keys is another, and each comes with its own heading only. - let vol = keys_filter("vol", &keymap); - assert_eq!( - acts(&vol), - vec![ActionId::VolumeUp, ActionId::VolumeDown, ActionId::Mix] - ); - assert_eq!(heads(&vol), vec![Category::Audio, Category::View]); - // Case is not part of the question, in either direction. - assert_eq!(keys_filter("VoL", &keymap).len(), vol.len()); - // The stroke column is searched too -- "what did ctrl do again" -- and - // an unbound-looking word finds nothing rather than everything. - let ctrl = keys_filter("ctrl+", &keymap); - assert!(acts(&ctrl).contains(&ActionId::Save)); - assert!(!acts(&ctrl).contains(&ActionId::Play)); - assert!( - keys_filter("qzx", &keymap).is_empty(), - "headings left behind" - ); - // The card's own door is on the card, by name and by stroke. - assert_eq!( - acts(&keys_filter("f1", &keymap)), - vec![ActionId::ShowActions] - ); - assert_eq!( - acts(&keys_filter("all actions", &keymap)), - vec![ActionId::ShowActions] - ); - } - - /// What a keystroke means to that box: a letter is a letter, and a word - /// gpui reports for a key that prints nothing is not typed letter by - /// letter into the search. - #[test] - fn only_a_printable_stroke_types_into_the_search() { - assert_eq!(typed("a"), Some('a')); - assert_eq!(typed("-"), Some('-')); - assert_eq!(typed("1"), Some('1')); - // The one printable key gpui reports by name. - assert_eq!(typed("space"), Some(' ')); - for word in ["left", "escape", "f1", "backspace", "tab", "delete", "home"] { - assert_eq!(typed(word), None, "{word}"); - } - } - - #[test] - fn the_keybindings_card_fits_the_smallest_window() { - // The row list is capped and scrolls, so the card's height no longer - // depends on how many actions there are: a title, a status line, the - // search box and the viewport, inside the 640x360 the rest of the - // layout is sized for. - let title = 17.; // 13 px text on its own line - let status = 28.; // 11 px text, two lines: a refusal wraps - let search = 15.; // 11 px text, one line: it never wraps - let gaps = 4. * 2.; - let padding = 24.; - // The line the list scrolls under: margin, rule, padding. - let separator = 4. + 1. + 4.; - assert!( - title + status + search + separator + KEYS_ROWS_H + gaps + padding <= 360., - "card too tall" - ); - // ...and the list is the only part that grows with the editor, so the - // rows past the fold are reached by scrolling that viewport (and, with - // forty of them, by the search box above it) rather than by a card - // taller than the window. - assert!( - keys_rows().len() as f32 * KEYS_ROW_H > KEYS_ROWS_H, - "the list outgrew the viewport long ago; the cap must still scroll" - ); - // The cap is only honest if it is the taller list that scrolls, not the - // card that grows: every action must be reachable by scrolling, and - // enough of them visible that the list reads as a list. - assert!( - KEYS_ROWS_H / KEYS_ROW_H >= 8., - "too few rows visible to scan" - ); - assert!(KEYS_W <= 640., "card too wide"); - // The rows are clickable, so WCAG 2.5.8 binds them like every other - // target in this window. - assert!(KEYS_ROW_H >= HIT_MIN); - } - - /// The equalizer card's graph: where a band lands on it, that a drag reads - /// back as the gain it painted -- the two are one mapping and its inverse, - /// which is what makes a handle follow the pointer -- and that the card - /// still fits the window the other two are sized for. - #[test] - fn the_equalizer_graph_puts_a_band_where_a_drag_reads_it_and_fits_the_smallest_window() { - use engine::eq::{Band, BandKind, EqParams}; - // Flat is the middle of the box: a band nobody has touched must not - // look like one that has been turned down. - assert_eq!(eq_y(0.), 0.5); - // Full boost is the top edge, full cut the bottom one -- y grows down. - assert_eq!(eq_y(EQ_GAIN_LIMIT), 0.); - assert_eq!(eq_y(-EQ_GAIN_LIMIT), 1.); - assert_eq!(eq_y(EQ_GAIN_LIMIT / 2.), 0.25); - // A file may carry a gain past what this card offers (the format writes - // any finite value): it paints on the edge, never off the box. - assert_eq!(eq_y(400.), 0.); - assert_eq!(eq_y(-400.), 1.); - - // A pointer reads back as the gain that paints where it landed, which - // is what makes a drag land under the hand ([`Player::drag_band`]). - for gain in [-12., -6., 0., 6., 12.] { - let read = (0.5 - eq_y(gain)) * 2. * EQ_GAIN_LIMIT; - assert!((read - gain).abs() < 1e-4, "{gain} read back as {read}"); - } - - // The frequency axis is logarithmic and spans the audible range: the - // ends are the ends, and the decade at 200 Hz is as wide as the one at - // 2 kHz -- the whole reason a bass band is reachable at all. - assert_eq!(eq_x(EQ_FREQ_LOW), 0.); - assert_eq!(eq_x(EQ_FREQ_HIGH), 1.); - assert!((eq_x(200.) - 1. / 3.).abs() < 1e-4); - assert!(((eq_x(2000.) - eq_x(200.)) - (eq_x(20000.) - eq_x(2000.))).abs() < 1e-4); - // Off either end clamps rather than painting outside the box. - assert_eq!(eq_x(1.), 0.); - assert_eq!(eq_x(96_000.), 1.); - // Every tick the card names is on the axis it is drawn against. - for (freq, label) in EQ_TICKS { - assert!( - (EQ_FREQ_LOW..=EQ_FREQ_HIGH).contains(&freq), - "tick {label} is off the axis" - ); - } - // The default bands all land inside it too, spread out enough that the - // nearest-band pick (`Player::nearest_band`) has something to pick. - let xs: Vec = EqParams::default_layout() - .bands - .iter() - .map(|b| eq_x(b.freq_hz)) - .collect(); - for pair in xs.windows(2) { - assert!(pair[1] - pair[0] > 0.1, "bands too close to aim at: {xs:?}"); - } - - // Every default band says what it is, and a shelf says so: "12 kHz" - // alone would not tell anyone it tilts the whole top octave. - let labels: Vec = EqParams::default_layout() - .bands - .iter() - .map(band_label) - .collect(); - assert_eq!( - labels, - [ - "80 Hz low shelf", - "250 Hz", - "1 kHz", - "4 kHz", - "12 kHz high shelf" - ] - ); - // A band moved off a round number reads as where it *is*: a keystroke - // that changes the filter and not the number on the card is a keystroke - // nobody can aim. - assert_eq!( - band_label(&Band { - freq_hz: 2600., - gain_db: 0., - q: 1., - kind: BandKind::Peak - }), - "2.6 kHz" - ); - assert_eq!(eq_freq_label(1122.), "1.12 kHz"); - assert_eq!(eq_freq_label(12000.), "12 kHz", "no zeroes to read past"); - assert_eq!(eq_freq_label(80.), "80 Hz"); - - // The card fits the smallest window and takes the room a bigger one has - // -- it is a graph, and the width *is* the frequency resolution. - assert!(eq_card_w(640.) <= 640. - 24., "card too wide for 640"); - assert!(eq_card_w(1280.) > eq_card_w(640.), "card ignores the window"); - assert_eq!(eq_card_w(1920.), EQ_W_MAX, "card grows without end"); - assert!(eq_card_w(320.) >= KEYS_W, "card narrower than a row of text"); - // At the smallest window the graph is still a graph: three across for - // one down, so an octave is wide enough to put a handle in. - assert!( - eq_card_w(640.) - 24. >= 3. * EQ_GRAPH_H, - "graph too square to aim at" - ); - - // The same shape as the other two cards, so it fits where they do: the - // graph stands where the export card's rows do, and is shorter than - // they are. The numbers row is a row of buttons now, so it is one of - // those tall rather than one line of text. - let (title, status, gaps, padding) = (17., 28., 4. * 2., 24.); - assert!( - title + status + EQ_GRAPH_H + HIT_MIN + gaps + padding + CONTROL_H <= 360., - "card too tall" - ); - assert!( - EQ_GRAPH_H <= EXPORT_ROWS_H, - "graph taller than a card of rows" - ); - // What is dragged is the whole graph -- the handle is a 10 px dot, but - // a press anywhere in the box takes the band nearest it -- so WCAG - // 2.5.8 is satisfied by the box, which is far past the minimum. - assert!(EQ_GRAPH_H >= HIT_MIN); - assert!( - EQ_HANDLE < HIT_MIN, - "a dot that size would want its own hitbox" - ); - assert!(KEYS_ROW_H >= HIT_MIN); - } - - /// Editing a band, which is what the card is *for*: the pointer reads a - /// frequency off the axis the same way the axis draws one, a new band lands - /// in the gap beside the picked one rather than on top of it, and every band - /// the card will hold has a digit that picks it. - #[test] - fn a_band_can_be_moved_added_and_reached() { - use engine::eq::{Band, BandKind, EqParams}; - // Across the graph and back: a drag sets the frequency the handle is - // then drawn at, so the two mappings have to be one another's inverse or - // the handle walks away from the pointer. - for freq in [20., 80., 250., 1000., 4000., 12000., 20000.] { - let read = eq_freq(eq_x(freq)); - assert!( - (read / freq - 1.).abs() < 1e-3, - "{freq} Hz read back as {read}" - ); - } - // Off the box either end stops at the axis, never past it. - assert_eq!(eq_freq(-1.), EQ_FREQ_LOW); - assert_eq!(eq_freq(2.), EQ_FREQ_HIGH); - - // A step of the frequency keys is a real move on screen -- a keystroke - // that changes nothing visible is a keystroke that reads as broken -- - // and small enough to aim with. - let step = eq_x(1000. * EQ_FREQ_STEP) - eq_x(1000.); - assert!(step > 0.01 && step < 0.06, "frequency key steps {step}"); - - // A new band lands between the picked one and the next one up, in - // octaves: 250 Hz and 1 kHz put it at 500, which is a gap on screen. - let bands = EqParams::default_layout().bands; - let added = inserted_band(&bands, 1); - assert!((added.freq_hz - 500.).abs() < 1., "landed at {added:?}"); - assert_eq!(added.gain_db, 0., "a new band changes nothing until moved"); - assert_eq!(added.kind, BandKind::Peak, "a new band is not a shelf"); - assert!(eq_x(added.freq_hz) - eq_x(bands[1].freq_hz) > 0.1); - // Above the topmost band the gap is the rest of the axis, and the band - // still lands on it rather than off the end. - let top = inserted_band(&bands, bands.len() - 1); - assert!( - top.freq_hz > bands[4].freq_hz && top.freq_hz <= EQ_FREQ_HIGH, - "landed at {top:?}" - ); - // Bands out of frequency order (a drag may cross two over) still get a - // sane neighbour: the next one *up*, not the next one along the list. - let crossed = vec![ - Band { - freq_hz: 4000., - gain_db: 0., - q: 1., - kind: BandKind::Peak, - }, - Band { - freq_hz: 100., - gain_db: 0., - q: 1., - kind: BandKind::Peak, - }, - ]; - let between = inserted_band(&crossed, 1); - assert!( - (between.freq_hz - 632.).abs() < 2., - "landed at {between:?}, not between 100 and 4000" - ); - - // Every band the card will hold is one digit away: the keyboard has ten - // digits, which is exactly why the cap is what it is. - assert!( - EQ_BANDS_MAX <= 10, - "a band past the tenth has no key that picks it" - ); - assert!(EQ_BANDS_MAX > EqParams::default_layout().bands.len()); - // The Q range holds the default, so a file's band never opens out of - // range and needs dragging back in before it can be edited. - assert!((EQ_Q_LOW..=EQ_Q_HIGH).contains(&0.707)); - assert!(EQ_Q_STEP > 1.); - } - - /// The analyser drawn behind the curve: a tone has to land on its own - /// frequency, or the backdrop is a decoration rather than a reading of what - /// is playing -- and someone shaping a band against it would be aiming at - /// the wrong octave. - #[test] - fn the_spectrum_puts_a_tone_under_its_own_frequency() { - use std::f32::consts::TAU; - let rate = 48_000u32; - let sine = |hz: f32, amp: f32| -> Vec { - (0..EQ_FFT) - .map(|i| amp * (TAU * hz * i as f32 / rate as f32).sin()) - .collect() - }; - - // Silence is the floor of the box everywhere, not a band of noise. - let quiet = eq_spectrum(&vec![0.; EQ_FFT], rate); - assert_eq!(quiet.len(), EQ_CURVE_STEPS + 1); - assert!(quiet.iter().all(|&l| l == 0.), "silence drew something"); - - // A tone peaks over its own frequency, and the columns two octaves - // either side of it are near the floor. "Over" to within a bin down low - // and a column up high, which is all a 1024-point transform on a log - // axis can promise: at 200 Hz a whole column is a fraction of a bin - // wide, so the peak sits on the bin the tone fell in. - let column = |freq: f32| (eq_x(freq) * EQ_CURVE_STEPS as f32).round() as usize; - let freq_at = |col: usize| { - let along = col as f32 / EQ_CURVE_STEPS as f32; - EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along) - }; - for hz in [200., 1000., 5000.] { - let levels = eq_spectrum(&sine(hz, 0.05), rate); - let (at, top) = - levels - .iter() - .enumerate() - .fold((0, 0f32), |best, (i, &l)| match l > best.1 { - true => (i, l), - false => best, - }); - let slack = 1.5 * rate as f32 / EQ_FFT as f32 + 0.04 * hz; - assert!( - (freq_at(at) - hz).abs() <= slack, - "{hz} Hz peaked at {:.0} Hz (column {at})", - freq_at(at) - ); - // -26 dBFS, which is where a 0.05 tone sits on the axis. - let want = - (20. * 0.05f32.log10() - EQ_SPECTRUM_DB.0) / (EQ_SPECTRUM_DB.1 - EQ_SPECTRUM_DB.0); - assert!( - (top - want).abs() < 0.05, - "a -26 dBFS tone drew {top} of the box, not {want}" - ); - // Two octaves off is far enough down the box that the hump reads as - // one hump: 0.4 of the axis is a little over 30 dB. - for off in [hz / 4., hz * 4.] { - let away = levels[column(off).min(EQ_CURVE_STEPS)]; - assert!( - top - away > 0.4, - "{hz} Hz drew {top} but still {away} at {off} Hz" - ); - } - } - - // Level reads as level: 40 dB quieter sits lower by the fraction of the - // axis those 40 dB are. - let loud = eq_spectrum(&sine(1000., 0.05), rate); - let soft = eq_spectrum(&sine(1000., 0.0005), rate); - let at = column(1000.); - let drop = loud[at] - soft[at]; - let (floor, ceiling) = EQ_SPECTRUM_DB; - assert!( - (drop - 40. / (ceiling - floor)).abs() < 0.05, - "40 dB quieter moved the analyser {drop} of the box" - ); - - // A tap the engine has not filled yet (right after a seek) draws - // nothing at all rather than a transform of half a window. - assert!(eq_spectrum(&[0.; 16], rate).is_empty()); - } - - /// The speed bar is the same round trip -- pixels -> rate -> fill -- with - /// one thing the colour sliders do not have to promise: **exactly 1.00x has - /// to be reachable**, by a hand as well as by the reset. A grid that missed - /// it would leave a clip nobody could put back. - #[test] - fn the_speed_bar_lands_where_it_paints_and_real_time_is_reachable() { - let bar = Bounds { - origin: point(px(180.), px(240.)), - size: size(px(COLOR_BAR_W), px(KEYS_ROW_H)), - }; - let (lo, hi) = ( - f32::from(Speed::MIN.permille()), - f32::from(Speed::MAX.permille()), - ); - // The same arithmetic `Player::drag_speed` runs, which is the one thing - // a test of it can share without re-deriving it. - let at = |x: f32| { - let raw = lo + frac_along(px(x), bar) * (hi - lo); - speed_at((raw / SPEED_STEP as f32).round() as i32 * SPEED_STEP) - }; - assert_eq!(at(180.), Speed::MIN, "the left end is a quarter speed"); - assert_eq!(at(180. + COLOR_BAR_W), Speed::MAX, "the right end is 4x"); - assert_eq!(at(-4000.), Speed::MIN, "off the left clamps"); - assert_eq!(at(9999.), Speed::MAX, "off the right clamps"); - let mut hits_real_time = false; - for step in 0..=240 { - let along = step as f32 / 240.; - let speed = at(180. + along * COLOR_BAR_W); - hits_real_time |= speed == Speed::NORMAL; - assert_eq!( - i32::from(speed.permille()) % SPEED_STEP, - 0, - "{speed} is off the {SPEED_STEP} grid the keys move on" - ); - // What the bar paints from that rate is where the pointer was, to - // within the half step the snap costs. - let painted = (f32::from(speed.permille()) - lo) / (hi - lo); - let slack = SPEED_STEP as f32 / (hi - lo) / 2. + 1e-4; - assert!( - (painted - along).abs() <= slack, - "pressed at {along}, paints at {painted}" - ); - } - assert!(hits_real_time, "a drag can land on exactly 1.00x"); - // ...and every preset the card offers is a rate the bar can also reach. - for permille in SPEED_PRESETS { - assert_eq!(Speed::from_permille(permille).permille(), permille); - assert_eq!(i32::from(permille) % SPEED_STEP, 0); - } - assert!(SPEED_PRESETS.contains(&Speed::NORMAL.permille()), "reset"); - } - - /// A colour slider is dragged straight to a value, so where the pointer - /// lands and where the bar then paints have to be the same place: this is - /// the round trip [`Player::drag_color`] makes, pixels -> value -> fill. - #[test] - fn a_colour_drag_lands_where_it_paints_and_the_card_fits_the_smallest_window() { - // A bar as laid out, somewhere that is not the window's origin -- a - // mapping that forgot the offset would pass at zero. - let bar = Bounds { - origin: point(px(180.), px(240.)), - size: size(px(COLOR_BAR_W), px(KEYS_ROW_H)), - }; - for &(label, low, high) in &COLOR_BANDS { - // The ends are the ends: the left of the bar is the bottom of the - // range and the right is the top, so a slider can be pulled to - // either without hunting for the last pixel. - let at = |x: f32| color_snap(low + frac_along(px(x), bar) * (high - low)); - assert_eq!(at(180.), low, "{label} left end"); - assert_eq!(at(180. + COLOR_BAR_W), high, "{label} right end"); - // Off either end clamps rather than running past the range. - assert_eq!(at(-4000.), low, "{label} off the left"); - assert_eq!(at(9999.), high, "{label} off the right"); - - for step in 0..=48 { - let along = step as f32 / 48.; - let value = at(180. + along * COLOR_BAR_W); - // Every stop is one the keyboard can also reach, which is what - // keeps "0.35" the number the file writes. - let steps = value / COLOR_STEP; - assert!( - (steps - steps.round()).abs() < 1e-3, - "{label}: {value} is off the {COLOR_STEP} grid" - ); - assert!( - (low..=high).contains(&value), - "{label}: {value} outside {low}..{high}" - ); - // What the row paints from that value is where the pointer was, - // to within the half step the snap costs. - let painted = (value - low) / (high - low); - let slack = COLOR_STEP / (high - low) / 2. + 1e-4; - assert!( - (painted - along).abs() <= slack, - "{label}: pressed at {along}, paints at {painted}" - ); - } - } - - // The same shape as the other two cards, so it fits where they do: the - // graph, four rows and the reset button inside a 360 px window. - let (title, status, gaps, padding) = (17., 17., 6. * 2., 24.); - let rows = COLOR_BANDS.len() as f32 * KEYS_ROW_H; - assert!( - title + status + HIST_H + rows + gaps + padding + CONTROL_H + 4. <= 360., - "card too tall" - ); - assert!(COLOR_W <= 640., "card too wide"); - // The label still has room beside the bar and the readout, which is - // what the buttons coming off the row bought. - let row = COLOR_W - padding - 12. - 2. * 8. - COLOR_BAR_W - 44.; - assert!(row >= LABEL_MIN_W, "no room left for a label: {row}px"); - // What is dragged is the whole row's height, not the 4 px the bar is - // drawn as (WCAG 2.5.8) -- the same split the ruler makes. - assert!(KEYS_ROW_H >= HIT_MIN); - } - - /// The graph over the sliders is the frame the grade already went through, - /// so it has to count what is actually in those bytes -- BGRA on the wire, - /// red-green-blue in the bins. - #[test] - fn the_histogram_counts_the_frame_it_is_handed() { - // Half pure red, half mid grey: two known values, in two known bins. - let (w, h) = (64usize, 64usize); - let mut frame = Vec::with_capacity(w * h * 4); - for _ in 0..h { - for col in 0..w { - match col < w / 2 { - true => frame.extend_from_slice(&[0, 0, 255, 255]), - false => frame.extend_from_slice(&[128, 128, 128, 255]), - } - } - } - let bins = histogram(&frame); - let half = (w * h / 2) as u32; - // 64 bins over 256 codes: 255 is the last bin, 128 the middle one, 0 the - // first. - assert_eq!(bins[0][63], half, "the red half tops the red channel"); - assert_eq!(bins[0][32], half, "and the grey half sits mid red"); - for channel in [1, 2] { - assert_eq!(bins[channel][0], half, "no green or blue in the red half"); - assert_eq!(bins[channel][32], half); - assert_eq!(bins[channel][63], 0); - } - // Nothing is counted twice and nothing is dropped: this frame is small - // enough to be read whole. - for channel in bins { - assert_eq!(channel.iter().sum::(), (w * h) as u32); - } - - // A grade shifts it, which is the whole point of drawing it: the same - // frame darkened lands in lower bins. - let darker: Vec = frame.iter().map(|b| b / 2).collect(); - let bins = histogram(&darker); - assert_eq!(bins[0][31], half, "255 -> 127"); - assert_eq!(bins[0][16], half, "128 -> 64"); - - // A real frame is subsampled: a 1080p one is read every 253rd pixel, so - // the shape costs a thousandth of the reads and still counts thousands. - let big = vec![200u8; 1920 * 1080 * 4]; - let bins = histogram(&big); - let counted = bins[0].iter().sum::(); - let pixels = 1920 * 1080usize; - let expected = pixels.div_ceil(pixels / HIST_SAMPLES) as u32; - assert_eq!(counted, expected, "every strided pixel counted, once"); - assert!( - (HIST_SAMPLES as u32..=HIST_SAMPLES as u32 + 64).contains(&counted), - "{counted} samples is not the budget" - ); - assert_eq!(bins[0][200 * HIST_BINS / 256], counted, "all in one bin"); - - // An empty buffer is a flat graph rather than a panic: the card is open - // before the first frame is pumped. - assert_eq!(histogram(&[]), [[0; HIST_BINS]; 3]); - } - - /// Mute and level are one control with two states, and the whole point is - /// that mute keeps the level: the user gets back what they had, not 100%. - #[test] - fn muting_keeps_the_level_it_comes_back_to() { - let mut volume = Volume::default(); - assert_eq!(volume.gain(), 1.0); - assert_eq!(volume.label(), "Vol 100%"); - - // Four presses down, then muted: the gain is silence but the level is - // still what it was, and the button keeps saying so. - for _ in 0..4 { - volume.step(false); - } - assert_eq!(volume.gain(), 0.8); - volume.muted = true; - assert_eq!(volume.gain(), 0.0); - assert_eq!(volume.label(), "Muted 80%"); - - // Turning it down while muted stays muted -- the one thing a mute - // button must never do is get louder because you asked for quieter. - volume.step(false); - assert_eq!(volume.gain(), 0.0); - assert!(volume.muted); - - // Unmute returns to the level, including the step taken while silent. - volume.muted = false; - assert_eq!(volume.gain(), 0.75); - } - - /// The whole transport in one place: the clock keeps running past the last - /// frame (wall time takes over at audio EOF), so "the clock is going" is - /// not "this is playing" -- and a button that read the clock showed Pause - /// on a timeline that had stopped moving. Ended is its own state, it draws - /// Play, and the next press starts over from the top. - #[test] - fn a_played_out_timeline_is_not_playing_and_the_next_press_starts_it_over() { - assert_eq!(transport(true, false), Transport::Playing); - assert_eq!(transport(false, false), Transport::Paused); - // The transition the bug was about: the clock is still running and the - // decoder is finished. Played out wins, however the clock reads. - assert_eq!(transport(true, true), Transport::Ended); - assert_eq!(transport(false, true), Transport::Ended); - - // What the button draws, in each state. Two bars only while it moves. - assert!(Transport::Playing.is_playing()); - for state in [Transport::Paused, Transport::Ended, Transport::Stopped] { - assert!(!state.is_playing(), "{state:?} must draw the Play triangle"); - } - - // And what a press does: start over at the end, plain toggle before it, - // nothing with no timeline. Same answer for the key and the button -- - // both come through `Player::toggle_or_restart`. - assert!(Transport::Ended.restarts()); - for state in [Transport::Playing, Transport::Paused, Transport::Stopped] { - assert!(!state.restarts(), "{state:?} must toggle, not reseek"); - } - } - - /// The half of `Ended` the eye cannot see: the clock. Wall time takes over - /// at the last frame and nothing used to stop it, so the playhead walked off - /// the end of the timeline in real time -- and the playhead is what a cut, a - /// paste, an insert and the analyser all act at. `pump` pauses on the - /// crossing; this is the engine contract that rests on, driven exactly as - /// the pump drives it. - #[test] - fn the_clock_stops_where_the_timeline_does_and_the_end_still_restarts() { - let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); - session.set_gain(0.0); - // Start a breath short of the end: the tail is what this is about, and - // playing the whole five seconds would say nothing more. - session.seek(4.8); - session.play(); - - // The pump's own loop -- tick, drain, ask where the transport is -- - // with a deadline so a fixture that will not decode fails as a failure - // rather than as a hang. - let deadline = Instant::now() + Duration::from_secs(20); - let mut state = transport(session.is_playing(), session.is_eos()); - while state != Transport::Ended { - assert!(Instant::now() < deadline, "never reached the end of a 5s file"); - session.tick(); - while session.try_frame().is_some() {} - state = transport(session.is_playing(), session.is_eos()); - } - - // What `pump` does on the crossing, and the whole point of it: the - // position holds still afterwards instead of counting on past the end, - // and it holds still *on the out point* -- where the timecode and the - // playhead have been showing it. The clock at the moment the end is - // recognised is not that: a slow renderer reaches EOF with the clock - // seconds past the timeline, which is why this repositions rather than - // only freezing. - session.halt_at_end(); - let stopped_at = session.now(); - assert_eq!(stopped_at, session.timeline_duration()); - std::thread::sleep(Duration::from_millis(250)); - assert_eq!(session.now(), stopped_at, "the clock kept running past EOF"); - // And it is still the end: pausing must not spend the state the glyph - // and the restart both read. - assert!(session.is_eos()); - assert_eq!( - transport(session.is_playing(), session.is_eos()), - Transport::Ended - ); - - // The restart path off that frozen end, which is what the button and - // the play key do from `Ended`: back to the top, and running. - session.seek(0.); - session.play(); - assert!(!session.is_eos(), "a seek revives the session"); - assert!(session.now() < 1.0); - assert_eq!( - transport(session.is_playing(), session.is_eos()), - Transport::Playing - ); - session.pause(); - } - - /// Both ends hold under a key held down: the ABI only accepts `0.0..=1.0`, - /// and a wrapped step count would hand it something else. - #[test] - fn the_volume_stops_at_both_ends() { - let mut volume = Volume::default(); - for _ in 0..40 { - volume.step(true); - } - assert_eq!(volume.gain(), 1.0); - assert_eq!(volume.steps, Volume::MAX_STEPS); - - for _ in 0..40 { - volume.step(false); - } - assert_eq!(volume.gain(), 0.0); - assert_eq!(volume.label(), "Vol 0%"); - - // Silent by the level rather than by the flag is still not muted: the - // button says which, because only one of them survives a step up. - assert!(!volume.muted); - volume.step(true); - assert_eq!(volume.gain(), 0.05); - } - - #[test] - fn a_quality_row_is_the_bitrate_it_promises() { - // Auto is the one row that says nothing: the exporter derives it, and - // a number typed against the custom row must not leak into it. - let mp4 = Format::Mp4; - assert_eq!( - export_settings(Quality::Auto, 7, mp4, DEFAULT_AUDIO_KBPS).bitrate, - None - ); - assert_eq!( - export_settings(Quality::Low, 0, mp4, DEFAULT_AUDIO_KBPS).bitrate, - Some(2_000_000) - ); - assert_eq!( - export_settings(Quality::Medium, 0, mp4, DEFAULT_AUDIO_KBPS).bitrate, - Some(6_000_000) - ); - assert_eq!( - export_settings(Quality::High, 0, mp4, DEFAULT_AUDIO_KBPS).bitrate, - Some(12_000_000) - ); - // Megabits as typed, and as the row says it back. - assert_eq!( - export_settings(Quality::Custom, 7, mp4, DEFAULT_AUDIO_KBPS).bitrate, - Some(7_000_000) - ); - assert_eq!(Quality::Low.detail(0), "2 Mbps"); - // The picked format travels, or the card's rows would be a picture of a - // choice the engine never hears about. - for format in [Format::Mp4, Format::Wav, Format::Flac] { - assert_eq!( - export_settings(Quality::Auto, 0, format, DEFAULT_AUDIO_KBPS).format, - format - ); - } - // Every fixed row sits inside the engine's clamp - // (`MAX_EXPLICIT_BITRATE`), so no row can promise a bitrate the exporter - // silently changes -- the ceiling row included, which is the one a - // raised cap could have walked out past. - for quality in Quality::ALL { - let settings = export_settings(quality, MBPS_MAX, mp4, DEFAULT_AUDIO_KBPS); - if let Some(bitrate) = settings.bitrate { - assert!( - (u64::from(MBPS_MIN) * 1_000_000..=u64::from(MBPS_MAX) * 1_000_000) - .contains(&bitrate), - "{quality:?} outside the engine clamp" - ); - } - // The software pin is the environment's to set, never a row's. - assert!(!settings.force_sw); - } - } - - /// The Sound row: what it offers, and that the pick travels to the engine - /// for a *video* export as much as for an MP3 -- both files carry sound, so - /// a row that only reached the audio formats would be half a control. - #[test] - fn the_sound_row_carries_its_rate_into_both_kinds_of_file() { - // Sorted and unique, so a row that says "b for the next one" is stepping - // up and not shuffling. - assert!(AUDIO_KBPS.windows(2).all(|w| w[0] < w[1])); - // The untouched figure is one of the offered rows, or the first press of - // `b` would jump somewhere nobody chose. - assert!(AUDIO_KBPS.contains(&DEFAULT_AUDIO_KBPS)); - // ...and it is what this program wrote before the row existed: the - // export of a user who never opens it must not change under them. - assert_eq!(DEFAULT_AUDIO_KBPS, 256); - for format in [Format::Mp4, Format::Av1, Format::Hevc, Format::Mp3] { - for kbps in AUDIO_KBPS { - assert_eq!( - export_settings(Quality::Auto, 0, format, kbps).audio_kbps, - Some(kbps), - "{format:?} at {kbps} kbps" - ); - } - } - // The pointer's door to the same field: one row per rate, the one in - // force marked exactly once, and every row's small print short enough - // to survive `MENU_W`'s truncation (the resolution list's own rule). - let rows = audio_rate_choices(DEFAULT_AUDIO_KBPS); - assert_eq!(rows.len(), AUDIO_KBPS.len()); - assert_eq!(rows.iter().filter(|(.., picked)| *picked).count(), 1); - for ((choice, label, detail, picked), kbps) in rows.iter().zip(AUDIO_KBPS) { - assert_eq!(*choice, Choice::AudioRate(kbps)); - assert_eq!(label.as_ref(), format!("{kbps} kbps")); - assert!(detail.chars().count() <= 26, "{detail} is too long to read"); - assert_eq!(*picked, kbps == DEFAULT_AUDIO_KBPS); - } - // A rate no row holds marks none of them, rather than the wrong one. - assert!(audio_rate_choices(7).iter().all(|(.., picked)| !picked)); - - // The wrap the row's key does, which is the row's own step function. - assert_eq!( - next_audio_kbps(AUDIO_KBPS[AUDIO_KBPS.len() - 1]), - AUDIO_KBPS[0] - ); - assert_eq!(next_audio_kbps(DEFAULT_AUDIO_KBPS), 320); - // A rate no list holds (a stale one, say) lands back on the first row - // rather than nowhere. - assert_eq!(next_audio_kbps(7), AUDIO_KBPS[1]); - } - - #[test] - fn a_typed_bitrate_is_a_field_and_not_a_key_capture() { - // It opens on the number in force, so backspace edits that number - // rather than the field starting empty over a bitrate still being used. - let mut edit = NumberEdit::new(12); - assert_eq!(edit.text, "12"); - edit.backspace(); - edit.digit(8); - assert_eq!(edit.text, "18"); - assert_eq!(edit.commit(), Some(18)); - // A card nobody has typed a number into opens empty: zero is not a - // bitrate anyone chose. - assert_eq!(NumberEdit::new(0).text, ""); - - // Out of range is refused *in words* and the digits stay put: clamping - // 55 to 50 would write a bitrate the user never typed. - let mut edit = NumberEdit::new(0); - for digit in [5, 5] { - edit.digit(digit); - } - assert_eq!(edit.commit(), None); - assert_eq!(edit.text, "55", "a refusal keeps what was typed"); - let refusal = edit.refusal.clone().expect("a refusal says why"); - assert!(refusal.contains(&MBPS_MAX.to_string()), "{refusal}"); - assert!(edit.detail().starts_with("55▏"), "{}", edit.detail()); - assert!(edit.detail().contains(&refusal)); - // And is fixable in place, which is the whole point of a field. - edit.backspace(); - assert_eq!(edit.refusal, None, "the reason went with the digit"); - assert_eq!(edit.commit(), Some(5)); - - // Empty, zero, and past the digit cap: each its own reason, none of - // them silent. - assert!(commit_mbps("").is_err()); - assert!(commit_mbps("0").unwrap_err().contains("not a rate")); - assert_eq!(commit_mbps("1"), Ok(MBPS_MIN)); - assert_eq!(commit_mbps("50"), Ok(MBPS_MAX)); - assert!(commit_mbps("51").is_err()); - let mut edit = NumberEdit::new(0); - for digit in [9, 9, 9, 9] { - edit.digit(digit); - } - assert_eq!(edit.text, "999", "the cap holds"); - assert!(edit.refusal.is_some(), "and says it is holding"); - // Never past what a u64 bitrate can be built from -- the committed - // number is the only one that reaches the engine, and it is bounded. - assert!(u64::from(MBPS_MAX) * 1_000_000 < u64::from(u32::MAX)); - assert_eq!(MBPS_DIGITS, 3); - - // The arrows step inside the range and stop at both ends: a walk - // through the legal numbers, never a way out of them. - let mut edit = NumberEdit::new(0); - edit.step(1); - assert_eq!(edit.text, MBPS_MIN.to_string(), "empty starts at the floor"); - edit.step(-1); - assert_eq!(edit.text, MBPS_MIN.to_string()); - let mut edit = NumberEdit::new(MBPS_MAX); - edit.step(1); - assert_eq!(edit.text, MBPS_MAX.to_string()); - edit.step(-1); - assert_eq!(edit.text, (MBPS_MAX - 1).to_string()); - // A step past a refused number clears the refusal with it. - let mut edit = NumberEdit::new(0); - edit.digit(5); - edit.digit(5); - assert_eq!(edit.commit(), None); - edit.step(-1); - assert_eq!(edit.refusal, None); - assert_eq!(edit.text, MBPS_MAX.to_string(), "back inside the range"); - - // The hint the field shows when there is nothing to refuse names both - // ways out of it. - let detail = NumberEdit::new(6).detail(); - assert!(detail.contains("enter") && detail.contains("esc"), "{detail}"); - assert!(detail.starts_with("6▏"), "{detail}"); - } - - #[test] - fn a_clip_with_no_sound_is_refused_in_the_same_words_whichever_kind_it_is() { - // A still and a video with no audio track are one answer to one - // question: the lane and index that were picked, the file, and which of - // the two soundless things it is. What must never reach the bar is the - // demuxer's own words -- a png handed to the mp4 reader answers "a box - // with a larger size than it", which is true of a container and useless - // to a person. - assert_eq!( - unscannable(Lane::V1, 1, std::path::Path::new("/tmp/shot.png")), - "V1 clip 2 has no audio to scan — shot.png is a picture" - ); - assert_eq!( - unscannable( - Lane::new(LaneKind::Audio, 1), - 0, - std::path::Path::new("/tmp/test_baseline.mp4") - ), - "A2 clip 1 has no audio to scan — test_baseline.mp4 is silent" - ); - } - - /// The hold gate: a value runs, everything else still means one press one - /// action -- which is the whole invariant the blanket `is_held` filter used - /// to carry on its own. - #[test] - fn a_held_key_moves_a_value_and_nothing_else() { - use keymap::ActionId; - // A card's four arrows, whichever card it is. - for key in ["up", "down", "left", "right"] { - assert!(repeats(Repeat::Card, key, None), "{key} on a card"); - } - // The card's own one-shots: flatten every band, cut forty places, play - // them fast, close. None of them on a hold. - for key in ["r", "enter", "f", "1", "escape"] { - assert!(!repeats(Repeat::Card, key, None), "{key} on a card"); - } - // Outside a card the keymap answers, and only the volume pair is a - // value being moved. - assert!(repeats(Repeat::Keymap, "up", Some(ActionId::VolumeUp))); - assert!(repeats(Repeat::Keymap, "down", Some(ActionId::VolumeDown))); - // ...and the zoom pair, which runs the view the way they run the level. - assert!(repeats(Repeat::Keymap, "=", Some(ActionId::ZoomIn))); - assert!(!repeats(Repeat::Keymap, "0", Some(ActionId::ZoomFit))); - for action in ActionId::ALL { - let held = repeats(Repeat::Keymap, "k", Some(action)); - assert_eq!( - held, - matches!( - action, - ActionId::VolumeUp - | ActionId::VolumeDown - | ActionId::ZoomIn - | ActionId::ZoomOut - ), - "{action:?} on a hold" - ); - } - // An arrow with nothing bound to it moves nothing on the timeline. - assert!(!repeats(Repeat::Keymap, "left", None)); - // And a stroke being captured, an export, or the overlays: nothing at - // all, or the hold would bind a key and then fire what it just bound. - for key in ["up", "left", "escape", "5"] { - assert!(!repeats(Repeat::Nothing, key, Some(ActionId::VolumeUp))); - } - } - - #[test] - fn the_silence_card_fits_the_smallest_window_and_never_slows_a_silence_down() { - // The same 640x360 floor, and this card starts below the header: a - // title and a hint over its [`SILENCE_ROWS`] rows, the count line and - // the two buttons. - let (title, hint, count) = (17., 17., 17.); - let gaps = 6. * 5.; - let padding = 24.; - assert!( - HEADER_H - + 8. - + title - + hint - + SILENCE_ROWS as f32 * KEYS_ROW_H - + count - + KEYS_ROW_H - + gaps - + padding - <= 360., - "card too tall" - ); - // Its rows, its steppers and its buttons are clicked, so WCAG 2.5.8 - // binds them: a stepper is `HIT_MIN` square inside a row of that height. - assert!(KEYS_ROW_H >= HIT_MIN); - // ...and the pair of them fits beside the widest value the card prints. - assert!(2. * HIT_MIN + 4. < COLOR_W / 2., "steppers crowd the value"); - // A "speed-up" is never a slow-down: the rate stops above real time at - // one end and at what a clip can hold at the other, whatever the keys - // ask for. A silence played *slower* would make the timeline longer, - // which is the one thing neither button may do. - assert!(silence_rate(0) > Speed::NORMAL); - assert!(silence_rate(1000) > Speed::NORMAL); - assert_eq!(silence_rate(i32::MAX), Speed::MAX); - assert_eq!(silence_rate(4000), Speed::MAX); - } - - /// The choice lists that replaced two click-to-cycle surfaces: every value - /// on offer at once, exactly one of them marked as the one in force, the - /// same order the stroke steps through, and the open list inside the - /// 640x360 floor with every row a `HIT_MIN` target. - #[test] - fn a_choice_list_offers_every_value_and_fits_the_smallest_window() { - // Odd media: its own size is on the ladder, in its place by area, and - // nothing else moved. - let native = (1440, 1080); - let ladder = resolution_ladder(native); - assert_eq!( - ladder, - [ - (3840, 2160), - (2560, 1440), - (1920, 1080), - (1440, 1080), - (1280, 720), - (854, 480) - ] - ); - for size in RESOLUTIONS { - assert!(ladder.contains(&size), "{size:?} is not on offer"); - } - // Media already at a listed size is on the ladder once, not twice. - assert_eq!(resolution_ladder((1920, 1080)).len(), RESOLUTIONS.len()); - - // The rows say the same thing the ladder does, and mark the one in - // force -- exactly one row, whichever rung the project is on. - let rows = resolution_choices((1280, 720), native); - assert_eq!(rows.len(), ladder.len()); - assert_eq!(rows.iter().filter(|(.., picked)| *picked).count(), 1); - for ((choice, label, detail, picked), size) in rows.iter().zip(&ladder) { - assert_eq!(*choice, Choice::Size(size.0, size.1)); - assert_eq!(label.as_ref(), format!("{}p", size.1)); - assert!(detail.contains(&format!("{}x{}", size.0, size.1))); - assert_eq!(*picked, *size == (1280, 720)); - } - // The media's own size says so: it is the one rung a person cannot read - // off a number they chose. - let (.., native_detail, _) = &rows[3]; - assert!( - native_detail.contains("the media's own"), - "{native_detail}" - ); - // A project at a size nobody listed still gets the whole list, with - // nothing marked rather than a wrong row marked. - assert!( - resolution_choices((1000, 1000), native) - .iter() - .all(|(.., picked)| !picked) - ); - // Picking a row means that row, and stepping means the next one: the - // list and the stroke read the same ladder. - assert_eq!(next_resolution(ladder[1], native), ladder[2]); - - // The fit list, on a clip: all four policies, in the order the stroke - // steps through them, the clip's own marked and every row naming the - // canvas it would place the picture on. - let mut fit = FITS[0]; - for next in FITS.into_iter().skip(1).chain([FITS[0]]) { - assert_eq!(next_fit(fit), next, "the stroke skips a policy"); - fit = next; - } - let fits = fit_choices(Lane::V1, 3, FITS[2], (1920, 1080)); - assert_eq!(fits.len(), FITS.len()); - assert_eq!(fits.iter().filter(|(.., picked)| *picked).count(), 1); - assert_eq!(fits[2].0, Choice::Fit(Lane::V1, 3, FITS[2])); - assert!(fits[2].3, "the clip's own policy is not marked"); - assert!(fits[0].2.contains("1920x1080"), "{}", fits[0].2); - - // The rate list, the other setting the project has of its own: every - // rate on offer, the media's own cycled in at its place by speed and - // said so, and the one the timeline is cut at marked. The value carried - // is the `f64` the engine conforms to, not the rounded label -- 23.976 - // is not 24000/1001, and a rate the timescales cannot name is refused. - let ntsc = 24_000. / 1001.; - let rates = frame_rate_ladder(25.); - assert_eq!(rates.len(), FRAME_RATES.len(), "25 is already on the list"); - let odd = frame_rate_ladder(48.); - assert_eq!(odd[5], 48., "the media's own, in its place by speed"); - assert_eq!(odd.len(), FRAME_RATES.len() + 1); - let fps = fps_choices(ntsc, 48.); - assert_eq!(fps.len(), odd.len()); - assert_eq!(fps.iter().filter(|(.., picked)| *picked).count(), 1); - assert_eq!(fps[0].0, Choice::Fps(ntsc), "the ratio, not 23.976"); - assert_eq!(fps[0].1.as_ref(), "23.976 fps"); - assert!(fps[0].3, "the rate in force is not marked"); - assert!(fps[5].2.contains("the media's own"), "{}", fps[5].2); - for (.., detail, _) in &fps { - assert!(detail.chars().count() < 26, "{detail} loses its tail"); - } - - // The HDR list, the third project setting: all three renditions in the - // order they brighten, the one in force marked, and every row saying - // what it is in words that fit beside the label. - let tones = tone_choices(Preset::Standard); - assert_eq!(tones.len(), Preset::ALL.len()); - assert_eq!(tones.iter().filter(|(.., picked)| *picked).count(), 1); - for (row, preset) in tones.iter().zip(Preset::ALL) { - assert_eq!(row.0, Choice::Tone(preset)); - assert_eq!(row.1.as_ref(), tone_label(preset)); - assert!(!row.2.is_empty(), "{preset:?} says nothing about itself"); - assert!(row.2.chars().count() < 26, "{} loses its tail", row.2); - } - assert!(tones[1].3, "the rendition in force is not marked"); - - // The open list fits the floor the menus are measured against: the - // longest of them is the rate ladder with an odd rate cycled in, and it - // hangs at the pointer with every row on screen. Rows are click targets - // (WCAG 2.5.8). - assert!(MENU_ROW_H >= HIT_MIN); - assert!(odd.len() > ladder.len(), "the longest list moved"); - assert!(MENU_PAD * 2. + odd.len() as f32 * MENU_ROW_H <= 360.); - let tall = MENU_PAD * 2. + ladder.len() as f32 * MENU_ROW_H; - assert!(tall <= 360., "the list is taller than the floor"); - assert_eq!( - menu_at(point(px(600.), px(340.)), size(px(640.), px(360.)), tall), - (640. - MENU_W, 360. - tall), - "the list would hang off the smallest window" - ); - } - - #[test] - fn the_export_card_fits_the_smallest_window() { - // Same 640x360 floor the keybindings card is measured against: the - // capped row list, the two summary lines and the confirm button, under - // a title and a status line. - let title = 17.; - let status = 28.; - // The head is one line of 11 px at this width -- every field of it, - // worst case, is 71 characters against the 76 that fit. The tail is - // budgeted for two: the destination's name is the user's and a long one - // wraps. - let summary = 15. + 30.; - // Six children in the column, so five gaps. - let gaps = 5. * 2.; - let padding = 24.; - assert_eq!( - EXPORT_FIXED_H, - title + status + summary + CONTROL_H + 4. + gaps + padding - ); - assert!(EXPORT_FIXED_H + EXPORT_ROWS_H <= 360., "card too tall"); - // The list grows with a window that has the room -- and never shrinks - // below the cap that made the floor fit, whatever arithmetic the window - // hands it. - let cap = |h: f32| (h - EXPORT_FIXED_H - 24.).max(EXPORT_ROWS_H); - assert_eq!(cap(360.), EXPORT_ROWS_H); - assert_eq!(cap(0.), EXPORT_ROWS_H); - assert!(cap(720.) > EXPORT_ROWS_H); - assert!(EXPORT_FIXED_H + cap(720.) <= 720.); - // ...and inside the 640 px floor with the scrim showing either side. - assert!(EXPORT_W + 2. * 12. <= 640.); - // The cap is only honest if enough of the list is on screen to read as - // one -- and the whole format section is: its header and every codec - // row, so nothing that is picked *first* is behind a scroll. - let codecs = FORMATS.iter().filter(|(row, ..)| !row.is_empty()).count(); - assert!(EXPORT_ROWS_H / KEYS_ROW_H >= 1. + codecs as f32); - // Clickable rows, so WCAG 2.5.8 binds them as it binds the panel's -- - // and the bitrate steppers are `HIT_MIN` squares sitting inside a row, - // which only fits while the row is at least as tall as one. - assert!(KEYS_ROW_H >= HIT_MIN); - assert!(CONTROL_H >= HIT_MIN); - // The dimmed text on the card -- every refusal, every detail, every key - // in its column -- is body text on `BG_RAISED` and WCAG 1.4.3 binds it. - // A dimmed row is drawn in this ink rather than at an opacity, which is - // what a refusal used to be readable through. - // Every palette, not the one in force: a family is picked at runtime - // now (`ui::theme`), so a floor met by one of them and missed by the - // other is a window somebody is looking at. - for id in crate::ui::theme::PaletteId::ALL { - let p = id.palette(); - assert!( - contrast(p.FG_SECONDARY, p.BG_RAISED) >= 4.5, - "{id:?}: refusal ink {:.2}", - contrast(p.FG_SECONDARY, p.BG_RAISED) - ); - // ...and on the picked row, where the highlight is the accent at - // surface brightness. Both inks clear 4.5:1 on it now -- the row still - // lifts its key and detail to `FG_PRIMARY`, as emphasis rather than as - // the rescue it used to be. - assert!(contrast(p.FG_PRIMARY, p.BG_SELECTED) >= 4.5, "{id:?}"); - assert!( - contrast(p.FG_SECONDARY, p.BG_SELECTED) >= 4.5, - "{id:?}: refusal ink on the picked row {:.2}", - contrast(p.FG_SECONDARY, p.BG_SELECTED) - ); - } - } - - /// The progress line's two clocks, driven the way a repaint drives them: - /// steady work, a stall where hardware hands over to software, then steady - /// work again. The estimate may not whipsaw, may not vanish once it has - /// been given, and must meet the elapsed clock at the end. - #[test] - fn the_export_estimate_rides_out_a_stall_and_converges() { - let (mut marks, mut elapsed, mut progress) = (Vec::new(), 0f32, 0f32); - // 2%/s, a 12 s stall at 40% -- longer than the window, so the window - // alone would have nothing left to measure -- and the same rate to the - // end: 62 s of wall clock for 50 s of work. - let rate = 0.02; - let (mut quiet, mut before_stall, mut after_stall, mut last) = (0f32, 0., 0., f32::MAX); - while progress < 1. { - let stalled = (20. ..32.).contains(&elapsed); - note_progress(&mut marks, elapsed, progress); - // What is really left, to hold every guess against. - let truth = (1. - progress) / rate + if stalled { 32. - elapsed } else { 0. }; - match eta_secs(&marks, elapsed, progress) { - // "estimating…" is only allowed before there is a span to - // measure, and never again after the first number. - None => { - assert!(elapsed < ETA_SPAN + 1., "estimate vanished at {elapsed}"); - quiet = elapsed; - } - Some(left) => { - // No guess is ever wilder than four times the truth: that - // is the eightfold spike a raw window rate throws on either - // edge of the stall. - assert!(left <= truth * 4., "at {elapsed}s: {left} vs {truth}"); - // While the rate holds, the answer is the true one and it - // only ever counts down. - if elapsed >= 5. && elapsed < 20. { - assert!((left - truth).abs() <= truth * 0.15, "{elapsed}s: {left}"); - assert!(left < last, "estimate grew while the rate held"); - } - // Eight seconds past the stall it has caught up again. - if elapsed >= 40. { - assert!((left - truth).abs() <= truth * 0.25, "{elapsed}s: {left}"); - assert!(left < last + 0.001, "estimate grew after the stall"); - } - if (20. ..20.25).contains(&elapsed) { - before_stall = left; - } - if (31.5..31.75).contains(&elapsed) { - after_stall = left; - } - last = left; - } - } - // A window's worth of marks and no more, however long the encode. - assert!(marks.len() <= 20, "{} marks", marks.len()); - elapsed += 0.25; - if !stalled { - progress = (progress + rate * 0.25).min(1.); - } - } - assert!(quiet > 0. && quiet < ETA_SPAN + 1.); - // The stall stretched the guess instead of erasing it, and by more than - // the stopped clock adds on its own. - assert!( - after_stall > before_stall + 12., - "{before_stall} -> {after_stall}" - ); - // Both clocks meet: a finished pass has nothing left. - assert_eq!(eta_secs(&marks, elapsed, 1.), Some(0.)); - assert!((elapsed - 62.).abs() < 1., "{elapsed}"); - assert_eq!(clock(83.4), "1:23"); - assert_eq!(clock(114.), "1:54"); - assert_eq!(clock(-1.), "0:00"); - } - - /// The import line's own state machine, driven the way a repaint drives - /// it: the worker writes a stage, the poll notices it changed and restarts - /// the stall clock, and the line's words change only when a stage has - /// actually stood still. The whole point is that a stuck read reads as a - /// stuck read and never as a frozen window. - #[test] - fn an_import_line_says_a_stage_has_stopped_moving_and_only_then() { - use std::sync::Arc; - use std::sync::atomic::{AtomicU8, Ordering::Relaxed}; - let stage = Arc::new(AtomicU8::new(ImportStage::Header as u8)); - let started = Instant::now() - Duration::from_secs(9); - let mut import = Import { - path: PathBuf::from("/films/A Film.mkv"), - started, - stage: Arc::clone(&stage), - seen: ImportStage::Header, - // As if the header had been running for those nine seconds. - since: started, - cancelled: Arc::default(), - }; - // Nine seconds inside one stage: past the wait a person tolerates, so - // the line stops pretending it is a progress line. - let since = import.poll(); - assert!(since > IMPORT_STALL, "{since}"); - let stalled = import_line("A Film.mkv", import.seen, 9., since, 0, false); - assert!(stalled.contains("still reading the header"), "{stalled}"); - assert!(stalled.contains("not frozen"), "{stalled}"); - assert!(stalled.contains("0:09 elapsed"), "{stalled}"); - // The worker moves on: the stall clock restarts even though the elapsed - // one does not, which is the distinction the two clocks exist for. - stage.store(ImportStage::Subtitles as u8, Relaxed); - let since = import.poll(); - assert_eq!(import.seen, ImportStage::Subtitles); - assert!(since < IMPORT_STALL, "{since}"); - let moving = import_line("A Film.mkv", import.seen, 9., since, 2, false); - assert!( - moving.starts_with("IMPORTING A Film.mkv · reading the subtitle tracks"), - "{moving}" - ); - assert!(!moving.contains("still"), "{moving}"); - // ...and what is behind it in the queue, which is what a drop of three - // files or an argv of three files leaves waiting. - assert!(moving.ends_with("· 2 more waiting"), "{moving}"); - assert!(!stalled.ends_with("waiting"), "an empty queue says nothing"); - // A stage that does not move is not the same fact as a stage that came - // back to the same value: the poll only restarts on a change. - let held = import.since; - import.poll(); - assert_eq!(import.since, held, "an unchanged stage must not reset it"); - } - - /// The launch, from argv to the window being up: nothing named on the - /// command line is read before there is a window, so all a launch does is - /// sort argv into the file that becomes the timeline and the queue that is - /// read through -- and a run with no arguments has neither, exactly as it - /// had none before. - #[test] - fn a_launch_queues_the_file_it_names_instead_of_opening_it() { - let film = PathBuf::from("/films/Dune.mkv"); - let extra = PathBuf::from("/films/Titles.mov"); - let (arg, queue) = launch_queue([film.clone(), extra.clone()].into_iter()); - assert_eq!(arg.as_deref(), Some(film.as_path()), "argv[1] is the open"); - // In the order they were named, the timeline's file first: six header - // walks racing over one disk finish no sooner than six in a row, and - // the one the person is waiting to watch goes first. - assert_eq!(queue, [film, extra], "argv, in arrival order"); - // ...and no argument at all is still the empty window: nothing to open - // and nothing to read. - let (arg, queue) = launch_queue(std::iter::empty()); - assert_eq!(arg, None); - assert!(queue.is_empty(), "no argv, nothing queued"); - } - - /// Which door a queued file goes through. One queue carries the file argv - /// named and every import behind it, so this fork -- made when the worker - /// starts and carried to the landing as a [`Landed`] -- is the whole state - /// machine: the named file becomes the timeline (a `.edith` restoring a - /// whole one), everything else joins the library, including the very same - /// film dropped again once the open has landed. - #[test] - fn the_file_argv_named_lands_as_the_timeline_and_everything_behind_it_as_imports() { - let film = PathBuf::from("/films/Dune.mkv"); - let extra = PathBuf::from("/films/Titles.mov"); - let project = PathBuf::from("/films/Dune.edith"); - assert_eq!(arrival(Some(&film), &film), Landing::Open); - assert_eq!(arrival(Some(&project), &project), Landing::Project); - assert_eq!(arrival(Some(&film), &extra), Landing::Import); - // Cleared as it lands: a drop of the film already on the timeline is an - // import, which is what a drop has always been. - assert_eq!(arrival(None, &film), Landing::Import); - // ...except a `.edith`, which is a whole timeline and has nothing to be - // imported into: dropped or picked, it lands where argv's does, and its - // open is the worker's like every other. - assert_eq!(arrival(None, &project), Landing::Project); - assert_eq!(arrival(Some(&film), &project), Landing::Project); - } - - /// What the window says while the file argv named is being read: the file's - /// name, the read that is running, and a clock proving the window is - /// answering -- in the *opening* wording, because the one person who typed - /// that name is not importing anything. - #[test] - fn the_named_file_is_read_under_an_opening_line_not_an_importing_one() { - let opening = import_line("Dune.mkv", ImportStage::Header, 0.4, 0.4, 1, true); - assert!( - opening.starts_with("OPENING Dune.mkv · reading the header"), - "{opening}" - ); - assert!(opening.ends_with("· 1 more waiting"), "{opening}"); - // Twelve seconds into a cold 25 GB header walk, which is the whole - // reason the window is up: it says the read is still moving through the - // same stage and that this is not a freeze. - let stalled = import_line("Dune.mkv", ImportStage::Header, 12., 12., 0, true); - assert!(stalled.starts_with("OPENING Dune.mkv · still"), "{stalled}"); - assert!(stalled.contains("not frozen"), "{stalled}"); - assert!(stalled.contains("0:12 elapsed"), "{stalled}"); - // The files behind it are imports and still say so. - let import = import_line("Titles.mov", ImportStage::Header, 0.4, 0.4, 0, false); - assert!(import.starts_with("IMPORTING Titles.mov"), "{import}"); - } - - /// One gesture over the real gate, with the plumbing around it spelled out: - /// a write reseeks (the worker owes a frame again), a landed frame clears - /// that and flushes what is held, and the release flushes whatever the - /// worker is doing. Forty snapped steps and four frames delivered must cost - /// five writes -- the press's and one per frame -- and not forty, which is - /// the 22-30 s freeze this exists to remove. - #[test] - fn a_bar_wide_sweep_writes_once_per_frame_delivered() { - let mut stash: Option = None; - let mut written = Vec::new(); - let mut busy = false; - for step in 0..40 { - if let Some(value) = stash_or_write(&mut stash, step, step == 0, busy) { - // What `write_color` does: the write supersedes the stash and - // reseeks, so the worker owes a frame from here. - stash = None; - written.push(value); - busy = true; - } - // A frame lands every tenth sample: `pump` clears the seek and the - // render flushes what the drag held back. - if step % 10 == 9 { - busy = false; - if let Some(value) = stash.take() { - written.push(value); - busy = true; - } - } - } - // The release, whatever the worker is doing. - written.extend(stash.take()); - assert_eq!(written, vec![0, 9, 19, 29, 39], "one write per frame landed"); - } - - /// The one value a gesture may never lose: where the hand let go. The - /// release samples into a busy worker -- so the sample is held -- and the - /// flush behind it is what writes it. - #[test] - fn a_release_lands_the_value_the_hand_let_go_on() { - let mut stash = None; - assert_eq!(stash_or_write(&mut stash, 7, false, true), None); - assert_eq!(stash_or_write(&mut stash, 11, false, true), None); - assert_eq!(stash.take(), Some(11), "the release writes the last sample"); - // The press is never held: it is the undo step the gesture rolls back - // to, and one taken a frame late is a snapshot of the wrong grade. - assert_eq!(stash_or_write(&mut stash, 3, true, true), Some(3)); - assert_eq!(stash, None); - // Nothing to hold when the worker is idle: the write goes straight out. - assert_eq!(stash_or_write(&mut stash, 5, false, false), Some(5)); - assert_eq!(stash, None); - } - - /// A seek says nothing until it has stood: an ordinary one is a flicker and - /// a cold read of a big file is the case worth words. - #[test] - fn a_seek_says_so_only_once_it_has_stood() { - assert_eq!(seek_line(None), None, "no seek, no line"); - assert_eq!(seek_line(Some(Duration::from_millis(300))), None); - let line = seek_line(Some(SEEK_STALL + Duration::from_secs(7))).expect("past the stall"); - assert!(line.contains("still opening the picture"), "{line}"); - assert!(line.contains("not frozen"), "{line}"); - assert!(line.contains("0:09 elapsed"), "{line}"); - } - - /// The silence card's own state machine, driven the way a repaint drives - /// it: a worker moves its mark, the poll notices and restarts the stall - /// clock, and the line says a read has stopped only when it actually has. - /// The card is up through all of it -- that is the whole change, since the - /// same decode used to run on the render thread and hold the frame for - /// fifty-one seconds on a 25 GB film. - #[test] - fn a_silence_card_is_up_while_its_scan_runs_and_says_where_it_has_got_to() { - use std::sync::Arc; - use std::sync::atomic::Ordering::Relaxed; - let progress = Arc::new(engine::silence::Progress::default()); - // Two hours and eight minutes, as the header claims it. - progress.total.store(7680, Relaxed); - let started = Instant::now() - Duration::from_secs(9); - let mut scan = SilenceScan { - key: (PathBuf::from("/films/A Film.mkv"), 0, 0, 192_000), - started, - progress: Arc::clone(&progress), - seen: 0, - since: started, - }; - // Nine seconds and the mark has not moved: past the wait a person - // tolerates, so the line stops pretending it is a progress line. - let since = scan.poll(); - assert!(since > IMPORT_STALL, "{since}"); - let stalled = silence_line(0., 768., 9., since); - assert!(stalled.contains("still reading the sound"), "{stalled}"); - assert!(stalled.contains("not frozen"), "{stalled}"); - assert!(stalled.contains("0:00 of ~12:48 scanned"), "{stalled}"); - assert!(stalled.contains("0:09 elapsed"), "{stalled}"); - // The worker reports, and the stall clock restarts even though the - // elapsed one does not -- the two clocks' whole distinction. - let mut last = 0; - for deci in [83, 1_140, 4_002] { - progress.scanned.store(deci, Relaxed); - let since = scan.poll(); - assert!(since < IMPORT_STALL, "{since}"); - assert!(scan.seen > last, "{} after {last}", scan.seen); - last = scan.seen; - } - let moving = silence_line(scan.seen as f32 / 10., 768., 9., 0.2); - assert_eq!(moving, "SCANNING · 6:40 of ~12:48 scanned · 0:09 elapsed"); - assert!(!moving.contains("still"), "{moving}"); - // A header that does not say how long the track is says nothing rather - // than guessing at it. - let unknown = silence_line(60., 0., 61., 0.2); - assert_eq!(unknown, "SCANNING · 1:00 scanned · 1:01 elapsed"); - // A mark that comes back the same is not the same fact as one that - // moved: the poll only restarts on a change. - let held = scan.since; - scan.poll(); - assert_eq!(scan.since, held, "an unchanged mark must not reset it"); - } - - /// The cache is per scanned stretch, which is what stops two films - /// thrashing each other's fifty seconds: A, then B, then A again is *one* - /// decode of A. And a stretch already being read is waited for rather than - /// read twice -- both halves of an A/V take name the same file and the same - /// frames. A *trimmed* A is not A: it is a shorter read of its own, which - /// is the whole point of scanning the clip instead of the file. - #[test] - fn a_second_film_does_not_cost_the_first_one_its_levels() { - let (a, b) = ( - (PathBuf::from("/films/a.mkv"), 0, 0, 3000), - (PathBuf::from("/films/b.mkv"), 0, 0, 3000), - ); - let half = (PathBuf::from("/films/a.mkv"), 0, 0, 1500); - let mut cache: std::collections::HashMap = std::collections::HashMap::new(); - let mut started = Vec::new(); - // What a card open does, three times over, with the worker landing - // between each: plan, and start what the plan says to start. - for key in [&a, &b, &a] { - match scan_plan(cache.contains_key(key), None, key) { - ScanPlan::Start => { - started.push(key.clone()); - cache.insert(key.clone(), ()); - } - ScanPlan::Marks => {} - ScanPlan::Wait => unreachable!("nothing is running"), - } - } - assert_eq!(started, vec![a.clone(), b.clone()], "A was decoded twice"); - // The single-slot cache this replaced would have evicted A when B - // landed; both are held. - assert!(cache.contains_key(&a) && cache.contains_key(&b)); - // A scan in flight on the same source is joined, not restarted -- and - // one on another source is not waited for. - assert_eq!(scan_plan(false, Some(&a), &a), ScanPlan::Wait); - assert_eq!(scan_plan(false, Some(&b), &a), ScanPlan::Start); - // Levels in hand beat a worker either way: the marks are arithmetic. - assert_eq!(scan_plan(true, Some(&a), &a), ScanPlan::Marks); - // The same file cut in half is a read of its own: neither A's levels - // nor A's worker answers for it. - assert_eq!( - scan_plan(cache.contains_key(&half), None, &half), - ScanPlan::Start - ); - assert_eq!(scan_plan(false, Some(&a), &half), ScanPlan::Start); - // ...and the seconds asked for are the clip's, at the project's rate. - assert_eq!(source_secs(&half, 30.), (0., 50.)); - assert_eq!(source_secs(&(half.0.clone(), 0, 900, 1500), 30.), (30., 50.)); - // A rate that is not one reads the file rather than nothing. - assert_eq!(source_secs(&half, 0.), (0., f64::INFINITY)); - } - - /// The two halves a worker hands back for an import, unwrapped: every import - /// lands as a [`Landed::Read`], and a test that has to say so at four call - /// sites is saying it once here. - fn read_parts( - path: &std::path::Path, - stage: &std::sync::atomic::AtomicU8, - gate: Option, - ) -> (Subs, crate::Probe) { - match read_ahead(path, stage, gate) { - crate::Landed::Read(subs, probe) => (subs, probe), - _ => panic!("an import into a timeline that is up lands as a read"), - } - } - - /// The import door's split, which is what keeps the render thread out of a - /// header walk: what the worker probed and what the landing registers add up - /// to exactly the rows, lengths and refusals the in-place import lands. - #[test] - fn probing_ahead_lands_exactly_what_importing_in_place_lands() { - use std::sync::atomic::AtomicU8; - let stage = AtomicU8::new(ImportStage::Header as u8); - let plain = { - let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open"); - session.set_gain(0.0); - session.import(&asset("test_av2.mp4")).expect("av2 matches"); - ( - session.sources().to_vec(), - session.file_frames(&asset("test_av2.mp4")), - session.timeline_duration(), - ) - }; - let split = { - let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open"); - session.set_gain(0.0); - let (subs, probe) = - read_parts(&asset("test_av2.mp4"), &stage, Some(session.import_gate())); - // This mp4 is walked now (an mp4 can carry `tx3g`) and has no - // subtitle track in it, so the worker hands over an empty list -- - // the same thing the import lands with. - assert!(subs.expect("an mp4 is readable").is_empty()); - let probe = probe - .expect("a container is probed on the worker") - .expect("av2 matches"); - session - .import_probed(&asset("test_av2.mp4"), probe) - .expect("av2 matches"); - ( - session.sources().to_vec(), - session.file_frames(&asset("test_av2.mp4")), - session.timeline_duration(), - ) - }; - assert_eq!(plain, split); - // ...and it leaves the stage where the line can read it: a worker that - // never announced its second read would show one that never ends. - assert_eq!( - ImportStage::from_u8(stage.load(std::sync::atomic::Ordering::Relaxed)), - ImportStage::Subtitles - ); - // A refusal is the engine's refusal, and now it is *the* refusal: the - // walk happens once, on the worker, so what the probe says is what the - // notice shows -- worded exactly as importing in place worded it. - let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open"); - session.set_gain(0.0); - let (_, probe) = read_parts(&asset("test_25fps.mp4"), &stage, Some(session.import_gate())); - let on_the_worker = probe - .expect("a container is probed") - .map(|_| ()) - .map_err(|e| e.to_string()); - assert_eq!( - on_the_worker, - session - .import(&asset("test_25fps.mp4")) - .map(|_| ()) - .map_err(|e| e.to_string()) - ); - // A timeline that moved while the worker read is not one the probe was - // decided against, so the probe is not trusted -- the import is simply - // taken the slow way and lands the same row. - let mut moved = PlaybackSession::open(asset("test_av.mp4")).expect("open"); - moved.set_gain(0.0); - let (_, probe) = read_parts(&asset("test_av2.mp4"), &stage, Some(moved.import_gate())); - moved.import(&asset("test_still.png")).expect("a still joins"); - let stale = probe.expect("a container is probed").expect("av2 matches"); - assert_eq!( - moved.import_probed(&asset("test_av2.mp4"), stale).ok(), - Some(2), - "a stale probe still lands the file, by the door that re-reads it" - ); - // A path nothing can read is refused by the worker now, in the engine's - // own words: nothing walks it a second time to re-word it, and neither - // half is a panic. - let (subs, probe) = read_parts( - std::path::Path::new("/no/such/film.mkv"), - &stage, - Some(session.import_gate()), - ); - assert!(subs.is_err(), "the cue walk comes back as a refusal"); - assert!( - probe.expect("a container is probed").is_err(), - "and so does the container walk" - ); - } - - /// The import door's two halves, split across the worker hop: what - /// [`read_ahead`] walks is exactly what the render thread would have walked, - /// and pushing it says what walking it in place used to say. - #[test] - fn an_imports_subtitles_are_read_by_the_worker_and_only_pushed_here() { - use std::sync::atomic::AtomicU8; - let stage = AtomicU8::new(ImportStage::Header as u8); - let film = asset("test_subs.mkv"); - // The in-place walk (`subtitle_notice`) and the split one land the same - // tracks and the same tail on the same timeline. - let mut in_place = PlaybackSession::open(asset("test_av.mp4")).expect("open"); - in_place.set_gain(0.0); - let said = subtitle_notice(&mut in_place, &film); - let mut split = PlaybackSession::open(asset("test_av.mp4")).expect("open"); - split.set_gain(0.0); - let (walked, _) = read_parts(&film, &stage, Some(split.import_gate())); - let walked = walked.expect("the mkv is readable"); - assert_eq!(subtitle_tail(&mut split, Ok(walked)), said); - assert_eq!(split.subtitles().len(), in_place.subtitles().len()); - // The same file twice is still one row, and still says so: the dedupe - // lives in the push, which is the half that stayed here. - let (again, _) = read_parts(&film, &stage, Some(split.import_gate())); - let again = again.expect("the mkv is readable"); - assert_eq!(subtitle_tail(&mut split, Ok(again)), None); - // A standalone `.srt` is walked by the same worker: an import of one is - // not a door that reads on the render thread either. - let srt = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../engine/tests/data/test_subs.srt") - .canonicalize() - .expect("the subtitle fixture"); - assert_eq!( - read_parts(&srt, &stage, Some(split.import_gate())) - .0 - .expect("the srt is readable") - .len(), - 1 - ); - // ...and a refusal is worded as a tail, never as a failed import. - let unread: Subs = Err("nothing to read".into()); - assert_eq!( - subtitle_tail(&mut split, unread), - Some(" — SUBTITLES UNREAD: nothing to read".to_string()) - ); - } - - #[test] - fn every_codec_row_is_offered_or_says_why_not() { - // One row per codec, and the boxes it can go in are the container row's - // business: seven rows that pick, one that says why it cannot. A codec - // twice over (AV1 · MKV beside AV1 · MP4) was two rows asking the same - // question, and five picture rows above the fold is what the card was - // called unfriendly for. - let offered: Vec<&[Format]> = FORMATS - .iter() - .map(|&(row, ..)| row) - .filter(|row| !row.is_empty()) - .collect(); - assert_eq!( - offered, - vec![ - &[Format::Mp4][..], - &[Format::Av1, Format::Av1Mp4][..], - &[Format::Hevc, Format::HevcMp4][..], - &[Format::Wav][..], - &[Format::Flac][..], - &[Format::Mp3][..], - &[Format::Ogg][..], - ] - ); - // Every format the engine writes is on exactly one row: one the card - // cannot reach is one nobody can pick. - for format in [ - Format::Mp4, - Format::Av1, - Format::Av1Mp4, - Format::Hevc, - Format::HevcMp4, - Format::Wav, - Format::Flac, - Format::Mp3, - Format::Ogg, - ] { - assert_eq!( - FORMATS - .iter() - .filter(|(row, ..)| row.contains(&format)) - .count(), - 1, - "{format:?}" - ); - } - // The boxes the container row offers, and what the extension of each is - // -- the destination follows the format, so these are what a file gets - // named with. - assert_eq!(containers(Format::Av1), [Format::Av1, Format::Av1Mp4]); - assert_eq!(containers(Format::HevcMp4), [Format::Hevc, Format::HevcMp4]); - assert_eq!(containers(Format::Mp3), [Format::Mp3]); - assert_eq!(Format::Av1.ext(), "mkv"); - assert_eq!(Format::Av1Mp4.ext(), "mp4"); - assert_eq!(Format::Hevc.ext(), "mkv"); - assert_eq!(Format::HevcMp4.ext(), "mp4"); - // The container key walks the row and wraps, and does nothing at all - // where there is only one box -- a stroke must not invent a choice the - // card is not offering. - assert_eq!(next_container(Format::Av1), Format::Av1Mp4); - assert_eq!(next_container(Format::Av1Mp4), Format::Av1); - assert_eq!(next_container(Format::Hevc), Format::HevcMp4); - assert_eq!(next_container(Format::Mp4), Format::Mp4); - assert_eq!(next_container(Format::Wav), Format::Wav); - for (row, stroke, label, detail) in FORMATS { - assert!(!label.is_empty(), "a row with no name"); - // A refused row is a row with a reason, never a hidden one: an - // empty detail column would read as an oversight. - assert!(!detail.is_empty(), "{label} says nothing"); - // Every row that can be picked has a key of its own, and no row - // that cannot has one: the card is drivable without a pointer. - assert_eq!(!row.is_empty(), !stroke.is_empty(), "{label}"); - if let Some(&first) = row.first() { - assert_eq!( - format_key(stroke, first), - Some(first), - "{label} keys to itself" - ); - assert!( - stroke.parse::().is_err(), - "{label} takes a digit the bitrate needs" - ); - // Every box on one row is the same codec, so the quality rows - // do not change meaning when the container does. - assert!(row.iter().all(|f| f.has_video() == first.has_video())); - assert!( - row.iter() - .all(|f| bitrate_refusal(*f) == bitrate_refusal(first)) - ); - } - } - // No two rows share a key, and none of them is a stroke the card already - // answers to itself -- an ambiguous key is a key that picks the wrong - // thing on a card that has no other input. - let keys: Vec<&str> = FORMATS - .iter() - .map(|&(_, stroke, ..)| stroke) - .filter(|stroke| !stroke.is_empty()) - .collect(); - for (i, key) in keys.iter().enumerate() { - assert!(!keys[i + 1..].contains(key), "{key} picks two rows"); - assert!( - !["c", "q", "d", "g", "r", "enter", "backspace", ESCAPE].contains(key), - "{key} is already the card's own" - ); - } - assert_eq!( - format_key("a", Format::Mp4), - Some(Format::Av1Mp4), - "the box already chosen is kept" - ); - assert_eq!( - format_key("a", Format::Wav), - Some(Format::Av1), - "and a codec with no such box takes its first" - ); - assert_eq!(format_key("h", Format::Av1Mp4), Some(Format::HevcMp4)); - assert_eq!(format_key("p", Format::Mp4), Some(Format::Mp3)); - assert_eq!( - format_key("m", Format::Mp3), - Some(Format::Mp4), - "not MP3, which is p" - ); - assert_eq!( - format_key("x", Format::Mp4), - None, - "a stroke no row carries" - ); - assert_eq!(format_key("o", Format::Mp4), Some(Format::Ogg)); - // The one codec left that this program reads and cannot write is a row - // of its own, refused by name rather than absent: VP9, because AV1 is - // the row that replaced it. Its reason travels with it, in the row or in - // the footer line that collects them -- either way it is on screen - // without a click. OGG was the other one until `rusty_vorbis` gave this - // project an encoder, and the row that says so is the row above. - let (row, _, _, detail) = FORMATS - .into_iter() - .find(|(_, _, name, _)| *name == "VP9") - .expect("VP9 has a row"); - assert!(row.is_empty(), "VP9 is not offered"); - assert!(detail.contains("replaces it"), "VP9: {detail}"); - let (row, _, _, detail) = FORMATS - .into_iter() - .find(|(_, _, name, _)| *name == "OGG") - .expect("OGG has a row"); - assert_eq!(row, [Format::Ogg], "OGG is a row that picks now"); - assert!( - detail.contains("rusty_vorbis"), - "the row names the encoder like every other live one: {detail}" - ); - // Both AV1 boxes say they carry sound: the file used to be picture only, - // and a line that still said so would be the lie a user plays the file - // to find out about. HEVC says intra-only before anyone waits on one -- - // a file several times the size, which the disk would otherwise say. - for format in [Format::Av1, Format::Av1Mp4] { - assert!(format_line(format).starts_with("AV1 · ")); - } - for format in [Format::Hevc, Format::HevcMp4] { - assert!(format_line(format).starts_with("HEVC intra · ")); - } - // The head names the box every format goes in, which is what the - // destination is then named after. - for format in [ - Format::Mp4, - Format::Av1, - Format::Av1Mp4, - Format::Hevc, - Format::HevcMp4, - ] { - assert!( - format_line(format).contains(&format.ext().to_uppercase()), - "{format:?}: {}", - format_line(format) - ); - } - // ...and it stays inside the one line the card budgets for it: the - // longest of them, with every field after it, against the 76 characters - // that fit at `EXPORT_W`. - let longest = summary_head( - Format::Hevc, - Some(((1920, 1080), 23.976)), - "AAC · SW encode (rusty_aac)", - ); - assert!( - longest.chars().count() <= 76, - "{longest} is {} long", - longest.chars().count() - ); - assert!( - FORMATS - .into_iter() - .any(|(row, _, _, detail)| row.contains(&Format::Hevc) && detail.contains("intra")) - ); - // Only a picture encoder is given a bitrate, and the quality rows dim - // with the reason for every format that is not one. - for format in [ - Format::Mp4, - Format::Av1, - Format::Av1Mp4, - Format::Hevc, - Format::HevcMp4, - ] { - assert!( - format.has_video() && bitrate_refusal(format).is_none(), - "{format:?}" - ); - } - for format in [Format::Wav, Format::Flac, Format::Mp3] { - assert!(!format.has_video()); - assert!( - bitrate_refusal(format).is_some(), - "{format:?} dims silently" - ); - } - assert!(bitrate_refusal(Format::Wav).unwrap().contains("lossless")); - // MP3 has a rate and it is the *Sound* row's: the quality rows are the - // picture's, and this refusal used to claim a fixed 256 kbps that the - // Sound row can now change under it. - assert!(bitrate_refusal(Format::Mp3).unwrap().contains("Sound row")); - assert!( - !format_line(Format::Mp3).contains("256"), - "the summary states a rate the Sound row can change under it" - ); - // The destination follows the format and keeps the stem, mp4 included. - assert_eq!( - retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav), - std::path::Path::new("/a/take.export.wav") - ); - assert_eq!( - retarget(std::path::Path::new("/a/take.export.wav"), Format::Mp4), - std::path::Path::new("/a/take.export.mp4") - ); - assert!(format_line(Format::Flac).contains("lossless")); - } - - /// The one line the card is answerable for: what it says is on screen before - /// the button is pressed, and every field of it is one `ffprobe` reads back - /// off the file that comes out. - #[test] - fn the_summary_states_the_file_before_it_is_written() { - let head = summary_head(Format::Mp4, Some(((1920, 1080), 30.)), "AAC copy"); - for field in ["H.264", "MP4", "1920x1080", "30 fps", "AAC copy"] { - assert!(head.contains(field), "{field} missing from {head}"); - } - // The rate as a person writes it, and the ratio one spelled out rather - // than rounded to a rate nothing is written at. - assert_eq!(fps_label(30.), "30"); - assert_eq!(fps_label(24000. / 1001.), "23.976"); - assert_eq!(fps_label(29.97002997), "29.97"); - // A format with no picture states no size and no rate it does not write. - let audio = summary_head(Format::Wav, Some(((1920, 1080), 30.)), "PCM · SW (hound)"); - assert!( - !audio.contains("1920x1080") && !audio.contains("fps"), - "{audio}" - ); - assert!(audio.contains("PCM · SW (hound)")); - // ...and one with no sound on the timeline says that, rather than - // leaving the field out and reading as a file with sound in it. - assert!( - summary_head(Format::Mp4, Some(((640, 360), 25.)), "no sound to write") - .contains("no sound to write") - ); - // The tail: where it lands, about how big, and what will encode it -- - // never a guessed seat, and no seat at all for a format with no picture. - let tail = summary_tail( - Path::new("/a/take.export.mp4"), - Some(45_000_000), - Some("VA-API"), - true, - ); - assert!(tail.starts_with("take.export.mp4"), "{tail}"); - assert!( - tail.contains("≈ 45 MB") && tail.contains("VA-API"), - "{tail}" - ); - assert!(summary_tail(Path::new("/a/x.mp4"), None, None, true).contains("encoder …")); - assert!(!summary_tail(Path::new("/a/x.wav"), None, None, false).contains("encoder")); - assert!(!summary_tail(Path::new("/a/x.wav"), None, None, false).contains("MB")); - // 6 Mbps over a minute is 45 MB. `Auto` has no figure to estimate from - // and an empty timeline no length: neither invents one. - assert_eq!(estimated_bytes(Some(6_000_000), 60.), Some(45_000_000)); - assert_eq!(estimated_bytes(Some(2_000_000), 90.), Some(22_500_000)); - assert_eq!(estimated_bytes(None, 60.), None); - assert_eq!(estimated_bytes(Some(6_000_000), 0.), None); - assert_eq!(estimated_bytes(Some(0), 60.), None); - // ...and a short one is not nothing. Three seconds at the floor - // bitrate is 375 kB, which used to round to the "≈ 0 MB" this line - // exists to never say -- the shortest export a frame can make is - // still a real file with a real size. - let short = estimated_bytes(Some(1_000_000), 3.).expect("a rate and a length"); - assert_eq!(size_label(short), "375 kB"); - let frame = summary_tail(Path::new("/a/x.mp4"), estimated_bytes(Some(1_000_000), 1. / 60.), None, true); - assert!( - frame.contains("≈ 2 kB") && !frame.contains("0 MB") && !frame.contains("0 kB"), - "{frame}" - ); - // The boundary reads in the unit that can state it, either side. - assert_eq!(size_label(999_600), "1 MB"); - assert_eq!(size_label(499_000), "499 kB"); - assert_eq!(size_label(1), "1 kB"); - } - - /// Which cue is on screen when: the whole of what the overlay decides, and - /// the one piece of it that is arithmetic rather than layout. - #[test] - fn a_cue_is_on_screen_from_its_start_until_the_moment_it_ends() { - use engine::subtitle::Cue; - let cue = |start_us, end_us, text: &str| Cue { - start_us, - end_us, - text: text.to_string(), - image: None, - }; - // Two cues that hand over exactly, and one that overlaps the second -- - // a sign over a line of dialogue, which is two plates at one moment. - let cues = [ - cue(500_000, 1_500_000, "first line"), - cue(1_500_000, 2_500_000, "second line"), - cue(2_000_000, 2_200_000, "a sign"), - ]; - let at = |t: f64| -> Vec<&str> { - cues_at(&cues, t) - .into_iter() - .map(|c| c.text.as_str()) - .collect() - }; - // Before the first, between none of them: nothing, which is what makes - // the overlay disappear rather than sit there empty. - assert!(at(0.).is_empty()); - assert!(at(0.4).is_empty()); - assert!(at(3.).is_empty()); - assert_eq!(at(0.5), ["first line"], "on at its own start"); - assert_eq!(at(1.4), ["first line"]); - // Half-open: the frame the first ends on is the second's, never both. - assert_eq!(at(1.5), ["second line"]); - assert_eq!(at(2.1), ["second line", "a sign"], "two at once stack"); - assert_eq!(at(2.2), ["second line"], "the sign is over"); - // ...and the end of the last one is the end of it. - assert!(at(2.5).is_empty()); - // A negative time is before everything rather than a panic: the - // playhead is clamped, but nothing here depends on that. - assert!(at(-1.).is_empty()); - } - - /// The two places a subtitle is drawn -- the plate over the picture and the - /// strip under the lanes -- inside the 640x360 floor the rest of this window - /// is sized for, and the plate readable on whatever the film is showing. - #[test] - fn the_subtitle_plate_and_strip_fit_the_smallest_window() { - // The strip costs the panel its own row and the panel's gap, and costs - // nothing at all when there is no track to draw. - assert_eq!(subtitle_strip_h(false), 0.); - assert_eq!(subtitle_strip_h(true), SUB_LANE_H + 8.); - // What is left for the picture at the floor, with the panel a project - // starts with and the strip under it. - let picture = 360. - HEADER_H - panel_h(2) - subtitle_strip_h(true); - assert!(picture > 0., "the strip pushed the picture off the window"); - // A two-line cue and the gap under it fit inside that, which is the - // whole claim: the plate sits *over* the picture and must not need more - // of it than there is. - assert!( - SUB_BOTTOM + 2. * SUB_LINE_H <= picture, - "a two-line cue does not fit the smallest picture" - ); - // The text sits on its line rather than being clipped by it. - assert!(SUB_LINE_H >= SUB_TEXT); - // White on the plate, not chrome on chrome: a cue is read against the - // film, and this is the one pair here that has to survive any picture. - for id in crate::ui::theme::PaletteId::ALL { - assert!(contrast(id.palette().SUB_FG, 0x000000) >= 7., "{id:?}"); - } - // The strip is a picture and not a target -- nothing on it takes a - // click -- which is the only reason it may be under `HIT_MIN`. - assert!(SUB_LANE_H < HIT_MIN && SUB_LANE_H > 0.); - // The library's own list of tracks scrolls past three rather than - // taking the media list's room. - assert_eq!(SUB_ROWS_H / ROW_H, 3.); - assert!(ROW_H >= HIT_MIN, "a subtitle row is clicked to pick it"); - // At the floor there are no group headers at all: the list is one row - // tall there, and a header would name a film and then show none of it. - // The rows go on naming their own file, so nothing is lost by it. - assert!(!sub_headers_fit(360.), "a header at the floor eats the track"); - // At the size the window opens on there is room for a header and the - // tracks under it, which is the only condition it is drawn on. - assert!(sub_headers_fit(720.)); - // ...and where it is drawn it fits inside the same capped list, header - // and two rows under it, without the tracks losing their budget. - assert!(SUB_HEAD_H + 2. * ROW_H <= SUB_ROWS_H); - // A header takes no click -- there is nothing to fold and nothing to - // aim at -- which is the only reason it may be under `HIT_MIN`. - assert!(SUB_HEAD_H < HIT_MIN && SUB_HEAD_H > 0.); - } - - /// What the rows of both lists do with a name too long for the column: two - /// episodes off one release differ in their last two characters, and a name - /// cut from the right is the same row twice. - #[test] - fn a_long_name_is_cut_out_of_its_middle_so_two_episodes_stay_two_rows() { - let (a, b) = ( - "A Long Release Name Of A Series 01", - "A Long Release Name Of A Series 02", - ); - // The two call sites at the narrowest the column ever is: a media row's - // name gets the row's whole width, a subtitle row's file prefix gets a - // share of it because the language has to fit beside it. - let media = row_text_w(LIBRARY_MIN_W); - let prefix = media * SUB_STEM_SHARE; - for width in [media, prefix] { - assert!(width > 0., "the floor leaves a row no words at all"); - assert_ne!( - clip_middle(a, width), - clip_middle(b, width), - "{width}px: two episodes read as one row" - ); - // Both ends survive: the release's name at the front, the number - // that tells them apart at the back. - assert!(clip_middle(a, width).starts_with(&a[..2])); - assert!(clip_middle(a, width).ends_with("01")); - assert!(clip_middle(a, width).contains('…')); - // Never wider than the column can hold, gap included. - assert!(clip_middle(a, width).chars().count() <= (width / 6.) as usize + 1); - } - // A name the width holds is left exactly as it is -- no gap, nothing - // dropped -- and so is a name at any width once the column is wide. - assert_eq!(clip_middle("eng.srt", 400.), "eng.srt"); - assert_eq!(clip_middle(a, 4000.), a); - // Nothing panics at a width no column ever has, and something of both - // ends is still there. - assert_eq!(clip_middle(a, 0.).chars().count(), 5); - assert!(clip_middle(a, 0.).ends_with('1')); - // Counted in characters and not bytes: a name in another script is cut - // between its letters, not through one. - assert_eq!(clip_middle("ααααααααααααααα", 24.), "αα…αα"); - } - - /// The two doors subtitles arrive through, end to end on the fixtures: a - /// file beside the media and the tracks inside an mkv, what the overlay then - /// says at a given moment, and where the strip draws it. - #[test] - fn subtitles_arrive_beside_the_media_and_inside_it() { - // Which door a path goes through is decided before anything is opened. - // ...and a `.mks` is one, the subtitles of a Matroska file alone: it has - // no source in it to import, so the drop door has to send it where `+ S` - // sends it. Its two siblings are media and must not come here -- a - // `.mka` is a song this would stop importing. - for name in ["subs.srt", "SUBS.SRT", "a.vtt", "a.ass", "a.ssa", "s.mks", "S.MKS"] { - assert!(is_subtitle(Path::new(name)), "{name}"); - } - for name in ["a.mp4", "a.mkv", "song.mka", "film.mk3d", "notes.txt", "a"] { - assert!(!is_subtitle(Path::new(name)), "{name}"); - } - // Every container the engine can walk for tracks inside it, Matroska - // and ISO-BMFF alike -- an mp4 carries `tx3g`, so the app has to ask it. - // The Matroska half is the engine's own closed set, extension for - // extension, so no file is walked here that it would refuse there. - for name in [ - "film.MKV", "clip.webm", "clip.mp4", "a.m4v", "a.MOV", "song.mka", "s.mks", "f.MK3D", - ] { - assert!(carries_subtitles(Path::new(name)), "{name}"); - assert!( - engine::demux::is_matroska(Path::new(name)) - || matches!( - Path::new(name) - .extension() - .and_then(|e| e.to_str()) - .map(str::to_ascii_lowercase) - .as_deref(), - Some("mp4" | "m4v" | "mov") - ), - "{name} is walked by the app but not by the engine" - ); - } - for name in ["song.wav", "still.png", "notes.txt", "a"] { - assert!(!carries_subtitles(Path::new(name)), "{name}"); - } - // The three doors, on the one file that used to split them: what the - // drop/argv door does with it ([`Player::take_import`] routes on - // `is_subtitle`), what the worker reads for it ([`walk_subtitles`]), and - // what `+ S` reads ([`Player::add_subtitles`] -> `parse_subtitles`) are - // the same walk of the same bytes. - let mks = asset("test_subs.mks"); - assert!(is_subtitle(&mks), "the drop door takes it as subtitles"); - let dropped = walk_subtitles(&mks).expect("the drop door's worker reads it"); - let plus_s = PlaybackSession::parse_subtitles(&mks).expect("`+ S` reads it"); - assert!(!dropped.is_empty(), "and there are tracks in it"); - assert_eq!( - dropped.iter().map(|t| &t.label).collect::>(), - plus_s.iter().map(|t| &t.label).collect::>(), - ); - - let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); - session.set_gain(0.0); - // Beside the media: the drop door's own call, and the row it makes. - let srt = Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../engine/tests/data/test_subs.srt") - .canonicalize() - .expect("the subtitle fixture"); - assert_eq!(session.import_subtitles(&srt).expect("the .srt imports"), 1); - let track = &session.subtitles()[0]; - assert_eq!(track.label, "test_subs.srt"); - assert_eq!(subtitle_detail(track), "3 cues"); - // What the overlay draws at a moment inside the first cue, and between - // two of them -- the fixture's own timings (0.5-1.5 s, 2.0-3.25 s). - let text = |t: f64| -> Vec { - cues_at(&track.cues, t) - .into_iter() - .map(|c| c.text.clone()) - .collect() - }; - assert_eq!(text(0.7), ["first line"]); - assert!(text(1.8).is_empty(), "between two cues the plate goes"); - assert_eq!(text(2.5), ["second line\nwith a break"]); - // Where the strip puts that first cue: 0.5 s in at 40 px to the second - // is 20 px along, and a second of cue is 40 px wide. - let scale = Scale::default(); - assert_eq!(scale.pps, PPS_DEFAULT); - assert_eq!(cue_box(scale, &track.cues[0]), (20., 40.)); - // Zoomed right out, a cue worth a fraction of a pixel is still a mark. - let far = Scale { - pps: 0.01, - start: 0., - }; - assert_eq!(cue_box(far, &track.cues[0]).1, SUB_CUE_MIN_W); - // ...and scrolled past, its left edge is negative, exactly as a clip - // box's is: the bed clips it. - let scrolled = Scale { - pps: PPS_DEFAULT, - start: 1., - }; - assert_eq!(cue_box(scrolled, &track.cues[0]).0, -20.); - - // Inside the media: the tracks of an mkv, taken by the same call every - // open and import door makes. Two of them in the fixture, named by what - // the file says rather than by number. - let notice = - subtitle_notice(&mut session, &asset("test_subs.mkv")).expect("the mkv carries two"); - assert!(notice.contains('2'), "{notice}"); - assert_eq!(session.subtitles().len(), 3); - assert_eq!(session.subtitles()[1].label, "eng"); - assert_eq!(session.subtitles()[2].label, "fra — Signs"); - assert_eq!(subtitle_detail(&session.subtitles()[1]), "3 cues"); - // The same file twice adds nothing and says nothing. - assert_eq!(subtitle_notice(&mut session, &asset("test_subs.mkv")), None); - // An mp4 is walked too (it can carry `tx3g`); this one holds none, so - // the notice grows no tail. - assert_eq!(subtitle_notice(&mut session, &asset("test_av.mp4")), None); - - // A track that could not be read says why, where its cue count would - // be: what the greyed library row prints, and the whole difference - // between "this film has no subtitles" and "these four are pictures". - let refused = engine::subtitle::SubtitleTrack { - path: PathBuf::from("/a/remux.mkv"), - track: Some(1), - // Neither field, like `SubtitleTrack::refused` leaves them: what is - // refused is never written, and the row keeps the label it was - // refused under. - language: String::new(), - name: String::new(), - label: "eng".into(), - cues: Vec::new(), - bitmap: false, - refused: Some("S_HDMV/PGS subtitles are pictures, not text".into()), - }; - assert!(subtitle_detail(&refused).contains("pictures")); - assert!(cues_at(&refused.cues, 1.).is_empty()); - - // ...and what the plate and the strip draw after a *cut*: the timeline's - // own clock, asked of the engine through the very map an export writes - // the file with (`PlaybackSession::timeline_cues`), so the preview and - // the file cannot drift apart. The numbers are the export's own - // (`export::a_subtitle_file_beside_the_media_keeps_the_timelines_own_ - // clock`): 0.5s..2.5s rippled out of a five-second timeline leaves - // three seconds, which clips the second cue and takes the third away - // altogether -- while the track itself still holds all three, which is - // exactly why the drawing may not read them straight. - let lanes = session.lanes(); - session - .cut_regions(&[(15, 60)], &lanes) - .expect("cut 0.5s..2.5s out"); - assert_eq!(session.timeline_duration(), 3.0); - assert_eq!(session.subtitles()[0].cues.len(), 3, "the track is untouched"); - let mapped = session.timeline_cues(0); - assert_eq!( - mapped - .iter() - .map(|c| (c.start_us, c.end_us)) - .collect::>(), - vec![(500_000, 1_500_000), (2_000_000, 3_000_000)] - ); - // The overlay's own two lines, at the same moments as above. - let drawn = |t: f64| -> Vec { - cues_at(&mapped, t) - .into_iter() - .map(|c| c.text.clone()) - .collect() - }; - assert_eq!(drawn(0.7), ["first line"]); - assert_eq!(drawn(2.5), ["second line\nwith a break"]); - assert!( - drawn(4.2).is_empty(), - "a cue past the cut end is drawn where the file writes none" - ); - // ...and the strip's: the second cue is one second wide now, not 1.25. - assert_eq!(cue_box(scale, &mapped[1]), (80., 40.)); - } - - /// The edit toolbar against the 640x360 floor the whole editor is measured - /// at. It does not fit and cannot be made to -- so what it may never do is - /// *hide* the tail: the row scrolls, and the door to everything scrolled - /// off it is pinned outside the scrolling box. - #[test] - fn toolbar_fits_the_smallest_window() { - let toolbar = include_str!("ui/toolbar.rs"); - let row = &toolbar[toolbar.find("pub(crate) fn toolbar(").expect("the toolbar")..]; - // Every button in the row is a hit target, so none of them is narrower - // than `HIT_MIN`, and they sit in 8 px gaps inside the row's own 12 px - // padding. - let buttons = row.matches("action_control(").count(); - assert!(buttons >= 11, "the row's buttons moved; this scan is blind"); - // The row is shorter than it was -- the project's own settings (size, - // rate, HDR) are the inspector's now and the transport is the - // picture's -- so whether it fits at 640 px depends on the words in it - // and is not something this scan can measure. What it can hold to is - // the rule: "it scrolls" is not "it can be found", so the door to - // whatever is off the right edge is pinned outside the scrolling box - // and the card it opens carries every action there is - // (`every_action_is_on_the_actions_card`). - assert!( - row.contains("\"controls-more\""), - "nothing pinned beside the scrolling row: the tail is unreachable at 640 px" - ); - assert_eq!(row.matches("overflow_x_scroll").count(), 1); - assert!( - row.find("\"controls-more\"") > row.find("overflow_x_scroll"), - "the pinned door is inside the row it is meant to outlive" - ); - // ...and nothing in the row decides for itself whether it can act: the - // oracle does, once, for the key and the button alike. A raw `control(` - // in here is a button that can go dead while its stroke still fires -- - // the bug this redesign was called in for. - assert_eq!( - row.matches("\n .child(control(").count(), - 0, - "a toolbar button bypassing the availability oracle" - ); - } - - /// The whole reason `ui/theme.rs` exists: a colour written anywhere else is - /// a colour the next palette sweep will miss, which is exactly how 186 grey - /// calls survived every previous attempt at this. - #[test] - fn no_colour_is_written_outside_the_theme() { - let source = ui_source(); - let stray: Vec<&str> = source - .lines() - .filter(|l| l.contains("rgb(0x") || l.contains("rgba(0x")) - .collect(); - assert!(stray.is_empty(), "colour written outside the theme: {stray:?}"); - } - - /// "It scrolls" is not "it can be found": at the 640x360 floor the timeline - /// takes its share and no more, so a third track is behind a scroll -- and - /// the line that says so has to keep telling the truth *while* the column is - /// being scrolled, or it is an instruction nobody can carry out. - #[test] - fn the_line_about_what_is_below_the_fold_counts_what_is_still_below_it() { - // The timeline is a region and not the window: its chrome and one whole - // lane fit the share it may take at the floor. - let floor = 360. * TIMELINE_SHARE; - assert!( - TIMELINE_FIXED_H + LANE_H <= floor, - "{TIMELINE_FIXED_H} px of chrome and a lane will not fit {floor} px" - ); - // What is left over is measured in whole lanes, at least one. - assert_eq!(lanes_shown(LANE_H), 1); - assert_eq!(lanes_shown(LANE_H - 10.), 1); - assert_eq!(lanes_shown(2. * LANE_H + 8.), 2); - - // Four tracks in a two-lane box: two are below, and each row scrolled - // past takes one off that count until none is left. This is the bug the - // graft fixes -- the count used to be `total - shown` forever, so the - // line still said "2 more below" with the last track on screen. - let box_h = 2. * LANE_H + 8.; - assert_eq!(rows_below(4, box_h, 0.), 2); - assert_eq!(rows_below(4, box_h, LANE_H + 8.), 1); - assert_eq!(rows_below(4, box_h, 2. * (LANE_H + 8.)), 0); - // Past the end (gpui clamps, but the arithmetic must not wrap). - assert_eq!(rows_below(4, box_h, 900.), 0); - // A project that fits says nothing at all. - assert_eq!(rows_below(2, box_h, 0.), 0); - - // The inspector's rows are not one height, so its own line is measured - // in pixels off the scroll instead: gpui keeps the offset negative going - // down, and at the bottom the two cancel out exactly. - assert_eq!(px_below(120., 0.), 120.); - assert_eq!(px_below(120., -40.), 80.); - assert_eq!(px_below(120., -120.), 0.); - assert_eq!(px_below(0., 0.), 0.); - } - - /// The failure a user never learns about is the one that was answered by - /// another failure: two imports failing back to back are two messages, in - /// the order they happened, and the second does not overwrite the first - /// before a frame has drawn it. - #[test] - fn a_second_message_queues_behind_the_first_instead_of_erasing_it() { - let mut q = std::collections::VecDeque::new(); - push_notice(&mut q, "NOTHING ADDED — no video stream".into()); - push_notice(&mut q, "NOTHING ADDED — the file is not there".into()); - assert_eq!(q.len(), 2); - assert_eq!(q.front().map(|n: &gpui::SharedString| n.as_ref()), Some("NOTHING ADDED — no video stream")); - - // A held key that refuses says its one sentence once: the count on the - // bar is a count of messages, not of how long the key was held. - push_notice(&mut q, "NOTHING ADDED — the file is not there".into()); - assert_eq!(q.len(), 2); - - // ...and the ceiling drops the oldest rather than the newest: the thing - // that just happened is the thing worth reading. - for i in 0..NOTICES_MAX + 3 { - push_notice(&mut q, format!("SCAN FAILED: {i}").into()); - } - assert_eq!(q.len(), NOTICES_MAX); - assert_eq!(q.back().map(|n: &gpui::SharedString| n.as_ref()), Some("SCAN FAILED: 10")); - - // Answering the bar brings the next one up, oldest first. - let front = q.pop_front(); - assert_ne!(front, q.front().cloned()); - } - - /// The bar colours itself off the words the message already opens with, so - /// the tone cannot disagree with the sentence it labels. - #[test] - fn a_message_wears_the_colour_its_own_words_say() { - assert_eq!(notice_tone("SCAN FAILED: no audio"), STATUS_ERROR()); - assert_eq!(notice_tone(&format!("{EXPORT_DONE}out.mp4")), STATUS_SUCCESS()); - assert_eq!(notice_tone("NOTHING DETACHED — not grouped"), STATUS_WARNING()); - assert_eq!(notice_tone("SNAP ON"), ACCENT_PRIMARY()); - } - - /// The cards are sections of the inspector, not sheets over the timeline: - /// adjusting a clip must never hide the clip. Structural, because that is - /// where the rule lives -- a card rendered from the root again would be an - /// overlay again, whatever it looked like on the day it was written. - #[test] - fn an_inspector_section_occludes_no_timeline() { - let inspector = include_str!("ui/inspector.rs"); - let root = include_str!("main.rs").split("#[cfg(test)]").next().unwrap(); - let render = &root[root.find("impl Render for Player").expect("the root render")..]; - for card in [ - "eq_card", "color_card", "speed_card", "silence_card", "mix_card", - ] { - assert!( - inspector.contains(&format!("self.{card}(")), - "{card} is not a section of the inspector" - ); - assert!( - !render.contains(&format!("self.{card}(")), - "{card} is drawn from the root again -- it is an overlay over the timeline" - ); - } - // The docked cards are placed against the inspector's own box, which is - // what turns `scrim()` (`absolute().inset_0()`) from a window-wide sheet - // into this column. - assert!( - inspector.contains(".relative()"), - "the inspector is not a positioning context: its cards would cover the window" - ); - } - - /// MUST 1, on the two named offenders: the button that relabels itself - /// mid-export and the one that used to read "Muted 80%". Both live in a - /// rect that is reserved once, so the words change and the box does not. - #[test] - fn a_stateful_button_keeps_its_rect() { - use crate::ui::toolbar::{EXPORT_SLOT_W, SNAP_SLOT_W, VOLUME_SLOT_W}; - // Widest word each slot can hold, at the 12 px text this window is set - // in -- ~7 px a character plus the 16 px of padding. - let fits = |slot: f32, word: &str| slot >= word.chars().count() as f32 * 7. + 16.; - for word in ["Export", "Cancel"] { - assert!(fits(EXPORT_SLOT_W, word), "{word} overflows its rect"); - } - for word in ["Snap on", "Snap off", "No subs", "Subs off"] { - assert!(fits(SNAP_SLOT_W, word), "{word} overflows its rect"); - } - for word in ["100%", "× 100%"] { - assert!(fits(VOLUME_SLOT_W, word), "{word} overflows its rect"); - } - // And the rect is passed, not hoped for: every stateful control in the - // three chrome rows names its width. - let toolbar = include_str!("ui/toolbar.rs"); - for (id, slot) in [ - ("\"export\"", "EXPORT_SLOT_W"), - ("\"snap\"", "SNAP_SLOT_W"), - ("\"subs\"", "SNAP_SLOT_W"), - ("\"volume\"", "VOLUME_SLOT_W"), - ("\"zoom-fit\"", "ZOOM_SLOT_W"), - ] { - let at = toolbar.find(id).unwrap_or_else(|| panic!("no {id} button")); - assert!( - toolbar[at..at + 120].contains(slot), - "{id} does not reserve {slot}" - ); - } - } - - #[test] - fn nothing_clickable_is_smaller_than_the_wcag_minimum() { - // Every hit target in the panel, including the scrub strip -- whose bar - // is 6 px to look at and whose click area must not be. - assert!(CONTROL_H >= HIT_MIN); - assert!(RULER_HIT_H >= HIT_MIN); - assert!(LANE_H >= HIT_MIN); - // A clip box is a hit target too, and its two trim strips occlude it: - // on a box narrower than the pair there is no body left to press, so - // the clip cannot be selected, dragged or menued at all -- which is - // every clip a jumpcut leaves at a normal zoom. Below three handles - // there are no strips. - assert!(!trims(0.)); - assert!(!trims(EDGE_W)); - assert!(!trims(2. * EDGE_W), "a box that is all handle and no clip"); - assert!(!trims(3. * EDGE_W - 0.1)); - // And where they are drawn, what is left between them is a hit target - // in its own right -- a whole handle's width of clip. - for width in [3. * EDGE_W, 24., 100., 4000.] { - assert!(trims(width)); - assert!( - width - 2. * EDGE_W >= EDGE_W, - "{width} px of box leaves no middle" - ); - } - } - - /// WCAG 2.1 relative luminance of a packed `0xRRGGBB`. - fn luminance(colour: u32) -> f64 { - let channel = |shift: u32| { - let s = f64::from((colour >> shift) & 0xff) / 255.; - if s <= 0.03928 { - s / 12.92 - } else { - ((s + 0.055) / 1.055).powf(2.4) - } - }; - 0.2126 * channel(16) + 0.7152 * channel(8) + 0.0722 * channel(0) - } - - /// WCAG 2.1 contrast ratio, 1..=21. - fn contrast(a: u32, b: u32) -> f64 { - let (a, b) = (luminance(a), luminance(b)); - (a.max(b) + 0.05) / (a.min(b) + 0.05) - } - - #[test] - fn a_lane_row_is_a_fixed_header_and_a_bed_that_can_be_hit() { - // The header column is what the ruler is offset by as well, so both - // numbers are shared rather than repeated per row (A-MUST1/A-MUST2). - assert!(HEADER_W > 0. && HEADER_GAP >= 0.); - // Two lanes, a ruler, a button row and the timecode line, inside the - // panel the window is sized for. - assert!( - CONTROL_H + RULER_HIT_H + 2. * LANE_H + 17. + 4. * 8. + 16. <= PANEL_H, - "the second lane does not fit the panel" - ); - // Headers and clip boxes are as tall as the lane, and the lane is a - // click target (WCAG 2.5.8). - assert!(LANE_H >= HIT_MIN); - // A label row that ate the whole lane would leave no waveform. - assert!(LABEL_H < LANE_H / 2.); - // An added track adds its own row to the panel, and the two a project - // starts with leave it exactly the height it has always been. - assert_eq!(panel_h(2), PANEL_H); - assert_eq!(panel_h(1), PANEL_H); - assert_eq!(panel_h(3), PANEL_H + LANE_H + 8.); - assert_eq!( - panel_h(LANES_MAX), - PANEL_H + lanes_h(LANES_MAX) - lanes_h(2) - ); - // Past the cap the column scrolls instead: the panel stops growing, so - // no number of tracks can push the picture off the window. - assert_eq!(panel_h(LANES_MAX + 1), panel_h(LANES_MAX)); - assert_eq!(panel_h(50), panel_h(LANES_MAX)); - assert_eq!(lanes_h(0), 0.); - assert_eq!(lanes_h(1), LANE_H); - assert_eq!(lanes_h(2), 2. * LANE_H + 8.); - } - - #[test] - fn a_click_marks_the_whole_group_and_nothing_else() { - let (v, a) = ((Lane::V1, 0), (Lane::A1, 0)); - // Clicking the video half of group 1 marks the audio half with it. - assert!(marked(v, Some(1), Some(v), Some(1))); - assert!(marked(a, Some(1), Some(v), Some(1))); - // Another group's clips stay unmarked, in either lane. - assert!(!marked((Lane::V1, 1), Some(2), Some(v), Some(1))); - assert!(!marked((Lane::A1, 1), Some(2), Some(v), Some(1))); - // A half a lift left behind has no group: it marks itself only, which - // is what makes it separately deletable. Two ungrouped clips must not - // mark each other by both being ungrouped. - assert!(marked(a, None, Some(a), None)); - assert!(!marked(v, None, Some(a), None)); - // Nothing selected marks nothing. - assert!(!marked(v, Some(1), None, None)); - } - - #[test] - fn a_name_is_dropped_rather_than_smeared_across_a_thin_clip() { - assert!(show_label(LABEL_MIN_W)); - assert!(show_label(400.)); - assert!(!show_label(LABEL_MIN_W - 0.1)); - // The label test is the box's own width in pixels now, which is what - // the scale hands it -- no bed width, and so nothing to be zero. - let scale = Scale::default(); - assert!(show_label(scale.width_px(LABEL_MIN_W as f64 / PPS_DEFAULT))); - assert!(!show_label(scale.width_px(0.))); - } - - #[test] - fn an_envelope_stays_inside_the_box_it_is_drawn_in() { - // A ramp: silence at the start, full scale at the end. - let peaks: Vec<(f32, f32)> = (0..40) - .map(|i| (-(i as f32) / 39., i as f32 / 39.)) - .collect(); - let (w, h) = (100., 30.); - let cols = envelope(&peaks, 0., 1., w, h); - assert_eq!(cols.len(), (w / WAVE_COL) as usize + 1); - for &(x, top, bottom) in &cols { - assert!((0. ..=w).contains(&x), "x {x} outside 0..{w}"); - assert!((0. ..=h).contains(&top), "top {top} outside 0..{h}"); - assert!( - (0. ..=h).contains(&bottom), - "bottom {bottom} outside 0..{h}" - ); - // Never inverted, and never a polygon with no area: silence has to - // read as a line rather than as nothing at all. - assert!( - bottom - top >= 1., - "column {top}..{bottom} is thinner than a pixel" - ); - } - // The ramp is drawn as a ramp: the last column is taller than the first. - let height = |&(_, top, bottom): &(f32, f32, f32)| bottom - top; - assert!(height(cols.last().unwrap()) > height(cols.first().unwrap()) + 5.); - // Degenerate inputs draw nothing rather than panicking. - assert!(envelope(&[], 0., 1., w, h).is_empty()); - assert!(envelope(&peaks, 0., 1., 0., h).is_empty()); - // A clip whose range runs past the peaks clamps to the last bucket. - assert!(!envelope(&peaks, 0., 99., w, h).is_empty()); - } - - /// A box laid out wider than any screen -- a long clip at a deep zoom -- is - /// still one screen's worth of columns: the path a repaint has to build is - /// bounded by what can be seen, not by what the layout says the box is. - /// Unbounded, a 5 s clip zoomed to the frame is a path of millions of points - /// per frame, and the repaint that stalls on it is the waveform that - /// "disappeared". - #[test] - fn an_envelope_never_costs_more_points_than_a_screen_can_show() { - let peaks: Vec<(f32, f32)> = (0..200).map(|i| (-(i as f32) / 199., 1.)).collect(); - // The width a 5 s clip is laid out at when the bed shows 8 frames of it. - let huge = 5. * 30. / 8. * 1200.; - let cols = envelope(&peaks, 0., 5., huge, 30.); - assert!( - cols.len() <= WAVE_COLS_MAX + 1, - "{} columns for a {huge} px box", - cols.len() - ); - // ...and the slice actually painted is the part of the box on the bed, - // which is where that width stops mattering: a column per two visible - // pixels, at every zoom. - let (x, w) = visible_slice(-huge / 2., huge, 1200.); - assert_eq!((x, w), (huge / 2., 1200.)); - assert_eq!(envelope(&peaks, 0., 5., w, 30.).len(), 601); - // A box entirely off the bed has no slice, and one that has never been - // measured is drawn whole -- what was drawn before there was a bed. - assert_eq!(visible_slice(2000., 500., 1200.), (0., 0.)); - assert_eq!(visible_slice(-3000., 500., 1200.), (500., 0.)); - assert_eq!(visible_slice(-40., 500., 0.), (0., 500.)); - // Half on, at either edge. - assert_eq!(visible_slice(-100., 500., 1200.), (100., 400.)); - assert_eq!(visible_slice(1000., 500., 1200.), (0., 200.)); - } - - /// The box a trim draws is the box its release commits, at every speed. The - /// preview used to hand the *timeline* frame count to a source-frame field: - /// at 2x a tail moved twice as fast as the pointer and snapped back on - /// release, and a head drag moved the clip's other edge. - #[test] - fn a_trim_preview_lands_where_the_release_commits() { - let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); - session.set_gain(0.0); - for permille in SPEED_PRESETS { - // Live, so the loop owes it no undo step: the speeds are the axis - // this walks, and the trims below are what is undone. - session - .set_speed_live(Lane::V1, 0, Speed::from_permille(permille)) - .expect("a clip alone on its lane may be speeded"); - for edge in [Edge::Start, Edge::End] { - let clip = session.lane_clips(Lane::V1)[0]; - let (lo, hi) = session - .trim_room(Lane::V1, 0, edge) - .expect("clip 0 is there"); - // Both walls and the middle of the room: the whole range a - // pointer can be clamped to. - for to in [lo, (lo + hi) / 2, hi] { - let preview = trimmed_clip(clip, edge, to, false); - // The drag is one edit and one undo step, so the next `to` - // is measured from the same clip this one was. - if session.trim_clip(Lane::V1, 0, edge, to) { - assert_eq!( - preview, - session.lane_clips(Lane::V1)[0], - "{edge:?} to {to} at {permille} per mille" - ); - assert!(session.undo(), "the trim is one undo step"); - } else { - // An edge already where it was asked to go is not an - // edit, and the preview draws the clip unchanged. - assert_eq!(preview, clip, "{edge:?} to {to} at {permille} per mille"); - } - assert_eq!(session.lane_clips(Lane::V1)[0], clip, "back where it was"); - } - } - } - } - - /// A still trims the same way, and the preview knows it: its head grows - /// forward from source frame 0 -- every frame of it is the same picture -- - /// so the box stretches instead of sliding left. - #[test] - fn a_stills_trim_preview_grows_forward_like_the_commit() { - let mut session = PlaybackSession::open(asset("test_still.png")).expect("a picture opens"); - for edge in [Edge::Start, Edge::End] { - let clip = session.lane_clips(Lane::V1)[0]; - let (lo, hi) = session - .trim_room(Lane::V1, 0, edge) - .expect("clip 0 is there"); - for to in [lo, (lo + hi) / 2, hi] { - let preview = trimmed_clip(clip, edge, to, true); - match session.trim_clip(Lane::V1, 0, edge, to) { - true => { - assert_eq!( - preview, - session.lane_clips(Lane::V1)[0], - "a still {edge:?} to {to}" - ); - assert!(session.undo(), "the trim is one undo step"); - } - false => assert_eq!(preview, clip, "a still {edge:?} to {to}"), - } - assert_eq!(session.lane_clips(Lane::V1)[0], clip, "back where it was"); - } - } - } - - /// gpui freezes a drag's payload for the whole gesture, and nothing stops a - /// stroke from editing the lane under it: the drop has to find the clip that - /// was picked up, not whatever slid into its index. - #[test] - fn a_drop_moves_the_clip_that_was_picked_up_not_its_old_index() { - let at = |start: u32| Clip { - start, - in_frame: 0, - out_frame: 30, - source: 0, - link: None, - eq: None, - color: None, - fit: FitPolicy::Fit, - speed: Speed::NORMAL, - }; - let lane = [at(0), at(30), at(60)]; - let dragged = lane[2]; - assert_eq!(live_idx(&lane, 2, dragged), Some(2), "nothing moved"); - // A delete in front of it: the clip is now index 1, and the index the - // drag froze names a clip nobody grabbed. - let after = [at(0), at(60)]; - assert_eq!(live_idx(&after, 2, dragged), Some(1)); - assert_eq!(live_idx(&after, 1, dragged), Some(1)); - // Deleted mid-drag: there is nothing to move, and moving its neighbour - // instead is exactly the bug this exists for. - assert_eq!(live_idx(&[at(0)], 2, dragged), None); - assert_eq!(live_idx(&[], 0, dragged), None); - } - - #[test] - fn a_quiet_source_still_draws_as_a_shape() { - // An eighth of full scale, which is about where the fixtures sit. - let quiet: Vec<(f32, f32)> = vec![(-0.125, 0.125), (-0.0625, 0.0625)]; - let loud = normalise(quiet.clone()); - assert_eq!(loud[0], (-1., 1.)); - assert_eq!(loud[1], (-0.5, 0.5)); - // Digital silence has no loudest sample to scale to; it must not divide - // by zero and must stay flat. - assert_eq!(normalise(vec![(0., 0.)]), vec![(0., 0.)]); - assert!(normalise(Vec::new()).is_empty()); - } - - /// The whole waveform path, from the file on disk to the columns that get - /// painted: what no screenshot can assert about the shape. - #[test] - fn the_fixtures_waveform_reaches_the_lane_as_a_shape() { - let asset = |name: &str| { - std::path::Path::new(env!("CARGO_MANIFEST_DIR")) - .join("../../assets") - .join(name) - }; - let peaks = normalise( - engine::waveform::peaks(asset("test_av.mp4"), 0, WAVE_BPS) - .expect("open the fixture") - .expect("test_av.mp4 has audio"), - ); - // 5 s of source at the rate the lane asks for. - assert!(peaks.len().abs_diff(5 * WAVE_BPS as usize) <= WAVE_BPS as usize); - let cols = envelope(&peaks, 0., 5., 600., 30.); - let height = |&(_, top, bottom): &(f32, f32, f32)| bottom - top; - let tallest = cols.iter().map(height).fold(0., f32::max); - let flattest = cols.iter().map(height).fold(f32::MAX, f32::min); - // The fixture's 1 Hz pulse: a full-scale peak and a near-silent dip in - // every second, so the drawn envelope is a shape and not a bar. - assert!(tallest > 25., "loudest column only {tallest} px of 30"); - assert!( - flattest < 8., - "quietest column {flattest} px -- no dips drawn" - ); - // A video-only source draws no waveform at all rather than a flat fake. - assert!( - engine::waveform::peaks(asset("test_baseline.mp4"), 0, WAVE_BPS) - .expect("open the fixture") - .is_none() - ); - } - - #[test] - fn every_mark_on_a_clip_is_legible_on_it() { - // The body a name and a waveform are drawn on is the clip's kind - // ([`clip_kind`]); the source tint is the border and the library - // swatch, and is measured for telling itself apart rather than for - // carrying text. - // Every palette a person can pick, not merely the one in force. - for id in crate::ui::theme::PaletteId::ALL { - let p = id.palette(); - for (i, tint) in [p.CLIP_VIDEO, p.CLIP_AUDIO, p.CLIP_IMAGE, p.CLIP_TEXT] - .iter() - .enumerate() - { - // WCAG 1.4.3: the clip's name is body text on its tint. - assert!( - contrast(p.FG_PRIMARY, *tint) >= 4.5, - "{id:?} source {i}: label contrast {:.2}", - contrast(p.FG_PRIMARY, *tint) - ); - // WCAG 1.4.11: the waveform is a non-text graphic on it. - assert!( - contrast(p.FG_SECONDARY, *tint) >= 3., - "{id:?} source {i}: waveform contrast {:.2}", - contrast(p.FG_SECONDARY, *tint) - ); - } - // A selected clip's bed is the same two marks on a different colour. - assert!(contrast(p.FG_PRIMARY, p.BG_SELECTED) >= 4.5, "{id:?}"); - assert!(contrast(p.FG_SECONDARY, p.BG_SELECTED) >= 3., "{id:?}"); - // The bed a gap shows through has to read as a hole in the lane -- - // the clip is the object, the bed is the hole -- and the playhead - // has to be findable on both. - assert!(contrast(p.CLIP_VIDEO, p.BG_TIMELINE) >= 1.5, "{id:?}"); - assert!(contrast(p.ACCENT_PLAYHEAD, p.BG_TIMELINE) >= 3., "{id:?}"); - assert!(contrast(p.ACCENT_PLAYHEAD, p.CLIP_VIDEO) >= 3., "{id:?}"); - } - // The sanity check on the ratio itself: black on white is 21:1. - assert!((contrast(0xffffff, 0x000000) - 21.).abs() < 0.01); - } - - #[test] - fn source_tints_differ_per_source_and_cycle() { - // The bug: the first entry *was* `BG_RAISED`, so the first file imported - // -- the one every session has -- wore the panel's own background and - // had no visible swatch at all. - assert_ne!(source_tint(0), BG_RAISED()); - // ...in every family, since the swatch is drawn on whichever panel is - // in force (`ui::theme`) and a tint that vanished into one of them is a - // file with no colour at all. - for id in crate::ui::theme::PaletteId::ALL { - let p = id.palette(); - for (i, &tint) in p.SOURCE_TINTS.iter().enumerate() { - assert_ne!(tint, p.BG_RAISED, "{id:?} tint {i} is the panel"); - } - } - // Neighbouring sources must not share one, or an import is invisible. - assert_ne!(source_tint(0), source_tint(1)); - assert_ne!(source_tint(1), source_tint(2)); - assert_ne!(source_tint(2), source_tint(3)); - // Past the palette it wraps -- never an index panic. - assert_eq!(source_tint(4), source_tint(0)); - assert_eq!(source_tint(9), source_tint(1)); - assert_eq!(source_tint(usize::MAX), SOURCE_TINTS()[usize::MAX % 4]); - } - - /// Not "they are different numbers" -- different *enough to see*, against - /// each other and against the surface a swatch is drawn on. The palette is - /// deliberately dark and low-saturation, so the margin is thin and a new - /// tint picked by eye can land inside it without anyone noticing. - #[test] - fn source_tints_are_all_discernible() { - // Summed channel distance: `BG_RAISED` to the warm tint is 18, and that - // step is the one already accepted as readable on a lane. - let apart = |a: u32, b: u32| { - (0..3) - .map(|i| { - let shift = i * 8; - ((a >> shift) & 0xff).abs_diff((b >> shift) & 0xff) - }) - .sum::() - }; - // Every family, not the one in force: a palette is picked at runtime - // now, and four tints tuned by eye on one ground are exactly where a - // pair lands inside the margin on another. - for id in crate::ui::theme::PaletteId::ALL { - let p = id.palette(); - for (i, &tint) in p.SOURCE_TINTS.iter().enumerate() { - assert!( - apart(tint, p.BG_RAISED) >= 16, - "{id:?} tint {i} is {} from the panel it sits on", - apart(tint, p.BG_RAISED) - ); - for (j, &other) in p.SOURCE_TINTS.iter().enumerate().skip(i + 1) { - assert!( - apart(tint, other) >= 16, - "{id:?} tints {i} and {j} are only {} apart", - apart(tint, other) - ); - } - } - // The two a person sees side by side first must be further apart - // than the floor: source 0 and source 1 are the first import and - // the second. - assert!(apart(p.SOURCE_TINTS[0], p.SOURCE_TINTS[1]) >= 32, "{id:?}"); - } - } - - /// A `.srt` dropped on the window is nobody's stream: it has no source - /// entry, and the lookup that used to fall back to index 0 painted it with - /// the first file's colour -- a swatch saying it came out of a film it - /// never touched. - #[test] - fn a_standalone_subtitle_wears_no_file_tint() { - let sources = [ - Source { - path: PathBuf::from("/films/a.mkv"), - audio_stream: 0, - }, - Source { - path: PathBuf::from("/films/b.mp4"), - audio_stream: 0, - }, - // A second stream of the first file is a second source and the - // same colour. - Source { - path: PathBuf::from("/films/a.mkv"), - audio_stream: 1, - }, - ]; - assert_eq!( - file_tint(&sources, Path::new("/films/a.mkv")), - Some(source_tint(0)) - ); - assert_eq!( - file_tint(&sources, Path::new("/films/b.mp4")), - Some(source_tint(1)) - ); - assert_eq!(file_tint(&sources, Path::new("/subs/a.eng.srt")), None); - assert_eq!(file_tint(&[], Path::new("/films/a.mkv")), None); - // The same file under two spellings is one file and one colour: a - // source is stored symlink-resolved, everything else as it was typed. - let here = std::fs::canonicalize(".").expect("the crate directory"); - let sources = [Source { - path: here.join("Cargo.toml"), - audio_stream: 0, - }]; - assert_eq!( - file_tint(&sources, Path::new("Cargo.toml")), - Some(source_tint(0)), - "a relative spelling of the source file wears the source's colour" - ); - } - - /// The two shapes the engine really builds: a track *of* a file states a - /// language and no title (`of_matroska`, `of_mp4`), and a standalone file - /// states no language and is its own name (`external`). - fn sub(path: &str, track: Option, label: &str) -> engine::subtitle::SubtitleTrack { - let (language, name) = match track { - Some(_) => (label.to_string(), String::new()), - None => (String::new(), label.to_string()), - }; - engine::subtitle::SubtitleTrack { - path: PathBuf::from(path), - track, - language, - name, - label: label.to_string(), - cues: Vec::new(), - bitmap: false, - refused: None, - } - } - - /// A film's two ASS tracks with the timeline trimmed to twenty seconds: - /// one of them still has cues there and one has none, and the card said - /// nothing whatever about the second while the Subtitles list went on - /// showing it with its eighty-three cues. - /// - /// And the 25 GB remux's thirty-five: naming those wrapped the row to ten - /// lines and pushed Destination under the fold, so past the value box's - /// three lines the same line counts instead. - #[test] - fn the_card_names_the_subtitle_it_leaves_off_and_counts_them_when_it_cannot() { - let film = "/films/An Episode 01.mkv"; - let two = [ - sub(film, Some(1), "[ASS]"), - sub(film, Some(2), "[ASS] [FOR DUB]"), - ]; - // What the engine answers about the one pick that reached it, and what - // this side knows about the row that did not. - let named = subtitle_plan("[ASS] → embedded".to_string(), &two, &[0]); - assert_eq!(named, "[ASS] → embedded; [ASS] [FOR DUB] — no cues here"); - assert!( - named.chars().count() <= SUB_PLAN_CHARS, - "two tracks fit the value box: {named}" - ); - // Thirty-five off one file: twenty-two carry cues here, nine are - // pictures, one could not be read, three have nothing on this timeline. - let many: Vec<_> = (0..35) - .map(|i| { - let mut track = sub("/films/A Remux.mkv", Some(i), "eng — Subtitles"); - track.bitmap = (22..31).contains(&i); - track.refused = (i == 31).then(|| "VobSub is pictures".to_string()); - track - }) - .collect(); - // The picks are every track with a cue on the timeline: the twenty-two - // and the nine picture ones, which the engine drops itself. - let picks: Vec = (0..31usize).collect(); - let counted = subtitle_plan("22 tracks → embedded (…)".to_string(), &many, &picks); - assert_eq!(counted, "22 of 35 → embedded; 9 pictures; 1 unread; 3 no cues here"); - assert!( - counted.chars().count() <= SUB_PLAN_CHARS, - "thirty-five tracks still fit the value box: {counted}" - ); - // Nothing on the timeline at all is still the engine's word for it. - assert_eq!(subtitle_plan("none".to_string(), &[], &[]), "none"); - } - - /// The list is in the order tracks were added, which is not the order a - /// person reads it in: importing a second film puts its tracks after the - /// first film's, and importing a third `.srt` for the first film puts that - /// one last of all. The rows still read as three sources. - #[test] - fn subtitle_rows_group_a_source_however_they_were_added() { - let tracks = [ - sub("/films/a.mkv", Some(1), "eng"), - sub("/films/b.mkv", Some(1), "eng"), - sub("/films/a.mkv", Some(2), "fre"), - sub("/subs/late.srt", None, "late.srt"), - sub("/films/b.mkv", Some(3), "ger"), - ]; - let groups = subtitle_rows(&tracks); - assert_eq!( - groups.iter().map(|g| g.name.as_str()).collect::>(), - ["a", "b", "late"], - "one group per file, in the order the files first appear" - ); - assert_eq!( - groups - .iter() - .map(|g| g.rows.iter().map(|r| r.label.as_str()).collect::>()) - .collect::>(), - [vec!["eng", "fre"], vec!["eng", "ger"], vec!["late.srt"]], - "a file's tracks are contiguous and in add order" - ); - // Numbered within the file, the way `row_name` numbers audio streams: - // two tracks that both say "eng" are told apart by nothing else. - assert_eq!( - groups - .iter() - .map(|g| g.rows.iter().map(|r| r.number).collect::>()) - .collect::>(), - [vec![1, 2], vec![1, 2], vec![1]] - ); - // The swatch key is the file, so a group and that file's media rows - // wear one colour -- and the standalone one has none. - let sources = [Source { - path: PathBuf::from("/films/a.mkv"), - audio_stream: 0, - }]; - assert_eq!( - file_tint(&sources, &groups[0].path), - Some(source_tint(0)), - "the group carries the path the tint is asked by" - ); - assert_eq!(file_tint(&sources, &groups[2].path), None); - } - - /// What the strip header, the section heading and the toggle's notice all - /// say. Two films each carrying an "eng" track are one word apart until the - /// film is in the name; a film carrying two is one word apart from itself. - #[test] - fn the_picked_subtitle_is_named_with_the_film_it_came_out_of() { - let tracks = [ - sub("/films/a.mkv", Some(1), "eng"), - sub("/films/b.mkv", Some(1), "eng"), - sub("/films/a.mkv", Some(2), "eng"), - sub("/films/b.mkv", Some(2), "und"), - sub("/subs/late.srt", None, "late.srt"), - ]; - let name = |track| sub_pick_name(&tracks, track).expect("a track that is there"); - // The two "eng"s of two films: one file gave several so its tracks are - // numbered, the other gave one so it is not. - assert_eq!(name(0), "eng 1 — a"); - assert_eq!(name(2), "eng 2 — a"); - assert_eq!(name(1), "eng 1 — b"); - assert_ne!(name(0), name(1), "two films' eng tracks read apart"); - for picked in [name(0), name(1), name(2)] { - assert!(picked.contains(" — a") || picked.contains(" — b")); - } - // "und" is the tag for "nobody said", humanised once by - // `subtitle_rows` and not again here. - assert_eq!(name(3), "unknown language 2 — b"); - // A standalone `.srt` is its own file and its label already says so: - // one track, so no number, and no stem after it saying it again. - assert_eq!(name(4), "late.srt"); - // The silence `subtitle_track` gives at the same moment. - assert_eq!(sub_pick_name(&tracks, 5), None); - assert_eq!(sub_pick_name(&[], 0), None); - } - - /// The door this editor answers "don't make me import the film again" with, - /// and it is in the panel where the tracks it adds are listed: the Text - /// tab's own button reads a file's subtitle tracks onto the open timeline - /// -- a release's `.mkv`, an `.srt` beside it -- while the file itself - /// joins nothing. It is the *action* and not a second implementation of it, - /// so the button, the stroke and the actions card cannot drift apart, and - /// it is oracle-gated like every other action button, so with no timeline - /// open it dims and says why instead of opening a chooser for nothing. - #[test] - fn the_text_tab_carries_the_add_subtitles_door() { - let library = include_str!("ui/library.rs"); - let at = library - .find("\"add-subtitles\"") - .expect("no add-subtitles control in the library column"); - let block = &library[at..(at + 1400).min(library.len())]; - assert!( - block.contains("ActionId::AddSubtitleTrack"), - "the button is a door of its own rather than the action: {block}" - ); - assert!( - block.contains("pick_and_add_subtitles"), - "the button does not open the subtitle chooser: {block}" - ); - // `action_control` is the oracle-gated one: dimmed with the refusal in - // the oracle's own words. `control` alone would be lit with no timeline. - assert!( - library[..at].ends_with("self.action_control(\n "), - "the add-subtitles button is not oracle-gated" - ); - // ...and the empty tab names that button, rather than pointing at a - // toolbar the person is not looking at. - assert!( - crate::LibraryTab::Text.empty().contains("Add subtitles"), - "{}", - crate::LibraryTab::Text.empty() - ); - } - - /// The one thing regrouping must not break: `sub_track` is a flat index - /// into the add-order list, a click sets it and a save writes it into the - /// `.edith`. Every row must still name the track it was made from -- rows - /// for refused tracks included, because they take a number in that list - /// whether or not anyone can pick them. - #[test] - fn a_subtitle_row_names_the_flat_track_it_was_made_from() { - let mut tracks = vec![ - sub("/films/a.mkv", Some(1), "eng"), - sub("/films/b.mkv", Some(1), "eng"), - sub("/films/a.mkv", Some(2), "fre"), - ]; - // Track 1 of b is pictures: still a row, still index 1 of the list. - tracks[1].bitmap = true; - tracks[1].refused = Some("PGS subtitles are pictures".to_string()); - let groups = subtitle_rows(&tracks); - let flat: Vec<(usize, &str)> = groups - .iter() - .flat_map(|g| g.rows.iter().map(|r| (r.track, r.label.as_str()))) - .collect(); - assert_eq!(flat, [(0, "eng"), (2, "fre"), (1, "eng")]); - for (track, label) in flat { - assert_eq!( - tracks[track].label, label, - "row {track} picks the track it names" - ); - } - // (c) The refused one is here, saying why, and greyable by that alone. - let refused = &groups[1].rows[0]; - assert_eq!( - refused.refused.as_deref(), - Some("PGS subtitles are pictures") - ); - assert_eq!(refused.detail, "PGS subtitles are pictures"); - assert!(refused.bitmap); - // ...and it was counted: the row after it in add order is still 2. - assert_eq!(groups[0].rows[1].track, 2); - } - - /// The × on a row shifts every track after it down one, and the pick is - /// what an export writes into the file -- so a pick that stayed put would - /// silently change which track the next export carries. Every relation - /// between the pick and the row that went, on a list of three. - #[test] - fn removing_a_subtitle_row_carries_the_pick_with_it() { - // A row *before* the pick: the same track stays picked, one index down. - assert_eq!(sub_pick_after_removal(2, 0, 2), 1); - assert_eq!(sub_pick_after_removal(2, 1, 2), 1); - // A row *after* it: the pick has not moved and neither has its index. - assert_eq!(sub_pick_after_removal(0, 2, 2), 0); - assert_eq!(sub_pick_after_removal(1, 2, 2), 1); - // The picked row itself: the one that slid into its place... - assert_eq!(sub_pick_after_removal(1, 1, 2), 1); - // ...and the last row when the picked one was the last, since there is - // nothing after it to slide. - assert_eq!(sub_pick_after_removal(2, 2, 2), 1); - // The last row of all: an emptied list is legal for subtitles, and the - // section is not drawn at all at that point. - assert_eq!(sub_pick_after_removal(0, 0, 0), 0); - } - - /// The same claim from the click's end, on the order imports actually - /// arrive in: two films opened one after the other and an `.srt` dropped - /// last interleave in the flat list, and the display reorders them. What a - /// click sets is the row's own `track`, so the *n*th row on screen has to - /// pick the track it shows and the echoes have to name that same file. - #[test] - fn a_click_on_a_regrouped_row_picks_the_track_that_row_shows() { - let tracks = [ - sub("/films/a.mkv", Some(1), "eng"), - sub("/films/b.mkv", Some(1), "eng"), - sub("/films/a.mkv", Some(2), "fre"), - sub("/subs/late.srt", None, "late.srt"), - sub("/films/b.mkv", Some(3), "ger"), - ]; - let rows: Vec<_> = subtitle_rows(&tracks) - .into_iter() - .flat_map(|group| { - group - .rows - .into_iter() - .map(move |row| (group.path.clone(), row)) - }) - .collect(); - // Read top to bottom, the rows are no longer in add order... - assert_eq!( - rows.iter().map(|(_, row)| row.track).collect::>(), - [0, 2, 1, 4, 3] - ); - for (path, row) in &rows { - // ...and what the click writes into `sub_track` -- and a save into - // the `.edith` -- still lands on the track the row is showing. - let picked = &tracks[row.track]; - assert_eq!(&picked.path, path, "row {} picks another file", row.track); - assert_eq!(lang_human(&picked.label), row.label); - // And the heading, the strip and the notice name that same file - // back, so a click cannot leave the echoes pointing elsewhere. - let echo = sub_pick_name(&tracks, row.track).expect("the row's own track"); - let stem = path.file_stem().expect("a fixture path").to_string_lossy(); - assert!( - echo.contains(&*stem), - "picked {}, echoed {echo}", - path.display() - ); - } - } - - /// "und" is what a muxer writes when nobody said what the language is. A - /// row showing it verbatim names a language nobody speaks. - #[test] - fn an_untagged_language_says_it_is_unknown() { - assert_eq!(lang_human("und"), "unknown language"); - assert_eq!(lang_human("eng"), "eng"); - assert_eq!(lang_human("fre — Commentary"), "fre — Commentary"); - // Reaching the subtitle rows too: a track whose only name was the tag. - let groups = subtitle_rows(&[sub("/films/a.mkv", Some(1), "und")]); - assert_eq!(groups[0].rows[0].label, "unknown language"); - // The pair, read as the pair: the row title comes off `language` and - // `name` and never out of the flattened label, which is what let an - // "und" beside a title through as a language nobody speaks. A refused - // track states neither and keeps its label. - let titled = |language: &str, name: &str, label: &str| engine::subtitle::SubtitleTrack { - path: PathBuf::from("/films/a.mkv"), - track: Some(1), - language: language.into(), - name: name.into(), - label: label.into(), - cues: Vec::new(), - bitmap: false, - refused: None, - }; - for (language, name, label, title) in [ - ("fra", "Signs", "fra — Signs", "fra — Signs"), - ("und", "Signs", "Signs", "Signs"), - ("und", "", "und", "unknown language"), - ("", "late.srt", "late.srt", "late.srt"), - ("", "", "eng", "eng"), - ] { - let rows = subtitle_rows(&[titled(language, name, label)]); - assert_eq!(rows[0].rows[0].label, title, "{language:?} {name:?}"); - } - } - - /// The bug: an empty timeline is end-of-stream from its one black frame - /// onward, so the pump had `done` set before anything was ever pressed -- - /// and the transport's restart branch read that as "played out, start from - /// the top". It started a clock against a zero-length timeline, which was - /// `done` again by the next repaint, so every further press restarted it - /// too: the button read "Pause" and no press of it ever paused. - /// - /// What holds it now is one predicate, checked here against real sessions - /// on both sides -- the emptied one refuses, a timeline with clips on it - /// does not. - #[test] - fn an_empty_timeline_has_nothing_to_play() { - let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); - // Silent like the engine suite: this opens the real device. - session.set_gain(0.0); - // A timeline with clips on it plays, and always did: the guard must not - // touch that side. - assert!(!session.is_empty()); - assert!(!nothing_to_play(Some(&session))); - - // Every clip taken off, which is a state and not a failure. - while session.delete_clip(Lane::V1, 0) {} - while session.delete_clip(Lane::A1, 0) {} - assert!(session.is_empty(), "the timeline is empty"); - assert_eq!(session.timeline_duration(), 0.0); - - // What the pump does every render, and what set `done` before the fix: - // the black frame goes by and the session is at its end at once. - for _ in 0..40 { - while session.try_frame().is_some() {} - std::thread::sleep(Duration::from_millis(10)); - } - assert!( - session.is_eos(), - "an empty timeline is done before it starts" - ); - - // So the press is refused rather than sent down the restart branch -- - // and with no session at all it is the same refusal. - assert!(nothing_to_play(Some(&session))); - assert!(nothing_to_play(None)); - assert!(!session.is_playing(), "and nothing was started"); - } - - /// The slider writes the same numbers the keys do, and mute is not one of - /// them: dragging while muted picks the level unmuting comes back to. - #[test] - fn the_slider_lands_on_the_grid_the_keys_move_on() { - let mut volume = Volume::default(); - // Both ends exactly, and clamped past them. - volume.set_along(0.); - assert_eq!(volume.gain(), 0.0); - assert_eq!(volume.label(), "Vol 0%"); - volume.set_along(1.5); - assert_eq!(volume.gain(), 1.0); - assert_eq!(volume.along(), 1.0); - - // Halfway is 50%, and a key press from there is 5% -- the same step - // count as before, on a finer grid. - volume.set_along(0.5); - assert_eq!(volume.label(), "Vol 50%"); - volume.step(true); - assert_eq!(volume.label(), "Vol 55%"); - volume.step(false); - assert_eq!(volume.gain(), 0.5); - - // A number no step lands on comes back as the nearest one, so the label - // and the fill are the same value the device was handed. - volume.set_along(0.333); - assert_eq!(volume.label(), "Vol 33%"); - assert_eq!(volume.along(), 0.33); - - // Muted, the drag moves the level and nothing comes out. - volume.muted = true; - volume.set_along(0.8); - assert_eq!(volume.gain(), 0.0); - assert_eq!(volume.label(), "Muted 80%"); - volume.muted = false; - assert_eq!(volume.gain(), 0.8); - } - - /// The slider lands where it paints: the arithmetic `Player::drag_volume` - /// runs over the bar's own painted width, which is the one thing a test of - /// it can share without re-deriving it. - #[test] - fn the_volume_slider_lands_where_it_paints() { - let bar = Bounds { - origin: point(px(420.), px(508.)), - size: size(px(VOLUME_W), px(CONTROL_H)), - }; - let at = |x: f32| { - let mut volume = Volume::default(); - volume.set_along(frac_along(px(x), bar)); - volume - }; - assert_eq!(at(420.).gain(), 0.0, "the left end is silence"); - assert_eq!(at(420. + VOLUME_W).gain(), 1.0, "the right end is full"); - assert_eq!(at(-4000.).gain(), 0.0, "off the left clamps"); - assert_eq!(at(9999.).gain(), 1.0, "off the right clamps"); - // Every pixel along it: a level the keys could also reach, painted back - // where the hand pressed to within the half step the rounding costs. - for step in 0..=(VOLUME_W as u32) { - let along = step as f32 / VOLUME_W; - let volume = at(420. + along * VOLUME_W); - let painted = volume.along(); - let slack = 0.5 / f32::from(Volume::MAX_STEPS) + 1e-4; - assert!( - (painted - along).abs() <= slack, - "pressed at {along}, paints at {painted}" - ); - } - } -} +mod tests; fn main() { // A keymap file that cannot be read leaves the defaults in force, and takes diff --git a/crates/app/src/tests/cards.rs b/crates/app/src/tests/cards.rs new file mode 100644 index 0000000..ae76269 --- /dev/null +++ b/crates/app/src/tests/cards.rs @@ -0,0 +1,1353 @@ +//! The cards the window opens over itself: the keys, the equaliser, the +//! colour and speed bars, the silence scan, the choices and the export. + +use super::*; + +#[test] +fn escape_gets_out_of_an_export_whatever_is_held_with_it() { + use keymap::ActionId; + // The regression this guards: looking the stroke up in the keymap made + // ctrl+escape mean nothing, and an export that a modifier could trap + // the user inside of is worse than an unbound chord. + assert!(cancels_export("escape", None)); + assert!(cancels_export("escape", Some(ActionId::CancelExport))); + // A rebound cancel works as well -- it adds a way out, never replaces + // the one that always worked. + assert!(cancels_export("q", Some(ActionId::CancelExport))); + // Nothing else does, whatever it means outside an export. + assert!(!cancels_export("e", Some(ActionId::Export))); + assert!(!cancels_export("space", Some(ActionId::Play))); + assert!(!cancels_export("q", None)); +} + +#[test] +fn a_capture_waits_through_a_lone_modifier() { + // gpui delivers these on their own; taking one as a binding would make + // the action fire on the way to every chord that uses it. + for key in [ + "control", "shift", "alt", "super", "platform", "function", "fn", "meta", "command", + ] { + assert!(is_bare_modifier(key), "{key}"); + } + // Everything a binding is actually made of, escape included -- the + // capture branch turns that one away itself. + for key in ["c", "x", "space", "escape", "delete", "f1", "z"] { + assert!(!is_bare_modifier(key), "{key}"); + } +} + +/// The whole point of the card: there is no action a pointer cannot reach. +/// It renders [`keys_rows`] and nothing else, so this reads the same list +/// the card does -- add an `ActionId` and forget to surface it and this +/// fails, which is the only way that stays true as the editor grows. +#[test] +fn every_action_is_on_the_actions_card() { + use keymap::{ActionId, Category, Keymap}; + let rows = keys_rows(); + let listed: Vec = rows + .iter() + .filter_map(|r| match r { + KeyRow::Act(a) => Some(*a), + _ => None, + }) + .collect(); + for action in ActionId::ALL { + assert_eq!( + listed.iter().filter(|a| **a == action).count(), + 1, + "{action:?} is not on the card exactly once" + ); + } + assert_eq!(listed.len(), ActionId::ALL.len()); + // Under its own heading, in the registry's order: every row after a + // heading belongs to that heading until the next one. + let mut heading = None; + let mut heads = 0; + for row in &rows { + match row { + KeyRow::Head(category) => { + heading = Some(*category); + heads += 1; + } + KeyRow::Act(action) => assert_eq!(Some(action.category()), heading, "{action:?}"), + KeyRow::Fixed(i) => assert_eq!(Some(keymap::FIXED[*i].category), heading), + } + } + assert_eq!(heads, Category::ALL.len(), "a heading per category"); + // The card-local strokes are still all there beside them. + assert_eq!( + rows.iter() + .filter(|r| matches!(r, KeyRow::Fixed(_))) + .count(), + keymap::FIXED.len() + ); + // Both columns say something: the label does the action, the stroke + // beside it changes that stroke, and neither may read blank. + let keymap = Keymap::defaults(); + for action in ActionId::ALL { + assert!(!action.label().is_empty(), "{action:?}"); + assert_ne!(keymap.display(action), "unbound", "{action:?}"); + } + // The list scrolls inside a card the smallest window holds, so a + // thirty-fourth action costs no height at all. + assert!(rows.len() as f32 * KEYS_ROW_H > KEYS_ROWS_H, "no cap needed?"); + // Both halves of a row are click targets, so WCAG 2.5.8 binds them. + assert!(KEYS_ROW_H >= HIT_MIN); +} + +/// The search box: what a typed word leaves standing. Forty actions is more +/// than a 360 px window shows at once, so this is the card's answer to +/// "where is the one I want" -- and a heading with nothing under it would +/// be worse than no filter at all. +#[test] +fn a_search_leaves_the_rows_it_names_under_their_own_headings() { + use keymap::{ActionId, Category, Keymap}; + let keymap = Keymap::defaults(); + let acts = |found: &[(usize, KeyRow)]| -> Vec { + found + .iter() + .filter_map(|(_, r)| match r { + KeyRow::Act(a) => Some(*a), + _ => None, + }) + .collect() + }; + let heads = |found: &[(usize, KeyRow)]| -> Vec { + found + .iter() + .filter_map(|(_, r)| match r { + KeyRow::Head(c) => Some(*c), + _ => None, + }) + .collect() + }; + // Nothing typed hides nothing, and every row keeps its place in the + // unfiltered list: an element id must not move under a keystroke. + let all = keys_filter("", &keymap); + assert_eq!(all.len(), keys_rows().len()); + assert!(all.iter().enumerate().all(|(n, (i, _))| n == *i)); + // The word the user types is the word on the row. The mix card names + // the track volumes, so it is an honest hit; the fixed row about the + // volume keys is another, and each comes with its own heading only. + let vol = keys_filter("vol", &keymap); + assert_eq!( + acts(&vol), + vec![ActionId::VolumeUp, ActionId::VolumeDown, ActionId::Mix] + ); + assert_eq!(heads(&vol), vec![Category::Audio, Category::View]); + // Case is not part of the question, in either direction. + assert_eq!(keys_filter("VoL", &keymap).len(), vol.len()); + // The stroke column is searched too -- "what did ctrl do again" -- and + // an unbound-looking word finds nothing rather than everything. + let ctrl = keys_filter("ctrl+", &keymap); + assert!(acts(&ctrl).contains(&ActionId::Save)); + assert!(!acts(&ctrl).contains(&ActionId::Play)); + assert!( + keys_filter("qzx", &keymap).is_empty(), + "headings left behind" + ); + // The card's own door is on the card, by name and by stroke. + assert_eq!( + acts(&keys_filter("f1", &keymap)), + vec![ActionId::ShowActions] + ); + assert_eq!( + acts(&keys_filter("all actions", &keymap)), + vec![ActionId::ShowActions] + ); +} + +/// What a keystroke means to that box: a letter is a letter, and a word +/// gpui reports for a key that prints nothing is not typed letter by +/// letter into the search. +#[test] +fn only_a_printable_stroke_types_into_the_search() { + assert_eq!(typed("a"), Some('a')); + assert_eq!(typed("-"), Some('-')); + assert_eq!(typed("1"), Some('1')); + // The one printable key gpui reports by name. + assert_eq!(typed("space"), Some(' ')); + for word in ["left", "escape", "f1", "backspace", "tab", "delete", "home"] { + assert_eq!(typed(word), None, "{word}"); + } +} + +#[test] +fn the_keybindings_card_fits_the_smallest_window() { + // The row list is capped and scrolls, so the card's height no longer + // depends on how many actions there are: a title, a status line, the + // search box and the viewport, inside the 640x360 the rest of the + // layout is sized for. + let title = 17.; // 13 px text on its own line + let status = 28.; // 11 px text, two lines: a refusal wraps + let search = 15.; // 11 px text, one line: it never wraps + let gaps = 4. * 2.; + let padding = 24.; + // The line the list scrolls under: margin, rule, padding. + let separator = 4. + 1. + 4.; + assert!( + title + status + search + separator + KEYS_ROWS_H + gaps + padding <= 360., + "card too tall" + ); + // ...and the list is the only part that grows with the editor, so the + // rows past the fold are reached by scrolling that viewport (and, with + // forty of them, by the search box above it) rather than by a card + // taller than the window. + assert!( + keys_rows().len() as f32 * KEYS_ROW_H > KEYS_ROWS_H, + "the list outgrew the viewport long ago; the cap must still scroll" + ); + // The cap is only honest if it is the taller list that scrolls, not the + // card that grows: every action must be reachable by scrolling, and + // enough of them visible that the list reads as a list. + assert!( + KEYS_ROWS_H / KEYS_ROW_H >= 8., + "too few rows visible to scan" + ); + assert!(KEYS_W <= 640., "card too wide"); + // The rows are clickable, so WCAG 2.5.8 binds them like every other + // target in this window. + assert!(KEYS_ROW_H >= HIT_MIN); +} + +/// The equalizer card's graph: where a band lands on it, that a drag reads +/// back as the gain it painted -- the two are one mapping and its inverse, +/// which is what makes a handle follow the pointer -- and that the card +/// still fits the window the other two are sized for. +#[test] +fn the_equalizer_graph_puts_a_band_where_a_drag_reads_it_and_fits_the_smallest_window() { + use engine::eq::{Band, BandKind, EqParams}; + // Flat is the middle of the box: a band nobody has touched must not + // look like one that has been turned down. + assert_eq!(eq_y(0.), 0.5); + // Full boost is the top edge, full cut the bottom one -- y grows down. + assert_eq!(eq_y(EQ_GAIN_LIMIT), 0.); + assert_eq!(eq_y(-EQ_GAIN_LIMIT), 1.); + assert_eq!(eq_y(EQ_GAIN_LIMIT / 2.), 0.25); + // A file may carry a gain past what this card offers (the format writes + // any finite value): it paints on the edge, never off the box. + assert_eq!(eq_y(400.), 0.); + assert_eq!(eq_y(-400.), 1.); + + // A pointer reads back as the gain that paints where it landed, which + // is what makes a drag land under the hand ([`Player::drag_band`]). + for gain in [-12., -6., 0., 6., 12.] { + let read = (0.5 - eq_y(gain)) * 2. * EQ_GAIN_LIMIT; + assert!((read - gain).abs() < 1e-4, "{gain} read back as {read}"); + } + + // The frequency axis is logarithmic and spans the audible range: the + // ends are the ends, and the decade at 200 Hz is as wide as the one at + // 2 kHz -- the whole reason a bass band is reachable at all. + assert_eq!(eq_x(EQ_FREQ_LOW), 0.); + assert_eq!(eq_x(EQ_FREQ_HIGH), 1.); + assert!((eq_x(200.) - 1. / 3.).abs() < 1e-4); + assert!(((eq_x(2000.) - eq_x(200.)) - (eq_x(20000.) - eq_x(2000.))).abs() < 1e-4); + // Off either end clamps rather than painting outside the box. + assert_eq!(eq_x(1.), 0.); + assert_eq!(eq_x(96_000.), 1.); + // Every tick the card names is on the axis it is drawn against. + for (freq, label) in EQ_TICKS { + assert!( + (EQ_FREQ_LOW..=EQ_FREQ_HIGH).contains(&freq), + "tick {label} is off the axis" + ); + } + // The default bands all land inside it too, spread out enough that the + // nearest-band pick (`Player::nearest_band`) has something to pick. + let xs: Vec = EqParams::default_layout() + .bands + .iter() + .map(|b| eq_x(b.freq_hz)) + .collect(); + for pair in xs.windows(2) { + assert!(pair[1] - pair[0] > 0.1, "bands too close to aim at: {xs:?}"); + } + + // Every default band says what it is, and a shelf says so: "12 kHz" + // alone would not tell anyone it tilts the whole top octave. + let labels: Vec = EqParams::default_layout() + .bands + .iter() + .map(band_label) + .collect(); + assert_eq!( + labels, + [ + "80 Hz low shelf", + "250 Hz", + "1 kHz", + "4 kHz", + "12 kHz high shelf" + ] + ); + // A band moved off a round number reads as where it *is*: a keystroke + // that changes the filter and not the number on the card is a keystroke + // nobody can aim. + assert_eq!( + band_label(&Band { + freq_hz: 2600., + gain_db: 0., + q: 1., + kind: BandKind::Peak + }), + "2.6 kHz" + ); + assert_eq!(eq_freq_label(1122.), "1.12 kHz"); + assert_eq!(eq_freq_label(12000.), "12 kHz", "no zeroes to read past"); + assert_eq!(eq_freq_label(80.), "80 Hz"); + + // The card fits the smallest window and takes the room a bigger one has + // -- it is a graph, and the width *is* the frequency resolution. + assert!(eq_card_w(640.) <= 640. - 24., "card too wide for 640"); + assert!(eq_card_w(1280.) > eq_card_w(640.), "card ignores the window"); + assert_eq!(eq_card_w(1920.), EQ_W_MAX, "card grows without end"); + assert!(eq_card_w(320.) >= KEYS_W, "card narrower than a row of text"); + // At the smallest window the graph is still a graph: three across for + // one down, so an octave is wide enough to put a handle in. + assert!( + eq_card_w(640.) - 24. >= 3. * EQ_GRAPH_H, + "graph too square to aim at" + ); + + // The same shape as the other two cards, so it fits where they do: the + // graph stands where the export card's rows do, and is shorter than + // they are. The numbers row is a row of buttons now, so it is one of + // those tall rather than one line of text. + let (title, status, gaps, padding) = (17., 28., 4. * 2., 24.); + assert!( + title + status + EQ_GRAPH_H + HIT_MIN + gaps + padding + CONTROL_H <= 360., + "card too tall" + ); + assert!( + EQ_GRAPH_H <= EXPORT_ROWS_H, + "graph taller than a card of rows" + ); + // What is dragged is the whole graph -- the handle is a 10 px dot, but + // a press anywhere in the box takes the band nearest it -- so WCAG + // 2.5.8 is satisfied by the box, which is far past the minimum. + assert!(EQ_GRAPH_H >= HIT_MIN); + assert!( + EQ_HANDLE < HIT_MIN, + "a dot that size would want its own hitbox" + ); + assert!(KEYS_ROW_H >= HIT_MIN); +} + +/// Editing a band, which is what the card is *for*: the pointer reads a +/// frequency off the axis the same way the axis draws one, a new band lands +/// in the gap beside the picked one rather than on top of it, and every band +/// the card will hold has a digit that picks it. +#[test] +fn a_band_can_be_moved_added_and_reached() { + use engine::eq::{Band, BandKind, EqParams}; + // Across the graph and back: a drag sets the frequency the handle is + // then drawn at, so the two mappings have to be one another's inverse or + // the handle walks away from the pointer. + for freq in [20., 80., 250., 1000., 4000., 12000., 20000.] { + let read = eq_freq(eq_x(freq)); + assert!( + (read / freq - 1.).abs() < 1e-3, + "{freq} Hz read back as {read}" + ); + } + // Off the box either end stops at the axis, never past it. + assert_eq!(eq_freq(-1.), EQ_FREQ_LOW); + assert_eq!(eq_freq(2.), EQ_FREQ_HIGH); + + // A step of the frequency keys is a real move on screen -- a keystroke + // that changes nothing visible is a keystroke that reads as broken -- + // and small enough to aim with. + let step = eq_x(1000. * EQ_FREQ_STEP) - eq_x(1000.); + assert!(step > 0.01 && step < 0.06, "frequency key steps {step}"); + + // A new band lands between the picked one and the next one up, in + // octaves: 250 Hz and 1 kHz put it at 500, which is a gap on screen. + let bands = EqParams::default_layout().bands; + let added = inserted_band(&bands, 1); + assert!((added.freq_hz - 500.).abs() < 1., "landed at {added:?}"); + assert_eq!(added.gain_db, 0., "a new band changes nothing until moved"); + assert_eq!(added.kind, BandKind::Peak, "a new band is not a shelf"); + assert!(eq_x(added.freq_hz) - eq_x(bands[1].freq_hz) > 0.1); + // Above the topmost band the gap is the rest of the axis, and the band + // still lands on it rather than off the end. + let top = inserted_band(&bands, bands.len() - 1); + assert!( + top.freq_hz > bands[4].freq_hz && top.freq_hz <= EQ_FREQ_HIGH, + "landed at {top:?}" + ); + // Bands out of frequency order (a drag may cross two over) still get a + // sane neighbour: the next one *up*, not the next one along the list. + let crossed = vec![ + Band { + freq_hz: 4000., + gain_db: 0., + q: 1., + kind: BandKind::Peak, + }, + Band { + freq_hz: 100., + gain_db: 0., + q: 1., + kind: BandKind::Peak, + }, + ]; + let between = inserted_band(&crossed, 1); + assert!( + (between.freq_hz - 632.).abs() < 2., + "landed at {between:?}, not between 100 and 4000" + ); + + // Every band the card will hold is one digit away: the keyboard has ten + // digits, which is exactly why the cap is what it is. + assert!( + EQ_BANDS_MAX <= 10, + "a band past the tenth has no key that picks it" + ); + assert!(EQ_BANDS_MAX > EqParams::default_layout().bands.len()); + // The Q range holds the default, so a file's band never opens out of + // range and needs dragging back in before it can be edited. + assert!((EQ_Q_LOW..=EQ_Q_HIGH).contains(&0.707)); + assert!(EQ_Q_STEP > 1.); +} + +/// The analyser drawn behind the curve: a tone has to land on its own +/// frequency, or the backdrop is a decoration rather than a reading of what +/// is playing -- and someone shaping a band against it would be aiming at +/// the wrong octave. +#[test] +fn the_spectrum_puts_a_tone_under_its_own_frequency() { + use std::f32::consts::TAU; + let rate = 48_000u32; + let sine = |hz: f32, amp: f32| -> Vec { + (0..EQ_FFT) + .map(|i| amp * (TAU * hz * i as f32 / rate as f32).sin()) + .collect() + }; + + // Silence is the floor of the box everywhere, not a band of noise. + let quiet = eq_spectrum(&vec![0.; EQ_FFT], rate); + assert_eq!(quiet.len(), EQ_CURVE_STEPS + 1); + assert!(quiet.iter().all(|&l| l == 0.), "silence drew something"); + + // A tone peaks over its own frequency, and the columns two octaves + // either side of it are near the floor. "Over" to within a bin down low + // and a column up high, which is all a 1024-point transform on a log + // axis can promise: at 200 Hz a whole column is a fraction of a bin + // wide, so the peak sits on the bin the tone fell in. + let column = |freq: f32| (eq_x(freq) * EQ_CURVE_STEPS as f32).round() as usize; + let freq_at = |col: usize| { + let along = col as f32 / EQ_CURVE_STEPS as f32; + EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along) + }; + for hz in [200., 1000., 5000.] { + let levels = eq_spectrum(&sine(hz, 0.05), rate); + let (at, top) = + levels + .iter() + .enumerate() + .fold((0, 0f32), |best, (i, &l)| match l > best.1 { + true => (i, l), + false => best, + }); + let slack = 1.5 * rate as f32 / EQ_FFT as f32 + 0.04 * hz; + assert!( + (freq_at(at) - hz).abs() <= slack, + "{hz} Hz peaked at {:.0} Hz (column {at})", + freq_at(at) + ); + // -26 dBFS, which is where a 0.05 tone sits on the axis. + let want = + (20. * 0.05f32.log10() - EQ_SPECTRUM_DB.0) / (EQ_SPECTRUM_DB.1 - EQ_SPECTRUM_DB.0); + assert!( + (top - want).abs() < 0.05, + "a -26 dBFS tone drew {top} of the box, not {want}" + ); + // Two octaves off is far enough down the box that the hump reads as + // one hump: 0.4 of the axis is a little over 30 dB. + for off in [hz / 4., hz * 4.] { + let away = levels[column(off).min(EQ_CURVE_STEPS)]; + assert!( + top - away > 0.4, + "{hz} Hz drew {top} but still {away} at {off} Hz" + ); + } + } + + // Level reads as level: 40 dB quieter sits lower by the fraction of the + // axis those 40 dB are. + let loud = eq_spectrum(&sine(1000., 0.05), rate); + let soft = eq_spectrum(&sine(1000., 0.0005), rate); + let at = column(1000.); + let drop = loud[at] - soft[at]; + let (floor, ceiling) = EQ_SPECTRUM_DB; + assert!( + (drop - 40. / (ceiling - floor)).abs() < 0.05, + "40 dB quieter moved the analyser {drop} of the box" + ); + + // A tap the engine has not filled yet (right after a seek) draws + // nothing at all rather than a transform of half a window. + assert!(eq_spectrum(&[0.; 16], rate).is_empty()); +} + +/// The speed bar is the same round trip -- pixels -> rate -> fill -- with +/// one thing the colour sliders do not have to promise: **exactly 1.00x has +/// to be reachable**, by a hand as well as by the reset. A grid that missed +/// it would leave a clip nobody could put back. +#[test] +fn the_speed_bar_lands_where_it_paints_and_real_time_is_reachable() { + let bar = Bounds { + origin: point(px(180.), px(240.)), + size: size(px(COLOR_BAR_W), px(KEYS_ROW_H)), + }; + let (lo, hi) = ( + f32::from(Speed::MIN.permille()), + f32::from(Speed::MAX.permille()), + ); + // The same arithmetic `Player::drag_speed` runs, which is the one thing + // a test of it can share without re-deriving it. + let at = |x: f32| { + let raw = lo + frac_along(px(x), bar) * (hi - lo); + speed_at((raw / SPEED_STEP as f32).round() as i32 * SPEED_STEP) + }; + assert_eq!(at(180.), Speed::MIN, "the left end is a quarter speed"); + assert_eq!(at(180. + COLOR_BAR_W), Speed::MAX, "the right end is 4x"); + assert_eq!(at(-4000.), Speed::MIN, "off the left clamps"); + assert_eq!(at(9999.), Speed::MAX, "off the right clamps"); + let mut hits_real_time = false; + for step in 0..=240 { + let along = step as f32 / 240.; + let speed = at(180. + along * COLOR_BAR_W); + hits_real_time |= speed == Speed::NORMAL; + assert_eq!( + i32::from(speed.permille()) % SPEED_STEP, + 0, + "{speed} is off the {SPEED_STEP} grid the keys move on" + ); + // What the bar paints from that rate is where the pointer was, to + // within the half step the snap costs. + let painted = (f32::from(speed.permille()) - lo) / (hi - lo); + let slack = SPEED_STEP as f32 / (hi - lo) / 2. + 1e-4; + assert!( + (painted - along).abs() <= slack, + "pressed at {along}, paints at {painted}" + ); + } + assert!(hits_real_time, "a drag can land on exactly 1.00x"); + // ...and every preset the card offers is a rate the bar can also reach. + for permille in SPEED_PRESETS { + assert_eq!(Speed::from_permille(permille).permille(), permille); + assert_eq!(i32::from(permille) % SPEED_STEP, 0); + } + assert!(SPEED_PRESETS.contains(&Speed::NORMAL.permille()), "reset"); +} + +/// A colour slider is dragged straight to a value, so where the pointer +/// lands and where the bar then paints have to be the same place: this is +/// the round trip [`Player::drag_color`] makes, pixels -> value -> fill. +#[test] +fn a_colour_drag_lands_where_it_paints_and_the_card_fits_the_smallest_window() { + // A bar as laid out, somewhere that is not the window's origin -- a + // mapping that forgot the offset would pass at zero. + let bar = Bounds { + origin: point(px(180.), px(240.)), + size: size(px(COLOR_BAR_W), px(KEYS_ROW_H)), + }; + for &(label, low, high) in &COLOR_BANDS { + // The ends are the ends: the left of the bar is the bottom of the + // range and the right is the top, so a slider can be pulled to + // either without hunting for the last pixel. + let at = |x: f32| color_snap(low + frac_along(px(x), bar) * (high - low)); + assert_eq!(at(180.), low, "{label} left end"); + assert_eq!(at(180. + COLOR_BAR_W), high, "{label} right end"); + // Off either end clamps rather than running past the range. + assert_eq!(at(-4000.), low, "{label} off the left"); + assert_eq!(at(9999.), high, "{label} off the right"); + + for step in 0..=48 { + let along = step as f32 / 48.; + let value = at(180. + along * COLOR_BAR_W); + // Every stop is one the keyboard can also reach, which is what + // keeps "0.35" the number the file writes. + let steps = value / COLOR_STEP; + assert!( + (steps - steps.round()).abs() < 1e-3, + "{label}: {value} is off the {COLOR_STEP} grid" + ); + assert!( + (low..=high).contains(&value), + "{label}: {value} outside {low}..{high}" + ); + // What the row paints from that value is where the pointer was, + // to within the half step the snap costs. + let painted = (value - low) / (high - low); + let slack = COLOR_STEP / (high - low) / 2. + 1e-4; + assert!( + (painted - along).abs() <= slack, + "{label}: pressed at {along}, paints at {painted}" + ); + } + } + + // The same shape as the other two cards, so it fits where they do: the + // graph, four rows and the reset button inside a 360 px window. + let (title, status, gaps, padding) = (17., 17., 6. * 2., 24.); + let rows = COLOR_BANDS.len() as f32 * KEYS_ROW_H; + assert!( + title + status + HIST_H + rows + gaps + padding + CONTROL_H + 4. <= 360., + "card too tall" + ); + assert!(COLOR_W <= 640., "card too wide"); + // The label still has room beside the bar and the readout, which is + // what the buttons coming off the row bought. + let row = COLOR_W - padding - 12. - 2. * 8. - COLOR_BAR_W - 44.; + assert!(row >= LABEL_MIN_W, "no room left for a label: {row}px"); + // What is dragged is the whole row's height, not the 4 px the bar is + // drawn as (WCAG 2.5.8) -- the same split the ruler makes. + assert!(KEYS_ROW_H >= HIT_MIN); +} + +/// The graph over the sliders is the frame the grade already went through, +/// so it has to count what is actually in those bytes -- BGRA on the wire, +/// red-green-blue in the bins. +#[test] +fn the_histogram_counts_the_frame_it_is_handed() { + // Half pure red, half mid grey: two known values, in two known bins. + let (w, h) = (64usize, 64usize); + let mut frame = Vec::with_capacity(w * h * 4); + for _ in 0..h { + for col in 0..w { + match col < w / 2 { + true => frame.extend_from_slice(&[0, 0, 255, 255]), + false => frame.extend_from_slice(&[128, 128, 128, 255]), + } + } + } + let bins = histogram(&frame); + let half = (w * h / 2) as u32; + // 64 bins over 256 codes: 255 is the last bin, 128 the middle one, 0 the + // first. + assert_eq!(bins[0][63], half, "the red half tops the red channel"); + assert_eq!(bins[0][32], half, "and the grey half sits mid red"); + for channel in [1, 2] { + assert_eq!(bins[channel][0], half, "no green or blue in the red half"); + assert_eq!(bins[channel][32], half); + assert_eq!(bins[channel][63], 0); + } + // Nothing is counted twice and nothing is dropped: this frame is small + // enough to be read whole. + for channel in bins { + assert_eq!(channel.iter().sum::(), (w * h) as u32); + } + + // A grade shifts it, which is the whole point of drawing it: the same + // frame darkened lands in lower bins. + let darker: Vec = frame.iter().map(|b| b / 2).collect(); + let bins = histogram(&darker); + assert_eq!(bins[0][31], half, "255 -> 127"); + assert_eq!(bins[0][16], half, "128 -> 64"); + + // A real frame is subsampled: a 1080p one is read every 253rd pixel, so + // the shape costs a thousandth of the reads and still counts thousands. + let big = vec![200u8; 1920 * 1080 * 4]; + let bins = histogram(&big); + let counted = bins[0].iter().sum::(); + let pixels = 1920 * 1080usize; + let expected = pixels.div_ceil(pixels / HIST_SAMPLES) as u32; + assert_eq!(counted, expected, "every strided pixel counted, once"); + assert!( + (HIST_SAMPLES as u32..=HIST_SAMPLES as u32 + 64).contains(&counted), + "{counted} samples is not the budget" + ); + assert_eq!(bins[0][200 * HIST_BINS / 256], counted, "all in one bin"); + + // An empty buffer is a flat graph rather than a panic: the card is open + // before the first frame is pumped. + assert_eq!(histogram(&[]), [[0; HIST_BINS]; 3]); +} + +/// Mute and level are one control with two states, and the whole point is +/// that mute keeps the level: the user gets back what they had, not 100%. +#[test] +fn muting_keeps_the_level_it_comes_back_to() { + let mut volume = Volume::default(); + assert_eq!(volume.gain(), 1.0); + assert_eq!(volume.label(), "Vol 100%"); + + // Four presses down, then muted: the gain is silence but the level is + // still what it was, and the button keeps saying so. + for _ in 0..4 { + volume.step(false); + } + assert_eq!(volume.gain(), 0.8); + volume.muted = true; + assert_eq!(volume.gain(), 0.0); + assert_eq!(volume.label(), "Muted 80%"); + + // Turning it down while muted stays muted -- the one thing a mute + // button must never do is get louder because you asked for quieter. + volume.step(false); + assert_eq!(volume.gain(), 0.0); + assert!(volume.muted); + + // Unmute returns to the level, including the step taken while silent. + volume.muted = false; + assert_eq!(volume.gain(), 0.75); +} + +/// The whole transport in one place: the clock keeps running past the last +/// frame (wall time takes over at audio EOF), so "the clock is going" is +/// not "this is playing" -- and a button that read the clock showed Pause +/// on a timeline that had stopped moving. Ended is its own state, it draws +/// Play, and the next press starts over from the top. +#[test] +fn a_played_out_timeline_is_not_playing_and_the_next_press_starts_it_over() { + assert_eq!(transport(true, false), Transport::Playing); + assert_eq!(transport(false, false), Transport::Paused); + // The transition the bug was about: the clock is still running and the + // decoder is finished. Played out wins, however the clock reads. + assert_eq!(transport(true, true), Transport::Ended); + assert_eq!(transport(false, true), Transport::Ended); + + // What the button draws, in each state. Two bars only while it moves. + assert!(Transport::Playing.is_playing()); + for state in [Transport::Paused, Transport::Ended, Transport::Stopped] { + assert!(!state.is_playing(), "{state:?} must draw the Play triangle"); + } + + // And what a press does: start over at the end, plain toggle before it, + // nothing with no timeline. Same answer for the key and the button -- + // both come through `Player::toggle_or_restart`. + assert!(Transport::Ended.restarts()); + for state in [Transport::Playing, Transport::Paused, Transport::Stopped] { + assert!(!state.restarts(), "{state:?} must toggle, not reseek"); + } +} + +/// The half of `Ended` the eye cannot see: the clock. Wall time takes over +/// at the last frame and nothing used to stop it, so the playhead walked off +/// the end of the timeline in real time -- and the playhead is what a cut, a +/// paste, an insert and the analyser all act at. `pump` pauses on the +/// crossing; this is the engine contract that rests on, driven exactly as +/// the pump drives it. +#[test] +fn the_clock_stops_where_the_timeline_does_and_the_end_still_restarts() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + // Start a breath short of the end: the tail is what this is about, and + // playing the whole five seconds would say nothing more. + session.seek(4.8); + session.play(); + + // The pump's own loop -- tick, drain, ask where the transport is -- + // with a deadline so a fixture that will not decode fails as a failure + // rather than as a hang. + let deadline = Instant::now() + Duration::from_secs(20); + let mut state = transport(session.is_playing(), session.is_eos()); + while state != Transport::Ended { + assert!(Instant::now() < deadline, "never reached the end of a 5s file"); + session.tick(); + while session.try_frame().is_some() {} + state = transport(session.is_playing(), session.is_eos()); + } + + // What `pump` does on the crossing, and the whole point of it: the + // position holds still afterwards instead of counting on past the end, + // and it holds still *on the out point* -- where the timecode and the + // playhead have been showing it. The clock at the moment the end is + // recognised is not that: a slow renderer reaches EOF with the clock + // seconds past the timeline, which is why this repositions rather than + // only freezing. + session.halt_at_end(); + let stopped_at = session.now(); + assert_eq!(stopped_at, session.timeline_duration()); + std::thread::sleep(Duration::from_millis(250)); + assert_eq!(session.now(), stopped_at, "the clock kept running past EOF"); + // And it is still the end: pausing must not spend the state the glyph + // and the restart both read. + assert!(session.is_eos()); + assert_eq!( + transport(session.is_playing(), session.is_eos()), + Transport::Ended + ); + + // The restart path off that frozen end, which is what the button and + // the play key do from `Ended`: back to the top, and running. + session.seek(0.); + session.play(); + assert!(!session.is_eos(), "a seek revives the session"); + assert!(session.now() < 1.0); + assert_eq!( + transport(session.is_playing(), session.is_eos()), + Transport::Playing + ); + session.pause(); +} + +/// Both ends hold under a key held down: the ABI only accepts `0.0..=1.0`, +/// and a wrapped step count would hand it something else. +#[test] +fn the_volume_stops_at_both_ends() { + let mut volume = Volume::default(); + for _ in 0..40 { + volume.step(true); + } + assert_eq!(volume.gain(), 1.0); + assert_eq!(volume.steps, Volume::MAX_STEPS); + + for _ in 0..40 { + volume.step(false); + } + assert_eq!(volume.gain(), 0.0); + assert_eq!(volume.label(), "Vol 0%"); + + // Silent by the level rather than by the flag is still not muted: the + // button says which, because only one of them survives a step up. + assert!(!volume.muted); + volume.step(true); + assert_eq!(volume.gain(), 0.05); +} + +#[test] +fn a_quality_row_is_the_bitrate_it_promises() { + // Auto is the one row that says nothing: the exporter derives it, and + // a number typed against the custom row must not leak into it. + let mp4 = Format::Mp4; + assert_eq!( + export_settings(Quality::Auto, 7, mp4, DEFAULT_AUDIO_KBPS).bitrate, + None + ); + assert_eq!( + export_settings(Quality::Low, 0, mp4, DEFAULT_AUDIO_KBPS).bitrate, + Some(2_000_000) + ); + assert_eq!( + export_settings(Quality::Medium, 0, mp4, DEFAULT_AUDIO_KBPS).bitrate, + Some(6_000_000) + ); + assert_eq!( + export_settings(Quality::High, 0, mp4, DEFAULT_AUDIO_KBPS).bitrate, + Some(12_000_000) + ); + // Megabits as typed, and as the row says it back. + assert_eq!( + export_settings(Quality::Custom, 7, mp4, DEFAULT_AUDIO_KBPS).bitrate, + Some(7_000_000) + ); + assert_eq!(Quality::Low.detail(0), "2 Mbps"); + // The picked format travels, or the card's rows would be a picture of a + // choice the engine never hears about. + for format in [Format::Mp4, Format::Wav, Format::Flac] { + assert_eq!( + export_settings(Quality::Auto, 0, format, DEFAULT_AUDIO_KBPS).format, + format + ); + } + // Every fixed row sits inside the engine's clamp + // (`MAX_EXPLICIT_BITRATE`), so no row can promise a bitrate the exporter + // silently changes -- the ceiling row included, which is the one a + // raised cap could have walked out past. + for quality in Quality::ALL { + let settings = export_settings(quality, MBPS_MAX, mp4, DEFAULT_AUDIO_KBPS); + if let Some(bitrate) = settings.bitrate { + assert!( + (u64::from(MBPS_MIN) * 1_000_000..=u64::from(MBPS_MAX) * 1_000_000) + .contains(&bitrate), + "{quality:?} outside the engine clamp" + ); + } + // The software pin is the environment's to set, never a row's. + assert!(!settings.force_sw); + } +} + +/// The Sound row: what it offers, and that the pick travels to the engine +/// for a *video* export as much as for an MP3 -- both files carry sound, so +/// a row that only reached the audio formats would be half a control. +#[test] +fn the_sound_row_carries_its_rate_into_both_kinds_of_file() { + // Sorted and unique, so a row that says "b for the next one" is stepping + // up and not shuffling. + assert!(AUDIO_KBPS.windows(2).all(|w| w[0] < w[1])); + // The untouched figure is one of the offered rows, or the first press of + // `b` would jump somewhere nobody chose. + assert!(AUDIO_KBPS.contains(&DEFAULT_AUDIO_KBPS)); + // ...and it is what this program wrote before the row existed: the + // export of a user who never opens it must not change under them. + assert_eq!(DEFAULT_AUDIO_KBPS, 256); + for format in [Format::Mp4, Format::Av1, Format::Hevc, Format::Mp3] { + for kbps in AUDIO_KBPS { + assert_eq!( + export_settings(Quality::Auto, 0, format, kbps).audio_kbps, + Some(kbps), + "{format:?} at {kbps} kbps" + ); + } + } + // The pointer's door to the same field: one row per rate, the one in + // force marked exactly once, and every row's small print short enough + // to survive `MENU_W`'s truncation (the resolution list's own rule). + let rows = audio_rate_choices(DEFAULT_AUDIO_KBPS); + assert_eq!(rows.len(), AUDIO_KBPS.len()); + assert_eq!(rows.iter().filter(|(.., picked)| *picked).count(), 1); + for ((choice, label, detail, picked), kbps) in rows.iter().zip(AUDIO_KBPS) { + assert_eq!(*choice, Choice::AudioRate(kbps)); + assert_eq!(label.as_ref(), format!("{kbps} kbps")); + assert!(detail.chars().count() <= 26, "{detail} is too long to read"); + assert_eq!(*picked, kbps == DEFAULT_AUDIO_KBPS); + } + // A rate no row holds marks none of them, rather than the wrong one. + assert!(audio_rate_choices(7).iter().all(|(.., picked)| !picked)); + + // The wrap the row's key does, which is the row's own step function. + assert_eq!( + next_audio_kbps(AUDIO_KBPS[AUDIO_KBPS.len() - 1]), + AUDIO_KBPS[0] + ); + assert_eq!(next_audio_kbps(DEFAULT_AUDIO_KBPS), 320); + // A rate no list holds (a stale one, say) lands back on the first row + // rather than nowhere. + assert_eq!(next_audio_kbps(7), AUDIO_KBPS[1]); +} + +#[test] +fn a_typed_bitrate_is_a_field_and_not_a_key_capture() { + // It opens on the number in force, so backspace edits that number + // rather than the field starting empty over a bitrate still being used. + let mut edit = NumberEdit::new(12); + assert_eq!(edit.text, "12"); + edit.backspace(); + edit.digit(8); + assert_eq!(edit.text, "18"); + assert_eq!(edit.commit(), Some(18)); + // A card nobody has typed a number into opens empty: zero is not a + // bitrate anyone chose. + assert_eq!(NumberEdit::new(0).text, ""); + + // Out of range is refused *in words* and the digits stay put: clamping + // 55 to 50 would write a bitrate the user never typed. + let mut edit = NumberEdit::new(0); + for digit in [5, 5] { + edit.digit(digit); + } + assert_eq!(edit.commit(), None); + assert_eq!(edit.text, "55", "a refusal keeps what was typed"); + let refusal = edit.refusal.clone().expect("a refusal says why"); + assert!(refusal.contains(&MBPS_MAX.to_string()), "{refusal}"); + assert!(edit.detail().starts_with("55▏"), "{}", edit.detail()); + assert!(edit.detail().contains(&refusal)); + // And is fixable in place, which is the whole point of a field. + edit.backspace(); + assert_eq!(edit.refusal, None, "the reason went with the digit"); + assert_eq!(edit.commit(), Some(5)); + + // Empty, zero, and past the digit cap: each its own reason, none of + // them silent. + assert!(commit_mbps("").is_err()); + assert!(commit_mbps("0").unwrap_err().contains("not a rate")); + assert_eq!(commit_mbps("1"), Ok(MBPS_MIN)); + assert_eq!(commit_mbps("50"), Ok(MBPS_MAX)); + assert!(commit_mbps("51").is_err()); + let mut edit = NumberEdit::new(0); + for digit in [9, 9, 9, 9] { + edit.digit(digit); + } + assert_eq!(edit.text, "999", "the cap holds"); + assert!(edit.refusal.is_some(), "and says it is holding"); + // Never past what a u64 bitrate can be built from -- the committed + // number is the only one that reaches the engine, and it is bounded. + assert!(u64::from(MBPS_MAX) * 1_000_000 < u64::from(u32::MAX)); + assert_eq!(MBPS_DIGITS, 3); + + // The arrows step inside the range and stop at both ends: a walk + // through the legal numbers, never a way out of them. + let mut edit = NumberEdit::new(0); + edit.step(1); + assert_eq!(edit.text, MBPS_MIN.to_string(), "empty starts at the floor"); + edit.step(-1); + assert_eq!(edit.text, MBPS_MIN.to_string()); + let mut edit = NumberEdit::new(MBPS_MAX); + edit.step(1); + assert_eq!(edit.text, MBPS_MAX.to_string()); + edit.step(-1); + assert_eq!(edit.text, (MBPS_MAX - 1).to_string()); + // A step past a refused number clears the refusal with it. + let mut edit = NumberEdit::new(0); + edit.digit(5); + edit.digit(5); + assert_eq!(edit.commit(), None); + edit.step(-1); + assert_eq!(edit.refusal, None); + assert_eq!(edit.text, MBPS_MAX.to_string(), "back inside the range"); + + // The hint the field shows when there is nothing to refuse names both + // ways out of it. + let detail = NumberEdit::new(6).detail(); + assert!(detail.contains("enter") && detail.contains("esc"), "{detail}"); + assert!(detail.starts_with("6▏"), "{detail}"); +} + +#[test] +fn a_clip_with_no_sound_is_refused_in_the_same_words_whichever_kind_it_is() { + // A still and a video with no audio track are one answer to one + // question: the lane and index that were picked, the file, and which of + // the two soundless things it is. What must never reach the bar is the + // demuxer's own words -- a png handed to the mp4 reader answers "a box + // with a larger size than it", which is true of a container and useless + // to a person. + assert_eq!( + unscannable(Lane::V1, 1, std::path::Path::new("/tmp/shot.png")), + "V1 clip 2 has no audio to scan — shot.png is a picture" + ); + assert_eq!( + unscannable( + Lane::new(LaneKind::Audio, 1), + 0, + std::path::Path::new("/tmp/test_baseline.mp4") + ), + "A2 clip 1 has no audio to scan — test_baseline.mp4 is silent" + ); +} + +/// The hold gate: a value runs, everything else still means one press one +/// action -- which is the whole invariant the blanket `is_held` filter used +/// to carry on its own. +#[test] +fn a_held_key_moves_a_value_and_nothing_else() { + use keymap::ActionId; + // A card's four arrows, whichever card it is. + for key in ["up", "down", "left", "right"] { + assert!(repeats(Repeat::Card, key, None), "{key} on a card"); + } + // The card's own one-shots: flatten every band, cut forty places, play + // them fast, close. None of them on a hold. + for key in ["r", "enter", "f", "1", "escape"] { + assert!(!repeats(Repeat::Card, key, None), "{key} on a card"); + } + // Outside a card the keymap answers, and only the volume pair is a + // value being moved. + assert!(repeats(Repeat::Keymap, "up", Some(ActionId::VolumeUp))); + assert!(repeats(Repeat::Keymap, "down", Some(ActionId::VolumeDown))); + // ...and the zoom pair, which runs the view the way they run the level. + assert!(repeats(Repeat::Keymap, "=", Some(ActionId::ZoomIn))); + assert!(!repeats(Repeat::Keymap, "0", Some(ActionId::ZoomFit))); + for action in ActionId::ALL { + let held = repeats(Repeat::Keymap, "k", Some(action)); + assert_eq!( + held, + matches!( + action, + ActionId::VolumeUp + | ActionId::VolumeDown + | ActionId::ZoomIn + | ActionId::ZoomOut + ), + "{action:?} on a hold" + ); + } + // An arrow with nothing bound to it moves nothing on the timeline. + assert!(!repeats(Repeat::Keymap, "left", None)); + // And a stroke being captured, an export, or the overlays: nothing at + // all, or the hold would bind a key and then fire what it just bound. + for key in ["up", "left", "escape", "5"] { + assert!(!repeats(Repeat::Nothing, key, Some(ActionId::VolumeUp))); + } +} + +#[test] +fn the_silence_card_fits_the_smallest_window_and_never_slows_a_silence_down() { + // The same 640x360 floor, and this card starts below the header: a + // title and a hint over its [`SILENCE_ROWS`] rows, the count line and + // the two buttons. + let (title, hint, count) = (17., 17., 17.); + let gaps = 6. * 5.; + let padding = 24.; + assert!( + HEADER_H + + 8. + + title + + hint + + SILENCE_ROWS as f32 * KEYS_ROW_H + + count + + KEYS_ROW_H + + gaps + + padding + <= 360., + "card too tall" + ); + // Its rows, its steppers and its buttons are clicked, so WCAG 2.5.8 + // binds them: a stepper is `HIT_MIN` square inside a row of that height. + assert!(KEYS_ROW_H >= HIT_MIN); + // ...and the pair of them fits beside the widest value the card prints. + assert!(2. * HIT_MIN + 4. < COLOR_W / 2., "steppers crowd the value"); + // A "speed-up" is never a slow-down: the rate stops above real time at + // one end and at what a clip can hold at the other, whatever the keys + // ask for. A silence played *slower* would make the timeline longer, + // which is the one thing neither button may do. + assert!(silence_rate(0) > Speed::NORMAL); + assert!(silence_rate(1000) > Speed::NORMAL); + assert_eq!(silence_rate(i32::MAX), Speed::MAX); + assert_eq!(silence_rate(4000), Speed::MAX); +} + +/// The choice lists that replaced two click-to-cycle surfaces: every value +/// on offer at once, exactly one of them marked as the one in force, the +/// same order the stroke steps through, and the open list inside the +/// 640x360 floor with every row a `HIT_MIN` target. +#[test] +fn a_choice_list_offers_every_value_and_fits_the_smallest_window() { + // Odd media: its own size is on the ladder, in its place by area, and + // nothing else moved. + let native = (1440, 1080); + let ladder = resolution_ladder(native); + assert_eq!( + ladder, + [ + (3840, 2160), + (2560, 1440), + (1920, 1080), + (1440, 1080), + (1280, 720), + (854, 480) + ] + ); + for size in RESOLUTIONS { + assert!(ladder.contains(&size), "{size:?} is not on offer"); + } + // Media already at a listed size is on the ladder once, not twice. + assert_eq!(resolution_ladder((1920, 1080)).len(), RESOLUTIONS.len()); + + // The rows say the same thing the ladder does, and mark the one in + // force -- exactly one row, whichever rung the project is on. + let rows = resolution_choices((1280, 720), native); + assert_eq!(rows.len(), ladder.len()); + assert_eq!(rows.iter().filter(|(.., picked)| *picked).count(), 1); + for ((choice, label, detail, picked), size) in rows.iter().zip(&ladder) { + assert_eq!(*choice, Choice::Size(size.0, size.1)); + assert_eq!(label.as_ref(), format!("{}p", size.1)); + assert!(detail.contains(&format!("{}x{}", size.0, size.1))); + assert_eq!(*picked, *size == (1280, 720)); + } + // The media's own size says so: it is the one rung a person cannot read + // off a number they chose. + let (.., native_detail, _) = &rows[3]; + assert!( + native_detail.contains("the media's own"), + "{native_detail}" + ); + // A project at a size nobody listed still gets the whole list, with + // nothing marked rather than a wrong row marked. + assert!( + resolution_choices((1000, 1000), native) + .iter() + .all(|(.., picked)| !picked) + ); + // Picking a row means that row, and stepping means the next one: the + // list and the stroke read the same ladder. + assert_eq!(next_resolution(ladder[1], native), ladder[2]); + + // The fit list, on a clip: all four policies, in the order the stroke + // steps through them, the clip's own marked and every row naming the + // canvas it would place the picture on. + let mut fit = FITS[0]; + for next in FITS.into_iter().skip(1).chain([FITS[0]]) { + assert_eq!(next_fit(fit), next, "the stroke skips a policy"); + fit = next; + } + let fits = fit_choices(Lane::V1, 3, FITS[2], (1920, 1080)); + assert_eq!(fits.len(), FITS.len()); + assert_eq!(fits.iter().filter(|(.., picked)| *picked).count(), 1); + assert_eq!(fits[2].0, Choice::Fit(Lane::V1, 3, FITS[2])); + assert!(fits[2].3, "the clip's own policy is not marked"); + assert!(fits[0].2.contains("1920x1080"), "{}", fits[0].2); + + // The rate list, the other setting the project has of its own: every + // rate on offer, the media's own cycled in at its place by speed and + // said so, and the one the timeline is cut at marked. The value carried + // is the `f64` the engine conforms to, not the rounded label -- 23.976 + // is not 24000/1001, and a rate the timescales cannot name is refused. + let ntsc = 24_000. / 1001.; + let rates = frame_rate_ladder(25.); + assert_eq!(rates.len(), FRAME_RATES.len(), "25 is already on the list"); + let odd = frame_rate_ladder(48.); + assert_eq!(odd[5], 48., "the media's own, in its place by speed"); + assert_eq!(odd.len(), FRAME_RATES.len() + 1); + let fps = fps_choices(ntsc, 48.); + assert_eq!(fps.len(), odd.len()); + assert_eq!(fps.iter().filter(|(.., picked)| *picked).count(), 1); + assert_eq!(fps[0].0, Choice::Fps(ntsc), "the ratio, not 23.976"); + assert_eq!(fps[0].1.as_ref(), "23.976 fps"); + assert!(fps[0].3, "the rate in force is not marked"); + assert!(fps[5].2.contains("the media's own"), "{}", fps[5].2); + for (.., detail, _) in &fps { + assert!(detail.chars().count() < 26, "{detail} loses its tail"); + } + + // The HDR list, the third project setting: all three renditions in the + // order they brighten, the one in force marked, and every row saying + // what it is in words that fit beside the label. + let tones = tone_choices(Preset::Standard); + assert_eq!(tones.len(), Preset::ALL.len()); + assert_eq!(tones.iter().filter(|(.., picked)| *picked).count(), 1); + for (row, preset) in tones.iter().zip(Preset::ALL) { + assert_eq!(row.0, Choice::Tone(preset)); + assert_eq!(row.1.as_ref(), tone_label(preset)); + assert!(!row.2.is_empty(), "{preset:?} says nothing about itself"); + assert!(row.2.chars().count() < 26, "{} loses its tail", row.2); + } + assert!(tones[1].3, "the rendition in force is not marked"); + + // The open list fits the floor the menus are measured against: the + // longest of them is the rate ladder with an odd rate cycled in, and it + // hangs at the pointer with every row on screen. Rows are click targets + // (WCAG 2.5.8). + assert!(MENU_ROW_H >= HIT_MIN); + assert!(odd.len() > ladder.len(), "the longest list moved"); + assert!(MENU_PAD * 2. + odd.len() as f32 * MENU_ROW_H <= 360.); + let tall = MENU_PAD * 2. + ladder.len() as f32 * MENU_ROW_H; + assert!(tall <= 360., "the list is taller than the floor"); + assert_eq!( + menu_at(point(px(600.), px(340.)), size(px(640.), px(360.)), tall), + (640. - MENU_W, 360. - tall), + "the list would hang off the smallest window" + ); +} + +#[test] +fn the_export_card_fits_the_smallest_window() { + // Same 640x360 floor the keybindings card is measured against: the + // capped row list, the two summary lines and the confirm button, under + // a title and a status line. + let title = 17.; + let status = 28.; + // The head is one line of 11 px at this width -- every field of it, + // worst case, is 71 characters against the 76 that fit. The tail is + // budgeted for two: the destination's name is the user's and a long one + // wraps. + let summary = 15. + 30.; + // Six children in the column, so five gaps. + let gaps = 5. * 2.; + let padding = 24.; + assert_eq!( + EXPORT_FIXED_H, + title + status + summary + CONTROL_H + 4. + gaps + padding + ); + assert!(EXPORT_FIXED_H + EXPORT_ROWS_H <= 360., "card too tall"); + // The list grows with a window that has the room -- and never shrinks + // below the cap that made the floor fit, whatever arithmetic the window + // hands it. + let cap = |h: f32| (h - EXPORT_FIXED_H - 24.).max(EXPORT_ROWS_H); + assert_eq!(cap(360.), EXPORT_ROWS_H); + assert_eq!(cap(0.), EXPORT_ROWS_H); + assert!(cap(720.) > EXPORT_ROWS_H); + assert!(EXPORT_FIXED_H + cap(720.) <= 720.); + // ...and inside the 640 px floor with the scrim showing either side. + assert!(EXPORT_W + 2. * 12. <= 640.); + // The cap is only honest if enough of the list is on screen to read as + // one -- and the whole format section is: its header and every codec + // row, so nothing that is picked *first* is behind a scroll. + let codecs = FORMATS.iter().filter(|(row, ..)| !row.is_empty()).count(); + assert!(EXPORT_ROWS_H / KEYS_ROW_H >= 1. + codecs as f32); + // Clickable rows, so WCAG 2.5.8 binds them as it binds the panel's -- + // and the bitrate steppers are `HIT_MIN` squares sitting inside a row, + // which only fits while the row is at least as tall as one. + assert!(KEYS_ROW_H >= HIT_MIN); + assert!(CONTROL_H >= HIT_MIN); + // The dimmed text on the card -- every refusal, every detail, every key + // in its column -- is body text on `BG_RAISED` and WCAG 1.4.3 binds it. + // A dimmed row is drawn in this ink rather than at an opacity, which is + // what a refusal used to be readable through. + // Every palette, not the one in force: a family is picked at runtime + // now (`ui::theme`), so a floor met by one of them and missed by the + // other is a window somebody is looking at. + for id in crate::ui::theme::PaletteId::ALL { + let p = id.palette(); + assert!( + contrast(p.FG_SECONDARY, p.BG_RAISED) >= 4.5, + "{id:?}: refusal ink {:.2}", + contrast(p.FG_SECONDARY, p.BG_RAISED) + ); + // ...and on the picked row, where the highlight is the accent at + // surface brightness. Both inks clear 4.5:1 on it now -- the row still + // lifts its key and detail to `FG_PRIMARY`, as emphasis rather than as + // the rescue it used to be. + assert!(contrast(p.FG_PRIMARY, p.BG_SELECTED) >= 4.5, "{id:?}"); + assert!( + contrast(p.FG_SECONDARY, p.BG_SELECTED) >= 4.5, + "{id:?}: refusal ink on the picked row {:.2}", + contrast(p.FG_SECONDARY, p.BG_SELECTED) + ); + } +} + +/// The progress line's two clocks, driven the way a repaint drives them: +/// steady work, a stall where hardware hands over to software, then steady +/// work again. The estimate may not whipsaw, may not vanish once it has +/// been given, and must meet the elapsed clock at the end. +#[test] +fn the_export_estimate_rides_out_a_stall_and_converges() { + let (mut marks, mut elapsed, mut progress) = (Vec::new(), 0f32, 0f32); + // 2%/s, a 12 s stall at 40% -- longer than the window, so the window + // alone would have nothing left to measure -- and the same rate to the + // end: 62 s of wall clock for 50 s of work. + let rate = 0.02; + let (mut quiet, mut before_stall, mut after_stall, mut last) = (0f32, 0., 0., f32::MAX); + while progress < 1. { + let stalled = (20. ..32.).contains(&elapsed); + note_progress(&mut marks, elapsed, progress); + // What is really left, to hold every guess against. + let truth = (1. - progress) / rate + if stalled { 32. - elapsed } else { 0. }; + match eta_secs(&marks, elapsed, progress) { + // "estimating…" is only allowed before there is a span to + // measure, and never again after the first number. + None => { + assert!(elapsed < ETA_SPAN + 1., "estimate vanished at {elapsed}"); + quiet = elapsed; + } + Some(left) => { + // No guess is ever wilder than four times the truth: that + // is the eightfold spike a raw window rate throws on either + // edge of the stall. + assert!(left <= truth * 4., "at {elapsed}s: {left} vs {truth}"); + // While the rate holds, the answer is the true one and it + // only ever counts down. + if elapsed >= 5. && elapsed < 20. { + assert!((left - truth).abs() <= truth * 0.15, "{elapsed}s: {left}"); + assert!(left < last, "estimate grew while the rate held"); + } + // Eight seconds past the stall it has caught up again. + if elapsed >= 40. { + assert!((left - truth).abs() <= truth * 0.25, "{elapsed}s: {left}"); + assert!(left < last + 0.001, "estimate grew after the stall"); + } + if (20. ..20.25).contains(&elapsed) { + before_stall = left; + } + if (31.5..31.75).contains(&elapsed) { + after_stall = left; + } + last = left; + } + } + // A window's worth of marks and no more, however long the encode. + assert!(marks.len() <= 20, "{} marks", marks.len()); + elapsed += 0.25; + if !stalled { + progress = (progress + rate * 0.25).min(1.); + } + } + assert!(quiet > 0. && quiet < ETA_SPAN + 1.); + // The stall stretched the guess instead of erasing it, and by more than + // the stopped clock adds on its own. + assert!( + after_stall > before_stall + 12., + "{before_stall} -> {after_stall}" + ); + // Both clocks meet: a finished pass has nothing left. + assert_eq!(eta_secs(&marks, elapsed, 1.), Some(0.)); + assert!((elapsed - 62.).abs() < 1., "{elapsed}"); + assert_eq!(clock(83.4), "1:23"); + assert_eq!(clock(114.), "1:54"); + assert_eq!(clock(-1.), "0:00"); +} diff --git a/crates/app/src/tests/editing.rs b/crates/app/src/tests/editing.rs new file mode 100644 index 0000000..616f8d2 --- /dev/null +++ b/crates/app/src/tests/editing.rs @@ -0,0 +1,1592 @@ +//! Importing, the library column, the menus, and every edit a clip or a +//! track can be handed. + +use super::*; + +/// What the file manager is handed: the parts a path keeps as they are, and +/// the ones the bus would otherwise read as something else. +#[test] +fn file_uri_encodes_what_a_path_carries() { + assert_eq!( + file_uri(std::path::Path::new("/a/b.mp4")), + "file:///a/b.mp4" + ); + assert_eq!( + file_uri(std::path::Path::new("/home/x/out dir/my export.mp4")), + "file:///home/x/out%20dir/my%20export.mp4" + ); + assert_eq!( + file_uri(std::path::Path::new("/tmp/ünlü#1?.mp4")), + "file:///tmp/%C3%BCnl%C3%BC%231%3F.mp4" + ); +} + +/// An import fills the *library* and nothing else -- the whole point of +/// this door: the row is there at the file's own length before any clip +/// plays it, wearing the tint the lanes will tint that clip with, and the +/// timeline is exactly as long as it was. Placing it is the drag, and the +/// drag is a separate act. +#[test] +fn an_import_adds_a_row_at_its_own_length_and_leaves_the_lanes_alone() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + let before = session.timeline_duration(); + let clips: Vec = session + .lanes() + .into_iter() + .map(|lane| session.lane_clips(lane).len()) + .collect(); + session.import(&asset("test_av2.mp4")).expect("av2 matches"); + assert_eq!(session.sources().len(), 2, "the library grew"); + assert_eq!( + session.timeline_duration(), + before, + "an import must not place a clip" + ); + assert_eq!( + session + .lanes() + .into_iter() + .map(|lane| session.lane_clips(lane).len()) + .collect::>(), + clips, + "no lane moved" + ); + // The rows the panel draws: one per source, each its file's own length + // -- source 1 has no clip anywhere and is still 4 s at 30 fps. + let rows = library_rows( + session.sources(), + &HashMap::new(), + &HashMap::new(), + None, + |path| session.file_frames(path), + ); + assert_eq!(rows.len(), 2); + assert_eq!(rows[0].frames, 150, "5 s at 30 fps"); + assert_eq!(rows[1].frames, 120, "4 s at 30 fps, never placed"); + // The swatch is the clip colour, by the same index and the same + // function -- what makes the panel and the lanes one association. + for row in 0..rows.len() { + assert_eq!(rows[row].tint, row); + assert_eq!(source_tint(row), SOURCE_TINTS()[row % SOURCE_TINTS().len()]); + } +} + +/// The window opened on a song and nothing else -- the launch argument, the +/// drop on an empty window and the Import button all end in the same +/// `PlaybackSession::open`. The library lists it placeable, the lane door +/// the Add button and a drag share puts it on `A1`, and the one format that +/// needs a picture says so on its own row instead of failing at the end of +/// an export. +#[test] +fn a_song_opens_the_window_by_itself() { + let mut session = + PlaybackSession::open(asset("test_tone.mp3")).expect("a song is a timeline"); + session.set_gain(0.0); + // The source's own path, which is the canonical one a row carries. + let path = session.sources()[0].path.clone(); + assert!(session.lane_clips(Lane::V1).is_empty(), "no picture"); + assert_eq!(session.lane_clips(Lane::A1).len(), 1); + + // The library row: probed like any other source, and not greyed -- + // `unusable` is what the panel dims a row with. + let streams = HashMap::from([( + path.clone(), + engine::AudioSession::probe_streams(&path).expect("probe the song"), + )]); + let rate = streams[&path] + .iter() + .find(|s| s.index == session.sources()[0].audio_stream) + .map(|s| (s.sample_rate, s.channels)); + let frames = session.file_frames(&path); + let rows = library_rows(session.sources(), &streams, &HashMap::new(), rate, |_| { + frames + }); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].name, "test_tone.mp3"); + assert_eq!(rows[0].unusable, None, "the row is placeable"); + assert_eq!(rows[0].frames, 90, "3 s at the audio-only 30 fps"); + + // ...and it places, on the audio lane, through the door `insert_source` + // uses: a second copy of the song at the playhead. + session.seek(1.0); + assert!( + session + .place_stream_at(1.0, &path, 0, Some(Lane::A1)) + .expect("its own file is on this timeline") + ); + assert_eq!(session.lane_clips(Lane::A1).len(), 2); + assert!(session.lane_clips(Lane::V1).is_empty(), "still no picture"); + + // Both picture rows carry the reason rather than the format's detail + // line, each naming itself; the audio formats are what this timeline is + // and are never refused. + assert_eq!( + format_refusal(&session, Format::Mp4).as_deref(), + Some("no picture — an mp4 would be black; export WAV, FLAC, MP3 or OGG") + ); + assert_eq!( + format_refusal(&session, Format::Av1).as_deref(), + Some("no picture — an AV1 Matroska would be black; export WAV, FLAC, MP3 or OGG") + ); + assert_eq!( + format_refusal(&session, Format::Av1Mp4).as_deref(), + Some("no picture — an AV1 mp4 would be black; export WAV, FLAC, MP3 or OGG") + ); + assert_eq!(format_refusal(&session, Format::Wav), None); + assert_eq!(format_refusal(&session, Format::Flac), None); + assert_eq!(format_refusal(&session, Format::Mp3), None); +} + +/// A file's every audio track gets a row: the ones the timeline can take +/// are placeable, the ones it cannot are listed greyed with the reason. +/// Which rows exist at all is the branchy part of the panel, so it is +/// planned as data and checked here rather than through the pointer. +#[test] +fn every_audio_stream_of_a_file_is_a_row_usable_or_not() { + let multi = PathBuf::from("/m/movie.mp4"); + let sources = [source("/m/movie.mp4", 0)]; + let mut streams = HashMap::new(); + streams.insert( + multi.clone(), + vec![ + info(0, 44_100, 2, None, true), + info(1, 44_100, 2, Some("fra"), true), + info(2, 22_050, 1, Some("deu"), true), + info(3, 0, 0, None, false), + ], + ); + let rows = library_rows( + &sources, + &streams, + &HashMap::new(), + Some((44_100, 2)), + |_| 90, + ); + assert_eq!( + rows.iter().map(|r| r.stream).collect::>(), + [0, 1, 2, 3], + "one row per audio stream, in file order" + ); + assert!( + rows.iter().all(|r| r.path == multi && r.tint == 0), + "every stream of one file wears the file's own tint" + ); + assert_eq!(rows[0].name, "movie.mp4 [audio 1]"); + assert_eq!(rows[1].name, "movie.mp4 [audio 2]"); + assert_eq!(rows[1].detail, "fra 44.1 kHz stereo"); + // Placeable: the one already on the timeline, and the one that matches + // it. The mono track cannot join a stereo timeline -- one device and one + // copied AAC track for the whole of it -- and the codec we cannot read + // cannot join anything. Both say which. Its 22 kHz is *not* part of that + // any more: a rate of its own is resampled at the decoder's door, and a + // row greyed for one the engine accepts is this picker telling a lie. + assert_eq!((&rows[0].unusable, &rows[1].unusable), (&None, &None)); + assert_eq!(rows[2].unusable.as_deref(), Some("the timeline is stereo")); + assert_eq!( + unusable(&info(9, 48_000, 2, None, true), Some((44_100, 2))), + None, + "48 kHz stereo joins a 44.1 kHz stereo timeline" + ); + assert_eq!(rows[3].unusable.as_deref(), Some("unsupported codec")); + assert_eq!( + rows[3].detail, "", + "a stream we cannot parse claims nothing" + ); + // Every row is the same file, so every row is that file's length. + assert!(rows.iter().all(|r| r.frames == 90)); + + // The single-stream case is exactly one row and no stream tag: no + // regression for the media everything else in the world is. + let plain = [source("/m/plain.mp4", 0)]; + let mut one = HashMap::new(); + one.insert( + PathBuf::from("/m/plain.mp4"), + vec![info(0, 44_100, 2, None, true)], + ); + let rows = library_rows(&plain, &one, &HashMap::new(), Some((44_100, 2)), |_| 90); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].name, "plain.mp4"); + assert_eq!( + rows[0].detail, "", + "one audio track is the row it has always been: name and length" + ); + // ...as is a silent file, and a file not probed yet. + let mut silent = HashMap::new(); + silent.insert(PathBuf::from("/m/plain.mp4"), Vec::new()); + for probe in [silent, HashMap::new()] { + let rows = library_rows(&plain, &probe, &HashMap::new(), None, |_| 90); + assert_eq!(rows.len(), 1); + assert_eq!(rows[0].name, "plain.mp4"); + assert_eq!(rows[0].detail, ""); + } + + // A second stream *placed* on the timeline is a source entry of its + // own: it keeps its row, no duplicate appears for it, and the rows of + // one file stay together whatever order the entries came in. + let placed = [ + source("/m/movie.mp4", 0), + source("/m/other.mp4", 0), + source("/m/movie.mp4", 2), + ]; + streams.insert( + PathBuf::from("/m/other.mp4"), + vec![info(0, 44_100, 2, None, true)], + ); + let rows = library_rows( + &placed, + &streams, + &HashMap::new(), + Some((44_100, 2)), + |_| 90, + ); + assert_eq!( + rows.iter() + .map(|r| (file_name(&r.path), r.stream)) + .collect::>(), + [ + ("movie.mp4".to_string(), 0), + ("other.mp4".to_string(), 0), + ("movie.mp4".to_string(), 2), + ("movie.mp4".to_string(), 1), + ("movie.mp4".to_string(), 3), + ] + ); + assert!( + rows[2].unusable.is_none(), + "a stream already on the timeline is playing, whatever a probe says" + ); + assert_eq!(rows[1].tint, 1, "the other file is the other tint"); +} + +/// What the clip menu offers, and where it hangs. The two items that act on +/// the playhead rather than on the clicked clip are the ones that can be +/// inapplicable, and a menu at the edge of the window has to come back +/// inside it or its last item cannot be clicked at all. +#[test] +fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() { + use keymap::{ActionId, Keymap}; + // Frames 30..90 of the timeline, taken from the head of its source. + let clip = Clip { + start: 30, + in_frame: 0, + out_frame: 60, + source: 0, + link: None, + eq: None, + color: None, + fit: FitPolicy::default(), + speed: Speed::NORMAL, + }; + assert_eq!(clip.end(), 90); + let a1 = Lane::A1; + let v1 = Lane::V1; + // The question the clip menu asks: a timeline is open and the menu was + // opened on this clip, at this playhead. + let on = |clip: &Clip, lane, action, playhead| { + enable( + action, + Ctx { + clip: Some((*clip, lane)), + playhead, + timeline: true, + ..Ctx::default() + }, + ) + }; + let offered = |clip: &Clip, lane, action, playhead| on(clip, lane, action, playhead).yes(); + // Cut splits from inside only: neither edge has anything to split off. + assert!(offered(&clip, v1, ActionId::Cut, 31)); + assert!(offered(&clip, v1, ActionId::Cut, 89)); + assert!(!offered(&clip, v1, ActionId::Cut, 30)); + assert!(!offered(&clip, v1, ActionId::Cut, 90)); + assert!(!offered(&clip, v1, ActionId::Cut, 200)); + // A slowed clip refuses more than the edges do, and it may not say the + // edges' words while doing it: at a quarter speed each of its sixty + // source frames is on screen four timeline frames, and only the first of + // the four is a frame the file has. The three between are inside the + // clip by any reading of the playhead, so "only from inside a clip" + // there is a refusal claiming something the screen contradicts. + let slow = Clip { + speed: Speed::MIN, + ..clip + }; + assert_eq!(slow.frames(), 240, "a quarter speed is four times as long"); + assert!(offered(&slow, v1, ActionId::Cut, 34), "34 is a source frame"); + assert!(!offered(&slow, v1, ActionId::Cut, 35)); + assert_eq!( + on(&slow, v1, ActionId::Cut, 35).why(), + Some("this speed holds one frame here — step to the next"), + ); + assert_eq!( + on(&slow, v1, ActionId::Cut, 30).why(), + Some("only from inside a clip"), + "the head is still the edge's refusal, speed or no speed", + ); + // Regroup is the other way round: only where this clip meets another. + assert!(offered(&clip, v1, ActionId::Regroup, 30)); + assert!(offered(&clip, v1, ActionId::Regroup, 90)); + assert!(!offered(&clip, v1, ActionId::Regroup, 60)); + // Detach is the clip's own business: nothing to take apart in one that + // names no group, and whether the group still has another half is the + // engine's question. Group is offered on every clip, for that reason. + assert!(!offered(&clip, v1, ActionId::Detach, 0)); + let grouped = Clip { + link: Some(3), + ..clip + }; + assert!(offered(&grouped, v1, ActionId::Detach, 60)); + assert!(offered(&clip, a1, ActionId::Group, 0)); + // The equalizer is the one item the *lane* decides: it filters samples, + // and a video clip has none of its own. Never the playhead's business. + assert!(offered(&clip, a1, ActionId::Equalizer, 0)); + assert!(offered(&clip, a1, ActionId::Equalizer, 60)); + assert!(!offered(&clip, v1, ActionId::Equalizer, 60)); + // The rest act on the clip that was clicked, so they always mean + // something -- the engine words its own refusals. + for action in [ActionId::Delete, ActionId::Lift, ActionId::ToggleMute] { + assert!(offered(&clip, v1, action, 0)); + assert!(offered(&clip, a1, action, 60)); + } + // Except the grade, which is a picture setting: offered on a video + // clip wherever the playhead is, dimmed on a waveform. + assert!(offered(&clip, v1, ActionId::Color, 0)); + assert!(!offered(&clip, a1, ActionId::Color, 60)); + // The two kinds of no, which is what the row is told apart by: a grade + // on a waveform is a *class* answer -- an audio clip has no picture and + // never will, so the menu leaves the item out entirely -- where a cut at + // the clip's edge is this moment's answer and the next click of the + // playhead changes it, so that one is drawn, dimmed, and says why. + // + // What the menu draws for a clip of each kind, in order: the render + // loop's `continue`, as a list. + let menu = |lane, image, playhead| { + MENU_ITEMS + .into_iter() + .filter(|&action| { + enable( + action, + Ctx { + clip: Some((clip, lane)), + image, + playhead, + timeline: true, + ..Ctx::default() + }, + ) + .listed() + }) + .collect::>() + }; + // Sound: no grade and no fit policy, and the equalizer that is the + // whole reason an audio clip has a menu of its own. + let sound = menu(a1, false, 60); + assert!(!sound.contains(&ActionId::Color), "{sound:?}"); + assert!(!sound.contains(&ActionId::Fit), "{sound:?}"); + assert!(sound.contains(&ActionId::Equalizer)); + assert!(sound.contains(&ActionId::Silence)); + // Picture: the mirror of it. The sound of a take is the audio lane's, + // clip for clip, so the equalizer is not this clip's business -- but the + // silence scan is, because it opens on the half it is grouped with. + let picture = menu(v1, false, 60); + assert!(!picture.contains(&ActionId::Equalizer), "{picture:?}"); + assert!(picture.contains(&ActionId::Color)); + assert!(picture.contains(&ActionId::Fit)); + assert!(picture.contains(&ActionId::Silence)); + // A still: picture with no sound anywhere, ever. Graded, fitted and + // re-timed like any other clip (a speed reaches a still through the same + // rewrite), scanned like none. + let still = menu(v1, true, 60); + assert!(!still.contains(&ActionId::Silence), "{still:?}"); + assert!(!still.contains(&ActionId::Equalizer), "{still:?}"); + assert!(still.contains(&ActionId::Color)); + assert!(still.contains(&ActionId::Fit)); + assert!(still.contains(&ActionId::Speed)); + // ...and the state refusals are on all three, dimmed rather than gone: + // at 30 the playhead is on this clip's head, where a cut has nothing to + // split off -- a row the next click of the playhead lights. + for rows in [menu(a1, false, 30), menu(v1, false, 30), menu(v1, true, 30)] { + assert!(rows.contains(&ActionId::Cut), "{rows:?}"); + assert!(rows.contains(&ActionId::Detach), "{rows:?}"); + } + // The actions card is the other half of the rule: it lists the whole + // registry, so a class refusal is dimmed there with its reason and never + // dropped -- an action missing from the one surface that lists + // everything would read as an action that does not exist. + let listed: Vec = keys_rows() + .into_iter() + .filter_map(|r| match r { + KeyRow::Act(action) => Some(action), + _ => None, + }) + .collect(); + for (lane, action) in [ + (a1, ActionId::Color), + (a1, ActionId::Fit), + (v1, ActionId::Equalizer), + ] { + assert!(matches!(on(&clip, lane, action, 60), Enable::Hidden(_))); + assert!(listed.contains(&action), "{action:?} left the actions card"); + assert!(on(&clip, lane, action, 60).why().is_some()); + } + assert!(matches!(on(&clip, v1, ActionId::Cut, 30), Enable::No(_))); + assert!(matches!(on(&clip, v1, ActionId::Regroup, 60), Enable::No(_))); + assert!(matches!(on(&clip, v1, ActionId::Detach, 0), Enable::No(_))); + // Every refusal says something, and says it short enough to sit in the + // menu's right-hand column beside a label -- the still's included, which + // the card dims with while the menu leaves the row out. + for action in MENU_ITEMS { + for (lane, image) in [(v1, false), (a1, false), (v1, true)] { + for playhead in [0, 30, 60, 90] { + let refusal = enable( + action, + Ctx { + clip: Some((clip, lane)), + image, + playhead, + timeline: true, + ..Ctx::default() + }, + ); + if let Some(why) = refusal.why() { + assert!(!why.is_empty() && why.len() <= 30, "{action:?}: {why:?}"); + } + } + } + } + assert!(matches!( + enable( + ActionId::Silence, + Ctx { + clip: Some((clip, v1)), + image: true, + playhead: 60, + timeline: true, + ..Ctx::default() + } + ), + Enable::Hidden(_) + )); + // The editor as a whole, which is how the actions card asks: with no + // timeline nothing is offered, an export leaves only its own cancel, + // and the three that act on the marked clip say so when none is. + let whole = |action, ctx| enable(action, ctx); + assert_eq!( + whole(ActionId::Play, Ctx::default()), + Enable::No("no timeline open") + ); + let live = Ctx { + timeline: true, + playable: true, + ..Ctx::default() + }; + assert!(whole(ActionId::Play, live).yes()); + // ...and an open timeline with nothing on its lanes refuses the + // transport in the oracle rather than in the button, which is what + // makes the key and the button say the same thing. + assert_eq!( + whole( + ActionId::Play, + Ctx { + playable: false, + ..live + } + ), + Enable::No("put a clip on a lane first") + ); + // The magnet and the monitoring level are the editor's own and answer + // with no timeline at all -- the keyboard always fired them there, and + // now so does the toolbar. + for editor_wide in [ + ActionId::ToggleSnap, + ActionId::ToggleMute, + ActionId::VolumeUp, + ActionId::VolumeDown, + ] { + assert!( + whole(editor_wide, Ctx::default()).yes(), + "{editor_wide:?} is dead with no file open while its key still fires" + ); + } + assert!(!whole(ActionId::Delete, live).yes()); + assert!(!whole(ActionId::Paste, live).yes()); + assert!( + whole( + ActionId::Paste, + Ctx { + clipboard: true, + ..live + } + ) + .yes() + ); + assert!(!whole(ActionId::CancelExport, live).yes()); + let busy = Ctx { + exporting: true, + ..live + }; + assert!(whole(ActionId::CancelExport, busy).yes()); + for action in ActionId::ALL { + // Nothing may touch the edit list while an export is reading it -- + // and the palette does not: it repaints this window and writes one + // word to the user's own config file, which is why it is the one + // action besides the cancel that stays live here. + let allowed = action == ActionId::CancelExport || action == ActionId::Theme; + assert_eq!( + whole(action, busy).yes(), + allowed, + "{action:?} while an export reads the edit list" + ); + } + // The playhead frame is the engine's own rule, boundary included. + assert_eq!(frame_at(1.0, 30.), 30); + assert_eq!(frame_at(0.0, 30.), 0); + assert_eq!(frame_at(-1.0, 30.), 0); + // Where it hangs: at the pointer when it fits, back inside when not. + let viewport = size(px(800.), px(400.)); + assert_eq!(menu_at(point(px(10.), px(10.)), viewport, 150.), (10., 10.)); + assert_eq!( + menu_at(point(px(700.), px(380.)), viewport, 150.), + (800. - MENU_W, 250.) + ); + // A window smaller than the menu loses its bottom, never its top. + assert_eq!( + menu_at(point(px(90.), px(40.)), size(px(100.), px(50.)), 150.), + (0., 0.) + ); + // Every item is an action the registry knows, so the menu and the keys + // menu say the same thing about it -- and none of them is unreachable + // by keyboard, which is what makes the hint column worth drawing. + let keymap = Keymap::defaults(); + for action in MENU_ITEMS { + assert!(ActionId::ALL.contains(&action), "{action:?} is not listed"); + assert_ne!(keymap.display(action), "unbound", "{action:?}"); + } + // ...and the whole card still fits the 640x360 floor, however many items + // it grows to: the list is what scrolls where the window is too short + // for it, never the card that grows. + let items = MENU_ITEMS.len() + 1; // Properties + let floor = size(px(640.), px(360.)); + assert!(MENU_PAD * 2. + menu_rows_h(items, floor) <= 360., "too tall"); + assert!( + menu_rows_h(items, floor) / MENU_ROW_H >= 12., + "too few items visible to scan on the smallest window" + ); + assert_eq!( + menu_at(point(px(0.), px(0.)), floor, { + MENU_PAD * 2. + menu_rows_h(items, floor) + }), + (0., 0.) + ); + // The picker is the same card and the longest list in it is the palette + // family list, which grows every time somebody asks for more colours. + // Twelve of them still stand on screen *whole* at the floor -- so the + // list's `overflow_y_scroll` is a safety net rather than something a + // person has to find. The day a family makes this fail is the day the + // card owes the affordance line the inspector and the cards carry + // ("more below — scroll the …"): a row nobody knows is under the fold + // is a row that is not there, and no scroll bar says it. + let families = crate::ui::theme::PaletteId::ALL.len(); + assert_eq!( + menu_rows_h(families, floor), + families as f32 * MENU_ROW_H, + "{families} palettes no longer fit 640x360 -- the picker now needs \ + the 'more below' line and a keyboard cursor that scrolls into view" + ); + // ...and the detail beside each one is short enough to survive the + // right-hand column at that width instead of being truncated mid-word. + for id in crate::ui::theme::PaletteId::ALL { + assert!(id.detail().len() <= 30, "{id:?}: {:?}", id.detail()); + } +} + +/// Both menus, at the two things they can be opened on, and the box each +/// one is drawn in. Two rules, and the render obeys them by *calling* what +/// this calls -- [`menu_items`] and [`row_items`] are the only lists either +/// menu is built from, and [`menu_rows_h`] is the height each is both placed +/// by and drawn to: +/// +/// 1. a row exists only where the oracle lists the action for the very thing +/// that was right-clicked, so an item can never offer a video action on a +/// waveform (the complaint this comes from) and a new action added to +/// `MENU_ITEMS` cannot appear where it does not apply; +/// 2. the whole card is inside the window, wherever it was opened and +/// however long the list -- a menu drawn past the bottom edge is a menu +/// whose last items nobody can click. +#[test] +fn a_menu_offers_only_what_applies_and_is_drawn_inside_the_window() { + use keymap::ActionId; + let clip = Clip { + start: 30, + in_frame: 0, + out_frame: 60, + source: 0, + link: Some(1), + eq: None, + color: None, + fit: FitPolicy::default(), + speed: Speed::NORMAL, + }; + let ctx = |lane, image| Ctx { + clip: Some((clip, lane)), + image, + playhead: 60, + timeline: true, + ..Ctx::default() + }; + // The oracle is the whole of what the menu draws: every item it lists is + // one the oracle would list, and every item it leaves out is one the + // oracle hides -- there is no third answer, and no hand-written list. + for (lane, image) in [(Lane::V1, false), (Lane::A1, false), (Lane::V1, true)] { + let ctx = ctx(lane, image); + let rows = menu_items(ctx); + for action in MENU_ITEMS { + assert_eq!( + rows.contains(&action), + enable(action, ctx).listed(), + "{action:?} on {lane:?}, image={image}" + ); + } + } + // Sound has no picture settings; picture has no equalizer of its own; a + // still has no sound to scan. The user's own words: an audio clip must + // not be offered what only a picture can be given. + let sound = menu_items(ctx(Lane::A1, false)); + assert!(!sound.contains(&ActionId::Color), "{sound:?}"); + assert!(!sound.contains(&ActionId::Fit), "{sound:?}"); + assert!(sound.contains(&ActionId::Equalizer)); + let picture = menu_items(ctx(Lane::V1, false)); + assert!(!picture.contains(&ActionId::Equalizer), "{picture:?}"); + assert!(picture.contains(&ActionId::Color)); + assert!(!menu_items(ctx(Lane::V1, true)).contains(&ActionId::Silence)); + // The library menu is the same rule on the other panel: its items come + // off `row_items` and nothing else, and the two that change the timeline + // say why rather than being clicked and refused afterwards. + let live = RowCtx { + timeline: true, + usable: true, + ..RowCtx::default() + }; + for ctx in [ + live, + RowCtx { + usable: false, + ..live + }, + RowCtx { placed: 2, ..live }, + RowCtx { + exporting: true, + ..live + }, + RowCtx::default(), + ] { + let rows = row_items(ctx); + for item in ROW_ITEMS { + assert_eq!(rows.contains(&item), row_enable(item, ctx).listed()); + } + // Whatever the state, the two that need neither timeline nor edit + // list are offered: a file is always describable and findable. + assert!(row_enable(RowItem::Reveal, ctx).yes()); + assert!(row_enable(RowItem::Properties, ctx).yes()); + } + assert!(row_enable(RowItem::Add, live).yes()); + assert!( + !row_enable( + RowItem::Add, + RowCtx { + usable: false, + ..live + } + ) + .yes(), + "a file that cannot join this timeline is not an Add anybody can ask for" + ); + assert!(!row_enable(RowItem::Remove, RowCtx { placed: 1, ..live }).yes()); + assert!(!row_enable(RowItem::Add, RowCtx::default()).yes()); + // Every refusal is short enough to sit in the hint column beside its + // label, the clip menu's rule. + for item in ROW_ITEMS { + for ctx in [live, RowCtx::default()] { + if let Some(why) = row_enable(item, ctx).why() { + assert!(!why.is_empty() && why.len() <= 30, "{why:?}"); + } + } + } + // ...and the box. Every window from the floor up, every corner of it, + // and every list length either menu can have: the card is placed by + // `MENU_PAD * 2 + menu_rows_h` and drawn to it, so this is the card. + for viewport in [ + size(px(640.), px(360.)), + size(px(800.), px(600.)), + size(px(1280.), px(690.)), + // Smaller than the floor the layout is sized for: it still may not + // draw outside the window it has. + size(px(320.), px(200.)), + ] { + for rows in 1..=MENU_ITEMS.len() + 1 { + let h = MENU_PAD * 2. + menu_rows_h(rows, viewport); + for at in [ + point(px(0.), px(0.)), + point(px(10.), px(10.)), + // The click that started all this: low in the window, where + // the menu used to hang off the bottom edge. + point(px(0.), viewport.height - px(4.)), + point(viewport.width - px(4.), viewport.height - px(4.)), + point(viewport.width * 2., viewport.height * 2.), + ] { + let (x, y) = menu_at(at, viewport, h); + assert!(x >= 0. && y >= 0., "{x},{y} outside {viewport:?}"); + assert!( + x + MENU_W <= f32::from(viewport.width) + 0.01, + "{rows} rows at {at:?} hang off the right of {viewport:?}" + ); + assert!( + y + h <= f32::from(viewport.height) + 0.01, + "{rows} rows at {at:?} hang off the bottom of {viewport:?}" + ); + } + } + } + // On any window with the room, the whole list is drawn rather than + // twelve rows of it and a scroll nobody is told about. + let items = MENU_ITEMS.len() + 1; + let real = size(px(1280.), px(690.)); + assert_eq!(menu_rows_h(items, real), items as f32 * MENU_ROW_H); + assert!(menu_rows_h(items, size(px(640.), px(360.))) < items as f32 * MENU_ROW_H); +} + +/// The other half of the keys menu's guarantee, and the audit this batch was +/// asked for kept as a test: no action may be a stroke and nothing else. +/// The actions card answers it for all of them at once -- its rows come off +/// [`ActionId::ALL`], so a fortieth action is on it the moment it exists and +/// there is no hand-written list here to fall behind. +#[test] +fn every_action_is_reachable_without_the_keyboard() { + use keymap::ActionId; + let source = ui_source(); + let source = source.as_str(); + let element = |id: &str| source.contains(&format!("\"{id}\"")); + let listed: Vec = keys_rows() + .iter() + .filter_map(|r| match r { + KeyRow::Act(a) => Some(*a), + _ => None, + }) + .collect(); + for action in ActionId::ALL { + assert_eq!( + listed.iter().filter(|a| **a == action).count(), + 1, + "{action:?} is reachable by keyboard only" + ); + } + // The snap has a door of its own as well as its row on the card: the + // button beside the zoom, which says which way it is set as well as + // setting it. + assert!(element("snap"), "no snap button beside the zoom"); + // And the card is a door the pointer can open: the panel's own button. + assert!(element("keys"), "no way to open the actions card"); + // The card-local strokes have the same rule, and each of them is a thing + // on its card: the graph and its two buttons, the colour bars and their + // reset, the speed bar and its presets, and the silence card's rows -- + // whose steppers are the pointer's only way to a threshold. + for id in [ + "eq-graph", + "eq-reset", + "eq-spectrum", + "color-bar", + "color-reset", + "speed-bar", + "speed-preset", + "silence-row", + "silence-step", + "mix-row", + "mix-step", + "silence-apply", + "export-confirm", + ] { + assert!(element(id), "{id} is not on any card"); + } + // ...and each one is named by the row that carries its stroke, so a + // card-local key added to `FIXED` with nothing to click fails here + // instead of being noticed by whoever tries to use the card without a + // keyboard. `KeyRow::Fixed` is "shown and never offered", which used to + // mean the twenty-eight rows below were the one part of this editor no + // reachability test read. + for fixed in keymap::FIXED.iter() { + match fixed.reach { + keymap::Reach::Click(id) => assert!( + element(id), + "{:?} ({}) points at {id}, which is on no card", + fixed.chord, + fixed.label + ), + // Nothing to click by decision, not by omission: getting out of + // a card, and the hold that repeats what a drag already does. + keymap::Reach::Gesture => {} + } + } +} + +/// The other half of "getting out of a card is a `Reach::Gesture`": the +/// gesture has to exist. Every card's scrim closes it on a press, so a hand +/// that never touches the keyboard can shut every one of them -- for seven +/// cards `esc` was the only exit, which is the same complaint as an action +/// reachable by stroke alone, said about the way out instead of the way in. +/// +/// Read off [`Player::modal`] rather than off a list written here: a card +/// counted there and not closed by [`Player::close_card`] fails this test +/// the day it is added, which is the only way the two stay in step. +#[test] +fn every_card_closes_without_the_keyboard() { + let source = ui_source(); + let source = source.as_str(); + // A fn's source, up to the next one: enough of a body to scan. + let body = |name: &str| -> &str { + let at = source + .find(&format!("fn {name}(")) + .unwrap_or_else(|| panic!("no fn {name} in main.rs")); + let rest = &source[at..]; + &rest[..rest[1..].find("\n fn ").map_or(rest.len(), |e| e + 1)] + }; + for card in [ + "keys_overlay", + "export_card", + "eq_card", + "color_card", + "speed_card", + "mix_card", + "silence_card", + ] { + let src = body(card); + assert!( + src.contains("this.close_card()"), + "{card}'s scrim swallows the press without closing the card: \ + escape is the only way out of it" + ); + assert!( + src.contains("MouseButton::Left, swallow"), + "{card}'s body does not swallow its own presses, so a press on \ + one of its controls would close the card under itself" + ); + } + // ...and every state that makes the window modal is a state that press + // clears. `exporting()` is not one of them: a running export is a job + // with a cancel button, not a card with a scrim. + let close = body("close_card"); + for field in body("modal").split("self.").skip(1).filter_map(|rest| { + let name: String = rest + .chars() + .take_while(|c| c.is_alphanumeric() || *c == '_') + .collect(); + (!rest[name.len()..].starts_with('(')).then_some(name) + }) { + assert!( + close.contains(&format!("self.{field}")), + "{field} makes the window modal and `close_card` leaves it set: \ + that card cannot be closed by pointer" + ); + } +} + +/// A clip too short to hit is still a clip: at a far zoom-out its box is +/// drawn [`HIT_MIN`] wide rather than the fraction of a pixel it is worth, +/// because a box nobody can put a pointer on cannot be selected, dragged, +/// trimmed or given a menu -- and an invisible unselectable take is strictly +/// worse than one drawn a few pixels too wide. +#[test] +fn a_clip_box_is_never_narrower_than_its_target() { + // Two seconds on a bed showing an hour: a fifth of a pixel. + let far = Scale { + pps: 0.1, + start: 0., + }; + assert!(far.width_px(2.) < 1., "the fixture is not zoomed out enough"); + assert_eq!(clip_width(far.width_px(2.)), HIT_MIN); + // Zero is the floor's own case: a clip trimmed to nothing, and the + // width a lane draws before its first frame is measured. + assert_eq!(clip_width(0.), HIT_MIN); + // What is already wide enough keeps its own width, to the pixel: the + // floor is a floor and never a resize. + let near = Scale::default(); + assert_eq!(clip_width(near.width_px(5.)), near.width_px(5.)); + // ...and the padding is not trimmable: the strips are asked of the + // clip's own width, so a box drawn wider than its length keeps all of + // that box as a body to select and drag by ([`trims`]). + assert!(!trims(far.width_px(2.))); + assert!(clip_width(far.width_px(2.)) >= HIT_MIN); +} + +/// What the Detach and Group items do to a real timeline: a music video's +/// sound comes off its picture, Delete on the loose half takes that half +/// only, undo puts both back, and Group makes the two one take again -- +/// whole-take delete and all. +#[test] +fn a_detached_half_is_removed_alone_and_groups_again() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + assert!(whole_take(&session, Lane::V1, 0), "one take to start with"); + assert!(whole_take(&session, Lane::A1, 0)); + let frames = session.lane_clips(Lane::V1)[0].len(); + + // Detach audio: neither half is a whole take any more, so Delete on + // either leaves the other exactly where it is. + assert!(session.ungroup(Lane::V1, 0)); + assert!( + !whole_take(&session, Lane::A1, 0), + "the sound is a half now" + ); + assert!(!whole_take(&session, Lane::V1, 0), "and so is the picture"); + assert!(session.lift_clip(Lane::A1, 0)); + assert!(session.lane_clips(Lane::A1).is_empty(), "the sound went"); + assert_eq!(session.lane_clips(Lane::V1).len(), 1, "the picture stayed"); + assert_eq!(session.lane_clips(Lane::V1)[0].len(), frames, "untrimmed"); + + // One undo per edit, the removal then the detach. + assert!(session.undo()); + assert_eq!(session.lane_clips(Lane::A1).len(), 1, "the sound is back"); + assert!(session.undo()); + assert!(whole_take(&session, Lane::A1, 0), "one take again"); + + // Group: the partner is the clip covering these very frames on the + // other track, which is what the item hands the engine. + assert!(session.ungroup(Lane::V1, 0)); + assert_eq!(span_partner(&session, Lane::V1, 0), Some((Lane::A1, 0))); + session + .group(Lane::V1, 0, Lane::A1, 0) + .expect("both halves still cover the same frames"); + assert!( + whole_take(&session, Lane::A1, 0), + "a take that ripples again" + ); + assert_eq!( + span_partner(&session, Lane::V1, 0), + None, + "and nothing left on another track to group with" + ); +} + +/// Which clip Group reaches when more than one covers the span: the sound, +/// whatever order the lanes are stored in. A project file may hold them in +/// any order -- a video layer *before* the audio lane among them -- and +/// "group this" means the other half of the take, never the layer above it. +#[test] +fn group_reaches_the_sound_before_a_video_layer_over_it() { + use engine::project::LaneKind; + + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + let v2 = session.add_lane(LaneKind::Video); + // A bare layer, through the one-lane door: a *drop* on V2 brings the + // file's sound down with it and would put a third clip over this span. + let whole = session.lane_clips(Lane::V1)[0]; + assert!( + session.place_at(v2, 0.0, whole), + "a layer covering the same frames as the take" + ); + + // Saved and loaded back with the lanes in the order a hand-written + // project may hold them: the sound last, behind the layer. + let dir = engine::scratch::Scratch::dir("ve_group"); + let file = dir.join("lanes.edith"); + session.save_project(&file).expect("save the project"); + let text = std::fs::read_to_string(&file).expect("read it back"); + let (sound, rest): (Vec<&str>, Vec<&str>) = + text.lines().partition(|l| l.starts_with("audio ")); + std::fs::write( + &file, + format!("{}\n{}\n", rest.join("\n"), sound.join("\n")), + ) + .expect("write the reordered project"); + let mut session = PlaybackSession::open_project(&file).expect("it loads as it stands"); + std::fs::remove_dir_all(&dir).ok(); + assert_eq!( + session.lanes(), + vec![Lane::V1, v2, Lane::A1], + "the sound is the last lane there" + ); + + // Detached, so Group has a choice to get wrong: the layer covers these + // frames too, and it is the lane the walk meets first. + assert!(session.ungroup(Lane::V1, 0)); + // Group on the picture reaches the sound, not that layer. + assert_eq!(span_partner(&session, Lane::V1, 0), Some((Lane::A1, 0))); + session + .group(Lane::V1, 0, Lane::A1, 0) + .expect("the two halves cover the same frames"); + // ...and a lane of its own kind is still groupable, once the sound is + // spoken for: two video lanes may be one take. + assert_eq!( + span_partner(&session, Lane::V1, 0), + Some((v2, 0)), + "the layer is what is left to group with" + ); +} + +/// The refusal path, end to end against the real files: an incompatible +/// import changes nothing, and the library mirrors `sources()` 1:1, so a +/// refused file cannot leave a row behind. +#[test] +fn a_refused_import_leaves_no_row_and_an_accepted_one_is_whole() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + // Silent like the engine suite: this opens the real device. + session.set_gain(0.0); + assert_eq!(session.sources().len(), 1); + // 640x360 joins now (the project canvas places it), and so does a file + // with no sound (it plays silence over its span). What is left is one + // output device: a mono track cannot join a stereo timeline. + let refusal = session + .import(&asset("test_ac3.mp4")) + .expect_err("a mono track must not join a stereo timeline") + .to_string(); + assert!(refusal.contains("audio"), "refusal must name it: {refusal}"); + assert_eq!(session.sources().len(), 1, "a refusal added a row"); + // An accepted one does add a row, and it reads as the whole file: 4 s + // at 30 fps, its own length and not one taken off the lanes. + session.import(&asset("test_av2.mp4")).expect("av2 matches"); + assert_eq!(session.sources().len(), 2); + let second = session.sources()[1].path.clone(); + assert_eq!(session.file_frames(&second), 120); + assert_eq!(timecode(120. / 30., 30.), "00:00:04:00"); +} + +/// What the Add button and a dropped row both do, minus the pointer: the +/// clip [`Player::insert_source`] builds, put in where the playhead is. One +/// call, so what a drop does cannot drift from what the button does. +#[test] +fn adding_a_row_drops_the_whole_source_in_at_the_playhead() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + session.import(&asset("test_av2.mp4")).expect("av2 matches"); + // In the library only: the 5 s the fixture is, still. + assert_eq!(session.timeline_duration(), 5.0); + // Two seconds in, which is inside the first take: the insert splits it. + session.seek(2.0); + let second = session.sources()[1].path.clone(); + let frames = session.file_frames(&second); + // Through the engine door `insert_source` uses, with the row's own + // stream: the button, the drop and this are one call. + assert!( + session + .place_stream_at(2.0, &second, 0, None) + .expect("av2 is already on the timeline") + ); + // The whole of source 1 went in and nothing was painted over: the + // timeline is longer by exactly that file. + assert_eq!(session.timeline_duration(), 9.0); + let (video, audio) = (session.lane_clips(Lane::V1), session.lane_clips(Lane::A1)); + // One take, not a video clip with no sound under it: both lanes hold + // the same clip at the same place, in the same group. + let at = |lane: &[Clip]| { + *lane + .iter() + .find(|c| c.start == 60) + .expect("inserted at 2 s") + }; + assert_eq!(at(video), at(audio)); + assert_eq!(at(video).source, 1); + assert_eq!(at(video).len(), frames); + assert!(at(video).link.is_some()); + assert_eq!(video.len(), audio.len()); + + // The same door with a *second audio stream* of a file already there: + // a new source entry, the same picture, and the row that was dragged + // is what plays. This is the whole user-facing point of the slice. + let mut session = + PlaybackSession::open(asset("test_multilang.mp4")).expect("open the fixture"); + session.set_gain(0.0); + let path = session.sources()[0].path.clone(); + let frames = session.file_frames(&path); + let end = session.timeline_duration(); + assert!( + session + .place_stream_at(end, &path, 1, None) + .expect("the French track shares the timeline's parameters") + ); + assert_eq!(session.sources()[1].audio_stream, 1); + assert_eq!(session.timeline_duration(), end * 2.0); + // Both rows are the same file, so both rows are that file's length -- + // the second one before any clip of its own existed. + assert_eq!(session.file_frames(&path), frames); +} + +/// The drop a hand actually makes: a library row let go on the *empty* bed +/// past the last clip, which is most of the bed on any timeline shorter +/// than the window. The whole chain the release runs, minus gpui's own +/// pointer read -- [`Player::place_frame`]'s [`landing`], the frame back +/// through the rate as [`Player::insert_source`] hands it over, and the one +/// engine door a row goes through -- and the head lands on the frame the +/// ghost was drawn on, black in front of it. It used to be swallowed by the +/// clipboard's clamp inside `Project::paste` and appended after the last +/// clip wherever it was let go, which is the bug this pins. +#[test] +fn a_row_dropped_on_the_open_bed_lands_under_the_pointer() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + session.import(&asset("test_av2.mp4")).expect("av2 matches"); + let second = session.sources()[1].path.clone(); + let fps = session.meta().frame_rate; + assert_eq!(session.timeline_duration(), 5.0); + // 5 s of timeline on a bed 30 s wide: the open bed past the last clip + // is five sixths of it. + let bed: Bounds = Bounds { + origin: point(px(12.), px(400.)), + size: size(px(600.), px(LANE_H)), + }; + let scale = Scale { + pps: 20., + start: 0., + }; + + // What `Player::place_frame` answers for a pointer 200 px along the + // bed: ten seconds in, five seconds past the end of the timeline, and + // no mark anywhere near enough to pull it back. + let clips = [session.lane_clips(Lane::V1), session.lane_clips(Lane::A1)]; + let marks = snap_marks(&clips, None, frame_at(session.now(), fps)); + let under = frame_at(scale.time_at(px_along(px(212.), bed)), fps); + let (at, cue) = landing(under, 0, 0, true, scale.snap_frames(fps), &marks); + assert_eq!((at, cue), (300, None), "the pointer is on frame 300"); + + // ...and what the release does with it: the frame back through the same + // rate every box is drawn at, into the door the Add button uses too. + assert!( + session + .place_stream_at(f64::from(at) / fps, &second, 0, None) + .expect("av2 is already on this timeline") + ); + let head = |lane| { + session + .lane_clips(lane) + .last() + .copied() + .expect("the dropped clip") + }; + assert_eq!( + head(Lane::V1).start, + at, + "the drop landed somewhere other than under the pointer" + ); + assert_eq!(head(Lane::A1).start, at, "...and its sound with it"); + assert!(head(Lane::V1).link.is_some(), "one grouped take"); + assert_eq!(head(Lane::V1).link, head(Lane::A1).link); + // The bed in front of it stays black: nothing was stretched to reach + // it, and the 4 s file is the whole of what was added. + assert_eq!(session.timeline_duration(), 14.0); +} + +/// Remove from library, through the door the menu item uses +/// ([`Player::remove_source`] calls exactly this): refused by name while +/// clips play from the file, and once they do not the row leaves the list. +#[test] +fn removing_a_row_is_refused_while_it_plays_and_takes_the_row_away() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + // Imported, then dragged onto the end: an import alone fills the + // library, and a row with no clip is removable without any refusal to + // test. This one has to have a take on the timeline. + session.import(&asset("test_av2.mp4")).expect("av2 matches"); + let second = session.sources()[1].path.clone(); + let end = session.timeline_duration(); + assert!( + session + .place_stream_at(end, &second, 0, None) + .expect("a file just imported is on this timeline") + ); + let streams = HashMap::new(); + let rows = |session: &PlaybackSession| { + library_rows(session.sources(), &streams, &HashMap::new(), None, |_| 0).len() + }; + assert_eq!(rows(&session), 2, "a row per source"); + + let refusal = session + .remove_source(&second, 0) + .expect_err("its take is still on the timeline") + .to_string(); + assert!(refusal.contains("still plays"), "{refusal}"); + assert!( + refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"), + "the refusal names the lanes to clear: {refusal}" + ); + assert_eq!(rows(&session), 2, "and the row is still there"); + + // Delete that take -- the whole group, from either half -- and the file + // can go. The list is what says so. + let last = session.lane_clips(Lane::V1).len() - 1; + assert!(session.delete_clip(Lane::V1, last)); + session + .remove_source(&second, 0) + .expect("nothing plays av2 any more"); + assert_eq!(rows(&session), 1, "the row went with it"); + assert_eq!(session.sources().len(), 1); + // The one file left is held to the same rule and no other: its own take + // is still on the lanes, so it stays... + let first = session.sources()[0].path.clone(); + let refusal = session + .remove_source(&first, 0) + .expect_err("its take is still on the timeline") + .to_string(); + assert!(refusal.contains("still plays"), "{refusal}"); + // ...and once nothing plays it, the *last* row goes too. What is left + // is the empty library `Player::close_session` turns back into the + // window the editor launches as -- the user-reported bug was that this + // very removal was refused, leaving a row that could never be taken + // out. + assert!(session.delete_clip(Lane::V1, 0)); + session + .remove_source(&first, 0) + .expect("the only row goes like any other"); + assert_eq!(rows(&session), 0, "an empty library"); + assert!(session.sources().is_empty()); + // And it is still a session: silent, empty, and asked for its length + // rather than panicking on a source list that is not there. + assert_eq!(session.timeline_duration(), 0.0); + assert!( + session.save_project(&asset("nothing.edith")).is_err(), + "a project naming no file could never be opened again, so it is not written" + ); + // A row this timeline never had is refused, not panicked on. + assert!(session.remove_source(&second, 0).is_err()); +} + +/// The clipboard after a library removal. A copied clip names its file by +/// index and a removal renumbers the list, so this is the difference +/// between pasting the take that was copied and pasting **another file** +/// over the same range ([`clipboard_after_remove`], called by +/// [`Player::remove_source`]). +#[test] +fn a_copied_clip_is_renumbered_or_dropped_when_a_row_leaves_the_library() { + let clip = |source: usize| Clip { + start: 0, + in_frame: 0, + out_frame: 30, + source, + link: None, + eq: None, + color: None, + fit: Default::default(), + speed: Default::default(), + }; + // Copied from source 2, source 0 removed: the same file is source 1 now. + assert_eq!( + clipboard_after_remove(Some(clip(2)), 0).map(|c| c.source), + Some(1), + "the clipboard follows its file down the list" + ); + // Copied from a source *before* the one that went: untouched. + assert_eq!( + clipboard_after_remove(Some(clip(0)), 2).map(|c| c.source), + Some(0) + ); + // Copied from the row that was just removed: there is nothing left to + // paste, and pasting the next file along would be a lie. + assert!(clipboard_after_remove(Some(clip(1)), 1).is_none()); + assert!(clipboard_after_remove(None, 0).is_none()); +} + +/// The trim-a-clip path through the doors the edge drag uses: +/// [`Player::trim_to`] clamps the pointer with `trim_room` and +/// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less +/// of its file, the sound linked to it follows, the head trim moves the +/// in-point, and one undo takes a whole gesture back. +/// +/// The routing *to* these doors -- the 6 px edge strip claiming the press +/// the clip's own body-drag would otherwise take -- is gpui hitbox +/// behaviour (`occlude`) and is not reachable without a window. +#[test] +fn a_clip_trimmed_by_its_edge_plays_less_of_its_file() { + use engine::project::Edge; + + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + let whole = session.lane_clips(Lane::V1)[0]; + let full = session.timeline_duration(); + assert_eq!( + session.trim_room(Lane::V1, 0, Edge::End), + Some((whole.start + 1, whole.end())), + "the file's own last frame is how far the tail goes" + ); + assert!( + !session.trim_clip(Lane::V1, 0, Edge::End, 9_999), + "it already plays all of it" + ); + + // Pulled in by a third: the timeline ends earlier and the sound with it. + let shorter = whole.end() - whole.len() / 3; + assert!(session.trim_clip(Lane::V1, 0, Edge::End, shorter)); + assert_eq!(session.lane_clips(Lane::V1)[0].end(), shorter); + assert_eq!( + session.lane_clips(Lane::A1)[0].end(), + shorter, + "the linked sound was trimmed with the picture" + ); + assert!(session.timeline_duration() < full, "and plays out earlier"); + + // ...and dragged back out, as far as the file goes and no further. + assert!(session.trim_clip(Lane::V1, 0, Edge::End, 9_999)); + assert_eq!( + session.lane_clips(Lane::V1)[0], + whole, + "the whole take back" + ); + + // The head takes the in-point with it, so what plays at the new start + // is source frame 10 rather than source frame 0. + assert!(session.trim_clip(Lane::V1, 0, Edge::Start, 10)); + let head = session.lane_clips(Lane::V1)[0]; + assert_eq!((head.start, head.in_frame), (10, 10)); + assert_eq!(session.lane_clips(Lane::A1)[0].in_frame, 10, "sound too"); + assert_eq!( + session.trim_room(Lane::V1, 0, Edge::Start).map(|r| r.0), + Some(0), + "and it may be pulled back out to the file's first frame" + ); + + assert!(session.undo(), "one step for the whole drag"); + assert_eq!(session.lane_clips(Lane::V1)[0], whole); +} + +/// The move-a-clip-between-tracks path through the door the drop uses +/// ([`Player::move_clip`] calls exactly this): the clip changes row, the +/// *picture* comes from the new row afterwards -- which is what "it plays +/// from there" means -- and one undo puts it back. +#[test] +fn a_clip_dragged_onto_another_track_plays_from_it() { + use engine::project::LaneKind; + + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + let v2 = session.add_lane(LaneKind::Video); + assert_eq!(session.video_clip_at(0.0), Some((Lane::V1, 0))); + + assert!(session.move_clip_to(Lane::V1, 0, v2, 0), "V1 -> V2"); + assert!(session.lane_clips(Lane::V1).is_empty(), "it left V1"); + assert_eq!(session.lane_clips(v2).len(), 1, "and landed on V2"); + assert_eq!( + session.video_clip_at(0.0), + Some((v2, 0)), + "the picture now comes from V2" + ); + assert_eq!(session.lane_clips(Lane::A1).len(), 1, "its sound stayed"); + + // Dropped on a lane of the other kind it is refused and nothing moves -- + // the notice the front-end shows for it says which kind of lane to use. + // (The other refusal, landing on another clip, is the engine's own test + // `move_clip_keeps_the_frames_and_refuses_the_rest`.) + assert!(!session.move_clip_to(v2, 0, Lane::A1, 0), "picture on A1"); + assert_eq!(session.lane_clips(v2).len(), 1, "and it stayed on V2"); + assert!( + session.move_clip_to(v2, 0, Lane::V1, 0), + "dragged back down" + ); + + // One undo per move, and each is a single step. + assert!(session.undo(), "the drag back"); + assert_eq!(session.video_clip_at(0.0), Some((v2, 0))); + assert!(session.undo(), "the drag up"); + assert_eq!(session.video_clip_at(0.0), Some((Lane::V1, 0))); + assert!(session.lane_clips(v2).is_empty()); +} + +/// The add-a-track path end to end through the doors the buttons and the +/// drop use: `+ V` adds a row, a library row let go over it lands there and +/// nowhere else, Delete on it leaves the lanes under it where they are, and +/// undo takes the whole thing back one step at a time. +#[test] +fn a_track_can_be_added_dropped_on_edited_and_taken_back() { + use engine::project::LaneKind; + + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1]); + // What the `+ V` button asks for, and what the row it draws is called. + let v2 = session.add_lane(LaneKind::Video); + assert_eq!(v2.label(), "V2"); + assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1, v2]); + assert!(session.lane_clips(v2).is_empty()); + // A library row let go over that row: the same door the Add button + // uses, told which lane it was let go over. + let path = session.sources()[0].path.clone(); + assert!( + session + .place_stream_at(1.0, &path, 0, Some(v2)) + .expect("its own file is on this timeline") + ); + assert_eq!(session.lane_clips(v2).len(), 1, "the drop landed on V2"); + assert_eq!(session.lane_clips(v2)[0].start, 30, "at the playhead"); + // ...with the sound it came with, on the row of its own the drop added: + // a file with audio dropped on a layer used to land silent. + let a2 = Lane::new(LaneKind::Audio, 1); + assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1, v2, a2]); + assert_eq!(session.lane_clips(a2), session.lane_clips(v2), "same take"); + assert_eq!( + session.lane_clips(v2)[0].link, + session.lane_clips(a2)[0].link, + "grouped, so a drag moves both" + ); + // And nowhere else: the first pair is exactly as it was, one take each. + assert_eq!(session.lane_clips(Lane::V1).len(), 1); + assert_eq!(session.lane_clips(Lane::A1).len(), 1); + // ...and it is a project that saves and opens again as it stands: a + // grouped pair on a further row is what the file has to carry. + let dir = engine::scratch::Scratch::dir("ve_layer"); + let file = dir.join("layer.edith"); + session.save_project(&file).expect("save the project"); + let back = PlaybackSession::open_project(&file).expect("it loads as it stands"); + std::fs::remove_dir_all(&dir).ok(); + assert_eq!(back.lanes(), session.lanes()); + for lane in back.lanes() { + assert_eq!(back.lane_clips(lane), session.lane_clips(lane), "{lane:?}"); + } + // Delete on the layer is a lift: it is laid over the timeline, so + // closing a hole under it would drag the take beneath out of step with + // it. The take on the first pair is still a take, and still ripples. + assert!(!whole_take(&session, v2, 0)); + assert!(whole_take(&session, Lane::V1, 0)); + assert!(whole_take(&session, Lane::A1, 0)); + assert_eq!(a2.label(), "A2"); + assert!(session.lift_clip(v2, 0)); + assert!(session.lane_clips(v2).is_empty()); + assert_eq!(session.lane_clips(Lane::V1).len(), 1, "V1 stayed put"); + assert_eq!( + session.lane_clips(a2).len(), + 1, + "a lift takes the half it names: the sound is still there to lift" + ); + assert!(session.lift_clip(a2, 0)); + + // A second audio lane used to be what an mp4 export could not write -- + // it copied one AAC track and a mix is not a copy. It mixes now + // (`export::copy_audio`), so no row is greyed by a count of lanes. + for format in [Format::Mp4, Format::Av1, Format::Av1Mp4] { + assert_eq!( + format_refusal(&session, format), + None, + "two audio lanes are a mix, not a refusal" + ); + } + + // Undo, one edit at a time and backwards: the lift of the sound, the + // lift of the picture, the drop on V2 with the lane A2 it added, and + // last the lane V2 -- an added track is one step like every other edit. + for lanes in [4, 4, 3, 2] { + assert!(session.undo()); + assert_eq!(session.lanes().len(), lanes); + } + assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1]); + assert_eq!(session.lane_clips(Lane::V1).len(), 1); + assert_eq!(format_refusal(&session, Format::Mp4), None); +} + +#[test] +fn a_source_is_only_ever_asked_for_its_peaks_once() { + let (a, b) = (asset("test_av.mp4"), asset("test_av2.mp4")); + // Two files, and two streams of the first: three envelopes, because + // one file's two audio tracks are two different waveforms. + let sources = [ + Source { + path: a.clone(), + audio_stream: 0, + }, + Source { + path: a.clone(), + audio_stream: 1, + }, + Source { + path: b.clone(), + audio_stream: 0, + }, + ]; + let keys = |s: &[Source]| { + s.iter() + .map(|s| (s.path.clone(), s.audio_stream)) + .collect::>() + }; + let mut waves: HashMap<(PathBuf, usize), Wave> = HashMap::new(); + assert_eq!(unseen_sources(&sources, &waves), keys(&sources)); + // The entry goes in when the decode *starts*, so the sixty repaints a + // second that happen while it runs must not start it again -- which is + // what this asserts about a key whose value is not an answer yet. + waves.insert((a.clone(), 0), Wave::Loading); + assert_eq!( + unseen_sources(&sources, &waves), + keys(&sources[1..]), + "the file's other stream is a key of its own" + ); + // A file with no audio is an answer like any other: never re-asked. + waves.insert((a, 1), Wave::Silent); + waves.insert((b.clone(), 0), Wave::Silent); + assert!(unseen_sources(&sources, &waves).is_empty()); + // The stream probe is per *file*: the two entries of `a` ask once. + let mut streams: HashMap> = HashMap::new(); + assert_eq!( + unseen_paths(&sources, &streams), + vec![asset("test_av.mp4"), b] + ); + streams.insert(asset("test_av.mp4"), Vec::new()); + assert_eq!(unseen_paths(&sources, &streams).len(), 1); +} + +#[test] +fn the_add_button_is_dead_unless_it_would_do_something() { + let picked = (PathBuf::from("/m/0.mp4"), 0); + assert!(can_add(Some(&picked), true, false)); + // Nothing picked, nothing to put it on, or an export reading the very + // edit list this would change. + assert!(!can_add(None, true, false)); + assert!(!can_add(Some(&picked), false, false)); + assert!(!can_add(Some(&picked), true, true)); +} + +#[test] +fn the_media_column_never_takes_the_picture_over() { + for window in [360., 640., 1280., 1920., 3840.] { + let w = crate::library_w(window); + // The whole point of the budget: the picture keeps the majority of + // the row at every size a window can be. + assert!(w <= window / 3., "{window}px window gave the list {w}px"); + assert!(w >= LIBRARY_MIN_W.min(window / 3.), "{window}px: {w}px"); + assert!(w <= LIBRARY_MAX_W); + } + // It yields: a narrower window gives the list less, never the same. + assert!(crate::library_w(640.) < crate::library_w(1280.)); + // Rows are clickable, so WCAG 2.5.8 binds them like every other target, + // and a name over a timecode has to fit inside one. + assert!(ROW_H >= HIT_MIN); + assert!(SWATCH_W < LIBRARY_MIN_W); +} + +#[test] +fn the_window_is_named_after_the_program_and_what_is_open() { + assert_eq!(window_title("test_av.mp4"), "test_av.mp4 — edith"); + // An empty window is the program, not "no file open — edith". + assert_eq!(window_title(NO_FILE), "edith"); +} + +#[test] +fn frac_along_measures_from_the_elements_own_left_edge() { + // A ruler inset by the panel's 12 px padding: window x is not bar x. + let bar: Bounds = Bounds { + origin: point(px(12.), px(400.)), + size: size(px(200.), px(6.)), + }; + assert_eq!(frac_along(px(12.), bar), 0.); + assert_eq!(frac_along(px(112.), bar), 0.5); + assert_eq!(frac_along(px(212.), bar), 1.); + // Outside the bar (a click that slid off) clamps, never extrapolates. + assert_eq!(frac_along(px(0.), bar), 0.); + assert_eq!(frac_along(px(9999.), bar), 1.); + // Never painted: no division by zero, no NaN reaching seek(). + assert_eq!(frac_along(px(50.), Bounds::default()), 0.); + + // The equalizer's axis is the other one, and reads the same way. + let graph: Bounds = Bounds { + origin: point(px(12.), px(60.)), + size: size(px(296.), px(EQ_GRAPH_H)), + }; + assert_eq!(frac_down(px(60.), graph), 0.); + assert_eq!(frac_down(px(60. + EQ_GRAPH_H / 2.), graph), 0.5); + assert_eq!(frac_down(px(9999.), graph), 1.); + // Never painted reads as flat: an unpainted graph must not slam a band + // to +12 dB on the first press. + assert_eq!(frac_down(px(50.), Bounds::default()), 0.5); +} diff --git a/crates/app/src/tests/layout.rs b/crates/app/src/tests/layout.rs new file mode 100644 index 0000000..eed39e7 --- /dev/null +++ b/crates/app/src/tests/layout.rs @@ -0,0 +1,1093 @@ +//! What is drawn and where: the toolbar, the theme, the notices, the lanes +//! and their marks, the tints, the subtitle rows and the sliders. + +use super::*; + +/// The edit toolbar against the 640x360 floor the whole editor is measured +/// at. It does not fit and cannot be made to -- so what it may never do is +/// *hide* the tail: the row scrolls, and the door to everything scrolled +/// off it is pinned outside the scrolling box. +#[test] +fn toolbar_fits_the_smallest_window() { + let toolbar = src_text("ui/toolbar.rs"); + let row = &toolbar[toolbar.find("pub(crate) fn toolbar(").expect("the toolbar")..]; + // Every button in the row is a hit target, so none of them is narrower + // than `HIT_MIN`, and they sit in 8 px gaps inside the row's own 12 px + // padding. + let buttons = row.matches("action_control(").count(); + assert!(buttons >= 11, "the row's buttons moved; this scan is blind"); + // The row is shorter than it was -- the project's own settings (size, + // rate, HDR) are the inspector's now and the transport is the + // picture's -- so whether it fits at 640 px depends on the words in it + // and is not something this scan can measure. What it can hold to is + // the rule: "it scrolls" is not "it can be found", so the door to + // whatever is off the right edge is pinned outside the scrolling box + // and the card it opens carries every action there is + // (`every_action_is_on_the_actions_card`). + assert!( + row.contains("\"controls-more\""), + "nothing pinned beside the scrolling row: the tail is unreachable at 640 px" + ); + assert_eq!(row.matches("overflow_x_scroll").count(), 1); + assert!( + row.find("\"controls-more\"") > row.find("overflow_x_scroll"), + "the pinned door is inside the row it is meant to outlive" + ); + // ...and nothing in the row decides for itself whether it can act: the + // oracle does, once, for the key and the button alike. A raw `control(` + // in here is a button that can go dead while its stroke still fires -- + // the bug this redesign was called in for. + assert_eq!( + row.matches("\n .child(control(").count(), + 0, + "a toolbar button bypassing the availability oracle" + ); +} + +/// The whole reason `ui/theme.rs` exists: a colour written anywhere else is +/// a colour the next palette sweep will miss, which is exactly how 186 grey +/// calls survived every previous attempt at this. +#[test] +fn no_colour_is_written_outside_the_theme() { + let source = ui_source(); + let stray: Vec<&str> = source + .lines() + .filter(|l| l.contains("rgb(0x") || l.contains("rgba(0x")) + .collect(); + assert!(stray.is_empty(), "colour written outside the theme: {stray:?}"); +} + +/// "It scrolls" is not "it can be found": at the 640x360 floor the timeline +/// takes its share and no more, so a third track is behind a scroll -- and +/// the line that says so has to keep telling the truth *while* the column is +/// being scrolled, or it is an instruction nobody can carry out. +#[test] +fn the_line_about_what_is_below_the_fold_counts_what_is_still_below_it() { + // The timeline is a region and not the window: its chrome and one whole + // lane fit the share it may take at the floor. + let floor = 360. * TIMELINE_SHARE; + assert!( + TIMELINE_FIXED_H + LANE_H <= floor, + "{TIMELINE_FIXED_H} px of chrome and a lane will not fit {floor} px" + ); + // What is left over is measured in whole lanes, at least one. + assert_eq!(lanes_shown(LANE_H), 1); + assert_eq!(lanes_shown(LANE_H - 10.), 1); + assert_eq!(lanes_shown(2. * LANE_H + 8.), 2); + + // Four tracks in a two-lane box: two are below, and each row scrolled + // past takes one off that count until none is left. This is the bug the + // graft fixes -- the count used to be `total - shown` forever, so the + // line still said "2 more below" with the last track on screen. + let box_h = 2. * LANE_H + 8.; + assert_eq!(rows_below(4, box_h, 0.), 2); + assert_eq!(rows_below(4, box_h, LANE_H + 8.), 1); + assert_eq!(rows_below(4, box_h, 2. * (LANE_H + 8.)), 0); + // Past the end (gpui clamps, but the arithmetic must not wrap). + assert_eq!(rows_below(4, box_h, 900.), 0); + // A project that fits says nothing at all. + assert_eq!(rows_below(2, box_h, 0.), 0); + + // The inspector's rows are not one height, so its own line is measured + // in pixels off the scroll instead: gpui keeps the offset negative going + // down, and at the bottom the two cancel out exactly. + assert_eq!(px_below(120., 0.), 120.); + assert_eq!(px_below(120., -40.), 80.); + assert_eq!(px_below(120., -120.), 0.); + assert_eq!(px_below(0., 0.), 0.); +} + +/// The failure a user never learns about is the one that was answered by +/// another failure: two imports failing back to back are two messages, in +/// the order they happened, and the second does not overwrite the first +/// before a frame has drawn it. +#[test] +fn a_second_message_queues_behind_the_first_instead_of_erasing_it() { + let mut q = std::collections::VecDeque::new(); + push_notice(&mut q, "NOTHING ADDED — no video stream".into()); + push_notice(&mut q, "NOTHING ADDED — the file is not there".into()); + assert_eq!(q.len(), 2); + assert_eq!(q.front().map(|n: &gpui::SharedString| n.as_ref()), Some("NOTHING ADDED — no video stream")); + + // A held key that refuses says its one sentence once: the count on the + // bar is a count of messages, not of how long the key was held. + push_notice(&mut q, "NOTHING ADDED — the file is not there".into()); + assert_eq!(q.len(), 2); + + // ...and the ceiling drops the oldest rather than the newest: the thing + // that just happened is the thing worth reading. + for i in 0..NOTICES_MAX + 3 { + push_notice(&mut q, format!("SCAN FAILED: {i}").into()); + } + assert_eq!(q.len(), NOTICES_MAX); + assert_eq!(q.back().map(|n: &gpui::SharedString| n.as_ref()), Some("SCAN FAILED: 10")); + + // Answering the bar brings the next one up, oldest first. + let front = q.pop_front(); + assert_ne!(front, q.front().cloned()); +} + +/// The bar colours itself off the words the message already opens with, so +/// the tone cannot disagree with the sentence it labels. +#[test] +fn a_message_wears_the_colour_its_own_words_say() { + assert_eq!(notice_tone("SCAN FAILED: no audio"), STATUS_ERROR()); + assert_eq!(notice_tone(&format!("{EXPORT_DONE}out.mp4")), STATUS_SUCCESS()); + assert_eq!(notice_tone("NOTHING DETACHED — not grouped"), STATUS_WARNING()); + assert_eq!(notice_tone("SNAP ON"), ACCENT_PRIMARY()); +} + +/// The cards are sections of the inspector, not sheets over the timeline: +/// adjusting a clip must never hide the clip. Structural, because that is +/// where the rule lives -- a card rendered from the root again would be an +/// overlay again, whatever it looked like on the day it was written. +#[test] +fn an_inspector_section_occludes_no_timeline() { + let inspector = src_text("ui/inspector.rs"); + // Whichever file the root render has come to live in, from the impl to the + // end of it -- found rather than named, so moving the root does not quietly + // leave this rule reading a file the render is no longer in. + let render = source_files() + .iter() + .map(|path| std::fs::read_to_string(path).expect("a source file")) + .find_map(|text| text.find("impl Render for Player").map(|at| text[at..].to_string())) + .expect("the root render"); + for card in [ + "eq_card", "color_card", "speed_card", "silence_card", "mix_card", + ] { + assert!( + inspector.contains(&format!("self.{card}(")), + "{card} is not a section of the inspector" + ); + assert!( + !render.contains(&format!("self.{card}(")), + "{card} is drawn from the root again -- it is an overlay over the timeline" + ); + } + // The docked cards are placed against the inspector's own box, which is + // what turns `scrim()` (`absolute().inset_0()`) from a window-wide sheet + // into this column. + assert!( + inspector.contains(".relative()"), + "the inspector is not a positioning context: its cards would cover the window" + ); +} + +/// MUST 1, on the two named offenders: the button that relabels itself +/// mid-export and the one that used to read "Muted 80%". Both live in a +/// rect that is reserved once, so the words change and the box does not. +#[test] +fn a_stateful_button_keeps_its_rect() { + use crate::ui::toolbar::{EXPORT_SLOT_W, SNAP_SLOT_W, VOLUME_SLOT_W}; + // Widest word each slot can hold, at the 12 px text this window is set + // in -- ~7 px a character plus the 16 px of padding. + let fits = |slot: f32, word: &str| slot >= word.chars().count() as f32 * 7. + 16.; + for word in ["Export", "Cancel"] { + assert!(fits(EXPORT_SLOT_W, word), "{word} overflows its rect"); + } + for word in ["Snap on", "Snap off", "No subs", "Subs off"] { + assert!(fits(SNAP_SLOT_W, word), "{word} overflows its rect"); + } + for word in ["100%", "× 100%"] { + assert!(fits(VOLUME_SLOT_W, word), "{word} overflows its rect"); + } + // And the rect is passed, not hoped for: every stateful control in the + // three chrome rows names its width. + let toolbar = src_text("ui/toolbar.rs"); + for (id, slot) in [ + ("\"export\"", "EXPORT_SLOT_W"), + ("\"snap\"", "SNAP_SLOT_W"), + ("\"subs\"", "SNAP_SLOT_W"), + ("\"volume\"", "VOLUME_SLOT_W"), + ("\"zoom-fit\"", "ZOOM_SLOT_W"), + ] { + let at = toolbar.find(id).unwrap_or_else(|| panic!("no {id} button")); + assert!( + toolbar[at..at + 120].contains(slot), + "{id} does not reserve {slot}" + ); + } +} + +#[test] +fn nothing_clickable_is_smaller_than_the_wcag_minimum() { + // Every hit target in the panel, including the scrub strip -- whose bar + // is 6 px to look at and whose click area must not be. + assert!(CONTROL_H >= HIT_MIN); + assert!(RULER_HIT_H >= HIT_MIN); + assert!(LANE_H >= HIT_MIN); + // A clip box is a hit target too, and its two trim strips occlude it: + // on a box narrower than the pair there is no body left to press, so + // the clip cannot be selected, dragged or menued at all -- which is + // every clip a jumpcut leaves at a normal zoom. Below three handles + // there are no strips. + assert!(!trims(0.)); + assert!(!trims(EDGE_W)); + assert!(!trims(2. * EDGE_W), "a box that is all handle and no clip"); + assert!(!trims(3. * EDGE_W - 0.1)); + // And where they are drawn, what is left between them is a hit target + // in its own right -- a whole handle's width of clip. + for width in [3. * EDGE_W, 24., 100., 4000.] { + assert!(trims(width)); + assert!( + width - 2. * EDGE_W >= EDGE_W, + "{width} px of box leaves no middle" + ); + } +} + +#[test] +fn a_lane_row_is_a_fixed_header_and_a_bed_that_can_be_hit() { + // The header column is what the ruler is offset by as well, so both + // numbers are shared rather than repeated per row (A-MUST1/A-MUST2). + assert!(HEADER_W > 0. && HEADER_GAP >= 0.); + // Two lanes, a ruler, a button row and the timecode line, inside the + // panel the window is sized for. + assert!( + CONTROL_H + RULER_HIT_H + 2. * LANE_H + 17. + 4. * 8. + 16. <= PANEL_H, + "the second lane does not fit the panel" + ); + // Headers and clip boxes are as tall as the lane, and the lane is a + // click target (WCAG 2.5.8). + assert!(LANE_H >= HIT_MIN); + // A label row that ate the whole lane would leave no waveform. + assert!(LABEL_H < LANE_H / 2.); + // An added track adds its own row to the panel, and the two a project + // starts with leave it exactly the height it has always been. + assert_eq!(panel_h(2), PANEL_H); + assert_eq!(panel_h(1), PANEL_H); + assert_eq!(panel_h(3), PANEL_H + LANE_H + 8.); + assert_eq!( + panel_h(LANES_MAX), + PANEL_H + lanes_h(LANES_MAX) - lanes_h(2) + ); + // Past the cap the column scrolls instead: the panel stops growing, so + // no number of tracks can push the picture off the window. + assert_eq!(panel_h(LANES_MAX + 1), panel_h(LANES_MAX)); + assert_eq!(panel_h(50), panel_h(LANES_MAX)); + assert_eq!(lanes_h(0), 0.); + assert_eq!(lanes_h(1), LANE_H); + assert_eq!(lanes_h(2), 2. * LANE_H + 8.); +} + +#[test] +fn a_click_marks_the_whole_group_and_nothing_else() { + let (v, a) = ((Lane::V1, 0), (Lane::A1, 0)); + // Clicking the video half of group 1 marks the audio half with it. + assert!(marked(v, Some(1), Some(v), Some(1))); + assert!(marked(a, Some(1), Some(v), Some(1))); + // Another group's clips stay unmarked, in either lane. + assert!(!marked((Lane::V1, 1), Some(2), Some(v), Some(1))); + assert!(!marked((Lane::A1, 1), Some(2), Some(v), Some(1))); + // A half a lift left behind has no group: it marks itself only, which + // is what makes it separately deletable. Two ungrouped clips must not + // mark each other by both being ungrouped. + assert!(marked(a, None, Some(a), None)); + assert!(!marked(v, None, Some(a), None)); + // Nothing selected marks nothing. + assert!(!marked(v, Some(1), None, None)); +} + +#[test] +fn a_name_is_dropped_rather_than_smeared_across_a_thin_clip() { + assert!(show_label(LABEL_MIN_W)); + assert!(show_label(400.)); + assert!(!show_label(LABEL_MIN_W - 0.1)); + // The label test is the box's own width in pixels now, which is what + // the scale hands it -- no bed width, and so nothing to be zero. + let scale = Scale::default(); + assert!(show_label(scale.width_px(LABEL_MIN_W as f64 / PPS_DEFAULT))); + assert!(!show_label(scale.width_px(0.))); +} + +#[test] +fn an_envelope_stays_inside_the_box_it_is_drawn_in() { + // A ramp: silence at the start, full scale at the end. + let peaks: Vec<(f32, f32)> = (0..40) + .map(|i| (-(i as f32) / 39., i as f32 / 39.)) + .collect(); + let (w, h) = (100., 30.); + let cols = envelope(&peaks, 0., 1., w, h); + assert_eq!(cols.len(), (w / WAVE_COL) as usize + 1); + for &(x, top, bottom) in &cols { + assert!((0. ..=w).contains(&x), "x {x} outside 0..{w}"); + assert!((0. ..=h).contains(&top), "top {top} outside 0..{h}"); + assert!( + (0. ..=h).contains(&bottom), + "bottom {bottom} outside 0..{h}" + ); + // Never inverted, and never a polygon with no area: silence has to + // read as a line rather than as nothing at all. + assert!( + bottom - top >= 1., + "column {top}..{bottom} is thinner than a pixel" + ); + } + // The ramp is drawn as a ramp: the last column is taller than the first. + let height = |&(_, top, bottom): &(f32, f32, f32)| bottom - top; + assert!(height(cols.last().unwrap()) > height(cols.first().unwrap()) + 5.); + // Degenerate inputs draw nothing rather than panicking. + assert!(envelope(&[], 0., 1., w, h).is_empty()); + assert!(envelope(&peaks, 0., 1., 0., h).is_empty()); + // A clip whose range runs past the peaks clamps to the last bucket. + assert!(!envelope(&peaks, 0., 99., w, h).is_empty()); +} + +/// A box laid out wider than any screen -- a long clip at a deep zoom -- is +/// still one screen's worth of columns: the path a repaint has to build is +/// bounded by what can be seen, not by what the layout says the box is. +/// Unbounded, a 5 s clip zoomed to the frame is a path of millions of points +/// per frame, and the repaint that stalls on it is the waveform that +/// "disappeared". +#[test] +fn an_envelope_never_costs_more_points_than_a_screen_can_show() { + let peaks: Vec<(f32, f32)> = (0..200).map(|i| (-(i as f32) / 199., 1.)).collect(); + // The width a 5 s clip is laid out at when the bed shows 8 frames of it. + let huge = 5. * 30. / 8. * 1200.; + let cols = envelope(&peaks, 0., 5., huge, 30.); + assert!( + cols.len() <= WAVE_COLS_MAX + 1, + "{} columns for a {huge} px box", + cols.len() + ); + // ...and the slice actually painted is the part of the box on the bed, + // which is where that width stops mattering: a column per two visible + // pixels, at every zoom. + let (x, w) = visible_slice(-huge / 2., huge, 1200.); + assert_eq!((x, w), (huge / 2., 1200.)); + assert_eq!(envelope(&peaks, 0., 5., w, 30.).len(), 601); + // A box entirely off the bed has no slice, and one that has never been + // measured is drawn whole -- what was drawn before there was a bed. + assert_eq!(visible_slice(2000., 500., 1200.), (0., 0.)); + assert_eq!(visible_slice(-3000., 500., 1200.), (500., 0.)); + assert_eq!(visible_slice(-40., 500., 0.), (0., 500.)); + // Half on, at either edge. + assert_eq!(visible_slice(-100., 500., 1200.), (100., 400.)); + assert_eq!(visible_slice(1000., 500., 1200.), (0., 200.)); +} + +/// The box a trim draws is the box its release commits, at every speed. The +/// preview used to hand the *timeline* frame count to a source-frame field: +/// at 2x a tail moved twice as fast as the pointer and snapped back on +/// release, and a head drag moved the clip's other edge. +#[test] +fn a_trim_preview_lands_where_the_release_commits() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + for permille in SPEED_PRESETS { + // Live, so the loop owes it no undo step: the speeds are the axis + // this walks, and the trims below are what is undone. + session + .set_speed_live(Lane::V1, 0, Speed::from_permille(permille)) + .expect("a clip alone on its lane may be speeded"); + for edge in [Edge::Start, Edge::End] { + let clip = session.lane_clips(Lane::V1)[0]; + let (lo, hi) = session + .trim_room(Lane::V1, 0, edge) + .expect("clip 0 is there"); + // Both walls and the middle of the room: the whole range a + // pointer can be clamped to. + for to in [lo, (lo + hi) / 2, hi] { + let preview = trimmed_clip(clip, edge, to, false); + // The drag is one edit and one undo step, so the next `to` + // is measured from the same clip this one was. + if session.trim_clip(Lane::V1, 0, edge, to) { + assert_eq!( + preview, + session.lane_clips(Lane::V1)[0], + "{edge:?} to {to} at {permille} per mille" + ); + assert!(session.undo(), "the trim is one undo step"); + } else { + // An edge already where it was asked to go is not an + // edit, and the preview draws the clip unchanged. + assert_eq!(preview, clip, "{edge:?} to {to} at {permille} per mille"); + } + assert_eq!(session.lane_clips(Lane::V1)[0], clip, "back where it was"); + } + } + } +} + +/// A still trims the same way, and the preview knows it: its head grows +/// forward from source frame 0 -- every frame of it is the same picture -- +/// so the box stretches instead of sliding left. +#[test] +fn a_stills_trim_preview_grows_forward_like_the_commit() { + let mut session = PlaybackSession::open(asset("test_still.png")).expect("a picture opens"); + for edge in [Edge::Start, Edge::End] { + let clip = session.lane_clips(Lane::V1)[0]; + let (lo, hi) = session + .trim_room(Lane::V1, 0, edge) + .expect("clip 0 is there"); + for to in [lo, (lo + hi) / 2, hi] { + let preview = trimmed_clip(clip, edge, to, true); + match session.trim_clip(Lane::V1, 0, edge, to) { + true => { + assert_eq!( + preview, + session.lane_clips(Lane::V1)[0], + "a still {edge:?} to {to}" + ); + assert!(session.undo(), "the trim is one undo step"); + } + false => assert_eq!(preview, clip, "a still {edge:?} to {to}"), + } + assert_eq!(session.lane_clips(Lane::V1)[0], clip, "back where it was"); + } + } +} + +/// gpui freezes a drag's payload for the whole gesture, and nothing stops a +/// stroke from editing the lane under it: the drop has to find the clip that +/// was picked up, not whatever slid into its index. +#[test] +fn a_drop_moves_the_clip_that_was_picked_up_not_its_old_index() { + let at = |start: u32| Clip { + start, + in_frame: 0, + out_frame: 30, + source: 0, + link: None, + eq: None, + color: None, + fit: FitPolicy::Fit, + speed: Speed::NORMAL, + }; + let lane = [at(0), at(30), at(60)]; + let dragged = lane[2]; + assert_eq!(live_idx(&lane, 2, dragged), Some(2), "nothing moved"); + // A delete in front of it: the clip is now index 1, and the index the + // drag froze names a clip nobody grabbed. + let after = [at(0), at(60)]; + assert_eq!(live_idx(&after, 2, dragged), Some(1)); + assert_eq!(live_idx(&after, 1, dragged), Some(1)); + // Deleted mid-drag: there is nothing to move, and moving its neighbour + // instead is exactly the bug this exists for. + assert_eq!(live_idx(&[at(0)], 2, dragged), None); + assert_eq!(live_idx(&[], 0, dragged), None); +} + +#[test] +fn a_quiet_source_still_draws_as_a_shape() { + // An eighth of full scale, which is about where the fixtures sit. + let quiet: Vec<(f32, f32)> = vec![(-0.125, 0.125), (-0.0625, 0.0625)]; + let loud = normalise(quiet.clone()); + assert_eq!(loud[0], (-1., 1.)); + assert_eq!(loud[1], (-0.5, 0.5)); + // Digital silence has no loudest sample to scale to; it must not divide + // by zero and must stay flat. + assert_eq!(normalise(vec![(0., 0.)]), vec![(0., 0.)]); + assert!(normalise(Vec::new()).is_empty()); +} + +/// The whole waveform path, from the file on disk to the columns that get +/// painted: what no screenshot can assert about the shape. +#[test] +fn the_fixtures_waveform_reaches_the_lane_as_a_shape() { + let asset = |name: &str| { + std::path::Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) + }; + let peaks = normalise( + engine::waveform::peaks(asset("test_av.mp4"), 0, WAVE_BPS) + .expect("open the fixture") + .expect("test_av.mp4 has audio"), + ); + // 5 s of source at the rate the lane asks for. + assert!(peaks.len().abs_diff(5 * WAVE_BPS as usize) <= WAVE_BPS as usize); + let cols = envelope(&peaks, 0., 5., 600., 30.); + let height = |&(_, top, bottom): &(f32, f32, f32)| bottom - top; + let tallest = cols.iter().map(height).fold(0., f32::max); + let flattest = cols.iter().map(height).fold(f32::MAX, f32::min); + // The fixture's 1 Hz pulse: a full-scale peak and a near-silent dip in + // every second, so the drawn envelope is a shape and not a bar. + assert!(tallest > 25., "loudest column only {tallest} px of 30"); + assert!( + flattest < 8., + "quietest column {flattest} px -- no dips drawn" + ); + // A video-only source draws no waveform at all rather than a flat fake. + assert!( + engine::waveform::peaks(asset("test_baseline.mp4"), 0, WAVE_BPS) + .expect("open the fixture") + .is_none() + ); +} + +#[test] +fn every_mark_on_a_clip_is_legible_on_it() { + // The body a name and a waveform are drawn on is the clip's kind + // ([`clip_kind`]); the source tint is the border and the library + // swatch, and is measured for telling itself apart rather than for + // carrying text. + // Every palette a person can pick, not merely the one in force. + for id in crate::ui::theme::PaletteId::ALL { + let p = id.palette(); + for (i, tint) in [p.CLIP_VIDEO, p.CLIP_AUDIO, p.CLIP_IMAGE, p.CLIP_TEXT] + .iter() + .enumerate() + { + // WCAG 1.4.3: the clip's name is body text on its tint. + assert!( + contrast(p.FG_PRIMARY, *tint) >= 4.5, + "{id:?} source {i}: label contrast {:.2}", + contrast(p.FG_PRIMARY, *tint) + ); + // WCAG 1.4.11: the waveform is a non-text graphic on it. + assert!( + contrast(p.FG_SECONDARY, *tint) >= 3., + "{id:?} source {i}: waveform contrast {:.2}", + contrast(p.FG_SECONDARY, *tint) + ); + } + // A selected clip's bed is the same two marks on a different colour. + assert!(contrast(p.FG_PRIMARY, p.BG_SELECTED) >= 4.5, "{id:?}"); + assert!(contrast(p.FG_SECONDARY, p.BG_SELECTED) >= 3., "{id:?}"); + // The bed a gap shows through has to read as a hole in the lane -- + // the clip is the object, the bed is the hole -- and the playhead + // has to be findable on both. + assert!(contrast(p.CLIP_VIDEO, p.BG_TIMELINE) >= 1.5, "{id:?}"); + assert!(contrast(p.ACCENT_PLAYHEAD, p.BG_TIMELINE) >= 3., "{id:?}"); + assert!(contrast(p.ACCENT_PLAYHEAD, p.CLIP_VIDEO) >= 3., "{id:?}"); + } + // The sanity check on the ratio itself: black on white is 21:1. + assert!((contrast(0xffffff, 0x000000) - 21.).abs() < 0.01); +} + +#[test] +fn source_tints_differ_per_source_and_cycle() { + // The bug: the first entry *was* `BG_RAISED`, so the first file imported + // -- the one every session has -- wore the panel's own background and + // had no visible swatch at all. + assert_ne!(source_tint(0), BG_RAISED()); + // ...in every family, since the swatch is drawn on whichever panel is + // in force (`ui::theme`) and a tint that vanished into one of them is a + // file with no colour at all. + for id in crate::ui::theme::PaletteId::ALL { + let p = id.palette(); + for (i, &tint) in p.SOURCE_TINTS.iter().enumerate() { + assert_ne!(tint, p.BG_RAISED, "{id:?} tint {i} is the panel"); + } + } + // Neighbouring sources must not share one, or an import is invisible. + assert_ne!(source_tint(0), source_tint(1)); + assert_ne!(source_tint(1), source_tint(2)); + assert_ne!(source_tint(2), source_tint(3)); + // Past the palette it wraps -- never an index panic. + assert_eq!(source_tint(4), source_tint(0)); + assert_eq!(source_tint(9), source_tint(1)); + assert_eq!(source_tint(usize::MAX), SOURCE_TINTS()[usize::MAX % 4]); +} + +/// Not "they are different numbers" -- different *enough to see*, against +/// each other and against the surface a swatch is drawn on. The palette is +/// deliberately dark and low-saturation, so the margin is thin and a new +/// tint picked by eye can land inside it without anyone noticing. +#[test] +fn source_tints_are_all_discernible() { + // Summed channel distance: `BG_RAISED` to the warm tint is 18, and that + // step is the one already accepted as readable on a lane. + let apart = |a: u32, b: u32| { + (0..3) + .map(|i| { + let shift = i * 8; + ((a >> shift) & 0xff).abs_diff((b >> shift) & 0xff) + }) + .sum::() + }; + // Every family, not the one in force: a palette is picked at runtime + // now, and four tints tuned by eye on one ground are exactly where a + // pair lands inside the margin on another. + for id in crate::ui::theme::PaletteId::ALL { + let p = id.palette(); + for (i, &tint) in p.SOURCE_TINTS.iter().enumerate() { + assert!( + apart(tint, p.BG_RAISED) >= 16, + "{id:?} tint {i} is {} from the panel it sits on", + apart(tint, p.BG_RAISED) + ); + for (j, &other) in p.SOURCE_TINTS.iter().enumerate().skip(i + 1) { + assert!( + apart(tint, other) >= 16, + "{id:?} tints {i} and {j} are only {} apart", + apart(tint, other) + ); + } + } + // The two a person sees side by side first must be further apart + // than the floor: source 0 and source 1 are the first import and + // the second. + assert!(apart(p.SOURCE_TINTS[0], p.SOURCE_TINTS[1]) >= 32, "{id:?}"); + } +} + +/// A `.srt` dropped on the window is nobody's stream: it has no source +/// entry, and the lookup that used to fall back to index 0 painted it with +/// the first file's colour -- a swatch saying it came out of a film it +/// never touched. +#[test] +fn a_standalone_subtitle_wears_no_file_tint() { + let sources = [ + Source { + path: PathBuf::from("/films/a.mkv"), + audio_stream: 0, + }, + Source { + path: PathBuf::from("/films/b.mp4"), + audio_stream: 0, + }, + // A second stream of the first file is a second source and the + // same colour. + Source { + path: PathBuf::from("/films/a.mkv"), + audio_stream: 1, + }, + ]; + assert_eq!( + file_tint(&sources, Path::new("/films/a.mkv")), + Some(source_tint(0)) + ); + assert_eq!( + file_tint(&sources, Path::new("/films/b.mp4")), + Some(source_tint(1)) + ); + assert_eq!(file_tint(&sources, Path::new("/subs/a.eng.srt")), None); + assert_eq!(file_tint(&[], Path::new("/films/a.mkv")), None); + // The same file under two spellings is one file and one colour: a + // source is stored symlink-resolved, everything else as it was typed. + let here = std::fs::canonicalize(".").expect("the crate directory"); + let sources = [Source { + path: here.join("Cargo.toml"), + audio_stream: 0, + }]; + assert_eq!( + file_tint(&sources, Path::new("Cargo.toml")), + Some(source_tint(0)), + "a relative spelling of the source file wears the source's colour" + ); +} + +/// A film's two ASS tracks with the timeline trimmed to twenty seconds: +/// one of them still has cues there and one has none, and the card said +/// nothing whatever about the second while the Subtitles list went on +/// showing it with its eighty-three cues. +/// +/// And the 25 GB remux's thirty-five: naming those wrapped the row to ten +/// lines and pushed Destination under the fold, so past the value box's +/// three lines the same line counts instead. +#[test] +fn the_card_names_the_subtitle_it_leaves_off_and_counts_them_when_it_cannot() { + let film = "/films/An Episode 01.mkv"; + let two = [ + sub(film, Some(1), "[ASS]"), + sub(film, Some(2), "[ASS] [FOR DUB]"), + ]; + // What the engine answers about the one pick that reached it, and what + // this side knows about the row that did not. + let named = subtitle_plan("[ASS] → embedded".to_string(), &two, &[0]); + assert_eq!(named, "[ASS] → embedded; [ASS] [FOR DUB] — no cues here"); + assert!( + named.chars().count() <= SUB_PLAN_CHARS, + "two tracks fit the value box: {named}" + ); + // Thirty-five off one file: twenty-two carry cues here, nine are + // pictures, one could not be read, three have nothing on this timeline. + let many: Vec<_> = (0..35) + .map(|i| { + let mut track = sub("/films/A Remux.mkv", Some(i), "eng — Subtitles"); + track.bitmap = (22..31).contains(&i); + track.refused = (i == 31).then(|| "VobSub is pictures".to_string()); + track + }) + .collect(); + // The picks are every track with a cue on the timeline: the twenty-two + // and the nine picture ones, which the engine drops itself. + let picks: Vec = (0..31usize).collect(); + let counted = subtitle_plan("22 tracks → embedded (…)".to_string(), &many, &picks); + assert_eq!(counted, "22 of 35 → embedded; 9 pictures; 1 unread; 3 no cues here"); + assert!( + counted.chars().count() <= SUB_PLAN_CHARS, + "thirty-five tracks still fit the value box: {counted}" + ); + // Nothing on the timeline at all is still the engine's word for it. + assert_eq!(subtitle_plan("none".to_string(), &[], &[]), "none"); +} + +/// The list is in the order tracks were added, which is not the order a +/// person reads it in: importing a second film puts its tracks after the +/// first film's, and importing a third `.srt` for the first film puts that +/// one last of all. The rows still read as three sources. +#[test] +fn subtitle_rows_group_a_source_however_they_were_added() { + let tracks = [ + sub("/films/a.mkv", Some(1), "eng"), + sub("/films/b.mkv", Some(1), "eng"), + sub("/films/a.mkv", Some(2), "fre"), + sub("/subs/late.srt", None, "late.srt"), + sub("/films/b.mkv", Some(3), "ger"), + ]; + let groups = subtitle_rows(&tracks); + assert_eq!( + groups.iter().map(|g| g.name.as_str()).collect::>(), + ["a", "b", "late"], + "one group per file, in the order the files first appear" + ); + assert_eq!( + groups + .iter() + .map(|g| g.rows.iter().map(|r| r.label.as_str()).collect::>()) + .collect::>(), + [vec!["eng", "fre"], vec!["eng", "ger"], vec!["late.srt"]], + "a file's tracks are contiguous and in add order" + ); + // Numbered within the file, the way `row_name` numbers audio streams: + // two tracks that both say "eng" are told apart by nothing else. + assert_eq!( + groups + .iter() + .map(|g| g.rows.iter().map(|r| r.number).collect::>()) + .collect::>(), + [vec![1, 2], vec![1, 2], vec![1]] + ); + // The swatch key is the file, so a group and that file's media rows + // wear one colour -- and the standalone one has none. + let sources = [Source { + path: PathBuf::from("/films/a.mkv"), + audio_stream: 0, + }]; + assert_eq!( + file_tint(&sources, &groups[0].path), + Some(source_tint(0)), + "the group carries the path the tint is asked by" + ); + assert_eq!(file_tint(&sources, &groups[2].path), None); +} + +/// What the strip header, the section heading and the toggle's notice all +/// say. Two films each carrying an "eng" track are one word apart until the +/// film is in the name; a film carrying two is one word apart from itself. +#[test] +fn the_picked_subtitle_is_named_with_the_film_it_came_out_of() { + let tracks = [ + sub("/films/a.mkv", Some(1), "eng"), + sub("/films/b.mkv", Some(1), "eng"), + sub("/films/a.mkv", Some(2), "eng"), + sub("/films/b.mkv", Some(2), "und"), + sub("/subs/late.srt", None, "late.srt"), + ]; + let name = |track| sub_pick_name(&tracks, track).expect("a track that is there"); + // The two "eng"s of two films: one file gave several so its tracks are + // numbered, the other gave one so it is not. + assert_eq!(name(0), "eng 1 — a"); + assert_eq!(name(2), "eng 2 — a"); + assert_eq!(name(1), "eng 1 — b"); + assert_ne!(name(0), name(1), "two films' eng tracks read apart"); + for picked in [name(0), name(1), name(2)] { + assert!(picked.contains(" — a") || picked.contains(" — b")); + } + // "und" is the tag for "nobody said", humanised once by + // `subtitle_rows` and not again here. + assert_eq!(name(3), "unknown language 2 — b"); + // A standalone `.srt` is its own file and its label already says so: + // one track, so no number, and no stem after it saying it again. + assert_eq!(name(4), "late.srt"); + // The silence `subtitle_track` gives at the same moment. + assert_eq!(sub_pick_name(&tracks, 5), None); + assert_eq!(sub_pick_name(&[], 0), None); +} + +/// The door this editor answers "don't make me import the film again" with, +/// and it is in the panel where the tracks it adds are listed: the Text +/// tab's own button reads a file's subtitle tracks onto the open timeline +/// -- a release's `.mkv`, an `.srt` beside it -- while the file itself +/// joins nothing. It is the *action* and not a second implementation of it, +/// so the button, the stroke and the actions card cannot drift apart, and +/// it is oracle-gated like every other action button, so with no timeline +/// open it dims and says why instead of opening a chooser for nothing. +#[test] +fn the_text_tab_carries_the_add_subtitles_door() { + let library = src_text("ui/library.rs"); + let at = library + .find("\"add-subtitles\"") + .expect("no add-subtitles control in the library column"); + let block = &library[at..(at + 1400).min(library.len())]; + assert!( + block.contains("ActionId::AddSubtitleTrack"), + "the button is a door of its own rather than the action: {block}" + ); + assert!( + block.contains("pick_and_add_subtitles"), + "the button does not open the subtitle chooser: {block}" + ); + // `action_control` is the oracle-gated one: dimmed with the refusal in + // the oracle's own words. `control` alone would be lit with no timeline. + assert!( + library[..at].ends_with("self.action_control(\n "), + "the add-subtitles button is not oracle-gated" + ); + // ...and the empty tab names that button, rather than pointing at a + // toolbar the person is not looking at. + assert!( + crate::LibraryTab::Text.empty().contains("Add subtitles"), + "{}", + crate::LibraryTab::Text.empty() + ); +} + +/// The one thing regrouping must not break: `sub_track` is a flat index +/// into the add-order list, a click sets it and a save writes it into the +/// `.edith`. Every row must still name the track it was made from -- rows +/// for refused tracks included, because they take a number in that list +/// whether or not anyone can pick them. +#[test] +fn a_subtitle_row_names_the_flat_track_it_was_made_from() { + let mut tracks = vec![ + sub("/films/a.mkv", Some(1), "eng"), + sub("/films/b.mkv", Some(1), "eng"), + sub("/films/a.mkv", Some(2), "fre"), + ]; + // Track 1 of b is pictures: still a row, still index 1 of the list. + tracks[1].bitmap = true; + tracks[1].refused = Some("PGS subtitles are pictures".to_string()); + let groups = subtitle_rows(&tracks); + let flat: Vec<(usize, &str)> = groups + .iter() + .flat_map(|g| g.rows.iter().map(|r| (r.track, r.label.as_str()))) + .collect(); + assert_eq!(flat, [(0, "eng"), (2, "fre"), (1, "eng")]); + for (track, label) in flat { + assert_eq!( + tracks[track].label, label, + "row {track} picks the track it names" + ); + } + // (c) The refused one is here, saying why, and greyable by that alone. + let refused = &groups[1].rows[0]; + assert_eq!( + refused.refused.as_deref(), + Some("PGS subtitles are pictures") + ); + assert_eq!(refused.detail, "PGS subtitles are pictures"); + assert!(refused.bitmap); + // ...and it was counted: the row after it in add order is still 2. + assert_eq!(groups[0].rows[1].track, 2); +} + +/// The × on a row shifts every track after it down one, and the pick is +/// what an export writes into the file -- so a pick that stayed put would +/// silently change which track the next export carries. Every relation +/// between the pick and the row that went, on a list of three. +#[test] +fn removing_a_subtitle_row_carries_the_pick_with_it() { + // A row *before* the pick: the same track stays picked, one index down. + assert_eq!(sub_pick_after_removal(2, 0, 2), 1); + assert_eq!(sub_pick_after_removal(2, 1, 2), 1); + // A row *after* it: the pick has not moved and neither has its index. + assert_eq!(sub_pick_after_removal(0, 2, 2), 0); + assert_eq!(sub_pick_after_removal(1, 2, 2), 1); + // The picked row itself: the one that slid into its place... + assert_eq!(sub_pick_after_removal(1, 1, 2), 1); + // ...and the last row when the picked one was the last, since there is + // nothing after it to slide. + assert_eq!(sub_pick_after_removal(2, 2, 2), 1); + // The last row of all: an emptied list is legal for subtitles, and the + // section is not drawn at all at that point. + assert_eq!(sub_pick_after_removal(0, 0, 0), 0); +} + +/// The same claim from the click's end, on the order imports actually +/// arrive in: two films opened one after the other and an `.srt` dropped +/// last interleave in the flat list, and the display reorders them. What a +/// click sets is the row's own `track`, so the *n*th row on screen has to +/// pick the track it shows and the echoes have to name that same file. +#[test] +fn a_click_on_a_regrouped_row_picks_the_track_that_row_shows() { + let tracks = [ + sub("/films/a.mkv", Some(1), "eng"), + sub("/films/b.mkv", Some(1), "eng"), + sub("/films/a.mkv", Some(2), "fre"), + sub("/subs/late.srt", None, "late.srt"), + sub("/films/b.mkv", Some(3), "ger"), + ]; + let rows: Vec<_> = subtitle_rows(&tracks) + .into_iter() + .flat_map(|group| { + group + .rows + .into_iter() + .map(move |row| (group.path.clone(), row)) + }) + .collect(); + // Read top to bottom, the rows are no longer in add order... + assert_eq!( + rows.iter().map(|(_, row)| row.track).collect::>(), + [0, 2, 1, 4, 3] + ); + for (path, row) in &rows { + // ...and what the click writes into `sub_track` -- and a save into + // the `.edith` -- still lands on the track the row is showing. + let picked = &tracks[row.track]; + assert_eq!(&picked.path, path, "row {} picks another file", row.track); + assert_eq!(lang_human(&picked.label), row.label); + // And the heading, the strip and the notice name that same file + // back, so a click cannot leave the echoes pointing elsewhere. + let echo = sub_pick_name(&tracks, row.track).expect("the row's own track"); + let stem = path.file_stem().expect("a fixture path").to_string_lossy(); + assert!( + echo.contains(&*stem), + "picked {}, echoed {echo}", + path.display() + ); + } +} + +/// "und" is what a muxer writes when nobody said what the language is. A +/// row showing it verbatim names a language nobody speaks. +#[test] +fn an_untagged_language_says_it_is_unknown() { + assert_eq!(lang_human("und"), "unknown language"); + assert_eq!(lang_human("eng"), "eng"); + assert_eq!(lang_human("fre — Commentary"), "fre — Commentary"); + // Reaching the subtitle rows too: a track whose only name was the tag. + let groups = subtitle_rows(&[sub("/films/a.mkv", Some(1), "und")]); + assert_eq!(groups[0].rows[0].label, "unknown language"); + // The pair, read as the pair: the row title comes off `language` and + // `name` and never out of the flattened label, which is what let an + // "und" beside a title through as a language nobody speaks. A refused + // track states neither and keeps its label. + let titled = |language: &str, name: &str, label: &str| engine::subtitle::SubtitleTrack { + path: PathBuf::from("/films/a.mkv"), + track: Some(1), + language: language.into(), + name: name.into(), + label: label.into(), + cues: Vec::new(), + bitmap: false, + refused: None, + }; + for (language, name, label, title) in [ + ("fra", "Signs", "fra — Signs", "fra — Signs"), + ("und", "Signs", "Signs", "Signs"), + ("und", "", "und", "unknown language"), + ("", "late.srt", "late.srt", "late.srt"), + ("", "", "eng", "eng"), + ] { + let rows = subtitle_rows(&[titled(language, name, label)]); + assert_eq!(rows[0].rows[0].label, title, "{language:?} {name:?}"); + } +} + +/// The bug: an empty timeline is end-of-stream from its one black frame +/// onward, so the pump had `done` set before anything was ever pressed -- +/// and the transport's restart branch read that as "played out, start from +/// the top". It started a clock against a zero-length timeline, which was +/// `done` again by the next repaint, so every further press restarted it +/// too: the button read "Pause" and no press of it ever paused. +/// +/// What holds it now is one predicate, checked here against real sessions +/// on both sides -- the emptied one refuses, a timeline with clips on it +/// does not. +#[test] +fn an_empty_timeline_has_nothing_to_play() { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + // Silent like the engine suite: this opens the real device. + session.set_gain(0.0); + // A timeline with clips on it plays, and always did: the guard must not + // touch that side. + assert!(!session.is_empty()); + assert!(!nothing_to_play(Some(&session))); + + // Every clip taken off, which is a state and not a failure. + while session.delete_clip(Lane::V1, 0) {} + while session.delete_clip(Lane::A1, 0) {} + assert!(session.is_empty(), "the timeline is empty"); + assert_eq!(session.timeline_duration(), 0.0); + + // What the pump does every render, and what set `done` before the fix: + // the black frame goes by and the session is at its end at once. + for _ in 0..40 { + while session.try_frame().is_some() {} + std::thread::sleep(Duration::from_millis(10)); + } + assert!( + session.is_eos(), + "an empty timeline is done before it starts" + ); + + // So the press is refused rather than sent down the restart branch -- + // and with no session at all it is the same refusal. + assert!(nothing_to_play(Some(&session))); + assert!(nothing_to_play(None)); + assert!(!session.is_playing(), "and nothing was started"); +} + +/// The slider writes the same numbers the keys do, and mute is not one of +/// them: dragging while muted picks the level unmuting comes back to. +#[test] +fn the_slider_lands_on_the_grid_the_keys_move_on() { + let mut volume = Volume::default(); + // Both ends exactly, and clamped past them. + volume.set_along(0.); + assert_eq!(volume.gain(), 0.0); + assert_eq!(volume.label(), "Vol 0%"); + volume.set_along(1.5); + assert_eq!(volume.gain(), 1.0); + assert_eq!(volume.along(), 1.0); + + // Halfway is 50%, and a key press from there is 5% -- the same step + // count as before, on a finer grid. + volume.set_along(0.5); + assert_eq!(volume.label(), "Vol 50%"); + volume.step(true); + assert_eq!(volume.label(), "Vol 55%"); + volume.step(false); + assert_eq!(volume.gain(), 0.5); + + // A number no step lands on comes back as the nearest one, so the label + // and the fill are the same value the device was handed. + volume.set_along(0.333); + assert_eq!(volume.label(), "Vol 33%"); + assert_eq!(volume.along(), 0.33); + + // Muted, the drag moves the level and nothing comes out. + volume.muted = true; + volume.set_along(0.8); + assert_eq!(volume.gain(), 0.0); + assert_eq!(volume.label(), "Muted 80%"); + volume.muted = false; + assert_eq!(volume.gain(), 0.8); +} + +/// The slider lands where it paints: the arithmetic `Player::drag_volume` +/// runs over the bar's own painted width, which is the one thing a test of +/// it can share without re-deriving it. +#[test] +fn the_volume_slider_lands_where_it_paints() { + let bar = Bounds { + origin: point(px(420.), px(508.)), + size: size(px(VOLUME_W), px(CONTROL_H)), + }; + let at = |x: f32| { + let mut volume = Volume::default(); + volume.set_along(frac_along(px(x), bar)); + volume + }; + assert_eq!(at(420.).gain(), 0.0, "the left end is silence"); + assert_eq!(at(420. + VOLUME_W).gain(), 1.0, "the right end is full"); + assert_eq!(at(-4000.).gain(), 0.0, "off the left clamps"); + assert_eq!(at(9999.).gain(), 1.0, "off the right clamps"); + // Every pixel along it: a level the keys could also reach, painted back + // where the hand pressed to within the half step the rounding costs. + for step in 0..=(VOLUME_W as u32) { + let along = step as f32 / VOLUME_W; + let volume = at(420. + along * VOLUME_W); + let painted = volume.along(); + let slack = 0.5 / f32::from(Volume::MAX_STEPS) + 1e-4; + assert!( + (painted - along).abs() <= slack, + "pressed at {along}, paints at {painted}" + ); + } +} diff --git a/crates/app/src/tests/media.rs b/crates/app/src/tests/media.rs new file mode 100644 index 0000000..0643730 --- /dev/null +++ b/crates/app/src/tests/media.rs @@ -0,0 +1,1035 @@ +//! What the workers hand back: the progress lines, the file named on the +//! command line, the scans, the codecs offered, and the subtitles found. + +use super::*; + +/// The import line's own state machine, driven the way a repaint drives +/// it: the worker writes a stage, the poll notices it changed and restarts +/// the stall clock, and the line's words change only when a stage has +/// actually stood still. The whole point is that a stuck read reads as a +/// stuck read and never as a frozen window. +#[test] +fn an_import_line_says_a_stage_has_stopped_moving_and_only_then() { + use std::sync::Arc; + use std::sync::atomic::{AtomicU8, Ordering::Relaxed}; + let stage = Arc::new(AtomicU8::new(ImportStage::Header as u8)); + let started = Instant::now() - Duration::from_secs(9); + let mut import = Import { + path: PathBuf::from("/films/A Film.mkv"), + started, + stage: Arc::clone(&stage), + seen: ImportStage::Header, + // As if the header had been running for those nine seconds. + since: started, + cancelled: Arc::default(), + }; + // Nine seconds inside one stage: past the wait a person tolerates, so + // the line stops pretending it is a progress line. + let since = import.poll(); + assert!(since > IMPORT_STALL, "{since}"); + let stalled = import_line("A Film.mkv", import.seen, 9., since, 0, false); + assert!(stalled.contains("still reading the header"), "{stalled}"); + assert!(stalled.contains("not frozen"), "{stalled}"); + assert!(stalled.contains("0:09 elapsed"), "{stalled}"); + // The worker moves on: the stall clock restarts even though the elapsed + // one does not, which is the distinction the two clocks exist for. + stage.store(ImportStage::Subtitles as u8, Relaxed); + let since = import.poll(); + assert_eq!(import.seen, ImportStage::Subtitles); + assert!(since < IMPORT_STALL, "{since}"); + let moving = import_line("A Film.mkv", import.seen, 9., since, 2, false); + assert!( + moving.starts_with("IMPORTING A Film.mkv · reading the subtitle tracks"), + "{moving}" + ); + assert!(!moving.contains("still"), "{moving}"); + // ...and what is behind it in the queue, which is what a drop of three + // files or an argv of three files leaves waiting. + assert!(moving.ends_with("· 2 more waiting"), "{moving}"); + assert!(!stalled.ends_with("waiting"), "an empty queue says nothing"); + // A stage that does not move is not the same fact as a stage that came + // back to the same value: the poll only restarts on a change. + let held = import.since; + import.poll(); + assert_eq!(import.since, held, "an unchanged stage must not reset it"); +} + +/// The launch, from argv to the window being up: nothing named on the +/// command line is read before there is a window, so all a launch does is +/// sort argv into the file that becomes the timeline and the queue that is +/// read through -- and a run with no arguments has neither, exactly as it +/// had none before. +#[test] +fn a_launch_queues_the_file_it_names_instead_of_opening_it() { + let film = PathBuf::from("/films/Dune.mkv"); + let extra = PathBuf::from("/films/Titles.mov"); + let (arg, queue) = launch_queue([film.clone(), extra.clone()].into_iter()); + assert_eq!(arg.as_deref(), Some(film.as_path()), "argv[1] is the open"); + // In the order they were named, the timeline's file first: six header + // walks racing over one disk finish no sooner than six in a row, and + // the one the person is waiting to watch goes first. + assert_eq!(queue, [film, extra], "argv, in arrival order"); + // ...and no argument at all is still the empty window: nothing to open + // and nothing to read. + let (arg, queue) = launch_queue(std::iter::empty()); + assert_eq!(arg, None); + assert!(queue.is_empty(), "no argv, nothing queued"); +} + +/// Which door a queued file goes through. One queue carries the file argv +/// named and every import behind it, so this fork -- made when the worker +/// starts and carried to the landing as a [`Landed`] -- is the whole state +/// machine: the named file becomes the timeline (a `.edith` restoring a +/// whole one), everything else joins the library, including the very same +/// film dropped again once the open has landed. +#[test] +fn the_file_argv_named_lands_as_the_timeline_and_everything_behind_it_as_imports() { + let film = PathBuf::from("/films/Dune.mkv"); + let extra = PathBuf::from("/films/Titles.mov"); + let project = PathBuf::from("/films/Dune.edith"); + assert_eq!(arrival(Some(&film), &film), Landing::Open); + assert_eq!(arrival(Some(&project), &project), Landing::Project); + assert_eq!(arrival(Some(&film), &extra), Landing::Import); + // Cleared as it lands: a drop of the film already on the timeline is an + // import, which is what a drop has always been. + assert_eq!(arrival(None, &film), Landing::Import); + // ...except a `.edith`, which is a whole timeline and has nothing to be + // imported into: dropped or picked, it lands where argv's does, and its + // open is the worker's like every other. + assert_eq!(arrival(None, &project), Landing::Project); + assert_eq!(arrival(Some(&film), &project), Landing::Project); +} + +/// What the window says while the file argv named is being read: the file's +/// name, the read that is running, and a clock proving the window is +/// answering -- in the *opening* wording, because the one person who typed +/// that name is not importing anything. +#[test] +fn the_named_file_is_read_under_an_opening_line_not_an_importing_one() { + let opening = import_line("Dune.mkv", ImportStage::Header, 0.4, 0.4, 1, true); + assert!( + opening.starts_with("OPENING Dune.mkv · reading the header"), + "{opening}" + ); + assert!(opening.ends_with("· 1 more waiting"), "{opening}"); + // Twelve seconds into a cold 25 GB header walk, which is the whole + // reason the window is up: it says the read is still moving through the + // same stage and that this is not a freeze. + let stalled = import_line("Dune.mkv", ImportStage::Header, 12., 12., 0, true); + assert!(stalled.starts_with("OPENING Dune.mkv · still"), "{stalled}"); + assert!(stalled.contains("not frozen"), "{stalled}"); + assert!(stalled.contains("0:12 elapsed"), "{stalled}"); + // The files behind it are imports and still say so. + let import = import_line("Titles.mov", ImportStage::Header, 0.4, 0.4, 0, false); + assert!(import.starts_with("IMPORTING Titles.mov"), "{import}"); +} + +/// One gesture over the real gate, with the plumbing around it spelled out: +/// a write reseeks (the worker owes a frame again), a landed frame clears +/// that and flushes what is held, and the release flushes whatever the +/// worker is doing. Forty snapped steps and four frames delivered must cost +/// five writes -- the press's and one per frame -- and not forty, which is +/// the 22-30 s freeze this exists to remove. +#[test] +fn a_bar_wide_sweep_writes_once_per_frame_delivered() { + let mut stash: Option = None; + let mut written = Vec::new(); + let mut busy = false; + for step in 0..40 { + if let Some(value) = stash_or_write(&mut stash, step, step == 0, busy) { + // What `write_color` does: the write supersedes the stash and + // reseeks, so the worker owes a frame from here. + stash = None; + written.push(value); + busy = true; + } + // A frame lands every tenth sample: `pump` clears the seek and the + // render flushes what the drag held back. + if step % 10 == 9 { + busy = false; + if let Some(value) = stash.take() { + written.push(value); + busy = true; + } + } + } + // The release, whatever the worker is doing. + written.extend(stash.take()); + assert_eq!(written, vec![0, 9, 19, 29, 39], "one write per frame landed"); +} + +/// The one value a gesture may never lose: where the hand let go. The +/// release samples into a busy worker -- so the sample is held -- and the +/// flush behind it is what writes it. +#[test] +fn a_release_lands_the_value_the_hand_let_go_on() { + let mut stash = None; + assert_eq!(stash_or_write(&mut stash, 7, false, true), None); + assert_eq!(stash_or_write(&mut stash, 11, false, true), None); + assert_eq!(stash.take(), Some(11), "the release writes the last sample"); + // The press is never held: it is the undo step the gesture rolls back + // to, and one taken a frame late is a snapshot of the wrong grade. + assert_eq!(stash_or_write(&mut stash, 3, true, true), Some(3)); + assert_eq!(stash, None); + // Nothing to hold when the worker is idle: the write goes straight out. + assert_eq!(stash_or_write(&mut stash, 5, false, false), Some(5)); + assert_eq!(stash, None); +} + +/// A seek says nothing until it has stood: an ordinary one is a flicker and +/// a cold read of a big file is the case worth words. +#[test] +fn a_seek_says_so_only_once_it_has_stood() { + assert_eq!(seek_line(None), None, "no seek, no line"); + assert_eq!(seek_line(Some(Duration::from_millis(300))), None); + let line = seek_line(Some(SEEK_STALL + Duration::from_secs(7))).expect("past the stall"); + assert!(line.contains("still opening the picture"), "{line}"); + assert!(line.contains("not frozen"), "{line}"); + assert!(line.contains("0:09 elapsed"), "{line}"); +} + +/// The silence card's own state machine, driven the way a repaint drives +/// it: a worker moves its mark, the poll notices and restarts the stall +/// clock, and the line says a read has stopped only when it actually has. +/// The card is up through all of it -- that is the whole change, since the +/// same decode used to run on the render thread and hold the frame for +/// fifty-one seconds on a 25 GB film. +#[test] +fn a_silence_card_is_up_while_its_scan_runs_and_says_where_it_has_got_to() { + use std::sync::Arc; + use std::sync::atomic::Ordering::Relaxed; + let progress = Arc::new(engine::silence::Progress::default()); + // Two hours and eight minutes, as the header claims it. + progress.total.store(7680, Relaxed); + let started = Instant::now() - Duration::from_secs(9); + let mut scan = SilenceScan { + key: (PathBuf::from("/films/A Film.mkv"), 0, 0, 192_000), + started, + progress: Arc::clone(&progress), + seen: 0, + since: started, + }; + // Nine seconds and the mark has not moved: past the wait a person + // tolerates, so the line stops pretending it is a progress line. + let since = scan.poll(); + assert!(since > IMPORT_STALL, "{since}"); + let stalled = silence_line(0., 768., 9., since); + assert!(stalled.contains("still reading the sound"), "{stalled}"); + assert!(stalled.contains("not frozen"), "{stalled}"); + assert!(stalled.contains("0:00 of ~12:48 scanned"), "{stalled}"); + assert!(stalled.contains("0:09 elapsed"), "{stalled}"); + // The worker reports, and the stall clock restarts even though the + // elapsed one does not -- the two clocks' whole distinction. + let mut last = 0; + for deci in [83, 1_140, 4_002] { + progress.scanned.store(deci, Relaxed); + let since = scan.poll(); + assert!(since < IMPORT_STALL, "{since}"); + assert!(scan.seen > last, "{} after {last}", scan.seen); + last = scan.seen; + } + let moving = silence_line(scan.seen as f32 / 10., 768., 9., 0.2); + assert_eq!(moving, "SCANNING · 6:40 of ~12:48 scanned · 0:09 elapsed"); + assert!(!moving.contains("still"), "{moving}"); + // A header that does not say how long the track is says nothing rather + // than guessing at it. + let unknown = silence_line(60., 0., 61., 0.2); + assert_eq!(unknown, "SCANNING · 1:00 scanned · 1:01 elapsed"); + // A mark that comes back the same is not the same fact as one that + // moved: the poll only restarts on a change. + let held = scan.since; + scan.poll(); + assert_eq!(scan.since, held, "an unchanged mark must not reset it"); +} + +/// The cache is per scanned stretch, which is what stops two films +/// thrashing each other's fifty seconds: A, then B, then A again is *one* +/// decode of A. And a stretch already being read is waited for rather than +/// read twice -- both halves of an A/V take name the same file and the same +/// frames. A *trimmed* A is not A: it is a shorter read of its own, which +/// is the whole point of scanning the clip instead of the file. +#[test] +fn a_second_film_does_not_cost_the_first_one_its_levels() { + let (a, b) = ( + (PathBuf::from("/films/a.mkv"), 0, 0, 3000), + (PathBuf::from("/films/b.mkv"), 0, 0, 3000), + ); + let half = (PathBuf::from("/films/a.mkv"), 0, 0, 1500); + let mut cache: std::collections::HashMap = std::collections::HashMap::new(); + let mut started = Vec::new(); + // What a card open does, three times over, with the worker landing + // between each: plan, and start what the plan says to start. + for key in [&a, &b, &a] { + match scan_plan(cache.contains_key(key), None, key) { + ScanPlan::Start => { + started.push(key.clone()); + cache.insert(key.clone(), ()); + } + ScanPlan::Marks => {} + ScanPlan::Wait => unreachable!("nothing is running"), + } + } + assert_eq!(started, vec![a.clone(), b.clone()], "A was decoded twice"); + // The single-slot cache this replaced would have evicted A when B + // landed; both are held. + assert!(cache.contains_key(&a) && cache.contains_key(&b)); + // A scan in flight on the same source is joined, not restarted -- and + // one on another source is not waited for. + assert_eq!(scan_plan(false, Some(&a), &a), ScanPlan::Wait); + assert_eq!(scan_plan(false, Some(&b), &a), ScanPlan::Start); + // Levels in hand beat a worker either way: the marks are arithmetic. + assert_eq!(scan_plan(true, Some(&a), &a), ScanPlan::Marks); + // The same file cut in half is a read of its own: neither A's levels + // nor A's worker answers for it. + assert_eq!( + scan_plan(cache.contains_key(&half), None, &half), + ScanPlan::Start + ); + assert_eq!(scan_plan(false, Some(&a), &half), ScanPlan::Start); + // ...and the seconds asked for are the clip's, at the project's rate. + assert_eq!(source_secs(&half, 30.), (0., 50.)); + assert_eq!(source_secs(&(half.0.clone(), 0, 900, 1500), 30.), (30., 50.)); + // A rate that is not one reads the file rather than nothing. + assert_eq!(source_secs(&half, 0.), (0., f64::INFINITY)); +} + +/// The import door's split, which is what keeps the render thread out of a +/// header walk: what the worker probed and what the landing registers add up +/// to exactly the rows, lengths and refusals the in-place import lands. +#[test] +fn probing_ahead_lands_exactly_what_importing_in_place_lands() { + use std::sync::atomic::AtomicU8; + let stage = AtomicU8::new(ImportStage::Header as u8); + let plain = { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open"); + session.set_gain(0.0); + session.import(&asset("test_av2.mp4")).expect("av2 matches"); + ( + session.sources().to_vec(), + session.file_frames(&asset("test_av2.mp4")), + session.timeline_duration(), + ) + }; + let split = { + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open"); + session.set_gain(0.0); + let (subs, probe) = + read_parts(&asset("test_av2.mp4"), &stage, Some(session.import_gate())); + // This mp4 is walked now (an mp4 can carry `tx3g`) and has no + // subtitle track in it, so the worker hands over an empty list -- + // the same thing the import lands with. + assert!(subs.expect("an mp4 is readable").is_empty()); + let probe = probe + .expect("a container is probed on the worker") + .expect("av2 matches"); + session + .import_probed(&asset("test_av2.mp4"), probe) + .expect("av2 matches"); + ( + session.sources().to_vec(), + session.file_frames(&asset("test_av2.mp4")), + session.timeline_duration(), + ) + }; + assert_eq!(plain, split); + // ...and it leaves the stage where the line can read it: a worker that + // never announced its second read would show one that never ends. + assert_eq!( + ImportStage::from_u8(stage.load(std::sync::atomic::Ordering::Relaxed)), + ImportStage::Subtitles + ); + // A refusal is the engine's refusal, and now it is *the* refusal: the + // walk happens once, on the worker, so what the probe says is what the + // notice shows -- worded exactly as importing in place worded it. + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open"); + session.set_gain(0.0); + let (_, probe) = read_parts(&asset("test_25fps.mp4"), &stage, Some(session.import_gate())); + let on_the_worker = probe + .expect("a container is probed") + .map(|_| ()) + .map_err(|e| e.to_string()); + assert_eq!( + on_the_worker, + session + .import(&asset("test_25fps.mp4")) + .map(|_| ()) + .map_err(|e| e.to_string()) + ); + // A timeline that moved while the worker read is not one the probe was + // decided against, so the probe is not trusted -- the import is simply + // taken the slow way and lands the same row. + let mut moved = PlaybackSession::open(asset("test_av.mp4")).expect("open"); + moved.set_gain(0.0); + let (_, probe) = read_parts(&asset("test_av2.mp4"), &stage, Some(moved.import_gate())); + moved.import(&asset("test_still.png")).expect("a still joins"); + let stale = probe.expect("a container is probed").expect("av2 matches"); + assert_eq!( + moved.import_probed(&asset("test_av2.mp4"), stale).ok(), + Some(2), + "a stale probe still lands the file, by the door that re-reads it" + ); + // A path nothing can read is refused by the worker now, in the engine's + // own words: nothing walks it a second time to re-word it, and neither + // half is a panic. + let (subs, probe) = read_parts( + std::path::Path::new("/no/such/film.mkv"), + &stage, + Some(session.import_gate()), + ); + assert!(subs.is_err(), "the cue walk comes back as a refusal"); + assert!( + probe.expect("a container is probed").is_err(), + "and so does the container walk" + ); +} + +/// The import door's two halves, split across the worker hop: what +/// [`read_ahead`] walks is exactly what the render thread would have walked, +/// and pushing it says what walking it in place used to say. +#[test] +fn an_imports_subtitles_are_read_by_the_worker_and_only_pushed_here() { + use std::sync::atomic::AtomicU8; + let stage = AtomicU8::new(ImportStage::Header as u8); + let film = asset("test_subs.mkv"); + // The in-place walk (`subtitle_notice`) and the split one land the same + // tracks and the same tail on the same timeline. + let mut in_place = PlaybackSession::open(asset("test_av.mp4")).expect("open"); + in_place.set_gain(0.0); + let said = subtitle_notice(&mut in_place, &film); + let mut split = PlaybackSession::open(asset("test_av.mp4")).expect("open"); + split.set_gain(0.0); + let (walked, _) = read_parts(&film, &stage, Some(split.import_gate())); + let walked = walked.expect("the mkv is readable"); + assert_eq!(subtitle_tail(&mut split, Ok(walked)), said); + assert_eq!(split.subtitles().len(), in_place.subtitles().len()); + // The same file twice is still one row, and still says so: the dedupe + // lives in the push, which is the half that stayed here. + let (again, _) = read_parts(&film, &stage, Some(split.import_gate())); + let again = again.expect("the mkv is readable"); + assert_eq!(subtitle_tail(&mut split, Ok(again)), None); + // A standalone `.srt` is walked by the same worker: an import of one is + // not a door that reads on the render thread either. + let srt = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../engine/tests/data/test_subs.srt") + .canonicalize() + .expect("the subtitle fixture"); + assert_eq!( + read_parts(&srt, &stage, Some(split.import_gate())) + .0 + .expect("the srt is readable") + .len(), + 1 + ); + // ...and a refusal is worded as a tail, never as a failed import. + let unread: Subs = Err("nothing to read".into()); + assert_eq!( + subtitle_tail(&mut split, unread), + Some(" — SUBTITLES UNREAD: nothing to read".to_string()) + ); +} + +#[test] +fn every_codec_row_is_offered_or_says_why_not() { + // One row per codec, and the boxes it can go in are the container row's + // business: seven rows that pick, one that says why it cannot. A codec + // twice over (AV1 · MKV beside AV1 · MP4) was two rows asking the same + // question, and five picture rows above the fold is what the card was + // called unfriendly for. + let offered: Vec<&[Format]> = FORMATS + .iter() + .map(|&(row, ..)| row) + .filter(|row| !row.is_empty()) + .collect(); + assert_eq!( + offered, + vec![ + &[Format::Mp4][..], + &[Format::Av1, Format::Av1Mp4][..], + &[Format::Hevc, Format::HevcMp4][..], + &[Format::Wav][..], + &[Format::Flac][..], + &[Format::Mp3][..], + &[Format::Ogg][..], + ] + ); + // Every format the engine writes is on exactly one row: one the card + // cannot reach is one nobody can pick. + for format in [ + Format::Mp4, + Format::Av1, + Format::Av1Mp4, + Format::Hevc, + Format::HevcMp4, + Format::Wav, + Format::Flac, + Format::Mp3, + Format::Ogg, + ] { + assert_eq!( + FORMATS + .iter() + .filter(|(row, ..)| row.contains(&format)) + .count(), + 1, + "{format:?}" + ); + } + // The boxes the container row offers, and what the extension of each is + // -- the destination follows the format, so these are what a file gets + // named with. + assert_eq!(containers(Format::Av1), [Format::Av1, Format::Av1Mp4]); + assert_eq!(containers(Format::HevcMp4), [Format::Hevc, Format::HevcMp4]); + assert_eq!(containers(Format::Mp3), [Format::Mp3]); + assert_eq!(Format::Av1.ext(), "mkv"); + assert_eq!(Format::Av1Mp4.ext(), "mp4"); + assert_eq!(Format::Hevc.ext(), "mkv"); + assert_eq!(Format::HevcMp4.ext(), "mp4"); + // The container key walks the row and wraps, and does nothing at all + // where there is only one box -- a stroke must not invent a choice the + // card is not offering. + assert_eq!(next_container(Format::Av1), Format::Av1Mp4); + assert_eq!(next_container(Format::Av1Mp4), Format::Av1); + assert_eq!(next_container(Format::Hevc), Format::HevcMp4); + assert_eq!(next_container(Format::Mp4), Format::Mp4); + assert_eq!(next_container(Format::Wav), Format::Wav); + for (row, stroke, label, detail) in FORMATS { + assert!(!label.is_empty(), "a row with no name"); + // A refused row is a row with a reason, never a hidden one: an + // empty detail column would read as an oversight. + assert!(!detail.is_empty(), "{label} says nothing"); + // Every row that can be picked has a key of its own, and no row + // that cannot has one: the card is drivable without a pointer. + assert_eq!(!row.is_empty(), !stroke.is_empty(), "{label}"); + if let Some(&first) = row.first() { + assert_eq!( + format_key(stroke, first), + Some(first), + "{label} keys to itself" + ); + assert!( + stroke.parse::().is_err(), + "{label} takes a digit the bitrate needs" + ); + // Every box on one row is the same codec, so the quality rows + // do not change meaning when the container does. + assert!(row.iter().all(|f| f.has_video() == first.has_video())); + assert!( + row.iter() + .all(|f| bitrate_refusal(*f) == bitrate_refusal(first)) + ); + } + } + // No two rows share a key, and none of them is a stroke the card already + // answers to itself -- an ambiguous key is a key that picks the wrong + // thing on a card that has no other input. + let keys: Vec<&str> = FORMATS + .iter() + .map(|&(_, stroke, ..)| stroke) + .filter(|stroke| !stroke.is_empty()) + .collect(); + for (i, key) in keys.iter().enumerate() { + assert!(!keys[i + 1..].contains(key), "{key} picks two rows"); + assert!( + !["c", "q", "d", "g", "r", "enter", "backspace", ESCAPE].contains(key), + "{key} is already the card's own" + ); + } + assert_eq!( + format_key("a", Format::Mp4), + Some(Format::Av1Mp4), + "the box already chosen is kept" + ); + assert_eq!( + format_key("a", Format::Wav), + Some(Format::Av1), + "and a codec with no such box takes its first" + ); + assert_eq!(format_key("h", Format::Av1Mp4), Some(Format::HevcMp4)); + assert_eq!(format_key("p", Format::Mp4), Some(Format::Mp3)); + assert_eq!( + format_key("m", Format::Mp3), + Some(Format::Mp4), + "not MP3, which is p" + ); + assert_eq!( + format_key("x", Format::Mp4), + None, + "a stroke no row carries" + ); + assert_eq!(format_key("o", Format::Mp4), Some(Format::Ogg)); + // The one codec left that this program reads and cannot write is a row + // of its own, refused by name rather than absent: VP9, because AV1 is + // the row that replaced it. Its reason travels with it, in the row or in + // the footer line that collects them -- either way it is on screen + // without a click. OGG was the other one until `rusty_vorbis` gave this + // project an encoder, and the row that says so is the row above. + let (row, _, _, detail) = FORMATS + .into_iter() + .find(|(_, _, name, _)| *name == "VP9") + .expect("VP9 has a row"); + assert!(row.is_empty(), "VP9 is not offered"); + assert!(detail.contains("replaces it"), "VP9: {detail}"); + let (row, _, _, detail) = FORMATS + .into_iter() + .find(|(_, _, name, _)| *name == "OGG") + .expect("OGG has a row"); + assert_eq!(row, [Format::Ogg], "OGG is a row that picks now"); + assert!( + detail.contains("rusty_vorbis"), + "the row names the encoder like every other live one: {detail}" + ); + // Both AV1 boxes say they carry sound: the file used to be picture only, + // and a line that still said so would be the lie a user plays the file + // to find out about. HEVC says intra-only before anyone waits on one -- + // a file several times the size, which the disk would otherwise say. + for format in [Format::Av1, Format::Av1Mp4] { + assert!(format_line(format).starts_with("AV1 · ")); + } + for format in [Format::Hevc, Format::HevcMp4] { + assert!(format_line(format).starts_with("HEVC intra · ")); + } + // The head names the box every format goes in, which is what the + // destination is then named after. + for format in [ + Format::Mp4, + Format::Av1, + Format::Av1Mp4, + Format::Hevc, + Format::HevcMp4, + ] { + assert!( + format_line(format).contains(&format.ext().to_uppercase()), + "{format:?}: {}", + format_line(format) + ); + } + // ...and it stays inside the one line the card budgets for it: the + // longest of them, with every field after it, against the 76 characters + // that fit at `EXPORT_W`. + let longest = summary_head( + Format::Hevc, + Some(((1920, 1080), 23.976)), + "AAC · SW encode (rusty_aac)", + ); + assert!( + longest.chars().count() <= 76, + "{longest} is {} long", + longest.chars().count() + ); + assert!( + FORMATS + .into_iter() + .any(|(row, _, _, detail)| row.contains(&Format::Hevc) && detail.contains("intra")) + ); + // Only a picture encoder is given a bitrate, and the quality rows dim + // with the reason for every format that is not one. + for format in [ + Format::Mp4, + Format::Av1, + Format::Av1Mp4, + Format::Hevc, + Format::HevcMp4, + ] { + assert!( + format.has_video() && bitrate_refusal(format).is_none(), + "{format:?}" + ); + } + for format in [Format::Wav, Format::Flac, Format::Mp3] { + assert!(!format.has_video()); + assert!( + bitrate_refusal(format).is_some(), + "{format:?} dims silently" + ); + } + assert!(bitrate_refusal(Format::Wav).unwrap().contains("lossless")); + // MP3 has a rate and it is the *Sound* row's: the quality rows are the + // picture's, and this refusal used to claim a fixed 256 kbps that the + // Sound row can now change under it. + assert!(bitrate_refusal(Format::Mp3).unwrap().contains("Sound row")); + assert!( + !format_line(Format::Mp3).contains("256"), + "the summary states a rate the Sound row can change under it" + ); + // The destination follows the format and keeps the stem, mp4 included. + assert_eq!( + retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav), + std::path::Path::new("/a/take.export.wav") + ); + assert_eq!( + retarget(std::path::Path::new("/a/take.export.wav"), Format::Mp4), + std::path::Path::new("/a/take.export.mp4") + ); + assert!(format_line(Format::Flac).contains("lossless")); +} + +/// The one line the card is answerable for: what it says is on screen before +/// the button is pressed, and every field of it is one `ffprobe` reads back +/// off the file that comes out. +#[test] +fn the_summary_states_the_file_before_it_is_written() { + let head = summary_head(Format::Mp4, Some(((1920, 1080), 30.)), "AAC copy"); + for field in ["H.264", "MP4", "1920x1080", "30 fps", "AAC copy"] { + assert!(head.contains(field), "{field} missing from {head}"); + } + // The rate as a person writes it, and the ratio one spelled out rather + // than rounded to a rate nothing is written at. + assert_eq!(fps_label(30.), "30"); + assert_eq!(fps_label(24000. / 1001.), "23.976"); + assert_eq!(fps_label(29.97002997), "29.97"); + // A format with no picture states no size and no rate it does not write. + let audio = summary_head(Format::Wav, Some(((1920, 1080), 30.)), "PCM · SW (hound)"); + assert!( + !audio.contains("1920x1080") && !audio.contains("fps"), + "{audio}" + ); + assert!(audio.contains("PCM · SW (hound)")); + // ...and one with no sound on the timeline says that, rather than + // leaving the field out and reading as a file with sound in it. + assert!( + summary_head(Format::Mp4, Some(((640, 360), 25.)), "no sound to write") + .contains("no sound to write") + ); + // The tail: where it lands, about how big, and what will encode it -- + // never a guessed seat, and no seat at all for a format with no picture. + let tail = summary_tail( + Path::new("/a/take.export.mp4"), + Some(45_000_000), + Some("VA-API"), + true, + ); + assert!(tail.starts_with("take.export.mp4"), "{tail}"); + assert!( + tail.contains("≈ 45 MB") && tail.contains("VA-API"), + "{tail}" + ); + assert!(summary_tail(Path::new("/a/x.mp4"), None, None, true).contains("encoder …")); + assert!(!summary_tail(Path::new("/a/x.wav"), None, None, false).contains("encoder")); + assert!(!summary_tail(Path::new("/a/x.wav"), None, None, false).contains("MB")); + // 6 Mbps over a minute is 45 MB. `Auto` has no figure to estimate from + // and an empty timeline no length: neither invents one. + assert_eq!(estimated_bytes(Some(6_000_000), 60.), Some(45_000_000)); + assert_eq!(estimated_bytes(Some(2_000_000), 90.), Some(22_500_000)); + assert_eq!(estimated_bytes(None, 60.), None); + assert_eq!(estimated_bytes(Some(6_000_000), 0.), None); + assert_eq!(estimated_bytes(Some(0), 60.), None); + // ...and a short one is not nothing. Three seconds at the floor + // bitrate is 375 kB, which used to round to the "≈ 0 MB" this line + // exists to never say -- the shortest export a frame can make is + // still a real file with a real size. + let short = estimated_bytes(Some(1_000_000), 3.).expect("a rate and a length"); + assert_eq!(size_label(short), "375 kB"); + let frame = summary_tail(Path::new("/a/x.mp4"), estimated_bytes(Some(1_000_000), 1. / 60.), None, true); + assert!( + frame.contains("≈ 2 kB") && !frame.contains("0 MB") && !frame.contains("0 kB"), + "{frame}" + ); + // The boundary reads in the unit that can state it, either side. + assert_eq!(size_label(999_600), "1 MB"); + assert_eq!(size_label(499_000), "499 kB"); + assert_eq!(size_label(1), "1 kB"); +} + +/// Which cue is on screen when: the whole of what the overlay decides, and +/// the one piece of it that is arithmetic rather than layout. +#[test] +fn a_cue_is_on_screen_from_its_start_until_the_moment_it_ends() { + use engine::subtitle::Cue; + let cue = |start_us, end_us, text: &str| Cue { + start_us, + end_us, + text: text.to_string(), + image: None, + }; + // Two cues that hand over exactly, and one that overlaps the second -- + // a sign over a line of dialogue, which is two plates at one moment. + let cues = [ + cue(500_000, 1_500_000, "first line"), + cue(1_500_000, 2_500_000, "second line"), + cue(2_000_000, 2_200_000, "a sign"), + ]; + let at = |t: f64| -> Vec<&str> { + cues_at(&cues, t) + .into_iter() + .map(|c| c.text.as_str()) + .collect() + }; + // Before the first, between none of them: nothing, which is what makes + // the overlay disappear rather than sit there empty. + assert!(at(0.).is_empty()); + assert!(at(0.4).is_empty()); + assert!(at(3.).is_empty()); + assert_eq!(at(0.5), ["first line"], "on at its own start"); + assert_eq!(at(1.4), ["first line"]); + // Half-open: the frame the first ends on is the second's, never both. + assert_eq!(at(1.5), ["second line"]); + assert_eq!(at(2.1), ["second line", "a sign"], "two at once stack"); + assert_eq!(at(2.2), ["second line"], "the sign is over"); + // ...and the end of the last one is the end of it. + assert!(at(2.5).is_empty()); + // A negative time is before everything rather than a panic: the + // playhead is clamped, but nothing here depends on that. + assert!(at(-1.).is_empty()); +} + +/// The two places a subtitle is drawn -- the plate over the picture and the +/// strip under the lanes -- inside the 640x360 floor the rest of this window +/// is sized for, and the plate readable on whatever the film is showing. +#[test] +fn the_subtitle_plate_and_strip_fit_the_smallest_window() { + // The strip costs the panel its own row and the panel's gap, and costs + // nothing at all when there is no track to draw. + assert_eq!(subtitle_strip_h(false), 0.); + assert_eq!(subtitle_strip_h(true), SUB_LANE_H + 8.); + // What is left for the picture at the floor, with the panel a project + // starts with and the strip under it. + let picture = 360. - HEADER_H - panel_h(2) - subtitle_strip_h(true); + assert!(picture > 0., "the strip pushed the picture off the window"); + // A two-line cue and the gap under it fit inside that, which is the + // whole claim: the plate sits *over* the picture and must not need more + // of it than there is. + assert!( + SUB_BOTTOM + 2. * SUB_LINE_H <= picture, + "a two-line cue does not fit the smallest picture" + ); + // The text sits on its line rather than being clipped by it. + assert!(SUB_LINE_H >= SUB_TEXT); + // White on the plate, not chrome on chrome: a cue is read against the + // film, and this is the one pair here that has to survive any picture. + for id in crate::ui::theme::PaletteId::ALL { + assert!(contrast(id.palette().SUB_FG, 0x000000) >= 7., "{id:?}"); + } + // The strip is a picture and not a target -- nothing on it takes a + // click -- which is the only reason it may be under `HIT_MIN`. + assert!(SUB_LANE_H < HIT_MIN && SUB_LANE_H > 0.); + // The library's own list of tracks scrolls past three rather than + // taking the media list's room. + assert_eq!(SUB_ROWS_H / ROW_H, 3.); + assert!(ROW_H >= HIT_MIN, "a subtitle row is clicked to pick it"); + // At the floor there are no group headers at all: the list is one row + // tall there, and a header would name a film and then show none of it. + // The rows go on naming their own file, so nothing is lost by it. + assert!(!sub_headers_fit(360.), "a header at the floor eats the track"); + // At the size the window opens on there is room for a header and the + // tracks under it, which is the only condition it is drawn on. + assert!(sub_headers_fit(720.)); + // ...and where it is drawn it fits inside the same capped list, header + // and two rows under it, without the tracks losing their budget. + assert!(SUB_HEAD_H + 2. * ROW_H <= SUB_ROWS_H); + // A header takes no click -- there is nothing to fold and nothing to + // aim at -- which is the only reason it may be under `HIT_MIN`. + assert!(SUB_HEAD_H < HIT_MIN && SUB_HEAD_H > 0.); +} + +/// What the rows of both lists do with a name too long for the column: two +/// episodes off one release differ in their last two characters, and a name +/// cut from the right is the same row twice. +#[test] +fn a_long_name_is_cut_out_of_its_middle_so_two_episodes_stay_two_rows() { + let (a, b) = ( + "A Long Release Name Of A Series 01", + "A Long Release Name Of A Series 02", + ); + // The two call sites at the narrowest the column ever is: a media row's + // name gets the row's whole width, a subtitle row's file prefix gets a + // share of it because the language has to fit beside it. + let media = row_text_w(LIBRARY_MIN_W); + let prefix = media * SUB_STEM_SHARE; + for width in [media, prefix] { + assert!(width > 0., "the floor leaves a row no words at all"); + assert_ne!( + clip_middle(a, width), + clip_middle(b, width), + "{width}px: two episodes read as one row" + ); + // Both ends survive: the release's name at the front, the number + // that tells them apart at the back. + assert!(clip_middle(a, width).starts_with(&a[..2])); + assert!(clip_middle(a, width).ends_with("01")); + assert!(clip_middle(a, width).contains('…')); + // Never wider than the column can hold, gap included. + assert!(clip_middle(a, width).chars().count() <= (width / 6.) as usize + 1); + } + // A name the width holds is left exactly as it is -- no gap, nothing + // dropped -- and so is a name at any width once the column is wide. + assert_eq!(clip_middle("eng.srt", 400.), "eng.srt"); + assert_eq!(clip_middle(a, 4000.), a); + // Nothing panics at a width no column ever has, and something of both + // ends is still there. + assert_eq!(clip_middle(a, 0.).chars().count(), 5); + assert!(clip_middle(a, 0.).ends_with('1')); + // Counted in characters and not bytes: a name in another script is cut + // between its letters, not through one. + assert_eq!(clip_middle("ααααααααααααααα", 24.), "αα…αα"); +} + +/// The two doors subtitles arrive through, end to end on the fixtures: a +/// file beside the media and the tracks inside an mkv, what the overlay then +/// says at a given moment, and where the strip draws it. +#[test] +fn subtitles_arrive_beside_the_media_and_inside_it() { + // Which door a path goes through is decided before anything is opened. + // ...and a `.mks` is one, the subtitles of a Matroska file alone: it has + // no source in it to import, so the drop door has to send it where `+ S` + // sends it. Its two siblings are media and must not come here -- a + // `.mka` is a song this would stop importing. + for name in ["subs.srt", "SUBS.SRT", "a.vtt", "a.ass", "a.ssa", "s.mks", "S.MKS"] { + assert!(is_subtitle(Path::new(name)), "{name}"); + } + for name in ["a.mp4", "a.mkv", "song.mka", "film.mk3d", "notes.txt", "a"] { + assert!(!is_subtitle(Path::new(name)), "{name}"); + } + // Every container the engine can walk for tracks inside it, Matroska + // and ISO-BMFF alike -- an mp4 carries `tx3g`, so the app has to ask it. + // The Matroska half is the engine's own closed set, extension for + // extension, so no file is walked here that it would refuse there. + for name in [ + "film.MKV", "clip.webm", "clip.mp4", "a.m4v", "a.MOV", "song.mka", "s.mks", "f.MK3D", + ] { + assert!(carries_subtitles(Path::new(name)), "{name}"); + assert!( + engine::demux::is_matroska(Path::new(name)) + || matches!( + Path::new(name) + .extension() + .and_then(|e| e.to_str()) + .map(str::to_ascii_lowercase) + .as_deref(), + Some("mp4" | "m4v" | "mov") + ), + "{name} is walked by the app but not by the engine" + ); + } + for name in ["song.wav", "still.png", "notes.txt", "a"] { + assert!(!carries_subtitles(Path::new(name)), "{name}"); + } + // The three doors, on the one file that used to split them: what the + // drop/argv door does with it ([`Player::take_import`] routes on + // `is_subtitle`), what the worker reads for it ([`walk_subtitles`]), and + // what `+ S` reads ([`Player::add_subtitles`] -> `parse_subtitles`) are + // the same walk of the same bytes. + let mks = asset("test_subs.mks"); + assert!(is_subtitle(&mks), "the drop door takes it as subtitles"); + let dropped = walk_subtitles(&mks).expect("the drop door's worker reads it"); + let plus_s = PlaybackSession::parse_subtitles(&mks).expect("`+ S` reads it"); + assert!(!dropped.is_empty(), "and there are tracks in it"); + assert_eq!( + dropped.iter().map(|t| &t.label).collect::>(), + plus_s.iter().map(|t| &t.label).collect::>(), + ); + + let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + session.set_gain(0.0); + // Beside the media: the drop door's own call, and the row it makes. + let srt = Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../engine/tests/data/test_subs.srt") + .canonicalize() + .expect("the subtitle fixture"); + assert_eq!(session.import_subtitles(&srt).expect("the .srt imports"), 1); + let track = &session.subtitles()[0]; + assert_eq!(track.label, "test_subs.srt"); + assert_eq!(subtitle_detail(track), "3 cues"); + // What the overlay draws at a moment inside the first cue, and between + // two of them -- the fixture's own timings (0.5-1.5 s, 2.0-3.25 s). + let text = |t: f64| -> Vec { + cues_at(&track.cues, t) + .into_iter() + .map(|c| c.text.clone()) + .collect() + }; + assert_eq!(text(0.7), ["first line"]); + assert!(text(1.8).is_empty(), "between two cues the plate goes"); + assert_eq!(text(2.5), ["second line\nwith a break"]); + // Where the strip puts that first cue: 0.5 s in at 40 px to the second + // is 20 px along, and a second of cue is 40 px wide. + let scale = Scale::default(); + assert_eq!(scale.pps, PPS_DEFAULT); + assert_eq!(cue_box(scale, &track.cues[0]), (20., 40.)); + // Zoomed right out, a cue worth a fraction of a pixel is still a mark. + let far = Scale { + pps: 0.01, + start: 0., + }; + assert_eq!(cue_box(far, &track.cues[0]).1, SUB_CUE_MIN_W); + // ...and scrolled past, its left edge is negative, exactly as a clip + // box's is: the bed clips it. + let scrolled = Scale { + pps: PPS_DEFAULT, + start: 1., + }; + assert_eq!(cue_box(scrolled, &track.cues[0]).0, -20.); + + // Inside the media: the tracks of an mkv, taken by the same call every + // open and import door makes. Two of them in the fixture, named by what + // the file says rather than by number. + let notice = + subtitle_notice(&mut session, &asset("test_subs.mkv")).expect("the mkv carries two"); + assert!(notice.contains('2'), "{notice}"); + assert_eq!(session.subtitles().len(), 3); + assert_eq!(session.subtitles()[1].label, "eng"); + assert_eq!(session.subtitles()[2].label, "fra — Signs"); + assert_eq!(subtitle_detail(&session.subtitles()[1]), "3 cues"); + // The same file twice adds nothing and says nothing. + assert_eq!(subtitle_notice(&mut session, &asset("test_subs.mkv")), None); + // An mp4 is walked too (it can carry `tx3g`); this one holds none, so + // the notice grows no tail. + assert_eq!(subtitle_notice(&mut session, &asset("test_av.mp4")), None); + + // A track that could not be read says why, where its cue count would + // be: what the greyed library row prints, and the whole difference + // between "this film has no subtitles" and "these four are pictures". + let refused = engine::subtitle::SubtitleTrack { + path: PathBuf::from("/a/remux.mkv"), + track: Some(1), + // Neither field, like `SubtitleTrack::refused` leaves them: what is + // refused is never written, and the row keeps the label it was + // refused under. + language: String::new(), + name: String::new(), + label: "eng".into(), + cues: Vec::new(), + bitmap: false, + refused: Some("S_HDMV/PGS subtitles are pictures, not text".into()), + }; + assert!(subtitle_detail(&refused).contains("pictures")); + assert!(cues_at(&refused.cues, 1.).is_empty()); + + // ...and what the plate and the strip draw after a *cut*: the timeline's + // own clock, asked of the engine through the very map an export writes + // the file with (`PlaybackSession::timeline_cues`), so the preview and + // the file cannot drift apart. The numbers are the export's own + // (`export::a_subtitle_file_beside_the_media_keeps_the_timelines_own_ + // clock`): 0.5s..2.5s rippled out of a five-second timeline leaves + // three seconds, which clips the second cue and takes the third away + // altogether -- while the track itself still holds all three, which is + // exactly why the drawing may not read them straight. + let lanes = session.lanes(); + session + .cut_regions(&[(15, 60)], &lanes) + .expect("cut 0.5s..2.5s out"); + assert_eq!(session.timeline_duration(), 3.0); + assert_eq!(session.subtitles()[0].cues.len(), 3, "the track is untouched"); + let mapped = session.timeline_cues(0); + assert_eq!( + mapped + .iter() + .map(|c| (c.start_us, c.end_us)) + .collect::>(), + vec![(500_000, 1_500_000), (2_000_000, 3_000_000)] + ); + // The overlay's own two lines, at the same moments as above. + let drawn = |t: f64| -> Vec { + cues_at(&mapped, t) + .into_iter() + .map(|c| c.text.clone()) + .collect() + }; + assert_eq!(drawn(0.7), ["first line"]); + assert_eq!(drawn(2.5), ["second line\nwith a break"]); + assert!( + drawn(4.2).is_empty(), + "a cue past the cut end is drawn where the file writes none" + ); + // ...and the strip's: the second cue is one second wide now, not 1.25. + assert_eq!(cue_box(scale, &mapped[1]), (80., 40.)); +} diff --git a/crates/app/src/tests/mod.rs b/crates/app/src/tests/mod.rs new file mode 100644 index 0000000..98d0c55 --- /dev/null +++ b/crates/app/src/tests/mod.rs @@ -0,0 +1,219 @@ +//! The window's tests, out of `main.rs` and into a module of their own: the +//! file was sixteen thousand lines and two thirds of them were this. What +//! stays here is what every part of it shares -- the imports, the fixtures, +//! and the source scans the guards read. + +mod editing; +mod view; +mod cards; +mod media; +mod layout; + +use super::{ + ACCENT_PRIMARY, AUDIO_KBPS, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, Ctx, DEFAULT_AUDIO_KBPS, EQ_BANDS_MAX, + EQ_CURVE_STEPS, EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_FREQ_STEP, EQ_GAIN_LIMIT, EQ_GRAPH_H, + EQ_HANDLE, EQ_Q_HIGH, EQ_Q_LOW, EQ_Q_STEP, EQ_SPECTRUM_DB, EQ_TICKS, EQ_W_MAX, ESCAPE, + EXPORT_FIXED_H, EXPORT_ROWS_H, EXPORT_W, Enable, FORMATS, + Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, FG_PRIMARY, + FG_SECONDARY, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, KeyRow, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX, + BG_CANVAS, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H, + MBPS_DIGITS, MBPS_MAX, MBPS_MIN, MB_FLOOR, MENU_W, NO_FILE, NumberEdit, PANEL_H, ROW_ITEMS, RowCtx, RowItem, + Quality, ROW_H, RULER_HIT_H, BG_SELECTED, SCROLL_NOTCH_SHARE, SILENCE_ROWS, + SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, BG_RAISED, SWATCH_W, Source, Speed, StreamInfo, + Transport, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, WAVE_COLS_MAX, Wave, band_label, + bitrate_detail, bitrate_refusal, can_add, cancels_export, clipboard_after_remove, color_snap, commit_mbps, + containers, + enable, envelope, eq_card_w, eq_freq, eq_freq_label, eq_spectrum, eq_x, eq_y, + estimated_bytes, export_path, export_settings, format_key, + format_line, format_refusal, fps_choices, fps_label, frac_along, frac_down, frame_at, + frame_rate_ladder, histogram, + inserted_band, is_bare_modifier, is_project, keymap, keys_filter, keys_rows, lanes_h, + marked, menu_at, menu_items, menu_rows_h, next_audio_kbps, next_container, normalise, nothing_to_play, panel_h, project_path, + LATE_RESYNC, RESYNC_GAP, should_resync, + retarget, row_enable, row_items, scrub_due, secs_label, show_label, silence_rate, size_label, snap_cue, snap_marks, snapped, + SUB_PLAN_CHARS, source_tint, span_partner, speed_at, sub_pick_after_removal, subtitle_plan, summary_head, summary_tail, timecode, transport, + EXPORT_DONE, NOTICES_MAX, STATUS_ERROR, TIMELINE_FIXED_H, TIMELINE_SHARE, lanes_shown, + px_below, rows_below, STATUS_SUCCESS, STATUS_WARNING, notice_tone, + push_notice, typed, unseen_paths, unseen_sources, + whole_take, window_title, +}; + +use super::{ + Choice, EDGE_W, ETA_SPAN, Edge, FITS, FRAME_RATES, LaneKind, PPS_DEFAULT, PPS_MIN, Preset, RESOLUTIONS, Repeat, + Scale, View, + ZOOM_MIN_FRAMES, ZOOM_OUT_MARGIN, ZOOM_STEP, audio_rate_choices, clock, eta_secs, file_name, file_uri, + fit_choices, landing, lane_refuses, library_rows, live_idx, next_fit, next_resolution, + note_progress, px_along, + IMPORT_STALL, Import, ImportStage, SEEK_STALL, ScanKey, ScanPlan, SilenceScan, import_line, + Landing, arrival, launch_queue, + read_ahead, scan_plan, seek_line, silence_line, source_secs, stash_or_write, + repeats, resolution_choices, resolution_ladder, span_label, tone_choices, tone_label, + clip_width, trimmed_clip, trims, unscannable, unusable, + visible_slice, +}; + +use super::{ + SUB_BOTTOM, SUB_CUE_MIN_W, SUB_HEAD_H, SUB_FG, SUB_LANE_H, SUB_LINE_H, SUB_ROWS_H, + SUB_STEM_SHARE, SUB_TEXT, clip_middle, cue_box, + carries_subtitles, cues_at, file_tint, is_subtitle, lang_human, row_text_w, sub_headers_fit, + Subs, subtitle_detail, subtitle_notice, subtitle_tail, + sub_pick_name, subtitle_rows, subtitle_strip_h, walk_subtitles, +}; + +use engine::PlaybackSession; + +use engine::scale::FitPolicy; + +use gpui::{Bounds, Pixels, point, px, size}; + +use std::collections::HashMap; + +use std::path::{Path, PathBuf}; + +use std::time::{Duration, Instant}; + +/// Every line of the window's source there is, as one string. The regions have +/// moved house twice -- one `main.rs`, then `ui/`, then the tests out of it -- +/// and a scan that names its files passes a rule by simply not looking where +/// the code went. So the files are found rather than listed: every `.rs` under +/// `src/`, read at run time. +fn ui_source() -> String { + source_files() + .iter() + .map(|path| std::fs::read_to_string(path).expect("a source file")) + .collect() +} + +/// One named file of that source, for the scans about a single region. +fn src_text(rel: &str) -> String { + std::fs::read_to_string(src_dir().join(rel)).expect("a source file") +} + +fn src_dir() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("src") +} + +/// Every source file the scans read, in a stable order. The tests are not the +/// window, and the keymap is what the window is compared *against* -- a table +/// that vouched for itself would answer every question asked of it. +fn source_files() -> Vec { + let mut found = Vec::new(); + let mut dirs = vec![src_dir()]; + while let Some(dir) = dirs.pop() { + let mut entries: Vec = std::fs::read_dir(&dir) + .expect("the source directory") + .map(|entry| entry.expect("a source entry").path()) + .collect(); + entries.sort(); + for path in entries { + if path.is_dir() { + if path.file_name() != Some("tests".as_ref()) { + dirs.push(path); + } + } else if path.extension() == Some("rs".as_ref()) + && path.file_name() != Some("keymap.rs".as_ref()) + { + found.push(path); + } + } + } + found +} + +fn asset(name: &str) -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")) + .join("../../assets") + .join(name) +} + +/// A source entry for `path` on `stream`, as the project keeps them. +fn source(path: &str, stream: usize) -> Source { + Source { + path: PathBuf::from(path), + audio_stream: stream, + } +} + +fn info( + index: usize, + rate: u32, + channels: u16, + lang: Option<&str>, + decodable: bool, +) -> StreamInfo { + StreamInfo { + index, + codec: if decodable { "aac" } else { "unknown" }.into(), + channels, + sample_rate: rate, + lang: lang.map(str::to_string), + decodable, + } +} + +/// The bed the view tests are drawn on: 200 px at 30 fps, as the drop test +/// above uses. +const TEST_BED: f32 = 200.; + +/// A scale against that bed and a timeline `duration` seconds long. +fn test_view(scale: Scale, duration: f64) -> View { + View { + scale, + bed: TEST_BED, + duration, + fps: 30., + } +} + +/// The two halves a worker hands back for an import, unwrapped: every import +/// lands as a [`Landed::Read`], and a test that has to say so at four call +/// sites is saying it once here. +fn read_parts( + path: &std::path::Path, + stage: &std::sync::atomic::AtomicU8, + gate: Option, +) -> (Subs, crate::Probe) { + match read_ahead(path, stage, gate) { + crate::Landed::Read(subs, probe) => (subs, probe), + _ => panic!("an import into a timeline that is up lands as a read"), + } +} + +/// WCAG 2.1 relative luminance of a packed `0xRRGGBB`. +fn luminance(colour: u32) -> f64 { + let channel = |shift: u32| { + let s = f64::from((colour >> shift) & 0xff) / 255.; + if s <= 0.03928 { + s / 12.92 + } else { + ((s + 0.055) / 1.055).powf(2.4) + } + }; + 0.2126 * channel(16) + 0.7152 * channel(8) + 0.0722 * channel(0) +} + +/// WCAG 2.1 contrast ratio, 1..=21. +fn contrast(a: u32, b: u32) -> f64 { + let (a, b) = (luminance(a), luminance(b)); + (a.max(b) + 0.05) / (a.min(b) + 0.05) +} + +/// The two shapes the engine really builds: a track *of* a file states a +/// language and no title (`of_matroska`, `of_mp4`), and a standalone file +/// states no language and is its own name (`external`). +fn sub(path: &str, track: Option, label: &str) -> engine::subtitle::SubtitleTrack { + let (language, name) = match track { + Some(_) => (label.to_string(), String::new()), + None => (String::new(), label.to_string()), + }; + engine::subtitle::SubtitleTrack { + path: PathBuf::from(path), + track, + language, + name, + label: label.to_string(), + cues: Vec::new(), + bitmap: false, + refused: None, + } +} diff --git a/crates/app/src/tests/view.rs b/crates/app/src/tests/view.rs new file mode 100644 index 0000000..545fb14 --- /dev/null +++ b/crates/app/src/tests/view.rs @@ -0,0 +1,857 @@ +//! 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::*; + +/// 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).as_deref(), + Some("NOT ON V1 — take.mp3 has no picture; drop it on an audio lane") + ); + assert_eq!( + lane_refuses(still, audio).as_deref(), + Some("NOT ON A1 — card.png is a still image; drop it on a video lane") + ); + // ...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), None); + assert_eq!(lane_refuses(still, video), None); + assert_eq!(lane_refuses(movie, video), 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), None); +} + +/// 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 { + start, + in_frame: 0, + out_frame: frames, + source: 0, + link, + eq: None, + color: 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, 300); + all.sort_unstable(); + assert_eq!(all, [0, 100, 100, 160, 160, 300, 400, 430]); + + // The video half in the hand: 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)), 300); + 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)), 0), [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)); +} + +/// The card's rate row: every component the container states and no other, +/// so a track the header is silent about is absent from the line rather +/// than sitting in it as a zero. +#[test] +fn a_rate_row_says_only_what_the_container_stated() { + use crate::MediaBitrate; + let all = MediaBitrate { + total: Some(8_432_000), + video: Some(7_918_000), + audio: Some(128_000), + }; + assert_eq!( + bitrate_detail(Some(all), 1), + "8.4 Mb/s · 7.9 video · 0.13 sound" + ); + // A Matroska states no audio rate of its own: the sound is dropped from + // the line, never drawn as "0". + assert_eq!( + bitrate_detail( + Some(MediaBitrate { + audio: None, + ..all + }), + 1 + ), + "8.4 Mb/s · 7.9 video" + ); + // A still, or anything that would not open: the probe answered, and the + // answer is that nobody said. + assert_eq!( + bitrate_detail(Some(MediaBitrate::default()), 0), + "not stated" + ); + // Asked, not answered yet -- a 12 GB film's walk takes seconds. + assert_eq!(bitrate_detail(None, 2), "…"); + // A dual-audio file: the number is the track that plays, and the line + // says so rather than letting it stand for the AC-3 beside it. + assert_eq!( + bitrate_detail(Some(all), 2), + "8.4 Mb/s · 7.9 video · 0.13 1 of 2" + ); + // Every component of a tiny file is stated, and small: the line changes + // unit, so not one of them reads as the zero it is not. In megabits + // this file was "0.00 Mb/s · 0.00 video · 0.00 sound". + assert_eq!( + bitrate_detail( + Some(MediaBitrate { + total: Some(4_998), + video: Some(113), + audio: Some(2_400), + }), + 1 + ), + "5.0 kb/s · 0.11 video · 2.4 sound" + ); +} + +/// The invariant under the row above, over every rate a container can +/// state: a component the file *does* state never renders as a zero. The +/// probe leaves out what is unstated, so a "0.00" on this card would be it +/// saying a track that plays is silent. +#[test] +fn a_stated_rate_never_renders_as_a_zero() { + use crate::MediaBitrate; + // Every decade from 1 bit a second to a 100 Mb/s master, the rounding + // edges of each unit switch, and every pair of them in one line: the + // line's unit is picked off its smallest component, so the widest + // spread is the one that could round the biggest away. + let edges: Vec = (0..12) + .flat_map(|e| { + let decade = 10_u64.pow(e); + [decade, decade * 4, decade * 5, decade * 9] + }) + .chain([MB_FLOOR - 1, MB_FLOOR, 999_999, 4_998, 113, 2_400]) + .collect(); + for &small in &edges { + for &big in &edges { + let line = bitrate_detail( + Some(MediaBitrate { + total: Some(small.max(big)), + video: Some(big), + audio: Some(small), + }), + 2, + ); + for number in line + .split(" · ") + .filter_map(|part| part.split(' ').next()) + .filter_map(|n| n.parse::().ok()) + { + assert!(number > 0., "{small}/{big} bits a second rendered as {line:?}"); + } + } + } +} + +#[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 export_lands_beside_the_source_and_never_on_it() { + // The whole point: the export of an .mp4 is never that .mp4. + assert_eq!( + export_path("assets/test_baseline.mp4"), + std::path::Path::new("assets/test_baseline.export.mp4") + ); + // A second export of an export is still not its own source. + assert_eq!( + export_path("a.export.mp4"), + std::path::Path::new("a.export.export.mp4") + ); + // Extensionless and dotted-directory names keep the directory intact. + assert_eq!(export_path("clip"), std::path::Path::new("clip.export.mp4")); + assert_eq!( + export_path("/v.1/clip.MP4"), + std::path::Path::new("/v.1/clip.export.mp4") + ); +} + +#[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, + } + .pretty(); + keymap.lookup(key, 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(), + 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() { + assert_eq!(span_label(4.5), "4.5s"); + assert_eq!(span_label(22.5), "22s"); + assert_eq!(span_label(90.), "1.5m"); + assert_eq!(span_label(3600.), "1.0h"); + // The span a five hour timeline is zoomed all the way out to. + assert_eq!(span_label(5. * 3600. * 1.05), "5.2h"); + // Before the first paint there is no bed and so no answer to give. + assert_eq!(span_label(0.), "—"); + assert_eq!(span_label(f64::NAN), "—"); + // A span under a second is a span: the tightest zoom is + // `ZOOM_MIN_FRAMES` across the bed, which on 240 fps slow-motion is + // 0.03s, and "0.0s" would be the pill saying nothing is on the bed. + for fps in [60., 120., 240., 1000.] { + let label = span_label(ZOOM_MIN_FRAMES / fps); + assert_ne!(label, "0.0s", "{fps} fps"); + assert_ne!(label, "0.00s", "{fps} fps"); + } + assert_eq!(span_label(ZOOM_MIN_FRAMES / 240.), "0.03s"); + // 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"); +}