forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB7f487c1Tahinli3 months ago659 commits

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