forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

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