forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB978e685Tahinli3 months ago627 commits

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