forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBfbc29d1Tahinli2 months ago972 commits

mod.rs281 lines, 11.0 KiBHistoryRawDownload
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
6mod cards;
7mod editing;
8mod layout;
9mod media;
10mod view;
11
12use super::{
13 ACCENT_PRIMARY, AUDIO_KBPS, BENCH_ITEMS, BG_RAISED, BPS_COARSE, BPS_FINE, BPS_MAX, BPS_MIN,
14 COLOR_BANDS, COLOR_BAR_W, COLOR_STEP, COLOR_W, CONTROL_H, Clip, ColorEdit, Ctx,
15 DEFAULT_AUDIO_KBPS, Decoder, EQ_BANDS_MAX, EQ_CURVE_STEPS, EQ_FFT, EQ_FREQ_HIGH, EQ_FREQ_LOW,
16 EQ_FREQ_STEP, EQ_GAIN_LIMIT, EQ_GRAPH_H, EQ_HANDLE, EQ_Q_HIGH, EQ_Q_LOW, EQ_Q_STEP,
17 EQ_SPECTRUM_DB, EQ_TICKS, EQ_W_MAX, ESCAPE, EXPORT_DONE, EXPORT_MOMENT_H, Enable, EncoderSeat,
18 FORMATS, Format, HEADER_H, HIST_BINS, HIST_H, HIST_SAMPLES, HIT_MIN, KEYS_ROW_H, KEYS_W,
19 KeyRow, LABEL_H, LANE_H, LANES_MAX, LATE_RESYNC, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MB_FLOOR,
20 MENU_ITEMS, MENU_PAD, MENU_ROW_H, MENU_W, NO_FILE, NOTICES_MAX, NumberEdit, OVERLAID, PANEL_H,
21 RESYNC_GAP, ROW_ITEMS, RULER_HIT_H, RowCtx, RowItem, SCROLL_NOTCH_SHARE, SILENCE_ROWS,
22 SOURCE_TINTS, SPEED_PRESETS, SPEED_STEP, STATUS_ERROR, STATUS_SUCCESS, STATUS_WARNING,
23 SUB_PLAN_CHARS, Source, Speed, StreamInfo, SubPickKey, TIMELINE_SHARE, Transport, VOLUME_W,
24 VizSlot, Volume, WAVE_BPS, WAVE_COL, WAVE_COLS_MAX, Wave, ZOOM_MIN_FRAMES, active_lane,
25 auto_bps, band_label, bitrate_detail, clipboard_after_remove, color_snap, containers,
26 destructive, enable, enable_lane, envelope, eq_card_w, eq_freq, eq_freq_label, eq_graph_h,
27 eq_spectrum, eq_x, eq_y, estimated_bytes, export_path, export_settings, format_refusal,
28 fps_choices, fps_label, frac_along, frac_down, frame_at, frame_rate_ladder, histogram,
29 inserted_band, is_project, keymap, keys_rows, keys_rows_matching, lane_items, lanes_h, marked,
30 menu_at, menu_items, menu_rows_h, next_container, normalise, nothing_to_play, notice_tone,
31 panel_h, parse_budget, project_path, proxies_to_start, push_notice, px_below, range_word,
32 rate_label, retarget, row_enable, row_items, scrub_due, secs_label, should_resync,
33 silence_rate, size_label, snap_cue, snap_marks, snapped, source_tint, span_partner, speed_at,
34 sub_pick_after_removal, sub_pick_after_restore, subtitle_plan, timecode, timeline_fixed_h,
35 tip_may_paint, transport, typed, unseen_paths, unseen_sources, viz_held_paint, whole_take,
36 window_title,
37};
38
39use super::{
40 ActionId, Choice, EDGE_W, ETA_SPAN, Edge, FITS, FRAME_RATES, IMPORT_STALL, Import, ImportStage,
41 Landing, LaneKind, PPS_DEFAULT, PPS_MIN, Preset, RESOLUTIONS, Repeat, SAMPLE_RATES, SEEK_STALL,
42 Scale, ScanKey, ScanPlan, SilenceScan, SubClip, View, ZOOM_OUT_MARGIN, ZOOM_STEP, arrival,
43 audio_rate_choices, av1_hw_warning, clip_width, clock, encoder_choices, encoder_label,
44 eta_secs, file_name, file_uri, fit_choices, frames_of_us, full_scan_key, import_line, landing,
45 lane_refuses, launch_queue, library_rows, live_idx, next_fit, next_resolution, note_progress,
46 pending_fps_choices, pending_resolution_choices, px_along, read_ahead, repeats,
47 resolution_choices, resolution_ladder, sample_rate_choices, scan_plan, seek_line,
48 silence_cached, silence_line, slice_whole_levels, source_secs, stash_or_write, tone_choices,
49 tone_label, trimmed_clip, trimmed_sub, trims, unscannable, unusable,
50};
51
52use super::{
53 SUB_BOTTOM, SUB_CUE_MIN_W, SUB_LINE_H, SUB_TEXT, Subs, carries_subtitles, cue_box, cues_at,
54 file_tint, is_subtitle, lang_human, sub_bottom, sub_pick_name, subtitle_detail,
55 subtitle_notice, subtitle_rows, subtitle_tail, subtitle_toggle_notice, walk_subtitles,
56};
57
58use engine::PlaybackSession;
59
60use engine::scale::FitPolicy;
61
62use gpui::{Bounds, Pixels, point, px, size};
63
64use std::collections::HashMap;
65
66use std::path::{Path, PathBuf};
67
68use std::time::{Duration, Instant};
69
70use std::sync::{LazyLock, Mutex, MutexGuard, Once};
71
72static CONFIG_ENV_LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));
73
74fn config_env_lock() -> MutexGuard<'static, ()> {
75 CONFIG_ENV_LOCK
76 .lock()
77 .expect("config environment lock poisoned")
78}
79
80/// Tests never open PipeWire. The output seam also refuses a cargo-test
81/// binary under `target/*/deps/`; this pin is the documented door and the
82/// source-scan guard below.
83fn pin_silent_output() {
84 static PIN: Once = Once::new();
85 PIN.call_once(|| {
86 // SAFETY: this process is the test binary; no other thread has
87 // opened a device yet because `asset()` (every session fixture)
88 // calls this first.
89 unsafe { std::env::set_var("VE_NO_AO", "1") };
90 });
91}
92
93/// Every line of the window's source there is, as one string. The regions have
94/// moved house twice -- one `main.rs`, then `ui/`, then the tests out of it --
95/// and a scan that names its files passes a rule by simply not looking where
96/// the code went. So the files are found rather than listed: every `.rs` under
97/// `src/`, read at run time.
98///
99/// For asking *whether* a line is written anywhere. Never slice it: the files
100/// are joined end to end, so a cut that runs to "the next `fn`" runs out of
101/// the file it started in and reads the following one as more of the same
102/// ([`source_from`]).
103fn ui_source() -> String {
104 source_files()
105 .iter()
106 .map(|path| std::fs::read_to_string(path).expect("a source file"))
107 .collect()
108}
109
110/// The one file `needle` is written in, from the needle to the end of *that*
111/// file. Every scan that slices starts here, because the alternative is
112/// slicing [`ui_source()`]: 42 files with 42 seams between them, and the last
113/// fn of any of them -- `silence_card` in `ui/cards.rs` -- read as running on
114/// into the file that happens to follow it. The file is found and not named,
115/// so the code may move house without this going blind.
116fn source_from(needle: &str) -> String {
117 source_files()
118 .iter()
119 .map(|path| std::fs::read_to_string(path).expect("a source file"))
120 .find_map(|text| text.find(needle).map(|at| text[at..].to_string()))
121 .unwrap_or_else(|| panic!("no {needle} in the window's source"))
122}
123
124/// One method's body: from its `fn` line to the ` }` that closes it. The
125/// brace at the impl's own indent is where a method ends and nothing inside
126/// one is written that far out -- which the old cut, "up to the next
127/// `\n fn `", was not: these methods are `pub(crate) fn`, so it matched
128/// none of them and read every card's body as running to the end of the
129/// window instead.
130fn fn_body(name: &str) -> String {
131 let text = source_from(&format!("fn {name}("));
132 let end = text
133 .find("\n }\n")
134 .map_or(text.len(), |at| at + "\n }\n".len());
135 text[..end].to_string()
136}
137
138/// One named file of that source, for the scans about a single region.
139fn src_text(rel: &str) -> String {
140 std::fs::read_to_string(src_dir().join(rel)).expect("a source file")
141}
142
143fn src_dir() -> PathBuf {
144 Path::new(env!("CARGO_MANIFEST_DIR")).join("src")
145}
146
147/// Every source file the scans read, in a stable order. The tests are not the
148/// window, and the keymap is what the window is compared *against* -- a table
149/// that vouched for itself would answer every question asked of it.
150fn source_files() -> Vec<PathBuf> {
151 let mut found = Vec::new();
152 let mut dirs = vec![src_dir()];
153 while let Some(dir) = dirs.pop() {
154 let mut entries: Vec<PathBuf> = std::fs::read_dir(&dir)
155 .expect("the source directory")
156 .map(|entry| entry.expect("a source entry").path())
157 .collect();
158 entries.sort();
159 for path in entries {
160 if path.is_dir() {
161 if path.file_name() != Some("tests".as_ref()) {
162 dirs.push(path);
163 }
164 } else if path.extension() == Some("rs".as_ref())
165 && path.file_name() != Some("keymap.rs".as_ref())
166 {
167 found.push(path);
168 }
169 }
170 }
171 found
172}
173
174fn asset(name: &str) -> PathBuf {
175 pin_silent_output();
176 Path::new(env!("CARGO_MANIFEST_DIR"))
177 .join("../../assets")
178 .join(name)
179}
180
181/// A source entry for `path` on `stream`, as the project keeps them.
182fn source(path: &str, stream: usize) -> Source {
183 Source {
184 path: PathBuf::from(path),
185 audio_stream: stream,
186 }
187}
188
189fn info(index: usize, rate: u32, channels: u16, lang: Option<&str>, decodable: bool) -> StreamInfo {
190 StreamInfo {
191 index,
192 codec: if decodable { "aac" } else { "unknown" }.into(),
193 channels,
194 sample_rate: rate,
195 lang: lang.map(str::to_string),
196 decodable,
197 }
198}
199
200/// The bed the view tests are drawn on: 200 px at 30 fps, as the drop test
201/// above uses.
202const TEST_BED: f32 = 200.;
203
204/// A scale against that bed and a timeline `duration` seconds long.
205fn test_view(scale: Scale, duration: f64) -> View {
206 View {
207 scale,
208 bed: TEST_BED,
209 duration,
210 fps: 30.,
211 }
212}
213
214/// The two halves a worker hands back for an import, unwrapped: every import
215/// lands as a [`Landed::Read`], and a test that has to say so at four call
216/// sites is saying it once here.
217fn read_parts(
218 path: &std::path::Path,
219 stage: &std::sync::atomic::AtomicU8,
220 gate: Option<engine::ImportGate>,
221) -> (Subs, crate::Probe) {
222 match read_ahead(path, stage, gate) {
223 crate::Landed::Read(subs, probe) => (subs, probe),
224 _ => panic!("an import into a timeline that is up lands as a read"),
225 }
226}
227
228/// WCAG 2.1 relative luminance of a packed `0xRRGGBB`.
229fn luminance(colour: u32) -> f64 {
230 let channel = |shift: u32| {
231 let s = f64::from((colour >> shift) & 0xff) / 255.;
232 if s <= 0.03928 {
233 s / 12.92
234 } else {
235 ((s + 0.055) / 1.055).powf(2.4)
236 }
237 };
238 0.2126 * channel(16) + 0.7152 * channel(8) + 0.0722 * channel(0)
239}
240
241/// WCAG 2.1 contrast ratio, 1..=21.
242fn contrast(a: u32, b: u32) -> f64 {
243 let (a, b) = (luminance(a), luminance(b));
244 (a.max(b) + 0.05) / (a.min(b) + 0.05)
245}
246
247/// The two shapes the engine really builds: a track *of* a file states a
248/// language and no title (`of_matroska`, `of_mp4`), and a standalone file
249/// states no language and is its own name (`external`).
250fn sub(path: &str, track: Option<u64>, label: &str) -> engine::subtitle::SubtitleTrack {
251 let (language, name) = match track {
252 Some(_) => (label.to_string(), String::new()),
253 None => (String::new(), label.to_string()),
254 };
255 engine::subtitle::SubtitleTrack {
256 path: PathBuf::from(path),
257 track,
258 language,
259 name,
260 label: label.to_string(),
261 cues: Vec::new(),
262 bitmap: false,
263 refused: None,
264 }
265}
266
267#[test]
268fn the_suite_pins_a_silent_output() {
269 pin_silent_output();
270 assert!(
271 src_text("tests/mod.rs").contains("VE_NO_AO"),
272 "the fixture no longer pins silent output"
273 );
274 let session = PlaybackSession::open(asset("test_av.mp4")).expect("open");
275 let _ = session.set_gain(0.0);
276 assert_eq!(
277 engine::ao::AoSession::devices_opened(),
278 0,
279 "a test opened the speakers"
280 );
281}