forge
Explore
Log in

Don't you dare go Hollow

The window's tests move out of the file they were testing

Browse files at this commit

e87ada1ff3ae01ee2b6c4036ab423af4198fcf85Ahmet Kaan GümüşParent: e6624f3
  • chore
    • the window's tests move out of the file they were testing
Show full message
🔧 chore(tests): the window's tests move out of the file they were testing

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.

7 changed files +6150 -6080

crates/app/src/main.rsmodified+1 -6080

Diff too large; view file

@@ -10319,6086 +10319,7 @@ fn eta_secs(marks: &[(f32, f32)], elapsed: f32, progress: f32) -> Option<f32> {
10319 }10319 }
10320 10320
10321 #[cfg(test)]10321 #[cfg(test)]
10322-mod tests {
10323- use super::{
10324- ACCENT_PRIMARY, AUDIO_KBPS, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, Ctx, DEFAULT_AUDIO_KBPS, EQ_BANDS_MAX,
10325- EQ_CURVE_STEPS, EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_FREQ_STEP, EQ_GAIN_LIMIT, EQ_GRAPH_H,
10326- EQ_HANDLE, EQ_Q_HIGH, EQ_Q_LOW, EQ_Q_STEP, EQ_SPECTRUM_DB, EQ_TICKS, EQ_W_MAX, ESCAPE,
10327- EXPORT_FIXED_H, EXPORT_ROWS_H, EXPORT_W, Enable, FORMATS,
10328- Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, FG_PRIMARY,
10329- FG_SECONDARY, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, KeyRow, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX,
10330- BG_CANVAS, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H,
10331- MBPS_DIGITS, MBPS_MAX, MBPS_MIN, MB_FLOOR, MENU_W, NO_FILE, NumberEdit, PANEL_H, ROW_ITEMS, RowCtx, RowItem,
10332- Quality, ROW_H, RULER_HIT_H, BG_SELECTED, SCROLL_NOTCH_SHARE, SILENCE_ROWS,
10333- SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, BG_RAISED, SWATCH_W, Source, Speed, StreamInfo,
10334- Transport, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, WAVE_COLS_MAX, Wave, band_label,
10335- bitrate_detail, bitrate_refusal, can_add, cancels_export, clipboard_after_remove, color_snap, commit_mbps,
10336- containers,
10337- enable, envelope, eq_card_w, eq_freq, eq_freq_label, eq_spectrum, eq_x, eq_y,
10338- estimated_bytes, export_path, export_settings, format_key,
10339- format_line, format_refusal, fps_choices, fps_label, frac_along, frac_down, frame_at,
10340- frame_rate_ladder, histogram,
10341- inserted_band, is_bare_modifier, is_project, keymap, keys_filter, keys_rows, lanes_h,
10342- marked, menu_at, menu_items, menu_rows_h, next_audio_kbps, next_container, normalise, nothing_to_play, panel_h, project_path,
10343- LATE_RESYNC, RESYNC_GAP, should_resync,
10344- retarget, row_enable, row_items, scrub_due, secs_label, show_label, silence_rate, size_label, snap_cue, snap_marks, snapped,
10345- SUB_PLAN_CHARS, source_tint, span_partner, speed_at, sub_pick_after_removal, subtitle_plan, summary_head, summary_tail, timecode, transport,
10346- EXPORT_DONE, NOTICES_MAX, STATUS_ERROR, TIMELINE_FIXED_H, TIMELINE_SHARE, lanes_shown,
10347- px_below, rows_below, STATUS_SUCCESS, STATUS_WARNING, notice_tone,
10348- push_notice, typed, unseen_paths, unseen_sources,
10349- whole_take, window_title,
10350- };
10351- use super::{
10352- Choice, EDGE_W, ETA_SPAN, Edge, FITS, FRAME_RATES, LaneKind, PPS_DEFAULT, PPS_MIN, Preset, RESOLUTIONS, Repeat,
10353- Scale, View,
10354- ZOOM_MIN_FRAMES, ZOOM_OUT_MARGIN, ZOOM_STEP, audio_rate_choices, clock, eta_secs, file_name, file_uri,
10355- fit_choices, landing, lane_refuses, library_rows, live_idx, next_fit, next_resolution,
10356- note_progress, px_along,
10357- IMPORT_STALL, Import, ImportStage, SEEK_STALL, ScanKey, ScanPlan, SilenceScan, import_line,
10358- Landing, arrival, launch_queue,
10359- read_ahead, scan_plan, seek_line, silence_line, source_secs, stash_or_write,
10360- repeats, resolution_choices, resolution_ladder, span_label, tone_choices, tone_label,
10361- clip_width, trimmed_clip, trims, unscannable, unusable,
10362- visible_slice,
10363- };
10364- use super::{
10365- SUB_BOTTOM, SUB_CUE_MIN_W, SUB_HEAD_H, SUB_FG, SUB_LANE_H, SUB_LINE_H, SUB_ROWS_H,
10366- SUB_STEM_SHARE, SUB_TEXT, clip_middle, cue_box,
10367- carries_subtitles, cues_at, file_tint, is_subtitle, lang_human, row_text_w, sub_headers_fit,
10368- Subs, subtitle_detail, subtitle_notice, subtitle_tail,
10369- sub_pick_name, subtitle_rows, subtitle_strip_h, walk_subtitles,
10370- };
10371-
10372- /// What the file manager is handed: the parts a path keeps as they are, and
10373- /// the ones the bus would otherwise read as something else.
10374- #[test]
10375- fn file_uri_encodes_what_a_path_carries() {
10376- assert_eq!(
10377- file_uri(std::path::Path::new("/a/b.mp4")),
10378- "file:///a/b.mp4"
10379- );
10380- assert_eq!(
10381- file_uri(std::path::Path::new("/home/x/out dir/my export.mp4")),
10382- "file:///home/x/out%20dir/my%20export.mp4"
10383- );
10384- assert_eq!(
10385- file_uri(std::path::Path::new("/tmp/ünlü#1?.mp4")),
10386- "file:///tmp/%C3%BCnl%C3%BC%231%3F.mp4"
10387- );
10388- }
10389- use engine::PlaybackSession;
10390- use engine::scale::FitPolicy;
10391- use gpui::{Bounds, Pixels, point, px, size};
10392- use std::collections::HashMap;
10393- use std::path::{Path, PathBuf};
10394- use std::time::{Duration, Instant};
10395-
10396- /// Every line of UI source there is, as one string: the window used to be
10397- /// one file and the scans below read it with `include_str!`. The regions
10398- /// are modules now (`ui/`), so the scans read all of them -- a rule that
10399- /// stopped at `main.rs` would pass by simply not looking where the pixels
10400- /// moved to.
10401- fn ui_source() -> String {
10402- [
10403- include_str!("main.rs").split("#[cfg(test)]").next().unwrap(),
10404- include_str!("ui/theme.rs"),
10405- include_str!("ui/toolbar.rs"),
10406- include_str!("ui/inspector.rs"),
10407- include_str!("ui/timeline.rs"),
10408- include_str!("ui/library.rs"),
10409- include_str!("ui/preview.rs"),
10410- include_str!("ui/cards.rs"),
10411- include_str!("ui/overlays.rs"),
10412- include_str!("ui/widgets.rs"),
10413- ]
10414- .concat()
10415- }
10416-
10417- fn asset(name: &str) -> PathBuf {
10418- Path::new(env!("CARGO_MANIFEST_DIR"))
10419- .join("../../assets")
10420- .join(name)
10421- }
10422-
10423- /// A source entry for `path` on `stream`, as the project keeps them.
10424- fn source(path: &str, stream: usize) -> Source {
10425- Source {
10426- path: PathBuf::from(path),
10427- audio_stream: stream,
10428- }
10429- }
10430-
10431- /// An import fills the *library* and nothing else -- the whole point of
10432- /// this door: the row is there at the file's own length before any clip
10433- /// plays it, wearing the tint the lanes will tint that clip with, and the
10434- /// timeline is exactly as long as it was. Placing it is the drag, and the
10435- /// drag is a separate act.
10436- #[test]
10437- fn an_import_adds_a_row_at_its_own_length_and_leaves_the_lanes_alone() {
10438- let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
10439- session.set_gain(0.0);
10440- let before = session.timeline_duration();
10441- let clips: Vec<usize> = session
10442- .lanes()
10443- .into_iter()
10444- .map(|lane| session.lane_clips(lane).len())
10445- .collect();
10446- session.import(&asset("test_av2.mp4")).expect("av2 matches");
10447- assert_eq!(session.sources().len(), 2, "the library grew");
10448- assert_eq!(
10449- session.timeline_duration(),
10450- before,
10451- "an import must not place a clip"
10452- );
10453- assert_eq!(
10454- session
10455- .lanes()
10456- .into_iter()
10457- .map(|lane| session.lane_clips(lane).len())
10458- .collect::<Vec<_>>(),
10459- clips,
10460- "no lane moved"
10461- );
10462- // The rows the panel draws: one per source, each its file's own length
10463- // -- source 1 has no clip anywhere and is still 4 s at 30 fps.
10464- let rows = library_rows(
10465- session.sources(),
10466- &HashMap::new(),
10467- &HashMap::new(),
10468- None,
10469- |path| session.file_frames(path),
10470- );
10471- assert_eq!(rows.len(), 2);
10472- assert_eq!(rows[0].frames, 150, "5 s at 30 fps");
10473- assert_eq!(rows[1].frames, 120, "4 s at 30 fps, never placed");
10474- // The swatch is the clip colour, by the same index and the same
10475- // function -- what makes the panel and the lanes one association.
10476- for row in 0..rows.len() {
10477- assert_eq!(rows[row].tint, row);
10478- assert_eq!(source_tint(row), SOURCE_TINTS()[row % SOURCE_TINTS().len()]);
10479- }
10480- }
10481-
10482- /// The window opened on a song and nothing else -- the launch argument, the
10483- /// drop on an empty window and the Import button all end in the same
10484- /// `PlaybackSession::open`. The library lists it placeable, the lane door
10485- /// the Add button and a drag share puts it on `A1`, and the one format that
10486- /// needs a picture says so on its own row instead of failing at the end of
10487- /// an export.
10488- #[test]
10489- fn a_song_opens_the_window_by_itself() {
10490- let mut session =
10491- PlaybackSession::open(asset("test_tone.mp3")).expect("a song is a timeline");
10492- session.set_gain(0.0);
10493- // The source's own path, which is the canonical one a row carries.
10494- let path = session.sources()[0].path.clone();
10495- assert!(session.lane_clips(Lane::V1).is_empty(), "no picture");
10496- assert_eq!(session.lane_clips(Lane::A1).len(), 1);
10497-
10498- // The library row: probed like any other source, and not greyed --
10499- // `unusable` is what the panel dims a row with.
10500- let streams = HashMap::from([(
10501- path.clone(),
10502- engine::AudioSession::probe_streams(&path).expect("probe the song"),
10503- )]);
10504- let rate = streams[&path]
10505- .iter()
10506- .find(|s| s.index == session.sources()[0].audio_stream)
10507- .map(|s| (s.sample_rate, s.channels));
10508- let frames = session.file_frames(&path);
10509- let rows = library_rows(session.sources(), &streams, &HashMap::new(), rate, |_| {
10510- frames
10511- });
10512- assert_eq!(rows.len(), 1);
10513- assert_eq!(rows[0].name, "test_tone.mp3");
10514- assert_eq!(rows[0].unusable, None, "the row is placeable");
10515- assert_eq!(rows[0].frames, 90, "3 s at the audio-only 30 fps");
10516-
10517- // ...and it places, on the audio lane, through the door `insert_source`
10518- // uses: a second copy of the song at the playhead.
10519- session.seek(1.0);
10520- assert!(
10521- session
10522- .place_stream_at(1.0, &path, 0, Some(Lane::A1))
10523- .expect("its own file is on this timeline")
10524- );
10525- assert_eq!(session.lane_clips(Lane::A1).len(), 2);
10526- assert!(session.lane_clips(Lane::V1).is_empty(), "still no picture");
10527-
10528- // Both picture rows carry the reason rather than the format's detail
10529- // line, each naming itself; the audio formats are what this timeline is
10530- // and are never refused.
10531- assert_eq!(
10532- format_refusal(&session, Format::Mp4).as_deref(),
10533- Some("no picture — an mp4 would be black; export WAV, FLAC, MP3 or OGG")
10534- );
10535- assert_eq!(
10536- format_refusal(&session, Format::Av1).as_deref(),
10537- Some("no picture — an AV1 Matroska would be black; export WAV, FLAC, MP3 or OGG")
10538- );
10539- assert_eq!(
10540- format_refusal(&session, Format::Av1Mp4).as_deref(),
10541- Some("no picture — an AV1 mp4 would be black; export WAV, FLAC, MP3 or OGG")
10542- );
10543- assert_eq!(format_refusal(&session, Format::Wav), None);
10544- assert_eq!(format_refusal(&session, Format::Flac), None);
10545- assert_eq!(format_refusal(&session, Format::Mp3), None);
10546- }
10547-
10548- fn info(
10549- index: usize,
10550- rate: u32,
10551- channels: u16,
10552- lang: Option<&str>,
10553- decodable: bool,
10554- ) -> StreamInfo {
10555- StreamInfo {
10556- index,
10557- codec: if decodable { "aac" } else { "unknown" }.into(),
10558- channels,
10559- sample_rate: rate,
10560- lang: lang.map(str::to_string),
10561- decodable,
10562- }
10563- }
10564-
10565- /// A file's every audio track gets a row: the ones the timeline can take
10566- /// are placeable, the ones it cannot are listed greyed with the reason.
10567- /// Which rows exist at all is the branchy part of the panel, so it is
10568- /// planned as data and checked here rather than through the pointer.
10569- #[test]
10570- fn every_audio_stream_of_a_file_is_a_row_usable_or_not() {
10571- let multi = PathBuf::from("/m/movie.mp4");
10572- let sources = [source("/m/movie.mp4", 0)];
10573- let mut streams = HashMap::new();
10574- streams.insert(
10575- multi.clone(),
10576- vec![
10577- info(0, 44_100, 2, None, true),
10578- info(1, 44_100, 2, Some("fra"), true),
10579- info(2, 22_050, 1, Some("deu"), true),
10580- info(3, 0, 0, None, false),
10581- ],
10582- );
10583- let rows = library_rows(
10584- &sources,
10585- &streams,
10586- &HashMap::new(),
10587- Some((44_100, 2)),
10588- |_| 90,
10589- );
10590- assert_eq!(
10591- rows.iter().map(|r| r.stream).collect::<Vec<_>>(),
10592- [0, 1, 2, 3],
10593- "one row per audio stream, in file order"
10594- );
10595- assert!(
10596- rows.iter().all(|r| r.path == multi && r.tint == 0),
10597- "every stream of one file wears the file's own tint"
10598- );
10599- assert_eq!(rows[0].name, "movie.mp4 [audio 1]");
10600- assert_eq!(rows[1].name, "movie.mp4 [audio 2]");
10601- assert_eq!(rows[1].detail, "fra 44.1 kHz stereo");
10602- // Placeable: the one already on the timeline, and the one that matches
10603- // it. The mono track cannot join a stereo timeline -- one device and one
10604- // copied AAC track for the whole of it -- and the codec we cannot read
10605- // cannot join anything. Both say which. Its 22 kHz is *not* part of that
10606- // any more: a rate of its own is resampled at the decoder's door, and a
10607- // row greyed for one the engine accepts is this picker telling a lie.
10608- assert_eq!((&rows[0].unusable, &rows[1].unusable), (&None, &None));
10609- assert_eq!(rows[2].unusable.as_deref(), Some("the timeline is stereo"));
10610- assert_eq!(
10611- unusable(&info(9, 48_000, 2, None, true), Some((44_100, 2))),
10612- None,
10613- "48 kHz stereo joins a 44.1 kHz stereo timeline"
10614- );
10615- assert_eq!(rows[3].unusable.as_deref(), Some("unsupported codec"));
10616- assert_eq!(
10617- rows[3].detail, "",
10618- "a stream we cannot parse claims nothing"
10619- );
10620- // Every row is the same file, so every row is that file's length.
10621- assert!(rows.iter().all(|r| r.frames == 90));
10622-
10623- // The single-stream case is exactly one row and no stream tag: no
10624- // regression for the media everything else in the world is.
10625- let plain = [source("/m/plain.mp4", 0)];
10626- let mut one = HashMap::new();
10627- one.insert(
10628- PathBuf::from("/m/plain.mp4"),
10629- vec![info(0, 44_100, 2, None, true)],
10630- );
10631- let rows = library_rows(&plain, &one, &HashMap::new(), Some((44_100, 2)), |_| 90);
10632- assert_eq!(rows.len(), 1);
10633- assert_eq!(rows[0].name, "plain.mp4");
10634- assert_eq!(
10635- rows[0].detail, "",
10636- "one audio track is the row it has always been: name and length"
10637- );
10638- // ...as is a silent file, and a file not probed yet.
10639- let mut silent = HashMap::new();
10640- silent.insert(PathBuf::from("/m/plain.mp4"), Vec::new());
10641- for probe in [silent, HashMap::new()] {
10642- let rows = library_rows(&plain, &probe, &HashMap::new(), None, |_| 90);
10643- assert_eq!(rows.len(), 1);
10644- assert_eq!(rows[0].name, "plain.mp4");
10645- assert_eq!(rows[0].detail, "");
10646- }
10647-
10648- // A second stream *placed* on the timeline is a source entry of its
10649- // own: it keeps its row, no duplicate appears for it, and the rows of
10650- // one file stay together whatever order the entries came in.
10651- let placed = [
10652- source("/m/movie.mp4", 0),
10653- source("/m/other.mp4", 0),
10654- source("/m/movie.mp4", 2),
10655- ];
10656- streams.insert(
10657- PathBuf::from("/m/other.mp4"),
10658- vec![info(0, 44_100, 2, None, true)],
10659- );
10660- let rows = library_rows(
10661- &placed,
10662- &streams,
10663- &HashMap::new(),
10664- Some((44_100, 2)),
10665- |_| 90,
10666- );
10667- assert_eq!(
10668- rows.iter()
10669- .map(|r| (file_name(&r.path), r.stream))
10670- .collect::<Vec<_>>(),
10671- [
10672- ("movie.mp4".to_string(), 0),
10673- ("other.mp4".to_string(), 0),
10674- ("movie.mp4".to_string(), 2),
10675- ("movie.mp4".to_string(), 1),
10676- ("movie.mp4".to_string(), 3),
10677- ]
10678- );
10679- assert!(
10680- rows[2].unusable.is_none(),
10681- "a stream already on the timeline is playing, whatever a probe says"
10682- );
10683- assert_eq!(rows[1].tint, 1, "the other file is the other tint");
10684- }
10685-
10686- /// What the clip menu offers, and where it hangs. The two items that act on
10687- /// the playhead rather than on the clicked clip are the ones that can be
10688- /// inapplicable, and a menu at the edge of the window has to come back
10689- /// inside it or its last item cannot be clicked at all.
10690- #[test]
10691- fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() {
10692- use keymap::{ActionId, Keymap};
10693- // Frames 30..90 of the timeline, taken from the head of its source.
10694- let clip = Clip {
10695- start: 30,
10696- in_frame: 0,
10697- out_frame: 60,
10698- source: 0,
10699- link: None,
10700- eq: None,
10701- color: None,
10702- fit: FitPolicy::default(),
10703- speed: Speed::NORMAL,
10704- };
10705- assert_eq!(clip.end(), 90);
10706- let a1 = Lane::A1;
10707- let v1 = Lane::V1;
10708- // The question the clip menu asks: a timeline is open and the menu was
10709- // opened on this clip, at this playhead.
10710- let on = |clip: &Clip, lane, action, playhead| {
10711- enable(
10712- action,
10713- Ctx {
10714- clip: Some((*clip, lane)),
10715- playhead,
10716- timeline: true,
10717- ..Ctx::default()
10718- },
10719- )
10720- };
10721- let offered = |clip: &Clip, lane, action, playhead| on(clip, lane, action, playhead).yes();
10722- // Cut splits from inside only: neither edge has anything to split off.
10723- assert!(offered(&clip, v1, ActionId::Cut, 31));
10724- assert!(offered(&clip, v1, ActionId::Cut, 89));
10725- assert!(!offered(&clip, v1, ActionId::Cut, 30));
10726- assert!(!offered(&clip, v1, ActionId::Cut, 90));
10727- assert!(!offered(&clip, v1, ActionId::Cut, 200));
10728- // A slowed clip refuses more than the edges do, and it may not say the
10729- // edges' words while doing it: at a quarter speed each of its sixty
10730- // source frames is on screen four timeline frames, and only the first of
10731- // the four is a frame the file has. The three between are inside the
10732- // clip by any reading of the playhead, so "only from inside a clip"
10733- // there is a refusal claiming something the screen contradicts.
10734- let slow = Clip {
10735- speed: Speed::MIN,
10736- ..clip
10737- };
10738- assert_eq!(slow.frames(), 240, "a quarter speed is four times as long");
10739- assert!(offered(&slow, v1, ActionId::Cut, 34), "34 is a source frame");
10740- assert!(!offered(&slow, v1, ActionId::Cut, 35));
10741- assert_eq!(
10742- on(&slow, v1, ActionId::Cut, 35).why(),
10743- Some("this speed holds one frame here — step to the next"),
10744- );
10745- assert_eq!(
10746- on(&slow, v1, ActionId::Cut, 30).why(),
10747- Some("only from inside a clip"),
10748- "the head is still the edge's refusal, speed or no speed",
10749- );
10750- // Regroup is the other way round: only where this clip meets another.
10751- assert!(offered(&clip, v1, ActionId::Regroup, 30));
10752- assert!(offered(&clip, v1, ActionId::Regroup, 90));
10753- assert!(!offered(&clip, v1, ActionId::Regroup, 60));
10754- // Detach is the clip's own business: nothing to take apart in one that
10755- // names no group, and whether the group still has another half is the
10756- // engine's question. Group is offered on every clip, for that reason.
10757- assert!(!offered(&clip, v1, ActionId::Detach, 0));
10758- let grouped = Clip {
10759- link: Some(3),
10760- ..clip
10761- };
10762- assert!(offered(&grouped, v1, ActionId::Detach, 60));
10763- assert!(offered(&clip, a1, ActionId::Group, 0));
10764- // The equalizer is the one item the *lane* decides: it filters samples,
10765- // and a video clip has none of its own. Never the playhead's business.
10766- assert!(offered(&clip, a1, ActionId::Equalizer, 0));
10767- assert!(offered(&clip, a1, ActionId::Equalizer, 60));
10768- assert!(!offered(&clip, v1, ActionId::Equalizer, 60));
10769- // The rest act on the clip that was clicked, so they always mean
10770- // something -- the engine words its own refusals.
10771- for action in [ActionId::Delete, ActionId::Lift, ActionId::ToggleMute] {
10772- assert!(offered(&clip, v1, action, 0));
10773- assert!(offered(&clip, a1, action, 60));
10774- }
10775- // Except the grade, which is a picture setting: offered on a video
10776- // clip wherever the playhead is, dimmed on a waveform.
10777- assert!(offered(&clip, v1, ActionId::Color, 0));
10778- assert!(!offered(&clip, a1, ActionId::Color, 60));
10779- // The two kinds of no, which is what the row is told apart by: a grade
10780- // on a waveform is a *class* answer -- an audio clip has no picture and
10781- // never will, so the menu leaves the item out entirely -- where a cut at
10782- // the clip's edge is this moment's answer and the next click of the
10783- // playhead changes it, so that one is drawn, dimmed, and says why.
10784- //
10785- // What the menu draws for a clip of each kind, in order: the render
10786- // loop's `continue`, as a list.
10787- let menu = |lane, image, playhead| {
10788- MENU_ITEMS
10789- .into_iter()
10790- .filter(|&action| {
10791- enable(
10792- action,
10793- Ctx {
10794- clip: Some((clip, lane)),
10795- image,
10796- playhead,
10797- timeline: true,
10798- ..Ctx::default()
10799- },
10800- )
10801- .listed()
10802- })
10803- .collect::<Vec<_>>()
10804- };
10805- // Sound: no grade and no fit policy, and the equalizer that is the
10806- // whole reason an audio clip has a menu of its own.
10807- let sound = menu(a1, false, 60);
10808- assert!(!sound.contains(&ActionId::Color), "{sound:?}");
10809- assert!(!sound.contains(&ActionId::Fit), "{sound:?}");
10810- assert!(sound.contains(&ActionId::Equalizer));
10811- assert!(sound.contains(&ActionId::Silence));
10812- // Picture: the mirror of it. The sound of a take is the audio lane's,
10813- // clip for clip, so the equalizer is not this clip's business -- but the
10814- // silence scan is, because it opens on the half it is grouped with.
10815- let picture = menu(v1, false, 60);
10816- assert!(!picture.contains(&ActionId::Equalizer), "{picture:?}");
10817- assert!(picture.contains(&ActionId::Color));
10818- assert!(picture.contains(&ActionId::Fit));
10819- assert!(picture.contains(&ActionId::Silence));
10820- // A still: picture with no sound anywhere, ever. Graded, fitted and
10821- // re-timed like any other clip (a speed reaches a still through the same
10822- // rewrite), scanned like none.
10823- let still = menu(v1, true, 60);
10824- assert!(!still.contains(&ActionId::Silence), "{still:?}");
10825- assert!(!still.contains(&ActionId::Equalizer), "{still:?}");
10826- assert!(still.contains(&ActionId::Color));
10827- assert!(still.contains(&ActionId::Fit));
10828- assert!(still.contains(&ActionId::Speed));
10829- // ...and the state refusals are on all three, dimmed rather than gone:
10830- // at 30 the playhead is on this clip's head, where a cut has nothing to
10831- // split off -- a row the next click of the playhead lights.
10832- for rows in [menu(a1, false, 30), menu(v1, false, 30), menu(v1, true, 30)] {
10833- assert!(rows.contains(&ActionId::Cut), "{rows:?}");
10834- assert!(rows.contains(&ActionId::Detach), "{rows:?}");
10835- }
10836- // The actions card is the other half of the rule: it lists the whole
10837- // registry, so a class refusal is dimmed there with its reason and never
10838- // dropped -- an action missing from the one surface that lists
10839- // everything would read as an action that does not exist.
10840- let listed: Vec<ActionId> = keys_rows()
10841- .into_iter()
10842- .filter_map(|r| match r {
10843- KeyRow::Act(action) => Some(action),
10844- _ => None,
10845- })
10846- .collect();
10847- for (lane, action) in [
10848- (a1, ActionId::Color),
10849- (a1, ActionId::Fit),
10850- (v1, ActionId::Equalizer),
10851- ] {
10852- assert!(matches!(on(&clip, lane, action, 60), Enable::Hidden(_)));
10853- assert!(listed.contains(&action), "{action:?} left the actions card");
10854- assert!(on(&clip, lane, action, 60).why().is_some());
10855- }
10856- assert!(matches!(on(&clip, v1, ActionId::Cut, 30), Enable::No(_)));
10857- assert!(matches!(on(&clip, v1, ActionId::Regroup, 60), Enable::No(_)));
10858- assert!(matches!(on(&clip, v1, ActionId::Detach, 0), Enable::No(_)));
10859- // Every refusal says something, and says it short enough to sit in the
10860- // menu's right-hand column beside a label -- the still's included, which
10861- // the card dims with while the menu leaves the row out.
10862- for action in MENU_ITEMS {
10863- for (lane, image) in [(v1, false), (a1, false), (v1, true)] {
10864- for playhead in [0, 30, 60, 90] {
10865- let refusal = enable(
10866- action,
10867- Ctx {
10868- clip: Some((clip, lane)),
10869- image,
10870- playhead,
10871- timeline: true,
10872- ..Ctx::default()
10873- },
10874- );
10875- if let Some(why) = refusal.why() {
10876- assert!(!why.is_empty() && why.len() <= 30, "{action:?}: {why:?}");
10877- }
10878- }
10879- }
10880- }
10881- assert!(matches!(
10882- enable(
10883- ActionId::Silence,
10884- Ctx {
10885- clip: Some((clip, v1)),
10886- image: true,
10887- playhead: 60,
10888- timeline: true,
10889- ..Ctx::default()
10890- }
10891- ),
10892- Enable::Hidden(_)
10893- ));
10894- // The editor as a whole, which is how the actions card asks: with no
10895- // timeline nothing is offered, an export leaves only its own cancel,
10896- // and the three that act on the marked clip say so when none is.
10897- let whole = |action, ctx| enable(action, ctx);
10898- assert_eq!(
10899- whole(ActionId::Play, Ctx::default()),
10900- Enable::No("no timeline open")
10901- );
10902- let live = Ctx {
10903- timeline: true,
10904- playable: true,
10905- ..Ctx::default()
10906- };
10907- assert!(whole(ActionId::Play, live).yes());
10908- // ...and an open timeline with nothing on its lanes refuses the
10909- // transport in the oracle rather than in the button, which is what
10910- // makes the key and the button say the same thing.
10911- assert_eq!(
10912- whole(
10913- ActionId::Play,
10914- Ctx {
10915- playable: false,
10916- ..live
10917- }
10918- ),
10919- Enable::No("put a clip on a lane first")
10920- );
10921- // The magnet and the monitoring level are the editor's own and answer
10922- // with no timeline at all -- the keyboard always fired them there, and
10923- // now so does the toolbar.
10924- for editor_wide in [
10925- ActionId::ToggleSnap,
10926- ActionId::ToggleMute,
10927- ActionId::VolumeUp,
10928- ActionId::VolumeDown,
10929- ] {
10930- assert!(
10931- whole(editor_wide, Ctx::default()).yes(),
10932- "{editor_wide:?} is dead with no file open while its key still fires"
10933- );
10934- }
10935- assert!(!whole(ActionId::Delete, live).yes());
10936- assert!(!whole(ActionId::Paste, live).yes());
10937- assert!(
10938- whole(
10939- ActionId::Paste,
10940- Ctx {
10941- clipboard: true,
10942- ..live
10943- }
10944- )
10945- .yes()
10946- );
10947- assert!(!whole(ActionId::CancelExport, live).yes());
10948- let busy = Ctx {
10949- exporting: true,
10950- ..live
10951- };
10952- assert!(whole(ActionId::CancelExport, busy).yes());
10953- for action in ActionId::ALL {
10954- // Nothing may touch the edit list while an export is reading it --
10955- // and the palette does not: it repaints this window and writes one
10956- // word to the user's own config file, which is why it is the one
10957- // action besides the cancel that stays live here.
10958- let allowed = action == ActionId::CancelExport || action == ActionId::Theme;
10959- assert_eq!(
10960- whole(action, busy).yes(),
10961- allowed,
10962- "{action:?} while an export reads the edit list"
10963- );
10964- }
10965- // The playhead frame is the engine's own rule, boundary included.
10966- assert_eq!(frame_at(1.0, 30.), 30);
10967- assert_eq!(frame_at(0.0, 30.), 0);
10968- assert_eq!(frame_at(-1.0, 30.), 0);
10969- // Where it hangs: at the pointer when it fits, back inside when not.
10970- let viewport = size(px(800.), px(400.));
10971- assert_eq!(menu_at(point(px(10.), px(10.)), viewport, 150.), (10., 10.));
10972- assert_eq!(
10973- menu_at(point(px(700.), px(380.)), viewport, 150.),
10974- (800. - MENU_W, 250.)
10975- );
10976- // A window smaller than the menu loses its bottom, never its top.
10977- assert_eq!(
10978- menu_at(point(px(90.), px(40.)), size(px(100.), px(50.)), 150.),
10979- (0., 0.)
10980- );
10981- // Every item is an action the registry knows, so the menu and the keys
10982- // menu say the same thing about it -- and none of them is unreachable
10983- // by keyboard, which is what makes the hint column worth drawing.
10984- let keymap = Keymap::defaults();
10985- for action in MENU_ITEMS {
10986- assert!(ActionId::ALL.contains(&action), "{action:?} is not listed");
10987- assert_ne!(keymap.display(action), "unbound", "{action:?}");
10988- }
10989- // ...and the whole card still fits the 640x360 floor, however many items
10990- // it grows to: the list is what scrolls where the window is too short
10991- // for it, never the card that grows.
10992- let items = MENU_ITEMS.len() + 1; // Properties
10993- let floor = size(px(640.), px(360.));
10994- assert!(MENU_PAD * 2. + menu_rows_h(items, floor) <= 360., "too tall");
10995- assert!(
10996- menu_rows_h(items, floor) / MENU_ROW_H >= 12.,
10997- "too few items visible to scan on the smallest window"
10998- );
10999- assert_eq!(
11000- menu_at(point(px(0.), px(0.)), floor, {
11001- MENU_PAD * 2. + menu_rows_h(items, floor)
11002- }),
11003- (0., 0.)
11004- );
11005- // The picker is the same card and the longest list in it is the palette
11006- // family list, which grows every time somebody asks for more colours.
11007- // Twelve of them still stand on screen *whole* at the floor -- so the
11008- // list's `overflow_y_scroll` is a safety net rather than something a
11009- // person has to find. The day a family makes this fail is the day the
11010- // card owes the affordance line the inspector and the cards carry
11011- // ("more below — scroll the …"): a row nobody knows is under the fold
11012- // is a row that is not there, and no scroll bar says it.
11013- let families = crate::ui::theme::PaletteId::ALL.len();
11014- assert_eq!(
11015- menu_rows_h(families, floor),
11016- families as f32 * MENU_ROW_H,
11017- "{families} palettes no longer fit 640x360 -- the picker now needs \
11018- the 'more below' line and a keyboard cursor that scrolls into view"
11019- );
11020- // ...and the detail beside each one is short enough to survive the
11021- // right-hand column at that width instead of being truncated mid-word.
11022- for id in crate::ui::theme::PaletteId::ALL {
11023- assert!(id.detail().len() <= 30, "{id:?}: {:?}", id.detail());
11024- }
11025- }
11026-
11027- /// Both menus, at the two things they can be opened on, and the box each
11028- /// one is drawn in. Two rules, and the render obeys them by *calling* what
11029- /// this calls -- [`menu_items`] and [`row_items`] are the only lists either
11030- /// menu is built from, and [`menu_rows_h`] is the height each is both placed
11031- /// by and drawn to:
11032- ///
11033- /// 1. a row exists only where the oracle lists the action for the very thing
11034- /// that was right-clicked, so an item can never offer a video action on a
11035- /// waveform (the complaint this comes from) and a new action added to
11036- /// `MENU_ITEMS` cannot appear where it does not apply;
11037- /// 2. the whole card is inside the window, wherever it was opened and
11038- /// however long the list -- a menu drawn past the bottom edge is a menu
11039- /// whose last items nobody can click.
11040- #[test]
11041- fn a_menu_offers_only_what_applies_and_is_drawn_inside_the_window() {
11042- use keymap::ActionId;
11043- let clip = Clip {
11044- start: 30,
11045- in_frame: 0,
11046- out_frame: 60,
11047- source: 0,
11048- link: Some(1),
11049- eq: None,
11050- color: None,
11051- fit: FitPolicy::default(),
11052- speed: Speed::NORMAL,
11053- };
11054- let ctx = |lane, image| Ctx {
11055- clip: Some((clip, lane)),
11056- image,
11057- playhead: 60,
11058- timeline: true,
11059- ..Ctx::default()
11060- };
11061- // The oracle is the whole of what the menu draws: every item it lists is
11062- // one the oracle would list, and every item it leaves out is one the
11063- // oracle hides -- there is no third answer, and no hand-written list.
11064- for (lane, image) in [(Lane::V1, false), (Lane::A1, false), (Lane::V1, true)] {
11065- let ctx = ctx(lane, image);
11066- let rows = menu_items(ctx);
11067- for action in MENU_ITEMS {
11068- assert_eq!(
11069- rows.contains(&action),
11070- enable(action, ctx).listed(),
11071- "{action:?} on {lane:?}, image={image}"
11072- );
11073- }
11074- }
11075- // Sound has no picture settings; picture has no equalizer of its own; a
11076- // still has no sound to scan. The user's own words: an audio clip must
11077- // not be offered what only a picture can be given.
11078- let sound = menu_items(ctx(Lane::A1, false));
11079- assert!(!sound.contains(&ActionId::Color), "{sound:?}");
11080- assert!(!sound.contains(&ActionId::Fit), "{sound:?}");
11081- assert!(sound.contains(&ActionId::Equalizer));
11082- let picture = menu_items(ctx(Lane::V1, false));
11083- assert!(!picture.contains(&ActionId::Equalizer), "{picture:?}");
11084- assert!(picture.contains(&ActionId::Color));
11085- assert!(!menu_items(ctx(Lane::V1, true)).contains(&ActionId::Silence));
11086- // The library menu is the same rule on the other panel: its items come
11087- // off `row_items` and nothing else, and the two that change the timeline
11088- // say why rather than being clicked and refused afterwards.
11089- let live = RowCtx {
11090- timeline: true,
11091- usable: true,
11092- ..RowCtx::default()
11093- };
11094- for ctx in [
11095- live,
11096- RowCtx {
11097- usable: false,
11098- ..live
11099- },
11100- RowCtx { placed: 2, ..live },
11101- RowCtx {
11102- exporting: true,
11103- ..live
11104- },
11105- RowCtx::default(),
11106- ] {
11107- let rows = row_items(ctx);
11108- for item in ROW_ITEMS {
11109- assert_eq!(rows.contains(&item), row_enable(item, ctx).listed());
11110- }
11111- // Whatever the state, the two that need neither timeline nor edit
11112- // list are offered: a file is always describable and findable.
11113- assert!(row_enable(RowItem::Reveal, ctx).yes());
11114- assert!(row_enable(RowItem::Properties, ctx).yes());
11115- }
11116- assert!(row_enable(RowItem::Add, live).yes());
11117- assert!(
11118- !row_enable(
11119- RowItem::Add,
11120- RowCtx {
11121- usable: false,
11122- ..live
11123- }
11124- )
11125- .yes(),
11126- "a file that cannot join this timeline is not an Add anybody can ask for"
11127- );
11128- assert!(!row_enable(RowItem::Remove, RowCtx { placed: 1, ..live }).yes());
11129- assert!(!row_enable(RowItem::Add, RowCtx::default()).yes());
11130- // Every refusal is short enough to sit in the hint column beside its
11131- // label, the clip menu's rule.
11132- for item in ROW_ITEMS {
11133- for ctx in [live, RowCtx::default()] {
11134- if let Some(why) = row_enable(item, ctx).why() {
11135- assert!(!why.is_empty() && why.len() <= 30, "{why:?}");
11136- }
11137- }
11138- }
11139- // ...and the box. Every window from the floor up, every corner of it,
11140- // and every list length either menu can have: the card is placed by
11141- // `MENU_PAD * 2 + menu_rows_h` and drawn to it, so this is the card.
11142- for viewport in [
11143- size(px(640.), px(360.)),
11144- size(px(800.), px(600.)),
11145- size(px(1280.), px(690.)),
11146- // Smaller than the floor the layout is sized for: it still may not
11147- // draw outside the window it has.
11148- size(px(320.), px(200.)),
11149- ] {
11150- for rows in 1..=MENU_ITEMS.len() + 1 {
11151- let h = MENU_PAD * 2. + menu_rows_h(rows, viewport);
11152- for at in [
11153- point(px(0.), px(0.)),
11154- point(px(10.), px(10.)),
11155- // The click that started all this: low in the window, where
11156- // the menu used to hang off the bottom edge.
11157- point(px(0.), viewport.height - px(4.)),
11158- point(viewport.width - px(4.), viewport.height - px(4.)),
11159- point(viewport.width * 2., viewport.height * 2.),
11160- ] {
11161- let (x, y) = menu_at(at, viewport, h);
11162- assert!(x >= 0. && y >= 0., "{x},{y} outside {viewport:?}");
11163- assert!(
11164- x + MENU_W <= f32::from(viewport.width) + 0.01,
11165- "{rows} rows at {at:?} hang off the right of {viewport:?}"
11166- );
11167- assert!(
11168- y + h <= f32::from(viewport.height) + 0.01,
11169- "{rows} rows at {at:?} hang off the bottom of {viewport:?}"
11170- );
11171- }
11172- }
11173- }
11174- // On any window with the room, the whole list is drawn rather than
11175- // twelve rows of it and a scroll nobody is told about.
11176- let items = MENU_ITEMS.len() + 1;
11177- let real = size(px(1280.), px(690.));
11178- assert_eq!(menu_rows_h(items, real), items as f32 * MENU_ROW_H);
11179- assert!(menu_rows_h(items, size(px(640.), px(360.))) < items as f32 * MENU_ROW_H);
11180- }
11181-
11182- /// The other half of the keys menu's guarantee, and the audit this batch was
11183- /// asked for kept as a test: no action may be a stroke and nothing else.
11184- /// The actions card answers it for all of them at once -- its rows come off
11185- /// [`ActionId::ALL`], so a fortieth action is on it the moment it exists and
11186- /// there is no hand-written list here to fall behind.
11187- #[test]
11188- fn every_action_is_reachable_without_the_keyboard() {
11189- use keymap::ActionId;
11190- let source = ui_source();
11191- let source = source.as_str();
11192- let element = |id: &str| source.contains(&format!("\"{id}\""));
11193- let listed: Vec<ActionId> = keys_rows()
11194- .iter()
11195- .filter_map(|r| match r {
11196- KeyRow::Act(a) => Some(*a),
11197- _ => None,
11198- })
11199- .collect();
11200- for action in ActionId::ALL {
11201- assert_eq!(
11202- listed.iter().filter(|a| **a == action).count(),
11203- 1,
11204- "{action:?} is reachable by keyboard only"
11205- );
11206- }
11207- // The snap has a door of its own as well as its row on the card: the
11208- // button beside the zoom, which says which way it is set as well as
11209- // setting it.
11210- assert!(element("snap"), "no snap button beside the zoom");
11211- // And the card is a door the pointer can open: the panel's own button.
11212- assert!(element("keys"), "no way to open the actions card");
11213- // The card-local strokes have the same rule, and each of them is a thing
11214- // on its card: the graph and its two buttons, the colour bars and their
11215- // reset, the speed bar and its presets, and the silence card's rows --
11216- // whose steppers are the pointer's only way to a threshold.
11217- for id in [
11218- "eq-graph",
11219- "eq-reset",
11220- "eq-spectrum",
11221- "color-bar",
11222- "color-reset",
11223- "speed-bar",
11224- "speed-preset",
11225- "silence-row",
11226- "silence-step",
11227- "mix-row",
11228- "mix-step",
11229- "silence-apply",
11230- "export-confirm",
11231- ] {
11232- assert!(element(id), "{id} is not on any card");
11233- }
11234- // ...and each one is named by the row that carries its stroke, so a
11235- // card-local key added to `FIXED` with nothing to click fails here
11236- // instead of being noticed by whoever tries to use the card without a
11237- // keyboard. `KeyRow::Fixed` is "shown and never offered", which used to
11238- // mean the twenty-eight rows below were the one part of this editor no
11239- // reachability test read.
11240- for fixed in keymap::FIXED.iter() {
11241- match fixed.reach {
11242- keymap::Reach::Click(id) => assert!(
11243- element(id),
11244- "{:?} ({}) points at {id}, which is on no card",
11245- fixed.chord,
11246- fixed.label
11247- ),
11248- // Nothing to click by decision, not by omission: getting out of
11249- // a card, and the hold that repeats what a drag already does.
11250- keymap::Reach::Gesture => {}
11251- }
11252- }
11253- }
11254-
11255- /// The other half of "getting out of a card is a `Reach::Gesture`": the
11256- /// gesture has to exist. Every card's scrim closes it on a press, so a hand
11257- /// that never touches the keyboard can shut every one of them -- for seven
11258- /// cards `esc` was the only exit, which is the same complaint as an action
11259- /// reachable by stroke alone, said about the way out instead of the way in.
11260- ///
11261- /// Read off [`Player::modal`] rather than off a list written here: a card
11262- /// counted there and not closed by [`Player::close_card`] fails this test
11263- /// the day it is added, which is the only way the two stay in step.
11264- #[test]
11265- fn every_card_closes_without_the_keyboard() {
11266- let source = ui_source();
11267- let source = source.as_str();
11268- // A fn's source, up to the next one: enough of a body to scan.
11269- let body = |name: &str| -> &str {
11270- let at = source
11271- .find(&format!("fn {name}("))
11272- .unwrap_or_else(|| panic!("no fn {name} in main.rs"));
11273- let rest = &source[at..];
11274- &rest[..rest[1..].find("\n fn ").map_or(rest.len(), |e| e + 1)]
11275- };
11276- for card in [
11277- "keys_overlay",
11278- "export_card",
11279- "eq_card",
11280- "color_card",
11281- "speed_card",
11282- "mix_card",
11283- "silence_card",
11284- ] {
11285- let src = body(card);
11286- assert!(
11287- src.contains("this.close_card()"),
11288- "{card}'s scrim swallows the press without closing the card: \
11289- escape is the only way out of it"
11290- );
11291- assert!(
11292- src.contains("MouseButton::Left, swallow"),
11293- "{card}'s body does not swallow its own presses, so a press on \
11294- one of its controls would close the card under itself"
11295- );
11296- }
11297- // ...and every state that makes the window modal is a state that press
11298- // clears. `exporting()` is not one of them: a running export is a job
11299- // with a cancel button, not a card with a scrim.
11300- let close = body("close_card");
11301- for field in body("modal").split("self.").skip(1).filter_map(|rest| {
11302- let name: String = rest
11303- .chars()
11304- .take_while(|c| c.is_alphanumeric() || *c == '_')
11305- .collect();
11306- (!rest[name.len()..].starts_with('(')).then_some(name)
11307- }) {
11308- assert!(
11309- close.contains(&format!("self.{field}")),
11310- "{field} makes the window modal and `close_card` leaves it set: \
11311- that card cannot be closed by pointer"
11312- );
11313- }
11314- }
11315-
11316- /// A clip too short to hit is still a clip: at a far zoom-out its box is
11317- /// drawn [`HIT_MIN`] wide rather than the fraction of a pixel it is worth,
11318- /// because a box nobody can put a pointer on cannot be selected, dragged,
11319- /// trimmed or given a menu -- and an invisible unselectable take is strictly
11320- /// worse than one drawn a few pixels too wide.
11321- #[test]
11322- fn a_clip_box_is_never_narrower_than_its_target() {
11323- // Two seconds on a bed showing an hour: a fifth of a pixel.
11324- let far = Scale {
11325- pps: 0.1,
11326- start: 0.,
11327- };
11328- assert!(far.width_px(2.) < 1., "the fixture is not zoomed out enough");
11329- assert_eq!(clip_width(far.width_px(2.)), HIT_MIN);
11330- // Zero is the floor's own case: a clip trimmed to nothing, and the
11331- // width a lane draws before its first frame is measured.
11332- assert_eq!(clip_width(0.), HIT_MIN);
11333- // What is already wide enough keeps its own width, to the pixel: the
11334- // floor is a floor and never a resize.
11335- let near = Scale::default();
11336- assert_eq!(clip_width(near.width_px(5.)), near.width_px(5.));
11337- // ...and the padding is not trimmable: the strips are asked of the
11338- // clip's own width, so a box drawn wider than its length keeps all of
11339- // that box as a body to select and drag by ([`trims`]).
11340- assert!(!trims(far.width_px(2.)));
11341- assert!(clip_width(far.width_px(2.)) >= HIT_MIN);
11342- }
11343-
11344- /// What the Detach and Group items do to a real timeline: a music video's
11345- /// sound comes off its picture, Delete on the loose half takes that half
11346- /// only, undo puts both back, and Group makes the two one take again --
11347- /// whole-take delete and all.
11348- #[test]
11349- fn a_detached_half_is_removed_alone_and_groups_again() {
11350- let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
11351- session.set_gain(0.0);
11352- assert!(whole_take(&session, Lane::V1, 0), "one take to start with");
11353- assert!(whole_take(&session, Lane::A1, 0));
11354- let frames = session.lane_clips(Lane::V1)[0].len();
11355-
11356- // Detach audio: neither half is a whole take any more, so Delete on
11357- // either leaves the other exactly where it is.
11358- assert!(session.ungroup(Lane::V1, 0));
11359- assert!(
11360- !whole_take(&session, Lane::A1, 0),
11361- "the sound is a half now"
11362- );
11363- assert!(!whole_take(&session, Lane::V1, 0), "and so is the picture");
11364- assert!(session.lift_clip(Lane::A1, 0));
11365- assert!(session.lane_clips(Lane::A1).is_empty(), "the sound went");
11366- assert_eq!(session.lane_clips(Lane::V1).len(), 1, "the picture stayed");
11367- assert_eq!(session.lane_clips(Lane::V1)[0].len(), frames, "untrimmed");
11368-
11369- // One undo per edit, the removal then the detach.
11370- assert!(session.undo());
11371- assert_eq!(session.lane_clips(Lane::A1).len(), 1, "the sound is back");
11372- assert!(session.undo());
11373- assert!(whole_take(&session, Lane::A1, 0), "one take again");
11374-
11375- // Group: the partner is the clip covering these very frames on the
11376- // other track, which is what the item hands the engine.
11377- assert!(session.ungroup(Lane::V1, 0));
11378- assert_eq!(span_partner(&session, Lane::V1, 0), Some((Lane::A1, 0)));
11379- session
11380- .group(Lane::V1, 0, Lane::A1, 0)
11381- .expect("both halves still cover the same frames");
11382- assert!(
11383- whole_take(&session, Lane::A1, 0),
11384- "a take that ripples again"
11385- );
11386- assert_eq!(
11387- span_partner(&session, Lane::V1, 0),
11388- None,
11389- "and nothing left on another track to group with"
11390- );
11391- }
11392-
11393- /// Which clip Group reaches when more than one covers the span: the sound,
11394- /// whatever order the lanes are stored in. A project file may hold them in
11395- /// any order -- a video layer *before* the audio lane among them -- and
11396- /// "group this" means the other half of the take, never the layer above it.
11397- #[test]
11398- fn group_reaches_the_sound_before_a_video_layer_over_it() {
11399- use engine::project::LaneKind;
11400-
11401- let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
11402- session.set_gain(0.0);
11403- let v2 = session.add_lane(LaneKind::Video);
11404- // A bare layer, through the one-lane door: a *drop* on V2 brings the
11405- // file's sound down with it and would put a third clip over this span.
11406- let whole = session.lane_clips(Lane::V1)[0];
11407- assert!(
11408- session.place_at(v2, 0.0, whole),
11409- "a layer covering the same frames as the take"
11410- );
11411-
11412- // Saved and loaded back with the lanes in the order a hand-written
11413- // project may hold them: the sound last, behind the layer.
11414- let dir = engine::scratch::Scratch::dir("ve_group");
11415- let file = dir.join("lanes.edith");
11416- session.save_project(&file).expect("save the project");
11417- let text = std::fs::read_to_string(&file).expect("read it back");
11418- let (sound, rest): (Vec<&str>, Vec<&str>) =
11419- text.lines().partition(|l| l.starts_with("audio "));
11420- std::fs::write(
11421- &file,
11422- format!("{}\n{}\n", rest.join("\n"), sound.join("\n")),
11423- )
11424- .expect("write the reordered project");
11425- let mut session = PlaybackSession::open_project(&file).expect("it loads as it stands");
11426- std::fs::remove_dir_all(&dir).ok();
11427- assert_eq!(
11428- session.lanes(),
11429- vec![Lane::V1, v2, Lane::A1],
11430- "the sound is the last lane there"
11431- );
11432-
11433- // Detached, so Group has a choice to get wrong: the layer covers these
11434- // frames too, and it is the lane the walk meets first.
11435- assert!(session.ungroup(Lane::V1, 0));
11436- // Group on the picture reaches the sound, not that layer.
11437- assert_eq!(span_partner(&session, Lane::V1, 0), Some((Lane::A1, 0)));
11438- session
11439- .group(Lane::V1, 0, Lane::A1, 0)
11440- .expect("the two halves cover the same frames");
11441- // ...and a lane of its own kind is still groupable, once the sound is
11442- // spoken for: two video lanes may be one take.
11443- assert_eq!(
11444- span_partner(&session, Lane::V1, 0),
11445- Some((v2, 0)),
11446- "the layer is what is left to group with"
11447- );
11448- }
11449-
11450- /// The refusal path, end to end against the real files: an incompatible
11451- /// import changes nothing, and the library mirrors `sources()` 1:1, so a
11452- /// refused file cannot leave a row behind.
11453- #[test]
11454- fn a_refused_import_leaves_no_row_and_an_accepted_one_is_whole() {
11455- let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
11456- // Silent like the engine suite: this opens the real device.
11457- session.set_gain(0.0);
11458- assert_eq!(session.sources().len(), 1);
11459- // 640x360 joins now (the project canvas places it), and so does a file
11460- // with no sound (it plays silence over its span). What is left is one
11461- // output device: a mono track cannot join a stereo timeline.
11462- let refusal = session
11463- .import(&asset("test_ac3.mp4"))
11464- .expect_err("a mono track must not join a stereo timeline")
11465- .to_string();
11466- assert!(refusal.contains("audio"), "refusal must name it: {refusal}");
11467- assert_eq!(session.sources().len(), 1, "a refusal added a row");
11468- // An accepted one does add a row, and it reads as the whole file: 4 s
11469- // at 30 fps, its own length and not one taken off the lanes.
11470- session.import(&asset("test_av2.mp4")).expect("av2 matches");
11471- assert_eq!(session.sources().len(), 2);
11472- let second = session.sources()[1].path.clone();
11473- assert_eq!(session.file_frames(&second), 120);
11474- assert_eq!(timecode(120. / 30., 30.), "00:00:04:00");
11475- }
11476-
11477- /// What the Add button and a dropped row both do, minus the pointer: the
11478- /// clip [`Player::insert_source`] builds, put in where the playhead is. One
11479- /// call, so what a drop does cannot drift from what the button does.
11480- #[test]
11481- fn adding_a_row_drops_the_whole_source_in_at_the_playhead() {
11482- let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
11483- session.set_gain(0.0);
11484- session.import(&asset("test_av2.mp4")).expect("av2 matches");
11485- // In the library only: the 5 s the fixture is, still.
11486- assert_eq!(session.timeline_duration(), 5.0);
11487- // Two seconds in, which is inside the first take: the insert splits it.
11488- session.seek(2.0);
11489- let second = session.sources()[1].path.clone();
11490- let frames = session.file_frames(&second);
11491- // Through the engine door `insert_source` uses, with the row's own
11492- // stream: the button, the drop and this are one call.
11493- assert!(
11494- session
11495- .place_stream_at(2.0, &second, 0, None)
11496- .expect("av2 is already on the timeline")
11497- );
11498- // The whole of source 1 went in and nothing was painted over: the
11499- // timeline is longer by exactly that file.
11500- assert_eq!(session.timeline_duration(), 9.0);
11501- let (video, audio) = (session.lane_clips(Lane::V1), session.lane_clips(Lane::A1));
11502- // One take, not a video clip with no sound under it: both lanes hold
11503- // the same clip at the same place, in the same group.
11504- let at = |lane: &[Clip]| {
11505- *lane
11506- .iter()
11507- .find(|c| c.start == 60)
11508- .expect("inserted at 2 s")
11509- };
11510- assert_eq!(at(video), at(audio));
11511- assert_eq!(at(video).source, 1);
11512- assert_eq!(at(video).len(), frames);
11513- assert!(at(video).link.is_some());
11514- assert_eq!(video.len(), audio.len());
11515-
11516- // The same door with a *second audio stream* of a file already there:
11517- // a new source entry, the same picture, and the row that was dragged
11518- // is what plays. This is the whole user-facing point of the slice.
11519- let mut session =
11520- PlaybackSession::open(asset("test_multilang.mp4")).expect("open the fixture");
11521- session.set_gain(0.0);
11522- let path = session.sources()[0].path.clone();
11523- let frames = session.file_frames(&path);
11524- let end = session.timeline_duration();
11525- assert!(
11526- session
11527- .place_stream_at(end, &path, 1, None)
11528- .expect("the French track shares the timeline's parameters")
11529- );
11530- assert_eq!(session.sources()[1].audio_stream, 1);
11531- assert_eq!(session.timeline_duration(), end * 2.0);
11532- // Both rows are the same file, so both rows are that file's length --
11533- // the second one before any clip of its own existed.
11534- assert_eq!(session.file_frames(&path), frames);
11535- }
11536-
11537- /// The drop a hand actually makes: a library row let go on the *empty* bed
11538- /// past the last clip, which is most of the bed on any timeline shorter
11539- /// than the window. The whole chain the release runs, minus gpui's own
11540- /// pointer read -- [`Player::place_frame`]'s [`landing`], the frame back
11541- /// through the rate as [`Player::insert_source`] hands it over, and the one
11542- /// engine door a row goes through -- and the head lands on the frame the
11543- /// ghost was drawn on, black in front of it. It used to be swallowed by the
11544- /// clipboard's clamp inside `Project::paste` and appended after the last
11545- /// clip wherever it was let go, which is the bug this pins.
11546- #[test]
11547- fn a_row_dropped_on_the_open_bed_lands_under_the_pointer() {
11548- let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
11549- session.set_gain(0.0);
11550- session.import(&asset("test_av2.mp4")).expect("av2 matches");
11551- let second = session.sources()[1].path.clone();
11552- let fps = session.meta().frame_rate;
11553- assert_eq!(session.timeline_duration(), 5.0);
11554- // 5 s of timeline on a bed 30 s wide: the open bed past the last clip
11555- // is five sixths of it.
11556- let bed: Bounds<Pixels> = Bounds {
11557- origin: point(px(12.), px(400.)),
11558- size: size(px(600.), px(LANE_H)),
11559- };
11560- let scale = Scale {
11561- pps: 20.,
11562- start: 0.,
11563- };
11564-
11565- // What `Player::place_frame` answers for a pointer 200 px along the
11566- // bed: ten seconds in, five seconds past the end of the timeline, and
11567- // no mark anywhere near enough to pull it back.
11568- let clips = [session.lane_clips(Lane::V1), session.lane_clips(Lane::A1)];
11569- let marks = snap_marks(&clips, None, frame_at(session.now(), fps));
11570- let under = frame_at(scale.time_at(px_along(px(212.), bed)), fps);
11571- let (at, cue) = landing(under, 0, 0, true, scale.snap_frames(fps), &marks);
11572- assert_eq!((at, cue), (300, None), "the pointer is on frame 300");
11573-
11574- // ...and what the release does with it: the frame back through the same
11575- // rate every box is drawn at, into the door the Add button uses too.
11576- assert!(
11577- session
11578- .place_stream_at(f64::from(at) / fps, &second, 0, None)
11579- .expect("av2 is already on this timeline")
11580- );
11581- let head = |lane| {
11582- session
11583- .lane_clips(lane)
11584- .last()
11585- .copied()
11586- .expect("the dropped clip")
11587- };
11588- assert_eq!(
11589- head(Lane::V1).start,
11590- at,
11591- "the drop landed somewhere other than under the pointer"
11592- );
11593- assert_eq!(head(Lane::A1).start, at, "...and its sound with it");
11594- assert!(head(Lane::V1).link.is_some(), "one grouped take");
11595- assert_eq!(head(Lane::V1).link, head(Lane::A1).link);
11596- // The bed in front of it stays black: nothing was stretched to reach
11597- // it, and the 4 s file is the whole of what was added.
11598- assert_eq!(session.timeline_duration(), 14.0);
11599- }
11600-
11601- /// Remove from library, through the door the menu item uses
11602- /// ([`Player::remove_source`] calls exactly this): refused by name while
11603- /// clips play from the file, and once they do not the row leaves the list.
11604- #[test]
11605- fn removing_a_row_is_refused_while_it_plays_and_takes_the_row_away() {
11606- let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
11607- session.set_gain(0.0);
11608- // Imported, then dragged onto the end: an import alone fills the
11609- // library, and a row with no clip is removable without any refusal to
11610- // test. This one has to have a take on the timeline.
11611- session.import(&asset("test_av2.mp4")).expect("av2 matches");
11612- let second = session.sources()[1].path.clone();
11613- let end = session.timeline_duration();
11614- assert!(
11615- session
11616- .place_stream_at(end, &second, 0, None)
11617- .expect("a file just imported is on this timeline")
11618- );
11619- let streams = HashMap::new();
11620- let rows = |session: &PlaybackSession| {
11621- library_rows(session.sources(), &streams, &HashMap::new(), None, |_| 0).len()
11622- };
11623- assert_eq!(rows(&session), 2, "a row per source");
11624-
11625- let refusal = session
11626- .remove_source(&second, 0)
11627- .expect_err("its take is still on the timeline")
11628- .to_string();
11629- assert!(refusal.contains("still plays"), "{refusal}");
11630- assert!(
11631- refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
11632- "the refusal names the lanes to clear: {refusal}"
11633- );
11634- assert_eq!(rows(&session), 2, "and the row is still there");
11635-
11636- // Delete that take -- the whole group, from either half -- and the file
11637- // can go. The list is what says so.
11638- let last = session.lane_clips(Lane::V1).len() - 1;
11639- assert!(session.delete_clip(Lane::V1, last));
11640- session
11641- .remove_source(&second, 0)
11642- .expect("nothing plays av2 any more");
11643- assert_eq!(rows(&session), 1, "the row went with it");
11644- assert_eq!(session.sources().len(), 1);
11645- // The one file left is held to the same rule and no other: its own take
11646- // is still on the lanes, so it stays...
11647- let first = session.sources()[0].path.clone();
11648- let refusal = session
11649- .remove_source(&first, 0)
11650- .expect_err("its take is still on the timeline")
11651- .to_string();
11652- assert!(refusal.contains("still plays"), "{refusal}");
11653- // ...and once nothing plays it, the *last* row goes too. What is left
11654- // is the empty library `Player::close_session` turns back into the
11655- // window the editor launches as -- the user-reported bug was that this
11656- // very removal was refused, leaving a row that could never be taken
11657- // out.
11658- assert!(session.delete_clip(Lane::V1, 0));
11659- session
11660- .remove_source(&first, 0)
11661- .expect("the only row goes like any other");
11662- assert_eq!(rows(&session), 0, "an empty library");
11663- assert!(session.sources().is_empty());
11664- // And it is still a session: silent, empty, and asked for its length
11665- // rather than panicking on a source list that is not there.
11666- assert_eq!(session.timeline_duration(), 0.0);
11667- assert!(
11668- session.save_project(&asset("nothing.edith")).is_err(),
11669- "a project naming no file could never be opened again, so it is not written"
11670- );
11671- // A row this timeline never had is refused, not panicked on.
11672- assert!(session.remove_source(&second, 0).is_err());
11673- }
11674-
11675- /// The clipboard after a library removal. A copied clip names its file by
11676- /// index and a removal renumbers the list, so this is the difference
11677- /// between pasting the take that was copied and pasting **another file**
11678- /// over the same range ([`clipboard_after_remove`], called by
11679- /// [`Player::remove_source`]).
11680- #[test]
11681- fn a_copied_clip_is_renumbered_or_dropped_when_a_row_leaves_the_library() {
11682- let clip = |source: usize| Clip {
11683- start: 0,
11684- in_frame: 0,
11685- out_frame: 30,
11686- source,
11687- link: None,
11688- eq: None,
11689- color: None,
11690- fit: Default::default(),
11691- speed: Default::default(),
11692- };
11693- // Copied from source 2, source 0 removed: the same file is source 1 now.
11694- assert_eq!(
11695- clipboard_after_remove(Some(clip(2)), 0).map(|c| c.source),
11696- Some(1),
11697- "the clipboard follows its file down the list"
11698- );
11699- // Copied from a source *before* the one that went: untouched.
11700- assert_eq!(
11701- clipboard_after_remove(Some(clip(0)), 2).map(|c| c.source),
11702- Some(0)
11703- );
11704- // Copied from the row that was just removed: there is nothing left to
11705- // paste, and pasting the next file along would be a lie.
11706- assert!(clipboard_after_remove(Some(clip(1)), 1).is_none());
11707- assert!(clipboard_after_remove(None, 0).is_none());
11708- }
11709-
11710- /// The trim-a-clip path through the doors the edge drag uses:
11711- /// [`Player::trim_to`] clamps the pointer with `trim_room` and
11712- /// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less
11713- /// of its file, the sound linked to it follows, the head trim moves the
11714- /// in-point, and one undo takes a whole gesture back.
11715- ///
11716- /// The routing *to* these doors -- the 6 px edge strip claiming the press
11717- /// the clip's own body-drag would otherwise take -- is gpui hitbox
11718- /// behaviour (`occlude`) and is not reachable without a window.
11719- #[test]
11720- fn a_clip_trimmed_by_its_edge_plays_less_of_its_file() {
11721- use engine::project::Edge;
11722-
11723- let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
11724- session.set_gain(0.0);
11725- let whole = session.lane_clips(Lane::V1)[0];
11726- let full = session.timeline_duration();
11727- assert_eq!(
11728- session.trim_room(Lane::V1, 0, Edge::End),
11729- Some((whole.start + 1, whole.end())),
11730- "the file's own last frame is how far the tail goes"
11731- );
11732- assert!(
11733- !session.trim_clip(Lane::V1, 0, Edge::End, 9_999),
11734- "it already plays all of it"
11735- );
11736-
11737- // Pulled in by a third: the timeline ends earlier and the sound with it.
11738- let shorter = whole.end() - whole.len() / 3;
11739- assert!(session.trim_clip(Lane::V1, 0, Edge::End, shorter));
11740- assert_eq!(session.lane_clips(Lane::V1)[0].end(), shorter);
11741- assert_eq!(
11742- session.lane_clips(Lane::A1)[0].end(),
11743- shorter,
11744- "the linked sound was trimmed with the picture"
11745- );
11746- assert!(session.timeline_duration() < full, "and plays out earlier");
11747-
11748- // ...and dragged back out, as far as the file goes and no further.
11749- assert!(session.trim_clip(Lane::V1, 0, Edge::End, 9_999));
11750- assert_eq!(
11751- session.lane_clips(Lane::V1)[0],
11752- whole,
11753- "the whole take back"
11754- );
11755-
11756- // The head takes the in-point with it, so what plays at the new start
11757- // is source frame 10 rather than source frame 0.
11758- assert!(session.trim_clip(Lane::V1, 0, Edge::Start, 10));
11759- let head = session.lane_clips(Lane::V1)[0];
11760- assert_eq!((head.start, head.in_frame), (10, 10));
11761- assert_eq!(session.lane_clips(Lane::A1)[0].in_frame, 10, "sound too");
11762- assert_eq!(
11763- session.trim_room(Lane::V1, 0, Edge::Start).map(|r| r.0),
11764- Some(0),
11765- "and it may be pulled back out to the file's first frame"
11766- );
11767-
11768- assert!(session.undo(), "one step for the whole drag");
11769- assert_eq!(session.lane_clips(Lane::V1)[0], whole);
11770- }
11771-
11772- /// The move-a-clip-between-tracks path through the door the drop uses
11773- /// ([`Player::move_clip`] calls exactly this): the clip changes row, the
11774- /// *picture* comes from the new row afterwards -- which is what "it plays
11775- /// from there" means -- and one undo puts it back.
11776- #[test]
11777- fn a_clip_dragged_onto_another_track_plays_from_it() {
11778- use engine::project::LaneKind;
11779-
11780- let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
11781- session.set_gain(0.0);
11782- let v2 = session.add_lane(LaneKind::Video);
11783- assert_eq!(session.video_clip_at(0.0), Some((Lane::V1, 0)));
11784-
11785- assert!(session.move_clip_to(Lane::V1, 0, v2, 0), "V1 -> V2");
11786- assert!(session.lane_clips(Lane::V1).is_empty(), "it left V1");
11787- assert_eq!(session.lane_clips(v2).len(), 1, "and landed on V2");
11788- assert_eq!(
11789- session.video_clip_at(0.0),
11790- Some((v2, 0)),
11791- "the picture now comes from V2"
11792- );
11793- assert_eq!(session.lane_clips(Lane::A1).len(), 1, "its sound stayed");
11794-
11795- // Dropped on a lane of the other kind it is refused and nothing moves --
11796- // the notice the front-end shows for it says which kind of lane to use.
11797- // (The other refusal, landing on another clip, is the engine's own test
11798- // `move_clip_keeps_the_frames_and_refuses_the_rest`.)
11799- assert!(!session.move_clip_to(v2, 0, Lane::A1, 0), "picture on A1");
11800- assert_eq!(session.lane_clips(v2).len(), 1, "and it stayed on V2");
11801- assert!(
11802- session.move_clip_to(v2, 0, Lane::V1, 0),
11803- "dragged back down"
11804- );
11805-
11806- // One undo per move, and each is a single step.
11807- assert!(session.undo(), "the drag back");
11808- assert_eq!(session.video_clip_at(0.0), Some((v2, 0)));
11809- assert!(session.undo(), "the drag up");
11810- assert_eq!(session.video_clip_at(0.0), Some((Lane::V1, 0)));
11811- assert!(session.lane_clips(v2).is_empty());
11812- }
11813-
11814- /// The add-a-track path end to end through the doors the buttons and the
11815- /// drop use: `+ V` adds a row, a library row let go over it lands there and
11816- /// nowhere else, Delete on it leaves the lanes under it where they are, and
11817- /// undo takes the whole thing back one step at a time.
11818- #[test]
11819- fn a_track_can_be_added_dropped_on_edited_and_taken_back() {
11820- use engine::project::LaneKind;
11821-
11822- let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
11823- session.set_gain(0.0);
11824- assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1]);
11825- // What the `+ V` button asks for, and what the row it draws is called.
11826- let v2 = session.add_lane(LaneKind::Video);
11827- assert_eq!(v2.label(), "V2");
11828- assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1, v2]);
11829- assert!(session.lane_clips(v2).is_empty());
11830- // A library row let go over that row: the same door the Add button
11831- // uses, told which lane it was let go over.
11832- let path = session.sources()[0].path.clone();
11833- assert!(
11834- session
11835- .place_stream_at(1.0, &path, 0, Some(v2))
11836- .expect("its own file is on this timeline")
11837- );
11838- assert_eq!(session.lane_clips(v2).len(), 1, "the drop landed on V2");
11839- assert_eq!(session.lane_clips(v2)[0].start, 30, "at the playhead");
11840- // ...with the sound it came with, on the row of its own the drop added:
11841- // a file with audio dropped on a layer used to land silent.
11842- let a2 = Lane::new(LaneKind::Audio, 1);
11843- assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1, v2, a2]);
11844- assert_eq!(session.lane_clips(a2), session.lane_clips(v2), "same take");
11845- assert_eq!(
11846- session.lane_clips(v2)[0].link,
11847- session.lane_clips(a2)[0].link,
11848- "grouped, so a drag moves both"
11849- );
11850- // And nowhere else: the first pair is exactly as it was, one take each.
11851- assert_eq!(session.lane_clips(Lane::V1).len(), 1);
11852- assert_eq!(session.lane_clips(Lane::A1).len(), 1);
11853- // ...and it is a project that saves and opens again as it stands: a
11854- // grouped pair on a further row is what the file has to carry.
11855- let dir = engine::scratch::Scratch::dir("ve_layer");
11856- let file = dir.join("layer.edith");
11857- session.save_project(&file).expect("save the project");
11858- let back = PlaybackSession::open_project(&file).expect("it loads as it stands");
11859- std::fs::remove_dir_all(&dir).ok();
11860- assert_eq!(back.lanes(), session.lanes());
11861- for lane in back.lanes() {
11862- assert_eq!(back.lane_clips(lane), session.lane_clips(lane), "{lane:?}");
11863- }
11864- // Delete on the layer is a lift: it is laid over the timeline, so
11865- // closing a hole under it would drag the take beneath out of step with
11866- // it. The take on the first pair is still a take, and still ripples.
11867- assert!(!whole_take(&session, v2, 0));
11868- assert!(whole_take(&session, Lane::V1, 0));
11869- assert!(whole_take(&session, Lane::A1, 0));
11870- assert_eq!(a2.label(), "A2");
11871- assert!(session.lift_clip(v2, 0));
11872- assert!(session.lane_clips(v2).is_empty());
11873- assert_eq!(session.lane_clips(Lane::V1).len(), 1, "V1 stayed put");
11874- assert_eq!(
11875- session.lane_clips(a2).len(),
11876- 1,
11877- "a lift takes the half it names: the sound is still there to lift"
11878- );
11879- assert!(session.lift_clip(a2, 0));
11880-
11881- // A second audio lane used to be what an mp4 export could not write --
11882- // it copied one AAC track and a mix is not a copy. It mixes now
11883- // (`export::copy_audio`), so no row is greyed by a count of lanes.
11884- for format in [Format::Mp4, Format::Av1, Format::Av1Mp4] {
11885- assert_eq!(
11886- format_refusal(&session, format),
11887- None,
11888- "two audio lanes are a mix, not a refusal"
11889- );
11890- }
11891-
11892- // Undo, one edit at a time and backwards: the lift of the sound, the
11893- // lift of the picture, the drop on V2 with the lane A2 it added, and
11894- // last the lane V2 -- an added track is one step like every other edit.
11895- for lanes in [4, 4, 3, 2] {
11896- assert!(session.undo());
11897- assert_eq!(session.lanes().len(), lanes);
11898- }
11899- assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1]);
11900- assert_eq!(session.lane_clips(Lane::V1).len(), 1);
11901- assert_eq!(format_refusal(&session, Format::Mp4), None);
11902- }
11903-
11904- #[test]
11905- fn a_source_is_only_ever_asked_for_its_peaks_once() {
11906- let (a, b) = (asset("test_av.mp4"), asset("test_av2.mp4"));
11907- // Two files, and two streams of the first: three envelopes, because
11908- // one file's two audio tracks are two different waveforms.
11909- let sources = [
11910- Source {
11911- path: a.clone(),
11912- audio_stream: 0,
11913- },
11914- Source {
11915- path: a.clone(),
11916- audio_stream: 1,
11917- },
11918- Source {
11919- path: b.clone(),
11920- audio_stream: 0,
11921- },
11922- ];
11923- let keys = |s: &[Source]| {
11924- s.iter()
11925- .map(|s| (s.path.clone(), s.audio_stream))
11926- .collect::<Vec<_>>()
11927- };
11928- let mut waves: HashMap<(PathBuf, usize), Wave> = HashMap::new();
11929- assert_eq!(unseen_sources(&sources, &waves), keys(&sources));
11930- // The entry goes in when the decode *starts*, so the sixty repaints a
11931- // second that happen while it runs must not start it again -- which is
11932- // what this asserts about a key whose value is not an answer yet.
11933- waves.insert((a.clone(), 0), Wave::Loading);
11934- assert_eq!(
11935- unseen_sources(&sources, &waves),
11936- keys(&sources[1..]),
11937- "the file's other stream is a key of its own"
11938- );
11939- // A file with no audio is an answer like any other: never re-asked.
11940- waves.insert((a, 1), Wave::Silent);
11941- waves.insert((b.clone(), 0), Wave::Silent);
11942- assert!(unseen_sources(&sources, &waves).is_empty());
11943- // The stream probe is per *file*: the two entries of `a` ask once.
11944- let mut streams: HashMap<PathBuf, Vec<StreamInfo>> = HashMap::new();
11945- assert_eq!(
11946- unseen_paths(&sources, &streams),
11947- vec![asset("test_av.mp4"), b]
11948- );
11949- streams.insert(asset("test_av.mp4"), Vec::new());
11950- assert_eq!(unseen_paths(&sources, &streams).len(), 1);
11951- }
11952-
11953- #[test]
11954- fn the_add_button_is_dead_unless_it_would_do_something() {
11955- let picked = (PathBuf::from("/m/0.mp4"), 0);
11956- assert!(can_add(Some(&picked), true, false));
11957- // Nothing picked, nothing to put it on, or an export reading the very
11958- // edit list this would change.
11959- assert!(!can_add(None, true, false));
11960- assert!(!can_add(Some(&picked), false, false));
11961- assert!(!can_add(Some(&picked), true, true));
11962- }
11963-
11964- #[test]
11965- fn the_media_column_never_takes_the_picture_over() {
11966- for window in [360., 640., 1280., 1920., 3840.] {
11967- let w = super::library_w(window);
11968- // The whole point of the budget: the picture keeps the majority of
11969- // the row at every size a window can be.
11970- assert!(w <= window / 3., "{window}px window gave the list {w}px");
11971- assert!(w >= LIBRARY_MIN_W.min(window / 3.), "{window}px: {w}px");
11972- assert!(w <= LIBRARY_MAX_W);
11973- }
11974- // It yields: a narrower window gives the list less, never the same.
11975- assert!(super::library_w(640.) < super::library_w(1280.));
11976- // Rows are clickable, so WCAG 2.5.8 binds them like every other target,
11977- // and a name over a timecode has to fit inside one.
11978- assert!(ROW_H >= HIT_MIN);
11979- assert!(SWATCH_W < LIBRARY_MIN_W);
11980- }
11981-
11982- #[test]
11983- fn the_window_is_named_after_the_program_and_what_is_open() {
11984- assert_eq!(window_title("test_av.mp4"), "test_av.mp4 — edith");
11985- // An empty window is the program, not "no file open — edith".
11986- assert_eq!(window_title(NO_FILE), "edith");
11987- }
11988-
11989- #[test]
11990- fn frac_along_measures_from_the_elements_own_left_edge() {
11991- // A ruler inset by the panel's 12 px padding: window x is not bar x.
11992- let bar: Bounds<Pixels> = Bounds {
11993- origin: point(px(12.), px(400.)),
11994- size: size(px(200.), px(6.)),
11995- };
11996- assert_eq!(frac_along(px(12.), bar), 0.);
11997- assert_eq!(frac_along(px(112.), bar), 0.5);
11998- assert_eq!(frac_along(px(212.), bar), 1.);
11999- // Outside the bar (a click that slid off) clamps, never extrapolates.
12000- assert_eq!(frac_along(px(0.), bar), 0.);
12001- assert_eq!(frac_along(px(9999.), bar), 1.);
12002- // Never painted: no division by zero, no NaN reaching seek().
12003- assert_eq!(frac_along(px(50.), Bounds::default()), 0.);
12004-
12005- // The equalizer's axis is the other one, and reads the same way.
12006- let graph: Bounds<Pixels> = Bounds {
12007- origin: point(px(12.), px(60.)),
12008- size: size(px(296.), px(EQ_GRAPH_H)),
12009- };
12010- assert_eq!(frac_down(px(60.), graph), 0.);
12011- assert_eq!(frac_down(px(60. + EQ_GRAPH_H / 2.), graph), 0.5);
12012- assert_eq!(frac_down(px(9999.), graph), 1.);
12013- // Never painted reads as flat: an unpainted graph must not slam a band
12014- // to +12 dB on the first press.
12015- assert_eq!(frac_down(px(50.), Bounds::default()), 0.5);
12016- }
12017-
12018- /// What a drop reads: the frame under the pointer, through the same scale
12019- /// the boxes are drawn through. Zoomed in, the same pixel is a different
12020- /// frame -- which is the whole reason `Player::frame_under` goes through
12021- /// [`Scale`] rather than through the duration alone.
12022- #[test]
12023- fn a_drop_reads_the_frame_under_the_pointer_at_every_zoom() {
12024- // A 200 px bed inset by the panel's padding, 10 seconds at 30 fps.
12025- let bed: Bounds<Pixels> = Bounds {
12026- origin: point(px(12.), px(400.)),
12027- size: size(px(200.), px(6.)),
12028- };
12029- let fps = 30.;
12030- // The frame a pointer at window `x` names, exactly as `frame_under`
12031- // composes it.
12032- let under = |scale: Scale, x: f32| frame_at(scale.time_at(px_along(px(x), bed)), fps);
12033-
12034- // The whole 10 s timeline across the 200 px bed: 20 px to the second,
12035- // so halfway along is frame 150.
12036- let fit = Scale {
12037- pps: 20.,
12038- start: 0.,
12039- };
12040- assert_eq!(under(fit, 12.), 0);
12041- assert_eq!(under(fit, 112.), 150);
12042- assert_eq!(under(fit, 212.), 300);
12043-
12044- // Four times in, starting at second 5: the same middle pixel is now the
12045- // frame in the middle of seconds 5..7.5, and the left edge is not 0.
12046- let zoomed = Scale {
12047- pps: 80.,
12048- start: 5.,
12049- };
12050- assert_eq!(under(zoomed, 12.), 150);
12051- assert_eq!(under(zoomed, 112.), 187);
12052- assert_eq!(under(zoomed, 212.), 225);
12053- // ...and a pointer that slid off either end of the bed names an end of
12054- // the bed, never a pixel outside it.
12055- assert_eq!(under(zoomed, 0.), 150);
12056- assert_eq!(under(fit, 9999.), 300);
12057- }
12058-
12059- /// The snap: a clip let go a few frames off a neighbour's edge lands *on*
12060- /// it, by whichever of its own ends is nearer, and a clip let go in open bed
12061- /// stays exactly where the hand left it.
12062- #[test]
12063- fn a_dropped_clip_snaps_to_the_edges_worth_landing_on() {
12064- // A neighbour covering [100, 160) and the playhead at 300.
12065- let marks = [100, 160, 300, 0];
12066- // Head a frame short of the neighbour's tail: laid end to end with it.
12067- assert_eq!(snapped(158, 40, 4, &marks), 160);
12068- // Tail a frame into its head: pulled back so the two meet exactly.
12069- assert_eq!(snapped(62, 40, 4, &marks), 60);
12070- // The playhead is an edge like any other.
12071- assert_eq!(snapped(298, 40, 4, &marks), 300);
12072- // Outside the tolerance nothing moves -- a gap the hand meant to leave
12073- // is a gap.
12074- assert_eq!(snapped(150, 40, 4, &marks), 150);
12075- // No tolerance at all (zoomed right in, where a few pixels are worth
12076- // less than a frame) is no snap: single frames are placed by hand.
12077- assert_eq!(snapped(158, 40, 0, &marks), 158);
12078- // The nearer edge wins when two are in reach.
12079- assert_eq!(snapped(101, 40, 8, &marks), 100);
12080- // ...and a mark closer to the head than `len` cannot pull the clip to a
12081- // negative start.
12082- assert_eq!(snapped(2, 40, 4, &marks), 0);
12083- }
12084-
12085- /// The shadow a drag draws and the drop that commits are one answer: both
12086- /// ask [`landing`], so the box seen in flight is the box the release leaves
12087- /// behind. What this pins down is the composition around the snap -- the
12088- /// grab offset comes off *before* the magnet, or a clip taken by its tail
12089- /// would land a boxful late.
12090- #[test]
12091- fn a_ghost_and_a_drop_are_one_landing() {
12092- // A neighbour covering [100, 160), the playhead at 300, and a 40 frame
12093- // clip taken hold of 12 frames in.
12094- let marks = [100, 160, 300, 0];
12095- let (len, grab, tol) = (40, 12, 4);
12096- // Pointer at frame 170: the head is 12 frames behind it, at 158, which
12097- // is a frame short of the neighbour's tail -- so both the ghost and the
12098- // drop say 160, and the line stands on the mark that pulled it.
12099- assert_eq!(landing(170, grab, len, true, tol, &marks), (160, Some(160)));
12100- // Without the grab taken off first, the same pointer would land the
12101- // box at 170 and no mark would be in reach: the offset is not cosmetic.
12102- assert_eq!(landing(170, 0, len, true, tol, &marks), (170, None));
12103- // A library row carries no grab and no length the engine has measured,
12104- // which is how `Player::place_frame` asks: only its head lands, on the
12105- // playhead here.
12106- assert_eq!(landing(298, 0, 0, true, tol, &marks), (300, Some(300)));
12107- // The magnet off, ghost and drop agree on the raw frame and no line is
12108- // drawn -- the frame-by-frame placement the switch is for.
12109- assert_eq!(landing(170, grab, len, false, tol, &marks), (158, None));
12110- // A pointer nearer the bed's start than the hand is into the box cannot
12111- // pull a head below zero.
12112- assert_eq!(landing(3, grab, len, true, tol, &marks), (0, Some(0)));
12113- }
12114-
12115- /// Which lanes tint that shadow as refused: the two kinds of file a lane
12116- /// cannot hold, in the words the release would say them in -- one rule, so
12117- /// what is shown as impossible is exactly what is refused.
12118- #[test]
12119- fn a_lane_refuses_the_files_it_cannot_hold_before_the_release_says_so() {
12120- let (video, audio) = (Lane::V1, Lane::A1);
12121- let sound = Path::new("/media/take.mp3");
12122- let still = Path::new("/media/card.png");
12123- let movie = Path::new("/media/take.mp4");
12124- assert_eq!(
12125- lane_refuses(sound, video).as_deref(),
12126- Some("NOT ON V1 — take.mp3 has no picture; drop it on an audio lane")
12127- );
12128- assert_eq!(
12129- lane_refuses(still, audio).as_deref(),
12130- Some("NOT ON A1 — card.png is a still image; drop it on a video lane")
12131- );
12132- // ...and every lane a file *can* go on says nothing at all, which is a
12133- // ghost drawn in the file's own colour.
12134- assert_eq!(lane_refuses(sound, audio), None);
12135- assert_eq!(lane_refuses(still, video), None);
12136- assert_eq!(lane_refuses(movie, video), None);
12137- // A file with a picture is not refused by an audio lane here: the
12138- // engine takes its sound onto one, and the words for a video-only file
12139- // are its own.
12140- assert_eq!(lane_refuses(movie, audio), None);
12141- }
12142-
12143- /// Where those edges come from: every lane, not the one being dropped on --
12144- /// and never the clip in the hand or the half of it one track down.
12145- #[test]
12146- fn the_marks_are_every_lane_the_playhead_and_the_start() {
12147- let clip = |start: u32, frames: u32, link| Clip {
12148- start,
12149- in_frame: 0,
12150- out_frame: frames,
12151- source: 0,
12152- link,
12153- eq: None,
12154- color: None,
12155- fit: Default::default(),
12156- speed: Default::default(),
12157- };
12158- // A grouped take across two lanes at 100..160, and a lone one on the
12159- // audio lane at 400..430.
12160- let video = [clip(100, 60, Some(7))];
12161- let audio = [clip(100, 60, Some(7)), clip(400, 30, None)];
12162- let lanes: [&[Clip]; 2] = [&video, &audio];
12163-
12164- // Nothing in the hand: both lanes' edges, the playhead, and 0.
12165- let mut all = snap_marks(&lanes, None, 300);
12166- all.sort_unstable();
12167- assert_eq!(all, [0, 100, 100, 160, 160, 300, 400, 430]);
12168-
12169- // The video half in the hand: its own edges are gone, and so are its
12170- // group's on the other lane -- both boxes travel with the drag. The
12171- // lone audio clip is still a target, which is the whole point: a take
12172- // being carried on V1 lands flush with a sound on A1.
12173- let mut carried = snap_marks(&lanes, Some((0, 0)), 300);
12174- carried.sort_unstable();
12175- assert_eq!(carried, [0, 300, 400, 430]);
12176-
12177- // An index that names no clip skips nothing and still answers.
12178- assert_eq!(snap_marks(&[], Some((3, 9)), 0), [0, 0]);
12179- }
12180-
12181- /// The line the bed draws, and the switch that turns the whole thing off.
12182- #[test]
12183- fn the_snap_names_the_mark_it_landed_on_unless_it_is_switched_off() {
12184- let marks = [100, 160, 300, 0];
12185- // Pulled by the tail: the clip lands at 60 and the line stands on the
12186- // edge its *tail* met, 100 -- not on the head it happens to have.
12187- assert_eq!(snap_cue(true, 62, 40, 4, &marks), (60, Some(100)));
12188- // Pulled by the head: line and landing are the same frame.
12189- assert_eq!(snap_cue(true, 158, 40, 4, &marks), (160, Some(160)));
12190- // A trim carries no length, so only its own edge lands.
12191- assert_eq!(snap_cue(true, 298, 0, 4, &marks), (300, Some(300)));
12192- // Open bed: nothing moves and nothing is drawn.
12193- assert_eq!(snap_cue(true, 200, 40, 4, &marks), (200, None));
12194- // Switched off, a gesture that would have snapped lands raw and draws
12195- // no line -- the frame-by-frame placement the toggle is for.
12196- assert_eq!(snap_cue(false, 158, 40, 4, &marks), (158, None));
12197- }
12198-
12199- /// The card's rate row: every component the container states and no other,
12200- /// so a track the header is silent about is absent from the line rather
12201- /// than sitting in it as a zero.
12202- #[test]
12203- fn a_rate_row_says_only_what_the_container_stated() {
12204- use super::MediaBitrate;
12205- let all = MediaBitrate {
12206- total: Some(8_432_000),
12207- video: Some(7_918_000),
12208- audio: Some(128_000),
12209- };
12210- assert_eq!(
12211- bitrate_detail(Some(all), 1),
12212- "8.4 Mb/s · 7.9 video · 0.13 sound"
12213- );
12214- // A Matroska states no audio rate of its own: the sound is dropped from
12215- // the line, never drawn as "0".
12216- assert_eq!(
12217- bitrate_detail(
12218- Some(MediaBitrate {
12219- audio: None,
12220- ..all
12221- }),
12222- 1
12223- ),
12224- "8.4 Mb/s · 7.9 video"
12225- );
12226- // A still, or anything that would not open: the probe answered, and the
12227- // answer is that nobody said.
12228- assert_eq!(
12229- bitrate_detail(Some(MediaBitrate::default()), 0),
12230- "not stated"
12231- );
12232- // Asked, not answered yet -- a 12 GB film's walk takes seconds.
12233- assert_eq!(bitrate_detail(None, 2), "…");
12234- // A dual-audio file: the number is the track that plays, and the line
12235- // says so rather than letting it stand for the AC-3 beside it.
12236- assert_eq!(
12237- bitrate_detail(Some(all), 2),
12238- "8.4 Mb/s · 7.9 video · 0.13 1 of 2"
12239- );
12240- // Every component of a tiny file is stated, and small: the line changes
12241- // unit, so not one of them reads as the zero it is not. In megabits
12242- // this file was "0.00 Mb/s · 0.00 video · 0.00 sound".
12243- assert_eq!(
12244- bitrate_detail(
12245- Some(MediaBitrate {
12246- total: Some(4_998),
12247- video: Some(113),
12248- audio: Some(2_400),
12249- }),
12250- 1
12251- ),
12252- "5.0 kb/s · 0.11 video · 2.4 sound"
12253- );
12254- }
12255-
12256- /// The invariant under the row above, over every rate a container can
12257- /// state: a component the file *does* state never renders as a zero. The
12258- /// probe leaves out what is unstated, so a "0.00" on this card would be it
12259- /// saying a track that plays is silent.
12260- #[test]
12261- fn a_stated_rate_never_renders_as_a_zero() {
12262- use super::MediaBitrate;
12263- // Every decade from 1 bit a second to a 100 Mb/s master, the rounding
12264- // edges of each unit switch, and every pair of them in one line: the
12265- // line's unit is picked off its smallest component, so the widest
12266- // spread is the one that could round the biggest away.
12267- let edges: Vec<u64> = (0..12)
12268- .flat_map(|e| {
12269- let decade = 10_u64.pow(e);
12270- [decade, decade * 4, decade * 5, decade * 9]
12271- })
12272- .chain([MB_FLOOR - 1, MB_FLOOR, 999_999, 4_998, 113, 2_400])
12273- .collect();
12274- for &small in &edges {
12275- for &big in &edges {
12276- let line = bitrate_detail(
12277- Some(MediaBitrate {
12278- total: Some(small.max(big)),
12279- video: Some(big),
12280- audio: Some(small),
12281- }),
12282- 2,
12283- );
12284- for number in line
12285- .split(" · ")
12286- .filter_map(|part| part.split(' ').next())
12287- .filter_map(|n| n.parse::<f64>().ok())
12288- {
12289- assert!(number > 0., "{small}/{big} bits a second rendered as {line:?}");
12290- }
12291- }
12292- }
12293- }
12294-
12295- #[test]
12296- fn timecode_counts_frames_inside_the_second() {
12297- assert_eq!(timecode(0., 30.), "00:00:00:00");
12298- assert_eq!(timecode(-1., 30.), "00:00:00:00"); // clamped, never negative
12299- assert_eq!(timecode(4.9667, 30.), "00:00:04:29"); // last frame of a 5 s clip
12300- assert_eq!(timecode(5., 30.), "00:00:05:00");
12301- assert_eq!(timecode(3661.5, 30.), "01:01:01:15");
12302- // Rounding must not spill into a frame the second does not have.
12303- assert_eq!(timecode(1. - f64::EPSILON, 30.), "00:00:00:29");
12304- assert_eq!(timecode(0.999, 29.97), "00:00:00:29");
12305- }
12306-
12307- #[test]
12308- fn scrub_seeks_only_on_a_new_frame_and_only_every_100ms() {
12309- let (slow, fast) = (Duration::from_millis(100), Duration::from_millis(99));
12310- // Both halves must hold: a moved pointer that has not crossed a frame
12311- // boundary would reopen the decoder for the same picture.
12312- assert!(scrub_due(31, 30, slow));
12313- assert!(!scrub_due(30, 30, slow));
12314- assert!(!scrub_due(31, 30, fast));
12315- assert!(!scrub_due(30, 30, fast));
12316- // Exactly at the gap counts, and a long stall never blocks.
12317- assert!(scrub_due(1, 0, Duration::from_secs(9)));
12318- }
crates/app/src/tests/cards.rsadded+1353 -0
@@ -0,0 +1,1353 @@
1+//! The cards the window opens over itself: the keys, the equaliser, the
2+//! colour and speed bars, the silence scan, the choices and the export.
3+
4+use super::*;
5+
6+#[test]
7+fn escape_gets_out_of_an_export_whatever_is_held_with_it() {
8+ use keymap::ActionId;
9+ // The regression this guards: looking the stroke up in the keymap made
10+ // ctrl+escape mean nothing, and an export that a modifier could trap
11+ // the user inside of is worse than an unbound chord.
12+ assert!(cancels_export("escape", None));
13+ assert!(cancels_export("escape", Some(ActionId::CancelExport)));
14+ // A rebound cancel works as well -- it adds a way out, never replaces
15+ // the one that always worked.
16+ assert!(cancels_export("q", Some(ActionId::CancelExport)));
17+ // Nothing else does, whatever it means outside an export.
18+ assert!(!cancels_export("e", Some(ActionId::Export)));
19+ assert!(!cancels_export("space", Some(ActionId::Play)));
20+ assert!(!cancels_export("q", None));
21+}
22+
23+#[test]
24+fn a_capture_waits_through_a_lone_modifier() {
25+ // gpui delivers these on their own; taking one as a binding would make
26+ // the action fire on the way to every chord that uses it.
27+ for key in [
28+ "control", "shift", "alt", "super", "platform", "function", "fn", "meta", "command",
29+ ] {
30+ assert!(is_bare_modifier(key), "{key}");
31+ }
32+ // Everything a binding is actually made of, escape included -- the
33+ // capture branch turns that one away itself.
34+ for key in ["c", "x", "space", "escape", "delete", "f1", "z"] {
35+ assert!(!is_bare_modifier(key), "{key}");
36+ }
37+}
38+
39+/// The whole point of the card: there is no action a pointer cannot reach.
40+/// It renders [`keys_rows`] and nothing else, so this reads the same list
41+/// the card does -- add an `ActionId` and forget to surface it and this
42+/// fails, which is the only way that stays true as the editor grows.
43+#[test]
44+fn every_action_is_on_the_actions_card() {
45+ use keymap::{ActionId, Category, Keymap};
46+ let rows = keys_rows();
47+ let listed: Vec<ActionId> = rows
48+ .iter()
49+ .filter_map(|r| match r {
50+ KeyRow::Act(a) => Some(*a),
51+ _ => None,
52+ })
53+ .collect();
54+ for action in ActionId::ALL {
55+ assert_eq!(
56+ listed.iter().filter(|a| **a == action).count(),
57+ 1,
58+ "{action:?} is not on the card exactly once"
59+ );
60+ }
61+ assert_eq!(listed.len(), ActionId::ALL.len());
62+ // Under its own heading, in the registry's order: every row after a
63+ // heading belongs to that heading until the next one.
64+ let mut heading = None;
65+ let mut heads = 0;
66+ for row in &rows {
67+ match row {
68+ KeyRow::Head(category) => {
69+ heading = Some(*category);
70+ heads += 1;
71+ }
72+ KeyRow::Act(action) => assert_eq!(Some(action.category()), heading, "{action:?}"),
73+ KeyRow::Fixed(i) => assert_eq!(Some(keymap::FIXED[*i].category), heading),
74+ }
75+ }
76+ assert_eq!(heads, Category::ALL.len(), "a heading per category");
77+ // The card-local strokes are still all there beside them.
78+ assert_eq!(
79+ rows.iter()
80+ .filter(|r| matches!(r, KeyRow::Fixed(_)))
81+ .count(),
82+ keymap::FIXED.len()
83+ );
84+ // Both columns say something: the label does the action, the stroke
85+ // beside it changes that stroke, and neither may read blank.
86+ let keymap = Keymap::defaults();
87+ for action in ActionId::ALL {
88+ assert!(!action.label().is_empty(), "{action:?}");
89+ assert_ne!(keymap.display(action), "unbound", "{action:?}");
90+ }
91+ // The list scrolls inside a card the smallest window holds, so a
92+ // thirty-fourth action costs no height at all.
93+ assert!(rows.len() as f32 * KEYS_ROW_H > KEYS_ROWS_H, "no cap needed?");
94+ // Both halves of a row are click targets, so WCAG 2.5.8 binds them.
95+ assert!(KEYS_ROW_H >= HIT_MIN);
96+}
97+
98+/// The search box: what a typed word leaves standing. Forty actions is more
99+/// than a 360 px window shows at once, so this is the card's answer to
100+/// "where is the one I want" -- and a heading with nothing under it would
101+/// be worse than no filter at all.
102+#[test]
103+fn a_search_leaves_the_rows_it_names_under_their_own_headings() {
104+ use keymap::{ActionId, Category, Keymap};
105+ let keymap = Keymap::defaults();
106+ let acts = |found: &[(usize, KeyRow)]| -> Vec<ActionId> {
107+ found
108+ .iter()
109+ .filter_map(|(_, r)| match r {
110+ KeyRow::Act(a) => Some(*a),
111+ _ => None,
112+ })
113+ .collect()
114+ };
115+ let heads = |found: &[(usize, KeyRow)]| -> Vec<Category> {
116+ found
117+ .iter()
118+ .filter_map(|(_, r)| match r {
119+ KeyRow::Head(c) => Some(*c),
120+ _ => None,
121+ })
122+ .collect()
123+ };
124+ // Nothing typed hides nothing, and every row keeps its place in the
125+ // unfiltered list: an element id must not move under a keystroke.
126+ let all = keys_filter("", &keymap);
127+ assert_eq!(all.len(), keys_rows().len());
128+ assert!(all.iter().enumerate().all(|(n, (i, _))| n == *i));
129+ // The word the user types is the word on the row. The mix card names
130+ // the track volumes, so it is an honest hit; the fixed row about the
131+ // volume keys is another, and each comes with its own heading only.
132+ let vol = keys_filter("vol", &keymap);
133+ assert_eq!(
134+ acts(&vol),
135+ vec![ActionId::VolumeUp, ActionId::VolumeDown, ActionId::Mix]
136+ );
137+ assert_eq!(heads(&vol), vec![Category::Audio, Category::View]);
138+ // Case is not part of the question, in either direction.
139+ assert_eq!(keys_filter("VoL", &keymap).len(), vol.len());
140+ // The stroke column is searched too -- "what did ctrl do again" -- and
141+ // an unbound-looking word finds nothing rather than everything.
142+ let ctrl = keys_filter("ctrl+", &keymap);
143+ assert!(acts(&ctrl).contains(&ActionId::Save));
144+ assert!(!acts(&ctrl).contains(&ActionId::Play));
145+ assert!(
146+ keys_filter("qzx", &keymap).is_empty(),
147+ "headings left behind"
148+ );
149+ // The card's own door is on the card, by name and by stroke.
150+ assert_eq!(
151+ acts(&keys_filter("f1", &keymap)),
152+ vec![ActionId::ShowActions]
153+ );
154+ assert_eq!(
155+ acts(&keys_filter("all actions", &keymap)),
156+ vec![ActionId::ShowActions]
157+ );
158+}
159+
160+/// What a keystroke means to that box: a letter is a letter, and a word
161+/// gpui reports for a key that prints nothing is not typed letter by
162+/// letter into the search.
163+#[test]
164+fn only_a_printable_stroke_types_into_the_search() {
165+ assert_eq!(typed("a"), Some('a'));
166+ assert_eq!(typed("-"), Some('-'));
167+ assert_eq!(typed("1"), Some('1'));
168+ // The one printable key gpui reports by name.
169+ assert_eq!(typed("space"), Some(' '));
170+ for word in ["left", "escape", "f1", "backspace", "tab", "delete", "home"] {
171+ assert_eq!(typed(word), None, "{word}");
172+ }
173+}
174+
175+#[test]
176+fn the_keybindings_card_fits_the_smallest_window() {
177+ // The row list is capped and scrolls, so the card's height no longer
178+ // depends on how many actions there are: a title, a status line, the
179+ // search box and the viewport, inside the 640x360 the rest of the
180+ // layout is sized for.
181+ let title = 17.; // 13 px text on its own line
182+ let status = 28.; // 11 px text, two lines: a refusal wraps
183+ let search = 15.; // 11 px text, one line: it never wraps
184+ let gaps = 4. * 2.;
185+ let padding = 24.;
186+ // The line the list scrolls under: margin, rule, padding.
187+ let separator = 4. + 1. + 4.;
188+ assert!(
189+ title + status + search + separator + KEYS_ROWS_H + gaps + padding <= 360.,
190+ "card too tall"
191+ );
192+ // ...and the list is the only part that grows with the editor, so the
193+ // rows past the fold are reached by scrolling that viewport (and, with
194+ // forty of them, by the search box above it) rather than by a card
195+ // taller than the window.
196+ assert!(
197+ keys_rows().len() as f32 * KEYS_ROW_H > KEYS_ROWS_H,
198+ "the list outgrew the viewport long ago; the cap must still scroll"
199+ );
200+ // The cap is only honest if it is the taller list that scrolls, not the
201+ // card that grows: every action must be reachable by scrolling, and
202+ // enough of them visible that the list reads as a list.
203+ assert!(
204+ KEYS_ROWS_H / KEYS_ROW_H >= 8.,
205+ "too few rows visible to scan"
206+ );
207+ assert!(KEYS_W <= 640., "card too wide");
208+ // The rows are clickable, so WCAG 2.5.8 binds them like every other
209+ // target in this window.
210+ assert!(KEYS_ROW_H >= HIT_MIN);
211+}
212+
213+/// The equalizer card's graph: where a band lands on it, that a drag reads
214+/// back as the gain it painted -- the two are one mapping and its inverse,
215+/// which is what makes a handle follow the pointer -- and that the card
216+/// still fits the window the other two are sized for.
217+#[test]
218+fn the_equalizer_graph_puts_a_band_where_a_drag_reads_it_and_fits_the_smallest_window() {
219+ use engine::eq::{Band, BandKind, EqParams};
220+ // Flat is the middle of the box: a band nobody has touched must not
221+ // look like one that has been turned down.
222+ assert_eq!(eq_y(0.), 0.5);
223+ // Full boost is the top edge, full cut the bottom one -- y grows down.
224+ assert_eq!(eq_y(EQ_GAIN_LIMIT), 0.);
225+ assert_eq!(eq_y(-EQ_GAIN_LIMIT), 1.);
226+ assert_eq!(eq_y(EQ_GAIN_LIMIT / 2.), 0.25);
227+ // A file may carry a gain past what this card offers (the format writes
228+ // any finite value): it paints on the edge, never off the box.
229+ assert_eq!(eq_y(400.), 0.);
230+ assert_eq!(eq_y(-400.), 1.);
231+
232+ // A pointer reads back as the gain that paints where it landed, which
233+ // is what makes a drag land under the hand ([`Player::drag_band`]).
234+ for gain in [-12., -6., 0., 6., 12.] {
235+ let read = (0.5 - eq_y(gain)) * 2. * EQ_GAIN_LIMIT;
236+ assert!((read - gain).abs() < 1e-4, "{gain} read back as {read}");
237+ }
238+
239+ // The frequency axis is logarithmic and spans the audible range: the
240+ // ends are the ends, and the decade at 200 Hz is as wide as the one at
241+ // 2 kHz -- the whole reason a bass band is reachable at all.
242+ assert_eq!(eq_x(EQ_FREQ_LOW), 0.);
243+ assert_eq!(eq_x(EQ_FREQ_HIGH), 1.);
244+ assert!((eq_x(200.) - 1. / 3.).abs() < 1e-4);
245+ assert!(((eq_x(2000.) - eq_x(200.)) - (eq_x(20000.) - eq_x(2000.))).abs() < 1e-4);
246+ // Off either end clamps rather than painting outside the box.
247+ assert_eq!(eq_x(1.), 0.);
248+ assert_eq!(eq_x(96_000.), 1.);
249+ // Every tick the card names is on the axis it is drawn against.
250+ for (freq, label) in EQ_TICKS {
251+ assert!(
252+ (EQ_FREQ_LOW..=EQ_FREQ_HIGH).contains(&freq),
253+ "tick {label} is off the axis"
254+ );
255+ }
256+ // The default bands all land inside it too, spread out enough that the
257+ // nearest-band pick (`Player::nearest_band`) has something to pick.
258+ let xs: Vec<f32> = EqParams::default_layout()
259+ .bands
260+ .iter()
261+ .map(|b| eq_x(b.freq_hz))
262+ .collect();
263+ for pair in xs.windows(2) {
264+ assert!(pair[1] - pair[0] > 0.1, "bands too close to aim at: {xs:?}");
265+ }
266+
267+ // Every default band says what it is, and a shelf says so: "12 kHz"
268+ // alone would not tell anyone it tilts the whole top octave.
269+ let labels: Vec<String> = EqParams::default_layout()
270+ .bands
271+ .iter()
272+ .map(band_label)
273+ .collect();
274+ assert_eq!(
275+ labels,
276+ [
277+ "80 Hz low shelf",
278+ "250 Hz",
279+ "1 kHz",
280+ "4 kHz",
281+ "12 kHz high shelf"
282+ ]
283+ );
284+ // A band moved off a round number reads as where it *is*: a keystroke
285+ // that changes the filter and not the number on the card is a keystroke
286+ // nobody can aim.
287+ assert_eq!(
288+ band_label(&Band {
289+ freq_hz: 2600.,
290+ gain_db: 0.,
291+ q: 1.,
292+ kind: BandKind::Peak
293+ }),
294+ "2.6 kHz"
295+ );
296+ assert_eq!(eq_freq_label(1122.), "1.12 kHz");
297+ assert_eq!(eq_freq_label(12000.), "12 kHz", "no zeroes to read past");
298+ assert_eq!(eq_freq_label(80.), "80 Hz");
299+
300+ // The card fits the smallest window and takes the room a bigger one has
301+ // -- it is a graph, and the width *is* the frequency resolution.
302+ assert!(eq_card_w(640.) <= 640. - 24., "card too wide for 640");
303+ assert!(eq_card_w(1280.) > eq_card_w(640.), "card ignores the window");
304+ assert_eq!(eq_card_w(1920.), EQ_W_MAX, "card grows without end");
305+ assert!(eq_card_w(320.) >= KEYS_W, "card narrower than a row of text");
306+ // At the smallest window the graph is still a graph: three across for
307+ // one down, so an octave is wide enough to put a handle in.
308+ assert!(
309+ eq_card_w(640.) - 24. >= 3. * EQ_GRAPH_H,
310+ "graph too square to aim at"
311+ );
312+
313+ // The same shape as the other two cards, so it fits where they do: the
314+ // graph stands where the export card's rows do, and is shorter than
315+ // they are. The numbers row is a row of buttons now, so it is one of
316+ // those tall rather than one line of text.
317+ let (title, status, gaps, padding) = (17., 28., 4. * 2., 24.);
318+ assert!(
319+ title + status + EQ_GRAPH_H + HIT_MIN + gaps + padding + CONTROL_H <= 360.,
320+ "card too tall"
321+ );
322+ assert!(
323+ EQ_GRAPH_H <= EXPORT_ROWS_H,
324+ "graph taller than a card of rows"
325+ );
326+ // What is dragged is the whole graph -- the handle is a 10 px dot, but
327+ // a press anywhere in the box takes the band nearest it -- so WCAG
328+ // 2.5.8 is satisfied by the box, which is far past the minimum.
329+ assert!(EQ_GRAPH_H >= HIT_MIN);
330+ assert!(
331+ EQ_HANDLE < HIT_MIN,
332+ "a dot that size would want its own hitbox"
333+ );
334+ assert!(KEYS_ROW_H >= HIT_MIN);
335+}
336+
337+/// Editing a band, which is what the card is *for*: the pointer reads a
338+/// frequency off the axis the same way the axis draws one, a new band lands
339+/// in the gap beside the picked one rather than on top of it, and every band
340+/// the card will hold has a digit that picks it.
341+#[test]
342+fn a_band_can_be_moved_added_and_reached() {
343+ use engine::eq::{Band, BandKind, EqParams};
344+ // Across the graph and back: a drag sets the frequency the handle is
345+ // then drawn at, so the two mappings have to be one another's inverse or
346+ // the handle walks away from the pointer.
347+ for freq in [20., 80., 250., 1000., 4000., 12000., 20000.] {
348+ let read = eq_freq(eq_x(freq));
349+ assert!(
350+ (read / freq - 1.).abs() < 1e-3,
351+ "{freq} Hz read back as {read}"
352+ );
353+ }
354+ // Off the box either end stops at the axis, never past it.
355+ assert_eq!(eq_freq(-1.), EQ_FREQ_LOW);
356+ assert_eq!(eq_freq(2.), EQ_FREQ_HIGH);
357+
358+ // A step of the frequency keys is a real move on screen -- a keystroke
359+ // that changes nothing visible is a keystroke that reads as broken --
360+ // and small enough to aim with.
361+ let step = eq_x(1000. * EQ_FREQ_STEP) - eq_x(1000.);
362+ assert!(step > 0.01 && step < 0.06, "frequency key steps {step}");
363+
364+ // A new band lands between the picked one and the next one up, in
365+ // octaves: 250 Hz and 1 kHz put it at 500, which is a gap on screen.
366+ let bands = EqParams::default_layout().bands;
367+ let added = inserted_band(&bands, 1);
368+ assert!((added.freq_hz - 500.).abs() < 1., "landed at {added:?}");
369+ assert_eq!(added.gain_db, 0., "a new band changes nothing until moved");
370+ assert_eq!(added.kind, BandKind::Peak, "a new band is not a shelf");
371+ assert!(eq_x(added.freq_hz) - eq_x(bands[1].freq_hz) > 0.1);
372+ // Above the topmost band the gap is the rest of the axis, and the band
373+ // still lands on it rather than off the end.
374+ let top = inserted_band(&bands, bands.len() - 1);
375+ assert!(
376+ top.freq_hz > bands[4].freq_hz && top.freq_hz <= EQ_FREQ_HIGH,
377+ "landed at {top:?}"
378+ );
379+ // Bands out of frequency order (a drag may cross two over) still get a
380+ // sane neighbour: the next one *up*, not the next one along the list.
381+ let crossed = vec![
382+ Band {
383+ freq_hz: 4000.,
384+ gain_db: 0.,
385+ q: 1.,
386+ kind: BandKind::Peak,
387+ },
388+ Band {
389+ freq_hz: 100.,
390+ gain_db: 0.,
391+ q: 1.,
392+ kind: BandKind::Peak,
393+ },
394+ ];
395+ let between = inserted_band(&crossed, 1);
396+ assert!(
397+ (between.freq_hz - 632.).abs() < 2.,
398+ "landed at {between:?}, not between 100 and 4000"
399+ );
400+
401+ // Every band the card will hold is one digit away: the keyboard has ten
402+ // digits, which is exactly why the cap is what it is.
403+ assert!(
404+ EQ_BANDS_MAX <= 10,
405+ "a band past the tenth has no key that picks it"
406+ );
407+ assert!(EQ_BANDS_MAX > EqParams::default_layout().bands.len());
408+ // The Q range holds the default, so a file's band never opens out of
409+ // range and needs dragging back in before it can be edited.
410+ assert!((EQ_Q_LOW..=EQ_Q_HIGH).contains(&0.707));
411+ assert!(EQ_Q_STEP > 1.);
412+}
413+
414+/// The analyser drawn behind the curve: a tone has to land on its own
415+/// frequency, or the backdrop is a decoration rather than a reading of what
416+/// is playing -- and someone shaping a band against it would be aiming at
417+/// the wrong octave.
418+#[test]
419+fn the_spectrum_puts_a_tone_under_its_own_frequency() {
420+ use std::f32::consts::TAU;
421+ let rate = 48_000u32;
422+ let sine = |hz: f32, amp: f32| -> Vec<f32> {
423+ (0..EQ_FFT)
424+ .map(|i| amp * (TAU * hz * i as f32 / rate as f32).sin())
425+ .collect()
426+ };
427+
428+ // Silence is the floor of the box everywhere, not a band of noise.
429+ let quiet = eq_spectrum(&vec![0.; EQ_FFT], rate);
430+ assert_eq!(quiet.len(), EQ_CURVE_STEPS + 1);
431+ assert!(quiet.iter().all(|&l| l == 0.), "silence drew something");
432+
433+ // A tone peaks over its own frequency, and the columns two octaves
434+ // either side of it are near the floor. "Over" to within a bin down low
435+ // and a column up high, which is all a 1024-point transform on a log
436+ // axis can promise: at 200 Hz a whole column is a fraction of a bin
437+ // wide, so the peak sits on the bin the tone fell in.
438+ let column = |freq: f32| (eq_x(freq) * EQ_CURVE_STEPS as f32).round() as usize;
439+ let freq_at = |col: usize| {
440+ let along = col as f32 / EQ_CURVE_STEPS as f32;
441+ EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along)
442+ };
443+ for hz in [200., 1000., 5000.] {
444+ let levels = eq_spectrum(&sine(hz, 0.05), rate);
445+ let (at, top) =
446+ levels
447+ .iter()
448+ .enumerate()
449+ .fold((0, 0f32), |best, (i, &l)| match l > best.1 {
450+ true => (i, l),
451+ false => best,
452+ });
453+ let slack = 1.5 * rate as f32 / EQ_FFT as f32 + 0.04 * hz;
454+ assert!(
455+ (freq_at(at) - hz).abs() <= slack,
456+ "{hz} Hz peaked at {:.0} Hz (column {at})",
457+ freq_at(at)
458+ );
459+ // -26 dBFS, which is where a 0.05 tone sits on the axis.
460+ let want =
461+ (20. * 0.05f32.log10() - EQ_SPECTRUM_DB.0) / (EQ_SPECTRUM_DB.1 - EQ_SPECTRUM_DB.0);
462+ assert!(
463+ (top - want).abs() < 0.05,
464+ "a -26 dBFS tone drew {top} of the box, not {want}"
465+ );
466+ // Two octaves off is far enough down the box that the hump reads as
467+ // one hump: 0.4 of the axis is a little over 30 dB.
468+ for off in [hz / 4., hz * 4.] {
469+ let away = levels[column(off).min(EQ_CURVE_STEPS)];
470+ assert!(
471+ top - away > 0.4,
472+ "{hz} Hz drew {top} but still {away} at {off} Hz"
473+ );
474+ }
475+ }
476+
477+ // Level reads as level: 40 dB quieter sits lower by the fraction of the
478+ // axis those 40 dB are.
479+ let loud = eq_spectrum(&sine(1000., 0.05), rate);
480+ let soft = eq_spectrum(&sine(1000., 0.0005), rate);
481+ let at = column(1000.);
482+ let drop = loud[at] - soft[at];
483+ let (floor, ceiling) = EQ_SPECTRUM_DB;
484+ assert!(
485+ (drop - 40. / (ceiling - floor)).abs() < 0.05,
486+ "40 dB quieter moved the analyser {drop} of the box"
487+ );
488+
489+ // A tap the engine has not filled yet (right after a seek) draws
490+ // nothing at all rather than a transform of half a window.
491+ assert!(eq_spectrum(&[0.; 16], rate).is_empty());
492+}
493+
494+/// The speed bar is the same round trip -- pixels -> rate -> fill -- with
495+/// one thing the colour sliders do not have to promise: **exactly 1.00x has
496+/// to be reachable**, by a hand as well as by the reset. A grid that missed
497+/// it would leave a clip nobody could put back.
498+#[test]
499+fn the_speed_bar_lands_where_it_paints_and_real_time_is_reachable() {
500+ let bar = Bounds {
501+ origin: point(px(180.), px(240.)),
502+ size: size(px(COLOR_BAR_W), px(KEYS_ROW_H)),
503+ };
504+ let (lo, hi) = (
505+ f32::from(Speed::MIN.permille()),
506+ f32::from(Speed::MAX.permille()),
507+ );
508+ // The same arithmetic `Player::drag_speed` runs, which is the one thing
509+ // a test of it can share without re-deriving it.
510+ let at = |x: f32| {
511+ let raw = lo + frac_along(px(x), bar) * (hi - lo);
512+ speed_at((raw / SPEED_STEP as f32).round() as i32 * SPEED_STEP)
513+ };
514+ assert_eq!(at(180.), Speed::MIN, "the left end is a quarter speed");
515+ assert_eq!(at(180. + COLOR_BAR_W), Speed::MAX, "the right end is 4x");
516+ assert_eq!(at(-4000.), Speed::MIN, "off the left clamps");
517+ assert_eq!(at(9999.), Speed::MAX, "off the right clamps");
518+ let mut hits_real_time = false;
519+ for step in 0..=240 {
520+ let along = step as f32 / 240.;
521+ let speed = at(180. + along * COLOR_BAR_W);
522+ hits_real_time |= speed == Speed::NORMAL;
523+ assert_eq!(
524+ i32::from(speed.permille()) % SPEED_STEP,
525+ 0,
526+ "{speed} is off the {SPEED_STEP} grid the keys move on"
527+ );
528+ // What the bar paints from that rate is where the pointer was, to
529+ // within the half step the snap costs.
530+ let painted = (f32::from(speed.permille()) - lo) / (hi - lo);
531+ let slack = SPEED_STEP as f32 / (hi - lo) / 2. + 1e-4;
532+ assert!(
533+ (painted - along).abs() <= slack,
534+ "pressed at {along}, paints at {painted}"
535+ );
536+ }
537+ assert!(hits_real_time, "a drag can land on exactly 1.00x");
538+ // ...and every preset the card offers is a rate the bar can also reach.
539+ for permille in SPEED_PRESETS {
540+ assert_eq!(Speed::from_permille(permille).permille(), permille);
541+ assert_eq!(i32::from(permille) % SPEED_STEP, 0);
542+ }
543+ assert!(SPEED_PRESETS.contains(&Speed::NORMAL.permille()), "reset");
544+}
545+
546+/// A colour slider is dragged straight to a value, so where the pointer
547+/// lands and where the bar then paints have to be the same place: this is
548+/// the round trip [`Player::drag_color`] makes, pixels -> value -> fill.
549+#[test]
550+fn a_colour_drag_lands_where_it_paints_and_the_card_fits_the_smallest_window() {
551+ // A bar as laid out, somewhere that is not the window's origin -- a
552+ // mapping that forgot the offset would pass at zero.
553+ let bar = Bounds {
554+ origin: point(px(180.), px(240.)),
555+ size: size(px(COLOR_BAR_W), px(KEYS_ROW_H)),
556+ };
557+ for &(label, low, high) in &COLOR_BANDS {
558+ // The ends are the ends: the left of the bar is the bottom of the
559+ // range and the right is the top, so a slider can be pulled to
560+ // either without hunting for the last pixel.
561+ let at = |x: f32| color_snap(low + frac_along(px(x), bar) * (high - low));
562+ assert_eq!(at(180.), low, "{label} left end");
563+ assert_eq!(at(180. + COLOR_BAR_W), high, "{label} right end");
564+ // Off either end clamps rather than running past the range.
565+ assert_eq!(at(-4000.), low, "{label} off the left");
566+ assert_eq!(at(9999.), high, "{label} off the right");
567+
568+ for step in 0..=48 {
569+ let along = step as f32 / 48.;
570+ let value = at(180. + along * COLOR_BAR_W);
571+ // Every stop is one the keyboard can also reach, which is what
572+ // keeps "0.35" the number the file writes.
573+ let steps = value / COLOR_STEP;
574+ assert!(
575+ (steps - steps.round()).abs() < 1e-3,
576+ "{label}: {value} is off the {COLOR_STEP} grid"
577+ );
578+ assert!(
579+ (low..=high).contains(&value),
580+ "{label}: {value} outside {low}..{high}"
581+ );
582+ // What the row paints from that value is where the pointer was,
583+ // to within the half step the snap costs.
584+ let painted = (value - low) / (high - low);
585+ let slack = COLOR_STEP / (high - low) / 2. + 1e-4;
586+ assert!(
587+ (painted - along).abs() <= slack,
588+ "{label}: pressed at {along}, paints at {painted}"
589+ );
590+ }
591+ }
592+
593+ // The same shape as the other two cards, so it fits where they do: the
594+ // graph, four rows and the reset button inside a 360 px window.
595+ let (title, status, gaps, padding) = (17., 17., 6. * 2., 24.);
596+ let rows = COLOR_BANDS.len() as f32 * KEYS_ROW_H;
597+ assert!(
598+ title + status + HIST_H + rows + gaps + padding + CONTROL_H + 4. <= 360.,
599+ "card too tall"
600+ );
601+ assert!(COLOR_W <= 640., "card too wide");
602+ // The label still has room beside the bar and the readout, which is
603+ // what the buttons coming off the row bought.
604+ let row = COLOR_W - padding - 12. - 2. * 8. - COLOR_BAR_W - 44.;
605+ assert!(row >= LABEL_MIN_W, "no room left for a label: {row}px");
606+ // What is dragged is the whole row's height, not the 4 px the bar is
607+ // drawn as (WCAG 2.5.8) -- the same split the ruler makes.
608+ assert!(KEYS_ROW_H >= HIT_MIN);
609+}
610+
611+/// The graph over the sliders is the frame the grade already went through,
612+/// so it has to count what is actually in those bytes -- BGRA on the wire,
613+/// red-green-blue in the bins.
614+#[test]
615+fn the_histogram_counts_the_frame_it_is_handed() {
616+ // Half pure red, half mid grey: two known values, in two known bins.
617+ let (w, h) = (64usize, 64usize);
618+ let mut frame = Vec::with_capacity(w * h * 4);
619+ for _ in 0..h {
620+ for col in 0..w {
621+ match col < w / 2 {
622+ true => frame.extend_from_slice(&[0, 0, 255, 255]),
623+ false => frame.extend_from_slice(&[128, 128, 128, 255]),
624+ }
625+ }
626+ }
627+ let bins = histogram(&frame);
628+ let half = (w * h / 2) as u32;
629+ // 64 bins over 256 codes: 255 is the last bin, 128 the middle one, 0 the
630+ // first.
631+ assert_eq!(bins[0][63], half, "the red half tops the red channel");
632+ assert_eq!(bins[0][32], half, "and the grey half sits mid red");
633+ for channel in [1, 2] {
634+ assert_eq!(bins[channel][0], half, "no green or blue in the red half");
635+ assert_eq!(bins[channel][32], half);
636+ assert_eq!(bins[channel][63], 0);
637+ }
638+ // Nothing is counted twice and nothing is dropped: this frame is small
639+ // enough to be read whole.
640+ for channel in bins {
641+ assert_eq!(channel.iter().sum::<u32>(), (w * h) as u32);
642+ }
643+
644+ // A grade shifts it, which is the whole point of drawing it: the same
645+ // frame darkened lands in lower bins.
646+ let darker: Vec<u8> = frame.iter().map(|b| b / 2).collect();
647+ let bins = histogram(&darker);
648+ assert_eq!(bins[0][31], half, "255 -> 127");
649+ assert_eq!(bins[0][16], half, "128 -> 64");
650+
651+ // A real frame is subsampled: a 1080p one is read every 253rd pixel, so
652+ // the shape costs a thousandth of the reads and still counts thousands.
653+ let big = vec![200u8; 1920 * 1080 * 4];
654+ let bins = histogram(&big);
655+ let counted = bins[0].iter().sum::<u32>();
656+ let pixels = 1920 * 1080usize;
657+ let expected = pixels.div_ceil(pixels / HIST_SAMPLES) as u32;
658+ assert_eq!(counted, expected, "every strided pixel counted, once");
659+ assert!(
660+ (HIST_SAMPLES as u32..=HIST_SAMPLES as u32 + 64).contains(&counted),
661+ "{counted} samples is not the budget"
662+ );
663+ assert_eq!(bins[0][200 * HIST_BINS / 256], counted, "all in one bin");
664+
665+ // An empty buffer is a flat graph rather than a panic: the card is open
666+ // before the first frame is pumped.
667+ assert_eq!(histogram(&[]), [[0; HIST_BINS]; 3]);
668+}
669+
670+/// Mute and level are one control with two states, and the whole point is
671+/// that mute keeps the level: the user gets back what they had, not 100%.
672+#[test]
673+fn muting_keeps_the_level_it_comes_back_to() {
674+ let mut volume = Volume::default();
675+ assert_eq!(volume.gain(), 1.0);
676+ assert_eq!(volume.label(), "Vol 100%");
677+
678+ // Four presses down, then muted: the gain is silence but the level is
679+ // still what it was, and the button keeps saying so.
680+ for _ in 0..4 {
681+ volume.step(false);
682+ }
683+ assert_eq!(volume.gain(), 0.8);
684+ volume.muted = true;
685+ assert_eq!(volume.gain(), 0.0);
686+ assert_eq!(volume.label(), "Muted 80%");
687+
688+ // Turning it down while muted stays muted -- the one thing a mute
689+ // button must never do is get louder because you asked for quieter.
690+ volume.step(false);
691+ assert_eq!(volume.gain(), 0.0);
692+ assert!(volume.muted);
693+
694+ // Unmute returns to the level, including the step taken while silent.
695+ volume.muted = false;
696+ assert_eq!(volume.gain(), 0.75);
697+}
698+
699+/// The whole transport in one place: the clock keeps running past the last
700+/// frame (wall time takes over at audio EOF), so "the clock is going" is
701+/// not "this is playing" -- and a button that read the clock showed Pause
702+/// on a timeline that had stopped moving. Ended is its own state, it draws
703+/// Play, and the next press starts over from the top.
704+#[test]
705+fn a_played_out_timeline_is_not_playing_and_the_next_press_starts_it_over() {
706+ assert_eq!(transport(true, false), Transport::Playing);
707+ assert_eq!(transport(false, false), Transport::Paused);
708+ // The transition the bug was about: the clock is still running and the
709+ // decoder is finished. Played out wins, however the clock reads.
710+ assert_eq!(transport(true, true), Transport::Ended);
711+ assert_eq!(transport(false, true), Transport::Ended);
712+
713+ // What the button draws, in each state. Two bars only while it moves.
714+ assert!(Transport::Playing.is_playing());
715+ for state in [Transport::Paused, Transport::Ended, Transport::Stopped] {
716+ assert!(!state.is_playing(), "{state:?} must draw the Play triangle");
717+ }
718+
719+ // And what a press does: start over at the end, plain toggle before it,
720+ // nothing with no timeline. Same answer for the key and the button --
721+ // both come through `Player::toggle_or_restart`.
722+ assert!(Transport::Ended.restarts());
723+ for state in [Transport::Playing, Transport::Paused, Transport::Stopped] {
724+ assert!(!state.restarts(), "{state:?} must toggle, not reseek");
725+ }
726+}
727+
728+/// The half of `Ended` the eye cannot see: the clock. Wall time takes over
729+/// at the last frame and nothing used to stop it, so the playhead walked off
730+/// the end of the timeline in real time -- and the playhead is what a cut, a
731+/// paste, an insert and the analyser all act at. `pump` pauses on the
732+/// crossing; this is the engine contract that rests on, driven exactly as
733+/// the pump drives it.
734+#[test]
735+fn the_clock_stops_where_the_timeline_does_and_the_end_still_restarts() {
736+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
737+ session.set_gain(0.0);
738+ // Start a breath short of the end: the tail is what this is about, and
739+ // playing the whole five seconds would say nothing more.
740+ session.seek(4.8);
741+ session.play();
742+
743+ // The pump's own loop -- tick, drain, ask where the transport is --
744+ // with a deadline so a fixture that will not decode fails as a failure
745+ // rather than as a hang.
746+ let deadline = Instant::now() + Duration::from_secs(20);
747+ let mut state = transport(session.is_playing(), session.is_eos());
748+ while state != Transport::Ended {
749+ assert!(Instant::now() < deadline, "never reached the end of a 5s file");
750+ session.tick();
751+ while session.try_frame().is_some() {}
752+ state = transport(session.is_playing(), session.is_eos());
753+ }
754+
755+ // What `pump` does on the crossing, and the whole point of it: the
756+ // position holds still afterwards instead of counting on past the end,
757+ // and it holds still *on the out point* -- where the timecode and the
758+ // playhead have been showing it. The clock at the moment the end is
759+ // recognised is not that: a slow renderer reaches EOF with the clock
760+ // seconds past the timeline, which is why this repositions rather than
761+ // only freezing.
762+ session.halt_at_end();
763+ let stopped_at = session.now();
764+ assert_eq!(stopped_at, session.timeline_duration());
765+ std::thread::sleep(Duration::from_millis(250));
766+ assert_eq!(session.now(), stopped_at, "the clock kept running past EOF");
767+ // And it is still the end: pausing must not spend the state the glyph
768+ // and the restart both read.
769+ assert!(session.is_eos());
770+ assert_eq!(
771+ transport(session.is_playing(), session.is_eos()),
772+ Transport::Ended
773+ );
774+
775+ // The restart path off that frozen end, which is what the button and
776+ // the play key do from `Ended`: back to the top, and running.
777+ session.seek(0.);
778+ session.play();
779+ assert!(!session.is_eos(), "a seek revives the session");
780+ assert!(session.now() < 1.0);
781+ assert_eq!(
782+ transport(session.is_playing(), session.is_eos()),
783+ Transport::Playing
784+ );
785+ session.pause();
786+}
787+
788+/// Both ends hold under a key held down: the ABI only accepts `0.0..=1.0`,
789+/// and a wrapped step count would hand it something else.
790+#[test]
791+fn the_volume_stops_at_both_ends() {
792+ let mut volume = Volume::default();
793+ for _ in 0..40 {
794+ volume.step(true);
795+ }
796+ assert_eq!(volume.gain(), 1.0);
797+ assert_eq!(volume.steps, Volume::MAX_STEPS);
798+
799+ for _ in 0..40 {
800+ volume.step(false);
801+ }
802+ assert_eq!(volume.gain(), 0.0);
803+ assert_eq!(volume.label(), "Vol 0%");
804+
805+ // Silent by the level rather than by the flag is still not muted: the
806+ // button says which, because only one of them survives a step up.
807+ assert!(!volume.muted);
808+ volume.step(true);
809+ assert_eq!(volume.gain(), 0.05);
810+}
811+
812+#[test]
813+fn a_quality_row_is_the_bitrate_it_promises() {
814+ // Auto is the one row that says nothing: the exporter derives it, and
815+ // a number typed against the custom row must not leak into it.
816+ let mp4 = Format::Mp4;
817+ assert_eq!(
818+ export_settings(Quality::Auto, 7, mp4, DEFAULT_AUDIO_KBPS).bitrate,
819+ None
820+ );
821+ assert_eq!(
822+ export_settings(Quality::Low, 0, mp4, DEFAULT_AUDIO_KBPS).bitrate,
823+ Some(2_000_000)
824+ );
825+ assert_eq!(
826+ export_settings(Quality::Medium, 0, mp4, DEFAULT_AUDIO_KBPS).bitrate,
827+ Some(6_000_000)
828+ );
829+ assert_eq!(
830+ export_settings(Quality::High, 0, mp4, DEFAULT_AUDIO_KBPS).bitrate,
831+ Some(12_000_000)
832+ );
833+ // Megabits as typed, and as the row says it back.
834+ assert_eq!(
835+ export_settings(Quality::Custom, 7, mp4, DEFAULT_AUDIO_KBPS).bitrate,
836+ Some(7_000_000)
837+ );
838+ assert_eq!(Quality::Low.detail(0), "2 Mbps");
839+ // The picked format travels, or the card's rows would be a picture of a
840+ // choice the engine never hears about.
841+ for format in [Format::Mp4, Format::Wav, Format::Flac] {
842+ assert_eq!(
843+ export_settings(Quality::Auto, 0, format, DEFAULT_AUDIO_KBPS).format,
844+ format
845+ );
846+ }
847+ // Every fixed row sits inside the engine's clamp
848+ // (`MAX_EXPLICIT_BITRATE`), so no row can promise a bitrate the exporter
849+ // silently changes -- the ceiling row included, which is the one a
850+ // raised cap could have walked out past.
851+ for quality in Quality::ALL {
852+ let settings = export_settings(quality, MBPS_MAX, mp4, DEFAULT_AUDIO_KBPS);
853+ if let Some(bitrate) = settings.bitrate {
854+ assert!(
855+ (u64::from(MBPS_MIN) * 1_000_000..=u64::from(MBPS_MAX) * 1_000_000)
856+ .contains(&bitrate),
857+ "{quality:?} outside the engine clamp"
858+ );
859+ }
860+ // The software pin is the environment's to set, never a row's.
861+ assert!(!settings.force_sw);
862+ }
863+}
864+
865+/// The Sound row: what it offers, and that the pick travels to the engine
866+/// for a *video* export as much as for an MP3 -- both files carry sound, so
867+/// a row that only reached the audio formats would be half a control.
868+#[test]
869+fn the_sound_row_carries_its_rate_into_both_kinds_of_file() {
870+ // Sorted and unique, so a row that says "b for the next one" is stepping
871+ // up and not shuffling.
872+ assert!(AUDIO_KBPS.windows(2).all(|w| w[0] < w[1]));
873+ // The untouched figure is one of the offered rows, or the first press of
874+ // `b` would jump somewhere nobody chose.
875+ assert!(AUDIO_KBPS.contains(&DEFAULT_AUDIO_KBPS));
876+ // ...and it is what this program wrote before the row existed: the
877+ // export of a user who never opens it must not change under them.
878+ assert_eq!(DEFAULT_AUDIO_KBPS, 256);
879+ for format in [Format::Mp4, Format::Av1, Format::Hevc, Format::Mp3] {
880+ for kbps in AUDIO_KBPS {
881+ assert_eq!(
882+ export_settings(Quality::Auto, 0, format, kbps).audio_kbps,
883+ Some(kbps),
884+ "{format:?} at {kbps} kbps"
885+ );
886+ }
887+ }
888+ // The pointer's door to the same field: one row per rate, the one in
889+ // force marked exactly once, and every row's small print short enough
890+ // to survive `MENU_W`'s truncation (the resolution list's own rule).
891+ let rows = audio_rate_choices(DEFAULT_AUDIO_KBPS);
892+ assert_eq!(rows.len(), AUDIO_KBPS.len());
893+ assert_eq!(rows.iter().filter(|(.., picked)| *picked).count(), 1);
894+ for ((choice, label, detail, picked), kbps) in rows.iter().zip(AUDIO_KBPS) {
895+ assert_eq!(*choice, Choice::AudioRate(kbps));
896+ assert_eq!(label.as_ref(), format!("{kbps} kbps"));
897+ assert!(detail.chars().count() <= 26, "{detail} is too long to read");
898+ assert_eq!(*picked, kbps == DEFAULT_AUDIO_KBPS);
899+ }
900+ // A rate no row holds marks none of them, rather than the wrong one.
901+ assert!(audio_rate_choices(7).iter().all(|(.., picked)| !picked));
902+
903+ // The wrap the row's key does, which is the row's own step function.
904+ assert_eq!(
905+ next_audio_kbps(AUDIO_KBPS[AUDIO_KBPS.len() - 1]),
906+ AUDIO_KBPS[0]
907+ );
908+ assert_eq!(next_audio_kbps(DEFAULT_AUDIO_KBPS), 320);
909+ // A rate no list holds (a stale one, say) lands back on the first row
910+ // rather than nowhere.
911+ assert_eq!(next_audio_kbps(7), AUDIO_KBPS[1]);
912+}
913+
914+#[test]
915+fn a_typed_bitrate_is_a_field_and_not_a_key_capture() {
916+ // It opens on the number in force, so backspace edits that number
917+ // rather than the field starting empty over a bitrate still being used.
918+ let mut edit = NumberEdit::new(12);
919+ assert_eq!(edit.text, "12");
920+ edit.backspace();
921+ edit.digit(8);
922+ assert_eq!(edit.text, "18");
923+ assert_eq!(edit.commit(), Some(18));
924+ // A card nobody has typed a number into opens empty: zero is not a
925+ // bitrate anyone chose.
926+ assert_eq!(NumberEdit::new(0).text, "");
927+
928+ // Out of range is refused *in words* and the digits stay put: clamping
929+ // 55 to 50 would write a bitrate the user never typed.
930+ let mut edit = NumberEdit::new(0);
931+ for digit in [5, 5] {
932+ edit.digit(digit);
933+ }
934+ assert_eq!(edit.commit(), None);
935+ assert_eq!(edit.text, "55", "a refusal keeps what was typed");
936+ let refusal = edit.refusal.clone().expect("a refusal says why");
937+ assert!(refusal.contains(&MBPS_MAX.to_string()), "{refusal}");
938+ assert!(edit.detail().starts_with("55▏"), "{}", edit.detail());
939+ assert!(edit.detail().contains(&refusal));
940+ // And is fixable in place, which is the whole point of a field.
941+ edit.backspace();
942+ assert_eq!(edit.refusal, None, "the reason went with the digit");
943+ assert_eq!(edit.commit(), Some(5));
944+
945+ // Empty, zero, and past the digit cap: each its own reason, none of
946+ // them silent.
947+ assert!(commit_mbps("").is_err());
948+ assert!(commit_mbps("0").unwrap_err().contains("not a rate"));
949+ assert_eq!(commit_mbps("1"), Ok(MBPS_MIN));
950+ assert_eq!(commit_mbps("50"), Ok(MBPS_MAX));
951+ assert!(commit_mbps("51").is_err());
952+ let mut edit = NumberEdit::new(0);
953+ for digit in [9, 9, 9, 9] {
954+ edit.digit(digit);
955+ }
956+ assert_eq!(edit.text, "999", "the cap holds");
957+ assert!(edit.refusal.is_some(), "and says it is holding");
958+ // Never past what a u64 bitrate can be built from -- the committed
959+ // number is the only one that reaches the engine, and it is bounded.
960+ assert!(u64::from(MBPS_MAX) * 1_000_000 < u64::from(u32::MAX));
961+ assert_eq!(MBPS_DIGITS, 3);
962+
963+ // The arrows step inside the range and stop at both ends: a walk
964+ // through the legal numbers, never a way out of them.
965+ let mut edit = NumberEdit::new(0);
966+ edit.step(1);
967+ assert_eq!(edit.text, MBPS_MIN.to_string(), "empty starts at the floor");
968+ edit.step(-1);
969+ assert_eq!(edit.text, MBPS_MIN.to_string());
970+ let mut edit = NumberEdit::new(MBPS_MAX);
971+ edit.step(1);
972+ assert_eq!(edit.text, MBPS_MAX.to_string());
973+ edit.step(-1);
974+ assert_eq!(edit.text, (MBPS_MAX - 1).to_string());
975+ // A step past a refused number clears the refusal with it.
976+ let mut edit = NumberEdit::new(0);
977+ edit.digit(5);
978+ edit.digit(5);
979+ assert_eq!(edit.commit(), None);
980+ edit.step(-1);
981+ assert_eq!(edit.refusal, None);
982+ assert_eq!(edit.text, MBPS_MAX.to_string(), "back inside the range");
983+
984+ // The hint the field shows when there is nothing to refuse names both
985+ // ways out of it.
986+ let detail = NumberEdit::new(6).detail();
987+ assert!(detail.contains("enter") && detail.contains("esc"), "{detail}");
988+ assert!(detail.starts_with("6▏"), "{detail}");
989+}
990+
991+#[test]
992+fn a_clip_with_no_sound_is_refused_in_the_same_words_whichever_kind_it_is() {
993+ // A still and a video with no audio track are one answer to one
994+ // question: the lane and index that were picked, the file, and which of
995+ // the two soundless things it is. What must never reach the bar is the
996+ // demuxer's own words -- a png handed to the mp4 reader answers "a box
997+ // with a larger size than it", which is true of a container and useless
998+ // to a person.
999+ assert_eq!(
1000+ unscannable(Lane::V1, 1, std::path::Path::new("/tmp/shot.png")),
1001+ "V1 clip 2 has no audio to scan — shot.png is a picture"
1002+ );
1003+ assert_eq!(
1004+ unscannable(
1005+ Lane::new(LaneKind::Audio, 1),
1006+ 0,
1007+ std::path::Path::new("/tmp/test_baseline.mp4")
1008+ ),
1009+ "A2 clip 1 has no audio to scan — test_baseline.mp4 is silent"
1010+ );
1011+}
1012+
1013+/// The hold gate: a value runs, everything else still means one press one
1014+/// action -- which is the whole invariant the blanket `is_held` filter used
1015+/// to carry on its own.
1016+#[test]
1017+fn a_held_key_moves_a_value_and_nothing_else() {
1018+ use keymap::ActionId;
1019+ // A card's four arrows, whichever card it is.
1020+ for key in ["up", "down", "left", "right"] {
1021+ assert!(repeats(Repeat::Card, key, None), "{key} on a card");
1022+ }
1023+ // The card's own one-shots: flatten every band, cut forty places, play
1024+ // them fast, close. None of them on a hold.
1025+ for key in ["r", "enter", "f", "1", "escape"] {
1026+ assert!(!repeats(Repeat::Card, key, None), "{key} on a card");
1027+ }
1028+ // Outside a card the keymap answers, and only the volume pair is a
1029+ // value being moved.
1030+ assert!(repeats(Repeat::Keymap, "up", Some(ActionId::VolumeUp)));
1031+ assert!(repeats(Repeat::Keymap, "down", Some(ActionId::VolumeDown)));
1032+ // ...and the zoom pair, which runs the view the way they run the level.
1033+ assert!(repeats(Repeat::Keymap, "=", Some(ActionId::ZoomIn)));
1034+ assert!(!repeats(Repeat::Keymap, "0", Some(ActionId::ZoomFit)));
1035+ for action in ActionId::ALL {
1036+ let held = repeats(Repeat::Keymap, "k", Some(action));
1037+ assert_eq!(
1038+ held,
1039+ matches!(
1040+ action,
1041+ ActionId::VolumeUp
1042+ | ActionId::VolumeDown
1043+ | ActionId::ZoomIn
1044+ | ActionId::ZoomOut
1045+ ),
1046+ "{action:?} on a hold"
1047+ );
1048+ }
1049+ // An arrow with nothing bound to it moves nothing on the timeline.
1050+ assert!(!repeats(Repeat::Keymap, "left", None));
1051+ // And a stroke being captured, an export, or the overlays: nothing at
1052+ // all, or the hold would bind a key and then fire what it just bound.
1053+ for key in ["up", "left", "escape", "5"] {
1054+ assert!(!repeats(Repeat::Nothing, key, Some(ActionId::VolumeUp)));
1055+ }
1056+}
1057+
1058+#[test]
1059+fn the_silence_card_fits_the_smallest_window_and_never_slows_a_silence_down() {
1060+ // The same 640x360 floor, and this card starts below the header: a
1061+ // title and a hint over its [`SILENCE_ROWS`] rows, the count line and
1062+ // the two buttons.
1063+ let (title, hint, count) = (17., 17., 17.);
1064+ let gaps = 6. * 5.;
1065+ let padding = 24.;
1066+ assert!(
1067+ HEADER_H
1068+ + 8.
1069+ + title
1070+ + hint
1071+ + SILENCE_ROWS as f32 * KEYS_ROW_H
1072+ + count
1073+ + KEYS_ROW_H
1074+ + gaps
1075+ + padding
1076+ <= 360.,
1077+ "card too tall"
1078+ );
1079+ // Its rows, its steppers and its buttons are clicked, so WCAG 2.5.8
1080+ // binds them: a stepper is `HIT_MIN` square inside a row of that height.
1081+ assert!(KEYS_ROW_H >= HIT_MIN);
1082+ // ...and the pair of them fits beside the widest value the card prints.
1083+ assert!(2. * HIT_MIN + 4. < COLOR_W / 2., "steppers crowd the value");
1084+ // A "speed-up" is never a slow-down: the rate stops above real time at
1085+ // one end and at what a clip can hold at the other, whatever the keys
1086+ // ask for. A silence played *slower* would make the timeline longer,
1087+ // which is the one thing neither button may do.
1088+ assert!(silence_rate(0) > Speed::NORMAL);
1089+ assert!(silence_rate(1000) > Speed::NORMAL);
1090+ assert_eq!(silence_rate(i32::MAX), Speed::MAX);
1091+ assert_eq!(silence_rate(4000), Speed::MAX);
1092+}
1093+
1094+/// The choice lists that replaced two click-to-cycle surfaces: every value
1095+/// on offer at once, exactly one of them marked as the one in force, the
1096+/// same order the stroke steps through, and the open list inside the
1097+/// 640x360 floor with every row a `HIT_MIN` target.
1098+#[test]
1099+fn a_choice_list_offers_every_value_and_fits_the_smallest_window() {
1100+ // Odd media: its own size is on the ladder, in its place by area, and
1101+ // nothing else moved.
1102+ let native = (1440, 1080);
1103+ let ladder = resolution_ladder(native);
1104+ assert_eq!(
1105+ ladder,
1106+ [
1107+ (3840, 2160),
1108+ (2560, 1440),
1109+ (1920, 1080),
1110+ (1440, 1080),
1111+ (1280, 720),
1112+ (854, 480)
1113+ ]
1114+ );
1115+ for size in RESOLUTIONS {
1116+ assert!(ladder.contains(&size), "{size:?} is not on offer");
1117+ }
1118+ // Media already at a listed size is on the ladder once, not twice.
1119+ assert_eq!(resolution_ladder((1920, 1080)).len(), RESOLUTIONS.len());
1120+
1121+ // The rows say the same thing the ladder does, and mark the one in
1122+ // force -- exactly one row, whichever rung the project is on.
1123+ let rows = resolution_choices((1280, 720), native);
1124+ assert_eq!(rows.len(), ladder.len());
1125+ assert_eq!(rows.iter().filter(|(.., picked)| *picked).count(), 1);
1126+ for ((choice, label, detail, picked), size) in rows.iter().zip(&ladder) {
1127+ assert_eq!(*choice, Choice::Size(size.0, size.1));
1128+ assert_eq!(label.as_ref(), format!("{}p", size.1));
1129+ assert!(detail.contains(&format!("{}x{}", size.0, size.1)));
1130+ assert_eq!(*picked, *size == (1280, 720));
1131+ }
1132+ // The media's own size says so: it is the one rung a person cannot read
1133+ // off a number they chose.
1134+ let (.., native_detail, _) = &rows[3];
1135+ assert!(
1136+ native_detail.contains("the media's own"),
1137+ "{native_detail}"
1138+ );
1139+ // A project at a size nobody listed still gets the whole list, with
1140+ // nothing marked rather than a wrong row marked.
1141+ assert!(
1142+ resolution_choices((1000, 1000), native)
1143+ .iter()
1144+ .all(|(.., picked)| !picked)
1145+ );
1146+ // Picking a row means that row, and stepping means the next one: the
1147+ // list and the stroke read the same ladder.
1148+ assert_eq!(next_resolution(ladder[1], native), ladder[2]);
1149+
1150+ // The fit list, on a clip: all four policies, in the order the stroke
1151+ // steps through them, the clip's own marked and every row naming the
1152+ // canvas it would place the picture on.
1153+ let mut fit = FITS[0];
1154+ for next in FITS.into_iter().skip(1).chain([FITS[0]]) {
1155+ assert_eq!(next_fit(fit), next, "the stroke skips a policy");
1156+ fit = next;
1157+ }
1158+ let fits = fit_choices(Lane::V1, 3, FITS[2], (1920, 1080));
1159+ assert_eq!(fits.len(), FITS.len());
1160+ assert_eq!(fits.iter().filter(|(.., picked)| *picked).count(), 1);
1161+ assert_eq!(fits[2].0, Choice::Fit(Lane::V1, 3, FITS[2]));
1162+ assert!(fits[2].3, "the clip's own policy is not marked");
1163+ assert!(fits[0].2.contains("1920x1080"), "{}", fits[0].2);
1164+
1165+ // The rate list, the other setting the project has of its own: every
1166+ // rate on offer, the media's own cycled in at its place by speed and
1167+ // said so, and the one the timeline is cut at marked. The value carried
1168+ // is the `f64` the engine conforms to, not the rounded label -- 23.976
1169+ // is not 24000/1001, and a rate the timescales cannot name is refused.
1170+ let ntsc = 24_000. / 1001.;
1171+ let rates = frame_rate_ladder(25.);
1172+ assert_eq!(rates.len(), FRAME_RATES.len(), "25 is already on the list");
1173+ let odd = frame_rate_ladder(48.);
1174+ assert_eq!(odd[5], 48., "the media's own, in its place by speed");
1175+ assert_eq!(odd.len(), FRAME_RATES.len() + 1);
1176+ let fps = fps_choices(ntsc, 48.);
1177+ assert_eq!(fps.len(), odd.len());
1178+ assert_eq!(fps.iter().filter(|(.., picked)| *picked).count(), 1);
1179+ assert_eq!(fps[0].0, Choice::Fps(ntsc), "the ratio, not 23.976");
1180+ assert_eq!(fps[0].1.as_ref(), "23.976 fps");
1181+ assert!(fps[0].3, "the rate in force is not marked");
1182+ assert!(fps[5].2.contains("the media's own"), "{}", fps[5].2);
1183+ for (.., detail, _) in &fps {
1184+ assert!(detail.chars().count() < 26, "{detail} loses its tail");
1185+ }
1186+
1187+ // The HDR list, the third project setting: all three renditions in the
1188+ // order they brighten, the one in force marked, and every row saying
1189+ // what it is in words that fit beside the label.
1190+ let tones = tone_choices(Preset::Standard);
1191+ assert_eq!(tones.len(), Preset::ALL.len());
1192+ assert_eq!(tones.iter().filter(|(.., picked)| *picked).count(), 1);
1193+ for (row, preset) in tones.iter().zip(Preset::ALL) {
1194+ assert_eq!(row.0, Choice::Tone(preset));
1195+ assert_eq!(row.1.as_ref(), tone_label(preset));
1196+ assert!(!row.2.is_empty(), "{preset:?} says nothing about itself");
1197+ assert!(row.2.chars().count() < 26, "{} loses its tail", row.2);
1198+ }
1199+ assert!(tones[1].3, "the rendition in force is not marked");
1200+
1201+ // The open list fits the floor the menus are measured against: the
1202+ // longest of them is the rate ladder with an odd rate cycled in, and it
1203+ // hangs at the pointer with every row on screen. Rows are click targets
1204+ // (WCAG 2.5.8).
1205+ assert!(MENU_ROW_H >= HIT_MIN);
1206+ assert!(odd.len() > ladder.len(), "the longest list moved");
1207+ assert!(MENU_PAD * 2. + odd.len() as f32 * MENU_ROW_H <= 360.);
1208+ let tall = MENU_PAD * 2. + ladder.len() as f32 * MENU_ROW_H;
1209+ assert!(tall <= 360., "the list is taller than the floor");
1210+ assert_eq!(
1211+ menu_at(point(px(600.), px(340.)), size(px(640.), px(360.)), tall),
1212+ (640. - MENU_W, 360. - tall),
1213+ "the list would hang off the smallest window"
1214+ );
1215+}
1216+
1217+#[test]
1218+fn the_export_card_fits_the_smallest_window() {
1219+ // Same 640x360 floor the keybindings card is measured against: the
1220+ // capped row list, the two summary lines and the confirm button, under
1221+ // a title and a status line.
1222+ let title = 17.;
1223+ let status = 28.;
1224+ // The head is one line of 11 px at this width -- every field of it,
1225+ // worst case, is 71 characters against the 76 that fit. The tail is
1226+ // budgeted for two: the destination's name is the user's and a long one
1227+ // wraps.
1228+ let summary = 15. + 30.;
1229+ // Six children in the column, so five gaps.
1230+ let gaps = 5. * 2.;
1231+ let padding = 24.;
1232+ assert_eq!(
1233+ EXPORT_FIXED_H,
1234+ title + status + summary + CONTROL_H + 4. + gaps + padding
1235+ );
1236+ assert!(EXPORT_FIXED_H + EXPORT_ROWS_H <= 360., "card too tall");
1237+ // The list grows with a window that has the room -- and never shrinks
1238+ // below the cap that made the floor fit, whatever arithmetic the window
1239+ // hands it.
1240+ let cap = |h: f32| (h - EXPORT_FIXED_H - 24.).max(EXPORT_ROWS_H);
1241+ assert_eq!(cap(360.), EXPORT_ROWS_H);
1242+ assert_eq!(cap(0.), EXPORT_ROWS_H);
1243+ assert!(cap(720.) > EXPORT_ROWS_H);
1244+ assert!(EXPORT_FIXED_H + cap(720.) <= 720.);
1245+ // ...and inside the 640 px floor with the scrim showing either side.
1246+ assert!(EXPORT_W + 2. * 12. <= 640.);
1247+ // The cap is only honest if enough of the list is on screen to read as
1248+ // one -- and the whole format section is: its header and every codec
1249+ // row, so nothing that is picked *first* is behind a scroll.
1250+ let codecs = FORMATS.iter().filter(|(row, ..)| !row.is_empty()).count();
1251+ assert!(EXPORT_ROWS_H / KEYS_ROW_H >= 1. + codecs as f32);
1252+ // Clickable rows, so WCAG 2.5.8 binds them as it binds the panel's --
1253+ // and the bitrate steppers are `HIT_MIN` squares sitting inside a row,
1254+ // which only fits while the row is at least as tall as one.
1255+ assert!(KEYS_ROW_H >= HIT_MIN);
1256+ assert!(CONTROL_H >= HIT_MIN);
1257+ // The dimmed text on the card -- every refusal, every detail, every key
1258+ // in its column -- is body text on `BG_RAISED` and WCAG 1.4.3 binds it.
1259+ // A dimmed row is drawn in this ink rather than at an opacity, which is
1260+ // what a refusal used to be readable through.
1261+ // Every palette, not the one in force: a family is picked at runtime
1262+ // now (`ui::theme`), so a floor met by one of them and missed by the
1263+ // other is a window somebody is looking at.
1264+ for id in crate::ui::theme::PaletteId::ALL {
1265+ let p = id.palette();
1266+ assert!(
1267+ contrast(p.FG_SECONDARY, p.BG_RAISED) >= 4.5,
1268+ "{id:?}: refusal ink {:.2}",
1269+ contrast(p.FG_SECONDARY, p.BG_RAISED)
1270+ );
1271+ // ...and on the picked row, where the highlight is the accent at
1272+ // surface brightness. Both inks clear 4.5:1 on it now -- the row still
1273+ // lifts its key and detail to `FG_PRIMARY`, as emphasis rather than as
1274+ // the rescue it used to be.
1275+ assert!(contrast(p.FG_PRIMARY, p.BG_SELECTED) >= 4.5, "{id:?}");
1276+ assert!(
1277+ contrast(p.FG_SECONDARY, p.BG_SELECTED) >= 4.5,
1278+ "{id:?}: refusal ink on the picked row {:.2}",
1279+ contrast(p.FG_SECONDARY, p.BG_SELECTED)
1280+ );
1281+ }
1282+}
1283+
1284+/// The progress line's two clocks, driven the way a repaint drives them:
1285+/// steady work, a stall where hardware hands over to software, then steady
1286+/// work again. The estimate may not whipsaw, may not vanish once it has
1287+/// been given, and must meet the elapsed clock at the end.
1288+#[test]
1289+fn the_export_estimate_rides_out_a_stall_and_converges() {
1290+ let (mut marks, mut elapsed, mut progress) = (Vec::new(), 0f32, 0f32);
1291+ // 2%/s, a 12 s stall at 40% -- longer than the window, so the window
1292+ // alone would have nothing left to measure -- and the same rate to the
1293+ // end: 62 s of wall clock for 50 s of work.
1294+ let rate = 0.02;
1295+ let (mut quiet, mut before_stall, mut after_stall, mut last) = (0f32, 0., 0., f32::MAX);
1296+ while progress < 1. {
1297+ let stalled = (20. ..32.).contains(&elapsed);
1298+ note_progress(&mut marks, elapsed, progress);
1299+ // What is really left, to hold every guess against.
1300+ let truth = (1. - progress) / rate + if stalled { 32. - elapsed } else { 0. };
1301+ match eta_secs(&marks, elapsed, progress) {
1302+ // "estimating…" is only allowed before there is a span to
1303+ // measure, and never again after the first number.
1304+ None => {
1305+ assert!(elapsed < ETA_SPAN + 1., "estimate vanished at {elapsed}");
1306+ quiet = elapsed;
1307+ }
1308+ Some(left) => {
1309+ // No guess is ever wilder than four times the truth: that
1310+ // is the eightfold spike a raw window rate throws on either
1311+ // edge of the stall.
1312+ assert!(left <= truth * 4., "at {elapsed}s: {left} vs {truth}");
1313+ // While the rate holds, the answer is the true one and it
1314+ // only ever counts down.
1315+ if elapsed >= 5. && elapsed < 20. {
1316+ assert!((left - truth).abs() <= truth * 0.15, "{elapsed}s: {left}");
1317+ assert!(left < last, "estimate grew while the rate held");
1318+ }
1319+ // Eight seconds past the stall it has caught up again.
1320+ if elapsed >= 40. {
1321+ assert!((left - truth).abs() <= truth * 0.25, "{elapsed}s: {left}");
1322+ assert!(left < last + 0.001, "estimate grew after the stall");
1323+ }
1324+ if (20. ..20.25).contains(&elapsed) {
1325+ before_stall = left;
1326+ }
1327+ if (31.5..31.75).contains(&elapsed) {
1328+ after_stall = left;
1329+ }
1330+ last = left;
1331+ }
1332+ }
1333+ // A window's worth of marks and no more, however long the encode.
1334+ assert!(marks.len() <= 20, "{} marks", marks.len());
1335+ elapsed += 0.25;
1336+ if !stalled {
1337+ progress = (progress + rate * 0.25).min(1.);
1338+ }
1339+ }
1340+ assert!(quiet > 0. && quiet < ETA_SPAN + 1.);
1341+ // The stall stretched the guess instead of erasing it, and by more than
1342+ // the stopped clock adds on its own.
1343+ assert!(
1344+ after_stall > before_stall + 12.,
1345+ "{before_stall} -> {after_stall}"
1346+ );
1347+ // Both clocks meet: a finished pass has nothing left.
1348+ assert_eq!(eta_secs(&marks, elapsed, 1.), Some(0.));
1349+ assert!((elapsed - 62.).abs() < 1., "{elapsed}");
1350+ assert_eq!(clock(83.4), "1:23");
1351+ assert_eq!(clock(114.), "1:54");
1352+ assert_eq!(clock(-1.), "0:00");
1353+}
crates/app/src/tests/editing.rsadded+1592 -0
@@ -0,0 +1,1592 @@
1+//! Importing, the library column, the menus, and every edit a clip or a
2+//! track can be handed.
3+
4+use super::*;
5+
6+/// What the file manager is handed: the parts a path keeps as they are, and
7+/// the ones the bus would otherwise read as something else.
8+#[test]
9+fn file_uri_encodes_what_a_path_carries() {
10+ assert_eq!(
11+ file_uri(std::path::Path::new("/a/b.mp4")),
12+ "file:///a/b.mp4"
13+ );
14+ assert_eq!(
15+ file_uri(std::path::Path::new("/home/x/out dir/my export.mp4")),
16+ "file:///home/x/out%20dir/my%20export.mp4"
17+ );
18+ assert_eq!(
19+ file_uri(std::path::Path::new("/tmp/ünlü#1?.mp4")),
20+ "file:///tmp/%C3%BCnl%C3%BC%231%3F.mp4"
21+ );
22+}
23+
24+/// An import fills the *library* and nothing else -- the whole point of
25+/// this door: the row is there at the file's own length before any clip
26+/// plays it, wearing the tint the lanes will tint that clip with, and the
27+/// timeline is exactly as long as it was. Placing it is the drag, and the
28+/// drag is a separate act.
29+#[test]
30+fn an_import_adds_a_row_at_its_own_length_and_leaves_the_lanes_alone() {
31+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
32+ session.set_gain(0.0);
33+ let before = session.timeline_duration();
34+ let clips: Vec<usize> = session
35+ .lanes()
36+ .into_iter()
37+ .map(|lane| session.lane_clips(lane).len())
38+ .collect();
39+ session.import(&asset("test_av2.mp4")).expect("av2 matches");
40+ assert_eq!(session.sources().len(), 2, "the library grew");
41+ assert_eq!(
42+ session.timeline_duration(),
43+ before,
44+ "an import must not place a clip"
45+ );
46+ assert_eq!(
47+ session
48+ .lanes()
49+ .into_iter()
50+ .map(|lane| session.lane_clips(lane).len())
51+ .collect::<Vec<_>>(),
52+ clips,
53+ "no lane moved"
54+ );
55+ // The rows the panel draws: one per source, each its file's own length
56+ // -- source 1 has no clip anywhere and is still 4 s at 30 fps.
57+ let rows = library_rows(
58+ session.sources(),
59+ &HashMap::new(),
60+ &HashMap::new(),
61+ None,
62+ |path| session.file_frames(path),
63+ );
64+ assert_eq!(rows.len(), 2);
65+ assert_eq!(rows[0].frames, 150, "5 s at 30 fps");
66+ assert_eq!(rows[1].frames, 120, "4 s at 30 fps, never placed");
67+ // The swatch is the clip colour, by the same index and the same
68+ // function -- what makes the panel and the lanes one association.
69+ for row in 0..rows.len() {
70+ assert_eq!(rows[row].tint, row);
71+ assert_eq!(source_tint(row), SOURCE_TINTS()[row % SOURCE_TINTS().len()]);
72+ }
73+}
74+
75+/// The window opened on a song and nothing else -- the launch argument, the
76+/// drop on an empty window and the Import button all end in the same
77+/// `PlaybackSession::open`. The library lists it placeable, the lane door
78+/// the Add button and a drag share puts it on `A1`, and the one format that
79+/// needs a picture says so on its own row instead of failing at the end of
80+/// an export.
81+#[test]
82+fn a_song_opens_the_window_by_itself() {
83+ let mut session =
84+ PlaybackSession::open(asset("test_tone.mp3")).expect("a song is a timeline");
85+ session.set_gain(0.0);
86+ // The source's own path, which is the canonical one a row carries.
87+ let path = session.sources()[0].path.clone();
88+ assert!(session.lane_clips(Lane::V1).is_empty(), "no picture");
89+ assert_eq!(session.lane_clips(Lane::A1).len(), 1);
90+
91+ // The library row: probed like any other source, and not greyed --
92+ // `unusable` is what the panel dims a row with.
93+ let streams = HashMap::from([(
94+ path.clone(),
95+ engine::AudioSession::probe_streams(&path).expect("probe the song"),
96+ )]);
97+ let rate = streams[&path]
98+ .iter()
99+ .find(|s| s.index == session.sources()[0].audio_stream)
100+ .map(|s| (s.sample_rate, s.channels));
101+ let frames = session.file_frames(&path);
102+ let rows = library_rows(session.sources(), &streams, &HashMap::new(), rate, |_| {
103+ frames
104+ });
105+ assert_eq!(rows.len(), 1);
106+ assert_eq!(rows[0].name, "test_tone.mp3");
107+ assert_eq!(rows[0].unusable, None, "the row is placeable");
108+ assert_eq!(rows[0].frames, 90, "3 s at the audio-only 30 fps");
109+
110+ // ...and it places, on the audio lane, through the door `insert_source`
111+ // uses: a second copy of the song at the playhead.
112+ session.seek(1.0);
113+ assert!(
114+ session
115+ .place_stream_at(1.0, &path, 0, Some(Lane::A1))
116+ .expect("its own file is on this timeline")
117+ );
118+ assert_eq!(session.lane_clips(Lane::A1).len(), 2);
119+ assert!(session.lane_clips(Lane::V1).is_empty(), "still no picture");
120+
121+ // Both picture rows carry the reason rather than the format's detail
122+ // line, each naming itself; the audio formats are what this timeline is
123+ // and are never refused.
124+ assert_eq!(
125+ format_refusal(&session, Format::Mp4).as_deref(),
126+ Some("no picture — an mp4 would be black; export WAV, FLAC, MP3 or OGG")
127+ );
128+ assert_eq!(
129+ format_refusal(&session, Format::Av1).as_deref(),
130+ Some("no picture — an AV1 Matroska would be black; export WAV, FLAC, MP3 or OGG")
131+ );
132+ assert_eq!(
133+ format_refusal(&session, Format::Av1Mp4).as_deref(),
134+ Some("no picture — an AV1 mp4 would be black; export WAV, FLAC, MP3 or OGG")
135+ );
136+ assert_eq!(format_refusal(&session, Format::Wav), None);
137+ assert_eq!(format_refusal(&session, Format::Flac), None);
138+ assert_eq!(format_refusal(&session, Format::Mp3), None);
139+}
140+
141+/// A file's every audio track gets a row: the ones the timeline can take
142+/// are placeable, the ones it cannot are listed greyed with the reason.
143+/// Which rows exist at all is the branchy part of the panel, so it is
144+/// planned as data and checked here rather than through the pointer.
145+#[test]
146+fn every_audio_stream_of_a_file_is_a_row_usable_or_not() {
147+ let multi = PathBuf::from("/m/movie.mp4");
148+ let sources = [source("/m/movie.mp4", 0)];
149+ let mut streams = HashMap::new();
150+ streams.insert(
151+ multi.clone(),
152+ vec![
153+ info(0, 44_100, 2, None, true),
154+ info(1, 44_100, 2, Some("fra"), true),
155+ info(2, 22_050, 1, Some("deu"), true),
156+ info(3, 0, 0, None, false),
157+ ],
158+ );
159+ let rows = library_rows(
160+ &sources,
161+ &streams,
162+ &HashMap::new(),
163+ Some((44_100, 2)),
164+ |_| 90,
165+ );
166+ assert_eq!(
167+ rows.iter().map(|r| r.stream).collect::<Vec<_>>(),
168+ [0, 1, 2, 3],
169+ "one row per audio stream, in file order"
170+ );
171+ assert!(
172+ rows.iter().all(|r| r.path == multi && r.tint == 0),
173+ "every stream of one file wears the file's own tint"
174+ );
175+ assert_eq!(rows[0].name, "movie.mp4 [audio 1]");
176+ assert_eq!(rows[1].name, "movie.mp4 [audio 2]");
177+ assert_eq!(rows[1].detail, "fra 44.1 kHz stereo");
178+ // Placeable: the one already on the timeline, and the one that matches
179+ // it. The mono track cannot join a stereo timeline -- one device and one
180+ // copied AAC track for the whole of it -- and the codec we cannot read
181+ // cannot join anything. Both say which. Its 22 kHz is *not* part of that
182+ // any more: a rate of its own is resampled at the decoder's door, and a
183+ // row greyed for one the engine accepts is this picker telling a lie.
184+ assert_eq!((&rows[0].unusable, &rows[1].unusable), (&None, &None));
185+ assert_eq!(rows[2].unusable.as_deref(), Some("the timeline is stereo"));
186+ assert_eq!(
187+ unusable(&info(9, 48_000, 2, None, true), Some((44_100, 2))),
188+ None,
189+ "48 kHz stereo joins a 44.1 kHz stereo timeline"
190+ );
191+ assert_eq!(rows[3].unusable.as_deref(), Some("unsupported codec"));
192+ assert_eq!(
193+ rows[3].detail, "",
194+ "a stream we cannot parse claims nothing"
195+ );
196+ // Every row is the same file, so every row is that file's length.
197+ assert!(rows.iter().all(|r| r.frames == 90));
198+
199+ // The single-stream case is exactly one row and no stream tag: no
200+ // regression for the media everything else in the world is.
201+ let plain = [source("/m/plain.mp4", 0)];
202+ let mut one = HashMap::new();
203+ one.insert(
204+ PathBuf::from("/m/plain.mp4"),
205+ vec![info(0, 44_100, 2, None, true)],
206+ );
207+ let rows = library_rows(&plain, &one, &HashMap::new(), Some((44_100, 2)), |_| 90);
208+ assert_eq!(rows.len(), 1);
209+ assert_eq!(rows[0].name, "plain.mp4");
210+ assert_eq!(
211+ rows[0].detail, "",
212+ "one audio track is the row it has always been: name and length"
213+ );
214+ // ...as is a silent file, and a file not probed yet.
215+ let mut silent = HashMap::new();
216+ silent.insert(PathBuf::from("/m/plain.mp4"), Vec::new());
217+ for probe in [silent, HashMap::new()] {
218+ let rows = library_rows(&plain, &probe, &HashMap::new(), None, |_| 90);
219+ assert_eq!(rows.len(), 1);
220+ assert_eq!(rows[0].name, "plain.mp4");
221+ assert_eq!(rows[0].detail, "");
222+ }
223+
224+ // A second stream *placed* on the timeline is a source entry of its
225+ // own: it keeps its row, no duplicate appears for it, and the rows of
226+ // one file stay together whatever order the entries came in.
227+ let placed = [
228+ source("/m/movie.mp4", 0),
229+ source("/m/other.mp4", 0),
230+ source("/m/movie.mp4", 2),
231+ ];
232+ streams.insert(
233+ PathBuf::from("/m/other.mp4"),
234+ vec![info(0, 44_100, 2, None, true)],
235+ );
236+ let rows = library_rows(
237+ &placed,
238+ &streams,
239+ &HashMap::new(),
240+ Some((44_100, 2)),
241+ |_| 90,
242+ );
243+ assert_eq!(
244+ rows.iter()
245+ .map(|r| (file_name(&r.path), r.stream))
246+ .collect::<Vec<_>>(),
247+ [
248+ ("movie.mp4".to_string(), 0),
249+ ("other.mp4".to_string(), 0),
250+ ("movie.mp4".to_string(), 2),
251+ ("movie.mp4".to_string(), 1),
252+ ("movie.mp4".to_string(), 3),
253+ ]
254+ );
255+ assert!(
256+ rows[2].unusable.is_none(),
257+ "a stream already on the timeline is playing, whatever a probe says"
258+ );
259+ assert_eq!(rows[1].tint, 1, "the other file is the other tint");
260+}
261+
262+/// What the clip menu offers, and where it hangs. The two items that act on
263+/// the playhead rather than on the clicked clip are the ones that can be
264+/// inapplicable, and a menu at the edge of the window has to come back
265+/// inside it or its last item cannot be clicked at all.
266+#[test]
267+fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() {
268+ use keymap::{ActionId, Keymap};
269+ // Frames 30..90 of the timeline, taken from the head of its source.
270+ let clip = Clip {
271+ start: 30,
272+ in_frame: 0,
273+ out_frame: 60,
274+ source: 0,
275+ link: None,
276+ eq: None,
277+ color: None,
278+ fit: FitPolicy::default(),
279+ speed: Speed::NORMAL,
280+ };
281+ assert_eq!(clip.end(), 90);
282+ let a1 = Lane::A1;
283+ let v1 = Lane::V1;
284+ // The question the clip menu asks: a timeline is open and the menu was
285+ // opened on this clip, at this playhead.
286+ let on = |clip: &Clip, lane, action, playhead| {
287+ enable(
288+ action,
289+ Ctx {
290+ clip: Some((*clip, lane)),
291+ playhead,
292+ timeline: true,
293+ ..Ctx::default()
294+ },
295+ )
296+ };
297+ let offered = |clip: &Clip, lane, action, playhead| on(clip, lane, action, playhead).yes();
298+ // Cut splits from inside only: neither edge has anything to split off.
299+ assert!(offered(&clip, v1, ActionId::Cut, 31));
300+ assert!(offered(&clip, v1, ActionId::Cut, 89));
301+ assert!(!offered(&clip, v1, ActionId::Cut, 30));
302+ assert!(!offered(&clip, v1, ActionId::Cut, 90));
303+ assert!(!offered(&clip, v1, ActionId::Cut, 200));
304+ // A slowed clip refuses more than the edges do, and it may not say the
305+ // edges' words while doing it: at a quarter speed each of its sixty
306+ // source frames is on screen four timeline frames, and only the first of
307+ // the four is a frame the file has. The three between are inside the
308+ // clip by any reading of the playhead, so "only from inside a clip"
309+ // there is a refusal claiming something the screen contradicts.
310+ let slow = Clip {
311+ speed: Speed::MIN,
312+ ..clip
313+ };
314+ assert_eq!(slow.frames(), 240, "a quarter speed is four times as long");
315+ assert!(offered(&slow, v1, ActionId::Cut, 34), "34 is a source frame");
316+ assert!(!offered(&slow, v1, ActionId::Cut, 35));
317+ assert_eq!(
318+ on(&slow, v1, ActionId::Cut, 35).why(),
319+ Some("this speed holds one frame here — step to the next"),
320+ );
321+ assert_eq!(
322+ on(&slow, v1, ActionId::Cut, 30).why(),
323+ Some("only from inside a clip"),
324+ "the head is still the edge's refusal, speed or no speed",
325+ );
326+ // Regroup is the other way round: only where this clip meets another.
327+ assert!(offered(&clip, v1, ActionId::Regroup, 30));
328+ assert!(offered(&clip, v1, ActionId::Regroup, 90));
329+ assert!(!offered(&clip, v1, ActionId::Regroup, 60));
330+ // Detach is the clip's own business: nothing to take apart in one that
331+ // names no group, and whether the group still has another half is the
332+ // engine's question. Group is offered on every clip, for that reason.
333+ assert!(!offered(&clip, v1, ActionId::Detach, 0));
334+ let grouped = Clip {
335+ link: Some(3),
336+ ..clip
337+ };
338+ assert!(offered(&grouped, v1, ActionId::Detach, 60));
339+ assert!(offered(&clip, a1, ActionId::Group, 0));
340+ // The equalizer is the one item the *lane* decides: it filters samples,
341+ // and a video clip has none of its own. Never the playhead's business.
342+ assert!(offered(&clip, a1, ActionId::Equalizer, 0));
343+ assert!(offered(&clip, a1, ActionId::Equalizer, 60));
344+ assert!(!offered(&clip, v1, ActionId::Equalizer, 60));
345+ // The rest act on the clip that was clicked, so they always mean
346+ // something -- the engine words its own refusals.
347+ for action in [ActionId::Delete, ActionId::Lift, ActionId::ToggleMute] {
348+ assert!(offered(&clip, v1, action, 0));
349+ assert!(offered(&clip, a1, action, 60));
350+ }
351+ // Except the grade, which is a picture setting: offered on a video
352+ // clip wherever the playhead is, dimmed on a waveform.
353+ assert!(offered(&clip, v1, ActionId::Color, 0));
354+ assert!(!offered(&clip, a1, ActionId::Color, 60));
355+ // The two kinds of no, which is what the row is told apart by: a grade
356+ // on a waveform is a *class* answer -- an audio clip has no picture and
357+ // never will, so the menu leaves the item out entirely -- where a cut at
358+ // the clip's edge is this moment's answer and the next click of the
359+ // playhead changes it, so that one is drawn, dimmed, and says why.
360+ //
361+ // What the menu draws for a clip of each kind, in order: the render
362+ // loop's `continue`, as a list.
363+ let menu = |lane, image, playhead| {
364+ MENU_ITEMS
365+ .into_iter()
366+ .filter(|&action| {
367+ enable(
368+ action,
369+ Ctx {
370+ clip: Some((clip, lane)),
371+ image,
372+ playhead,
373+ timeline: true,
374+ ..Ctx::default()
375+ },
376+ )
377+ .listed()
378+ })
379+ .collect::<Vec<_>>()
380+ };
381+ // Sound: no grade and no fit policy, and the equalizer that is the
382+ // whole reason an audio clip has a menu of its own.
383+ let sound = menu(a1, false, 60);
384+ assert!(!sound.contains(&ActionId::Color), "{sound:?}");
385+ assert!(!sound.contains(&ActionId::Fit), "{sound:?}");
386+ assert!(sound.contains(&ActionId::Equalizer));
387+ assert!(sound.contains(&ActionId::Silence));
388+ // Picture: the mirror of it. The sound of a take is the audio lane's,
389+ // clip for clip, so the equalizer is not this clip's business -- but the
390+ // silence scan is, because it opens on the half it is grouped with.
391+ let picture = menu(v1, false, 60);
392+ assert!(!picture.contains(&ActionId::Equalizer), "{picture:?}");
393+ assert!(picture.contains(&ActionId::Color));
394+ assert!(picture.contains(&ActionId::Fit));
395+ assert!(picture.contains(&ActionId::Silence));
396+ // A still: picture with no sound anywhere, ever. Graded, fitted and
397+ // re-timed like any other clip (a speed reaches a still through the same
398+ // rewrite), scanned like none.
399+ let still = menu(v1, true, 60);
400+ assert!(!still.contains(&ActionId::Silence), "{still:?}");
401+ assert!(!still.contains(&ActionId::Equalizer), "{still:?}");
402+ assert!(still.contains(&ActionId::Color));
403+ assert!(still.contains(&ActionId::Fit));
404+ assert!(still.contains(&ActionId::Speed));
405+ // ...and the state refusals are on all three, dimmed rather than gone:
406+ // at 30 the playhead is on this clip's head, where a cut has nothing to
407+ // split off -- a row the next click of the playhead lights.
408+ for rows in [menu(a1, false, 30), menu(v1, false, 30), menu(v1, true, 30)] {
409+ assert!(rows.contains(&ActionId::Cut), "{rows:?}");
410+ assert!(rows.contains(&ActionId::Detach), "{rows:?}");
411+ }
412+ // The actions card is the other half of the rule: it lists the whole
413+ // registry, so a class refusal is dimmed there with its reason and never
414+ // dropped -- an action missing from the one surface that lists
415+ // everything would read as an action that does not exist.
416+ let listed: Vec<ActionId> = keys_rows()
417+ .into_iter()
418+ .filter_map(|r| match r {
419+ KeyRow::Act(action) => Some(action),
420+ _ => None,
421+ })
422+ .collect();
423+ for (lane, action) in [
424+ (a1, ActionId::Color),
425+ (a1, ActionId::Fit),
426+ (v1, ActionId::Equalizer),
427+ ] {
428+ assert!(matches!(on(&clip, lane, action, 60), Enable::Hidden(_)));
429+ assert!(listed.contains(&action), "{action:?} left the actions card");
430+ assert!(on(&clip, lane, action, 60).why().is_some());
431+ }
432+ assert!(matches!(on(&clip, v1, ActionId::Cut, 30), Enable::No(_)));
433+ assert!(matches!(on(&clip, v1, ActionId::Regroup, 60), Enable::No(_)));
434+ assert!(matches!(on(&clip, v1, ActionId::Detach, 0), Enable::No(_)));
435+ // Every refusal says something, and says it short enough to sit in the
436+ // menu's right-hand column beside a label -- the still's included, which
437+ // the card dims with while the menu leaves the row out.
438+ for action in MENU_ITEMS {
439+ for (lane, image) in [(v1, false), (a1, false), (v1, true)] {
440+ for playhead in [0, 30, 60, 90] {
441+ let refusal = enable(
442+ action,
443+ Ctx {
444+ clip: Some((clip, lane)),
445+ image,
446+ playhead,
447+ timeline: true,
448+ ..Ctx::default()
449+ },
450+ );
451+ if let Some(why) = refusal.why() {
452+ assert!(!why.is_empty() && why.len() <= 30, "{action:?}: {why:?}");
453+ }
454+ }
455+ }
456+ }
457+ assert!(matches!(
458+ enable(
459+ ActionId::Silence,
460+ Ctx {
461+ clip: Some((clip, v1)),
462+ image: true,
463+ playhead: 60,
464+ timeline: true,
465+ ..Ctx::default()
466+ }
467+ ),
468+ Enable::Hidden(_)
469+ ));
470+ // The editor as a whole, which is how the actions card asks: with no
471+ // timeline nothing is offered, an export leaves only its own cancel,
472+ // and the three that act on the marked clip say so when none is.
473+ let whole = |action, ctx| enable(action, ctx);
474+ assert_eq!(
475+ whole(ActionId::Play, Ctx::default()),
476+ Enable::No("no timeline open")
477+ );
478+ let live = Ctx {
479+ timeline: true,
480+ playable: true,
481+ ..Ctx::default()
482+ };
483+ assert!(whole(ActionId::Play, live).yes());
484+ // ...and an open timeline with nothing on its lanes refuses the
485+ // transport in the oracle rather than in the button, which is what
486+ // makes the key and the button say the same thing.
487+ assert_eq!(
488+ whole(
489+ ActionId::Play,
490+ Ctx {
491+ playable: false,
492+ ..live
493+ }
494+ ),
495+ Enable::No("put a clip on a lane first")
496+ );
497+ // The magnet and the monitoring level are the editor's own and answer
498+ // with no timeline at all -- the keyboard always fired them there, and
499+ // now so does the toolbar.
500+ for editor_wide in [
501+ ActionId::ToggleSnap,
502+ ActionId::ToggleMute,
503+ ActionId::VolumeUp,
504+ ActionId::VolumeDown,
505+ ] {
506+ assert!(
507+ whole(editor_wide, Ctx::default()).yes(),
508+ "{editor_wide:?} is dead with no file open while its key still fires"
509+ );
510+ }
511+ assert!(!whole(ActionId::Delete, live).yes());
512+ assert!(!whole(ActionId::Paste, live).yes());
513+ assert!(
514+ whole(
515+ ActionId::Paste,
516+ Ctx {
517+ clipboard: true,
518+ ..live
519+ }
520+ )
521+ .yes()
522+ );
523+ assert!(!whole(ActionId::CancelExport, live).yes());
524+ let busy = Ctx {
525+ exporting: true,
526+ ..live
527+ };
528+ assert!(whole(ActionId::CancelExport, busy).yes());
529+ for action in ActionId::ALL {
530+ // Nothing may touch the edit list while an export is reading it --
531+ // and the palette does not: it repaints this window and writes one
532+ // word to the user's own config file, which is why it is the one
533+ // action besides the cancel that stays live here.
534+ let allowed = action == ActionId::CancelExport || action == ActionId::Theme;
535+ assert_eq!(
536+ whole(action, busy).yes(),
537+ allowed,
538+ "{action:?} while an export reads the edit list"
539+ );
540+ }
541+ // The playhead frame is the engine's own rule, boundary included.
542+ assert_eq!(frame_at(1.0, 30.), 30);
543+ assert_eq!(frame_at(0.0, 30.), 0);
544+ assert_eq!(frame_at(-1.0, 30.), 0);
545+ // Where it hangs: at the pointer when it fits, back inside when not.
546+ let viewport = size(px(800.), px(400.));
547+ assert_eq!(menu_at(point(px(10.), px(10.)), viewport, 150.), (10., 10.));
548+ assert_eq!(
549+ menu_at(point(px(700.), px(380.)), viewport, 150.),
550+ (800. - MENU_W, 250.)
551+ );
552+ // A window smaller than the menu loses its bottom, never its top.
553+ assert_eq!(
554+ menu_at(point(px(90.), px(40.)), size(px(100.), px(50.)), 150.),
555+ (0., 0.)
556+ );
557+ // Every item is an action the registry knows, so the menu and the keys
558+ // menu say the same thing about it -- and none of them is unreachable
559+ // by keyboard, which is what makes the hint column worth drawing.
560+ let keymap = Keymap::defaults();
561+ for action in MENU_ITEMS {
562+ assert!(ActionId::ALL.contains(&action), "{action:?} is not listed");
563+ assert_ne!(keymap.display(action), "unbound", "{action:?}");
564+ }
565+ // ...and the whole card still fits the 640x360 floor, however many items
566+ // it grows to: the list is what scrolls where the window is too short
567+ // for it, never the card that grows.
568+ let items = MENU_ITEMS.len() + 1; // Properties
569+ let floor = size(px(640.), px(360.));
570+ assert!(MENU_PAD * 2. + menu_rows_h(items, floor) <= 360., "too tall");
571+ assert!(
572+ menu_rows_h(items, floor) / MENU_ROW_H >= 12.,
573+ "too few items visible to scan on the smallest window"
574+ );
575+ assert_eq!(
576+ menu_at(point(px(0.), px(0.)), floor, {
577+ MENU_PAD * 2. + menu_rows_h(items, floor)
578+ }),
579+ (0., 0.)
580+ );
581+ // The picker is the same card and the longest list in it is the palette
582+ // family list, which grows every time somebody asks for more colours.
583+ // Twelve of them still stand on screen *whole* at the floor -- so the
584+ // list's `overflow_y_scroll` is a safety net rather than something a
585+ // person has to find. The day a family makes this fail is the day the
586+ // card owes the affordance line the inspector and the cards carry
587+ // ("more below — scroll the …"): a row nobody knows is under the fold
588+ // is a row that is not there, and no scroll bar says it.
589+ let families = crate::ui::theme::PaletteId::ALL.len();
590+ assert_eq!(
591+ menu_rows_h(families, floor),
592+ families as f32 * MENU_ROW_H,
593+ "{families} palettes no longer fit 640x360 -- the picker now needs \
594+ the 'more below' line and a keyboard cursor that scrolls into view"
595+ );
596+ // ...and the detail beside each one is short enough to survive the
597+ // right-hand column at that width instead of being truncated mid-word.
598+ for id in crate::ui::theme::PaletteId::ALL {
599+ assert!(id.detail().len() <= 30, "{id:?}: {:?}", id.detail());
600+ }
601+}
602+
603+/// Both menus, at the two things they can be opened on, and the box each
604+/// one is drawn in. Two rules, and the render obeys them by *calling* what
605+/// this calls -- [`menu_items`] and [`row_items`] are the only lists either
606+/// menu is built from, and [`menu_rows_h`] is the height each is both placed
607+/// by and drawn to:
608+///
609+/// 1. a row exists only where the oracle lists the action for the very thing
610+/// that was right-clicked, so an item can never offer a video action on a
611+/// waveform (the complaint this comes from) and a new action added to
612+/// `MENU_ITEMS` cannot appear where it does not apply;
613+/// 2. the whole card is inside the window, wherever it was opened and
614+/// however long the list -- a menu drawn past the bottom edge is a menu
615+/// whose last items nobody can click.
616+#[test]
617+fn a_menu_offers_only_what_applies_and_is_drawn_inside_the_window() {
618+ use keymap::ActionId;
619+ let clip = Clip {
620+ start: 30,
621+ in_frame: 0,
622+ out_frame: 60,
623+ source: 0,
624+ link: Some(1),
625+ eq: None,
626+ color: None,
627+ fit: FitPolicy::default(),
628+ speed: Speed::NORMAL,
629+ };
630+ let ctx = |lane, image| Ctx {
631+ clip: Some((clip, lane)),
632+ image,
633+ playhead: 60,
634+ timeline: true,
635+ ..Ctx::default()
636+ };
637+ // The oracle is the whole of what the menu draws: every item it lists is
638+ // one the oracle would list, and every item it leaves out is one the
639+ // oracle hides -- there is no third answer, and no hand-written list.
640+ for (lane, image) in [(Lane::V1, false), (Lane::A1, false), (Lane::V1, true)] {
641+ let ctx = ctx(lane, image);
642+ let rows = menu_items(ctx);
643+ for action in MENU_ITEMS {
644+ assert_eq!(
645+ rows.contains(&action),
646+ enable(action, ctx).listed(),
647+ "{action:?} on {lane:?}, image={image}"
648+ );
649+ }
650+ }
651+ // Sound has no picture settings; picture has no equalizer of its own; a
652+ // still has no sound to scan. The user's own words: an audio clip must
653+ // not be offered what only a picture can be given.
654+ let sound = menu_items(ctx(Lane::A1, false));
655+ assert!(!sound.contains(&ActionId::Color), "{sound:?}");
656+ assert!(!sound.contains(&ActionId::Fit), "{sound:?}");
657+ assert!(sound.contains(&ActionId::Equalizer));
658+ let picture = menu_items(ctx(Lane::V1, false));
659+ assert!(!picture.contains(&ActionId::Equalizer), "{picture:?}");
660+ assert!(picture.contains(&ActionId::Color));
661+ assert!(!menu_items(ctx(Lane::V1, true)).contains(&ActionId::Silence));
662+ // The library menu is the same rule on the other panel: its items come
663+ // off `row_items` and nothing else, and the two that change the timeline
664+ // say why rather than being clicked and refused afterwards.
665+ let live = RowCtx {
666+ timeline: true,
667+ usable: true,
668+ ..RowCtx::default()
669+ };
670+ for ctx in [
671+ live,
672+ RowCtx {
673+ usable: false,
674+ ..live
675+ },
676+ RowCtx { placed: 2, ..live },
677+ RowCtx {
678+ exporting: true,
679+ ..live
680+ },
681+ RowCtx::default(),
682+ ] {
683+ let rows = row_items(ctx);
684+ for item in ROW_ITEMS {
685+ assert_eq!(rows.contains(&item), row_enable(item, ctx).listed());
686+ }
687+ // Whatever the state, the two that need neither timeline nor edit
688+ // list are offered: a file is always describable and findable.
689+ assert!(row_enable(RowItem::Reveal, ctx).yes());
690+ assert!(row_enable(RowItem::Properties, ctx).yes());
691+ }
692+ assert!(row_enable(RowItem::Add, live).yes());
693+ assert!(
694+ !row_enable(
695+ RowItem::Add,
696+ RowCtx {
697+ usable: false,
698+ ..live
699+ }
700+ )
701+ .yes(),
702+ "a file that cannot join this timeline is not an Add anybody can ask for"
703+ );
704+ assert!(!row_enable(RowItem::Remove, RowCtx { placed: 1, ..live }).yes());
705+ assert!(!row_enable(RowItem::Add, RowCtx::default()).yes());
706+ // Every refusal is short enough to sit in the hint column beside its
707+ // label, the clip menu's rule.
708+ for item in ROW_ITEMS {
709+ for ctx in [live, RowCtx::default()] {
710+ if let Some(why) = row_enable(item, ctx).why() {
711+ assert!(!why.is_empty() && why.len() <= 30, "{why:?}");
712+ }
713+ }
714+ }
715+ // ...and the box. Every window from the floor up, every corner of it,
716+ // and every list length either menu can have: the card is placed by
717+ // `MENU_PAD * 2 + menu_rows_h` and drawn to it, so this is the card.
718+ for viewport in [
719+ size(px(640.), px(360.)),
720+ size(px(800.), px(600.)),
721+ size(px(1280.), px(690.)),
722+ // Smaller than the floor the layout is sized for: it still may not
723+ // draw outside the window it has.
724+ size(px(320.), px(200.)),
725+ ] {
726+ for rows in 1..=MENU_ITEMS.len() + 1 {
727+ let h = MENU_PAD * 2. + menu_rows_h(rows, viewport);
728+ for at in [
729+ point(px(0.), px(0.)),
730+ point(px(10.), px(10.)),
731+ // The click that started all this: low in the window, where
732+ // the menu used to hang off the bottom edge.
733+ point(px(0.), viewport.height - px(4.)),
734+ point(viewport.width - px(4.), viewport.height - px(4.)),
735+ point(viewport.width * 2., viewport.height * 2.),
736+ ] {
737+ let (x, y) = menu_at(at, viewport, h);
738+ assert!(x >= 0. && y >= 0., "{x},{y} outside {viewport:?}");
739+ assert!(
740+ x + MENU_W <= f32::from(viewport.width) + 0.01,
741+ "{rows} rows at {at:?} hang off the right of {viewport:?}"
742+ );
743+ assert!(
744+ y + h <= f32::from(viewport.height) + 0.01,
745+ "{rows} rows at {at:?} hang off the bottom of {viewport:?}"
746+ );
747+ }
748+ }
749+ }
750+ // On any window with the room, the whole list is drawn rather than
751+ // twelve rows of it and a scroll nobody is told about.
752+ let items = MENU_ITEMS.len() + 1;
753+ let real = size(px(1280.), px(690.));
754+ assert_eq!(menu_rows_h(items, real), items as f32 * MENU_ROW_H);
755+ assert!(menu_rows_h(items, size(px(640.), px(360.))) < items as f32 * MENU_ROW_H);
756+}
757+
758+/// The other half of the keys menu's guarantee, and the audit this batch was
759+/// asked for kept as a test: no action may be a stroke and nothing else.
760+/// The actions card answers it for all of them at once -- its rows come off
761+/// [`ActionId::ALL`], so a fortieth action is on it the moment it exists and
762+/// there is no hand-written list here to fall behind.
763+#[test]
764+fn every_action_is_reachable_without_the_keyboard() {
765+ use keymap::ActionId;
766+ let source = ui_source();
767+ let source = source.as_str();
768+ let element = |id: &str| source.contains(&format!("\"{id}\""));
769+ let listed: Vec<ActionId> = keys_rows()
770+ .iter()
771+ .filter_map(|r| match r {
772+ KeyRow::Act(a) => Some(*a),
773+ _ => None,
774+ })
775+ .collect();
776+ for action in ActionId::ALL {
777+ assert_eq!(
778+ listed.iter().filter(|a| **a == action).count(),
779+ 1,
780+ "{action:?} is reachable by keyboard only"
781+ );
782+ }
783+ // The snap has a door of its own as well as its row on the card: the
784+ // button beside the zoom, which says which way it is set as well as
785+ // setting it.
786+ assert!(element("snap"), "no snap button beside the zoom");
787+ // And the card is a door the pointer can open: the panel's own button.
788+ assert!(element("keys"), "no way to open the actions card");
789+ // The card-local strokes have the same rule, and each of them is a thing
790+ // on its card: the graph and its two buttons, the colour bars and their
791+ // reset, the speed bar and its presets, and the silence card's rows --
792+ // whose steppers are the pointer's only way to a threshold.
793+ for id in [
794+ "eq-graph",
795+ "eq-reset",
796+ "eq-spectrum",
797+ "color-bar",
798+ "color-reset",
799+ "speed-bar",
800+ "speed-preset",
801+ "silence-row",
802+ "silence-step",
803+ "mix-row",
804+ "mix-step",
805+ "silence-apply",
806+ "export-confirm",
807+ ] {
808+ assert!(element(id), "{id} is not on any card");
809+ }
810+ // ...and each one is named by the row that carries its stroke, so a
811+ // card-local key added to `FIXED` with nothing to click fails here
812+ // instead of being noticed by whoever tries to use the card without a
813+ // keyboard. `KeyRow::Fixed` is "shown and never offered", which used to
814+ // mean the twenty-eight rows below were the one part of this editor no
815+ // reachability test read.
816+ for fixed in keymap::FIXED.iter() {
817+ match fixed.reach {
818+ keymap::Reach::Click(id) => assert!(
819+ element(id),
820+ "{:?} ({}) points at {id}, which is on no card",
821+ fixed.chord,
822+ fixed.label
823+ ),
824+ // Nothing to click by decision, not by omission: getting out of
825+ // a card, and the hold that repeats what a drag already does.
826+ keymap::Reach::Gesture => {}
827+ }
828+ }
829+}
830+
831+/// The other half of "getting out of a card is a `Reach::Gesture`": the
832+/// gesture has to exist. Every card's scrim closes it on a press, so a hand
833+/// that never touches the keyboard can shut every one of them -- for seven
834+/// cards `esc` was the only exit, which is the same complaint as an action
835+/// reachable by stroke alone, said about the way out instead of the way in.
836+///
837+/// Read off [`Player::modal`] rather than off a list written here: a card
838+/// counted there and not closed by [`Player::close_card`] fails this test
839+/// the day it is added, which is the only way the two stay in step.
840+#[test]
841+fn every_card_closes_without_the_keyboard() {
842+ let source = ui_source();
843+ let source = source.as_str();
844+ // A fn's source, up to the next one: enough of a body to scan.
845+ let body = |name: &str| -> &str {
846+ let at = source
847+ .find(&format!("fn {name}("))
848+ .unwrap_or_else(|| panic!("no fn {name} in main.rs"));
849+ let rest = &source[at..];
850+ &rest[..rest[1..].find("\n fn ").map_or(rest.len(), |e| e + 1)]
851+ };
852+ for card in [
853+ "keys_overlay",
854+ "export_card",
855+ "eq_card",
856+ "color_card",
857+ "speed_card",
858+ "mix_card",
859+ "silence_card",
860+ ] {
861+ let src = body(card);
862+ assert!(
863+ src.contains("this.close_card()"),
864+ "{card}'s scrim swallows the press without closing the card: \
865+ escape is the only way out of it"
866+ );
867+ assert!(
868+ src.contains("MouseButton::Left, swallow"),
869+ "{card}'s body does not swallow its own presses, so a press on \
870+ one of its controls would close the card under itself"
871+ );
872+ }
873+ // ...and every state that makes the window modal is a state that press
874+ // clears. `exporting()` is not one of them: a running export is a job
875+ // with a cancel button, not a card with a scrim.
876+ let close = body("close_card");
877+ for field in body("modal").split("self.").skip(1).filter_map(|rest| {
878+ let name: String = rest
879+ .chars()
880+ .take_while(|c| c.is_alphanumeric() || *c == '_')
881+ .collect();
882+ (!rest[name.len()..].starts_with('(')).then_some(name)
883+ }) {
884+ assert!(
885+ close.contains(&format!("self.{field}")),
886+ "{field} makes the window modal and `close_card` leaves it set: \
887+ that card cannot be closed by pointer"
888+ );
889+ }
890+}
891+
892+/// A clip too short to hit is still a clip: at a far zoom-out its box is
893+/// drawn [`HIT_MIN`] wide rather than the fraction of a pixel it is worth,
894+/// because a box nobody can put a pointer on cannot be selected, dragged,
895+/// trimmed or given a menu -- and an invisible unselectable take is strictly
896+/// worse than one drawn a few pixels too wide.
897+#[test]
898+fn a_clip_box_is_never_narrower_than_its_target() {
899+ // Two seconds on a bed showing an hour: a fifth of a pixel.
900+ let far = Scale {
901+ pps: 0.1,
902+ start: 0.,
903+ };
904+ assert!(far.width_px(2.) < 1., "the fixture is not zoomed out enough");
905+ assert_eq!(clip_width(far.width_px(2.)), HIT_MIN);
906+ // Zero is the floor's own case: a clip trimmed to nothing, and the
907+ // width a lane draws before its first frame is measured.
908+ assert_eq!(clip_width(0.), HIT_MIN);
909+ // What is already wide enough keeps its own width, to the pixel: the
910+ // floor is a floor and never a resize.
911+ let near = Scale::default();
912+ assert_eq!(clip_width(near.width_px(5.)), near.width_px(5.));
913+ // ...and the padding is not trimmable: the strips are asked of the
914+ // clip's own width, so a box drawn wider than its length keeps all of
915+ // that box as a body to select and drag by ([`trims`]).
916+ assert!(!trims(far.width_px(2.)));
917+ assert!(clip_width(far.width_px(2.)) >= HIT_MIN);
918+}
919+
920+/// What the Detach and Group items do to a real timeline: a music video's
921+/// sound comes off its picture, Delete on the loose half takes that half
922+/// only, undo puts both back, and Group makes the two one take again --
923+/// whole-take delete and all.
924+#[test]
925+fn a_detached_half_is_removed_alone_and_groups_again() {
926+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
927+ session.set_gain(0.0);
928+ assert!(whole_take(&session, Lane::V1, 0), "one take to start with");
929+ assert!(whole_take(&session, Lane::A1, 0));
930+ let frames = session.lane_clips(Lane::V1)[0].len();
931+
932+ // Detach audio: neither half is a whole take any more, so Delete on
933+ // either leaves the other exactly where it is.
934+ assert!(session.ungroup(Lane::V1, 0));
935+ assert!(
936+ !whole_take(&session, Lane::A1, 0),
937+ "the sound is a half now"
938+ );
939+ assert!(!whole_take(&session, Lane::V1, 0), "and so is the picture");
940+ assert!(session.lift_clip(Lane::A1, 0));
941+ assert!(session.lane_clips(Lane::A1).is_empty(), "the sound went");
942+ assert_eq!(session.lane_clips(Lane::V1).len(), 1, "the picture stayed");
943+ assert_eq!(session.lane_clips(Lane::V1)[0].len(), frames, "untrimmed");
944+
945+ // One undo per edit, the removal then the detach.
946+ assert!(session.undo());
947+ assert_eq!(session.lane_clips(Lane::A1).len(), 1, "the sound is back");
948+ assert!(session.undo());
949+ assert!(whole_take(&session, Lane::A1, 0), "one take again");
950+
951+ // Group: the partner is the clip covering these very frames on the
952+ // other track, which is what the item hands the engine.
953+ assert!(session.ungroup(Lane::V1, 0));
954+ assert_eq!(span_partner(&session, Lane::V1, 0), Some((Lane::A1, 0)));
955+ session
956+ .group(Lane::V1, 0, Lane::A1, 0)
957+ .expect("both halves still cover the same frames");
958+ assert!(
959+ whole_take(&session, Lane::A1, 0),
960+ "a take that ripples again"
961+ );
962+ assert_eq!(
963+ span_partner(&session, Lane::V1, 0),
964+ None,
965+ "and nothing left on another track to group with"
966+ );
967+}
968+
969+/// Which clip Group reaches when more than one covers the span: the sound,
970+/// whatever order the lanes are stored in. A project file may hold them in
971+/// any order -- a video layer *before* the audio lane among them -- and
972+/// "group this" means the other half of the take, never the layer above it.
973+#[test]
974+fn group_reaches_the_sound_before_a_video_layer_over_it() {
975+ use engine::project::LaneKind;
976+
977+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
978+ session.set_gain(0.0);
979+ let v2 = session.add_lane(LaneKind::Video);
980+ // A bare layer, through the one-lane door: a *drop* on V2 brings the
981+ // file's sound down with it and would put a third clip over this span.
982+ let whole = session.lane_clips(Lane::V1)[0];
983+ assert!(
984+ session.place_at(v2, 0.0, whole),
985+ "a layer covering the same frames as the take"
986+ );
987+
988+ // Saved and loaded back with the lanes in the order a hand-written
989+ // project may hold them: the sound last, behind the layer.
990+ let dir = engine::scratch::Scratch::dir("ve_group");
991+ let file = dir.join("lanes.edith");
992+ session.save_project(&file).expect("save the project");
993+ let text = std::fs::read_to_string(&file).expect("read it back");
994+ let (sound, rest): (Vec<&str>, Vec<&str>) =
995+ text.lines().partition(|l| l.starts_with("audio "));
996+ std::fs::write(
997+ &file,
998+ format!("{}\n{}\n", rest.join("\n"), sound.join("\n")),
999+ )
1000+ .expect("write the reordered project");
1001+ let mut session = PlaybackSession::open_project(&file).expect("it loads as it stands");
1002+ std::fs::remove_dir_all(&dir).ok();
1003+ assert_eq!(
1004+ session.lanes(),
1005+ vec![Lane::V1, v2, Lane::A1],
1006+ "the sound is the last lane there"
1007+ );
1008+
1009+ // Detached, so Group has a choice to get wrong: the layer covers these
1010+ // frames too, and it is the lane the walk meets first.
1011+ assert!(session.ungroup(Lane::V1, 0));
1012+ // Group on the picture reaches the sound, not that layer.
1013+ assert_eq!(span_partner(&session, Lane::V1, 0), Some((Lane::A1, 0)));
1014+ session
1015+ .group(Lane::V1, 0, Lane::A1, 0)
1016+ .expect("the two halves cover the same frames");
1017+ // ...and a lane of its own kind is still groupable, once the sound is
1018+ // spoken for: two video lanes may be one take.
1019+ assert_eq!(
1020+ span_partner(&session, Lane::V1, 0),
1021+ Some((v2, 0)),
1022+ "the layer is what is left to group with"
1023+ );
1024+}
1025+
1026+/// The refusal path, end to end against the real files: an incompatible
1027+/// import changes nothing, and the library mirrors `sources()` 1:1, so a
1028+/// refused file cannot leave a row behind.
1029+#[test]
1030+fn a_refused_import_leaves_no_row_and_an_accepted_one_is_whole() {
1031+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1032+ // Silent like the engine suite: this opens the real device.
1033+ session.set_gain(0.0);
1034+ assert_eq!(session.sources().len(), 1);
1035+ // 640x360 joins now (the project canvas places it), and so does a file
1036+ // with no sound (it plays silence over its span). What is left is one
1037+ // output device: a mono track cannot join a stereo timeline.
1038+ let refusal = session
1039+ .import(&asset("test_ac3.mp4"))
1040+ .expect_err("a mono track must not join a stereo timeline")
1041+ .to_string();
1042+ assert!(refusal.contains("audio"), "refusal must name it: {refusal}");
1043+ assert_eq!(session.sources().len(), 1, "a refusal added a row");
1044+ // An accepted one does add a row, and it reads as the whole file: 4 s
1045+ // at 30 fps, its own length and not one taken off the lanes.
1046+ session.import(&asset("test_av2.mp4")).expect("av2 matches");
1047+ assert_eq!(session.sources().len(), 2);
1048+ let second = session.sources()[1].path.clone();
1049+ assert_eq!(session.file_frames(&second), 120);
1050+ assert_eq!(timecode(120. / 30., 30.), "00:00:04:00");
1051+}
1052+
1053+/// What the Add button and a dropped row both do, minus the pointer: the
1054+/// clip [`Player::insert_source`] builds, put in where the playhead is. One
1055+/// call, so what a drop does cannot drift from what the button does.
1056+#[test]
1057+fn adding_a_row_drops_the_whole_source_in_at_the_playhead() {
1058+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1059+ session.set_gain(0.0);
1060+ session.import(&asset("test_av2.mp4")).expect("av2 matches");
1061+ // In the library only: the 5 s the fixture is, still.
1062+ assert_eq!(session.timeline_duration(), 5.0);
1063+ // Two seconds in, which is inside the first take: the insert splits it.
1064+ session.seek(2.0);
1065+ let second = session.sources()[1].path.clone();
1066+ let frames = session.file_frames(&second);
1067+ // Through the engine door `insert_source` uses, with the row's own
1068+ // stream: the button, the drop and this are one call.
1069+ assert!(
1070+ session
1071+ .place_stream_at(2.0, &second, 0, None)
1072+ .expect("av2 is already on the timeline")
1073+ );
1074+ // The whole of source 1 went in and nothing was painted over: the
1075+ // timeline is longer by exactly that file.
1076+ assert_eq!(session.timeline_duration(), 9.0);
1077+ let (video, audio) = (session.lane_clips(Lane::V1), session.lane_clips(Lane::A1));
1078+ // One take, not a video clip with no sound under it: both lanes hold
1079+ // the same clip at the same place, in the same group.
1080+ let at = |lane: &[Clip]| {
1081+ *lane
1082+ .iter()
1083+ .find(|c| c.start == 60)
1084+ .expect("inserted at 2 s")
1085+ };
1086+ assert_eq!(at(video), at(audio));
1087+ assert_eq!(at(video).source, 1);
1088+ assert_eq!(at(video).len(), frames);
1089+ assert!(at(video).link.is_some());
1090+ assert_eq!(video.len(), audio.len());
1091+
1092+ // The same door with a *second audio stream* of a file already there:
1093+ // a new source entry, the same picture, and the row that was dragged
1094+ // is what plays. This is the whole user-facing point of the slice.
1095+ let mut session =
1096+ PlaybackSession::open(asset("test_multilang.mp4")).expect("open the fixture");
1097+ session.set_gain(0.0);
1098+ let path = session.sources()[0].path.clone();
1099+ let frames = session.file_frames(&path);
1100+ let end = session.timeline_duration();
1101+ assert!(
1102+ session
1103+ .place_stream_at(end, &path, 1, None)
1104+ .expect("the French track shares the timeline's parameters")
1105+ );
1106+ assert_eq!(session.sources()[1].audio_stream, 1);
1107+ assert_eq!(session.timeline_duration(), end * 2.0);
1108+ // Both rows are the same file, so both rows are that file's length --
1109+ // the second one before any clip of its own existed.
1110+ assert_eq!(session.file_frames(&path), frames);
1111+}
1112+
1113+/// The drop a hand actually makes: a library row let go on the *empty* bed
1114+/// past the last clip, which is most of the bed on any timeline shorter
1115+/// than the window. The whole chain the release runs, minus gpui's own
1116+/// pointer read -- [`Player::place_frame`]'s [`landing`], the frame back
1117+/// through the rate as [`Player::insert_source`] hands it over, and the one
1118+/// engine door a row goes through -- and the head lands on the frame the
1119+/// ghost was drawn on, black in front of it. It used to be swallowed by the
1120+/// clipboard's clamp inside `Project::paste` and appended after the last
1121+/// clip wherever it was let go, which is the bug this pins.
1122+#[test]
1123+fn a_row_dropped_on_the_open_bed_lands_under_the_pointer() {
1124+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1125+ session.set_gain(0.0);
1126+ session.import(&asset("test_av2.mp4")).expect("av2 matches");
1127+ let second = session.sources()[1].path.clone();
1128+ let fps = session.meta().frame_rate;
1129+ assert_eq!(session.timeline_duration(), 5.0);
1130+ // 5 s of timeline on a bed 30 s wide: the open bed past the last clip
1131+ // is five sixths of it.
1132+ let bed: Bounds<Pixels> = Bounds {
1133+ origin: point(px(12.), px(400.)),
1134+ size: size(px(600.), px(LANE_H)),
1135+ };
1136+ let scale = Scale {
1137+ pps: 20.,
1138+ start: 0.,
1139+ };
1140+
1141+ // What `Player::place_frame` answers for a pointer 200 px along the
1142+ // bed: ten seconds in, five seconds past the end of the timeline, and
1143+ // no mark anywhere near enough to pull it back.
1144+ let clips = [session.lane_clips(Lane::V1), session.lane_clips(Lane::A1)];
1145+ let marks = snap_marks(&clips, None, frame_at(session.now(), fps));
1146+ let under = frame_at(scale.time_at(px_along(px(212.), bed)), fps);
1147+ let (at, cue) = landing(under, 0, 0, true, scale.snap_frames(fps), &marks);
1148+ assert_eq!((at, cue), (300, None), "the pointer is on frame 300");
1149+
1150+ // ...and what the release does with it: the frame back through the same
1151+ // rate every box is drawn at, into the door the Add button uses too.
1152+ assert!(
1153+ session
1154+ .place_stream_at(f64::from(at) / fps, &second, 0, None)
1155+ .expect("av2 is already on this timeline")
1156+ );
1157+ let head = |lane| {
1158+ session
1159+ .lane_clips(lane)
1160+ .last()
1161+ .copied()
1162+ .expect("the dropped clip")
1163+ };
1164+ assert_eq!(
1165+ head(Lane::V1).start,
1166+ at,
1167+ "the drop landed somewhere other than under the pointer"
1168+ );
1169+ assert_eq!(head(Lane::A1).start, at, "...and its sound with it");
1170+ assert!(head(Lane::V1).link.is_some(), "one grouped take");
1171+ assert_eq!(head(Lane::V1).link, head(Lane::A1).link);
1172+ // The bed in front of it stays black: nothing was stretched to reach
1173+ // it, and the 4 s file is the whole of what was added.
1174+ assert_eq!(session.timeline_duration(), 14.0);
1175+}
1176+
1177+/// Remove from library, through the door the menu item uses
1178+/// ([`Player::remove_source`] calls exactly this): refused by name while
1179+/// clips play from the file, and once they do not the row leaves the list.
1180+#[test]
1181+fn removing_a_row_is_refused_while_it_plays_and_takes_the_row_away() {
1182+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1183+ session.set_gain(0.0);
1184+ // Imported, then dragged onto the end: an import alone fills the
1185+ // library, and a row with no clip is removable without any refusal to
1186+ // test. This one has to have a take on the timeline.
1187+ session.import(&asset("test_av2.mp4")).expect("av2 matches");
1188+ let second = session.sources()[1].path.clone();
1189+ let end = session.timeline_duration();
1190+ assert!(
1191+ session
1192+ .place_stream_at(end, &second, 0, None)
1193+ .expect("a file just imported is on this timeline")
1194+ );
1195+ let streams = HashMap::new();
1196+ let rows = |session: &PlaybackSession| {
1197+ library_rows(session.sources(), &streams, &HashMap::new(), None, |_| 0).len()
1198+ };
1199+ assert_eq!(rows(&session), 2, "a row per source");
1200+
1201+ let refusal = session
1202+ .remove_source(&second, 0)
1203+ .expect_err("its take is still on the timeline")
1204+ .to_string();
1205+ assert!(refusal.contains("still plays"), "{refusal}");
1206+ assert!(
1207+ refusal.contains("V1 (1 clip)") && refusal.contains("A1 (1 clip)"),
1208+ "the refusal names the lanes to clear: {refusal}"
1209+ );
1210+ assert_eq!(rows(&session), 2, "and the row is still there");
1211+
1212+ // Delete that take -- the whole group, from either half -- and the file
1213+ // can go. The list is what says so.
1214+ let last = session.lane_clips(Lane::V1).len() - 1;
1215+ assert!(session.delete_clip(Lane::V1, last));
1216+ session
1217+ .remove_source(&second, 0)
1218+ .expect("nothing plays av2 any more");
1219+ assert_eq!(rows(&session), 1, "the row went with it");
1220+ assert_eq!(session.sources().len(), 1);
1221+ // The one file left is held to the same rule and no other: its own take
1222+ // is still on the lanes, so it stays...
1223+ let first = session.sources()[0].path.clone();
1224+ let refusal = session
1225+ .remove_source(&first, 0)
1226+ .expect_err("its take is still on the timeline")
1227+ .to_string();
1228+ assert!(refusal.contains("still plays"), "{refusal}");
1229+ // ...and once nothing plays it, the *last* row goes too. What is left
1230+ // is the empty library `Player::close_session` turns back into the
1231+ // window the editor launches as -- the user-reported bug was that this
1232+ // very removal was refused, leaving a row that could never be taken
1233+ // out.
1234+ assert!(session.delete_clip(Lane::V1, 0));
1235+ session
1236+ .remove_source(&first, 0)
1237+ .expect("the only row goes like any other");
1238+ assert_eq!(rows(&session), 0, "an empty library");
1239+ assert!(session.sources().is_empty());
1240+ // And it is still a session: silent, empty, and asked for its length
1241+ // rather than panicking on a source list that is not there.
1242+ assert_eq!(session.timeline_duration(), 0.0);
1243+ assert!(
1244+ session.save_project(&asset("nothing.edith")).is_err(),
1245+ "a project naming no file could never be opened again, so it is not written"
1246+ );
1247+ // A row this timeline never had is refused, not panicked on.
1248+ assert!(session.remove_source(&second, 0).is_err());
1249+}
1250+
1251+/// The clipboard after a library removal. A copied clip names its file by
1252+/// index and a removal renumbers the list, so this is the difference
1253+/// between pasting the take that was copied and pasting **another file**
1254+/// over the same range ([`clipboard_after_remove`], called by
1255+/// [`Player::remove_source`]).
1256+#[test]
1257+fn a_copied_clip_is_renumbered_or_dropped_when_a_row_leaves_the_library() {
1258+ let clip = |source: usize| Clip {
1259+ start: 0,
1260+ in_frame: 0,
1261+ out_frame: 30,
1262+ source,
1263+ link: None,
1264+ eq: None,
1265+ color: None,
1266+ fit: Default::default(),
1267+ speed: Default::default(),
1268+ };
1269+ // Copied from source 2, source 0 removed: the same file is source 1 now.
1270+ assert_eq!(
1271+ clipboard_after_remove(Some(clip(2)), 0).map(|c| c.source),
1272+ Some(1),
1273+ "the clipboard follows its file down the list"
1274+ );
1275+ // Copied from a source *before* the one that went: untouched.
1276+ assert_eq!(
1277+ clipboard_after_remove(Some(clip(0)), 2).map(|c| c.source),
1278+ Some(0)
1279+ );
1280+ // Copied from the row that was just removed: there is nothing left to
1281+ // paste, and pasting the next file along would be a lie.
1282+ assert!(clipboard_after_remove(Some(clip(1)), 1).is_none());
1283+ assert!(clipboard_after_remove(None, 0).is_none());
1284+}
1285+
1286+/// The trim-a-clip path through the doors the edge drag uses:
1287+/// [`Player::trim_to`] clamps the pointer with `trim_room` and
1288+/// [`Player::commit_trim`] writes it with `trim_clip`. The clip plays less
1289+/// of its file, the sound linked to it follows, the head trim moves the
1290+/// in-point, and one undo takes a whole gesture back.
1291+///
1292+/// The routing *to* these doors -- the 6 px edge strip claiming the press
1293+/// the clip's own body-drag would otherwise take -- is gpui hitbox
1294+/// behaviour (`occlude`) and is not reachable without a window.
1295+#[test]
1296+fn a_clip_trimmed_by_its_edge_plays_less_of_its_file() {
1297+ use engine::project::Edge;
1298+
1299+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1300+ session.set_gain(0.0);
1301+ let whole = session.lane_clips(Lane::V1)[0];
1302+ let full = session.timeline_duration();
1303+ assert_eq!(
1304+ session.trim_room(Lane::V1, 0, Edge::End),
1305+ Some((whole.start + 1, whole.end())),
1306+ "the file's own last frame is how far the tail goes"
1307+ );
1308+ assert!(
1309+ !session.trim_clip(Lane::V1, 0, Edge::End, 9_999),
1310+ "it already plays all of it"
1311+ );
1312+
1313+ // Pulled in by a third: the timeline ends earlier and the sound with it.
1314+ let shorter = whole.end() - whole.len() / 3;
1315+ assert!(session.trim_clip(Lane::V1, 0, Edge::End, shorter));
1316+ assert_eq!(session.lane_clips(Lane::V1)[0].end(), shorter);
1317+ assert_eq!(
1318+ session.lane_clips(Lane::A1)[0].end(),
1319+ shorter,
1320+ "the linked sound was trimmed with the picture"
1321+ );
1322+ assert!(session.timeline_duration() < full, "and plays out earlier");
1323+
1324+ // ...and dragged back out, as far as the file goes and no further.
1325+ assert!(session.trim_clip(Lane::V1, 0, Edge::End, 9_999));
1326+ assert_eq!(
1327+ session.lane_clips(Lane::V1)[0],
1328+ whole,
1329+ "the whole take back"
1330+ );
1331+
1332+ // The head takes the in-point with it, so what plays at the new start
1333+ // is source frame 10 rather than source frame 0.
1334+ assert!(session.trim_clip(Lane::V1, 0, Edge::Start, 10));
1335+ let head = session.lane_clips(Lane::V1)[0];
1336+ assert_eq!((head.start, head.in_frame), (10, 10));
1337+ assert_eq!(session.lane_clips(Lane::A1)[0].in_frame, 10, "sound too");
1338+ assert_eq!(
1339+ session.trim_room(Lane::V1, 0, Edge::Start).map(|r| r.0),
1340+ Some(0),
1341+ "and it may be pulled back out to the file's first frame"
1342+ );
1343+
1344+ assert!(session.undo(), "one step for the whole drag");
1345+ assert_eq!(session.lane_clips(Lane::V1)[0], whole);
1346+}
1347+
1348+/// The move-a-clip-between-tracks path through the door the drop uses
1349+/// ([`Player::move_clip`] calls exactly this): the clip changes row, the
1350+/// *picture* comes from the new row afterwards -- which is what "it plays
1351+/// from there" means -- and one undo puts it back.
1352+#[test]
1353+fn a_clip_dragged_onto_another_track_plays_from_it() {
1354+ use engine::project::LaneKind;
1355+
1356+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1357+ session.set_gain(0.0);
1358+ let v2 = session.add_lane(LaneKind::Video);
1359+ assert_eq!(session.video_clip_at(0.0), Some((Lane::V1, 0)));
1360+
1361+ assert!(session.move_clip_to(Lane::V1, 0, v2, 0), "V1 -> V2");
1362+ assert!(session.lane_clips(Lane::V1).is_empty(), "it left V1");
1363+ assert_eq!(session.lane_clips(v2).len(), 1, "and landed on V2");
1364+ assert_eq!(
1365+ session.video_clip_at(0.0),
1366+ Some((v2, 0)),
1367+ "the picture now comes from V2"
1368+ );
1369+ assert_eq!(session.lane_clips(Lane::A1).len(), 1, "its sound stayed");
1370+
1371+ // Dropped on a lane of the other kind it is refused and nothing moves --
1372+ // the notice the front-end shows for it says which kind of lane to use.
1373+ // (The other refusal, landing on another clip, is the engine's own test
1374+ // `move_clip_keeps_the_frames_and_refuses_the_rest`.)
1375+ assert!(!session.move_clip_to(v2, 0, Lane::A1, 0), "picture on A1");
1376+ assert_eq!(session.lane_clips(v2).len(), 1, "and it stayed on V2");
1377+ assert!(
1378+ session.move_clip_to(v2, 0, Lane::V1, 0),
1379+ "dragged back down"
1380+ );
1381+
1382+ // One undo per move, and each is a single step.
1383+ assert!(session.undo(), "the drag back");
1384+ assert_eq!(session.video_clip_at(0.0), Some((v2, 0)));
1385+ assert!(session.undo(), "the drag up");
1386+ assert_eq!(session.video_clip_at(0.0), Some((Lane::V1, 0)));
1387+ assert!(session.lane_clips(v2).is_empty());
1388+}
1389+
1390+/// The add-a-track path end to end through the doors the buttons and the
1391+/// drop use: `+ V` adds a row, a library row let go over it lands there and
1392+/// nowhere else, Delete on it leaves the lanes under it where they are, and
1393+/// undo takes the whole thing back one step at a time.
1394+#[test]
1395+fn a_track_can_be_added_dropped_on_edited_and_taken_back() {
1396+ use engine::project::LaneKind;
1397+
1398+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1399+ session.set_gain(0.0);
1400+ assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1]);
1401+ // What the `+ V` button asks for, and what the row it draws is called.
1402+ let v2 = session.add_lane(LaneKind::Video);
1403+ assert_eq!(v2.label(), "V2");
1404+ assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1, v2]);
1405+ assert!(session.lane_clips(v2).is_empty());
1406+ // A library row let go over that row: the same door the Add button
1407+ // uses, told which lane it was let go over.
1408+ let path = session.sources()[0].path.clone();
1409+ assert!(
1410+ session
1411+ .place_stream_at(1.0, &path, 0, Some(v2))
1412+ .expect("its own file is on this timeline")
1413+ );
1414+ assert_eq!(session.lane_clips(v2).len(), 1, "the drop landed on V2");
1415+ assert_eq!(session.lane_clips(v2)[0].start, 30, "at the playhead");
1416+ // ...with the sound it came with, on the row of its own the drop added:
1417+ // a file with audio dropped on a layer used to land silent.
1418+ let a2 = Lane::new(LaneKind::Audio, 1);
1419+ assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1, v2, a2]);
1420+ assert_eq!(session.lane_clips(a2), session.lane_clips(v2), "same take");
1421+ assert_eq!(
1422+ session.lane_clips(v2)[0].link,
1423+ session.lane_clips(a2)[0].link,
1424+ "grouped, so a drag moves both"
1425+ );
1426+ // And nowhere else: the first pair is exactly as it was, one take each.
1427+ assert_eq!(session.lane_clips(Lane::V1).len(), 1);
1428+ assert_eq!(session.lane_clips(Lane::A1).len(), 1);
1429+ // ...and it is a project that saves and opens again as it stands: a
1430+ // grouped pair on a further row is what the file has to carry.
1431+ let dir = engine::scratch::Scratch::dir("ve_layer");
1432+ let file = dir.join("layer.edith");
1433+ session.save_project(&file).expect("save the project");
1434+ let back = PlaybackSession::open_project(&file).expect("it loads as it stands");
1435+ std::fs::remove_dir_all(&dir).ok();
1436+ assert_eq!(back.lanes(), session.lanes());
1437+ for lane in back.lanes() {
1438+ assert_eq!(back.lane_clips(lane), session.lane_clips(lane), "{lane:?}");
1439+ }
1440+ // Delete on the layer is a lift: it is laid over the timeline, so
1441+ // closing a hole under it would drag the take beneath out of step with
1442+ // it. The take on the first pair is still a take, and still ripples.
1443+ assert!(!whole_take(&session, v2, 0));
1444+ assert!(whole_take(&session, Lane::V1, 0));
1445+ assert!(whole_take(&session, Lane::A1, 0));
1446+ assert_eq!(a2.label(), "A2");
1447+ assert!(session.lift_clip(v2, 0));
1448+ assert!(session.lane_clips(v2).is_empty());
1449+ assert_eq!(session.lane_clips(Lane::V1).len(), 1, "V1 stayed put");
1450+ assert_eq!(
1451+ session.lane_clips(a2).len(),
1452+ 1,
1453+ "a lift takes the half it names: the sound is still there to lift"
1454+ );
1455+ assert!(session.lift_clip(a2, 0));
1456+
1457+ // A second audio lane used to be what an mp4 export could not write --
1458+ // it copied one AAC track and a mix is not a copy. It mixes now
1459+ // (`export::copy_audio`), so no row is greyed by a count of lanes.
1460+ for format in [Format::Mp4, Format::Av1, Format::Av1Mp4] {
1461+ assert_eq!(
1462+ format_refusal(&session, format),
1463+ None,
1464+ "two audio lanes are a mix, not a refusal"
1465+ );
1466+ }
1467+
1468+ // Undo, one edit at a time and backwards: the lift of the sound, the
1469+ // lift of the picture, the drop on V2 with the lane A2 it added, and
1470+ // last the lane V2 -- an added track is one step like every other edit.
1471+ for lanes in [4, 4, 3, 2] {
1472+ assert!(session.undo());
1473+ assert_eq!(session.lanes().len(), lanes);
1474+ }
1475+ assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1]);
1476+ assert_eq!(session.lane_clips(Lane::V1).len(), 1);
1477+ assert_eq!(format_refusal(&session, Format::Mp4), None);
1478+}
1479+
1480+#[test]
1481+fn a_source_is_only_ever_asked_for_its_peaks_once() {
1482+ let (a, b) = (asset("test_av.mp4"), asset("test_av2.mp4"));
1483+ // Two files, and two streams of the first: three envelopes, because
1484+ // one file's two audio tracks are two different waveforms.
1485+ let sources = [
1486+ Source {
1487+ path: a.clone(),
1488+ audio_stream: 0,
1489+ },
1490+ Source {
1491+ path: a.clone(),
1492+ audio_stream: 1,
1493+ },
1494+ Source {
1495+ path: b.clone(),
1496+ audio_stream: 0,
1497+ },
1498+ ];
1499+ let keys = |s: &[Source]| {
1500+ s.iter()
1501+ .map(|s| (s.path.clone(), s.audio_stream))
1502+ .collect::<Vec<_>>()
1503+ };
1504+ let mut waves: HashMap<(PathBuf, usize), Wave> = HashMap::new();
1505+ assert_eq!(unseen_sources(&sources, &waves), keys(&sources));
1506+ // The entry goes in when the decode *starts*, so the sixty repaints a
1507+ // second that happen while it runs must not start it again -- which is
1508+ // what this asserts about a key whose value is not an answer yet.
1509+ waves.insert((a.clone(), 0), Wave::Loading);
1510+ assert_eq!(
1511+ unseen_sources(&sources, &waves),
1512+ keys(&sources[1..]),
1513+ "the file's other stream is a key of its own"
1514+ );
1515+ // A file with no audio is an answer like any other: never re-asked.
1516+ waves.insert((a, 1), Wave::Silent);
1517+ waves.insert((b.clone(), 0), Wave::Silent);
1518+ assert!(unseen_sources(&sources, &waves).is_empty());
1519+ // The stream probe is per *file*: the two entries of `a` ask once.
1520+ let mut streams: HashMap<PathBuf, Vec<StreamInfo>> = HashMap::new();
1521+ assert_eq!(
1522+ unseen_paths(&sources, &streams),
1523+ vec![asset("test_av.mp4"), b]
1524+ );
1525+ streams.insert(asset("test_av.mp4"), Vec::new());
1526+ assert_eq!(unseen_paths(&sources, &streams).len(), 1);
1527+}
1528+
1529+#[test]
1530+fn the_add_button_is_dead_unless_it_would_do_something() {
1531+ let picked = (PathBuf::from("/m/0.mp4"), 0);
1532+ assert!(can_add(Some(&picked), true, false));
1533+ // Nothing picked, nothing to put it on, or an export reading the very
1534+ // edit list this would change.
1535+ assert!(!can_add(None, true, false));
1536+ assert!(!can_add(Some(&picked), false, false));
1537+ assert!(!can_add(Some(&picked), true, true));
1538+}
1539+
1540+#[test]
1541+fn the_media_column_never_takes_the_picture_over() {
1542+ for window in [360., 640., 1280., 1920., 3840.] {
1543+ let w = crate::library_w(window);
1544+ // The whole point of the budget: the picture keeps the majority of
1545+ // the row at every size a window can be.
1546+ assert!(w <= window / 3., "{window}px window gave the list {w}px");
1547+ assert!(w >= LIBRARY_MIN_W.min(window / 3.), "{window}px: {w}px");
1548+ assert!(w <= LIBRARY_MAX_W);
1549+ }
1550+ // It yields: a narrower window gives the list less, never the same.
1551+ assert!(crate::library_w(640.) < crate::library_w(1280.));
1552+ // Rows are clickable, so WCAG 2.5.8 binds them like every other target,
1553+ // and a name over a timecode has to fit inside one.
1554+ assert!(ROW_H >= HIT_MIN);
1555+ assert!(SWATCH_W < LIBRARY_MIN_W);
1556+}
1557+
1558+#[test]
1559+fn the_window_is_named_after_the_program_and_what_is_open() {
1560+ assert_eq!(window_title("test_av.mp4"), "test_av.mp4 — edith");
1561+ // An empty window is the program, not "no file open — edith".
1562+ assert_eq!(window_title(NO_FILE), "edith");
1563+}
1564+
1565+#[test]
1566+fn frac_along_measures_from_the_elements_own_left_edge() {
1567+ // A ruler inset by the panel's 12 px padding: window x is not bar x.
1568+ let bar: Bounds<Pixels> = Bounds {
1569+ origin: point(px(12.), px(400.)),
1570+ size: size(px(200.), px(6.)),
1571+ };
1572+ assert_eq!(frac_along(px(12.), bar), 0.);
1573+ assert_eq!(frac_along(px(112.), bar), 0.5);
1574+ assert_eq!(frac_along(px(212.), bar), 1.);
1575+ // Outside the bar (a click that slid off) clamps, never extrapolates.
1576+ assert_eq!(frac_along(px(0.), bar), 0.);
1577+ assert_eq!(frac_along(px(9999.), bar), 1.);
1578+ // Never painted: no division by zero, no NaN reaching seek().
1579+ assert_eq!(frac_along(px(50.), Bounds::default()), 0.);
1580+
1581+ // The equalizer's axis is the other one, and reads the same way.
1582+ let graph: Bounds<Pixels> = Bounds {
1583+ origin: point(px(12.), px(60.)),
1584+ size: size(px(296.), px(EQ_GRAPH_H)),
1585+ };
1586+ assert_eq!(frac_down(px(60.), graph), 0.);
1587+ assert_eq!(frac_down(px(60. + EQ_GRAPH_H / 2.), graph), 0.5);
1588+ assert_eq!(frac_down(px(9999.), graph), 1.);
1589+ // Never painted reads as flat: an unpainted graph must not slam a band
1590+ // to +12 dB on the first press.
1591+ assert_eq!(frac_down(px(50.), Bounds::default()), 0.5);
1592+}
crates/app/src/tests/layout.rsadded+1093 -0
@@ -0,0 +1,1093 @@
1+//! What is drawn and where: the toolbar, the theme, the notices, the lanes
2+//! and their marks, the tints, the subtitle rows and the sliders.
3+
4+use super::*;
5+
6+/// The edit toolbar against the 640x360 floor the whole editor is measured
7+/// at. It does not fit and cannot be made to -- so what it may never do is
8+/// *hide* the tail: the row scrolls, and the door to everything scrolled
9+/// off it is pinned outside the scrolling box.
10+#[test]
11+fn toolbar_fits_the_smallest_window() {
12+ let toolbar = src_text("ui/toolbar.rs");
13+ let row = &toolbar[toolbar.find("pub(crate) fn toolbar(").expect("the toolbar")..];
14+ // Every button in the row is a hit target, so none of them is narrower
15+ // than `HIT_MIN`, and they sit in 8 px gaps inside the row's own 12 px
16+ // padding.
17+ let buttons = row.matches("action_control(").count();
18+ assert!(buttons >= 11, "the row's buttons moved; this scan is blind");
19+ // The row is shorter than it was -- the project's own settings (size,
20+ // rate, HDR) are the inspector's now and the transport is the
21+ // picture's -- so whether it fits at 640 px depends on the words in it
22+ // and is not something this scan can measure. What it can hold to is
23+ // the rule: "it scrolls" is not "it can be found", so the door to
24+ // whatever is off the right edge is pinned outside the scrolling box
25+ // and the card it opens carries every action there is
26+ // (`every_action_is_on_the_actions_card`).
27+ assert!(
28+ row.contains("\"controls-more\""),
29+ "nothing pinned beside the scrolling row: the tail is unreachable at 640 px"
30+ );
31+ assert_eq!(row.matches("overflow_x_scroll").count(), 1);
32+ assert!(
33+ row.find("\"controls-more\"") > row.find("overflow_x_scroll"),
34+ "the pinned door is inside the row it is meant to outlive"
35+ );
36+ // ...and nothing in the row decides for itself whether it can act: the
37+ // oracle does, once, for the key and the button alike. A raw `control(`
38+ // in here is a button that can go dead while its stroke still fires --
39+ // the bug this redesign was called in for.
40+ assert_eq!(
41+ row.matches("\n .child(control(").count(),
42+ 0,
43+ "a toolbar button bypassing the availability oracle"
44+ );
45+}
46+
47+/// The whole reason `ui/theme.rs` exists: a colour written anywhere else is
48+/// a colour the next palette sweep will miss, which is exactly how 186 grey
49+/// calls survived every previous attempt at this.
50+#[test]
51+fn no_colour_is_written_outside_the_theme() {
52+ let source = ui_source();
53+ let stray: Vec<&str> = source
54+ .lines()
55+ .filter(|l| l.contains("rgb(0x") || l.contains("rgba(0x"))
56+ .collect();
57+ assert!(stray.is_empty(), "colour written outside the theme: {stray:?}");
58+}
59+
60+/// "It scrolls" is not "it can be found": at the 640x360 floor the timeline
61+/// takes its share and no more, so a third track is behind a scroll -- and
62+/// the line that says so has to keep telling the truth *while* the column is
63+/// being scrolled, or it is an instruction nobody can carry out.
64+#[test]
65+fn the_line_about_what_is_below_the_fold_counts_what_is_still_below_it() {
66+ // The timeline is a region and not the window: its chrome and one whole
67+ // lane fit the share it may take at the floor.
68+ let floor = 360. * TIMELINE_SHARE;
69+ assert!(
70+ TIMELINE_FIXED_H + LANE_H <= floor,
71+ "{TIMELINE_FIXED_H} px of chrome and a lane will not fit {floor} px"
72+ );
73+ // What is left over is measured in whole lanes, at least one.
74+ assert_eq!(lanes_shown(LANE_H), 1);
75+ assert_eq!(lanes_shown(LANE_H - 10.), 1);
76+ assert_eq!(lanes_shown(2. * LANE_H + 8.), 2);
77+
78+ // Four tracks in a two-lane box: two are below, and each row scrolled
79+ // past takes one off that count until none is left. This is the bug the
80+ // graft fixes -- the count used to be `total - shown` forever, so the
81+ // line still said "2 more below" with the last track on screen.
82+ let box_h = 2. * LANE_H + 8.;
83+ assert_eq!(rows_below(4, box_h, 0.), 2);
84+ assert_eq!(rows_below(4, box_h, LANE_H + 8.), 1);
85+ assert_eq!(rows_below(4, box_h, 2. * (LANE_H + 8.)), 0);
86+ // Past the end (gpui clamps, but the arithmetic must not wrap).
87+ assert_eq!(rows_below(4, box_h, 900.), 0);
88+ // A project that fits says nothing at all.
89+ assert_eq!(rows_below(2, box_h, 0.), 0);
90+
91+ // The inspector's rows are not one height, so its own line is measured
92+ // in pixels off the scroll instead: gpui keeps the offset negative going
93+ // down, and at the bottom the two cancel out exactly.
94+ assert_eq!(px_below(120., 0.), 120.);
95+ assert_eq!(px_below(120., -40.), 80.);
96+ assert_eq!(px_below(120., -120.), 0.);
97+ assert_eq!(px_below(0., 0.), 0.);
98+}
99+
100+/// The failure a user never learns about is the one that was answered by
101+/// another failure: two imports failing back to back are two messages, in
102+/// the order they happened, and the second does not overwrite the first
103+/// before a frame has drawn it.
104+#[test]
105+fn a_second_message_queues_behind_the_first_instead_of_erasing_it() {
106+ let mut q = std::collections::VecDeque::new();
107+ push_notice(&mut q, "NOTHING ADDED — no video stream".into());
108+ push_notice(&mut q, "NOTHING ADDED — the file is not there".into());
109+ assert_eq!(q.len(), 2);
110+ assert_eq!(q.front().map(|n: &gpui::SharedString| n.as_ref()), Some("NOTHING ADDED — no video stream"));
111+
112+ // A held key that refuses says its one sentence once: the count on the
113+ // bar is a count of messages, not of how long the key was held.
114+ push_notice(&mut q, "NOTHING ADDED — the file is not there".into());
115+ assert_eq!(q.len(), 2);
116+
117+ // ...and the ceiling drops the oldest rather than the newest: the thing
118+ // that just happened is the thing worth reading.
119+ for i in 0..NOTICES_MAX + 3 {
120+ push_notice(&mut q, format!("SCAN FAILED: {i}").into());
121+ }
122+ assert_eq!(q.len(), NOTICES_MAX);
123+ assert_eq!(q.back().map(|n: &gpui::SharedString| n.as_ref()), Some("SCAN FAILED: 10"));
124+
125+ // Answering the bar brings the next one up, oldest first.
126+ let front = q.pop_front();
127+ assert_ne!(front, q.front().cloned());
128+}
129+
130+/// The bar colours itself off the words the message already opens with, so
131+/// the tone cannot disagree with the sentence it labels.
132+#[test]
133+fn a_message_wears_the_colour_its_own_words_say() {
134+ assert_eq!(notice_tone("SCAN FAILED: no audio"), STATUS_ERROR());
135+ assert_eq!(notice_tone(&format!("{EXPORT_DONE}out.mp4")), STATUS_SUCCESS());
136+ assert_eq!(notice_tone("NOTHING DETACHED — not grouped"), STATUS_WARNING());
137+ assert_eq!(notice_tone("SNAP ON"), ACCENT_PRIMARY());
138+}
139+
140+/// The cards are sections of the inspector, not sheets over the timeline:
141+/// adjusting a clip must never hide the clip. Structural, because that is
142+/// where the rule lives -- a card rendered from the root again would be an
143+/// overlay again, whatever it looked like on the day it was written.
144+#[test]
145+fn an_inspector_section_occludes_no_timeline() {
146+ let inspector = src_text("ui/inspector.rs");
147+ // Whichever file the root render has come to live in, from the impl to the
148+ // end of it -- found rather than named, so moving the root does not quietly
149+ // leave this rule reading a file the render is no longer in.
150+ let render = source_files()
151+ .iter()
152+ .map(|path| std::fs::read_to_string(path).expect("a source file"))
153+ .find_map(|text| text.find("impl Render for Player").map(|at| text[at..].to_string()))
154+ .expect("the root render");
155+ for card in [
156+ "eq_card", "color_card", "speed_card", "silence_card", "mix_card",
157+ ] {
158+ assert!(
159+ inspector.contains(&format!("self.{card}(")),
160+ "{card} is not a section of the inspector"
161+ );
162+ assert!(
163+ !render.contains(&format!("self.{card}(")),
164+ "{card} is drawn from the root again -- it is an overlay over the timeline"
165+ );
166+ }
167+ // The docked cards are placed against the inspector's own box, which is
168+ // what turns `scrim()` (`absolute().inset_0()`) from a window-wide sheet
169+ // into this column.
170+ assert!(
171+ inspector.contains(".relative()"),
172+ "the inspector is not a positioning context: its cards would cover the window"
173+ );
174+}
175+
176+/// MUST 1, on the two named offenders: the button that relabels itself
177+/// mid-export and the one that used to read "Muted 80%". Both live in a
178+/// rect that is reserved once, so the words change and the box does not.
179+#[test]
180+fn a_stateful_button_keeps_its_rect() {
181+ use crate::ui::toolbar::{EXPORT_SLOT_W, SNAP_SLOT_W, VOLUME_SLOT_W};
182+ // Widest word each slot can hold, at the 12 px text this window is set
183+ // in -- ~7 px a character plus the 16 px of padding.
184+ let fits = |slot: f32, word: &str| slot >= word.chars().count() as f32 * 7. + 16.;
185+ for word in ["Export", "Cancel"] {
186+ assert!(fits(EXPORT_SLOT_W, word), "{word} overflows its rect");
187+ }
188+ for word in ["Snap on", "Snap off", "No subs", "Subs off"] {
189+ assert!(fits(SNAP_SLOT_W, word), "{word} overflows its rect");
190+ }
191+ for word in ["100%", "× 100%"] {
192+ assert!(fits(VOLUME_SLOT_W, word), "{word} overflows its rect");
193+ }
194+ // And the rect is passed, not hoped for: every stateful control in the
195+ // three chrome rows names its width.
196+ let toolbar = src_text("ui/toolbar.rs");
197+ for (id, slot) in [
198+ ("\"export\"", "EXPORT_SLOT_W"),
199+ ("\"snap\"", "SNAP_SLOT_W"),
200+ ("\"subs\"", "SNAP_SLOT_W"),
201+ ("\"volume\"", "VOLUME_SLOT_W"),
202+ ("\"zoom-fit\"", "ZOOM_SLOT_W"),
203+ ] {
204+ let at = toolbar.find(id).unwrap_or_else(|| panic!("no {id} button"));
205+ assert!(
206+ toolbar[at..at + 120].contains(slot),
207+ "{id} does not reserve {slot}"
208+ );
209+ }
210+}
211+
212+#[test]
213+fn nothing_clickable_is_smaller_than_the_wcag_minimum() {
214+ // Every hit target in the panel, including the scrub strip -- whose bar
215+ // is 6 px to look at and whose click area must not be.
216+ assert!(CONTROL_H >= HIT_MIN);
217+ assert!(RULER_HIT_H >= HIT_MIN);
218+ assert!(LANE_H >= HIT_MIN);
219+ // A clip box is a hit target too, and its two trim strips occlude it:
220+ // on a box narrower than the pair there is no body left to press, so
221+ // the clip cannot be selected, dragged or menued at all -- which is
222+ // every clip a jumpcut leaves at a normal zoom. Below three handles
223+ // there are no strips.
224+ assert!(!trims(0.));
225+ assert!(!trims(EDGE_W));
226+ assert!(!trims(2. * EDGE_W), "a box that is all handle and no clip");
227+ assert!(!trims(3. * EDGE_W - 0.1));
228+ // And where they are drawn, what is left between them is a hit target
229+ // in its own right -- a whole handle's width of clip.
230+ for width in [3. * EDGE_W, 24., 100., 4000.] {
231+ assert!(trims(width));
232+ assert!(
233+ width - 2. * EDGE_W >= EDGE_W,
234+ "{width} px of box leaves no middle"
235+ );
236+ }
237+}
238+
239+#[test]
240+fn a_lane_row_is_a_fixed_header_and_a_bed_that_can_be_hit() {
241+ // The header column is what the ruler is offset by as well, so both
242+ // numbers are shared rather than repeated per row (A-MUST1/A-MUST2).
243+ assert!(HEADER_W > 0. && HEADER_GAP >= 0.);
244+ // Two lanes, a ruler, a button row and the timecode line, inside the
245+ // panel the window is sized for.
246+ assert!(
247+ CONTROL_H + RULER_HIT_H + 2. * LANE_H + 17. + 4. * 8. + 16. <= PANEL_H,
248+ "the second lane does not fit the panel"
249+ );
250+ // Headers and clip boxes are as tall as the lane, and the lane is a
251+ // click target (WCAG 2.5.8).
252+ assert!(LANE_H >= HIT_MIN);
253+ // A label row that ate the whole lane would leave no waveform.
254+ assert!(LABEL_H < LANE_H / 2.);
255+ // An added track adds its own row to the panel, and the two a project
256+ // starts with leave it exactly the height it has always been.
257+ assert_eq!(panel_h(2), PANEL_H);
258+ assert_eq!(panel_h(1), PANEL_H);
259+ assert_eq!(panel_h(3), PANEL_H + LANE_H + 8.);
260+ assert_eq!(
261+ panel_h(LANES_MAX),
262+ PANEL_H + lanes_h(LANES_MAX) - lanes_h(2)
263+ );
264+ // Past the cap the column scrolls instead: the panel stops growing, so
265+ // no number of tracks can push the picture off the window.
266+ assert_eq!(panel_h(LANES_MAX + 1), panel_h(LANES_MAX));
267+ assert_eq!(panel_h(50), panel_h(LANES_MAX));
268+ assert_eq!(lanes_h(0), 0.);
269+ assert_eq!(lanes_h(1), LANE_H);
270+ assert_eq!(lanes_h(2), 2. * LANE_H + 8.);
271+}
272+
273+#[test]
274+fn a_click_marks_the_whole_group_and_nothing_else() {
275+ let (v, a) = ((Lane::V1, 0), (Lane::A1, 0));
276+ // Clicking the video half of group 1 marks the audio half with it.
277+ assert!(marked(v, Some(1), Some(v), Some(1)));
278+ assert!(marked(a, Some(1), Some(v), Some(1)));
279+ // Another group's clips stay unmarked, in either lane.
280+ assert!(!marked((Lane::V1, 1), Some(2), Some(v), Some(1)));
281+ assert!(!marked((Lane::A1, 1), Some(2), Some(v), Some(1)));
282+ // A half a lift left behind has no group: it marks itself only, which
283+ // is what makes it separately deletable. Two ungrouped clips must not
284+ // mark each other by both being ungrouped.
285+ assert!(marked(a, None, Some(a), None));
286+ assert!(!marked(v, None, Some(a), None));
287+ // Nothing selected marks nothing.
288+ assert!(!marked(v, Some(1), None, None));
289+}
290+
291+#[test]
292+fn a_name_is_dropped_rather_than_smeared_across_a_thin_clip() {
293+ assert!(show_label(LABEL_MIN_W));
294+ assert!(show_label(400.));
295+ assert!(!show_label(LABEL_MIN_W - 0.1));
296+ // The label test is the box's own width in pixels now, which is what
297+ // the scale hands it -- no bed width, and so nothing to be zero.
298+ let scale = Scale::default();
299+ assert!(show_label(scale.width_px(LABEL_MIN_W as f64 / PPS_DEFAULT)));
300+ assert!(!show_label(scale.width_px(0.)));
301+}
302+
303+#[test]
304+fn an_envelope_stays_inside_the_box_it_is_drawn_in() {
305+ // A ramp: silence at the start, full scale at the end.
306+ let peaks: Vec<(f32, f32)> = (0..40)
307+ .map(|i| (-(i as f32) / 39., i as f32 / 39.))
308+ .collect();
309+ let (w, h) = (100., 30.);
310+ let cols = envelope(&peaks, 0., 1., w, h);
311+ assert_eq!(cols.len(), (w / WAVE_COL) as usize + 1);
312+ for &(x, top, bottom) in &cols {
313+ assert!((0. ..=w).contains(&x), "x {x} outside 0..{w}");
314+ assert!((0. ..=h).contains(&top), "top {top} outside 0..{h}");
315+ assert!(
316+ (0. ..=h).contains(&bottom),
317+ "bottom {bottom} outside 0..{h}"
318+ );
319+ // Never inverted, and never a polygon with no area: silence has to
320+ // read as a line rather than as nothing at all.
321+ assert!(
322+ bottom - top >= 1.,
323+ "column {top}..{bottom} is thinner than a pixel"
324+ );
325+ }
326+ // The ramp is drawn as a ramp: the last column is taller than the first.
327+ let height = |&(_, top, bottom): &(f32, f32, f32)| bottom - top;
328+ assert!(height(cols.last().unwrap()) > height(cols.first().unwrap()) + 5.);
329+ // Degenerate inputs draw nothing rather than panicking.
330+ assert!(envelope(&[], 0., 1., w, h).is_empty());
331+ assert!(envelope(&peaks, 0., 1., 0., h).is_empty());
332+ // A clip whose range runs past the peaks clamps to the last bucket.
333+ assert!(!envelope(&peaks, 0., 99., w, h).is_empty());
334+}
335+
336+/// A box laid out wider than any screen -- a long clip at a deep zoom -- is
337+/// still one screen's worth of columns: the path a repaint has to build is
338+/// bounded by what can be seen, not by what the layout says the box is.
339+/// Unbounded, a 5 s clip zoomed to the frame is a path of millions of points
340+/// per frame, and the repaint that stalls on it is the waveform that
341+/// "disappeared".
342+#[test]
343+fn an_envelope_never_costs_more_points_than_a_screen_can_show() {
344+ let peaks: Vec<(f32, f32)> = (0..200).map(|i| (-(i as f32) / 199., 1.)).collect();
345+ // The width a 5 s clip is laid out at when the bed shows 8 frames of it.
346+ let huge = 5. * 30. / 8. * 1200.;
347+ let cols = envelope(&peaks, 0., 5., huge, 30.);
348+ assert!(
349+ cols.len() <= WAVE_COLS_MAX + 1,
350+ "{} columns for a {huge} px box",
351+ cols.len()
352+ );
353+ // ...and the slice actually painted is the part of the box on the bed,
354+ // which is where that width stops mattering: a column per two visible
355+ // pixels, at every zoom.
356+ let (x, w) = visible_slice(-huge / 2., huge, 1200.);
357+ assert_eq!((x, w), (huge / 2., 1200.));
358+ assert_eq!(envelope(&peaks, 0., 5., w, 30.).len(), 601);
359+ // A box entirely off the bed has no slice, and one that has never been
360+ // measured is drawn whole -- what was drawn before there was a bed.
361+ assert_eq!(visible_slice(2000., 500., 1200.), (0., 0.));
362+ assert_eq!(visible_slice(-3000., 500., 1200.), (500., 0.));
363+ assert_eq!(visible_slice(-40., 500., 0.), (0., 500.));
364+ // Half on, at either edge.
365+ assert_eq!(visible_slice(-100., 500., 1200.), (100., 400.));
366+ assert_eq!(visible_slice(1000., 500., 1200.), (0., 200.));
367+}
368+
369+/// The box a trim draws is the box its release commits, at every speed. The
370+/// preview used to hand the *timeline* frame count to a source-frame field:
371+/// at 2x a tail moved twice as fast as the pointer and snapped back on
372+/// release, and a head drag moved the clip's other edge.
373+#[test]
374+fn a_trim_preview_lands_where_the_release_commits() {
375+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
376+ session.set_gain(0.0);
377+ for permille in SPEED_PRESETS {
378+ // Live, so the loop owes it no undo step: the speeds are the axis
379+ // this walks, and the trims below are what is undone.
380+ session
381+ .set_speed_live(Lane::V1, 0, Speed::from_permille(permille))
382+ .expect("a clip alone on its lane may be speeded");
383+ for edge in [Edge::Start, Edge::End] {
384+ let clip = session.lane_clips(Lane::V1)[0];
385+ let (lo, hi) = session
386+ .trim_room(Lane::V1, 0, edge)
387+ .expect("clip 0 is there");
388+ // Both walls and the middle of the room: the whole range a
389+ // pointer can be clamped to.
390+ for to in [lo, (lo + hi) / 2, hi] {
391+ let preview = trimmed_clip(clip, edge, to, false);
392+ // The drag is one edit and one undo step, so the next `to`
393+ // is measured from the same clip this one was.
394+ if session.trim_clip(Lane::V1, 0, edge, to) {
395+ assert_eq!(
396+ preview,
397+ session.lane_clips(Lane::V1)[0],
398+ "{edge:?} to {to} at {permille} per mille"
399+ );
400+ assert!(session.undo(), "the trim is one undo step");
401+ } else {
402+ // An edge already where it was asked to go is not an
403+ // edit, and the preview draws the clip unchanged.
404+ assert_eq!(preview, clip, "{edge:?} to {to} at {permille} per mille");
405+ }
406+ assert_eq!(session.lane_clips(Lane::V1)[0], clip, "back where it was");
407+ }
408+ }
409+ }
410+}
411+
412+/// A still trims the same way, and the preview knows it: its head grows
413+/// forward from source frame 0 -- every frame of it is the same picture --
414+/// so the box stretches instead of sliding left.
415+#[test]
416+fn a_stills_trim_preview_grows_forward_like_the_commit() {
417+ let mut session = PlaybackSession::open(asset("test_still.png")).expect("a picture opens");
418+ for edge in [Edge::Start, Edge::End] {
419+ let clip = session.lane_clips(Lane::V1)[0];
420+ let (lo, hi) = session
421+ .trim_room(Lane::V1, 0, edge)
422+ .expect("clip 0 is there");
423+ for to in [lo, (lo + hi) / 2, hi] {
424+ let preview = trimmed_clip(clip, edge, to, true);
425+ match session.trim_clip(Lane::V1, 0, edge, to) {
426+ true => {
427+ assert_eq!(
428+ preview,
429+ session.lane_clips(Lane::V1)[0],
430+ "a still {edge:?} to {to}"
431+ );
432+ assert!(session.undo(), "the trim is one undo step");
433+ }
434+ false => assert_eq!(preview, clip, "a still {edge:?} to {to}"),
435+ }
436+ assert_eq!(session.lane_clips(Lane::V1)[0], clip, "back where it was");
437+ }
438+ }
439+}
440+
441+/// gpui freezes a drag's payload for the whole gesture, and nothing stops a
442+/// stroke from editing the lane under it: the drop has to find the clip that
443+/// was picked up, not whatever slid into its index.
444+#[test]
445+fn a_drop_moves_the_clip_that_was_picked_up_not_its_old_index() {
446+ let at = |start: u32| Clip {
447+ start,
448+ in_frame: 0,
449+ out_frame: 30,
450+ source: 0,
451+ link: None,
452+ eq: None,
453+ color: None,
454+ fit: FitPolicy::Fit,
455+ speed: Speed::NORMAL,
456+ };
457+ let lane = [at(0), at(30), at(60)];
458+ let dragged = lane[2];
459+ assert_eq!(live_idx(&lane, 2, dragged), Some(2), "nothing moved");
460+ // A delete in front of it: the clip is now index 1, and the index the
461+ // drag froze names a clip nobody grabbed.
462+ let after = [at(0), at(60)];
463+ assert_eq!(live_idx(&after, 2, dragged), Some(1));
464+ assert_eq!(live_idx(&after, 1, dragged), Some(1));
465+ // Deleted mid-drag: there is nothing to move, and moving its neighbour
466+ // instead is exactly the bug this exists for.
467+ assert_eq!(live_idx(&[at(0)], 2, dragged), None);
468+ assert_eq!(live_idx(&[], 0, dragged), None);
469+}
470+
471+#[test]
472+fn a_quiet_source_still_draws_as_a_shape() {
473+ // An eighth of full scale, which is about where the fixtures sit.
474+ let quiet: Vec<(f32, f32)> = vec![(-0.125, 0.125), (-0.0625, 0.0625)];
475+ let loud = normalise(quiet.clone());
476+ assert_eq!(loud[0], (-1., 1.));
477+ assert_eq!(loud[1], (-0.5, 0.5));
478+ // Digital silence has no loudest sample to scale to; it must not divide
479+ // by zero and must stay flat.
480+ assert_eq!(normalise(vec![(0., 0.)]), vec![(0., 0.)]);
481+ assert!(normalise(Vec::new()).is_empty());
482+}
483+
484+/// The whole waveform path, from the file on disk to the columns that get
485+/// painted: what no screenshot can assert about the shape.
486+#[test]
487+fn the_fixtures_waveform_reaches_the_lane_as_a_shape() {
488+ let asset = |name: &str| {
489+ std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
490+ .join("../../assets")
491+ .join(name)
492+ };
493+ let peaks = normalise(
494+ engine::waveform::peaks(asset("test_av.mp4"), 0, WAVE_BPS)
495+ .expect("open the fixture")
496+ .expect("test_av.mp4 has audio"),
497+ );
498+ // 5 s of source at the rate the lane asks for.
499+ assert!(peaks.len().abs_diff(5 * WAVE_BPS as usize) <= WAVE_BPS as usize);
500+ let cols = envelope(&peaks, 0., 5., 600., 30.);
501+ let height = |&(_, top, bottom): &(f32, f32, f32)| bottom - top;
502+ let tallest = cols.iter().map(height).fold(0., f32::max);
503+ let flattest = cols.iter().map(height).fold(f32::MAX, f32::min);
504+ // The fixture's 1 Hz pulse: a full-scale peak and a near-silent dip in
505+ // every second, so the drawn envelope is a shape and not a bar.
506+ assert!(tallest > 25., "loudest column only {tallest} px of 30");
507+ assert!(
508+ flattest < 8.,
509+ "quietest column {flattest} px -- no dips drawn"
510+ );
511+ // A video-only source draws no waveform at all rather than a flat fake.
512+ assert!(
513+ engine::waveform::peaks(asset("test_baseline.mp4"), 0, WAVE_BPS)
514+ .expect("open the fixture")
515+ .is_none()
516+ );
517+}
518+
519+#[test]
520+fn every_mark_on_a_clip_is_legible_on_it() {
521+ // The body a name and a waveform are drawn on is the clip's kind
522+ // ([`clip_kind`]); the source tint is the border and the library
523+ // swatch, and is measured for telling itself apart rather than for
524+ // carrying text.
525+ // Every palette a person can pick, not merely the one in force.
526+ for id in crate::ui::theme::PaletteId::ALL {
527+ let p = id.palette();
528+ for (i, tint) in [p.CLIP_VIDEO, p.CLIP_AUDIO, p.CLIP_IMAGE, p.CLIP_TEXT]
529+ .iter()
530+ .enumerate()
531+ {
532+ // WCAG 1.4.3: the clip's name is body text on its tint.
533+ assert!(
534+ contrast(p.FG_PRIMARY, *tint) >= 4.5,
535+ "{id:?} source {i}: label contrast {:.2}",
536+ contrast(p.FG_PRIMARY, *tint)
537+ );
538+ // WCAG 1.4.11: the waveform is a non-text graphic on it.
539+ assert!(
540+ contrast(p.FG_SECONDARY, *tint) >= 3.,
541+ "{id:?} source {i}: waveform contrast {:.2}",
542+ contrast(p.FG_SECONDARY, *tint)
543+ );
544+ }
545+ // A selected clip's bed is the same two marks on a different colour.
546+ assert!(contrast(p.FG_PRIMARY, p.BG_SELECTED) >= 4.5, "{id:?}");
547+ assert!(contrast(p.FG_SECONDARY, p.BG_SELECTED) >= 3., "{id:?}");
548+ // The bed a gap shows through has to read as a hole in the lane --
549+ // the clip is the object, the bed is the hole -- and the playhead
550+ // has to be findable on both.
551+ assert!(contrast(p.CLIP_VIDEO, p.BG_TIMELINE) >= 1.5, "{id:?}");
552+ assert!(contrast(p.ACCENT_PLAYHEAD, p.BG_TIMELINE) >= 3., "{id:?}");
553+ assert!(contrast(p.ACCENT_PLAYHEAD, p.CLIP_VIDEO) >= 3., "{id:?}");
554+ }
555+ // The sanity check on the ratio itself: black on white is 21:1.
556+ assert!((contrast(0xffffff, 0x000000) - 21.).abs() < 0.01);
557+}
558+
559+#[test]
560+fn source_tints_differ_per_source_and_cycle() {
561+ // The bug: the first entry *was* `BG_RAISED`, so the first file imported
562+ // -- the one every session has -- wore the panel's own background and
563+ // had no visible swatch at all.
564+ assert_ne!(source_tint(0), BG_RAISED());
565+ // ...in every family, since the swatch is drawn on whichever panel is
566+ // in force (`ui::theme`) and a tint that vanished into one of them is a
567+ // file with no colour at all.
568+ for id in crate::ui::theme::PaletteId::ALL {
569+ let p = id.palette();
570+ for (i, &tint) in p.SOURCE_TINTS.iter().enumerate() {
571+ assert_ne!(tint, p.BG_RAISED, "{id:?} tint {i} is the panel");
572+ }
573+ }
574+ // Neighbouring sources must not share one, or an import is invisible.
575+ assert_ne!(source_tint(0), source_tint(1));
576+ assert_ne!(source_tint(1), source_tint(2));
577+ assert_ne!(source_tint(2), source_tint(3));
578+ // Past the palette it wraps -- never an index panic.
579+ assert_eq!(source_tint(4), source_tint(0));
580+ assert_eq!(source_tint(9), source_tint(1));
581+ assert_eq!(source_tint(usize::MAX), SOURCE_TINTS()[usize::MAX % 4]);
582+}
583+
584+/// Not "they are different numbers" -- different *enough to see*, against
585+/// each other and against the surface a swatch is drawn on. The palette is
586+/// deliberately dark and low-saturation, so the margin is thin and a new
587+/// tint picked by eye can land inside it without anyone noticing.
588+#[test]
589+fn source_tints_are_all_discernible() {
590+ // Summed channel distance: `BG_RAISED` to the warm tint is 18, and that
591+ // step is the one already accepted as readable on a lane.
592+ let apart = |a: u32, b: u32| {
593+ (0..3)
594+ .map(|i| {
595+ let shift = i * 8;
596+ ((a >> shift) & 0xff).abs_diff((b >> shift) & 0xff)
597+ })
598+ .sum::<u32>()
599+ };
600+ // Every family, not the one in force: a palette is picked at runtime
601+ // now, and four tints tuned by eye on one ground are exactly where a
602+ // pair lands inside the margin on another.
603+ for id in crate::ui::theme::PaletteId::ALL {
604+ let p = id.palette();
605+ for (i, &tint) in p.SOURCE_TINTS.iter().enumerate() {
606+ assert!(
607+ apart(tint, p.BG_RAISED) >= 16,
608+ "{id:?} tint {i} is {} from the panel it sits on",
609+ apart(tint, p.BG_RAISED)
610+ );
611+ for (j, &other) in p.SOURCE_TINTS.iter().enumerate().skip(i + 1) {
612+ assert!(
613+ apart(tint, other) >= 16,
614+ "{id:?} tints {i} and {j} are only {} apart",
615+ apart(tint, other)
616+ );
617+ }
618+ }
619+ // The two a person sees side by side first must be further apart
620+ // than the floor: source 0 and source 1 are the first import and
621+ // the second.
622+ assert!(apart(p.SOURCE_TINTS[0], p.SOURCE_TINTS[1]) >= 32, "{id:?}");
623+ }
624+}
625+
626+/// A `.srt` dropped on the window is nobody's stream: it has no source
627+/// entry, and the lookup that used to fall back to index 0 painted it with
628+/// the first file's colour -- a swatch saying it came out of a film it
629+/// never touched.
630+#[test]
631+fn a_standalone_subtitle_wears_no_file_tint() {
632+ let sources = [
633+ Source {
634+ path: PathBuf::from("/films/a.mkv"),
635+ audio_stream: 0,
636+ },
637+ Source {
638+ path: PathBuf::from("/films/b.mp4"),
639+ audio_stream: 0,
640+ },
641+ // A second stream of the first file is a second source and the
642+ // same colour.
643+ Source {
644+ path: PathBuf::from("/films/a.mkv"),
645+ audio_stream: 1,
646+ },
647+ ];
648+ assert_eq!(
649+ file_tint(&sources, Path::new("/films/a.mkv")),
650+ Some(source_tint(0))
651+ );
652+ assert_eq!(
653+ file_tint(&sources, Path::new("/films/b.mp4")),
654+ Some(source_tint(1))
655+ );
656+ assert_eq!(file_tint(&sources, Path::new("/subs/a.eng.srt")), None);
657+ assert_eq!(file_tint(&[], Path::new("/films/a.mkv")), None);
658+ // The same file under two spellings is one file and one colour: a
659+ // source is stored symlink-resolved, everything else as it was typed.
660+ let here = std::fs::canonicalize(".").expect("the crate directory");
661+ let sources = [Source {
662+ path: here.join("Cargo.toml"),
663+ audio_stream: 0,
664+ }];
665+ assert_eq!(
666+ file_tint(&sources, Path::new("Cargo.toml")),
667+ Some(source_tint(0)),
668+ "a relative spelling of the source file wears the source's colour"
669+ );
670+}
671+
672+/// A film's two ASS tracks with the timeline trimmed to twenty seconds:
673+/// one of them still has cues there and one has none, and the card said
674+/// nothing whatever about the second while the Subtitles list went on
675+/// showing it with its eighty-three cues.
676+///
677+/// And the 25 GB remux's thirty-five: naming those wrapped the row to ten
678+/// lines and pushed Destination under the fold, so past the value box's
679+/// three lines the same line counts instead.
680+#[test]
681+fn the_card_names_the_subtitle_it_leaves_off_and_counts_them_when_it_cannot() {
682+ let film = "/films/An Episode 01.mkv";
683+ let two = [
684+ sub(film, Some(1), "[ASS]"),
685+ sub(film, Some(2), "[ASS] [FOR DUB]"),
686+ ];
687+ // What the engine answers about the one pick that reached it, and what
688+ // this side knows about the row that did not.
689+ let named = subtitle_plan("[ASS] → embedded".to_string(), &two, &[0]);
690+ assert_eq!(named, "[ASS] → embedded; [ASS] [FOR DUB] — no cues here");
691+ assert!(
692+ named.chars().count() <= SUB_PLAN_CHARS,
693+ "two tracks fit the value box: {named}"
694+ );
695+ // Thirty-five off one file: twenty-two carry cues here, nine are
696+ // pictures, one could not be read, three have nothing on this timeline.
697+ let many: Vec<_> = (0..35)
698+ .map(|i| {
699+ let mut track = sub("/films/A Remux.mkv", Some(i), "eng — Subtitles");
700+ track.bitmap = (22..31).contains(&i);
701+ track.refused = (i == 31).then(|| "VobSub is pictures".to_string());
702+ track
703+ })
704+ .collect();
705+ // The picks are every track with a cue on the timeline: the twenty-two
706+ // and the nine picture ones, which the engine drops itself.
707+ let picks: Vec<usize> = (0..31usize).collect();
708+ let counted = subtitle_plan("22 tracks → embedded (…)".to_string(), &many, &picks);
709+ assert_eq!(counted, "22 of 35 → embedded; 9 pictures; 1 unread; 3 no cues here");
710+ assert!(
711+ counted.chars().count() <= SUB_PLAN_CHARS,
712+ "thirty-five tracks still fit the value box: {counted}"
713+ );
714+ // Nothing on the timeline at all is still the engine's word for it.
715+ assert_eq!(subtitle_plan("none".to_string(), &[], &[]), "none");
716+}
717+
718+/// The list is in the order tracks were added, which is not the order a
719+/// person reads it in: importing a second film puts its tracks after the
720+/// first film's, and importing a third `.srt` for the first film puts that
721+/// one last of all. The rows still read as three sources.
722+#[test]
723+fn subtitle_rows_group_a_source_however_they_were_added() {
724+ let tracks = [
725+ sub("/films/a.mkv", Some(1), "eng"),
726+ sub("/films/b.mkv", Some(1), "eng"),
727+ sub("/films/a.mkv", Some(2), "fre"),
728+ sub("/subs/late.srt", None, "late.srt"),
729+ sub("/films/b.mkv", Some(3), "ger"),
730+ ];
731+ let groups = subtitle_rows(&tracks);
732+ assert_eq!(
733+ groups.iter().map(|g| g.name.as_str()).collect::<Vec<_>>(),
734+ ["a", "b", "late"],
735+ "one group per file, in the order the files first appear"
736+ );
737+ assert_eq!(
738+ groups
739+ .iter()
740+ .map(|g| g.rows.iter().map(|r| r.label.as_str()).collect::<Vec<_>>())
741+ .collect::<Vec<_>>(),
742+ [vec!["eng", "fre"], vec!["eng", "ger"], vec!["late.srt"]],
743+ "a file's tracks are contiguous and in add order"
744+ );
745+ // Numbered within the file, the way `row_name` numbers audio streams:
746+ // two tracks that both say "eng" are told apart by nothing else.
747+ assert_eq!(
748+ groups
749+ .iter()
750+ .map(|g| g.rows.iter().map(|r| r.number).collect::<Vec<_>>())
751+ .collect::<Vec<_>>(),
752+ [vec![1, 2], vec![1, 2], vec![1]]
753+ );
754+ // The swatch key is the file, so a group and that file's media rows
755+ // wear one colour -- and the standalone one has none.
756+ let sources = [Source {
757+ path: PathBuf::from("/films/a.mkv"),
758+ audio_stream: 0,
759+ }];
760+ assert_eq!(
761+ file_tint(&sources, &groups[0].path),
762+ Some(source_tint(0)),
763+ "the group carries the path the tint is asked by"
764+ );
765+ assert_eq!(file_tint(&sources, &groups[2].path), None);
766+}
767+
768+/// What the strip header, the section heading and the toggle's notice all
769+/// say. Two films each carrying an "eng" track are one word apart until the
770+/// film is in the name; a film carrying two is one word apart from itself.
771+#[test]
772+fn the_picked_subtitle_is_named_with_the_film_it_came_out_of() {
773+ let tracks = [
774+ sub("/films/a.mkv", Some(1), "eng"),
775+ sub("/films/b.mkv", Some(1), "eng"),
776+ sub("/films/a.mkv", Some(2), "eng"),
777+ sub("/films/b.mkv", Some(2), "und"),
778+ sub("/subs/late.srt", None, "late.srt"),
779+ ];
780+ let name = |track| sub_pick_name(&tracks, track).expect("a track that is there");
781+ // The two "eng"s of two films: one file gave several so its tracks are
782+ // numbered, the other gave one so it is not.
783+ assert_eq!(name(0), "eng 1 — a");
784+ assert_eq!(name(2), "eng 2 — a");
785+ assert_eq!(name(1), "eng 1 — b");
786+ assert_ne!(name(0), name(1), "two films' eng tracks read apart");
787+ for picked in [name(0), name(1), name(2)] {
788+ assert!(picked.contains(" — a") || picked.contains(" — b"));
789+ }
790+ // "und" is the tag for "nobody said", humanised once by
791+ // `subtitle_rows` and not again here.
792+ assert_eq!(name(3), "unknown language 2 — b");
793+ // A standalone `.srt` is its own file and its label already says so:
794+ // one track, so no number, and no stem after it saying it again.
795+ assert_eq!(name(4), "late.srt");
796+ // The silence `subtitle_track` gives at the same moment.
797+ assert_eq!(sub_pick_name(&tracks, 5), None);
798+ assert_eq!(sub_pick_name(&[], 0), None);
799+}
800+
801+/// The door this editor answers "don't make me import the film again" with,
802+/// and it is in the panel where the tracks it adds are listed: the Text
803+/// tab's own button reads a file's subtitle tracks onto the open timeline
804+/// -- a release's `.mkv`, an `.srt` beside it -- while the file itself
805+/// joins nothing. It is the *action* and not a second implementation of it,
806+/// so the button, the stroke and the actions card cannot drift apart, and
807+/// it is oracle-gated like every other action button, so with no timeline
808+/// open it dims and says why instead of opening a chooser for nothing.
809+#[test]
810+fn the_text_tab_carries_the_add_subtitles_door() {
811+ let library = src_text("ui/library.rs");
812+ let at = library
813+ .find("\"add-subtitles\"")
814+ .expect("no add-subtitles control in the library column");
815+ let block = &library[at..(at + 1400).min(library.len())];
816+ assert!(
817+ block.contains("ActionId::AddSubtitleTrack"),
818+ "the button is a door of its own rather than the action: {block}"
819+ );
820+ assert!(
821+ block.contains("pick_and_add_subtitles"),
822+ "the button does not open the subtitle chooser: {block}"
823+ );
824+ // `action_control` is the oracle-gated one: dimmed with the refusal in
825+ // the oracle's own words. `control` alone would be lit with no timeline.
826+ assert!(
827+ library[..at].ends_with("self.action_control(\n "),
828+ "the add-subtitles button is not oracle-gated"
829+ );
830+ // ...and the empty tab names that button, rather than pointing at a
831+ // toolbar the person is not looking at.
832+ assert!(
833+ crate::LibraryTab::Text.empty().contains("Add subtitles"),
834+ "{}",
835+ crate::LibraryTab::Text.empty()
836+ );
837+}
838+
839+/// The one thing regrouping must not break: `sub_track` is a flat index
840+/// into the add-order list, a click sets it and a save writes it into the
841+/// `.edith`. Every row must still name the track it was made from -- rows
842+/// for refused tracks included, because they take a number in that list
843+/// whether or not anyone can pick them.
844+#[test]
845+fn a_subtitle_row_names_the_flat_track_it_was_made_from() {
846+ let mut tracks = vec![
847+ sub("/films/a.mkv", Some(1), "eng"),
848+ sub("/films/b.mkv", Some(1), "eng"),
849+ sub("/films/a.mkv", Some(2), "fre"),
850+ ];
851+ // Track 1 of b is pictures: still a row, still index 1 of the list.
852+ tracks[1].bitmap = true;
853+ tracks[1].refused = Some("PGS subtitles are pictures".to_string());
854+ let groups = subtitle_rows(&tracks);
855+ let flat: Vec<(usize, &str)> = groups
856+ .iter()
857+ .flat_map(|g| g.rows.iter().map(|r| (r.track, r.label.as_str())))
858+ .collect();
859+ assert_eq!(flat, [(0, "eng"), (2, "fre"), (1, "eng")]);
860+ for (track, label) in flat {
861+ assert_eq!(
862+ tracks[track].label, label,
863+ "row {track} picks the track it names"
864+ );
865+ }
866+ // (c) The refused one is here, saying why, and greyable by that alone.
867+ let refused = &groups[1].rows[0];
868+ assert_eq!(
869+ refused.refused.as_deref(),
870+ Some("PGS subtitles are pictures")
871+ );
872+ assert_eq!(refused.detail, "PGS subtitles are pictures");
873+ assert!(refused.bitmap);
874+ // ...and it was counted: the row after it in add order is still 2.
875+ assert_eq!(groups[0].rows[1].track, 2);
876+}
877+
878+/// The × on a row shifts every track after it down one, and the pick is
879+/// what an export writes into the file -- so a pick that stayed put would
880+/// silently change which track the next export carries. Every relation
881+/// between the pick and the row that went, on a list of three.
882+#[test]
883+fn removing_a_subtitle_row_carries_the_pick_with_it() {
884+ // A row *before* the pick: the same track stays picked, one index down.
885+ assert_eq!(sub_pick_after_removal(2, 0, 2), 1);
886+ assert_eq!(sub_pick_after_removal(2, 1, 2), 1);
887+ // A row *after* it: the pick has not moved and neither has its index.
888+ assert_eq!(sub_pick_after_removal(0, 2, 2), 0);
889+ assert_eq!(sub_pick_after_removal(1, 2, 2), 1);
890+ // The picked row itself: the one that slid into its place...
891+ assert_eq!(sub_pick_after_removal(1, 1, 2), 1);
892+ // ...and the last row when the picked one was the last, since there is
893+ // nothing after it to slide.
894+ assert_eq!(sub_pick_after_removal(2, 2, 2), 1);
895+ // The last row of all: an emptied list is legal for subtitles, and the
896+ // section is not drawn at all at that point.
897+ assert_eq!(sub_pick_after_removal(0, 0, 0), 0);
898+}
899+
900+/// The same claim from the click's end, on the order imports actually
901+/// arrive in: two films opened one after the other and an `.srt` dropped
902+/// last interleave in the flat list, and the display reorders them. What a
903+/// click sets is the row's own `track`, so the *n*th row on screen has to
904+/// pick the track it shows and the echoes have to name that same file.
905+#[test]
906+fn a_click_on_a_regrouped_row_picks_the_track_that_row_shows() {
907+ let tracks = [
908+ sub("/films/a.mkv", Some(1), "eng"),
909+ sub("/films/b.mkv", Some(1), "eng"),
910+ sub("/films/a.mkv", Some(2), "fre"),
911+ sub("/subs/late.srt", None, "late.srt"),
912+ sub("/films/b.mkv", Some(3), "ger"),
913+ ];
914+ let rows: Vec<_> = subtitle_rows(&tracks)
915+ .into_iter()
916+ .flat_map(|group| {
917+ group
918+ .rows
919+ .into_iter()
920+ .map(move |row| (group.path.clone(), row))
921+ })
922+ .collect();
923+ // Read top to bottom, the rows are no longer in add order...
924+ assert_eq!(
925+ rows.iter().map(|(_, row)| row.track).collect::<Vec<_>>(),
926+ [0, 2, 1, 4, 3]
927+ );
928+ for (path, row) in &rows {
929+ // ...and what the click writes into `sub_track` -- and a save into
930+ // the `.edith` -- still lands on the track the row is showing.
931+ let picked = &tracks[row.track];
932+ assert_eq!(&picked.path, path, "row {} picks another file", row.track);
933+ assert_eq!(lang_human(&picked.label), row.label);
934+ // And the heading, the strip and the notice name that same file
935+ // back, so a click cannot leave the echoes pointing elsewhere.
936+ let echo = sub_pick_name(&tracks, row.track).expect("the row's own track");
937+ let stem = path.file_stem().expect("a fixture path").to_string_lossy();
938+ assert!(
939+ echo.contains(&*stem),
940+ "picked {}, echoed {echo}",
941+ path.display()
942+ );
943+ }
944+}
945+
946+/// "und" is what a muxer writes when nobody said what the language is. A
947+/// row showing it verbatim names a language nobody speaks.
948+#[test]
949+fn an_untagged_language_says_it_is_unknown() {
950+ assert_eq!(lang_human("und"), "unknown language");
951+ assert_eq!(lang_human("eng"), "eng");
952+ assert_eq!(lang_human("fre — Commentary"), "fre — Commentary");
953+ // Reaching the subtitle rows too: a track whose only name was the tag.
954+ let groups = subtitle_rows(&[sub("/films/a.mkv", Some(1), "und")]);
955+ assert_eq!(groups[0].rows[0].label, "unknown language");
956+ // The pair, read as the pair: the row title comes off `language` and
957+ // `name` and never out of the flattened label, which is what let an
958+ // "und" beside a title through as a language nobody speaks. A refused
959+ // track states neither and keeps its label.
960+ let titled = |language: &str, name: &str, label: &str| engine::subtitle::SubtitleTrack {
961+ path: PathBuf::from("/films/a.mkv"),
962+ track: Some(1),
963+ language: language.into(),
964+ name: name.into(),
965+ label: label.into(),
966+ cues: Vec::new(),
967+ bitmap: false,
968+ refused: None,
969+ };
970+ for (language, name, label, title) in [
971+ ("fra", "Signs", "fra — Signs", "fra — Signs"),
972+ ("und", "Signs", "Signs", "Signs"),
973+ ("und", "", "und", "unknown language"),
974+ ("", "late.srt", "late.srt", "late.srt"),
975+ ("", "", "eng", "eng"),
976+ ] {
977+ let rows = subtitle_rows(&[titled(language, name, label)]);
978+ assert_eq!(rows[0].rows[0].label, title, "{language:?} {name:?}");
979+ }
980+}
981+
982+/// The bug: an empty timeline is end-of-stream from its one black frame
983+/// onward, so the pump had `done` set before anything was ever pressed --
984+/// and the transport's restart branch read that as "played out, start from
985+/// the top". It started a clock against a zero-length timeline, which was
986+/// `done` again by the next repaint, so every further press restarted it
987+/// too: the button read "Pause" and no press of it ever paused.
988+///
989+/// What holds it now is one predicate, checked here against real sessions
990+/// on both sides -- the emptied one refuses, a timeline with clips on it
991+/// does not.
992+#[test]
993+fn an_empty_timeline_has_nothing_to_play() {
994+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
995+ // Silent like the engine suite: this opens the real device.
996+ session.set_gain(0.0);
997+ // A timeline with clips on it plays, and always did: the guard must not
998+ // touch that side.
999+ assert!(!session.is_empty());
1000+ assert!(!nothing_to_play(Some(&session)));
1001+
1002+ // Every clip taken off, which is a state and not a failure.
1003+ while session.delete_clip(Lane::V1, 0) {}
1004+ while session.delete_clip(Lane::A1, 0) {}
1005+ assert!(session.is_empty(), "the timeline is empty");
1006+ assert_eq!(session.timeline_duration(), 0.0);
1007+
1008+ // What the pump does every render, and what set `done` before the fix:
1009+ // the black frame goes by and the session is at its end at once.
1010+ for _ in 0..40 {
1011+ while session.try_frame().is_some() {}
1012+ std::thread::sleep(Duration::from_millis(10));
1013+ }
1014+ assert!(
1015+ session.is_eos(),
1016+ "an empty timeline is done before it starts"
1017+ );
1018+
1019+ // So the press is refused rather than sent down the restart branch --
1020+ // and with no session at all it is the same refusal.
1021+ assert!(nothing_to_play(Some(&session)));
1022+ assert!(nothing_to_play(None));
1023+ assert!(!session.is_playing(), "and nothing was started");
1024+}
1025+
1026+/// The slider writes the same numbers the keys do, and mute is not one of
1027+/// them: dragging while muted picks the level unmuting comes back to.
1028+#[test]
1029+fn the_slider_lands_on_the_grid_the_keys_move_on() {
1030+ let mut volume = Volume::default();
1031+ // Both ends exactly, and clamped past them.
1032+ volume.set_along(0.);
1033+ assert_eq!(volume.gain(), 0.0);
1034+ assert_eq!(volume.label(), "Vol 0%");
1035+ volume.set_along(1.5);
1036+ assert_eq!(volume.gain(), 1.0);
1037+ assert_eq!(volume.along(), 1.0);
1038+
1039+ // Halfway is 50%, and a key press from there is 5% -- the same step
1040+ // count as before, on a finer grid.
1041+ volume.set_along(0.5);
1042+ assert_eq!(volume.label(), "Vol 50%");
1043+ volume.step(true);
1044+ assert_eq!(volume.label(), "Vol 55%");
1045+ volume.step(false);
1046+ assert_eq!(volume.gain(), 0.5);
1047+
1048+ // A number no step lands on comes back as the nearest one, so the label
1049+ // and the fill are the same value the device was handed.
1050+ volume.set_along(0.333);
1051+ assert_eq!(volume.label(), "Vol 33%");
1052+ assert_eq!(volume.along(), 0.33);
1053+
1054+ // Muted, the drag moves the level and nothing comes out.
1055+ volume.muted = true;
1056+ volume.set_along(0.8);
1057+ assert_eq!(volume.gain(), 0.0);
1058+ assert_eq!(volume.label(), "Muted 80%");
1059+ volume.muted = false;
1060+ assert_eq!(volume.gain(), 0.8);
1061+}
1062+
1063+/// The slider lands where it paints: the arithmetic `Player::drag_volume`
1064+/// runs over the bar's own painted width, which is the one thing a test of
1065+/// it can share without re-deriving it.
1066+#[test]
1067+fn the_volume_slider_lands_where_it_paints() {
1068+ let bar = Bounds {
1069+ origin: point(px(420.), px(508.)),
1070+ size: size(px(VOLUME_W), px(CONTROL_H)),
1071+ };
1072+ let at = |x: f32| {
1073+ let mut volume = Volume::default();
1074+ volume.set_along(frac_along(px(x), bar));
1075+ volume
1076+ };
1077+ assert_eq!(at(420.).gain(), 0.0, "the left end is silence");
1078+ assert_eq!(at(420. + VOLUME_W).gain(), 1.0, "the right end is full");
1079+ assert_eq!(at(-4000.).gain(), 0.0, "off the left clamps");
1080+ assert_eq!(at(9999.).gain(), 1.0, "off the right clamps");
1081+ // Every pixel along it: a level the keys could also reach, painted back
1082+ // where the hand pressed to within the half step the rounding costs.
1083+ for step in 0..=(VOLUME_W as u32) {
1084+ let along = step as f32 / VOLUME_W;
1085+ let volume = at(420. + along * VOLUME_W);
1086+ let painted = volume.along();
1087+ let slack = 0.5 / f32::from(Volume::MAX_STEPS) + 1e-4;
1088+ assert!(
1089+ (painted - along).abs() <= slack,
1090+ "pressed at {along}, paints at {painted}"
1091+ );
1092+ }
1093+}
crates/app/src/tests/media.rsadded+1035 -0
@@ -0,0 +1,1035 @@
1+//! What the workers hand back: the progress lines, the file named on the
2+//! command line, the scans, the codecs offered, and the subtitles found.
3+
4+use super::*;
5+
6+/// The import line's own state machine, driven the way a repaint drives
7+/// it: the worker writes a stage, the poll notices it changed and restarts
8+/// the stall clock, and the line's words change only when a stage has
9+/// actually stood still. The whole point is that a stuck read reads as a
10+/// stuck read and never as a frozen window.
11+#[test]
12+fn an_import_line_says_a_stage_has_stopped_moving_and_only_then() {
13+ use std::sync::Arc;
14+ use std::sync::atomic::{AtomicU8, Ordering::Relaxed};
15+ let stage = Arc::new(AtomicU8::new(ImportStage::Header as u8));
16+ let started = Instant::now() - Duration::from_secs(9);
17+ let mut import = Import {
18+ path: PathBuf::from("/films/A Film.mkv"),
19+ started,
20+ stage: Arc::clone(&stage),
21+ seen: ImportStage::Header,
22+ // As if the header had been running for those nine seconds.
23+ since: started,
24+ cancelled: Arc::default(),
25+ };
26+ // Nine seconds inside one stage: past the wait a person tolerates, so
27+ // the line stops pretending it is a progress line.
28+ let since = import.poll();
29+ assert!(since > IMPORT_STALL, "{since}");
30+ let stalled = import_line("A Film.mkv", import.seen, 9., since, 0, false);
31+ assert!(stalled.contains("still reading the header"), "{stalled}");
32+ assert!(stalled.contains("not frozen"), "{stalled}");
33+ assert!(stalled.contains("0:09 elapsed"), "{stalled}");
34+ // The worker moves on: the stall clock restarts even though the elapsed
35+ // one does not, which is the distinction the two clocks exist for.
36+ stage.store(ImportStage::Subtitles as u8, Relaxed);
37+ let since = import.poll();
38+ assert_eq!(import.seen, ImportStage::Subtitles);
39+ assert!(since < IMPORT_STALL, "{since}");
40+ let moving = import_line("A Film.mkv", import.seen, 9., since, 2, false);
41+ assert!(
42+ moving.starts_with("IMPORTING A Film.mkv · reading the subtitle tracks"),
43+ "{moving}"
44+ );
45+ assert!(!moving.contains("still"), "{moving}");
46+ // ...and what is behind it in the queue, which is what a drop of three
47+ // files or an argv of three files leaves waiting.
48+ assert!(moving.ends_with("· 2 more waiting"), "{moving}");
49+ assert!(!stalled.ends_with("waiting"), "an empty queue says nothing");
50+ // A stage that does not move is not the same fact as a stage that came
51+ // back to the same value: the poll only restarts on a change.
52+ let held = import.since;
53+ import.poll();
54+ assert_eq!(import.since, held, "an unchanged stage must not reset it");
55+}
56+
57+/// The launch, from argv to the window being up: nothing named on the
58+/// command line is read before there is a window, so all a launch does is
59+/// sort argv into the file that becomes the timeline and the queue that is
60+/// read through -- and a run with no arguments has neither, exactly as it
61+/// had none before.
62+#[test]
63+fn a_launch_queues_the_file_it_names_instead_of_opening_it() {
64+ let film = PathBuf::from("/films/Dune.mkv");
65+ let extra = PathBuf::from("/films/Titles.mov");
66+ let (arg, queue) = launch_queue([film.clone(), extra.clone()].into_iter());
67+ assert_eq!(arg.as_deref(), Some(film.as_path()), "argv[1] is the open");
68+ // In the order they were named, the timeline's file first: six header
69+ // walks racing over one disk finish no sooner than six in a row, and
70+ // the one the person is waiting to watch goes first.
71+ assert_eq!(queue, [film, extra], "argv, in arrival order");
72+ // ...and no argument at all is still the empty window: nothing to open
73+ // and nothing to read.
74+ let (arg, queue) = launch_queue(std::iter::empty());
75+ assert_eq!(arg, None);
76+ assert!(queue.is_empty(), "no argv, nothing queued");
77+}
78+
79+/// Which door a queued file goes through. One queue carries the file argv
80+/// named and every import behind it, so this fork -- made when the worker
81+/// starts and carried to the landing as a [`Landed`] -- is the whole state
82+/// machine: the named file becomes the timeline (a `.edith` restoring a
83+/// whole one), everything else joins the library, including the very same
84+/// film dropped again once the open has landed.
85+#[test]
86+fn the_file_argv_named_lands_as_the_timeline_and_everything_behind_it_as_imports() {
87+ let film = PathBuf::from("/films/Dune.mkv");
88+ let extra = PathBuf::from("/films/Titles.mov");
89+ let project = PathBuf::from("/films/Dune.edith");
90+ assert_eq!(arrival(Some(&film), &film), Landing::Open);
91+ assert_eq!(arrival(Some(&project), &project), Landing::Project);
92+ assert_eq!(arrival(Some(&film), &extra), Landing::Import);
93+ // Cleared as it lands: a drop of the film already on the timeline is an
94+ // import, which is what a drop has always been.
95+ assert_eq!(arrival(None, &film), Landing::Import);
96+ // ...except a `.edith`, which is a whole timeline and has nothing to be
97+ // imported into: dropped or picked, it lands where argv's does, and its
98+ // open is the worker's like every other.
99+ assert_eq!(arrival(None, &project), Landing::Project);
100+ assert_eq!(arrival(Some(&film), &project), Landing::Project);
101+}
102+
103+/// What the window says while the file argv named is being read: the file's
104+/// name, the read that is running, and a clock proving the window is
105+/// answering -- in the *opening* wording, because the one person who typed
106+/// that name is not importing anything.
107+#[test]
108+fn the_named_file_is_read_under_an_opening_line_not_an_importing_one() {
109+ let opening = import_line("Dune.mkv", ImportStage::Header, 0.4, 0.4, 1, true);
110+ assert!(
111+ opening.starts_with("OPENING Dune.mkv · reading the header"),
112+ "{opening}"
113+ );
114+ assert!(opening.ends_with("· 1 more waiting"), "{opening}");
115+ // Twelve seconds into a cold 25 GB header walk, which is the whole
116+ // reason the window is up: it says the read is still moving through the
117+ // same stage and that this is not a freeze.
118+ let stalled = import_line("Dune.mkv", ImportStage::Header, 12., 12., 0, true);
119+ assert!(stalled.starts_with("OPENING Dune.mkv · still"), "{stalled}");
120+ assert!(stalled.contains("not frozen"), "{stalled}");
121+ assert!(stalled.contains("0:12 elapsed"), "{stalled}");
122+ // The files behind it are imports and still say so.
123+ let import = import_line("Titles.mov", ImportStage::Header, 0.4, 0.4, 0, false);
124+ assert!(import.starts_with("IMPORTING Titles.mov"), "{import}");
125+}
126+
127+/// One gesture over the real gate, with the plumbing around it spelled out:
128+/// a write reseeks (the worker owes a frame again), a landed frame clears
129+/// that and flushes what is held, and the release flushes whatever the
130+/// worker is doing. Forty snapped steps and four frames delivered must cost
131+/// five writes -- the press's and one per frame -- and not forty, which is
132+/// the 22-30 s freeze this exists to remove.
133+#[test]
134+fn a_bar_wide_sweep_writes_once_per_frame_delivered() {
135+ let mut stash: Option<i32> = None;
136+ let mut written = Vec::new();
137+ let mut busy = false;
138+ for step in 0..40 {
139+ if let Some(value) = stash_or_write(&mut stash, step, step == 0, busy) {
140+ // What `write_color` does: the write supersedes the stash and
141+ // reseeks, so the worker owes a frame from here.
142+ stash = None;
143+ written.push(value);
144+ busy = true;
145+ }
146+ // A frame lands every tenth sample: `pump` clears the seek and the
147+ // render flushes what the drag held back.
148+ if step % 10 == 9 {
149+ busy = false;
150+ if let Some(value) = stash.take() {
151+ written.push(value);
152+ busy = true;
153+ }
154+ }
155+ }
156+ // The release, whatever the worker is doing.
157+ written.extend(stash.take());
158+ assert_eq!(written, vec![0, 9, 19, 29, 39], "one write per frame landed");
159+}
160+
161+/// The one value a gesture may never lose: where the hand let go. The
162+/// release samples into a busy worker -- so the sample is held -- and the
163+/// flush behind it is what writes it.
164+#[test]
165+fn a_release_lands_the_value_the_hand_let_go_on() {
166+ let mut stash = None;
167+ assert_eq!(stash_or_write(&mut stash, 7, false, true), None);
168+ assert_eq!(stash_or_write(&mut stash, 11, false, true), None);
169+ assert_eq!(stash.take(), Some(11), "the release writes the last sample");
170+ // The press is never held: it is the undo step the gesture rolls back
171+ // to, and one taken a frame late is a snapshot of the wrong grade.
172+ assert_eq!(stash_or_write(&mut stash, 3, true, true), Some(3));
173+ assert_eq!(stash, None);
174+ // Nothing to hold when the worker is idle: the write goes straight out.
175+ assert_eq!(stash_or_write(&mut stash, 5, false, false), Some(5));
176+ assert_eq!(stash, None);
177+}
178+
179+/// A seek says nothing until it has stood: an ordinary one is a flicker and
180+/// a cold read of a big file is the case worth words.
181+#[test]
182+fn a_seek_says_so_only_once_it_has_stood() {
183+ assert_eq!(seek_line(None), None, "no seek, no line");
184+ assert_eq!(seek_line(Some(Duration::from_millis(300))), None);
185+ let line = seek_line(Some(SEEK_STALL + Duration::from_secs(7))).expect("past the stall");
186+ assert!(line.contains("still opening the picture"), "{line}");
187+ assert!(line.contains("not frozen"), "{line}");
188+ assert!(line.contains("0:09 elapsed"), "{line}");
189+}
190+
191+/// The silence card's own state machine, driven the way a repaint drives
192+/// it: a worker moves its mark, the poll notices and restarts the stall
193+/// clock, and the line says a read has stopped only when it actually has.
194+/// The card is up through all of it -- that is the whole change, since the
195+/// same decode used to run on the render thread and hold the frame for
196+/// fifty-one seconds on a 25 GB film.
197+#[test]
198+fn a_silence_card_is_up_while_its_scan_runs_and_says_where_it_has_got_to() {
199+ use std::sync::Arc;
200+ use std::sync::atomic::Ordering::Relaxed;
201+ let progress = Arc::new(engine::silence::Progress::default());
202+ // Two hours and eight minutes, as the header claims it.
203+ progress.total.store(7680, Relaxed);
204+ let started = Instant::now() - Duration::from_secs(9);
205+ let mut scan = SilenceScan {
206+ key: (PathBuf::from("/films/A Film.mkv"), 0, 0, 192_000),
207+ started,
208+ progress: Arc::clone(&progress),
209+ seen: 0,
210+ since: started,
211+ };
212+ // Nine seconds and the mark has not moved: past the wait a person
213+ // tolerates, so the line stops pretending it is a progress line.
214+ let since = scan.poll();
215+ assert!(since > IMPORT_STALL, "{since}");
216+ let stalled = silence_line(0., 768., 9., since);
217+ assert!(stalled.contains("still reading the sound"), "{stalled}");
218+ assert!(stalled.contains("not frozen"), "{stalled}");
219+ assert!(stalled.contains("0:00 of ~12:48 scanned"), "{stalled}");
220+ assert!(stalled.contains("0:09 elapsed"), "{stalled}");
221+ // The worker reports, and the stall clock restarts even though the
222+ // elapsed one does not -- the two clocks' whole distinction.
223+ let mut last = 0;
224+ for deci in [83, 1_140, 4_002] {
225+ progress.scanned.store(deci, Relaxed);
226+ let since = scan.poll();
227+ assert!(since < IMPORT_STALL, "{since}");
228+ assert!(scan.seen > last, "{} after {last}", scan.seen);
229+ last = scan.seen;
230+ }
231+ let moving = silence_line(scan.seen as f32 / 10., 768., 9., 0.2);
232+ assert_eq!(moving, "SCANNING · 6:40 of ~12:48 scanned · 0:09 elapsed");
233+ assert!(!moving.contains("still"), "{moving}");
234+ // A header that does not say how long the track is says nothing rather
235+ // than guessing at it.
236+ let unknown = silence_line(60., 0., 61., 0.2);
237+ assert_eq!(unknown, "SCANNING · 1:00 scanned · 1:01 elapsed");
238+ // A mark that comes back the same is not the same fact as one that
239+ // moved: the poll only restarts on a change.
240+ let held = scan.since;
241+ scan.poll();
242+ assert_eq!(scan.since, held, "an unchanged mark must not reset it");
243+}
244+
245+/// The cache is per scanned stretch, which is what stops two films
246+/// thrashing each other's fifty seconds: A, then B, then A again is *one*
247+/// decode of A. And a stretch already being read is waited for rather than
248+/// read twice -- both halves of an A/V take name the same file and the same
249+/// frames. A *trimmed* A is not A: it is a shorter read of its own, which
250+/// is the whole point of scanning the clip instead of the file.
251+#[test]
252+fn a_second_film_does_not_cost_the_first_one_its_levels() {
253+ let (a, b) = (
254+ (PathBuf::from("/films/a.mkv"), 0, 0, 3000),
255+ (PathBuf::from("/films/b.mkv"), 0, 0, 3000),
256+ );
257+ let half = (PathBuf::from("/films/a.mkv"), 0, 0, 1500);
258+ let mut cache: std::collections::HashMap<ScanKey, ()> = std::collections::HashMap::new();
259+ let mut started = Vec::new();
260+ // What a card open does, three times over, with the worker landing
261+ // between each: plan, and start what the plan says to start.
262+ for key in [&a, &b, &a] {
263+ match scan_plan(cache.contains_key(key), None, key) {
264+ ScanPlan::Start => {
265+ started.push(key.clone());
266+ cache.insert(key.clone(), ());
267+ }
268+ ScanPlan::Marks => {}
269+ ScanPlan::Wait => unreachable!("nothing is running"),
270+ }
271+ }
272+ assert_eq!(started, vec![a.clone(), b.clone()], "A was decoded twice");
273+ // The single-slot cache this replaced would have evicted A when B
274+ // landed; both are held.
275+ assert!(cache.contains_key(&a) && cache.contains_key(&b));
276+ // A scan in flight on the same source is joined, not restarted -- and
277+ // one on another source is not waited for.
278+ assert_eq!(scan_plan(false, Some(&a), &a), ScanPlan::Wait);
279+ assert_eq!(scan_plan(false, Some(&b), &a), ScanPlan::Start);
280+ // Levels in hand beat a worker either way: the marks are arithmetic.
281+ assert_eq!(scan_plan(true, Some(&a), &a), ScanPlan::Marks);
282+ // The same file cut in half is a read of its own: neither A's levels
283+ // nor A's worker answers for it.
284+ assert_eq!(
285+ scan_plan(cache.contains_key(&half), None, &half),
286+ ScanPlan::Start
287+ );
288+ assert_eq!(scan_plan(false, Some(&a), &half), ScanPlan::Start);
289+ // ...and the seconds asked for are the clip's, at the project's rate.
290+ assert_eq!(source_secs(&half, 30.), (0., 50.));
291+ assert_eq!(source_secs(&(half.0.clone(), 0, 900, 1500), 30.), (30., 50.));
292+ // A rate that is not one reads the file rather than nothing.
293+ assert_eq!(source_secs(&half, 0.), (0., f64::INFINITY));
294+}
295+
296+/// The import door's split, which is what keeps the render thread out of a
297+/// header walk: what the worker probed and what the landing registers add up
298+/// to exactly the rows, lengths and refusals the in-place import lands.
299+#[test]
300+fn probing_ahead_lands_exactly_what_importing_in_place_lands() {
301+ use std::sync::atomic::AtomicU8;
302+ let stage = AtomicU8::new(ImportStage::Header as u8);
303+ let plain = {
304+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
305+ session.set_gain(0.0);
306+ session.import(&asset("test_av2.mp4")).expect("av2 matches");
307+ (
308+ session.sources().to_vec(),
309+ session.file_frames(&asset("test_av2.mp4")),
310+ session.timeline_duration(),
311+ )
312+ };
313+ let split = {
314+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
315+ session.set_gain(0.0);
316+ let (subs, probe) =
317+ read_parts(&asset("test_av2.mp4"), &stage, Some(session.import_gate()));
318+ // This mp4 is walked now (an mp4 can carry `tx3g`) and has no
319+ // subtitle track in it, so the worker hands over an empty list --
320+ // the same thing the import lands with.
321+ assert!(subs.expect("an mp4 is readable").is_empty());
322+ let probe = probe
323+ .expect("a container is probed on the worker")
324+ .expect("av2 matches");
325+ session
326+ .import_probed(&asset("test_av2.mp4"), probe)
327+ .expect("av2 matches");
328+ (
329+ session.sources().to_vec(),
330+ session.file_frames(&asset("test_av2.mp4")),
331+ session.timeline_duration(),
332+ )
333+ };
334+ assert_eq!(plain, split);
335+ // ...and it leaves the stage where the line can read it: a worker that
336+ // never announced its second read would show one that never ends.
337+ assert_eq!(
338+ ImportStage::from_u8(stage.load(std::sync::atomic::Ordering::Relaxed)),
339+ ImportStage::Subtitles
340+ );
341+ // A refusal is the engine's refusal, and now it is *the* refusal: the
342+ // walk happens once, on the worker, so what the probe says is what the
343+ // notice shows -- worded exactly as importing in place worded it.
344+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
345+ session.set_gain(0.0);
346+ let (_, probe) = read_parts(&asset("test_25fps.mp4"), &stage, Some(session.import_gate()));
347+ let on_the_worker = probe
348+ .expect("a container is probed")
349+ .map(|_| ())
350+ .map_err(|e| e.to_string());
351+ assert_eq!(
352+ on_the_worker,
353+ session
354+ .import(&asset("test_25fps.mp4"))
355+ .map(|_| ())
356+ .map_err(|e| e.to_string())
357+ );
358+ // A timeline that moved while the worker read is not one the probe was
359+ // decided against, so the probe is not trusted -- the import is simply
360+ // taken the slow way and lands the same row.
361+ let mut moved = PlaybackSession::open(asset("test_av.mp4")).expect("open");
362+ moved.set_gain(0.0);
363+ let (_, probe) = read_parts(&asset("test_av2.mp4"), &stage, Some(moved.import_gate()));
364+ moved.import(&asset("test_still.png")).expect("a still joins");
365+ let stale = probe.expect("a container is probed").expect("av2 matches");
366+ assert_eq!(
367+ moved.import_probed(&asset("test_av2.mp4"), stale).ok(),
368+ Some(2),
369+ "a stale probe still lands the file, by the door that re-reads it"
370+ );
371+ // A path nothing can read is refused by the worker now, in the engine's
372+ // own words: nothing walks it a second time to re-word it, and neither
373+ // half is a panic.
374+ let (subs, probe) = read_parts(
375+ std::path::Path::new("/no/such/film.mkv"),
376+ &stage,
377+ Some(session.import_gate()),
378+ );
379+ assert!(subs.is_err(), "the cue walk comes back as a refusal");
380+ assert!(
381+ probe.expect("a container is probed").is_err(),
382+ "and so does the container walk"
383+ );
384+}
385+
386+/// The import door's two halves, split across the worker hop: what
387+/// [`read_ahead`] walks is exactly what the render thread would have walked,
388+/// and pushing it says what walking it in place used to say.
389+#[test]
390+fn an_imports_subtitles_are_read_by_the_worker_and_only_pushed_here() {
391+ use std::sync::atomic::AtomicU8;
392+ let stage = AtomicU8::new(ImportStage::Header as u8);
393+ let film = asset("test_subs.mkv");
394+ // The in-place walk (`subtitle_notice`) and the split one land the same
395+ // tracks and the same tail on the same timeline.
396+ let mut in_place = PlaybackSession::open(asset("test_av.mp4")).expect("open");
397+ in_place.set_gain(0.0);
398+ let said = subtitle_notice(&mut in_place, &film);
399+ let mut split = PlaybackSession::open(asset("test_av.mp4")).expect("open");
400+ split.set_gain(0.0);
401+ let (walked, _) = read_parts(&film, &stage, Some(split.import_gate()));
402+ let walked = walked.expect("the mkv is readable");
403+ assert_eq!(subtitle_tail(&mut split, Ok(walked)), said);
404+ assert_eq!(split.subtitles().len(), in_place.subtitles().len());
405+ // The same file twice is still one row, and still says so: the dedupe
406+ // lives in the push, which is the half that stayed here.
407+ let (again, _) = read_parts(&film, &stage, Some(split.import_gate()));
408+ let again = again.expect("the mkv is readable");
409+ assert_eq!(subtitle_tail(&mut split, Ok(again)), None);
410+ // A standalone `.srt` is walked by the same worker: an import of one is
411+ // not a door that reads on the render thread either.
412+ let srt = Path::new(env!("CARGO_MANIFEST_DIR"))
413+ .join("../engine/tests/data/test_subs.srt")
414+ .canonicalize()
415+ .expect("the subtitle fixture");
416+ assert_eq!(
417+ read_parts(&srt, &stage, Some(split.import_gate()))
418+ .0
419+ .expect("the srt is readable")
420+ .len(),
421+ 1
422+ );
423+ // ...and a refusal is worded as a tail, never as a failed import.
424+ let unread: Subs = Err("nothing to read".into());
425+ assert_eq!(
426+ subtitle_tail(&mut split, unread),
427+ Some(" — SUBTITLES UNREAD: nothing to read".to_string())
428+ );
429+}
430+
431+#[test]
432+fn every_codec_row_is_offered_or_says_why_not() {
433+ // One row per codec, and the boxes it can go in are the container row's
434+ // business: seven rows that pick, one that says why it cannot. A codec
435+ // twice over (AV1 · MKV beside AV1 · MP4) was two rows asking the same
436+ // question, and five picture rows above the fold is what the card was
437+ // called unfriendly for.
438+ let offered: Vec<&[Format]> = FORMATS
439+ .iter()
440+ .map(|&(row, ..)| row)
441+ .filter(|row| !row.is_empty())
442+ .collect();
443+ assert_eq!(
444+ offered,
445+ vec![
446+ &[Format::Mp4][..],
447+ &[Format::Av1, Format::Av1Mp4][..],
448+ &[Format::Hevc, Format::HevcMp4][..],
449+ &[Format::Wav][..],
450+ &[Format::Flac][..],
451+ &[Format::Mp3][..],
452+ &[Format::Ogg][..],
453+ ]
454+ );
455+ // Every format the engine writes is on exactly one row: one the card
456+ // cannot reach is one nobody can pick.
457+ for format in [
458+ Format::Mp4,
459+ Format::Av1,
460+ Format::Av1Mp4,
461+ Format::Hevc,
462+ Format::HevcMp4,
463+ Format::Wav,
464+ Format::Flac,
465+ Format::Mp3,
466+ Format::Ogg,
467+ ] {
468+ assert_eq!(
469+ FORMATS
470+ .iter()
471+ .filter(|(row, ..)| row.contains(&format))
472+ .count(),
473+ 1,
474+ "{format:?}"
475+ );
476+ }
477+ // The boxes the container row offers, and what the extension of each is
478+ // -- the destination follows the format, so these are what a file gets
479+ // named with.
480+ assert_eq!(containers(Format::Av1), [Format::Av1, Format::Av1Mp4]);
481+ assert_eq!(containers(Format::HevcMp4), [Format::Hevc, Format::HevcMp4]);
482+ assert_eq!(containers(Format::Mp3), [Format::Mp3]);
483+ assert_eq!(Format::Av1.ext(), "mkv");
484+ assert_eq!(Format::Av1Mp4.ext(), "mp4");
485+ assert_eq!(Format::Hevc.ext(), "mkv");
486+ assert_eq!(Format::HevcMp4.ext(), "mp4");
487+ // The container key walks the row and wraps, and does nothing at all
488+ // where there is only one box -- a stroke must not invent a choice the
489+ // card is not offering.
490+ assert_eq!(next_container(Format::Av1), Format::Av1Mp4);
491+ assert_eq!(next_container(Format::Av1Mp4), Format::Av1);
492+ assert_eq!(next_container(Format::Hevc), Format::HevcMp4);
493+ assert_eq!(next_container(Format::Mp4), Format::Mp4);
494+ assert_eq!(next_container(Format::Wav), Format::Wav);
495+ for (row, stroke, label, detail) in FORMATS {
496+ assert!(!label.is_empty(), "a row with no name");
497+ // A refused row is a row with a reason, never a hidden one: an
498+ // empty detail column would read as an oversight.
499+ assert!(!detail.is_empty(), "{label} says nothing");
500+ // Every row that can be picked has a key of its own, and no row
501+ // that cannot has one: the card is drivable without a pointer.
502+ assert_eq!(!row.is_empty(), !stroke.is_empty(), "{label}");
503+ if let Some(&first) = row.first() {
504+ assert_eq!(
505+ format_key(stroke, first),
506+ Some(first),
507+ "{label} keys to itself"
508+ );
509+ assert!(
510+ stroke.parse::<u32>().is_err(),
511+ "{label} takes a digit the bitrate needs"
512+ );
513+ // Every box on one row is the same codec, so the quality rows
514+ // do not change meaning when the container does.
515+ assert!(row.iter().all(|f| f.has_video() == first.has_video()));
516+ assert!(
517+ row.iter()
518+ .all(|f| bitrate_refusal(*f) == bitrate_refusal(first))
519+ );
520+ }
521+ }
522+ // No two rows share a key, and none of them is a stroke the card already
523+ // answers to itself -- an ambiguous key is a key that picks the wrong
524+ // thing on a card that has no other input.
525+ let keys: Vec<&str> = FORMATS
526+ .iter()
527+ .map(|&(_, stroke, ..)| stroke)
528+ .filter(|stroke| !stroke.is_empty())
529+ .collect();
530+ for (i, key) in keys.iter().enumerate() {
531+ assert!(!keys[i + 1..].contains(key), "{key} picks two rows");
532+ assert!(
533+ !["c", "q", "d", "g", "r", "enter", "backspace", ESCAPE].contains(key),
534+ "{key} is already the card's own"
535+ );
536+ }
537+ assert_eq!(
538+ format_key("a", Format::Mp4),
539+ Some(Format::Av1Mp4),
540+ "the box already chosen is kept"
541+ );
542+ assert_eq!(
543+ format_key("a", Format::Wav),
544+ Some(Format::Av1),
545+ "and a codec with no such box takes its first"
546+ );
547+ assert_eq!(format_key("h", Format::Av1Mp4), Some(Format::HevcMp4));
548+ assert_eq!(format_key("p", Format::Mp4), Some(Format::Mp3));
549+ assert_eq!(
550+ format_key("m", Format::Mp3),
551+ Some(Format::Mp4),
552+ "not MP3, which is p"
553+ );
554+ assert_eq!(
555+ format_key("x", Format::Mp4),
556+ None,
557+ "a stroke no row carries"
558+ );
559+ assert_eq!(format_key("o", Format::Mp4), Some(Format::Ogg));
560+ // The one codec left that this program reads and cannot write is a row
561+ // of its own, refused by name rather than absent: VP9, because AV1 is
562+ // the row that replaced it. Its reason travels with it, in the row or in
563+ // the footer line that collects them -- either way it is on screen
564+ // without a click. OGG was the other one until `rusty_vorbis` gave this
565+ // project an encoder, and the row that says so is the row above.
566+ let (row, _, _, detail) = FORMATS
567+ .into_iter()
568+ .find(|(_, _, name, _)| *name == "VP9")
569+ .expect("VP9 has a row");
570+ assert!(row.is_empty(), "VP9 is not offered");
571+ assert!(detail.contains("replaces it"), "VP9: {detail}");
572+ let (row, _, _, detail) = FORMATS
573+ .into_iter()
574+ .find(|(_, _, name, _)| *name == "OGG")
575+ .expect("OGG has a row");
576+ assert_eq!(row, [Format::Ogg], "OGG is a row that picks now");
577+ assert!(
578+ detail.contains("rusty_vorbis"),
579+ "the row names the encoder like every other live one: {detail}"
580+ );
581+ // Both AV1 boxes say they carry sound: the file used to be picture only,
582+ // and a line that still said so would be the lie a user plays the file
583+ // to find out about. HEVC says intra-only before anyone waits on one --
584+ // a file several times the size, which the disk would otherwise say.
585+ for format in [Format::Av1, Format::Av1Mp4] {
586+ assert!(format_line(format).starts_with("AV1 · "));
587+ }
588+ for format in [Format::Hevc, Format::HevcMp4] {
589+ assert!(format_line(format).starts_with("HEVC intra · "));
590+ }
591+ // The head names the box every format goes in, which is what the
592+ // destination is then named after.
593+ for format in [
594+ Format::Mp4,
595+ Format::Av1,
596+ Format::Av1Mp4,
597+ Format::Hevc,
598+ Format::HevcMp4,
599+ ] {
600+ assert!(
601+ format_line(format).contains(&format.ext().to_uppercase()),
602+ "{format:?}: {}",
603+ format_line(format)
604+ );
605+ }
606+ // ...and it stays inside the one line the card budgets for it: the
607+ // longest of them, with every field after it, against the 76 characters
608+ // that fit at `EXPORT_W`.
609+ let longest = summary_head(
610+ Format::Hevc,
611+ Some(((1920, 1080), 23.976)),
612+ "AAC · SW encode (rusty_aac)",
613+ );
614+ assert!(
615+ longest.chars().count() <= 76,
616+ "{longest} is {} long",
617+ longest.chars().count()
618+ );
619+ assert!(
620+ FORMATS
621+ .into_iter()
622+ .any(|(row, _, _, detail)| row.contains(&Format::Hevc) && detail.contains("intra"))
623+ );
624+ // Only a picture encoder is given a bitrate, and the quality rows dim
625+ // with the reason for every format that is not one.
626+ for format in [
627+ Format::Mp4,
628+ Format::Av1,
629+ Format::Av1Mp4,
630+ Format::Hevc,
631+ Format::HevcMp4,
632+ ] {
633+ assert!(
634+ format.has_video() && bitrate_refusal(format).is_none(),
635+ "{format:?}"
636+ );
637+ }
638+ for format in [Format::Wav, Format::Flac, Format::Mp3] {
639+ assert!(!format.has_video());
640+ assert!(
641+ bitrate_refusal(format).is_some(),
642+ "{format:?} dims silently"
643+ );
644+ }
645+ assert!(bitrate_refusal(Format::Wav).unwrap().contains("lossless"));
646+ // MP3 has a rate and it is the *Sound* row's: the quality rows are the
647+ // picture's, and this refusal used to claim a fixed 256 kbps that the
648+ // Sound row can now change under it.
649+ assert!(bitrate_refusal(Format::Mp3).unwrap().contains("Sound row"));
650+ assert!(
651+ !format_line(Format::Mp3).contains("256"),
652+ "the summary states a rate the Sound row can change under it"
653+ );
654+ // The destination follows the format and keeps the stem, mp4 included.
655+ assert_eq!(
656+ retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav),
657+ std::path::Path::new("/a/take.export.wav")
658+ );
659+ assert_eq!(
660+ retarget(std::path::Path::new("/a/take.export.wav"), Format::Mp4),
661+ std::path::Path::new("/a/take.export.mp4")
662+ );
663+ assert!(format_line(Format::Flac).contains("lossless"));
664+}
665+
666+/// The one line the card is answerable for: what it says is on screen before
667+/// the button is pressed, and every field of it is one `ffprobe` reads back
668+/// off the file that comes out.
669+#[test]
670+fn the_summary_states_the_file_before_it_is_written() {
671+ let head = summary_head(Format::Mp4, Some(((1920, 1080), 30.)), "AAC copy");
672+ for field in ["H.264", "MP4", "1920x1080", "30 fps", "AAC copy"] {
673+ assert!(head.contains(field), "{field} missing from {head}");
674+ }
675+ // The rate as a person writes it, and the ratio one spelled out rather
676+ // than rounded to a rate nothing is written at.
677+ assert_eq!(fps_label(30.), "30");
678+ assert_eq!(fps_label(24000. / 1001.), "23.976");
679+ assert_eq!(fps_label(29.97002997), "29.97");
680+ // A format with no picture states no size and no rate it does not write.
681+ let audio = summary_head(Format::Wav, Some(((1920, 1080), 30.)), "PCM · SW (hound)");
682+ assert!(
683+ !audio.contains("1920x1080") && !audio.contains("fps"),
684+ "{audio}"
685+ );
686+ assert!(audio.contains("PCM · SW (hound)"));
687+ // ...and one with no sound on the timeline says that, rather than
688+ // leaving the field out and reading as a file with sound in it.
689+ assert!(
690+ summary_head(Format::Mp4, Some(((640, 360), 25.)), "no sound to write")
691+ .contains("no sound to write")
692+ );
693+ // The tail: where it lands, about how big, and what will encode it --
694+ // never a guessed seat, and no seat at all for a format with no picture.
695+ let tail = summary_tail(
696+ Path::new("/a/take.export.mp4"),
697+ Some(45_000_000),
698+ Some("VA-API"),
699+ true,
700+ );
701+ assert!(tail.starts_with("take.export.mp4"), "{tail}");
702+ assert!(
703+ tail.contains("≈ 45 MB") && tail.contains("VA-API"),
704+ "{tail}"
705+ );
706+ assert!(summary_tail(Path::new("/a/x.mp4"), None, None, true).contains("encoder …"));
707+ assert!(!summary_tail(Path::new("/a/x.wav"), None, None, false).contains("encoder"));
708+ assert!(!summary_tail(Path::new("/a/x.wav"), None, None, false).contains("MB"));
709+ // 6 Mbps over a minute is 45 MB. `Auto` has no figure to estimate from
710+ // and an empty timeline no length: neither invents one.
711+ assert_eq!(estimated_bytes(Some(6_000_000), 60.), Some(45_000_000));
712+ assert_eq!(estimated_bytes(Some(2_000_000), 90.), Some(22_500_000));
713+ assert_eq!(estimated_bytes(None, 60.), None);
714+ assert_eq!(estimated_bytes(Some(6_000_000), 0.), None);
715+ assert_eq!(estimated_bytes(Some(0), 60.), None);
716+ // ...and a short one is not nothing. Three seconds at the floor
717+ // bitrate is 375 kB, which used to round to the "≈ 0 MB" this line
718+ // exists to never say -- the shortest export a frame can make is
719+ // still a real file with a real size.
720+ let short = estimated_bytes(Some(1_000_000), 3.).expect("a rate and a length");
721+ assert_eq!(size_label(short), "375 kB");
722+ let frame = summary_tail(Path::new("/a/x.mp4"), estimated_bytes(Some(1_000_000), 1. / 60.), None, true);
723+ assert!(
724+ frame.contains("≈ 2 kB") && !frame.contains("0 MB") && !frame.contains("0 kB"),
725+ "{frame}"
726+ );
727+ // The boundary reads in the unit that can state it, either side.
728+ assert_eq!(size_label(999_600), "1 MB");
729+ assert_eq!(size_label(499_000), "499 kB");
730+ assert_eq!(size_label(1), "1 kB");
731+}
732+
733+/// Which cue is on screen when: the whole of what the overlay decides, and
734+/// the one piece of it that is arithmetic rather than layout.
735+#[test]
736+fn a_cue_is_on_screen_from_its_start_until_the_moment_it_ends() {
737+ use engine::subtitle::Cue;
738+ let cue = |start_us, end_us, text: &str| Cue {
739+ start_us,
740+ end_us,
741+ text: text.to_string(),
742+ image: None,
743+ };
744+ // Two cues that hand over exactly, and one that overlaps the second --
745+ // a sign over a line of dialogue, which is two plates at one moment.
746+ let cues = [
747+ cue(500_000, 1_500_000, "first line"),
748+ cue(1_500_000, 2_500_000, "second line"),
749+ cue(2_000_000, 2_200_000, "a sign"),
750+ ];
751+ let at = |t: f64| -> Vec<&str> {
752+ cues_at(&cues, t)
753+ .into_iter()
754+ .map(|c| c.text.as_str())
755+ .collect()
756+ };
757+ // Before the first, between none of them: nothing, which is what makes
758+ // the overlay disappear rather than sit there empty.
759+ assert!(at(0.).is_empty());
760+ assert!(at(0.4).is_empty());
761+ assert!(at(3.).is_empty());
762+ assert_eq!(at(0.5), ["first line"], "on at its own start");
763+ assert_eq!(at(1.4), ["first line"]);
764+ // Half-open: the frame the first ends on is the second's, never both.
765+ assert_eq!(at(1.5), ["second line"]);
766+ assert_eq!(at(2.1), ["second line", "a sign"], "two at once stack");
767+ assert_eq!(at(2.2), ["second line"], "the sign is over");
768+ // ...and the end of the last one is the end of it.
769+ assert!(at(2.5).is_empty());
770+ // A negative time is before everything rather than a panic: the
771+ // playhead is clamped, but nothing here depends on that.
772+ assert!(at(-1.).is_empty());
773+}
774+
775+/// The two places a subtitle is drawn -- the plate over the picture and the
776+/// strip under the lanes -- inside the 640x360 floor the rest of this window
777+/// is sized for, and the plate readable on whatever the film is showing.
778+#[test]
779+fn the_subtitle_plate_and_strip_fit_the_smallest_window() {
780+ // The strip costs the panel its own row and the panel's gap, and costs
781+ // nothing at all when there is no track to draw.
782+ assert_eq!(subtitle_strip_h(false), 0.);
783+ assert_eq!(subtitle_strip_h(true), SUB_LANE_H + 8.);
784+ // What is left for the picture at the floor, with the panel a project
785+ // starts with and the strip under it.
786+ let picture = 360. - HEADER_H - panel_h(2) - subtitle_strip_h(true);
787+ assert!(picture > 0., "the strip pushed the picture off the window");
788+ // A two-line cue and the gap under it fit inside that, which is the
789+ // whole claim: the plate sits *over* the picture and must not need more
790+ // of it than there is.
791+ assert!(
792+ SUB_BOTTOM + 2. * SUB_LINE_H <= picture,
793+ "a two-line cue does not fit the smallest picture"
794+ );
795+ // The text sits on its line rather than being clipped by it.
796+ assert!(SUB_LINE_H >= SUB_TEXT);
797+ // White on the plate, not chrome on chrome: a cue is read against the
798+ // film, and this is the one pair here that has to survive any picture.
799+ for id in crate::ui::theme::PaletteId::ALL {
800+ assert!(contrast(id.palette().SUB_FG, 0x000000) >= 7., "{id:?}");
801+ }
802+ // The strip is a picture and not a target -- nothing on it takes a
803+ // click -- which is the only reason it may be under `HIT_MIN`.
804+ assert!(SUB_LANE_H < HIT_MIN && SUB_LANE_H > 0.);
805+ // The library's own list of tracks scrolls past three rather than
806+ // taking the media list's room.
807+ assert_eq!(SUB_ROWS_H / ROW_H, 3.);
808+ assert!(ROW_H >= HIT_MIN, "a subtitle row is clicked to pick it");
809+ // At the floor there are no group headers at all: the list is one row
810+ // tall there, and a header would name a film and then show none of it.
811+ // The rows go on naming their own file, so nothing is lost by it.
812+ assert!(!sub_headers_fit(360.), "a header at the floor eats the track");
813+ // At the size the window opens on there is room for a header and the
814+ // tracks under it, which is the only condition it is drawn on.
815+ assert!(sub_headers_fit(720.));
816+ // ...and where it is drawn it fits inside the same capped list, header
817+ // and two rows under it, without the tracks losing their budget.
818+ assert!(SUB_HEAD_H + 2. * ROW_H <= SUB_ROWS_H);
819+ // A header takes no click -- there is nothing to fold and nothing to
820+ // aim at -- which is the only reason it may be under `HIT_MIN`.
821+ assert!(SUB_HEAD_H < HIT_MIN && SUB_HEAD_H > 0.);
822+}
823+
824+/// What the rows of both lists do with a name too long for the column: two
825+/// episodes off one release differ in their last two characters, and a name
826+/// cut from the right is the same row twice.
827+#[test]
828+fn a_long_name_is_cut_out_of_its_middle_so_two_episodes_stay_two_rows() {
829+ let (a, b) = (
830+ "A Long Release Name Of A Series 01",
831+ "A Long Release Name Of A Series 02",
832+ );
833+ // The two call sites at the narrowest the column ever is: a media row's
834+ // name gets the row's whole width, a subtitle row's file prefix gets a
835+ // share of it because the language has to fit beside it.
836+ let media = row_text_w(LIBRARY_MIN_W);
837+ let prefix = media * SUB_STEM_SHARE;
838+ for width in [media, prefix] {
839+ assert!(width > 0., "the floor leaves a row no words at all");
840+ assert_ne!(
841+ clip_middle(a, width),
842+ clip_middle(b, width),
843+ "{width}px: two episodes read as one row"
844+ );
845+ // Both ends survive: the release's name at the front, the number
846+ // that tells them apart at the back.
847+ assert!(clip_middle(a, width).starts_with(&a[..2]));
848+ assert!(clip_middle(a, width).ends_with("01"));
849+ assert!(clip_middle(a, width).contains('…'));
850+ // Never wider than the column can hold, gap included.
851+ assert!(clip_middle(a, width).chars().count() <= (width / 6.) as usize + 1);
852+ }
853+ // A name the width holds is left exactly as it is -- no gap, nothing
854+ // dropped -- and so is a name at any width once the column is wide.
855+ assert_eq!(clip_middle("eng.srt", 400.), "eng.srt");
856+ assert_eq!(clip_middle(a, 4000.), a);
857+ // Nothing panics at a width no column ever has, and something of both
858+ // ends is still there.
859+ assert_eq!(clip_middle(a, 0.).chars().count(), 5);
860+ assert!(clip_middle(a, 0.).ends_with('1'));
861+ // Counted in characters and not bytes: a name in another script is cut
862+ // between its letters, not through one.
863+ assert_eq!(clip_middle("ααααααααααααααα", 24.), "αα…αα");
864+}
865+
866+/// The two doors subtitles arrive through, end to end on the fixtures: a
867+/// file beside the media and the tracks inside an mkv, what the overlay then
868+/// says at a given moment, and where the strip draws it.
869+#[test]
870+fn subtitles_arrive_beside_the_media_and_inside_it() {
871+ // Which door a path goes through is decided before anything is opened.
872+ // ...and a `.mks` is one, the subtitles of a Matroska file alone: it has
873+ // no source in it to import, so the drop door has to send it where `+ S`
874+ // sends it. Its two siblings are media and must not come here -- a
875+ // `.mka` is a song this would stop importing.
876+ for name in ["subs.srt", "SUBS.SRT", "a.vtt", "a.ass", "a.ssa", "s.mks", "S.MKS"] {
877+ assert!(is_subtitle(Path::new(name)), "{name}");
878+ }
879+ for name in ["a.mp4", "a.mkv", "song.mka", "film.mk3d", "notes.txt", "a"] {
880+ assert!(!is_subtitle(Path::new(name)), "{name}");
881+ }
882+ // Every container the engine can walk for tracks inside it, Matroska
883+ // and ISO-BMFF alike -- an mp4 carries `tx3g`, so the app has to ask it.
884+ // The Matroska half is the engine's own closed set, extension for
885+ // extension, so no file is walked here that it would refuse there.
886+ for name in [
887+ "film.MKV", "clip.webm", "clip.mp4", "a.m4v", "a.MOV", "song.mka", "s.mks", "f.MK3D",
888+ ] {
889+ assert!(carries_subtitles(Path::new(name)), "{name}");
890+ assert!(
891+ engine::demux::is_matroska(Path::new(name))
892+ || matches!(
893+ Path::new(name)
894+ .extension()
895+ .and_then(|e| e.to_str())
896+ .map(str::to_ascii_lowercase)
897+ .as_deref(),
898+ Some("mp4" | "m4v" | "mov")
899+ ),
900+ "{name} is walked by the app but not by the engine"
901+ );
902+ }
903+ for name in ["song.wav", "still.png", "notes.txt", "a"] {
904+ assert!(!carries_subtitles(Path::new(name)), "{name}");
905+ }
906+ // The three doors, on the one file that used to split them: what the
907+ // drop/argv door does with it ([`Player::take_import`] routes on
908+ // `is_subtitle`), what the worker reads for it ([`walk_subtitles`]), and
909+ // what `+ S` reads ([`Player::add_subtitles`] -> `parse_subtitles`) are
910+ // the same walk of the same bytes.
911+ let mks = asset("test_subs.mks");
912+ assert!(is_subtitle(&mks), "the drop door takes it as subtitles");
913+ let dropped = walk_subtitles(&mks).expect("the drop door's worker reads it");
914+ let plus_s = PlaybackSession::parse_subtitles(&mks).expect("`+ S` reads it");
915+ assert!(!dropped.is_empty(), "and there are tracks in it");
916+ assert_eq!(
917+ dropped.iter().map(|t| &t.label).collect::<Vec<_>>(),
918+ plus_s.iter().map(|t| &t.label).collect::<Vec<_>>(),
919+ );
920+
921+ let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
922+ session.set_gain(0.0);
923+ // Beside the media: the drop door's own call, and the row it makes.
924+ let srt = Path::new(env!("CARGO_MANIFEST_DIR"))
925+ .join("../engine/tests/data/test_subs.srt")
926+ .canonicalize()
927+ .expect("the subtitle fixture");
928+ assert_eq!(session.import_subtitles(&srt).expect("the .srt imports"), 1);
929+ let track = &session.subtitles()[0];
930+ assert_eq!(track.label, "test_subs.srt");
931+ assert_eq!(subtitle_detail(track), "3 cues");
932+ // What the overlay draws at a moment inside the first cue, and between
933+ // two of them -- the fixture's own timings (0.5-1.5 s, 2.0-3.25 s).
934+ let text = |t: f64| -> Vec<String> {
935+ cues_at(&track.cues, t)
936+ .into_iter()
937+ .map(|c| c.text.clone())
938+ .collect()
939+ };
940+ assert_eq!(text(0.7), ["first line"]);
941+ assert!(text(1.8).is_empty(), "between two cues the plate goes");
942+ assert_eq!(text(2.5), ["second line\nwith a break"]);
943+ // Where the strip puts that first cue: 0.5 s in at 40 px to the second
944+ // is 20 px along, and a second of cue is 40 px wide.
945+ let scale = Scale::default();
946+ assert_eq!(scale.pps, PPS_DEFAULT);
947+ assert_eq!(cue_box(scale, &track.cues[0]), (20., 40.));
948+ // Zoomed right out, a cue worth a fraction of a pixel is still a mark.
949+ let far = Scale {
950+ pps: 0.01,
951+ start: 0.,
952+ };
953+ assert_eq!(cue_box(far, &track.cues[0]).1, SUB_CUE_MIN_W);
954+ // ...and scrolled past, its left edge is negative, exactly as a clip
955+ // box's is: the bed clips it.
956+ let scrolled = Scale {
957+ pps: PPS_DEFAULT,
958+ start: 1.,
959+ };
960+ assert_eq!(cue_box(scrolled, &track.cues[0]).0, -20.);
961+
962+ // Inside the media: the tracks of an mkv, taken by the same call every
963+ // open and import door makes. Two of them in the fixture, named by what
964+ // the file says rather than by number.
965+ let notice =
966+ subtitle_notice(&mut session, &asset("test_subs.mkv")).expect("the mkv carries two");
967+ assert!(notice.contains('2'), "{notice}");
968+ assert_eq!(session.subtitles().len(), 3);
969+ assert_eq!(session.subtitles()[1].label, "eng");
970+ assert_eq!(session.subtitles()[2].label, "fra — Signs");
971+ assert_eq!(subtitle_detail(&session.subtitles()[1]), "3 cues");
972+ // The same file twice adds nothing and says nothing.
973+ assert_eq!(subtitle_notice(&mut session, &asset("test_subs.mkv")), None);
974+ // An mp4 is walked too (it can carry `tx3g`); this one holds none, so
975+ // the notice grows no tail.
976+ assert_eq!(subtitle_notice(&mut session, &asset("test_av.mp4")), None);
977+
978+ // A track that could not be read says why, where its cue count would
979+ // be: what the greyed library row prints, and the whole difference
980+ // between "this film has no subtitles" and "these four are pictures".
981+ let refused = engine::subtitle::SubtitleTrack {
982+ path: PathBuf::from("/a/remux.mkv"),
983+ track: Some(1),
984+ // Neither field, like `SubtitleTrack::refused` leaves them: what is
985+ // refused is never written, and the row keeps the label it was
986+ // refused under.
987+ language: String::new(),
988+ name: String::new(),
989+ label: "eng".into(),
990+ cues: Vec::new(),
991+ bitmap: false,
992+ refused: Some("S_HDMV/PGS subtitles are pictures, not text".into()),
993+ };
994+ assert!(subtitle_detail(&refused).contains("pictures"));
995+ assert!(cues_at(&refused.cues, 1.).is_empty());
996+
997+ // ...and what the plate and the strip draw after a *cut*: the timeline's
998+ // own clock, asked of the engine through the very map an export writes
999+ // the file with (`PlaybackSession::timeline_cues`), so the preview and
1000+ // the file cannot drift apart. The numbers are the export's own
1001+ // (`export::a_subtitle_file_beside_the_media_keeps_the_timelines_own_
1002+ // clock`): 0.5s..2.5s rippled out of a five-second timeline leaves
1003+ // three seconds, which clips the second cue and takes the third away
1004+ // altogether -- while the track itself still holds all three, which is
1005+ // exactly why the drawing may not read them straight.
1006+ let lanes = session.lanes();
1007+ session
1008+ .cut_regions(&[(15, 60)], &lanes)
1009+ .expect("cut 0.5s..2.5s out");
1010+ assert_eq!(session.timeline_duration(), 3.0);
1011+ assert_eq!(session.subtitles()[0].cues.len(), 3, "the track is untouched");
1012+ let mapped = session.timeline_cues(0);
1013+ assert_eq!(
1014+ mapped
1015+ .iter()
1016+ .map(|c| (c.start_us, c.end_us))
1017+ .collect::<Vec<_>>(),
1018+ vec![(500_000, 1_500_000), (2_000_000, 3_000_000)]
1019+ );
1020+ // The overlay's own two lines, at the same moments as above.
1021+ let drawn = |t: f64| -> Vec<String> {
1022+ cues_at(&mapped, t)
1023+ .into_iter()
1024+ .map(|c| c.text.clone())
1025+ .collect()
1026+ };
1027+ assert_eq!(drawn(0.7), ["first line"]);
1028+ assert_eq!(drawn(2.5), ["second line\nwith a break"]);
1029+ assert!(
1030+ drawn(4.2).is_empty(),
1031+ "a cue past the cut end is drawn where the file writes none"
1032+ );
1033+ // ...and the strip's: the second cue is one second wide now, not 1.25.
1034+ assert_eq!(cue_box(scale, &mapped[1]), (80., 40.));
1035+}
crates/app/src/tests/mod.rsadded+219 -0
@@ -0,0 +1,219 @@
1+//! The window's tests, out of `main.rs` and into a module of their own: the
2+//! file was sixteen thousand lines and two thirds of them were this. What
3+//! stays here is what every part of it shares -- the imports, the fixtures,
4+//! and the source scans the guards read.
5+
6+mod editing;
7+mod view;
8+mod cards;
9+mod media;
10+mod layout;
11+
12+use super::{
13+ ACCENT_PRIMARY, AUDIO_KBPS, COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, Ctx, DEFAULT_AUDIO_KBPS, EQ_BANDS_MAX,
14+ EQ_CURVE_STEPS, EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW, EQ_FREQ_STEP, EQ_GAIN_LIMIT, EQ_GRAPH_H,
15+ EQ_HANDLE, EQ_Q_HIGH, EQ_Q_LOW, EQ_Q_STEP, EQ_SPECTRUM_DB, EQ_TICKS, EQ_W_MAX, ESCAPE,
16+ EXPORT_FIXED_H, EXPORT_ROWS_H, EXPORT_W, Enable, FORMATS,
17+ Format, HEADER_GAP, HEADER_H, HEADER_W, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, FG_PRIMARY,
18+ FG_SECONDARY, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, KeyRow, LABEL_H, LABEL_MIN_W, LANE_H, LANES_MAX,
19+ BG_CANVAS, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS, MENU_PAD, MENU_ROW_H,
20+ MBPS_DIGITS, MBPS_MAX, MBPS_MIN, MB_FLOOR, MENU_W, NO_FILE, NumberEdit, PANEL_H, ROW_ITEMS, RowCtx, RowItem,
21+ Quality, ROW_H, RULER_HIT_H, BG_SELECTED, SCROLL_NOTCH_SHARE, SILENCE_ROWS,
22+ SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, BG_RAISED, SWATCH_W, Source, Speed, StreamInfo,
23+ Transport, VOLUME_W, Volume, WAVE_BPS, WAVE_COL, WAVE_COLS_MAX, Wave, band_label,
24+ bitrate_detail, bitrate_refusal, can_add, cancels_export, clipboard_after_remove, color_snap, commit_mbps,
25+ containers,
26+ enable, envelope, eq_card_w, eq_freq, eq_freq_label, eq_spectrum, eq_x, eq_y,
27+ estimated_bytes, export_path, export_settings, format_key,
28+ format_line, format_refusal, fps_choices, fps_label, frac_along, frac_down, frame_at,
29+ frame_rate_ladder, histogram,
30+ inserted_band, is_bare_modifier, is_project, keymap, keys_filter, keys_rows, lanes_h,
31+ marked, menu_at, menu_items, menu_rows_h, next_audio_kbps, next_container, normalise, nothing_to_play, panel_h, project_path,
32+ LATE_RESYNC, RESYNC_GAP, should_resync,
33+ retarget, row_enable, row_items, scrub_due, secs_label, show_label, silence_rate, size_label, snap_cue, snap_marks, snapped,
34+ SUB_PLAN_CHARS, source_tint, span_partner, speed_at, sub_pick_after_removal, subtitle_plan, summary_head, summary_tail, timecode, transport,
35+ EXPORT_DONE, NOTICES_MAX, STATUS_ERROR, TIMELINE_FIXED_H, TIMELINE_SHARE, lanes_shown,
36+ px_below, rows_below, STATUS_SUCCESS, STATUS_WARNING, notice_tone,
37+ push_notice, typed, unseen_paths, unseen_sources,
38+ whole_take, window_title,
39+};
40+
41+use super::{
42+ Choice, EDGE_W, ETA_SPAN, Edge, FITS, FRAME_RATES, LaneKind, PPS_DEFAULT, PPS_MIN, Preset, RESOLUTIONS, Repeat,
43+ Scale, View,
44+ ZOOM_MIN_FRAMES, ZOOM_OUT_MARGIN, ZOOM_STEP, audio_rate_choices, clock, eta_secs, file_name, file_uri,
45+ fit_choices, landing, lane_refuses, library_rows, live_idx, next_fit, next_resolution,
46+ note_progress, px_along,
47+ IMPORT_STALL, Import, ImportStage, SEEK_STALL, ScanKey, ScanPlan, SilenceScan, import_line,
48+ Landing, arrival, launch_queue,
49+ read_ahead, scan_plan, seek_line, silence_line, source_secs, stash_or_write,
50+ repeats, resolution_choices, resolution_ladder, span_label, tone_choices, tone_label,
51+ clip_width, trimmed_clip, trims, unscannable, unusable,
52+ visible_slice,
53+};
54+
55+use super::{
56+ SUB_BOTTOM, SUB_CUE_MIN_W, SUB_HEAD_H, SUB_FG, SUB_LANE_H, SUB_LINE_H, SUB_ROWS_H,
57+ SUB_STEM_SHARE, SUB_TEXT, clip_middle, cue_box,
58+ carries_subtitles, cues_at, file_tint, is_subtitle, lang_human, row_text_w, sub_headers_fit,
59+ Subs, subtitle_detail, subtitle_notice, subtitle_tail,
60+ sub_pick_name, subtitle_rows, subtitle_strip_h, walk_subtitles,
61+};
62+
63+use engine::PlaybackSession;
64+
65+use engine::scale::FitPolicy;
66+
67+use gpui::{Bounds, Pixels, point, px, size};
68+
69+use std::collections::HashMap;
70+
71+use std::path::{Path, PathBuf};
72+
73+use std::time::{Duration, Instant};
74+
75+/// Every line of the window's source there is, as one string. The regions have
76+/// moved house twice -- one `main.rs`, then `ui/`, then the tests out of it --
77+/// and a scan that names its files passes a rule by simply not looking where
78+/// the code went. So the files are found rather than listed: every `.rs` under
79+/// `src/`, read at run time.
80+fn ui_source() -> String {
81+ source_files()
82+ .iter()
83+ .map(|path| std::fs::read_to_string(path).expect("a source file"))
84+ .collect()
85+}
86+
87+/// One named file of that source, for the scans about a single region.
88+fn src_text(rel: &str) -> String {
89+ std::fs::read_to_string(src_dir().join(rel)).expect("a source file")
90+}
91+
92+fn src_dir() -> PathBuf {
93+ Path::new(env!("CARGO_MANIFEST_DIR")).join("src")
94+}
95+
96+/// Every source file the scans read, in a stable order. The tests are not the
97+/// window, and the keymap is what the window is compared *against* -- a table
98+/// that vouched for itself would answer every question asked of it.
99+fn source_files() -> Vec<PathBuf> {
100+ let mut found = Vec::new();
101+ let mut dirs = vec![src_dir()];
102+ while let Some(dir) = dirs.pop() {
103+ let mut entries: Vec<PathBuf> = std::fs::read_dir(&dir)
104+ .expect("the source directory")
105+ .map(|entry| entry.expect("a source entry").path())
106+ .collect();
107+ entries.sort();
108+ for path in entries {
109+ if path.is_dir() {
110+ if path.file_name() != Some("tests".as_ref()) {
111+ dirs.push(path);
112+ }
113+ } else if path.extension() == Some("rs".as_ref())
114+ && path.file_name() != Some("keymap.rs".as_ref())
115+ {
116+ found.push(path);
117+ }
118+ }
119+ }
120+ found
121+}
122+
123+fn asset(name: &str) -> PathBuf {
124+ Path::new(env!("CARGO_MANIFEST_DIR"))
125+ .join("../../assets")
126+ .join(name)
127+}
128+
129+/// A source entry for `path` on `stream`, as the project keeps them.
130+fn source(path: &str, stream: usize) -> Source {
131+ Source {
132+ path: PathBuf::from(path),
133+ audio_stream: stream,
134+ }
135+}
136+
137+fn info(
138+ index: usize,
139+ rate: u32,
140+ channels: u16,
141+ lang: Option<&str>,
142+ decodable: bool,
143+) -> StreamInfo {
144+ StreamInfo {
145+ index,
146+ codec: if decodable { "aac" } else { "unknown" }.into(),
147+ channels,
148+ sample_rate: rate,
149+ lang: lang.map(str::to_string),
150+ decodable,
151+ }
152+}
153+
154+/// The bed the view tests are drawn on: 200 px at 30 fps, as the drop test
155+/// above uses.
156+const TEST_BED: f32 = 200.;
157+
158+/// A scale against that bed and a timeline `duration` seconds long.
159+fn test_view(scale: Scale, duration: f64) -> View {
160+ View {
161+ scale,
162+ bed: TEST_BED,
163+ duration,
164+ fps: 30.,
165+ }
166+}
167+
168+/// The two halves a worker hands back for an import, unwrapped: every import
169+/// lands as a [`Landed::Read`], and a test that has to say so at four call
170+/// sites is saying it once here.
171+fn read_parts(
172+ path: &std::path::Path,
173+ stage: &std::sync::atomic::AtomicU8,
174+ gate: Option<engine::ImportGate>,
175+) -> (Subs, crate::Probe) {
176+ match read_ahead(path, stage, gate) {
177+ crate::Landed::Read(subs, probe) => (subs, probe),
178+ _ => panic!("an import into a timeline that is up lands as a read"),
179+ }
180+}
181+
182+/// WCAG 2.1 relative luminance of a packed `0xRRGGBB`.
183+fn luminance(colour: u32) -> f64 {
184+ let channel = |shift: u32| {
185+ let s = f64::from((colour >> shift) & 0xff) / 255.;
186+ if s <= 0.03928 {
187+ s / 12.92
188+ } else {
189+ ((s + 0.055) / 1.055).powf(2.4)
190+ }
191+ };
192+ 0.2126 * channel(16) + 0.7152 * channel(8) + 0.0722 * channel(0)
193+}
194+
195+/// WCAG 2.1 contrast ratio, 1..=21.
196+fn contrast(a: u32, b: u32) -> f64 {
197+ let (a, b) = (luminance(a), luminance(b));
198+ (a.max(b) + 0.05) / (a.min(b) + 0.05)
199+}
200+
201+/// The two shapes the engine really builds: a track *of* a file states a
202+/// language and no title (`of_matroska`, `of_mp4`), and a standalone file
203+/// states no language and is its own name (`external`).
204+fn sub(path: &str, track: Option<u64>, label: &str) -> engine::subtitle::SubtitleTrack {
205+ let (language, name) = match track {
206+ Some(_) => (label.to_string(), String::new()),
207+ None => (String::new(), label.to_string()),
208+ };
209+ engine::subtitle::SubtitleTrack {
210+ path: PathBuf::from(path),
211+ track,
212+ language,
213+ name,
214+ label: label.to_string(),
215+ cues: Vec::new(),
216+ bitmap: false,
217+ refused: None,
218+ }
219+}
crates/app/src/tests/view.rsadded+857 -0
@@ -0,0 +1,857 @@
1+//! Where a moment is drawn: drops and snaps, the zoom and the scroll, the
2+//! paths a file is written to, and the strokes the handler answers.
3+
4+use super::*;
5+
6+/// What a drop reads: the frame under the pointer, through the same scale
7+/// the boxes are drawn through. Zoomed in, the same pixel is a different
8+/// frame -- which is the whole reason `Player::frame_under` goes through
9+/// [`Scale`] rather than through the duration alone.
10+#[test]
11+fn a_drop_reads_the_frame_under_the_pointer_at_every_zoom() {
12+ // A 200 px bed inset by the panel's padding, 10 seconds at 30 fps.
13+ let bed: Bounds<Pixels> = Bounds {
14+ origin: point(px(12.), px(400.)),
15+ size: size(px(200.), px(6.)),
16+ };
17+ let fps = 30.;
18+ // The frame a pointer at window `x` names, exactly as `frame_under`
19+ // composes it.
20+ let under = |scale: Scale, x: f32| frame_at(scale.time_at(px_along(px(x), bed)), fps);
21+
22+ // The whole 10 s timeline across the 200 px bed: 20 px to the second,
23+ // so halfway along is frame 150.
24+ let fit = Scale {
25+ pps: 20.,
26+ start: 0.,
27+ };
28+ assert_eq!(under(fit, 12.), 0);
29+ assert_eq!(under(fit, 112.), 150);
30+ assert_eq!(under(fit, 212.), 300);
31+
32+ // Four times in, starting at second 5: the same middle pixel is now the
33+ // frame in the middle of seconds 5..7.5, and the left edge is not 0.
34+ let zoomed = Scale {
35+ pps: 80.,
36+ start: 5.,
37+ };
38+ assert_eq!(under(zoomed, 12.), 150);
39+ assert_eq!(under(zoomed, 112.), 187);
40+ assert_eq!(under(zoomed, 212.), 225);
41+ // ...and a pointer that slid off either end of the bed names an end of
42+ // the bed, never a pixel outside it.
43+ assert_eq!(under(zoomed, 0.), 150);
44+ assert_eq!(under(fit, 9999.), 300);
45+}
46+
47+/// The snap: a clip let go a few frames off a neighbour's edge lands *on*
48+/// it, by whichever of its own ends is nearer, and a clip let go in open bed
49+/// stays exactly where the hand left it.
50+#[test]
51+fn a_dropped_clip_snaps_to_the_edges_worth_landing_on() {
52+ // A neighbour covering [100, 160) and the playhead at 300.
53+ let marks = [100, 160, 300, 0];
54+ // Head a frame short of the neighbour's tail: laid end to end with it.
55+ assert_eq!(snapped(158, 40, 4, &marks), 160);
56+ // Tail a frame into its head: pulled back so the two meet exactly.
57+ assert_eq!(snapped(62, 40, 4, &marks), 60);
58+ // The playhead is an edge like any other.
59+ assert_eq!(snapped(298, 40, 4, &marks), 300);
60+ // Outside the tolerance nothing moves -- a gap the hand meant to leave
61+ // is a gap.
62+ assert_eq!(snapped(150, 40, 4, &marks), 150);
63+ // No tolerance at all (zoomed right in, where a few pixels are worth
64+ // less than a frame) is no snap: single frames are placed by hand.
65+ assert_eq!(snapped(158, 40, 0, &marks), 158);
66+ // The nearer edge wins when two are in reach.
67+ assert_eq!(snapped(101, 40, 8, &marks), 100);
68+ // ...and a mark closer to the head than `len` cannot pull the clip to a
69+ // negative start.
70+ assert_eq!(snapped(2, 40, 4, &marks), 0);
71+}
72+
73+/// The shadow a drag draws and the drop that commits are one answer: both
74+/// ask [`landing`], so the box seen in flight is the box the release leaves
75+/// behind. What this pins down is the composition around the snap -- the
76+/// grab offset comes off *before* the magnet, or a clip taken by its tail
77+/// would land a boxful late.
78+#[test]
79+fn a_ghost_and_a_drop_are_one_landing() {
80+ // A neighbour covering [100, 160), the playhead at 300, and a 40 frame
81+ // clip taken hold of 12 frames in.
82+ let marks = [100, 160, 300, 0];
83+ let (len, grab, tol) = (40, 12, 4);
84+ // Pointer at frame 170: the head is 12 frames behind it, at 158, which
85+ // is a frame short of the neighbour's tail -- so both the ghost and the
86+ // drop say 160, and the line stands on the mark that pulled it.
87+ assert_eq!(landing(170, grab, len, true, tol, &marks), (160, Some(160)));
88+ // Without the grab taken off first, the same pointer would land the
89+ // box at 170 and no mark would be in reach: the offset is not cosmetic.
90+ assert_eq!(landing(170, 0, len, true, tol, &marks), (170, None));
91+ // A library row carries no grab and no length the engine has measured,
92+ // which is how `Player::place_frame` asks: only its head lands, on the
93+ // playhead here.
94+ assert_eq!(landing(298, 0, 0, true, tol, &marks), (300, Some(300)));
95+ // The magnet off, ghost and drop agree on the raw frame and no line is
96+ // drawn -- the frame-by-frame placement the switch is for.
97+ assert_eq!(landing(170, grab, len, false, tol, &marks), (158, None));
98+ // A pointer nearer the bed's start than the hand is into the box cannot
99+ // pull a head below zero.
100+ assert_eq!(landing(3, grab, len, true, tol, &marks), (0, Some(0)));
101+}
102+
103+/// Which lanes tint that shadow as refused: the two kinds of file a lane
104+/// cannot hold, in the words the release would say them in -- one rule, so
105+/// what is shown as impossible is exactly what is refused.
106+#[test]
107+fn a_lane_refuses_the_files_it_cannot_hold_before_the_release_says_so() {
108+ let (video, audio) = (Lane::V1, Lane::A1);
109+ let sound = Path::new("/media/take.mp3");
110+ let still = Path::new("/media/card.png");
111+ let movie = Path::new("/media/take.mp4");
112+ assert_eq!(
113+ lane_refuses(sound, video).as_deref(),
114+ Some("NOT ON V1 — take.mp3 has no picture; drop it on an audio lane")
115+ );
116+ assert_eq!(
117+ lane_refuses(still, audio).as_deref(),
118+ Some("NOT ON A1 — card.png is a still image; drop it on a video lane")
119+ );
120+ // ...and every lane a file *can* go on says nothing at all, which is a
121+ // ghost drawn in the file's own colour.
122+ assert_eq!(lane_refuses(sound, audio), None);
123+ assert_eq!(lane_refuses(still, video), None);
124+ assert_eq!(lane_refuses(movie, video), None);
125+ // A file with a picture is not refused by an audio lane here: the
126+ // engine takes its sound onto one, and the words for a video-only file
127+ // are its own.
128+ assert_eq!(lane_refuses(movie, audio), None);
129+}
130+
131+/// Where those edges come from: every lane, not the one being dropped on --
132+/// and never the clip in the hand or the half of it one track down.
133+#[test]
134+fn the_marks_are_every_lane_the_playhead_and_the_start() {
135+ let clip = |start: u32, frames: u32, link| Clip {
136+ start,
137+ in_frame: 0,
138+ out_frame: frames,
139+ source: 0,
140+ link,
141+ eq: None,
142+ color: None,
143+ fit: Default::default(),
144+ speed: Default::default(),
145+ };
146+ // A grouped take across two lanes at 100..160, and a lone one on the
147+ // audio lane at 400..430.
148+ let video = [clip(100, 60, Some(7))];
149+ let audio = [clip(100, 60, Some(7)), clip(400, 30, None)];
150+ let lanes: [&[Clip]; 2] = [&video, &audio];
151+
152+ // Nothing in the hand: both lanes' edges, the playhead, and 0.
153+ let mut all = snap_marks(&lanes, None, 300);
154+ all.sort_unstable();
155+ assert_eq!(all, [0, 100, 100, 160, 160, 300, 400, 430]);
156+
157+ // The video half in the hand: its own edges are gone, and so are its
158+ // group's on the other lane -- both boxes travel with the drag. The
159+ // lone audio clip is still a target, which is the whole point: a take
160+ // being carried on V1 lands flush with a sound on A1.
161+ let mut carried = snap_marks(&lanes, Some((0, 0)), 300);
162+ carried.sort_unstable();
163+ assert_eq!(carried, [0, 300, 400, 430]);
164+
165+ // An index that names no clip skips nothing and still answers.
166+ assert_eq!(snap_marks(&[], Some((3, 9)), 0), [0, 0]);
167+}
168+
169+/// The line the bed draws, and the switch that turns the whole thing off.
170+#[test]
171+fn the_snap_names_the_mark_it_landed_on_unless_it_is_switched_off() {
172+ let marks = [100, 160, 300, 0];
173+ // Pulled by the tail: the clip lands at 60 and the line stands on the
174+ // edge its *tail* met, 100 -- not on the head it happens to have.
175+ assert_eq!(snap_cue(true, 62, 40, 4, &marks), (60, Some(100)));
176+ // Pulled by the head: line and landing are the same frame.
177+ assert_eq!(snap_cue(true, 158, 40, 4, &marks), (160, Some(160)));
178+ // A trim carries no length, so only its own edge lands.
179+ assert_eq!(snap_cue(true, 298, 0, 4, &marks), (300, Some(300)));
180+ // Open bed: nothing moves and nothing is drawn.
181+ assert_eq!(snap_cue(true, 200, 40, 4, &marks), (200, None));
182+ // Switched off, a gesture that would have snapped lands raw and draws
183+ // no line -- the frame-by-frame placement the toggle is for.
184+ assert_eq!(snap_cue(false, 158, 40, 4, &marks), (158, None));
185+}
186+
187+/// The card's rate row: every component the container states and no other,
188+/// so a track the header is silent about is absent from the line rather
189+/// than sitting in it as a zero.
190+#[test]
191+fn a_rate_row_says_only_what_the_container_stated() {
192+ use crate::MediaBitrate;
193+ let all = MediaBitrate {
194+ total: Some(8_432_000),
195+ video: Some(7_918_000),
196+ audio: Some(128_000),
197+ };
198+ assert_eq!(
199+ bitrate_detail(Some(all), 1),
200+ "8.4 Mb/s · 7.9 video · 0.13 sound"
201+ );
202+ // A Matroska states no audio rate of its own: the sound is dropped from
203+ // the line, never drawn as "0".
204+ assert_eq!(
205+ bitrate_detail(
206+ Some(MediaBitrate {
207+ audio: None,
208+ ..all
209+ }),
210+ 1
211+ ),
212+ "8.4 Mb/s · 7.9 video"
213+ );
214+ // A still, or anything that would not open: the probe answered, and the
215+ // answer is that nobody said.
216+ assert_eq!(
217+ bitrate_detail(Some(MediaBitrate::default()), 0),
218+ "not stated"
219+ );
220+ // Asked, not answered yet -- a 12 GB film's walk takes seconds.
221+ assert_eq!(bitrate_detail(None, 2), "…");
222+ // A dual-audio file: the number is the track that plays, and the line
223+ // says so rather than letting it stand for the AC-3 beside it.
224+ assert_eq!(
225+ bitrate_detail(Some(all), 2),
226+ "8.4 Mb/s · 7.9 video · 0.13 1 of 2"
227+ );
228+ // Every component of a tiny file is stated, and small: the line changes
229+ // unit, so not one of them reads as the zero it is not. In megabits
230+ // this file was "0.00 Mb/s · 0.00 video · 0.00 sound".
231+ assert_eq!(
232+ bitrate_detail(
233+ Some(MediaBitrate {
234+ total: Some(4_998),
235+ video: Some(113),
236+ audio: Some(2_400),
237+ }),
238+ 1
239+ ),
240+ "5.0 kb/s · 0.11 video · 2.4 sound"
241+ );
242+}
243+
244+/// The invariant under the row above, over every rate a container can
245+/// state: a component the file *does* state never renders as a zero. The
246+/// probe leaves out what is unstated, so a "0.00" on this card would be it
247+/// saying a track that plays is silent.
248+#[test]
249+fn a_stated_rate_never_renders_as_a_zero() {
250+ use crate::MediaBitrate;
251+ // Every decade from 1 bit a second to a 100 Mb/s master, the rounding
252+ // edges of each unit switch, and every pair of them in one line: the
253+ // line's unit is picked off its smallest component, so the widest
254+ // spread is the one that could round the biggest away.
255+ let edges: Vec<u64> = (0..12)
256+ .flat_map(|e| {
257+ let decade = 10_u64.pow(e);
258+ [decade, decade * 4, decade * 5, decade * 9]
259+ })
260+ .chain([MB_FLOOR - 1, MB_FLOOR, 999_999, 4_998, 113, 2_400])
261+ .collect();
262+ for &small in &edges {
263+ for &big in &edges {
264+ let line = bitrate_detail(
265+ Some(MediaBitrate {
266+ total: Some(small.max(big)),
267+ video: Some(big),
268+ audio: Some(small),
269+ }),
270+ 2,
271+ );
272+ for number in line
273+ .split(" · ")
274+ .filter_map(|part| part.split(' ').next())
275+ .filter_map(|n| n.parse::<f64>().ok())
276+ {
277+ assert!(number > 0., "{small}/{big} bits a second rendered as {line:?}");
278+ }
279+ }
280+ }
281+}
282+
283+#[test]
284+fn timecode_counts_frames_inside_the_second() {
285+ assert_eq!(timecode(0., 30.), "00:00:00:00");
286+ assert_eq!(timecode(-1., 30.), "00:00:00:00"); // clamped, never negative
287+ assert_eq!(timecode(4.9667, 30.), "00:00:04:29"); // last frame of a 5 s clip
288+ assert_eq!(timecode(5., 30.), "00:00:05:00");
289+ assert_eq!(timecode(3661.5, 30.), "01:01:01:15");
290+ // Rounding must not spill into a frame the second does not have.
291+ assert_eq!(timecode(1. - f64::EPSILON, 30.), "00:00:00:29");
292+ assert_eq!(timecode(0.999, 29.97), "00:00:00:29");
293+}
294+
295+#[test]
296+fn scrub_seeks_only_on_a_new_frame_and_only_every_100ms() {
297+ let (slow, fast) = (Duration::from_millis(100), Duration::from_millis(99));
298+ // Both halves must hold: a moved pointer that has not crossed a frame
299+ // boundary would reopen the decoder for the same picture.
300+ assert!(scrub_due(31, 30, slow));
301+ assert!(!scrub_due(30, 30, slow));
302+ assert!(!scrub_due(31, 30, fast));
303+ assert!(!scrub_due(30, 30, fast));
304+ // Exactly at the gap counts, and a long stall never blocks.
305+ assert!(scrub_due(1, 0, Duration::from_secs(9)));
306+}
307+
308+#[test]
309+fn the_picture_is_restarted_only_when_it_is_really_behind_and_not_twice() {
310+ // A quantum's worth of lateness is what every playing frame has; only a
311+ // gap an eye reads as out of sync answers with a reopen.
312+ assert!(!should_resync(0., None));
313+ assert!(!should_resync(LATE_RESYNC, None));
314+ assert!(should_resync(LATE_RESYNC + 0.1, None));
315+ // ...and a decoder that is still behind right after a restart -- the
316+ // usual case, since it was too slow to begin with -- waits out the gap
317+ // instead of reopening at every repaint.
318+ assert!(!should_resync(9., Some(Instant::now())));
319+ assert!(should_resync(
320+ 9.,
321+ Some(Instant::now() - RESYNC_GAP - Duration::from_millis(1))
322+ ));
323+}
324+
325+#[test]
326+fn export_lands_beside_the_source_and_never_on_it() {
327+ // The whole point: the export of an .mp4 is never that .mp4.
328+ assert_eq!(
329+ export_path("assets/test_baseline.mp4"),
330+ std::path::Path::new("assets/test_baseline.export.mp4")
331+ );
332+ // A second export of an export is still not its own source.
333+ assert_eq!(
334+ export_path("a.export.mp4"),
335+ std::path::Path::new("a.export.export.mp4")
336+ );
337+ // Extensionless and dotted-directory names keep the directory intact.
338+ assert_eq!(export_path("clip"), std::path::Path::new("clip.export.mp4"));
339+ assert_eq!(
340+ export_path("/v.1/clip.MP4"),
341+ std::path::Path::new("/v.1/clip.export.mp4")
342+ );
343+}
344+
345+#[test]
346+fn the_first_save_lands_beside_the_media() {
347+ assert_eq!(
348+ project_path("assets/test_av.mp4"),
349+ std::path::Path::new("assets/test_av.edith")
350+ );
351+ // The same rule an export follows: only the last extension moves.
352+ assert_eq!(
353+ project_path("a.export.mp4"),
354+ std::path::Path::new("a.export.edith")
355+ );
356+ assert_eq!(project_path("clip"), std::path::Path::new("clip.edith"));
357+ // Saving a loaded project writes the file it came from, not a second.
358+ assert_eq!(project_path("a.edith"), std::path::Path::new("a.edith"));
359+}
360+
361+#[test]
362+fn only_an_exact_edith_extension_is_a_project() {
363+ let p = std::path::Path::new;
364+ assert!(is_project(p("a.edith")));
365+ // A dotted directory must not decide it -- the file name does.
366+ assert!(is_project(p("/v.mp4/a.edith")));
367+ assert!(!is_project(p("a.mp4")));
368+ assert!(!is_project(p("/v.edith/a.mp4")));
369+ // Exactly what `save_project` writes: a dropped `.EDITH` goes to the
370+ // demuxer and is refused there, not parsed as a project.
371+ assert!(!is_project(p("a.EDITH")));
372+ // An extension, never a bare name.
373+ assert!(!is_project(p("edith")));
374+ assert!(!is_project(p("a.edith.mp4")));
375+}
376+
377+/// The keys menu is the registry drawn, so a *bindable* stroke cannot go
378+/// missing from it by construction. The strokes the modal cards read for
379+/// themselves are the ones that could: this reads the key handler's own
380+/// source and fails on any key it answers to that the menu never mentions.
381+#[test]
382+fn no_stroke_is_missing_from_the_keys_menu() {
383+ use keymap::{ActionId, Keymap};
384+ // Every file the window is written in -- the handler, and the helpers
385+ // it asks, wherever they have been moved to. The tests below compare
386+ // keys too, and are not shortcuts.
387+ let handler = ui_source();
388+ let handler = handler.as_str();
389+ let keymap = Keymap::defaults();
390+ let listed = |key: &str| {
391+ let pretty = keymap::Chord {
392+ key: key.to_string(),
393+ ctrl: false,
394+ }
395+ .pretty();
396+ keymap.lookup(key, false).is_some() || keymap::FIXED.iter().any(|f| f.chord == pretty)
397+ };
398+ let mut compared = 0;
399+ for (at, needle) in handler.match_indices("key == ") {
400+ let rest = &handler[at + needle.len()..];
401+ let key = match rest.strip_prefix('"') {
402+ Some(literal) => {
403+ literal[..literal.find('"').expect("unterminated key")].to_string()
404+ }
405+ // A named constant: the escape the cards get out by.
406+ None if rest.starts_with("ESCAPE") => crate::ESCAPE.to_string(),
407+ None => panic!("a key compared against something this cannot read: {rest:.20}"),
408+ };
409+ assert!(
410+ listed(&key),
411+ "the handler answers to {key:?} and the keys menu never says so"
412+ );
413+ compared += 1;
414+ }
415+ // The scan is only a guard while it still finds the comparisons: a
416+ // rewrite that spells them differently must come back here.
417+ assert!(
418+ compared >= 4,
419+ "the key comparisons moved; this scan is blind"
420+ );
421+ // The one branch that is not a comparison -- any digit is a bitrate.
422+ assert!(handler.contains("key.parse::<u32>()"));
423+ assert!(keymap::FIXED.iter().any(|f| f.chord == "0–9"));
424+ // And every entry of both halves lands under a heading the menu draws.
425+ for action in ActionId::ALL {
426+ assert!(keymap::Category::ALL.contains(&action.category()));
427+ }
428+ for fixed in keymap::FIXED.iter() {
429+ assert!(keymap::Category::ALL.contains(&fixed.category));
430+ }
431+}
432+
433+/// The mapping the whole panel is drawn and clicked through: a moment goes
434+/// to a pixel on the bed and comes back the same moment, at every zoom.
435+#[test]
436+fn a_moment_and_the_place_it_is_drawn_are_the_same_at_every_zoom() {
437+ let duration = 20.;
438+ // The fit, which is the only scale the content's own length picks: 20 s
439+ // across a 200 px bed is 10 px to the second, and a 5 s clip is a
440+ // quarter of the bed -- the answer the fractional view gave for it.
441+ let fit = test_view(Scale::default(), duration).fit();
442+ assert_eq!(fit.pps, 10.);
443+ assert_eq!(fit.width_px(5.), TEST_BED * 0.25);
444+ for t in [0., 5., 12.5, 20.] {
445+ assert_eq!(fit.px_at(t), (t / duration) as f32 * TEST_BED, "fit at {t}");
446+ }
447+ for scale in [
448+ fit,
449+ Scale {
450+ pps: 20.,
451+ start: 4.,
452+ },
453+ Scale {
454+ pps: 80.,
455+ start: 12.5,
456+ },
457+ Scale {
458+ pps: 375.,
459+ start: 19.,
460+ },
461+ ] {
462+ let scale = test_view(scale, duration).settled();
463+ for x in [0., 50., 100., TEST_BED] {
464+ let at = scale.time_at(x);
465+ assert!(
466+ (f64::from(scale.px_at(at)) - f64::from(x)).abs() < 1e-3,
467+ "{scale:?} round trip at {x}"
468+ );
469+ }
470+ // A stretch as long as what is on the bed is as wide as the bed.
471+ assert!(
472+ (f64::from(scale.width_px(test_view(scale, duration).span())) - f64::from(TEST_BED))
473+ .abs()
474+ < 1e-3,
475+ "{scale:?} spans the bed"
476+ );
477+ }
478+}
479+
480+/// The rule that makes a zoom usable: whatever was under the anchor is
481+/// still under it afterwards -- the playhead for a key, the pointer for a
482+/// ctrl+wheel.
483+#[test]
484+fn a_zoom_leaves_the_anchor_where_it_was_on_screen() {
485+ let duration = 20.;
486+ let mut scale = test_view(Scale::default(), duration).settled();
487+ // The same three points along the bed the fractional view held: a half,
488+ // a quarter and nine tenths of 200 px.
489+ for anchor in [100f32, 50., 180.] {
490+ // Well past the zoom-in stop: the anchor holds at the clamp too,
491+ // which is where it used to slide (the clamp came after the offset).
492+ for _ in 0..30 {
493+ let at = scale.time_at(anchor);
494+ let view = test_view(scale, duration);
495+ let zoomed = view.zoomed(ZOOM_STEP, anchor);
496+ // Only where the anchor is not pinned by an edge of the
497+ // timeline: a view already against an end cannot slide further.
498+ let span = test_view(zoomed, duration).span();
499+ let pinned = zoomed.start <= 0. || zoomed.start + span >= duration;
500+ if !pinned {
501+ assert!(
502+ (f64::from(zoomed.px_at(at)) - f64::from(anchor)).abs() < 1e-3,
503+ "{at} moved: {scale:?} -> {zoomed:?}"
504+ );
505+ }
506+ assert!(zoomed.pps >= scale.pps, "and it did zoom in");
507+ scale = zoomed;
508+ }
509+ }
510+}
511+
512+/// Both stops. In is [`ZOOM_MIN_FRAMES`] across the bed; out, on a timeline
513+/// far too short to be worth widening to, is a pixel to the second -- so a
514+/// short import can be zoomed out of, a long one zoomed into, and neither
515+/// can scroll off an end.
516+#[test]
517+fn zoom_stops_at_a_bedful_of_time_and_at_a_handful_of_frames() {
518+ let (duration, fps) = (20., 30.);
519+ let mut scale = Scale::default();
520+ for _ in 0..200 {
521+ scale = test_view(scale, duration).zoomed(1. / ZOOM_STEP, 100.);
522+ }
523+ assert!(
524+ (test_view(scale, duration).span() - f64::from(TEST_BED) / PPS_MIN).abs() < 1e-6,
525+ "widest is a pixel to the second, not the 20 s that happen to be on it"
526+ );
527+ for _ in 0..200 {
528+ scale = test_view(scale, duration).zoomed(ZOOM_STEP, 100.);
529+ }
530+ assert_eq!(
531+ (test_view(scale, duration).span() * fps).round(),
532+ ZOOM_MIN_FRAMES,
533+ "tightest is a handful of frames"
534+ );
535+ // Against the far end, the slice still ends at the last frame.
536+ let end = test_view(
537+ Scale {
538+ start: 1e6,
539+ ..scale
540+ },
541+ duration,
542+ );
543+ let end = (end.settled(), end.span());
544+ assert!((end.0.start + end.1 - duration).abs() < 1e-9);
545+ assert_eq!(
546+ test_view(
547+ Scale {
548+ start: -5.,
549+ ..scale
550+ },
551+ duration
552+ )
553+ .settled()
554+ .start,
555+ 0.
556+ );
557+ // The dead zone the fractional view had: a timeline of a handful of
558+ // frames could not be zoomed at all, because its own length was the
559+ // floor *and* the ceiling. Both keys work on it now.
560+ let tiny = test_view(Scale::default(), 0.1);
561+ assert!(tiny.zoomed(ZOOM_STEP, 100.).pps > PPS_DEFAULT);
562+ assert!(tiny.zoomed(1. / ZOOM_STEP, 100.).pps < PPS_DEFAULT);
563+ // A timeline with no length at all divides by nothing and scrolls
564+ // nowhere; the fit of one keeps the scale it had.
565+ let empty = test_view(Scale::default(), 0.);
566+ assert_eq!(empty.settled(), Scale::default());
567+ assert_eq!(empty.fit(), Scale::default());
568+ assert_eq!(Scale::default().px_at(0.), 0.);
569+ // A bed that was never painted clamps nothing -- there is nothing to
570+ // clamp against, and a zoom must survive the frame before the probe.
571+ let unpainted = View {
572+ bed: 0.,
573+ ..test_view(Scale { pps: 4e6, start: 3. }, duration)
574+ };
575+ assert_eq!(unpainted.settled().pps, 4e6);
576+ assert_eq!(unpainted.following(19.), unpainted.scale);
577+}
578+
579+/// The bug a fixed far stop was: two two-and-a-half hour clips are five
580+/// hours of timeline, longer than any stop measured in hours, so the end of
581+/// the second one could not be brought on screen by any zoom. The stop is
582+/// the timeline's own length now, so it can.
583+#[test]
584+fn zooming_out_reaches_the_end_of_a_timeline_however_long_it_is() {
585+ let bed = 900.;
586+ let view = |scale: Scale, duration: f64| View {
587+ scale,
588+ bed,
589+ duration,
590+ fps: 30.,
591+ };
592+ // As far out as the keys go, from the scale a fresh project is drawn at.
593+ let out = |duration: f64| {
594+ let mut scale = Scale::default();
595+ for _ in 0..400 {
596+ scale = view(scale, duration).zoomed(1. / ZOOM_STEP, 0.);
597+ }
598+ scale
599+ };
600+ let five_hours = 2. * 2.5 * 3600.;
601+ let wide = out(five_hours);
602+ // The whole five hours is on the bed, the last frame drawn inside the
603+ // window rather than against its edge.
604+ assert_eq!(wide.start, 0.);
605+ let end = wide.px_at(five_hours);
606+ assert!(end < bed, "the end of the timeline is off the bed at {end} px");
607+ assert!(end > bed * 0.9, "and not shrunk into a corner: {end} px");
608+ assert!(
609+ (view(wide, five_hours).span() - five_hours * ZOOM_OUT_MARGIN).abs() < 1e-6,
610+ "the far stop is the timeline plus its margin"
611+ );
612+ // Zooming back in still reaches the frame stop on a timeline that long:
613+ // the far stop moving does not drag the near one with it.
614+ let mut scale = wide;
615+ for _ in 0..400 {
616+ scale = view(scale, five_hours).zoomed(ZOOM_STEP, 0.);
617+ }
618+ assert_eq!(
619+ (view(scale, five_hours).span() * 30.).round(),
620+ ZOOM_MIN_FRAMES
621+ );
622+ // And a ten second project is not zoomed out to four hours of empty
623+ // bed: short of a pixel to the second its own length is not worth
624+ // widening to, and that is 900 s of bed, not 14400.
625+ assert!((view(out(10.), 10.).span() - f64::from(bed) / PPS_MIN).abs() < 1e-6);
626+ // Whatever the length, the resting scale is nobody's content: the width
627+ // invariant, which a far stop measured off the content would break.
628+ assert_eq!(view(Scale::default(), 10.).settled(), Scale::default());
629+ assert_eq!(view(Scale::default(), five_hours).settled(), Scale::default());
630+ // Shrinking the timeline pulls a fully zoomed out view in with it --
631+ // what was showing all of the timeline still shows all of it.
632+ let shrunk = view(wide, 1800.).settled();
633+ assert!((view(shrunk, 1800.).span() - 1800. * ZOOM_OUT_MARGIN).abs() < 1e-6);
634+ assert!(shrunk.px_at(1800.) < bed);
635+ // Growing it does not: a scale the user zoomed to is still legal, and
636+ // the stop it stopped at is one press further out.
637+ assert_eq!(view(wide, 2. * five_hours).settled().pps, wide.pps);
638+ assert!(view(wide, 2. * five_hours).zoomed(1. / ZOOM_STEP, 0.).pps < wide.pps);
639+}
640+
641+/// The bare wheel's own move: the view slides along the timeline, what is
642+/// drawn where slides with it, the scale never changes, and both ends stop
643+/// against the content rather than scrolling it off the bed.
644+#[test]
645+fn a_scroll_slides_the_view_without_zooming_it() {
646+ let duration = 60.;
647+ // Zoomed in far enough that there is somewhere to scroll to: 10 s of a
648+ // 60 s timeline on the bed.
649+ let start = test_view(
650+ Scale {
651+ pps: f64::from(TEST_BED) / 10.,
652+ start: 0.,
653+ },
654+ duration,
655+ )
656+ .settled();
657+ let notch = TEST_BED * SCROLL_NOTCH_SHARE;
658+ let on = test_view(start, duration).scrolled(notch);
659+ // A tenth of the bed later, and drawn a tenth of the bed to the left --
660+ // the two halves of one move.
661+ assert_eq!(on.pps, start.pps, "a scroll is not a zoom");
662+ assert!(
663+ (on.start - (start.start + 1.)).abs() < 1e-9,
664+ "one notch is a tenth of the 10 s on the bed: {on:?}"
665+ );
666+ assert!(
667+ (f64::from(start.px_at(20.) - on.px_at(20.)) - f64::from(notch)).abs() < 1e-3,
668+ "and what was drawn moved with it: {on:?}"
669+ );
670+ // Back the other way, from the same place, is the same distance.
671+ let back = test_view(on, duration).scrolled(-notch);
672+ assert!((back.start - start.start).abs() < 1e-9, "{back:?}");
673+ // Neither end can be scrolled off: the head stops at zero, and the tail
674+ // stops with the last frame on the bed -- the clamp is the timeline's
675+ // own length, not a number.
676+ let mut scale = start;
677+ for _ in 0..200 {
678+ scale = test_view(scale, duration).scrolled(notch);
679+ }
680+ assert_eq!(scale.pps, start.pps);
681+ assert!(
682+ (scale.start - (duration - 10.)).abs() < 1e-6,
683+ "the tail stops with the end on the bed: {scale:?}"
684+ );
685+ for _ in 0..200 {
686+ scale = test_view(scale, duration).scrolled(-notch);
687+ }
688+ assert_eq!(scale.start, 0., "and the head stops at the head: {scale:?}");
689+ // A view already showing all of it has nowhere to go.
690+ let whole = test_view(Scale::default(), duration).fit();
691+ assert_eq!(test_view(whole, duration).scrolled(notch), whole);
692+}
693+
694+/// What makes a zoomed timeline follow the playing head: off the bed at
695+/// either end pulls the view onto it, and on the bed it never moves -- a
696+/// view that jumped every frame would be unreadable.
697+#[test]
698+fn the_view_follows_a_playhead_that_runs_off_the_bed() {
699+ let duration = 20.;
700+ // 5 s on a 200 px bed: 40 px to the second, starting at second 5.
701+ let view = test_view(
702+ Scale {
703+ pps: 40.,
704+ start: 5.,
705+ },
706+ duration,
707+ );
708+ let scale = view.settled();
709+ assert_eq!(view.span(), 5.);
710+ // Inside: untouched, whichever part of the slice it is in.
711+ for at in [5., 7.5, 10.] {
712+ assert_eq!(view.following(at), scale, "{at} is on the bed");
713+ }
714+ // Past the right edge, as playback does it: the head comes back on the
715+ // bed, and the scale is not changed by the scroll.
716+ let moved = view.following(12.);
717+ assert_eq!(moved.pps, scale.pps);
718+ assert!(moved.start > scale.start, "scrolled forward");
719+ assert!(
720+ moved.px_at(12.) > 0. && moved.px_at(12.) < TEST_BED,
721+ "and the playhead is on screen"
722+ );
723+ // A seek back behind the slice does the same the other way.
724+ let back = view.following(1.);
725+ assert!(back.start < scale.start);
726+ assert!(back.px_at(1.) >= 0.);
727+ // With the whole timeline on the bed there is nothing to follow.
728+ let whole = test_view(Scale::default(), duration);
729+ let fit = whole.fit();
730+ for at in [0., 10., 20.] {
731+ assert_eq!(
732+ test_view(fit, duration).following(at),
733+ fit,
734+ "the fit never scrolls"
735+ );
736+ }
737+}
738+
739+/// The wheel during playback. A scroll away from the playing head used to
740+/// be undone by the follow on the very next frame -- with a second, longer
741+/// media on the timeline making it scrollable at all, one notch in five
742+/// reached the screen and the wheel looked dead. The hand keeps the view
743+/// now, and the follow takes it back by itself when the head runs into what
744+/// the hand is looking at.
745+#[test]
746+fn a_scroll_during_playback_wins_until_the_head_catches_up() {
747+ let duration = 80.;
748+ let mut scale = test_view(Scale { pps: 40., start: 0. }, duration).settled();
749+ // The render's arbitration, in the two lines it is there: a panned view
750+ // is left where the hand put it, and the pan ends where the head is
751+ // back on the bed.
752+ let frame = |scale: Scale, panned: &mut bool, at: f64| {
753+ let scale = match *panned {
754+ true => test_view(scale, duration).settled(),
755+ false => test_view(scale, duration).following(at),
756+ };
757+ if *panned && test_view(scale, duration).shows(at) {
758+ *panned = false;
759+ }
760+ scale
761+ };
762+ // Playing at second one, five notches of the wheel: every one of them
763+ // moves the view, and none is taken back by the head being off the bed.
764+ let notch = f64::from(TEST_BED * SCROLL_NOTCH_SHARE);
765+ let mut panned = false;
766+ for n in 1..=5 {
767+ scale = test_view(scale, duration).scrolled(TEST_BED * SCROLL_NOTCH_SHARE);
768+ panned = true;
769+ scale = frame(scale, &mut panned, 1.);
770+ // ...and the pan is only *held* while the head is off the bed: the
771+ // first notches still show it, so the follow has the view back for
772+ // free and would not have moved anything anyway.
773+ assert_eq!(panned, scale.start > 1., "held while the head is off");
774+ assert!(
775+ (scale.start - notch * f64::from(n) / 40.).abs() < 1e-6,
776+ "notch {n} reached the screen: {scale:?}"
777+ );
778+ }
779+ // The head runs into it: the pan is given back with nothing pressed...
780+ let span = test_view(scale, duration).span();
781+ let start = frame(scale, &mut panned, scale.start + span / 2.).start;
782+ assert!(!panned, "the follow has the view back");
783+ assert_eq!(start, scale.start, "and it did not jump to take it");
784+ // ...and the next head that runs off the bed pulls the view again.
785+ let ran_off = frame(scale, &mut panned, start + span + 1.);
786+ assert!(ran_off.start > start, "the follow follows again: {ran_off:?}");
787+ // A paused hand is untouched by any of this: with no follow asking,
788+ // `shows` is the only thing the pan is ever released by.
789+ assert!(test_view(scale, duration).shows(scale.start));
790+ assert!(!test_view(scale, duration).shows(scale.start + span + 0.5));
791+}
792+
793+/// The bug this mapping exists for: the first import used to fill the whole
794+/// track whatever it was, because the bed *was* the timeline -- so a 5 s
795+/// clip was 100% of the lane, zooming out did nothing, and adding a second
796+/// clip silently halved the first one's box.
797+#[test]
798+fn a_clip_is_drawn_the_same_width_whatever_else_is_on_the_timeline() {
799+ let bed = 900.;
800+ let of = |duration: f64| View {
801+ scale: Scale::default(),
802+ bed,
803+ duration,
804+ fps: 30.,
805+ };
806+ // One 5 s import, then a second clip after it: 20 s of timeline where
807+ // there were 5, and the first box has not moved or narrowed.
808+ let (alone, joined) = (of(5.).settled(), of(20.).settled());
809+ assert_eq!(alone, joined);
810+ assert_eq!(alone.width_px(5.), joined.width_px(5.));
811+ assert_eq!(joined.px_at(5.), alone.width_px(5.));
812+ // And it does not fill the track: a short clip reads as short.
813+ assert!(
814+ alone.width_px(5.) < bed / 2.,
815+ "5 s at {} px/s is {} px of a {bed} px bed",
816+ alone.pps,
817+ alone.width_px(5.)
818+ );
819+ // Zooming out visibly shrinks it, however short the timeline is -- the
820+ // press that used to be a no-op.
821+ let out = of(5.).zoomed(1. / ZOOM_STEP, 0.);
822+ assert!(
823+ out.width_px(5.) < alone.width_px(5.),
824+ "{} px is not smaller than {} px",
825+ out.width_px(5.),
826+ alone.width_px(5.)
827+ );
828+ // The way back to "the whole timeline across the bed" is still one key.
829+ assert_eq!(of(5.).fit().width_px(5.), bed);
830+}
831+
832+/// What the zoom button says: how much timeline is on the bed, in a unit
833+/// that tells two zooms apart.
834+#[test]
835+fn the_zoom_button_says_how_much_is_on_the_bed() {
836+ assert_eq!(span_label(4.5), "4.5s");
837+ assert_eq!(span_label(22.5), "22s");
838+ assert_eq!(span_label(90.), "1.5m");
839+ assert_eq!(span_label(3600.), "1.0h");
840+ // The span a five hour timeline is zoomed all the way out to.
841+ assert_eq!(span_label(5. * 3600. * 1.05), "5.2h");
842+ // Before the first paint there is no bed and so no answer to give.
843+ assert_eq!(span_label(0.), "—");
844+ assert_eq!(span_label(f64::NAN), "—");
845+ // A span under a second is a span: the tightest zoom is
846+ // `ZOOM_MIN_FRAMES` across the bed, which on 240 fps slow-motion is
847+ // 0.03s, and "0.0s" would be the pill saying nothing is on the bed.
848+ for fps in [60., 120., 240., 1000.] {
849+ let label = span_label(ZOOM_MIN_FRAMES / fps);
850+ assert_ne!(label, "0.0s", "{fps} fps");
851+ assert_ne!(label, "0.00s", "{fps} fps");
852+ }
853+ assert_eq!(span_label(ZOOM_MIN_FRAMES / 240.), "0.03s");
854+ // A frame of quiet at 60 fps, which the silence card says out loud.
855+ assert_eq!(secs_label(1. / 60.), "0.02s");
856+ assert_eq!(secs_label(4.5), "4.5s");
857+}