forge
Explore
Log in

Don't you dare go Hollow

The window's file lets sixteen neighbourhoods keep their own

Browse files at this commit

963252a1eeb3cebe2d003b0ad434f8404ae97e84Ahmet Kaan GümüşParent: e87ada1
  • chore
    • the window's file lets sixteen neighbourhoods keep their own
Show full message
🔧 chore(app): the window's file lets sixteen neighbourhoods keep their own

main.rs was 10,529 lines with every constant, every helper and the
window itself in one place. The geometry, the transport, the import
state, the menus, the export card, the oracle, the library rows, the
subtitles, the equalizer, the colour card, the viewport and the
timeline's arithmetic each move out to the module they belong to; the
Player and its two impls stay, which is what the file is for.

Pure motion: every line is the line it was, with pub(crate) added only
where a module boundary now stands between it and its caller.
Player::enable still delegates to the one oracle.

17 changed files +4963 -4890

crates/app/src/audio_cards.rsadded+187 -0
@@ -0,0 +1,187 @@
1+//! The equalizer, speed, silence and mixer cards' numbers.
2+
3+use crate::*;
4+
5+/// How far a band may be pushed either way, in dB. The engine clamps nothing
6+/// here -- it will filter whatever it is given -- so this is a UI decision:
7+/// past about this a peaking band stops sounding like tone and starts sounding
8+/// like a fault.
9+pub(crate) const EQ_GAIN_LIMIT: f32 = 12.;
10+
11+/// One dB per keystroke, which is roughly the smallest step anyone hears on a
12+/// single band.
13+pub(crate) const EQ_STEP: f32 = 1.;
14+
15+/// A twentieth of real time per keystroke, in the thousandths a [`Speed`] is
16+/// held in: fine enough to creep up on a rate, coarse enough that the whole
17+/// range is eighty presses and not eight hundred -- and it divides 1000, so
18+/// stepping from anywhere lands on exactly 1.00x on the way past.
19+pub(crate) const SPEED_STEP: i32 = 50;
20+
21+/// The rates the card's buttons offer, so the ones people actually name are one
22+/// click and not a drag. Real time is among them: it is the reset.
23+pub(crate) const SPEED_PRESETS: [u16; 6] = [250, 500, 1000, 1500, 2000, 4000];
24+
25+/// A rate from a number of thousandths that may have run off either end -- what
26+/// a keystroke and a drag both produce. Clamped, not refused: a hand pushing
27+/// past the limit means "as far as it goes", exactly as a trim does.
28+pub(crate) fn speed_at(permille: i32) -> Speed {
29+ Speed::from_permille(permille.clamp(0, i32::from(u16::MAX)) as u16)
30+}
31+
32+/// The silence card's rows, in the order it lists them: how wide the apply
33+/// reaches, the threshold and the unit it is read in, the three durations a
34+/// scan is told, and the rate the speed-up plays at. What `silence_field`
35+/// indexes and what [`Player::nudge_silence`] moves.
36+pub(crate) const SILENCE_ROWS: usize = 7;
37+
38+/// How wide a jumpcut reaches. A ripple used to be the whole timeline's
39+/// business and nothing else; it is a *choice* now, because a podcast track's
40+/// silences are not the music track's business -- and the choice has to be on
41+/// screen, because "everything after this moved" is not a thing to discover
42+/// afterwards.
43+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
44+pub(crate) enum Scope {
45+ /// The lanes of the take the scanned clip belongs to: its picture and its
46+ /// sound stay one take, and nothing else moves. The default, because a clip
47+ /// picked on screen is what a person means by "this".
48+ Take,
49+ /// That clip's lane, alone. Refused by the engine, by name, while the take
50+ /// has a half elsewhere -- detaching is how a person says they mean it.
51+ Track,
52+ /// Every lane, which is what a ripple always was and what the timeline-wide
53+ /// jumpcut still is.
54+ Everything,
55+}
56+
57+/// The order the card cycles them in.
58+pub(crate) const SCOPES: [Scope; 3] = [Scope::Take, Scope::Track, Scope::Everything];
59+
60+impl Scope {
61+ /// What the row says, given the lanes it works out to: the *names* of the
62+ /// tracks, because "this take" means nothing until it says which two.
63+ pub(crate) fn label(self, lanes: &[Lane]) -> String {
64+ let named = lanes
65+ .iter()
66+ .map(|l| l.label())
67+ .collect::<Vec<_>>()
68+ .join("+");
69+ match self {
70+ Scope::Take => format!("this take ({named})"),
71+ Scope::Track => format!("this track ({named})"),
72+ Scope::Everything => "every track".to_string(),
73+ }
74+ }
75+}
76+
77+/// One press of a nudge key on each kind of row: a dB on the threshold, a
78+/// twentieth of a second on the three durations, and the speed card's own step
79+/// on the rate.
80+pub(crate) const SILENCE_DB_STEP: f32 = 1.;
81+pub(crate) const SILENCE_SECS_STEP: f64 = 0.05;
82+
83+/// How far each of them may be pushed. UI decisions, all of them: the engine
84+/// takes any finite number, but a forgiveness of ten seconds finds nothing in a
85+/// talking head. The threshold reaches full scale, which calls a whole take
86+/// silent -- that is a thing someone may want to ask for (the preview on the
87+/// lane says what it would cost before anything is cut), so the top is 0 rather
88+/// than a number this card picked for them.
89+pub(crate) const SILENCE_DB_RANGE: (f32, f32) = (-80., 0.);
90+pub(crate) const SILENCE_SECS_RANGE: (f64, f64) = (0., 5.);
91+
92+/// One press of a nudge key on the mix card, in dB: the step every fader and
93+/// the limiter's ceiling moves by. A whole decibel, the smallest move anyone
94+/// hears as a move -- and it lands on round numbers, so a track set by ear
95+/// still reads as a number a person would say.
96+pub(crate) const MIX_DB_STEP: f32 = 1.;
97+
98+/// The mix card's rows below the faders: the limiter's ceiling and its switch.
99+/// One fader per audio track comes first, however many there are.
100+pub(crate) const MIX_MASTER_ROWS: usize = 2;
101+
102+/// The speed-up rate is bounded *below* by real time: a "speed-up" that slows
103+/// the silence down would make the timeline longer, which is the one thing
104+/// neither button may do. The top is [`Speed::MAX`].
105+pub(crate) fn silence_rate(permille: i32) -> Speed {
106+ speed_at(permille.clamp(
107+ i32::from(Speed::NORMAL.permille()) + SPEED_STEP,
108+ i32::from(Speed::MAX.permille()),
109+ ))
110+}
111+
112+/// The graph's frequency axis: the range an ear works in, and the range every
113+/// band a file can carry sits inside. Log-spaced, so an octave is an octave
114+/// wherever it falls.
115+pub(crate) const EQ_FREQ_LOW: f32 = 20.;
116+pub(crate) const EQ_FREQ_HIGH: f32 = 20_000.;
117+
118+/// The curve box. Tall enough that 1 dB is a visible move at the ±12 dB axis,
119+/// and short enough that the card still fits a 360 px window.
120+pub(crate) const EQ_GRAPH_H: f32 = 132.;
121+
122+/// How wide the equalizer card is allowed to get. It is the one card that is a
123+/// *graph*: every pixel across is frequency resolution, and at the 320 px the
124+/// other cards use, a third of an octave was a couple of pixels. Past this the
125+/// curve stops gaining anything and the card starts reading as a wall.
126+pub(crate) const EQ_W_MAX: f32 = 720.;
127+
128+/// The gap the card leaves either side of it, so it reads as a card on a scrim
129+/// rather than as a second window: it takes the width it can get inside that.
130+pub(crate) const EQ_W_MARGIN: f32 = 32.;
131+
132+/// How many bands one clip's equalizer may carry from this card. Ten because
133+/// the keyboard picks a band with a digit and a keyboard has ten of them --
134+/// past that a band would be reachable by pointer only. The engine itself caps
135+/// nothing (`EqParams::bands` is a plain `Vec`), so a file may still carry more
136+/// and this card will draw and edit every one it finds.
137+pub(crate) const EQ_BANDS_MAX: usize = 10;
138+
139+/// One press of the frequency keys, as a factor: a sixth of an octave, so a
140+/// band walks the whole axis in about sixty presses and still lands close
141+/// enough to a named frequency to aim at one.
142+pub(crate) const EQ_FREQ_STEP: f32 = 1.122_462;
143+
144+/// One press of the Q keys, as a factor, and the range they move in. Below the
145+/// bottom a peak is barely a peak any more; above the top it is a whistle on
146+/// one frequency. 0.707 -- the flat-shelf value, and the default -- sits inside
147+/// them, so nothing a file carries has to be dragged into range first.
148+pub(crate) const EQ_Q_STEP: f32 = 1.25;
149+pub(crate) const EQ_Q_LOW: f32 = 0.3;
150+pub(crate) const EQ_Q_HIGH: f32 = 12.;
151+
152+/// How many points the curve is drawn from. One per ~3 px across the card:
153+/// past that the line is smooth and the extra biquad evaluations are wasted.
154+pub(crate) const EQ_CURVE_STEPS: usize = 96;
155+
156+/// A band's handle on the curve. Only the dot -- what is *grabbed* is the whole
157+/// graph (the nearest band along the frequency axis), so the target is the box.
158+pub(crate) const EQ_HANDLE: f32 = 10.;
159+
160+/// The frequencies the graph names, so the curve can be read as a curve *of
161+/// something*. The two ends label themselves at the edges.
162+pub(crate) const EQ_TICKS: [(f32, &str); 5] = [
163+ (20., "20 Hz"),
164+ (100., "100"),
165+ (1000., "1k"),
166+ (10000., "10k"),
167+ (20000., "20k"),
168+];
169+
170+/// The gains the graph rules a line across, besides the 0 dB one it already
171+/// had: half way to each limit, so a boost can be read as "about six" without
172+/// counting pixels. The limits themselves are the box's own edges and are
173+/// named at the corners instead.
174+pub(crate) const EQ_DB_GRID: [f32; 2] = [6., -6.];
175+
176+
177+/// How many played samples one spectrum frame is transformed from. A power of
178+/// two ([`fft`] is radix-2) and the whole of the engine's tap: 1024 at 48 kHz
179+/// is a 47 Hz bin, fine enough that the bass end is a shape and short enough
180+/// (21 ms) that the analyser moves with the music.
181+pub(crate) const EQ_FFT: usize = 1024;
182+
183+/// The level range the analyser is drawn across, floor to ceiling in dBFS: the
184+/// bottom of the box is silence and the top is a bin at -12 dBFS, which is
185+/// about where a mixed track's loudest band sits. A look, not a measurement --
186+/// the numbers on the axis are the curve's dB, never the analyser's.
187+pub(crate) const EQ_SPECTRUM_DB: (f32, f32) = (-96., -12.);
crates/app/src/color_ui.rsadded+108 -0
@@ -0,0 +1,108 @@
1+//! The colour card's numbers and its histogram.
2+
3+use crate::*;
4+
5+/// The colour card's four controls, in the order it lists them: what each is
6+/// called and the range it moves in. The order is `ColorParams`' own, which is
7+/// what [`color_band`] indexes.
8+pub(crate) const COLOR_BANDS: [(&str, f32, f32); 4] = [
9+ ("Brightness", -1., 1.),
10+ ("Contrast", 0., 2.),
11+ ("Saturation", 0., 2.),
12+ ("Tint (cool–warm)", -1., 1.),
13+];
14+
15+/// A press of a nudge key: a fortieth of a band's range, so a slider crosses it
16+/// in forty presses and every stop is a number the file can write. A drag lands
17+/// on the same grid ([`Player::drag_color`]), so the pointer and the keyboard
18+/// cannot reach two different sets of values.
19+pub(crate) const COLOR_STEP: f32 = 0.05;
20+
21+/// The card's width: a slider row is a label, the bar and the value, and the
22+/// longest label has to fit beside all three without truncating (measured
23+/// against "Tint (cool–warm)").
24+pub(crate) const COLOR_W: f32 = 460.;
25+/// How much of a slider row the bar itself gets -- what a drag is read against,
26+/// so it takes the width the two nudge buttons used to.
27+pub(crate) const COLOR_BAR_W: f32 = 240.;
28+
29+/// The histogram's bins per channel. 64 is four codes of an 8-bit ramp per bin:
30+/// fine enough to see a grade tilt, coarse enough that a subsampled count is
31+/// not noise.
32+pub(crate) const HIST_BINS: usize = 64;
33+
34+/// How many pixels of a frame the histogram reads. The stride is
35+/// `pixels / HIST_SAMPLES` (1920x1080 -> every 253rd pixel), which is a
36+/// thousandth of the frame and walks across columns rather than down one.
37+pub(crate) const HIST_SAMPLES: usize = 8_192;
38+
39+/// The histogram box. Shorter than the equalizer's curve because four slider
40+/// rows stand under it and the card still has to fit a 360 px window.
41+pub(crate) const HIST_H: f32 = 96.;
42+
43+/// A slider value on the [`COLOR_STEP`] grid: what a drag rounds to, so the
44+/// pointer stops where the arrow keys do and "0.35" on screen is the number the
45+/// file writes rather than a rounding of one.
46+pub(crate) fn color_snap(value: f32) -> f32 {
47+ (value / COLOR_STEP).round() * COLOR_STEP
48+}
49+
50+/// How the frame on screen is spread across the tone range: `HIST_BINS` counts
51+/// per channel, read off the BGRA the decoder handed over -- which is the
52+/// *graded* picture, because the grade is folded into the conversion
53+/// (`engine::convert::i420_to_bgra_with`). So what this counts is what the eye
54+/// is looking at, and moving a slider moves it.
55+///
56+/// Every [`HIST_SAMPLES`]th-of-a-frame pixel, not every pixel: a shape drawn
57+/// from eight thousand samples is the same shape, at a thousandth of the reads.
58+pub(crate) fn histogram(bgra: &[u8]) -> [[u32; HIST_BINS]; 3] {
59+ let pixels = bgra.len() / 4;
60+ let stride = (pixels / HIST_SAMPLES).max(1);
61+ let mut bins = [[0u32; HIST_BINS]; 3];
62+ for p in (0..pixels).step_by(stride) {
63+ let px = &bgra[p * 4..];
64+ // BGRA on the wire, `[r, g, b]` in the bins: the graph names channels
65+ // the way a person does.
66+ for (channel, value) in [px[2], px[1], px[0]].into_iter().enumerate() {
67+ bins[channel][usize::from(value) * HIST_BINS / 256] += 1;
68+ }
69+ }
70+ bins
71+}
72+
73+/// The three counts drawn as three lines across the box, tallest bin to the top.
74+///
75+/// Square root, not linear: a shot with a big flat area (a night sky, a title
76+/// card) puts one bin so far above the rest that a linear graph is a single
77+/// spike beside a flat line, and the tilt a grade puts in the rest is exactly
78+/// what the card is for.
79+pub(crate) fn hist_curves(bins: [[u32; HIST_BINS]; 3]) -> impl IntoElement {
80+ canvas(
81+ |_, _, _| (),
82+ move |bounds, _, window, _| {
83+ let (o, s) = (bounds.origin, bounds.size);
84+ // Shared across the channels, so their relative weight is readable;
85+ // never zero, so an unpumped (all-zero) histogram is a flat line
86+ // rather than a division by nothing.
87+ let top = bins.iter().flatten().copied().max().unwrap_or(0).max(1) as f32;
88+ for (channel, counts) in bins.iter().enumerate() {
89+ let mut path = PathBuilder::stroke(px(1.5));
90+ for (bin, &count) in counts.iter().enumerate() {
91+ let at = point(
92+ o.x + s.width * (bin as f32 / (HIST_BINS - 1) as f32),
93+ o.y + s.height * (1. - (count as f32 / top).sqrt()),
94+ );
95+ match bin {
96+ 0 => path.move_to(at),
97+ _ => path.line_to(at),
98+ }
99+ }
100+ if let Ok(path) = path.build() {
101+ window.paint_path(path, rgb(HIST_INK()[channel]));
102+ }
103+ }
104+ },
105+ )
106+ .absolute()
107+ .size_full()
108+}
crates/app/src/eq_ui.rsadded+279 -0
@@ -0,0 +1,279 @@
1+//! The equalizer graph: its geometry, its analyser and its curve.
2+
3+use crate::*;
4+
5+/// Where a frequency sits across the graph, 0..1. Log, because an octave is an
6+/// octave whether it is 40 Hz wide or 10 kHz wide -- a linear axis would spend
7+/// three quarters of the card on the top two octaves and squeeze the bass, the
8+/// half of the range people actually reach for, into nothing.
9+pub(crate) fn eq_x(freq_hz: f32) -> f32 {
10+ let span = (EQ_FREQ_HIGH / EQ_FREQ_LOW).log10();
11+ ((freq_hz.max(1.) / EQ_FREQ_LOW).log10() / span).clamp(0., 1.)
12+}
13+
14+/// The frequency at a fraction across the graph -- [`eq_x`] backwards, which is
15+/// how a drag and the curve's own sample points read one. Clamped to the axis
16+/// either way, so a pointer that leaves the box stops at 20 Hz or 20 kHz.
17+pub(crate) fn eq_freq(along: f32) -> f32 {
18+ EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along.clamp(0., 1.))
19+}
20+
21+/// The band an "add" makes: a flat peak half way -- in octaves, which is what
22+/// the log axis draws -- between the picked band and whatever sits above it, so
23+/// a new band lands in the gap on screen rather than on top of its neighbour.
24+/// Above the topmost band the gap is the rest of the axis.
25+pub(crate) fn inserted_band(bands: &[Band], after: usize) -> Band {
26+ let below = bands.get(after).map_or(1000., |b| b.freq_hz);
27+ let above = bands
28+ .iter()
29+ .map(|b| b.freq_hz)
30+ .filter(|f| *f > below)
31+ .min_by(f32::total_cmp)
32+ .unwrap_or(EQ_FREQ_HIGH);
33+ Band {
34+ freq_hz: (below * above).sqrt().clamp(EQ_FREQ_LOW, EQ_FREQ_HIGH),
35+ gain_db: 0.,
36+ // A shade narrower than the flat-shelf 0.707 the defaults use: a band
37+ // someone asked for is a band they mean to aim, and a wide one aimed at
38+ // 300 Hz is really a band at everything.
39+ q: 1.,
40+ kind: BandKind::Peak,
41+ }
42+}
43+
44+/// Where a gain sits *down* the graph, 0..1 from the top: flat is the middle,
45+/// so a cut reads as a dip below the line it is a cut from. The inverse of
46+/// [`Player::drag_band`]'s reading of the pointer, and clamped like it, so a
47+/// curve loaded from a file with a gain past the card's limit paints on the
48+/// edge of the box rather than outside it.
49+pub(crate) fn eq_y(gain_db: f32) -> f32 {
50+ 0.5 - (gain_db / EQ_GAIN_LIMIT).clamp(-1., 1.) / 2.
51+}
52+
53+/// A frequency as the card writes it. Two decimals of a kHz at most, with the
54+/// zeroes trimmed, so "1 kHz" stays "1 kHz" and a band nudged off it reads as
55+/// 1.12 kHz rather than as the same "1 kHz" it was before the keystroke -- a
56+/// number that does not move under an edit is worse than no number.
57+pub(crate) fn eq_freq_label(freq_hz: f32) -> String {
58+ if freq_hz < 1000. {
59+ return format!("{freq_hz:.0} Hz");
60+ }
61+ let khz = format!("{:.2}", freq_hz / 1000.);
62+ let khz = khz.trim_end_matches('0').trim_end_matches('.');
63+ format!("{khz} kHz")
64+}
65+
66+/// What a band row calls itself: the corner or centre frequency, and for a
67+/// shelf the fact that it tilts everything past it -- which is the difference
68+/// between "12 kHz" moving the last octave and moving one band inside it.
69+pub(crate) fn band_label(band: &Band) -> String {
70+ let freq = eq_freq_label(band.freq_hz);
71+ match band.kind {
72+ BandKind::LowShelf => format!("{freq} low shelf"),
73+ BandKind::HighShelf => format!("{freq} high shelf"),
74+ BandKind::Peak => freq,
75+ }
76+}
77+
78+/// In-place radix-2 FFT of `re`/`im`, whose length must be a power of two.
79+///
80+/// Hand-written, and deliberately: a 1024-point transform once a frame is a
81+/// few tens of microseconds of plain arithmetic, and a dependency for it would
82+/// be a build cost this editor pays on every compile for one card's backdrop.
83+pub(crate) fn fft(re: &mut [f32], im: &mut [f32]) {
84+ let n = re.len();
85+ // Decimation in time: the input is first put in bit-reversed order, after
86+ // which the butterflies run over neighbours.
87+ let mut j = 0usize;
88+ for i in 1..n {
89+ let mut bit = n >> 1;
90+ while j & bit != 0 {
91+ j ^= bit;
92+ bit >>= 1;
93+ }
94+ j |= bit;
95+ if i < j {
96+ re.swap(i, j);
97+ im.swap(i, j);
98+ }
99+ }
100+ let mut span = 2;
101+ while span <= n {
102+ let step = std::f32::consts::TAU / span as f32;
103+ for start in (0..n).step_by(span) {
104+ for k in 0..span / 2 {
105+ // e^{-i2πk/span}: the negative sign is the forward transform.
106+ let (sin, cos) = (-step * k as f32).sin_cos();
107+ let (a, b) = (start + k, start + k + span / 2);
108+ let (tr, ti) = (cos * re[b] - sin * im[b], cos * im[b] + sin * re[b]);
109+ re[b] = re[a] - tr;
110+ im[b] = im[a] - ti;
111+ re[a] += tr;
112+ im[a] += ti;
113+ }
114+ }
115+ span <<= 1;
116+ }
117+}
118+
119+/// The played signal as one height per curve point, 0 (silence) to 1 (the top
120+/// of the box) -- the analyser the response curve is drawn on top of.
121+///
122+/// The newest [`EQ_FFT`] samples of the engine's tap, Hann-windowed so a tone
123+/// that does not land on a bin centre is one hump rather than a smear across
124+/// the axis. Each column takes the *loudest* bin between it and its
125+/// neighbours: the axis is logarithmic, so one column near 20 Hz is a fraction
126+/// of a bin while one near 20 kHz is hundreds, and averaging those would sink
127+/// every peak up there into the noise beside it.
128+///
129+/// Empty -- nothing to draw -- for a tap too short to transform, which is what
130+/// a session has just after a seek.
131+///
132+/// corner-cut: one transform length for the whole axis, so the bass end is a bin
133+/// (47 Hz at 48 kHz) wide however many columns are drawn across it -- a 60 Hz
134+/// hum and an 80 Hz one are the same hump down there. Upgrade path is the
135+/// analyser every mastering EQ uses: two or three transforms of different
136+/// lengths, each drawn over the octaves it resolves.
137+pub(crate) fn eq_spectrum(samples: &[f32], sample_rate: u32) -> Vec<f32> {
138+ if samples.len() < EQ_FFT {
139+ return Vec::new();
140+ }
141+ let tail = &samples[samples.len() - EQ_FFT..];
142+ let mut re: Vec<f32> = tail
143+ .iter()
144+ .enumerate()
145+ .map(|(i, s)| {
146+ let w = 0.5 * (1. - (std::f32::consts::TAU * i as f32 / EQ_FFT as f32).cos());
147+ s * w
148+ })
149+ .collect();
150+ let mut im = vec![0.; EQ_FFT];
151+ fft(&mut re, &mut im);
152+ // Magnitude per bin, scaled so a full-scale sine reads 0 dBFS: half the
153+ // energy is in the mirrored half of the transform, and the Hann window
154+ // takes another factor of two off.
155+ let mags: Vec<f32> = (0..EQ_FFT / 2)
156+ .map(|k| (re[k] * re[k] + im[k] * im[k]).sqrt() * 4. / EQ_FFT as f32)
157+ .collect();
158+ let bin_hz = sample_rate as f32 / EQ_FFT as f32;
159+ let (floor, ceiling) = EQ_SPECTRUM_DB;
160+ let at = |along: f32| EQ_FREQ_LOW * (EQ_FREQ_HIGH / EQ_FREQ_LOW).powf(along);
161+ (0..=EQ_CURVE_STEPS)
162+ .map(|step| {
163+ let along = step as f32 / EQ_CURVE_STEPS as f32;
164+ let half = 0.5 / EQ_CURVE_STEPS as f32;
165+ // Bin 0 is DC and means nothing here, so the low end starts at 1.
166+ let low = (at(along - half) / bin_hz).round().max(1.) as usize;
167+ let high = (at(along + half) / bin_hz).round().max(1.) as usize;
168+ let peak = (low..=high)
169+ .filter_map(|k| mags.get(k))
170+ .fold(0f32, |a, &b| a.max(b));
171+ let db = 20. * peak.max(1e-9).log10();
172+ ((db - floor) / (ceiling - floor)).clamp(0., 1.)
173+ })
174+ .collect()
175+}
176+
177+/// The analyser drawn as one filled shape from the floor of the box.
178+pub(crate) fn eq_spectrum_curve(levels: Vec<f32>) -> impl IntoElement {
179+ canvas(
180+ |_, _, _| (),
181+ move |bounds, _, window, _| {
182+ let (o, s) = (bounds.origin, bounds.size);
183+ let last = levels.len().saturating_sub(1).max(1) as f32;
184+ let mut path = PathBuilder::fill();
185+ path.move_to(point(o.x, o.y + s.height));
186+ for (i, level) in levels.iter().enumerate() {
187+ path.line_to(point(
188+ o.x + s.width * (i as f32 / last),
189+ o.y + s.height * (1. - level),
190+ ));
191+ }
192+ path.line_to(point(o.x + s.width, o.y + s.height));
193+ path.close();
194+ if let Ok(path) = path.build() {
195+ window.paint_path(path, rgba(EQ_SPECTRUM_INK()));
196+ }
197+ },
198+ )
199+ .absolute()
200+ .size_full()
201+}
202+
203+/// The cascade's frequency response, drawn as one line across the graph, with
204+/// each band's own response threaded dimly under it.
205+///
206+/// Every point comes from `EqParams::response_db`, which reads the very
207+/// coefficients the samples are filtered through: the curve cannot drift from
208+/// what is heard, because there is no second copy of the maths. A single band's
209+/// thread is that same call on a cascade of one, so the two cannot disagree
210+/// either -- and it is what makes a boost sitting inside a cut visible at all,
211+/// where the sum alone would draw a flat line and say nothing.
212+///
213+/// corner-cut: bands that overlap can sum past the ±`EQ_GAIN_LIMIT` axis and the
214+/// curve then rides the edge of the box; upgrade = a wider dB axis with the
215+/// handles and [`Player::drag_band`] rescaled to it.
216+pub(crate) fn eq_curve(params: EqParams, sample_rate: u32) -> impl IntoElement {
217+ canvas(
218+ |_, _, _| (),
219+ move |bounds, _, window, _| {
220+ let (o, s) = (bounds.origin, bounds.size);
221+ let line = |of: &EqParams| -> Vec<_> {
222+ (0..=EQ_CURVE_STEPS)
223+ .map(|step| {
224+ let along = step as f32 / EQ_CURVE_STEPS as f32;
225+ point(
226+ o.x + s.width * along,
227+ o.y + s.height
228+ * eq_y(of.response_db(eq_freq(along), sample_rate)),
229+ )
230+ })
231+ .collect()
232+ };
233+ // One thread per band, first, so the sum is drawn over them.
234+ for band in &params.bands {
235+ let mut bell = PathBuilder::stroke(px(1.));
236+ for (step, at) in line(&EqParams {
237+ bands: vec![*band],
238+ })
239+ .into_iter()
240+ .enumerate()
241+ {
242+ match step {
243+ 0 => bell.move_to(at),
244+ _ => bell.line_to(at),
245+ }
246+ }
247+ if let Ok(bell) = bell.build() {
248+ window.paint_path(bell, rgba(EQ_BELL_INK()));
249+ }
250+ }
251+ let points = line(&params);
252+ // The area between the curve and 0 dB, closed along that line: a
253+ // boost and a cut wind opposite ways around it, which is exactly
254+ // what makes both of them fill and the flat parts stay empty.
255+ let mut area = PathBuilder::fill();
256+ area.move_to(point(o.x, o.y + s.height / 2.));
257+ for at in &points {
258+ area.line_to(*at);
259+ }
260+ area.line_to(point(o.x + s.width, o.y + s.height / 2.));
261+ area.close();
262+ if let Ok(area) = area.build() {
263+ window.paint_path(area, rgba(EQ_FILL_INK()));
264+ }
265+ let mut path = PathBuilder::stroke(px(2.));
266+ for (step, at) in points.into_iter().enumerate() {
267+ match step {
268+ 0 => path.move_to(at),
269+ _ => path.line_to(at),
270+ }
271+ }
272+ if let Ok(path) = path.build() {
273+ window.paint_path(path, rgb(ACCENT_PRIMARY()));
274+ }
275+ },
276+ )
277+ .absolute()
278+ .size_full()
279+}
crates/app/src/export_ui.rsadded+810 -0
@@ -0,0 +1,810 @@
1+//! What the export card offers and what it writes.
2+
3+use crate::*;
4+
5+/// The project resolutions [`Player::cycle_resolution`] offers, largest first.
6+/// A short list of the sizes people name; the media's own is cycled in beside
7+/// them, which is what makes the trip round come back to where it started.
8+pub(crate) const RESOLUTIONS: [(u32, u32); 5] = [
9+ (3840, 2160),
10+ (2560, 1440),
11+ (1920, 1080),
12+ (1280, 720),
13+ (854, 480),
14+];
15+
16+/// The project frame rates the list offers, slowest first: the rates footage is
17+/// actually shot and delivered at, the NTSC ones written as the ratios they are
18+/// (`24000/1001`, not `23.976`) -- the engine conforms the timeline to the very
19+/// number it is handed, so a rate rounded here would be a rate no timescale can
20+/// name. The media's own is cycled in beside them
21+/// ([`frame_rate_ladder`]), which is what keeps the way back on the list.
22+pub(crate) const FRAME_RATES: [f64; 8] = [
23+ 24_000. / 1001.,
24+ 24.,
25+ 25.,
26+ 30_000. / 1001.,
27+ 30.,
28+ 50.,
29+ 60_000. / 1001.,
30+ 60.,
31+];
32+
33+/// What the export card offers, top to bottom. Bitrate is the only thing the
34+/// encoder actually takes: the codec and the container are what this program
35+/// can write and nothing else, so the card states them rather than offering
36+/// them.
37+#[derive(Clone, Copy, PartialEq, Debug)]
38+pub(crate) enum Quality {
39+ Auto,
40+ Low,
41+ Medium,
42+ High,
43+ Custom,
44+}
45+
46+impl Quality {
47+ pub(crate) const ALL: [Quality; 5] = [
48+ Quality::Auto,
49+ Quality::Low,
50+ Quality::Medium,
51+ Quality::High,
52+ Quality::Custom,
53+ ];
54+
55+ pub(crate) fn label(self) -> &'static str {
56+ match self {
57+ Quality::Auto => "Auto",
58+ Quality::Low => "Low",
59+ Quality::Medium => "Medium",
60+ Quality::High => "High",
61+ Quality::Custom => "Custom",
62+ }
63+ }
64+
65+ /// The figure the row stands for, said in the units the row is chosen by.
66+ pub(crate) fn detail(self, custom_mbps: u32) -> String {
67+ match self {
68+ Quality::Auto => "from the picture size and frame rate".to_string(),
69+ Quality::Custom => {
70+ format!("{custom_mbps} Mbps — wheel or ± steps, n types one, {MBPS_MIN}–{MBPS_MAX}")
71+ }
72+ other => format!(
73+ "{} Mbps",
74+ export_settings(other, 0, Format::Mp4, DEFAULT_AUDIO_KBPS)
75+ .bitrate
76+ .unwrap_or_default()
77+ / 1_000_000
78+ ),
79+ }
80+ }
81+}
82+
83+/// The export card's format rows: the key that picks one, its name, and what it
84+/// writes -- or, where this program cannot write it, the reason it cannot. A
85+/// format with no entry at all would read as an oversight, and a menu of three
86+/// as a claim that nothing else exists -- so the refusals are rows too, dimmed
87+/// and unclickable.
88+///
89+/// `None` is exactly that kind of row, and there are two left. MP3 stopped
90+/// being one when `rusty_mp3` gave this project an Apache-2.0 encoder (the LGPL
91+/// `shine-rs` was the licence question, and it is not the only encoder any
92+/// more), and HEVC stopped being one when OxideAV's pure-Rust H.265 gave it an
93+/// encoder — an *intra-only* one, which the rows say rather than let a user
94+/// find out from the size of the file. VP9 is the one this program still only
95+/// *reads*: the plugin decodes it and there is no encoder for it here, so it is
96+/// a row for the reason the refusals are rows at all — a codec that opens but
97+/// never comes back out is exactly the gap a user would otherwise go looking
98+/// for. AAC is not a row at all: it is what both containers' sound *is*, never a
99+/// file of its own.
100+///
101+/// A codec is one row, and the boxes it can be written into are the row's
102+/// containers: the same AV1 picture and the same AAC track go into a Matroska
103+/// file or into an mp4, and which one a user needs is about what has to play
104+/// the file, not about the encode. So the container is asked *once*, in a row
105+/// of its own, and only where there is more than one to ask about -- five
106+/// picture rows to read past were four of them saying the same codec twice.
107+pub(crate) const FORMATS: [(&[Format], &str, &str, &str); 8] = [
108+ (
109+ &[Format::Mp4],
110+ "m",
111+ "H.264",
112+ "plays everywhere · AAC sound · MP4 only",
113+ ),
114+ (
115+ &[Format::Av1, Format::Av1Mp4],
116+ "a",
117+ "AV1",
118+ "smallest file for the picture · AAC sound",
119+ ),
120+ (
121+ &[Format::Hevc, Format::HevcMp4],
122+ "h",
123+ "HEVC",
124+ "intra-only, every frame a cut point — large files",
125+ ),
126+ (&[Format::Wav], "w", "WAV", "16-bit PCM — audio only"),
127+ (&[Format::Flac], "f", "FLAC", "lossless — audio only"),
128+ (&[Format::Mp3], "p", "MP3", "MPEG-1 Layer III — audio only"),
129+ (
130+ &[Format::Ogg],
131+ "o",
132+ "OGG",
133+ "Vorbis (rusty_vorbis) — quality-coded, stereo",
134+ ),
135+ (&[], "", "VP9", "AV1 above replaces it"),
136+];
137+
138+/// The codec row a key picks, landed in the container already chosen: pressing
139+/// `a` after an mp4 gives AV1 *in mp4*, because a box decided once is not a
140+/// question again. A letter of the row's own name, spelled out in the table
141+/// rather than taken from the initial (`MP4` and `MP3` share one). Never a
142+/// digit -- those are the bitrate field's. `None` for every other stroke, the rows
143+/// that cannot be picked included.
144+pub(crate) fn format_key(key: &str, current: Format) -> Option<Format> {
145+ FORMATS
146+ .into_iter()
147+ .filter(|(_, stroke, ..)| !stroke.is_empty() && stroke.eq_ignore_ascii_case(key))
148+ .find_map(|(row, ..)| same_box(row, current))
149+}
150+
151+/// The boxes one codec may be written into, in the order its container row
152+/// cycles them. Empty for a codec this program cannot write at all.
153+pub(crate) fn containers(format: Format) -> &'static [Format] {
154+ FORMATS
155+ .into_iter()
156+ .map(|(row, ..)| row)
157+ .find(|row| row.contains(&format))
158+ .unwrap_or(&[])
159+}
160+
161+/// This row's format under the container `current` is already in, or the row's
162+/// first when it has no such box: an AV1 picked from a WAV lands in Matroska,
163+/// and picked from an mp4 stays in the mp4.
164+pub(crate) fn same_box(row: &[Format], current: Format) -> Option<Format> {
165+ row.iter()
166+ .copied()
167+ .find(|f| f.ext() == current.ext())
168+ .or_else(|| row.first().copied())
169+}
170+
171+/// The next box for the same codec, wrapping -- what the container row's key
172+/// does. The format itself for a codec with only one, so the stroke cannot
173+/// change what it is not offering.
174+pub(crate) fn next_container(format: Format) -> Format {
175+ let row = containers(format);
176+ let at = row.iter().position(|&f| f == format).unwrap_or(0);
177+ row.get((at + 1) % row.len().max(1))
178+ .copied()
179+ .unwrap_or(format)
180+}
181+
182+/// The next rate the Sound row offers, wrapping -- what its key does, and what
183+/// the row itself names so the stroke is never a guess. [`next_container`]'s
184+/// shape, for the same reason: one place decides what "next" means.
185+pub(crate) fn next_audio_kbps(kbps: u32) -> u32 {
186+ let at = AUDIO_KBPS.iter().position(|&k| k == kbps).unwrap_or(0);
187+ AUDIO_KBPS[(at + 1) % AUDIO_KBPS.len()]
188+}
189+
190+/// Why the quality rows say nothing about this format, or `None` where they
191+/// decide the picture. Only a picture encoder is given a bitrate here: the two
192+/// lossless audio formats have none to give and MP3 is written at one fixed
193+/// figure, so a live row over either would be a control that changes nothing.
194+pub(crate) fn bitrate_refusal(format: Format) -> Option<&'static str> {
195+ match format {
196+ Format::Wav | Format::Flac => Some("lossless audio — no bitrate to pick"),
197+ Format::Mp3 => Some("sound only — its rate is the Sound row"),
198+ // The guard is the question and not a list of names: an audio format
199+ // added without a line of its own above would otherwise show live
200+ // quality rows over a file that has no picture to spend a bitrate on.
201+ // OGG is exactly that format -- and it wants this sentence rather than
202+ // one of its own, because its *Sound* row already says the Vorbis half
203+ // ("quality-coded — Vorbis holds no rate to pick") and two rows saying
204+ // the same thing is one of them wasted.
205+ _ if !format.has_video() => Some("sound only — no picture to spend a bitrate on"),
206+ _ => None,
207+ }
208+}
209+
210+/// What one of the colour card's own strokes does. Its keys are card-local --
211+/// they mean nothing outside it -- so they are a table here rather than keymap
212+/// bindings, exactly as the export card's format initials are. Listed in
213+/// `keymap::FIXED` all the same, which is how the keys menu still says so.
214+pub(crate) enum ColorKey {
215+ Close,
216+ /// Steps down the four sliders, wrapping.
217+ Band(usize),
218+ /// Moves the picked slider, in [`COLOR_STEP`]s.
219+ Nudge(f32),
220+ Reset,
221+}
222+
223+/// Why the silence card has nothing to scan on that clip, in its own voice: the
224+/// lane and index the user picked, the file it is of, and which of the two
225+/// soundless things it is. One place, because a still and a silent video are
226+/// the same answer to the same question -- "a box with a larger size than it"
227+/// is what the *demuxer* would say about a png, and it is not an answer.
228+///
229+/// Costs nothing: the scan reads a file and writes marks, so a refusal here
230+/// leaves the project (and its undo history) exactly where it was.
231+pub(crate) fn unscannable(lane: Lane, idx: usize, path: &Path) -> String {
232+ let what = match engine::is_image(path) {
233+ true => "is a picture",
234+ false => "is silent",
235+ };
236+ format!(
237+ "{} clip {} has no audio to scan — {} {what}",
238+ lane.label(),
239+ idx + 1,
240+ file_name(path)
241+ )
242+}
243+
244+/// The half of a take whose *sound* the silence card scans: a link is one span
245+/// on however many lanes, so a card opened on the picture opens on the sound it
246+/// is grouped with. That is the lane the waveform is drawn on, and so the lane
247+/// the marks have to land on to be read against it -- and the ranges agree,
248+/// because a group is one span.
249+///
250+/// The clip itself for one already on an audio lane, for a detached picture,
251+/// and for a take whose sound is not on any lane: there is nothing better to
252+/// open on, and the refusal for a source with no audio at all is `scan`'s.
253+pub(crate) fn audio_half(session: &PlaybackSession, (lane, idx): (Lane, usize)) -> (Lane, usize) {
254+ if lane.kind == LaneKind::Audio {
255+ return (lane, idx);
256+ }
257+ let Some(link) = session.lane_clips(lane).get(idx).and_then(|c| c.link) else {
258+ return (lane, idx);
259+ };
260+ session
261+ .lanes()
262+ .into_iter()
263+ .filter(|l| l.kind == LaneKind::Audio)
264+ .find_map(|l| {
265+ session
266+ .lane_clips(l)
267+ .iter()
268+ .position(|c| c.link == Some(link))
269+ .map(|i| (l, i))
270+ })
271+ .unwrap_or((lane, idx))
272+}
273+
274+pub(crate) fn color_key(key: &str) -> Option<ColorKey> {
275+ Some(match key {
276+ ESCAPE => ColorKey::Close,
277+ "down" => ColorKey::Band(1),
278+ "up" => ColorKey::Band(COLOR_BANDS.len() - 1),
279+ "right" => ColorKey::Nudge(1.),
280+ "left" => ColorKey::Nudge(-1.),
281+ "r" => ColorKey::Reset,
282+ _ => return None,
283+ })
284+}
285+
286+/// The band'th control of a grade, to read or to write. The order is
287+/// [`COLOR_BANDS`]', which is the order the card lists them in.
288+pub(crate) fn band_mut(params: &mut ColorParams, band: usize) -> &mut f32 {
289+ match band {
290+ 0 => &mut params.brightness,
291+ 1 => &mut params.contrast,
292+ 2 => &mut params.saturation,
293+ _ => &mut params.tint,
294+ }
295+}
296+
297+/// The line under the rows: what the picked format really writes, in the terms
298+/// a file is judged by afterwards.
299+/// The next policy round the cycle, in the order the action's label reads.
300+/// Every fit policy, in the order the list offers them -- which is the order
301+/// [`next_fit`] steps through them, pinned by the test below: a list and a
302+/// stroke that disagreed about what comes next would be two settings.
303+pub(crate) const FITS: [FitPolicy; 4] = [
304+ FitPolicy::Fit,
305+ FitPolicy::Fill,
306+ FitPolicy::Stretch,
307+ FitPolicy::Center,
308+];
309+
310+pub(crate) fn next_fit(fit: FitPolicy) -> FitPolicy {
311+ match fit {
312+ FitPolicy::Fit => FitPolicy::Fill,
313+ FitPolicy::Fill => FitPolicy::Stretch,
314+ FitPolicy::Stretch => FitPolicy::Center,
315+ FitPolicy::Center => FitPolicy::Fit,
316+ }
317+}
318+
319+/// What a person calls one, said as what it does to the picture.
320+pub(crate) fn fit_label(fit: FitPolicy) -> &'static str {
321+ match fit {
322+ FitPolicy::Fit => "fit (whole picture, bars)",
323+ FitPolicy::Fill => "fill (cropped, no bars)",
324+ FitPolicy::Stretch => "stretch (aspect broken)",
325+ FitPolicy::Center => "centre (1:1, no resample)",
326+ }
327+}
328+
329+/// Every project resolution on offer, largest first: [`RESOLUTIONS`] with the
330+/// media's own size cycled in at its place by size -- so a project already at a
331+/// listed size does not see it twice, and the media's own shape, whatever it is,
332+/// is always on the list. The one order both the stroke and the list use.
333+pub(crate) fn resolution_ladder(native: (u32, u32)) -> Vec<(u32, u32)> {
334+ let mut sizes: Vec<(u32, u32)> = RESOLUTIONS.to_vec();
335+ if !sizes.contains(&native) {
336+ // By area, descending, like the list itself: the cycle then reads as one
337+ // ladder rather than a list with a stray rung at the end.
338+ let at = sizes
339+ .iter()
340+ .position(|&(w, h)| {
341+ u64::from(w) * u64::from(h) < u64::from(native.0) * u64::from(native.1)
342+ })
343+ .unwrap_or(sizes.len());
344+ sizes.insert(at, native);
345+ }
346+ sizes
347+}
348+
349+/// The resolution list's rows: every rung of the ladder, the media's own said
350+/// so, and the one in force marked. A size is named by its height the way the
351+/// button that opens the list names it, with the full figure beside it.
352+pub(crate) fn resolution_choices(current: (u32, u32), native: (u32, u32)) -> Vec<ChoiceRow> {
353+ resolution_ladder(native)
354+ .into_iter()
355+ .map(|(w, h)| {
356+ (
357+ Choice::Size(w, h),
358+ format!("{h}p").into(),
359+ match (w, h) == native {
360+ // Short enough to sit beside the label inside `MENU_W`:
361+ // the longer phrase lost its last word to the truncation.
362+ true => format!("{w}x{h} · the media's own"),
363+ false => format!("{w}x{h}"),
364+ }
365+ .into(),
366+ (w, h) == current,
367+ )
368+ })
369+ .collect()
370+}
371+
372+/// Every project frame rate on offer, slowest first: [`FRAME_RATES`] with the
373+/// media's own cycled in at its place by speed, so a project already cut at a
374+/// listed rate does not see it twice and the media's own rate -- the one a
375+/// project moved off it has no other way back to -- is always there.
376+/// [`resolution_ladder`]'s rule, for the other setting the project has of its
377+/// own.
378+pub(crate) fn frame_rate_ladder(native: f64) -> Vec<f64> {
379+ let mut rates = FRAME_RATES.to_vec();
380+ // Bit for bit: 23.976023976... is not 23.976, and a rate that read as
381+ // "already listed" when it is not would take the media's own off the list.
382+ if !rates.contains(&native) {
383+ let at = rates
384+ .iter()
385+ .position(|&fps| fps > native)
386+ .unwrap_or(rates.len());
387+ rates.insert(at, native);
388+ }
389+ rates
390+}
391+
392+/// The rate list's rows: every rung of the ladder, the media's own said so, and
393+/// the one in force marked. Named as a person writes a rate ([`fps_label`]),
394+/// with what it is for beside it -- short, or the row loses its tail to the
395+/// truncation the resolution list already met.
396+pub(crate) fn fps_choices(current: f64, native: f64) -> Vec<ChoiceRow> {
397+ frame_rate_ladder(native)
398+ .into_iter()
399+ .map(|fps| {
400+ (
401+ Choice::Fps(fps),
402+ format!("{} fps", fps_label(fps)).into(),
403+ match fps == native {
404+ true => "the media's own".to_string(),
405+ // The rates that are a ratio are the ones nobody can tell
406+ // from their neighbour by the label alone.
407+ false => match (fps - fps.round()).abs() < 0.001 {
408+ true => String::new(),
409+ false => "NTSC".to_string(),
410+ },
411+ }
412+ .into(),
413+ fps == current,
414+ )
415+ })
416+ .collect()
417+}
418+
419+/// The fit list's rows: all four policies against the canvas they place a
420+/// picture on, since the word alone ("fill") says nothing about the size it is
421+/// filling -- which is the very thing the notice says after a stroke.
422+pub(crate) fn fit_choices(lane: Lane, idx: usize, current: FitPolicy, (w, h): (u32, u32)) -> Vec<ChoiceRow> {
423+ FITS.into_iter()
424+ .map(|fit| {
425+ (
426+ Choice::Fit(lane, idx, fit),
427+ fit_label(fit).into(),
428+ // The canvas alone, worded as the resolution list words a size:
429+ // the policy names are long and anything wordier here loses its
430+ // tail to the truncation.
431+ format!("{w}x{h}").into(),
432+ fit == current,
433+ )
434+ })
435+ .collect()
436+}
437+
438+/// The sound-rate list's rows: every offered rate, the one in force marked, and
439+/// what each buys said in the fewest words that fit beside the label (a longer
440+/// phrase loses its tail to `MENU_W`'s truncation, as the two lists above say).
441+pub(crate) fn audio_rate_choices(current: u32) -> Vec<ChoiceRow> {
442+ AUDIO_KBPS
443+ .into_iter()
444+ .enumerate()
445+ .map(|(n, kbps)| {
446+ (
447+ Choice::AudioRate(kbps),
448+ format!("{kbps} kbps").into(),
449+ match (kbps, n) {
450+ (DEFAULT_AUDIO_KBPS, _) => "the default",
451+ (_, 0) => "smallest file",
452+ (k, _) if k < DEFAULT_AUDIO_KBPS => "smaller file",
453+ _ => "better sound",
454+ }
455+ .into(),
456+ kbps == current,
457+ )
458+ })
459+ .collect()
460+}
461+
462+/// How a rendition is named where a person reads it: the panel button, the
463+/// notice and the list row all say the same word ([`engine::tonemap::Preset`]).
464+pub(crate) fn tone_label(preset: Preset) -> &'static str {
465+ match preset {
466+ Preset::Reference => "Reference",
467+ Preset::Standard => "Standard",
468+ Preset::Vivid => "Vivid",
469+ }
470+}
471+
472+/// The HDR list's rows: all three renditions, the one in force marked, and what
473+/// each one *is* beside it -- in the fewest words that fit inside `MENU_W`, the
474+/// truncation the three lists above already met. Always offered, whatever is on
475+/// the timeline: a setting that appeared and vanished with the media would be a
476+/// setting nobody could find, and the row says who it acts on instead.
477+pub(crate) fn tone_choices(current: Preset) -> Vec<ChoiceRow> {
478+ Preset::ALL
479+ .into_iter()
480+ .map(|preset| {
481+ (
482+ Choice::Tone(preset),
483+ tone_label(preset).into(),
484+ match preset {
485+ Preset::Reference => "BT.2446-A, as published",
486+ Preset::Standard => "brighter, player-like",
487+ Preset::Vivid => "brightest, richer colour",
488+ }
489+ .into(),
490+ preset == current,
491+ )
492+ })
493+ .collect()
494+}
495+
496+/// The next project resolution after `current`, over [`RESOLUTIONS`] with the
497+/// media's own size cycled in at its place by size -- so the trip round always
498+/// comes back to the media, whatever odd shape it is, and a project already at a
499+/// listed size does not see it twice.
500+pub(crate) fn next_resolution(current: (u32, u32), native: (u32, u32)) -> (u32, u32) {
501+ let sizes = resolution_ladder(native);
502+ let at = sizes.iter().position(|&s| s == current);
503+ // A project at a size nobody listed (a hand-edited file) joins the cycle at
504+ // the top rather than being stuck.
505+ sizes[at.map_or(0, |at| (at + 1) % sizes.len())]
506+}
507+
508+/// The first of the two lines the card keeps above its button: what will be
509+/// *inside* the file. [`format_line`]'s codec and box, then the project's own
510+/// picture size and rate -- which is what a video export is written at however
511+/// many sizes and rates the media on the timeline are -- and last what the
512+/// sound will be, or that there is none. Every field here is one `ffprobe`
513+/// reads back off the finished file, so the line is checkable rather than a
514+/// promise.
515+pub(crate) fn summary_head(format: Format, picture: Option<((u32, u32), f64)>, audio: &str) -> String {
516+ let line = match picture.filter(|_| format.has_video()) {
517+ Some(((w, h), fps)) => {
518+ format!("{} · {w}x{h} · {} fps", format_line(format), fps_label(fps))
519+ }
520+ None => format_line(format).to_string(),
521+ };
522+ join_detail(&line, audio)
523+}
524+
525+/// The second: where it lands, roughly how big, and what will encode the
526+/// picture -- the seat as the probe found it (`…` until it lands, never a
527+/// guess), which is what the running export then names on its progress line.
528+pub(crate) fn summary_tail(path: &Path, bytes: Option<u64>, seat: Option<&'static str>, video: bool) -> String {
529+ let size = bytes.map_or_else(String::new, |bytes| format!("≈ {}", size_label(bytes)));
530+ let seat = match (video, seat) {
531+ (true, Some(seat)) => seat,
532+ (true, None) => "encoder …",
533+ (false, _) => "",
534+ };
535+ join_detail(&join_detail(&file_name(path), &size), seat)
536+}
537+
538+/// A frame rate as a person writes it: `30`, not `30.000`, and `23.976` for the
539+/// rate that is a ratio.
540+pub(crate) fn fps_label(fps: f64) -> String {
541+ match (fps - fps.round()).abs() < 0.001 {
542+ true => format!("{fps:.0}"),
543+ false => format!("{fps:.3}")
544+ .trim_end_matches('0')
545+ .trim_end_matches('.')
546+ .to_string(),
547+ }
548+}
549+
550+/// About how big a *chosen* bitrate makes the file: the picture's bits over the
551+/// timeline's length, in bytes -- the unit the line is written in is
552+/// [`size_label`]'s to pick. `None` for `Auto`, whose figure is the encoder's to
553+/// decide, and for a format with no bitrate at all -- a number nobody picked is
554+/// not an estimate. The sound and the container's own overhead are not in it,
555+/// which is why the card says "≈".
556+pub(crate) fn estimated_bytes(bitrate: Option<u64>, duration: f64) -> Option<u64> {
557+ let bitrate = bitrate.filter(|&b| b > 0 && duration > 0.)?;
558+ Some((bitrate as f64 * duration / 8.).round() as u64)
559+}
560+
561+/// A size in the largest unit that can state it, [`rate_scale`]'s rule:
562+/// megabytes for an export of any length, kilobytes below the one a whole
563+/// megabyte rounds away. A three second clip at the floor bitrate really is
564+/// 375 kB, and "≈ 0 MB" would be this line saying the file it is about to write
565+/// is empty -- the one thing the size field is there to deny. Never "0 kB"
566+/// either: an estimate that exists is at least a kilobyte of file.
567+pub(crate) fn size_label(bytes: u64) -> String {
568+ match (bytes as f64 / 1e6).round() as u64 {
569+ 0 => format!("{} kB", (bytes as f64 / 1e3).round().max(1.) as u64),
570+ mb => format!("{mb} MB"),
571+ }
572+}
573+
574+/// What is in the file and what box it is in, which is the head of the summary.
575+/// Terse on purpose: the fields after it (size, rate, sound) are what the line
576+/// is *for*, and a head that spent its width on prose used to push the whole
577+/// summary onto a second line -- what each codec means is on its row.
578+pub(crate) fn format_line(format: Format) -> &'static str {
579+ match format {
580+ Format::Mp4 => "H.264 · MP4",
581+ Format::Av1 => "AV1 · MKV",
582+ Format::Av1Mp4 => "AV1 · MP4",
583+ Format::Hevc => "HEVC intra · MKV",
584+ Format::HevcMp4 => "HEVC intra · MP4",
585+ // The three whose codec *is* their box: naming it twice would be the
586+ // only field on this line that says nothing.
587+ Format::Wav => "16-bit PCM · WAV",
588+ Format::Flac => "FLAC · lossless",
589+ Format::Mp3 => "MP3 · lossy",
590+ Format::Ogg => "Vorbis · OGG",
591+ }
592+}
593+
594+/// The row a format is picked by, which is what a refusal calls it: the codec,
595+/// since the container is a row of its own now -- `AV1`, not the `mkv` such a
596+/// file is named with.
597+pub(crate) fn format_label(format: Format) -> &'static str {
598+ FORMATS
599+ .iter()
600+ .find(|(row, ..)| row.contains(&format))
601+ .map_or("EXPORT", |(_, _, label, _)| *label)
602+}
603+
604+/// The destination under a format: `take.export.mp4` becomes `take.export.wav`.
605+/// The stem is untouched, so a name typed into the save dialog survives a
606+/// change of mind about the format -- only the extension is the format's to say.
607+pub(crate) fn retarget(path: &std::path::Path, format: Format) -> PathBuf {
608+ let mut path = path.to_path_buf();
609+ path.set_extension(format.ext());
610+ path
611+}
612+
613+/// The card's rows as the engine takes them. `Auto` leaves the bitrate to the
614+/// exporter, which derives it from the picture; the fixed rows are figures that
615+/// hold from 720p to 1080p, and a typed one is passed exactly as typed -- the
616+/// engine clamps every explicit bitrate to 1..50 Mbps (`MAX_EXPLICIT_BITRATE`), so this
617+/// must not clamp it a second time and disagree about where the edge is.
618+///
619+/// The bitrate travels even for an audio format, where the engine ignores it:
620+/// one settings value, and a row the card has dimmed cannot have been changed.
621+pub(crate) fn export_settings(
622+ quality: Quality,
623+ custom_mbps: u32,
624+ format: Format,
625+ audio_kbps: u32,
626+) -> ExportSettings {
627+ ExportSettings {
628+ format,
629+ // Always travels, exactly as the picture's bitrate does above: the
630+ // engine ignores it where nothing encodes the sound, and a row the card
631+ // has dimmed cannot have been changed.
632+ audio_kbps: Some(audio_kbps),
633+ bitrate: match quality {
634+ Quality::Auto => None,
635+ Quality::Low => Some(2_000_000),
636+ Quality::Medium => Some(6_000_000),
637+ Quality::High => Some(12_000_000),
638+ Quality::Custom => Some(u64::from(custom_mbps) * 1_000_000),
639+ },
640+ // No row of its own: the software pin is for a driver that encodes
641+ // badly, which is a thing about the machine and not about the output --
642+ // `VE_SW_ENC` already says it, and to the whole run rather than once.
643+ force_sw: false,
644+ // The picked track is put on by `start_export`, which is the only
645+ // caller that writes a file; the rest of them are asking about the
646+ // bitrate and the format.
647+ subtitles: Vec::new(),
648+ }
649+}
650+
651+/// What the engine will code an explicit bitrate at, in whole Mbps: outside
652+/// this it clamps (`export.rs` `MIN_BITRATE`/`MAX_EXPLICIT_BITRATE`), so a
653+/// number typed past either end would be written as a different one. The field
654+/// refuses it instead of clamping quietly -- a card that changes the user's
655+/// number without saying so is the one thing a field like this must never do.
656+///
657+/// The ceiling was 20, which was never a limit of any encoder here: it was the
658+/// top of the range the exporter *derives* an automatic bitrate in, borrowed as
659+/// the cap on a typed one. A 1080p master or a 4K edit wants more than that, so
660+/// the asked-for rate has its own ceiling now and this is it.
661+pub(crate) const MBPS_MIN: u32 = 1;
662+pub(crate) const MBPS_MAX: u32 = 50;
663+
664+/// How many digits the field takes. Two reach the ceiling; the third is there so
665+/// a number *past* it can be typed whole and refused in its own words, rather
666+/// than being dropped keystroke by keystroke.
667+pub(crate) const MBPS_DIGITS: usize = 3;
668+
669+/// A number being typed into a card row: the digits so far and, once a commit
670+/// has been refused, why. Text-field semantics on a card that has no text field
671+/// -- typing, backspace, arrows that step, enter that commits and escape that
672+/// gives up -- held as state and driven by the root's key handler, since
673+/// nothing in these cards takes gpui focus.
674+#[derive(Clone, Debug, Default, PartialEq, Eq)]
675+pub(crate) struct NumberEdit {
676+ pub(crate) text: String,
677+ pub(crate) refusal: Option<String>,
678+}
679+
680+impl NumberEdit {
681+ /// Starts on the number the row already carries, so backspace edits it
682+ /// rather than the field opening empty over a value that is still in force.
683+ /// Zero is no number at all -- it is what the card opens at, before anyone
684+ /// has typed one.
685+ pub(crate) fn new(value: u32) -> Self {
686+ NumberEdit {
687+ text: match value {
688+ 0 => String::new(),
689+ v => v.to_string(),
690+ },
691+ refusal: None,
692+ }
693+ }
694+
695+ /// A digit against what is there. The one past [`MBPS_DIGITS`] is refused
696+ /// *out loud*: a keystroke dropped in silence is how the old digit capture
697+ /// left the card showing a number the user had already typed past.
698+ pub(crate) fn digit(&mut self, digit: u32) {
699+ if self.text.chars().count() >= MBPS_DIGITS {
700+ self.refusal = Some(format!("{MBPS_DIGITS} digits is already past the ceiling"));
701+ return;
702+ }
703+ match char::from_digit(digit, 10) {
704+ Some(c) => {
705+ self.text.push(c);
706+ self.refusal = None;
707+ }
708+ None => self.refusal = Some("digits only".into()),
709+ }
710+ }
711+
712+ /// Erases the last digit, and the refusal with it: the number on screen has
713+ /// changed, so the reason the old one was refused no longer describes it.
714+ pub(crate) fn backspace(&mut self) {
715+ self.text.pop();
716+ self.refusal = None;
717+ }
718+
719+ /// The arrows, which is how a number gets picked rather than typed. Steps
720+ /// from what is in the field -- an empty one starts at the floor, so the
721+ /// first press up is `MBPS_MIN` and not a jump to some remembered value --
722+ /// and stays inside the range, because a step is a walk through the legal
723+ /// numbers rather than a way out of them.
724+ pub(crate) fn step(&mut self, by: i32) {
725+ let at = self.text.parse::<i32>().unwrap_or(MBPS_MIN as i32 - by.signum());
726+ self.text = (at + by)
727+ .clamp(MBPS_MIN as i32, MBPS_MAX as i32)
728+ .to_string();
729+ self.refusal = None;
730+ }
731+
732+ /// The number, or `None` with the reason recorded where the row will read
733+ /// it. Never clamped: 45 committed as 20 is a number the user did not type.
734+ pub(crate) fn commit(&mut self) -> Option<u32> {
735+ match commit_mbps(&self.text) {
736+ Ok(mbps) => Some(mbps),
737+ Err(why) => {
738+ self.refusal = Some(why);
739+ None
740+ }
741+ }
742+ }
743+
744+ /// What the row shows while it is being typed into: the digits, the caret
745+ /// that says they are landing *here*, and either the refusal or the two
746+ /// keys that end the edit.
747+ pub(crate) fn detail(&self) -> String {
748+ format!(
749+ "{}▏ Mbps — {}",
750+ self.text,
751+ match &self.refusal {
752+ Some(why) => why.as_str(),
753+ None => "enter commits · esc cancels",
754+ }
755+ )
756+ }
757+}
758+
759+/// A typed bitrate as the card takes it, or the reason it is not one. The words
760+/// are the row's: they are what the field shows in place of its hint.
761+pub(crate) fn commit_mbps(text: &str) -> Result<u32, String> {
762+ match text.parse::<u32>() {
763+ Ok(mbps) if (MBPS_MIN..=MBPS_MAX).contains(&mbps) => Ok(mbps),
764+ Ok(0) => Err(format!("0 is not a rate — {MBPS_MIN}–{MBPS_MAX} Mbps")),
765+ Ok(mbps) => Err(format!("{mbps} is past the {MBPS_MAX} Mbps ceiling")),
766+ Err(_) => Err(format!("type a number — {MBPS_MIN}–{MBPS_MAX} Mbps")),
767+ }
768+}
769+
770+/// Whether a stroke gets out of a running export. Escape does, whatever
771+/// modifiers are held with it, for the same reason it gets out of a capture and
772+/// out of the overlay: it is this window's way out, and a way out that only
773+/// works with the right modifiers is not one. Whatever the keymap has on cancel
774+/// works too, so rebinding it adds a way rather than replacing the one that
775+/// always worked -- and that binding is still what the progress line shows.
776+pub(crate) fn cancels_export(key: &str, action: Option<ActionId>) -> bool {
777+ key == ESCAPE || action == Some(ActionId::CancelExport)
778+}
779+
780+/// A clip's share of the lane. A timeline with no length reads as one full-width
781+/// box rather than as NaN, which gpui would carry into layout.
782+/// Why this timeline cannot be written in `format`, if it cannot.
783+///
784+/// An audio-only timeline is the one both picture formats refuse: every frame of
785+/// it is a gap, so the file would be a black picture over the sound. The engine
786+/// refuses it too (`export::start`); this is what greys the row before a
787+/// destination has been picked.
788+///
789+/// It is the *only* reason left. A second audio lane, a speeded clip, a source
790+/// no mp4 sample table holds: each of those used to grey the MP4 row, because
791+/// the mp4 path could only *copy* an AAC track. It re-encodes where a copy
792+/// cannot say what the timeline says (`export::copy_audio`), so none of them is
793+/// a refusal any more -- and every video format carries the sound, so there is
794+/// nothing here that is one format's alone.
795+pub(crate) fn format_refusal(session: &PlaybackSession, format: Format) -> Option<String> {
796+ if !format.has_video() {
797+ return None;
798+ }
799+ let picture = session
800+ .lanes()
801+ .into_iter()
802+ .any(|lane| lane.kind == LaneKind::Video && !session.lane_clips(lane).is_empty());
803+ match picture {
804+ true => None,
805+ false => Some(format!(
806+ "no picture — {} would be black; export WAV, FLAC, MP3 or OGG",
807+ format.name()
808+ )),
809+ }
810+}
crates/app/src/files.rsadded+155 -0
@@ -0,0 +1,155 @@
1+//! Paths in and out: the pickers, the URIs, the names.
2+
3+use crate::*;
4+
5+/// How a finished export announces itself. Written by `poll_export` and read
6+/// by the notice bar, which is what makes that one line clickable.
7+pub(crate) const EXPORT_DONE: &str = "EXPORT DONE → ";
8+
9+/// The path as a URI the bus will take: percent-encoded, because an export
10+/// lands wherever its source lives and those directories have spaces in them.
11+/// Bytes, not chars -- a path is not required to be UTF-8.
12+pub(crate) fn file_uri(path: &std::path::Path) -> String {
13+ use std::os::unix::ffi::OsStrExt;
14+ let mut uri = String::from("file://");
15+ for &b in path.as_os_str().as_bytes() {
16+ match b {
17+ b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => {
18+ uri.push(b as char)
19+ }
20+ _ => uri.push_str(&format!("%{b:02X}")),
21+ }
22+ }
23+ uri
24+}
25+
26+/// Shows a file in the desktop's file manager, selected: the freedesktop
27+/// interface every major one answers, asked for over the session bus. With no
28+/// file manager on the bus the folder itself is the next best thing, and with
29+/// neither there is nothing to say -- the notice the click retired was the
30+/// answer, and a machine without a desktop opener is not one a second notice
31+/// would help. Blocks on two child processes, so it is never called on the UI
32+/// thread.
33+pub(crate) fn show_in_file_manager(path: &std::path::Path) {
34+ // The URI must be absolute; an export path is only as absolute as the
35+ // source it was built from.
36+ let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
37+ let shown = std::process::Command::new("busctl")
38+ .args([
39+ "--user",
40+ "call",
41+ "org.freedesktop.FileManager1",
42+ "/org/freedesktop/FileManager1",
43+ "org.freedesktop.FileManager1",
44+ "ShowItems",
45+ "ass",
46+ "1",
47+ &file_uri(&path),
48+ "",
49+ ])
50+ .status()
51+ .is_ok_and(|s| s.success());
52+ if shown {
53+ return;
54+ }
55+ if let Some(dir) = path.parent() {
56+ let _ = std::process::Command::new("xdg-open").arg(dir).status();
57+ }
58+}
59+
60+/// Runs the first chooser that is installed. `Some(None)` is a cancelled
61+/// dialog; `None` is a machine with no chooser at all, and what still works
62+/// without one differs per dialog, so the caller words that refusal.
63+///
64+/// The desktop's own choosers, asked for by name because gpui 0.2 has no file
65+/// dialog of its own and none of these is worth a dependency.
66+pub(crate) fn run_picker(pickers: [(&str, Vec<String>); 2]) -> Option<Option<PathBuf>> {
67+ for (bin, args) in pickers {
68+ // Not installed: try the next one. Anything else (a cancel, a refusal)
69+ // is that chooser's answer and is taken as final.
70+ let Ok(out) = std::process::Command::new(bin).args(args).output() else {
71+ continue;
72+ };
73+ let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
74+ return Some((!path.is_empty()).then(|| PathBuf::from(path)));
75+ }
76+ None
77+}
78+
79+/// `title` is what the dialog calls itself: two buttons open this same chooser
80+/// for two different questions -- a file to import, a file to take subtitles out
81+/// of -- and a dialog titled "import" over the second one is the wrong question
82+/// answered. No extension filter on either: what can be read is the engine's
83+/// answer (`PlaybackSession::parse_subtitles` takes a container as readily as a
84+/// `.srt`), and a list of suffixes written here would hide a file edith would
85+/// have taken.
86+pub(crate) fn pick_file(title: &str) -> Result<Option<PathBuf>, &'static str> {
87+ run_picker([
88+ (
89+ "zenity",
90+ vec!["--file-selection".into(), format!("--title={title}")],
91+ ),
92+ ("kdialog", vec!["--getopenfilename".into()]),
93+ ])
94+ .ok_or(
95+ "NO FILE CHOOSER — install zenity or kdialog, or drag the file onto this window to import it",
96+ )
97+}
98+
99+/// The save-side dialog, opened on where the export would land anyway: with no
100+/// chooser installed that default is still what gets written, so this refusal
101+/// costs the export nothing and says so.
102+pub(crate) fn pick_save(default: &std::path::Path) -> Result<Option<PathBuf>, &'static str> {
103+ let default = default.to_string_lossy().into_owned();
104+ run_picker([
105+ (
106+ "zenity",
107+ vec![
108+ "--file-selection".into(),
109+ // No `--confirm-overwrite`: zenity 4.2 lists it as deprecated
110+ // and does the confirming itself.
111+ "--save".into(),
112+ "--title=edith — export to".into(),
113+ format!("--filename={default}"),
114+ ],
115+ ),
116+ ("kdialog", vec!["--getsavefilename".into(), default]),
117+ ])
118+ .ok_or(
119+ "NO FILE CHOOSER — install zenity or kdialog to choose where; exporting beside the source",
120+ )
121+}
122+
123+/// Where an export goes: the source path with `.export.mp4` for an extension,
124+/// so it lands beside the original and can never be the original.
125+pub(crate) fn export_path(source: impl Into<PathBuf>) -> PathBuf {
126+ let mut path = source.into();
127+ path.set_extension("export.mp4");
128+ path
129+}
130+
131+/// Where a save goes when the timeline did not come from a project file: the
132+/// media path with `.edith` for an extension, beside it like an export. A
133+/// project loaded from disk keeps its own path instead, so saving it twice
134+/// writes the same file.
135+pub(crate) fn project_path(source: impl Into<PathBuf>) -> PathBuf {
136+ let mut path = source.into();
137+ path.set_extension("edith");
138+ path
139+}
140+
141+/// Whether a dropped or named path is a project rather than media. Exactly the
142+/// lowercase extension `save_project` writes -- anything else goes to the
143+/// demuxer, which is the one that can say what it really is.
144+pub(crate) fn is_project(path: &std::path::Path) -> bool {
145+ path.extension().is_some_and(|e| e == "edith")
146+}
147+
148+/// The tail of a path, for showing. A path that is all root has none, and reads
149+/// as itself.
150+pub(crate) fn file_name(path: &std::path::Path) -> String {
151+ path.file_name().map_or_else(
152+ || path.display().to_string(),
153+ |n| n.to_string_lossy().into(),
154+ )
155+}
crates/app/src/importing.rsadded+374 -0
@@ -0,0 +1,374 @@
1+//! Bringing a file in: the library's tabs, the import and scan state, the stages.
2+
3+use crate::*;
4+
5+/// The library's three categories, in the order the giants list them: the
6+/// pictures, the sound, and the words. A file is in exactly one of them, so a
7+/// tab is a question with an answer rather than a filter with a guess.
8+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
9+pub(crate) enum LibraryTab {
10+ Media,
11+ Audio,
12+ Text,
13+}
14+
15+pub(crate) const LIBRARY_TABS: [LibraryTab; 3] = [LibraryTab::Media, LibraryTab::Audio, LibraryTab::Text];
16+
17+impl LibraryTab {
18+ pub(crate) fn label(self) -> &'static str {
19+ match self {
20+ LibraryTab::Media => "Media",
21+ LibraryTab::Audio => "Audio",
22+ LibraryTab::Text => "Text",
23+ }
24+ }
25+
26+ /// Whether a source belongs on this tab. Subtitles are not sources at all
27+ /// -- they are the [`Player::subtitle_section`] under the list -- so the
28+ /// Text tab holds no rows of its own and says so.
29+ pub(crate) fn holds(self, path: &Path) -> bool {
30+ match self {
31+ LibraryTab::Media => !engine::is_audio(path),
32+ LibraryTab::Audio => engine::is_audio(path),
33+ LibraryTab::Text => false,
34+ }
35+ }
36+
37+ /// What an empty tab says instead of being a blank column.
38+ pub(crate) fn empty(self) -> &'static str {
39+ match self {
40+ LibraryTab::Media => "No video or stills yet — Import, or drop a file on the window",
41+ LibraryTab::Audio => "No sound yet — Import, or drop a file on the window",
42+ LibraryTab::Text => {
43+ "No subtitles yet — Add subtitles from a file, or drop an .srt on the window"
44+ }
45+ }
46+ }
47+}
48+
49+/// What is known about a source's audio. Three states and not two, because a
50+/// file whose peaks have not come back yet must not be drawn as one that has no
51+/// audio at all: the first shows a bed, the second shows nothing.
52+#[derive(Clone)]
53+pub(crate) enum Wave {
54+ /// Asked for; the decode is running on a background thread.
55+ Loading,
56+ /// The file has no audio track. An answer, not a miss.
57+ Silent,
58+ /// The decode failed. Drawn as its own mark rather than as [`Self::Silent`]:
59+ /// "this file's sound could not be read" and "this file has no sound" look
60+ /// the same on a lane, and the first is a bug report waiting to happen.
61+ Failed,
62+ Peaks(Arc<Vec<(f32, f32)>>),
63+}
64+
65+/// The import a worker is reading, as the line above the panel shows it. No
66+/// fraction anywhere: neither read reports how far into the file it has come,
67+/// so what is honest is the file's name, the stage, and two clocks -- one that
68+/// proves the window is answering, one that says the stage has not moved.
69+pub(crate) struct Import {
70+ pub(crate) path: PathBuf,
71+ /// When the worker started, for the elapsed clock.
72+ pub(crate) started: Instant,
73+ /// Written by the worker between its two reads, read here every repaint.
74+ pub(crate) stage: Arc<std::sync::atomic::AtomicU8>,
75+ /// The stage the line last saw and when it last changed. The pair is the
76+ /// whole stall detector: a stage older than [`IMPORT_STALL`] is what the
77+ /// honest wording is for.
78+ pub(crate) seen: ImportStage,
79+ pub(crate) since: Instant,
80+ /// Set by the Cancel beside the line ([`Player::cancel_import`]), read at
81+ /// the landing: what the worker read is dropped instead of joining the
82+ /// timeline.
83+ ///
84+ /// corner-cut: the *read* is not stopped -- a demuxer walk polls nothing, so
85+ /// the worker finishes into a result nobody takes, and the window is given
86+ /// back at the click either way. Ceiling: a cancelled cold 24 GB import
87+ /// still costs the disk its twenty seconds. Upgrade: a flag
88+ /// `engine::demux::Demuxer::open` polls between clusters, which is where an
89+ /// export's own cancel already lives ([`engine::ExportHandle::cancel`]).
90+ pub(crate) cancelled: Arc<std::sync::atomic::AtomicBool>,
91+}
92+
93+impl Import {
94+ /// Reads the worker's stage and keeps the stall clock: it restarts when the
95+ /// stage actually changes and at no other time, which is what makes "has
96+ /// not moved in five seconds" a fact rather than a guess about the elapsed
97+ /// clock. Hands back how long the current stage has stood, so the line has
98+ /// one place to ask.
99+ pub(crate) fn poll(&mut self) -> f32 {
100+ let stage = ImportStage::from_u8(self.stage.load(std::sync::atomic::Ordering::Relaxed));
101+ if stage != self.seen {
102+ self.seen = stage;
103+ self.since = Instant::now();
104+ }
105+ self.since.elapsed().as_secs_f32()
106+ }
107+}
108+
109+/// What a scan is *of*: the source, which of its audio streams, and the clip's
110+/// own `[in, out)` source frames. The range is part of the name because it is
111+/// part of the read -- a clip cut in half is a different, shorter decode than
112+/// the whole take was, and levels read for one are not the other's.
113+pub(crate) type ScanKey = (PathBuf, usize, u32, u32);
114+
115+/// The silence scan a worker is running, as the card shows it. Same two clocks
116+/// as an [`Import`] and for the same reason -- one proves the window answers,
117+/// one says the read has stopped moving -- over a progress that *can* move:
118+/// a decode knows how far into the sound it has come, so the card says so.
119+pub(crate) struct SilenceScan {
120+ /// Source, stream and source range being scanned, which is the cache key
121+ /// the levels land under and what tells a second open of the same clip from
122+ /// a new one.
123+ pub(crate) key: ScanKey,
124+ /// When the worker started, for the elapsed clock.
125+ pub(crate) started: Instant,
126+ /// Written by the worker, read here every repaint. The cancel flag in it is
127+ /// this side's only word to a scan already running.
128+ pub(crate) progress: Arc<engine::silence::Progress>,
129+ /// The tenths-of-a-second mark the line last saw and when it last changed:
130+ /// the stall detector, exactly [`Import::poll`]'s.
131+ pub(crate) seen: u64,
132+ pub(crate) since: Instant,
133+}
134+
135+impl SilenceScan {
136+ /// Reads the worker's mark and keeps the stall clock, restarting it only
137+ /// when the mark actually moves -- [`Import::poll`]'s contract, over a
138+ /// number instead of a stage.
139+ pub(crate) fn poll(&mut self) -> f32 {
140+ let scanned = self.progress.scanned.load(std::sync::atomic::Ordering::Relaxed);
141+ if scanned != self.seen {
142+ self.seen = scanned;
143+ self.since = Instant::now();
144+ }
145+ self.since.elapsed().as_secs_f32()
146+ }
147+}
148+
149+/// How long a stage may sit without moving before the import line stops
150+/// reading like a progress line and says outright that the wait is the file's,
151+/// not the window's. Five seconds: a 25 GB remux spends eleven in its header
152+/// alone, and a person watching a still line for that long has already decided
153+/// the editor hung.
154+pub(crate) const IMPORT_STALL: f32 = 5.;
155+
156+/// Which of an import's two reads the worker is inside. Travels as one atomic,
157+/// the way an export's progress does ([`engine::ExportHandle`]) -- there is no
158+/// fraction to send, because neither read reports where in the file it is.
159+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
160+pub(crate) enum ImportStage {
161+ /// The container header: the sample tables, the cue index, the frame count.
162+ /// Eleven seconds on a cold 29 GB remux, a hundred and fifty milliseconds
163+ /// once the pages are warm -- the whole reason this runs off the UI thread.
164+ Header,
165+ /// The subtitle tracks inside a Matroska, which is a walk over the file's
166+ /// blocks rather than a header read (~200 ms on a two-hour film).
167+ Subtitles,
168+}
169+
170+impl ImportStage {
171+ /// The atomic the worker writes; `u8` because that is what an
172+ /// [`AtomicU8`](std::sync::atomic::AtomicU8) carries.
173+ pub(crate) fn from_u8(n: u8) -> Self {
174+ match n {
175+ 0 => Self::Header,
176+ _ => Self::Subtitles,
177+ }
178+ }
179+
180+ /// What the line calls this stage.
181+ pub(crate) fn what(self) -> &'static str {
182+ match self {
183+ Self::Header => "reading the header",
184+ Self::Subtitles => "reading the subtitle tracks",
185+ }
186+ }
187+}
188+
189+/// argv sorted into the file that becomes the timeline and the queue every
190+/// named file is read through, in the order they were named. The whole of what
191+/// a launch does before the window is on screen -- and it touches no disk,
192+/// which is the point: the header walk happens on a worker with the window
193+/// already up ([`Player::take_import`]).
194+pub(crate) fn launch_queue(
195+ args: impl Iterator<Item = PathBuf>,
196+) -> (Option<PathBuf>, std::collections::VecDeque<PathBuf>) {
197+ let queue: std::collections::VecDeque<PathBuf> = args.collect();
198+ (queue.front().cloned(), queue)
199+}
200+
201+/// What a queued file turns into. Every file goes through one queue -- argv's
202+/// first file, argv's extras, a drop, the Import button -- and this is the fork
203+/// its worker is started on.
204+#[derive(PartialEq, Eq, Debug, Clone, Copy)]
205+pub(crate) enum Landing {
206+ /// The media argv named: it becomes the timeline, and the canvas, the fps,
207+ /// the title and the export path come from it.
208+ Open,
209+ /// A `.edith` argv named: a whole timeline restored, not a source.
210+ Project,
211+ /// Everything else: a row in the library, the timeline untouched.
212+ Import,
213+}
214+
215+/// Which of the three a queued file is (`landing` above is the drag's).
216+/// `opening` is the one path argv named and is cleared as it lands, so a second
217+/// arrival of the same *media* path -- a drop of the film that is already open
218+/// -- is an import, which is what a drop has always been.
219+///
220+/// A `.edith` is never an import, whichever door it came through: it is a whole
221+/// timeline and there is nothing to add it to. Argv's, a dropped one and the
222+/// Import button's are one landing, so the seconds its open costs are the
223+/// worker's for all three ([`open_ahead`]) and the line above the panel names it
224+/// while it runs.
225+pub(crate) fn arrival(opening: Option<&std::path::Path>, path: &std::path::Path) -> Landing {
226+ match (is_project(path), opening == Some(path)) {
227+ (true, _) => Landing::Project,
228+ (false, true) => Landing::Open,
229+ (false, false) => Landing::Import,
230+ }
231+}
232+
233+/// The whole of what an import shows while it runs: which file, which stage,
234+/// the clock that proves the window is still answering, and what is behind it
235+/// in the queue.
236+///
237+/// `since` is how long the *stage* has stood still, which is the only movement
238+/// an unmeasurable read has: past [`IMPORT_STALL`] the line says so in words,
239+/// because a bar that cannot move and a bar that has stopped look identical.
240+///
241+/// `opening` is the file argv named, which is read through the same queue and
242+/// says so in the same words -- except that it is being *opened*, and a line
243+/// that called it an import would be describing the wrong thing to the one
244+/// person who typed the name.
245+pub(crate) fn import_line(
246+ name: &str,
247+ stage: ImportStage,
248+ elapsed: f32,
249+ since: f32,
250+ waiting: usize,
251+ opening: bool,
252+) -> String {
253+ let tail = match waiting {
254+ 0 => String::new(),
255+ n => format!(" · {n} more waiting"),
256+ };
257+ let what = stage.what();
258+ let verb = match opening {
259+ true => "OPENING",
260+ false => "IMPORTING",
261+ };
262+ match since >= IMPORT_STALL {
263+ true => format!(
264+ "{verb} {name} · still {what} — a big file is minutes of reading, and the window is \
265+ not frozen · {} elapsed{tail}",
266+ clock(elapsed)
267+ ),
268+ false => format!("{verb} {name} · {what} · {} elapsed{tail}", clock(elapsed)),
269+ }
270+}
271+
272+/// What opening the silence card on a source costs.
273+#[derive(PartialEq, Eq, Debug)]
274+pub(crate) enum ScanPlan {
275+ /// Its levels are already read: the marks are arithmetic on this frame.
276+ Marks,
277+ /// Nothing read: a worker, and a card that says so meanwhile.
278+ Start,
279+ /// A worker is already reading this very source -- the other half of a take
280+ /// names the same file, and a second card on it waits for the first read
281+ /// rather than throwing away the minute already spent.
282+ Wait,
283+}
284+
285+/// Which of the three [`ScanPlan`]s opening the card on `key` means. The whole
286+/// of the cache policy, and the reason a second film does not cost the first
287+/// one its levels: what is cached is asked per source, never "the last one".
288+pub(crate) fn scan_plan(cached: bool, running: Option<&ScanKey>, key: &ScanKey) -> ScanPlan {
289+ match (cached, running) {
290+ (true, _) => ScanPlan::Marks,
291+ (false, Some(at)) if at == key => ScanPlan::Wait,
292+ _ => ScanPlan::Start,
293+ }
294+}
295+
296+/// The half-open source seconds a [`ScanKey`]'s frames name, at the project's
297+/// rate -- what [`engine::silence::levels`] is asked to read, and the same
298+/// arithmetic playback puts a clip's `in_frame` through. A rate that is not a
299+/// rate reads the whole file rather than an empty window: a scan of nothing is
300+/// worse than a scan of too much.
301+pub(crate) fn source_secs(key: &ScanKey, fps: f64) -> (f64, f64) {
302+ match fps.is_finite() && fps > 0. {
303+ true => (f64::from(key.2) / fps, f64::from(key.3) / fps),
304+ false => (0., f64::INFINITY),
305+ }
306+}
307+
308+/// What the silence card says while its worker reads. Unlike an import this
309+/// one *has* a fraction -- a decode knows how far into the sound it has come --
310+/// so the line is where it is up to, out of what the header claims the track is
311+/// (`total` of 0 for a header that does not say, drawn as nothing rather than
312+/// as a guess). Both in seconds.
313+///
314+/// The stall clock is [`IMPORT_STALL`]'s, for its reason: past five seconds
315+/// without the mark moving, a line that cannot move and a line that has stopped
316+/// look identical, and only one of them is worth words.
317+pub(crate) fn silence_line(scanned: f32, total: f32, elapsed: f32, since: f32) -> String {
318+ let far = match total > 0. {
319+ true => format!("{} of ~{} scanned", clock(scanned), clock(total)),
320+ false => format!("{} scanned", clock(scanned)),
321+ };
322+ match since >= IMPORT_STALL {
323+ true => format!(
324+ "SCANNING · still reading the sound — a big film is minutes of decoding, and the \
325+ window is not frozen · {far} · {} elapsed",
326+ clock(elapsed)
327+ ),
328+ false => format!("SCANNING · {far} · {} elapsed", clock(elapsed)),
329+ }
330+}
331+
332+/// How often a progress mark is worth keeping, how far back the rate is
333+/// measured, and the least span that may answer at all. An export crosses
334+/// hardware and software segments that run at different speeds, so the
335+/// estimate is a window's average and never the instant's.
336+pub(crate) const ETA_SAMPLE: f32 = 0.5;
337+pub(crate) const ETA_WINDOW: f32 = 8.;
338+pub(crate) const ETA_SPAN: f32 = 1.5;
339+
340+/// Records where the export has got to and forgets what has fallen out of the
341+/// window. One mark per `ETA_SAMPLE`, a window's worth kept: a bounded list
342+/// whichever way the encode goes.
343+pub(crate) fn note_progress(marks: &mut Vec<(f32, f32)>, elapsed: f32, progress: f32) {
344+ if marks.last().is_none_or(|&(t, _)| elapsed - t >= ETA_SAMPLE) {
345+ marks.push((elapsed, progress));
346+ }
347+ while marks.len() > 2 && marks[0].0 < elapsed - ETA_WINDOW {
348+ marks.remove(0);
349+ }
350+}
351+
352+/// Seconds left at the window's rate, or `None` while nothing measurable has
353+/// happened yet -- which the line says as "estimating…" rather than as a
354+/// number it would have to take back.
355+pub(crate) fn eta_secs(marks: &[(f32, f32)], elapsed: f32, progress: f32) -> Option<f32> {
356+ // A finished pass is not a guess: it is over.
357+ if progress >= 1. {
358+ return Some(0.);
359+ }
360+ if progress <= 0. || elapsed < ETA_SPAN {
361+ return None;
362+ }
363+ // Two rates, averaged. The window's follows the encode across a
364+ // hardware-to-software handover; the whole run's is what keeps a window
365+ // that is all stall from throwing the number minutes out and back. Neither
366+ // alone reads well: raw window rate spikes eightfold on either edge of a
367+ // stall, and the run average alone never notices a segment change.
368+ let overall = progress / elapsed;
369+ let recent = marks
370+ .first()
371+ .filter(|&&(t, _)| elapsed - t >= ETA_SPAN)
372+ .map_or(overall, |&(t, p)| (progress - p) / (elapsed - t));
373+ Some(2. * (1. - progress) / (recent + overall))
374+}
crates/app/src/interact.rsadded+220 -0
@@ -0,0 +1,220 @@
1+//! What a pointer is doing: the drags, the ghosts, the trims and the key repeat.
2+
3+use crate::*;
4+
5+/// A library row being dragged: the file and which of its audio streams that
6+/// row is, which is the whole of what a row names. Where it lands does not
7+/// change what is inserted.
8+pub(crate) struct AssetDrag(pub(crate) PathBuf, pub(crate) usize);
9+
10+/// A clip already on the timeline being dragged: the lane it is on and its index
11+/// there, which is how every other edit names a clip. Unlike an [`AssetDrag`]
12+/// nothing is inserted -- the same clip changes lane and keeps the frames it
13+/// plays -- but where along the bed it is let go is exactly where it lands, less
14+/// the offset the hand grabbed it at ([`Player::grab`]).
15+#[derive(Clone, Copy)]
16+pub(crate) struct ClipDrag {
17+ pub(crate) lane: Lane,
18+ pub(crate) idx: usize,
19+ /// The clip that was picked up, so the drop can find it again: gpui freezes
20+ /// the payload for the whole gesture, and an edit made *during* one -- a
21+ /// stroke deletes, undoes or pastes, none of which a drag blocks -- ripples
22+ /// the indices under it. The index alone would then name a different take at
23+ /// the release, and the drag would move a clip nobody touched (see
24+ /// [`live_idx`]).
25+ pub(crate) clip: Clip,
26+}
27+
28+/// A track *header* being dragged: which track the hand took hold of, to be
29+/// let go over the header of the one whose place it is to take
30+/// ([`Player::reorder_lane`]). The lane alone -- a track carries its own clips
31+/// wherever it goes, so unlike a [`ClipDrag`] there is nothing else to name.
32+#[derive(Clone, Copy)]
33+pub(crate) struct LaneDrag(pub(crate) Lane);
34+
35+/// Where a header drag in flight would leave the track in the hand: the lane
36+/// whose slot it is about to take, and whether the line is drawn at that lane's
37+/// top edge (it is coming up from below) or its bottom one. The drop indicator
38+/// every editor draws between two tracks, and the header answer to the ghost a
39+/// clip drag lays on a lane ([`Ghost`]) -- stale between gestures, which costs
40+/// nothing because it is drawn only while one is live.
41+#[derive(Clone, Copy, PartialEq)]
42+pub(crate) struct LaneDrop {
43+ pub(crate) lane: Lane,
44+ pub(crate) above: bool,
45+}
46+
47+/// Where the drag in flight would leave what it is carrying: the lane the
48+/// pointer is over, the snapped head the release will commit ([`landing`]), and
49+/// how long the thing is. Drawn on that lane as a translucent box the size of
50+/// the take, so a landing is *seen* before the release rather than discovered
51+/// after it -- the line ([`Player::snap_cue`]) marks the frame, this shows the
52+/// body. `refused` is a drop the lane cannot take -- a picture over an audio
53+/// track, a sound over a video one -- tinted rather than silent, because the
54+/// refusal is coming at the release either way ([`lane_refuses`],
55+/// [`Project::move_clip`]).
56+#[derive(Clone, Copy, PartialEq)]
57+pub(crate) struct Ghost {
58+ pub(crate) lane: Lane,
59+ pub(crate) start: u32,
60+ /// Timeline frames, which a speed has already been counted into: the box is
61+ /// as wide as the clip is *long where it lands*. Zero for a library row of
62+ /// unknown length, drawn as a head marker.
63+ pub(crate) frames: u32,
64+ /// The swatch of the file being carried ([`file_tint`]), so the
65+ /// ghost reads as the thing in the hand.
66+ pub(crate) tint: u32,
67+ pub(crate) refused: bool,
68+}
69+
70+/// A clip edge being dragged: which end of which clip, and the timeline frame
71+/// the pointer has pulled it to. The box on screen is drawn from `to` while this
72+/// is set and the engine hears about it once, at the release
73+/// ([`Player::commit_trim`]) -- one edit, one undo step for the whole gesture,
74+/// exactly as an equalizer drag works.
75+#[derive(Clone, Copy)]
76+pub(crate) struct Trim {
77+ pub(crate) lane: Lane,
78+ pub(crate) idx: usize,
79+ pub(crate) edge: Edge,
80+ /// Already clamped by `PlaybackSession::trim_room`, so the width drawn from
81+ /// it is the width the release commits -- an edge stops under the pointer
82+ /// rather than snapping back after the fact.
83+ pub(crate) to: u32,
84+ /// The dragged clip's group, so its other halves' boxes follow the edge on
85+ /// screen exactly as the engine will move them.
86+ pub(crate) link: Option<u32>,
87+}
88+
89+/// How wide a clip's edge is as a *target*: the strip at each end where a press
90+/// means "make this longer or shorter" instead of "move this to another lane".
91+/// Wide enough to hit, narrow enough that the middle of even a small box is
92+/// still the body.
93+pub(crate) const EDGE_W: f32 = 6.;
94+
95+/// Whether a clip box this wide gets its two trim strips at all. Below three
96+/// handles wide the pair would occlude the whole box: every press on it would
97+/// trim, and the clip could not be selected, dragged to another lane or picked
98+/// up by its middle -- which is exactly what a jumpcut leaves behind
99+/// ([`Player::cut_silences`] manufactures a great many short clips). Above it,
100+/// what is left between the two strips is a handle's width of body in its own
101+/// right. A clip too short for its handles is trimmed by zooming in first: the
102+/// bed is a magnifier, and the strip grows with the box.
103+pub(crate) fn trims(width: f32) -> bool {
104+ width >= 3. * EDGE_W
105+}
106+
107+/// How wide a clip's box is *drawn*, given the width its own length is worth
108+/// (`span`). Never under [`HIT_MIN`], even where that is wider than the clip is
109+/// long: zoomed far out a short take is worth a fraction of a pixel, and a box
110+/// nobody can put a pointer on is a clip that cannot be selected, dragged, given
111+/// a menu or reached at all -- which is strictly worse than one drawn a few
112+/// pixels too wide. The same call [`cue_box`] makes for a mark, and what every
113+/// editor draws.
114+///
115+/// A drawing only: [`Scale::time_at`] still reads the bed, so a press inside the
116+/// padding names the frame it points at, and the box's head is the clip's own.
117+pub(crate) fn clip_width(span: f32) -> f32 {
118+ span.max(HIT_MIN)
119+}
120+
121+/// The sheet a card or a menu is painted on: the whole window, and the mouse
122+/// stops at it. Occluding is what tells gpui that nothing under this sheet is
123+/// hovered any more (`Hitbox::is_hovered`) -- without it the window carries on
124+/// hovering behind an open menu and pops *its* tooltip over the menu's items,
125+/// which is a card being painted over by the thing it covers.
126+///
127+/// Every card and every menu takes its sheet from here, so no surface can be
128+/// drawn over the top of one by having been given a plain scrim.
129+pub(crate) fn scrim() -> Div {
130+ div().absolute().inset_0().occlude()
131+}
132+
133+/// The sheet a card with a *slider* in it takes instead: the same scrim, with
134+/// the window's own drag listeners on it as well.
135+///
136+/// A scrim occludes, and occluding is where gpui's hit test stops
137+/// (`Hitbox::is_hovered`, window.rs:788) -- so while a card is up the root is
138+/// not hovered anywhere behind it and its `on_mouse_move`/`on_mouse_up` hear
139+/// nothing at all. Every drag in this window is tracked from the root, because
140+/// each of them starts on a strip a few pixels wide that the pointer leaves at
141+/// once ([`Player::drag_move`]), so a card's handles were set by the press and
142+/// then frozen: the value never followed the hand and the release never wrote.
143+/// The scrim is the one surface above the occluder that covers the whole card,
144+/// so the same two listeners go here, and a drag that leaves the card is picked
145+/// up by the root's copy of them without a seam.
146+pub(crate) fn drag_scrim(cx: &mut Context<Player>) -> Div {
147+ scrim()
148+ .on_mouse_move(cx.listener(Player::drag_move))
149+ .on_mouse_up(MouseButton::Left, cx.listener(Player::drag_release))
150+}
151+
152+/// A press that stops here. What every card's body hands its scrim: the scrim
153+/// closes the card on a press, and the card is painted after it, so this listener
154+/// runs first (gpui dispatches topmost-first, window.rs:3705) and a press meant
155+/// for a button never closes the card out from under its own click -- the rule
156+/// the menus already follow ([`Player::library_card`]).
157+pub(crate) fn swallow(_: &MouseDownEvent, _: &mut Window, cx: &mut App) {
158+ cx.stop_propagation();
159+}
160+
161+/// How close to an edge a dragged clip has to be let go for it to land *on* it:
162+/// the snap every timeline has, in pixels rather than frames so that it feels
163+/// the same at every zoom. Narrower than [`EDGE_W`] -- a hand aiming between two
164+/// takes must still be able to leave a gap of a few frames there.
165+pub(crate) const SNAP_PX: f64 = 5.;
166+
167+/// Where a held key would land, which is the whole of what auto-repeat has to
168+/// know. [`Player::repeat_scope`] answers it from the same state the handler
169+/// walks below itself.
170+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
171+pub(crate) enum Repeat {
172+ /// A card with values in it owns the keyboard: equalizer, colour, speed or
173+ /// silence. Its arrows are sliders.
174+ Card,
175+ /// Nobody does, so the keymap answers -- and only one pair of its actions
176+ /// is a value being moved rather than a thing being done once.
177+ Keymap,
178+ /// A stroke is being captured, an export is running, or an overlay with no
179+ /// value in it is up. Nothing there is worth a repeat.
180+ Nothing,
181+}
182+
183+/// Whether a *held* stroke means it again. One press is always one action; a
184+/// hold is only ever a value running, so this is what tells the two apart.
185+///
186+/// The cards' arrows, because that is what every one of them moves a slider
187+/// with -- and only the arrows, so the equalizer's `r` cannot flatten five
188+/// bands forty times a second and the silence card's `enter` cannot cut forty
189+/// places again on the next tick. Outside a card the volume pair and nothing
190+/// else: play, cut, delete, save, export and every other binding is a one-shot,
191+/// exactly as it was when the handler filtered every held key alike.
192+pub(crate) fn repeats(scope: Repeat, key: &str, action: Option<ActionId>) -> bool {
193+ match scope {
194+ Repeat::Card => matches!(key, "up" | "down" | "left" | "right"),
195+ Repeat::Keymap => matches!(
196+ action,
197+ Some(
198+ ActionId::VolumeUp
199+ | ActionId::VolumeDown
200+ // A zoom is a value being moved as much as a level is:
201+ // held, it runs from the whole timeline down to a handful
202+ // of frames and stops there. The fit is one press.
203+ | ActionId::ZoomIn
204+ | ActionId::ZoomOut
205+ )
206+ ),
207+ Repeat::Nothing => false,
208+ }
209+}
210+
211+/// The keys that are only ever half a chord. gpui delivers a lone modifier
212+/// press as a keystroke of its own, and taking one as a binding would leave an
213+/// action that fires the moment the user reaches for any chord that uses it --
214+/// so a capture waits through them instead.
215+pub(crate) fn is_bare_modifier(key: &str) -> bool {
216+ matches!(
217+ key,
218+ "control" | "shift" | "alt" | "super" | "platform" | "function" | "fn" | "meta" | "command"
219+ )
220+}
crates/app/src/layout.rsadded+291 -0
@@ -0,0 +1,291 @@
1+//! The window's fixed geometry: what every region is measured in.
2+
3+/// ...and the narrowest it is drawn: a library row whose length the engine has
4+/// not measured yet has a landing place but no width, and a head marker says
5+/// where it goes where a zero-width box would say nothing.
6+pub(crate) const GHOST_MIN: f32 = 2.;
7+
8+/// Fixed so the video region takes every pixel the window gains and the controls
9+/// never clip at 640x360.
10+pub(crate) const HEADER_H: f32 = 32.;
11+// 28 button row + 24 scrub strip + two 48 lanes + the timecode line + the gaps
12+// between them, with a few px of slack so a taller text line cannot push a lane
13+// off the bottom.
14+pub(crate) const PANEL_H: f32 = 220.;
15+/// How many lane rows are drawn before the lane column starts scrolling: past
16+/// this the panel would be taller than the picture it belongs under, and a
17+/// timeline that pushes the video off the window is not a timeline.
18+pub(crate) const LANES_MAX: usize = 6;
19+pub(crate) const LANE_H: f32 = 48.;
20+/// The lane header column: wide enough for `V1`/`A1` and fixed, so both lanes
21+/// and the ruler above them start at the same pixel and are the same width --
22+/// one x-to-time mapping for the whole timeline. `HEADER_GAP` is part of that
23+/// offset and is therefore shared by all three rows.
24+pub(crate) const HEADER_W: f32 = 40.;
25+pub(crate) const HEADER_GAP: f32 = 4.;
26+/// The label row inside a clip; a waveform paints under it, never through it.
27+pub(crate) const LABEL_H: f32 = 15.;
28+/// A clip narrower than this shows no name: two characters and an ellipsis say
29+/// nothing that the tint has not already said, and cost the picture a smear.
30+pub(crate) const LABEL_MIN_W: f32 = 36.;
31+/// Peak buckets per second of source. Fixed and modest on purpose: `peaks`
32+/// allocates one bucket per window, so a rate taken from anything the user can
33+/// influence is an allocation bomb -- and 40 is already finer than the pixels a
34+/// clip is ever given.
35+///
36+/// corner-cut: "finer than the pixels" stops being true once the timeline is
37+/// zoomed -- past ~25 ms per bucket the envelope reads as steps rather than as
38+/// a shape. Ceiling: [`View::max_zoom`]'s 8 frames across the bed. The upgrade
39+/// is a second, finer pass over the visible span only, cached like `waves` is.
40+pub(crate) const WAVE_BPS: u32 = 40;
41+/// Pixels per envelope column. Coarser than a pixel: the eye reads the shape,
42+/// and a path with a point per pixel is a path per repaint.
43+pub(crate) const WAVE_COL: f32 = 2.;
44+/// The most columns one envelope is ever built from. A waveform is drawn into
45+/// the slice of its box that is on the bed ([`visible_slice`]), and a bed is a
46+/// screen wide, so nothing on screen ever reaches this -- it is the backstop for
47+/// a box laid out wider than any screen, whose path would otherwise cost a point
48+/// per two pixels of a width nobody can see and stall the repaint that was
49+/// meant to draw the wave.
50+pub(crate) const WAVE_COLS_MAX: usize = 4096;
51+/// WCAG 2.5.8: nothing clickable is smaller than this. The scrub bar stays 6 px
52+/// to look at -- `RULER_HIT_H` is the strip that has to be hit.
53+pub(crate) const HIT_MIN: f32 = 24.;
54+/// The media library's column: a share of the window rather than a fixed width,
55+/// so it yields on a narrow one, and never more than a third of it -- the
56+/// picture is what this program is for and keeps the majority at every size.
57+/// The floor is what a file name and a timecode need to be readable at all.
58+pub(crate) const LIBRARY_FRAC: f32 = 0.2;
59+pub(crate) const LIBRARY_MIN_W: f32 = 120.;
60+pub(crate) const LIBRARY_MAX_W: f32 = 220.;
61+/// A library row: a name over its duration, two lines and a click target, so
62+/// `HIT_MIN` binds it like every other one.
63+pub(crate) const ROW_H: f32 = 32.;
64+/// The tint swatch down the left of a row: the same colour that source's clips
65+/// wear in the lanes, which is the whole of the panel<->timeline association.
66+pub(crate) const SWATCH_W: f32 = 4.;
67+pub(crate) const CONTROL_H: f32 = 28.;
68+/// The volume slider beside its button: a hundred steps across it, so a pixel
69+/// is finer than a step and the drag reads as continuous.
70+pub(crate) const VOLUME_W: f32 = 110.;
71+pub(crate) const RULER_HIT_H: f32 = HIT_MIN;
72+/// Wide enough for `HH:MM:SS:FF / HH:MM:SS:FF`, and fixed so changing digits
73+/// cannot push the layout around.
74+pub(crate) const TIME_W: f32 = 200.;
75+/// The keybindings card: a row per action, a title and a status line, inside a
76+/// 360 px tall window. The rows are click targets, so `HIT_MIN` binds them too.
77+/// Wider than the export card, and for the same reason that one is wider than
78+/// this used to be: at 320 the longest labels ("Remove the last video track (it
79+/// must be empty)") ran straight over the stroke printed at the other end of
80+/// their row. Every label in the registry fits beside its stroke here, and the
81+/// one that cannot -- a row waiting for a key to be pressed -- truncates rather
82+/// than overprinting. Still inside the 640 px floor.
83+pub(crate) const KEYS_W: f32 = 480.;
84+pub(crate) const KEYS_ROW_H: f32 = HIT_MIN;
85+/// How much of the row list is on screen at once; past this it scrolls. What
86+/// keeps the card inside the smallest window no matter how many actions the
87+/// editor grows -- ten rows fit here, and the eleventh is a scroll away.
88+pub(crate) const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H;
89+/// The same for the export card, which carries two summary lines and a button
90+/// under its list and so has less room: a section header, six codecs, the
91+/// container, five qualities and the destination are more rows than a 360 px
92+/// window holds. Eight on screen, which is the whole format section and its
93+/// header -- what a user picks first is never behind a scroll.
94+pub(crate) const EXPORT_ROWS_H: f32 = 8. * KEYS_ROW_H;
95+/// The export card is wider than the keybindings one: its rows carry a key, a
96+/// name *and* what the choice means, and the two summary lines under them state
97+/// the whole file. At `KEYS_W` every one of those wrapped to two lines, which is
98+/// the card the user called unfriendly. Still inside the 640 px floor with the
99+/// scrim showing either side of it.
100+pub(crate) const EXPORT_W: f32 = 420.;
101+/// The column the key of a row is printed in, wide enough for `0–9`: every row
102+/// in the export card says what picks it, so the card is drivable by keyboard
103+/// without a legend to memorise.
104+pub(crate) const EXPORT_KEY_W: f32 = 26.;
105+/// Everything in the export card that is *not* the row list: the title, the
106+/// status line, the head and tail of the summary, the button, the gaps between
107+/// them and the padding around the lot. What the list may be is the window
108+/// minus this -- and never less than [`EXPORT_ROWS_H`], which is the number
109+/// that makes the card fit the 360 px floor.
110+pub(crate) const EXPORT_FIXED_H: f32 = 17. + 28. + 15. + 30. + CONTROL_H + 4. + 10. + 24.;
111+/// The menu a right-click on a clip opens: wide enough for the longest label
112+/// beside the stroke that does the same thing, with the click targets `HIT_MIN`
113+/// binds like every other list here.
114+pub(crate) const MENU_W: f32 = 260.;
115+pub(crate) const MENU_ROW_H: f32 = HIT_MIN;
116+pub(crate) const MENU_PAD: f32 = 6.;
117+
118+/// A cue's text, and the line it sits on. Fixed rather than a share of the
119+/// picture: the video region is 108 px tall at the 640x360 floor and a
120+/// proportional size there would be unreadable at exactly the size where it has
121+/// to be read.
122+pub(crate) const SUB_TEXT: f32 = 14.;
123+pub(crate) const SUB_LINE_H: f32 = 18.;
124+/// How far off the bottom of the picture the plate sits.
125+pub(crate) const SUB_BOTTOM: f32 = 8.;
126+/// The subtitle strip under the lanes: thin, because it is a picture of where
127+/// the cues are and nothing on it can be dragged -- `HIT_MIN` binds targets, and
128+/// this row has none.
129+pub(crate) const SUB_LANE_H: f32 = 16.;
130+/// A mark narrower than this is still drawn this wide: a one-frame cue on a
131+/// zoomed-out bed is worth a fraction of a pixel, and a mark nobody can see says
132+/// the track is empty. The silence preview's marks are floored by it too -- they
133+/// are the same kind of thing, a picture of where something is and no target.
134+pub(crate) const SUB_CUE_MIN_W: f32 = 2.;
135+/// How much of the subtitle list in the library column is on screen at once,
136+/// past which it scrolls -- the media list above it is what keeps the height.
137+pub(crate) const SUB_ROWS_H: f32 = 3. * ROW_H;
138+/// The row naming the file a block of tracks came out of. Shorter than a track
139+/// row because nothing on it is clicked -- `HIT_MIN` binds targets and a header
140+/// is a label, not a way in -- and drawn at all only where the column has the
141+/// height to show tracks under it ([`sub_headers_fit`]).
142+pub(crate) const SUB_HEAD_H: f32 = 18.;
143+/// How much of the subtitle list is on screen at the 640x360 floor: one row,
144+/// measured -- the section's own heading and the Add button under it take the
145+/// rest of the 84 px the column has there.
146+pub(crate) const SUB_ROWS_AT_FLOOR: f32 = ROW_H;
147+/// How much of a subtitle row's width the file's name in front of the label may
148+/// take. Half: which file and which language are both worth reading, and a name
149+/// given the whole row is a row where the language is what gets truncated.
150+pub(crate) const SUB_STEM_SHARE: f32 = 0.5;
151+/// Roughly how wide one character of an 11 px list row is. Generous on purpose:
152+/// the element truncates for real, and a budget that overshoots would have the
153+/// element cut the tail off after [`clip_middle`] had already kept it.
154+pub(crate) const LIST_CHAR_W: f32 = 6.;
155+/// The fewest characters a clipped name is cut to, however narrow the column
156+/// gets: past this there is nothing on either side of the gap to read.
157+pub(crate) const LIST_CLIP_MIN: usize = 5;
158+/// How long the export card's Subtitles line may get before it counts tracks
159+/// instead of naming them ([`subtitle_plan`]). Three lines of that row's value
160+/// box, at [`LIST_CHAR_W`] to a character: [`EXPORT_W`] less the row's padding
161+/// and gap, its tick and [`EXPORT_KEY_W`] key column, and the word "Subtitles"
162+/// in front of the value. Not a track count -- what walks the Destination row
163+/// off the bottom of the card is the *wrapping*, and thirty-five one-word
164+/// labels wrap less than three long ones.
165+pub(crate) const SUB_PLAN_CHARS: usize = (3.
166+ * (EXPORT_W - 12. - 12. - (10. + 8. + EXPORT_KEY_W + 8. + 9. * LIST_CHAR_W))
167+ / LIST_CHAR_W) as usize;
168+
169+/// The one key name this file still spells out, and gpui's spelling of it: it
170+/// is the way out of a capture and out of the overlay, and both have to work
171+/// while the keymap itself is what is being changed -- so neither can go
172+/// through the keymap to find it.
173+pub(crate) const ESCAPE: &str = "escape";
174+
175+/// How tall a column of `lanes` rows is, gaps included -- the panel's own gap
176+/// between them, since the rows sit in it.
177+pub(crate) fn lanes_h(lanes: usize) -> f32 {
178+ match lanes {
179+ 0 => 0.,
180+ n => n as f32 * LANE_H + (n - 1) as f32 * 8.,
181+ }
182+}
183+
184+/// How many whole lane rows a box this tall shows. At least one: a box too
185+/// short for a single lane still shows part of one, and "0 shown" would count
186+/// every lane there is as hidden.
187+pub(crate) fn lanes_shown(box_h: f32) -> usize {
188+ (((box_h + 8.) / (LANE_H + 8.)).floor() as usize).max(1)
189+}
190+
191+/// How many rows are still below the fold *now*: the count the affordance says
192+/// out loud, and the reason it is a function of the scroll rather than of the
193+/// lane count alone. A line that keeps saying "2 more tracks below" after the
194+/// user has scrolled to the last one is a line that has stopped being true, and
195+/// an affordance nobody can make go away is read as a bug rather than as an
196+/// instruction.
197+///
198+/// `scrolled` is how far down the column has been taken, in pixels. Rounded to
199+/// the nearest row: a half-scrolled row is showing, so it is not below.
200+pub(crate) fn rows_below(total: usize, box_h: f32, scrolled: f32) -> usize {
201+ let past = ((scrolled / (LANE_H + 8.)).round().max(0.)) as usize;
202+ total.saturating_sub(past + lanes_shown(box_h))
203+}
204+
205+/// The same question for a column whose rows are not one height -- the
206+/// inspector's sections -- answered in pixels off what the scroll itself
207+/// reports: how far it may still be taken (`max_offset`) less how far it has
208+/// been (`offset`, which gpui keeps negative going down).
209+pub(crate) fn px_below(max_offset_h: f32, offset_y: f32) -> f32 {
210+ (max_offset_h + offset_y).max(0.)
211+}
212+
213+/// What the subtitle strip adds to the panel: its own row and the panel's gap
214+/// above it, and nothing at all for a timeline with no subtitles on it -- the
215+/// picture does not pay for a strip that is not drawn.
216+pub(crate) fn subtitle_strip_h(shown: bool) -> f32 {
217+ match shown {
218+ true => SUB_LANE_H + 8.,
219+ false => 0.,
220+ }
221+}
222+
223+/// How tall the panel is with `lanes` tracks in it: [`PANEL_H`] is sized for the
224+/// two a project starts with, and every further one adds its own row -- up to
225+/// [`LANES_MAX`], past which the lane column scrolls instead and the panel stops
226+/// growing.
227+pub(crate) fn panel_h(lanes: usize) -> f32 {
228+ PANEL_H + lanes_h(lanes.clamp(2, LANES_MAX)) - lanes_h(2)
229+}
230+
231+/// How tall the timeline region is: its own padding, the timecode line, the
232+/// ruler and the gaps between them, plus a row per lane. Measured from its
233+/// parts rather than taken off [`PANEL_H`] -- the button row moved out of it
234+/// ([`Player::toolbar`]), and a height still carrying that row's pixels is a
235+/// height that cuts the last lane off the bottom of the window.
236+pub(crate) fn timeline_h(lanes: usize) -> f32 {
237+ TIMELINE_FIXED_H + lanes_h(lanes.clamp(2, LANES_MAX))
238+}
239+
240+/// 8+8 padding, the timecode line, the 24 px ruler strip and the two 8 px gaps
241+/// between the three rows, with a couple of px of slack so a taller text line
242+/// cannot push a lane off the bottom.
243+pub(crate) const TIMELINE_FIXED_H: f32 = 16. + 18. + 8. + RULER_HIT_H + 8. + 4.;
244+
245+/// The most of a short window the timeline may take. At the 640x360 floor that
246+/// is 151 px of the 360, which leaves the picture a region rather than a
247+/// letterbox stripe -- and the lanes scroll inside it.
248+pub(crate) const TIMELINE_SHARE: f32 = 0.42;
249+
250+/// The edit toolbar directly above the timeline: one control's height in its
251+/// own padding, fixed so nothing in it can push the timeline down.
252+pub(crate) const TOOLBAR_H: f32 = CONTROL_H + 16.;
253+
254+/// The top bar: the project's name on the left, the two file actions on the
255+/// right. Fixed for the reason [`HEADER_H`] is.
256+pub(crate) const TOPBAR_H: f32 = 36.;
257+
258+/// The transport strip under the picture -- play, timecode, volume -- where a
259+/// player's own controls live in every consumer editor.
260+pub(crate) const TRANSPORT_H: f32 = CONTROL_H + 12.;
261+
262+/// One press of a zoom key, or one notch of ctrl+wheel.
263+pub(crate) const ZOOM_STEP: f32 = 1.25;
264+
265+/// How far one notch of a bare wheel slides the view along, as a share of what
266+/// is on the bed. A *share* rather than a number of pixels or of seconds: one
267+/// gesture then moves the same fraction of what is being looked at whether the
268+/// bed is showing five seconds or five hours, which is the only way a wheel is
269+/// usable at both ends of the zoom.
270+pub(crate) const SCROLL_NOTCH_SHARE: f32 = 0.1;
271+
272+/// How few frames the bed may be narrowed down to. Past this there is nothing
273+/// left to aim at -- a single frame across a whole window is a wall of colour,
274+/// not an edit surface.
275+pub(crate) const ZOOM_MIN_FRAMES: f64 = 8.;
276+
277+/// How thin a second of timeline may be drawn on a bed that is already showing
278+/// all of it: the far stop for a *short* project, which has no length of its own
279+/// worth widening to, so a five second import can still be zoomed out of.
280+pub(crate) const PPS_MIN: f64 = 1.;
281+
282+/// How much bed the far stop leaves past the last frame, as a multiple of the
283+/// timeline's own length -- so a timeline zoomed all the way out ends a sliver
284+/// short of the window's edge rather than glued to it.
285+pub(crate) const ZOOM_OUT_MARGIN: f64 = 1.05;
286+
287+/// How wide a second of timeline is drawn before anyone zooms: a five second
288+/// import is 200 px of a bed several times that, so a short clip reads as
289+/// short -- the thing a bed scaled to the content's own length cannot say.
290+/// [`View::fit`] is the one way back to "the whole timeline across the bed".
291+pub(crate) const PPS_DEFAULT: f64 = 40.;
crates/app/src/library_meta.rsadded+426 -0
@@ -0,0 +1,426 @@
1+//! What a library row is and what it says about its file.
2+
3+use crate::*;
4+
5+/// What is left on the clipboard after the library row at `removed` was taken
6+/// out. A copied clip names its file by *index* into the source list
7+/// (`engine::Clip::source`) and a removal renumbers that list
8+/// (`engine::Project::remove_source`), so a clipboard kept as it was would paste
9+/// **a different file** -- the next one along -- over the range it was copied
10+/// from.
11+///
12+/// The clip's own file gone means there is nothing to paste: `None`, and the
13+/// next paste says the clipboard is empty rather than putting some other take
14+/// down. Every index past it moves down by one, exactly as the lanes' clips do.
15+pub(crate) fn clipboard_after_remove(clip: Option<Clip>, removed: usize) -> Option<Clip> {
16+ let mut clip = clip?;
17+ match clip.source.cmp(&removed) {
18+ std::cmp::Ordering::Equal => None,
19+ std::cmp::Ordering::Greater => {
20+ clip.source -= 1;
21+ Some(clip)
22+ }
23+ std::cmp::Ordering::Less => Some(clip),
24+ }
25+}
26+
27+/// One library row: a file and one of its audio streams. Plain data, planned
28+/// before anything is drawn -- which rows exist at all is the branchy part.
29+#[derive(Debug, PartialEq)]
30+pub(crate) struct Row {
31+ pub(crate) path: PathBuf,
32+ pub(crate) stream: usize,
33+ /// The file, plus which stream this is when the file has several.
34+ pub(crate) name: String,
35+ /// What the stream is, or blank for a file with a single one.
36+ pub(crate) detail: String,
37+ /// Why it cannot be put on this timeline, for a row that cannot: shown in
38+ /// place of the length and the only thing that greys a row out.
39+ pub(crate) unusable: Option<String>,
40+ /// Frames of the *file*, for the length line.
41+ pub(crate) frames: u32,
42+ /// Index into `SOURCE_TINTS`, shared by every stream of one file: the
43+ /// swatch says which file, and the lanes tint their clips the same way.
44+ pub(crate) tint: usize,
45+}
46+
47+/// Every row the library shows: one per source entry, plus one for each further
48+/// audio stream those files have that no clip plays yet -- a remux with a track
49+/// per language lists them all, the ones this engine cannot use greyed out
50+/// rather than hidden. Streams a file has not been probed for yet simply are
51+/// not there; the row for what *is* on the timeline is always there.
52+///
53+/// `timeline_audio` is the rate and layout of source 0's stream, which every
54+/// other source must match: one output device and one copied AAC track for the
55+/// whole timeline (`PlaybackSession::place_stream_at`). `None` while unknown,
56+/// and then nothing is greyed for it -- the engine still refuses.
57+pub(crate) fn library_rows(
58+ sources: &[Source],
59+ streams: &HashMap<PathBuf, Vec<StreamInfo>>,
60+ decoders: &HashMap<PathBuf, Option<(Option<Codec>, Backend)>>,
61+ timeline_audio: Option<(u32, u16)>,
62+ frames: impl Fn(&Path) -> u32,
63+) -> Vec<Row> {
64+ let mut rows = Vec::new();
65+ for (i, source) in sources.iter().enumerate() {
66+ let of_file = streams.get(&source.path).map_or(&[][..], Vec::as_slice);
67+ let info = of_file.iter().find(|s| s.index == source.audio_stream);
68+ let tint = sources
69+ .iter()
70+ .position(|s| s.path == source.path)
71+ .expect("a source finds itself");
72+ rows.push(Row {
73+ path: source.path.clone(),
74+ stream: source.audio_stream,
75+ name: row_name(&source.path, source.audio_stream, of_file.len() > 1),
76+ // The decoder first: it is the same for every row of a file and
77+ // it is what a person opening the panel is asking about. The
78+ // stream half only where there is a choice to describe -- a file
79+ // with one audio track is the row it has always been, name and
80+ // length, and the length is what would be squeezed out at the
81+ // panel's least width.
82+ detail: join_detail(
83+ &decoders
84+ .get(&source.path)
85+ .copied()
86+ .flatten()
87+ .map_or_else(String::new, |(codec, backend)| decode_label(codec, backend)),
88+ &info
89+ .filter(|_| of_file.len() > 1)
90+ .map_or_else(String::new, stream_detail),
91+ ),
92+ // A stream already on the timeline is playing: whatever a probe
93+ // would say about it now, it is usable by demonstration.
94+ unusable: None,
95+ frames: frames(&source.path),
96+ tint,
97+ });
98+ // The file's other streams, listed once, right after the last entry
99+ // that names the file -- so a file's rows sit together.
100+ if sources[i + 1..].iter().any(|s| s.path == source.path) {
101+ continue;
102+ }
103+ for info in of_file {
104+ if sources
105+ .iter()
106+ .any(|s| s.path == source.path && s.audio_stream == info.index)
107+ {
108+ continue; // it has a row of its own above
109+ }
110+ rows.push(Row {
111+ path: source.path.clone(),
112+ stream: info.index,
113+ name: row_name(&source.path, info.index, true),
114+ detail: stream_detail(info),
115+ unusable: unusable(info, timeline_audio),
116+ frames: frames(&source.path),
117+ tint,
118+ });
119+ }
120+ }
121+ rows
122+}
123+
124+/// The row's second line: what the stream is and then either how long it is or
125+/// why it cannot be used, with the separator only where both halves exist (a
126+/// single-stream file says nothing about its stream).
127+pub(crate) fn join_detail(detail: &str, tail: &str) -> String {
128+ match (detail.is_empty(), tail.is_empty()) {
129+ (true, _) => tail.to_string(),
130+ (false, true) => detail.to_string(),
131+ (false, false) => format!("{detail} · {tail}"),
132+ }
133+}
134+
135+/// How a source's decoder reads: the codec and which seat has it, or the seat
136+/// alone for a still, which has no coded stream to name. The one place either
137+/// answer is spelled, so a row, a transport line and a card cannot disagree.
138+pub(crate) fn decode_label(codec: Option<Codec>, backend: Backend) -> String {
139+ match codec {
140+ Some(codec) => format!("{} · {}", codec.name(), backend.label()),
141+ None => backend.label().to_string(),
142+ }
143+}
144+
145+/// How a row names its file: the file alone when it has one audio stream or
146+/// none, and the file plus which stream this row is when it has several --
147+/// counted from 1, the way a player numbers tracks.
148+pub(crate) fn row_name(path: &Path, stream: usize, several: bool) -> String {
149+ match several {
150+ false => file_name(path),
151+ true => format!("{} [audio {}]", file_name(path), stream + 1),
152+ }
153+}
154+
155+/// What a stream is, for the row's second line: the language if the file says
156+/// one, then rate and layout. A field the header does not give is left out
157+/// rather than shown as a zero -- a stream we cannot parse says nothing about
158+/// itself, and saying "0 Hz" would be saying something.
159+pub(crate) fn stream_detail(info: &StreamInfo) -> String {
160+ let mut parts: Vec<String> = Vec::new();
161+ if let Some(lang) = &info.lang {
162+ parts.push(lang_human(lang).to_string());
163+ }
164+ if info.sample_rate > 0 {
165+ parts.push(format!("{} kHz", f64::from(info.sample_rate) / 1000.));
166+ }
167+ parts.extend(layout(info.channels));
168+ parts.join(" ")
169+}
170+
171+/// What a file is coded at, for the properties cards: the rate of the whole
172+/// file, then each track's own beside it. A component the container does not
173+/// state is left out for `stream_detail`'s reason -- a fabricated `0` would be
174+/// saying something -- and a file that states none of the three says so rather
175+/// than showing an empty row. `None` is the probe still running, which is a
176+/// real wait: it walks a Matroska's clusters.
177+///
178+/// The whole file's rate is the one that carries the unit and no word: named
179+/// "total" as well, the line loses its last component to `MENU_W`'s truncation
180+/// on an ordinary 1080p file -- and a rate cut to "0.13 soun" is a number the
181+/// card did not give.
182+///
183+/// `tracks` is how many sound tracks the file has, from `probe_streams`. The
184+/// rate is the one track this engine plays -- the first, neither their sum nor
185+/// the biggest -- so a file with more says which of how many: a bare "0.16
186+/// sound" on a file whose name says AC3.5.1 names a track without saying it is
187+/// one of two, and the card's Audio row above it may be describing the other.
188+///
189+/// The marker costs the word "sound", the way the whole file's rate costs the
190+/// word "total" above, and for the same reason. Measured in Noto Sans 11 px
191+/// against the 186 px this value has beside a "Bitrate" label: "0.16 sound 1/2"
192+/// wants 192 px on a 4.7 Mb/s film and 205 on the 39.8 Mb/s remux --
193+/// the marker is what gets cut, which is the one part of the line that is new.
194+/// Nothing that keeps the word fits the wide files -- the shortest, "snd 1/2",
195+/// still wants 188 px on that remux -- so the word goes and the number keeps
196+/// the answer: "0.16 1 of 2" wants 172 px, and 185 on the widest line a
197+/// library can produce (the 10.9 Mb/s three-track film).
198+pub(crate) fn bitrate_detail(rate: Option<MediaBitrate>, tracks: usize) -> String {
199+ let Some(rate) = rate else {
200+ return "…".to_string();
201+ };
202+ let (per, unit) = rate_scale(rate);
203+ let mut parts: Vec<String> = Vec::new();
204+ if let Some(total) = rate.total {
205+ // One unit for the three numbers, carried once, on the whole file's
206+ // rate: the components are read against it.
207+ parts.push(format!("{} {unit}", scaled(total, per)));
208+ }
209+ if let Some(video) = rate.video {
210+ parts.push(format!("{} video", scaled(video, per)));
211+ }
212+ if let Some(audio) = rate.audio {
213+ parts.push(match tracks > 1 {
214+ true => format!("{} 1 of {tracks}", scaled(audio, per)),
215+ false => format!("{} sound", scaled(audio, per)),
216+ });
217+ }
218+ match parts.is_empty() {
219+ true => "not stated".to_string(),
220+ false => parts.join(" · "),
221+ }
222+}
223+
224+/// Below this a megabit's two decimals cannot state a rate, so the line is read
225+/// in kilobits instead.
226+pub(crate) const MB_FLOOR: u64 = 10_000;
227+
228+/// What the line counts in, and the name of it: the largest unit that can state
229+/// its *smallest* component, because that is the one a bigger unit rounds away.
230+/// Megabits for everything a real file produces -- the smallest component over
231+/// an 18-file sweep of a library was 0.13 Mb/s -- kilobits for the sub-32x32
232+/// encodes below that.
233+///
234+/// corner-cut: one unit for the whole line, so a file mixing a multi-megabit
235+/// picture with a sub-10 kb/s sound track prints the picture as four or five
236+/// digits of kilobits and loses the line's tail to `MENU_W`. No such file
237+/// exists in a library, and both units at once ("0.01 Mb/s · 1.2 kb/s video ·
238+/// 9.5 kb/s sound") wants 215 px of the 186 the row has. Upgrade path is a
239+/// suffix per component ("1.2k video"), which measures 177 px.
240+pub(crate) fn rate_scale(rate: MediaBitrate) -> (f64, &'static str) {
241+ match [rate.total, rate.video, rate.audio]
242+ .into_iter()
243+ .flatten()
244+ .min()
245+ {
246+ // A rate this small is a broken header rather than a track, but it is
247+ // still a number the file stated, and bits state it.
248+ Some(bits) if bits < 10 => (1., "b/s"),
249+ Some(bits) if bits < MB_FLOOR => (1_000., "kb/s"),
250+ _ => (1_000_000., "Mb/s"),
251+ }
252+}
253+
254+/// A rate in the line's unit as a person reads it: one decimal above 1 of it,
255+/// two below -- a 128 kbps song rounded to one decimal is "0.1", which reads as
256+/// a guess where "0.13" reads as a measurement.
257+///
258+/// Never `0.00`: [`rate_scale`] picks the unit off the smallest component, so
259+/// two decimals always reach it. Every rate that gets here is one the container
260+/// really stated (the probe leaves out what it does not state, it never zeroes
261+/// it), and a "0.00 sound" would be this card saying a track that plays is
262+/// silent.
263+pub(crate) fn scaled(bits: u64, per: f64) -> String {
264+ let n = bits as f64 / per;
265+ match n >= 1. {
266+ true => format!("{n:.1}"),
267+ false => format!("{n:.2}"),
268+ }
269+}
270+
271+/// A language tag as a person reads it. Everything a file writes is passed
272+/// through untouched bar the one tag that is not a language: "und" is what a
273+/// muxer writes when nobody said, and a row showing it verbatim names a
274+/// language nobody speaks.
275+pub(crate) fn lang_human(lang: &str) -> &str {
276+ match lang {
277+ "und" => "unknown language",
278+ lang => lang,
279+ }
280+}
281+
282+pub(crate) fn layout(channels: u16) -> Option<String> {
283+ match channels {
284+ 0 => None,
285+ 1 => Some("mono".to_string()),
286+ 2 => Some("stereo".to_string()),
287+ n => Some(format!("{n} ch")),
288+ }
289+}
290+
291+/// Why a stream cannot go on this timeline, or `None` if it can. Both answers
292+/// are shown: a stream nothing can be done with is listed greyed with the
293+/// reason, never dropped from the list -- a file has the tracks it has, and a
294+/// picker that hides them is a picker that lies.
295+pub(crate) fn unusable(info: &StreamInfo, timeline_audio: Option<(u32, u16)>) -> Option<String> {
296+ if !info.decodable {
297+ // AAC and AC-3 name themselves (`StreamInfo::codec`, which reads the
298+ // stsd fourcc by hand); anything else mp4 0.14 does not parse has no
299+ // name to give, and a row with no name still says why it is greyed.
300+ return Some(match info.codec.as_str() {
301+ "unknown" => "unsupported codec".to_string(),
302+ codec => format!("{codec} is not supported"),
303+ });
304+ }
305+ // The **layout** and not the rate, which is what the engine's own gate now
306+ // asks (`PlaybackSession::import`): a stream written at another sample rate
307+ // is resampled onto the timeline's at the decoder's door, so greying its row
308+ // would be this picker refusing what the timeline accepts.
309+ let (_, channels) = timeline_audio?;
310+ (info.channels != channels).then(|| {
311+ format!(
312+ "the timeline is {}",
313+ layout(channels).unwrap_or_else(|| "silent".to_string())
314+ )
315+ })
316+}
317+
318+/// How wide the equalizer card is drawn in a window this wide: all of it bar a
319+/// margin, up to [`EQ_W_MAX`]. The card is a graph, and a graph of twenty
320+/// thousand hertz on 320 px spends four pixels on the octave below middle C --
321+/// so it takes the room a big window has and stays inside a small one. Floored
322+/// at the other cards' width, which is the last size the rows still read at.
323+pub(crate) fn eq_card_w(window_w: f32) -> f32 {
324+ (window_w - EQ_W_MARGIN).clamp(KEYS_W, EQ_W_MAX)
325+}
326+
327+/// What the media list is given of the window. A share of it, so a narrow
328+/// window gives the panel less rather than giving the picture nothing, floored
329+/// where a name stops being readable and capped at a third of the window --
330+/// the picture is what the program is for and keeps the majority at every size.
331+pub(crate) fn library_w(window_w: f32) -> f32 {
332+ (window_w * LIBRARY_FRAC)
333+ .clamp(LIBRARY_MIN_W, LIBRARY_MAX_W)
334+ .min(window_w / 3.)
335+}
336+
337+/// What is left of a library column this wide for a row's *words*: the panel's
338+/// padding on both sides, the tint bar, the gap after it and the row's own right
339+/// inset. Every row in the column -- media and subtitle -- is built to this
340+/// shape, so one number answers for both.
341+pub(crate) fn row_text_w(width: f32) -> f32 {
342+ // 8 px of panel padding each side, then the bar, the gap after it and the
343+ // row's own right inset -- the numbers the rows are built with.
344+ width - 16. - SWATCH_W - 6. - 6.
345+}
346+
347+/// A name cut to what a column this wide can hold, out of the *middle*. Two
348+/// files off one release differ in their last characters and nowhere else --
349+/// "…Episode 01" against "…02" -- so a name cut from the right is the same
350+/// name twice and the list stops naming anything. The width decides how much
351+/// survives, not a number of characters somebody guessed: a wider window spells
352+/// more of the file out, and the floor still keeps both ends.
353+///
354+/// The element truncates for real; this only decides where what is lost comes
355+/// out of.
356+pub(crate) fn clip_middle(name: &str, width: f32) -> String {
357+ let budget = ((width / LIST_CHAR_W) as usize).max(LIST_CLIP_MIN);
358+ let chars: Vec<char> = name.chars().collect();
359+ if chars.len() <= budget {
360+ return name.to_string();
361+ }
362+ // The gap costs a character, and what is left of the odd one goes to the
363+ // tail: the tail is the half that tells two of them apart.
364+ let head = (budget - 1) / 2;
365+ let tail = budget - 1 - head;
366+ format!(
367+ "{}…{}",
368+ chars[..head].iter().collect::<String>(),
369+ chars[chars.len() - tail..].iter().collect::<String>()
370+ )
371+}
372+
373+/// Whether the subtitle list has the height to name each file over its tracks.
374+/// A header is worth its own height only where there are still tracks under it
375+/// to read: at the 640x360 floor the list is one row tall, and a header there
376+/// would name a film and show none of it -- so at the floor there are no
377+/// headers and the rows say which file they came from themselves.
378+///
379+/// The window's height answers it on its own: the row above the picture and the
380+/// panel under it are fixed, so every pixel the window gains past the floor is a
381+/// pixel this column gains.
382+pub(crate) fn sub_headers_fit(viewport_h: f32) -> bool {
383+ SUB_ROWS_AT_FLOOR + (viewport_h - 360.).max(0.) >= SUB_HEAD_H + 2. * ROW_H
384+}
385+
386+/// What the window is called: the program, and what is open in it. The name is
387+/// what the header shows, so an empty window says the program alone rather than
388+/// "no file open — edith".
389+pub(crate) fn window_title(name: &str) -> String {
390+ if name == NO_FILE {
391+ "edith".to_string()
392+ } else {
393+ format!("{name} — edith")
394+ }
395+}
396+
397+/// The tint a clip from source `n` wears. Cycled rather than extended: past the
398+/// palette two sources share a colour, which is a smaller lie than a fifth tint
399+/// bright enough to leave the family.
400+pub(crate) fn source_tint(source: usize) -> u32 {
401+ SOURCE_TINTS()[source % SOURCE_TINTS().len()]
402+}
403+
404+/// The tint of a *file*, which is what a library row is named by: the first
405+/// source entry naming it, since two audio streams of one file are two sources
406+/// and one colour.
407+///
408+/// `None` for a path no source names -- a standalone `.srt` is on nobody's
409+/// timeline, and painting it with the first file's colour would say it came out
410+/// of that file. No swatch says what is true: it belongs to itself.
411+pub(crate) fn file_tint(sources: &[Source], path: &Path) -> Option<u32> {
412+ sources
413+ .iter()
414+ .position(|s| s.path == path)
415+ .or_else(|| {
416+ // A source entry is stored symlink-resolved (`Source::new`) and a
417+ // path from anywhere else -- a subtitle track, a file being
418+ // dragged -- is stored as it was spelled. `edith assets/film.mkv`
419+ // is one file under two spellings, and matching by spelling alone
420+ // said the film had no colour. Only asked when the spellings
421+ // differ, so the common paint costs no syscall.
422+ let path = std::fs::canonicalize(path).ok()?;
423+ sources.iter().position(|s| s.path == path)
424+ })
425+ .map(source_tint)
426+}
crates/app/src/main.rsmodified+34 -4890

Diff too large; view file

@@ -1,6 +1,40 @@
1 mod keymap;1 mod keymap;
2 mod ui;2 mod ui;
3 3
4+mod audio_cards;
5+mod color_ui;
6+mod eq_ui;
7+mod export_ui;
8+mod files;
9+mod importing;
10+mod interact;
11+mod layout;
12+mod library_meta;
13+mod menus;
14+mod notices;
15+mod oracle;
16+mod subs;
17+mod timeline_math;
18+mod transport;
19+mod viewport;
20+
21+pub(crate) use audio_cards::*;
22+pub(crate) use color_ui::*;
23+pub(crate) use eq_ui::*;
24+pub(crate) use export_ui::*;
25+pub(crate) use files::*;
26+pub(crate) use importing::*;
27+pub(crate) use interact::*;
28+pub(crate) use layout::*;
29+pub(crate) use library_meta::*;
30+pub(crate) use menus::*;
31+pub(crate) use notices::*;
32+pub(crate) use oracle::*;
33+pub(crate) use subs::*;
34+pub(crate) use timeline_math::*;
35+pub(crate) use transport::*;
36+pub(crate) use viewport::*;
37+
4 use ui::inspector::section_head;38 use ui::inspector::section_head;
5 use ui::theme::*;39 use ui::theme::*;
6 use ui::toolbar::{EXPORT_SLOT_W, SNAP_SLOT_W, VOLUME_SLOT_W, ZOOM_SLOT_W};40 use ui::toolbar::{EXPORT_SLOT_W, SNAP_SLOT_W, VOLUME_SLOT_W, ZOOM_SLOT_W};
@@ -34,1131 +68,6 @@ use gpui::{
34 canvas, div, img, point, prelude::*, px, relative, rgb, rgba, size,68 canvas, div, img, point, prelude::*, px, relative, rgb, rgba, size,
35 };69 };
36 70
37-/// ...and the narrowest it is drawn: a library row whose length the engine has
38-/// not measured yet has a landing place but no width, and a head marker says
39-/// where it goes where a zero-width box would say nothing.
40-const GHOST_MIN: f32 = 2.;
41-
42-/// Fixed so the video region takes every pixel the window gains and the controls
43-/// never clip at 640x360.
44-const HEADER_H: f32 = 32.;
45-// 28 button row + 24 scrub strip + two 48 lanes + the timecode line + the gaps
46-// between them, with a few px of slack so a taller text line cannot push a lane
47-// off the bottom.
48-const PANEL_H: f32 = 220.;
49-/// How many lane rows are drawn before the lane column starts scrolling: past
50-/// this the panel would be taller than the picture it belongs under, and a
51-/// timeline that pushes the video off the window is not a timeline.
52-const LANES_MAX: usize = 6;
53-const LANE_H: f32 = 48.;
54-/// The lane header column: wide enough for `V1`/`A1` and fixed, so both lanes
55-/// and the ruler above them start at the same pixel and are the same width --
56-/// one x-to-time mapping for the whole timeline. `HEADER_GAP` is part of that
57-/// offset and is therefore shared by all three rows.
58-const HEADER_W: f32 = 40.;
59-const HEADER_GAP: f32 = 4.;
60-/// The label row inside a clip; a waveform paints under it, never through it.
61-const LABEL_H: f32 = 15.;
62-/// A clip narrower than this shows no name: two characters and an ellipsis say
63-/// nothing that the tint has not already said, and cost the picture a smear.
64-const LABEL_MIN_W: f32 = 36.;
65-/// Peak buckets per second of source. Fixed and modest on purpose: `peaks`
66-/// allocates one bucket per window, so a rate taken from anything the user can
67-/// influence is an allocation bomb -- and 40 is already finer than the pixels a
68-/// clip is ever given.
69-///
70-/// corner-cut: "finer than the pixels" stops being true once the timeline is
71-/// zoomed -- past ~25 ms per bucket the envelope reads as steps rather than as
72-/// a shape. Ceiling: [`View::max_zoom`]'s 8 frames across the bed. The upgrade
73-/// is a second, finer pass over the visible span only, cached like `waves` is.
74-const WAVE_BPS: u32 = 40;
75-/// Pixels per envelope column. Coarser than a pixel: the eye reads the shape,
76-/// and a path with a point per pixel is a path per repaint.
77-const WAVE_COL: f32 = 2.;
78-/// The most columns one envelope is ever built from. A waveform is drawn into
79-/// the slice of its box that is on the bed ([`visible_slice`]), and a bed is a
80-/// screen wide, so nothing on screen ever reaches this -- it is the backstop for
81-/// a box laid out wider than any screen, whose path would otherwise cost a point
82-/// per two pixels of a width nobody can see and stall the repaint that was
83-/// meant to draw the wave.
84-const WAVE_COLS_MAX: usize = 4096;
85-/// WCAG 2.5.8: nothing clickable is smaller than this. The scrub bar stays 6 px
86-/// to look at -- `RULER_HIT_H` is the strip that has to be hit.
87-const HIT_MIN: f32 = 24.;
88-/// The media library's column: a share of the window rather than a fixed width,
89-/// so it yields on a narrow one, and never more than a third of it -- the
90-/// picture is what this program is for and keeps the majority at every size.
91-/// The floor is what a file name and a timecode need to be readable at all.
92-const LIBRARY_FRAC: f32 = 0.2;
93-const LIBRARY_MIN_W: f32 = 120.;
94-const LIBRARY_MAX_W: f32 = 220.;
95-/// A library row: a name over its duration, two lines and a click target, so
96-/// `HIT_MIN` binds it like every other one.
97-const ROW_H: f32 = 32.;
98-/// The tint swatch down the left of a row: the same colour that source's clips
99-/// wear in the lanes, which is the whole of the panel<->timeline association.
100-const SWATCH_W: f32 = 4.;
101-const CONTROL_H: f32 = 28.;
102-/// The volume slider beside its button: a hundred steps across it, so a pixel
103-/// is finer than a step and the drag reads as continuous.
104-const VOLUME_W: f32 = 110.;
105-const RULER_HIT_H: f32 = HIT_MIN;
106-/// Wide enough for `HH:MM:SS:FF / HH:MM:SS:FF`, and fixed so changing digits
107-/// cannot push the layout around.
108-const TIME_W: f32 = 200.;
109-/// The keybindings card: a row per action, a title and a status line, inside a
110-/// 360 px tall window. The rows are click targets, so `HIT_MIN` binds them too.
111-/// Wider than the export card, and for the same reason that one is wider than
112-/// this used to be: at 320 the longest labels ("Remove the last video track (it
113-/// must be empty)") ran straight over the stroke printed at the other end of
114-/// their row. Every label in the registry fits beside its stroke here, and the
115-/// one that cannot -- a row waiting for a key to be pressed -- truncates rather
116-/// than overprinting. Still inside the 640 px floor.
117-const KEYS_W: f32 = 480.;
118-const KEYS_ROW_H: f32 = HIT_MIN;
119-/// How much of the row list is on screen at once; past this it scrolls. What
120-/// keeps the card inside the smallest window no matter how many actions the
121-/// editor grows -- ten rows fit here, and the eleventh is a scroll away.
122-const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H;
123-/// The same for the export card, which carries two summary lines and a button
124-/// under its list and so has less room: a section header, six codecs, the
125-/// container, five qualities and the destination are more rows than a 360 px
126-/// window holds. Eight on screen, which is the whole format section and its
127-/// header -- what a user picks first is never behind a scroll.
128-const EXPORT_ROWS_H: f32 = 8. * KEYS_ROW_H;
129-/// The export card is wider than the keybindings one: its rows carry a key, a
130-/// name *and* what the choice means, and the two summary lines under them state
131-/// the whole file. At `KEYS_W` every one of those wrapped to two lines, which is
132-/// the card the user called unfriendly. Still inside the 640 px floor with the
133-/// scrim showing either side of it.
134-const EXPORT_W: f32 = 420.;
135-/// The column the key of a row is printed in, wide enough for `0–9`: every row
136-/// in the export card says what picks it, so the card is drivable by keyboard
137-/// without a legend to memorise.
138-const EXPORT_KEY_W: f32 = 26.;
139-/// Everything in the export card that is *not* the row list: the title, the
140-/// status line, the head and tail of the summary, the button, the gaps between
141-/// them and the padding around the lot. What the list may be is the window
142-/// minus this -- and never less than [`EXPORT_ROWS_H`], which is the number
143-/// that makes the card fit the 360 px floor.
144-const EXPORT_FIXED_H: f32 = 17. + 28. + 15. + 30. + CONTROL_H + 4. + 10. + 24.;
145-/// The menu a right-click on a clip opens: wide enough for the longest label
146-/// beside the stroke that does the same thing, with the click targets `HIT_MIN`
147-/// binds like every other list here.
148-const MENU_W: f32 = 260.;
149-const MENU_ROW_H: f32 = HIT_MIN;
150-const MENU_PAD: f32 = 6.;
151-
152-/// A cue's text, and the line it sits on. Fixed rather than a share of the
153-/// picture: the video region is 108 px tall at the 640x360 floor and a
154-/// proportional size there would be unreadable at exactly the size where it has
155-/// to be read.
156-const SUB_TEXT: f32 = 14.;
157-const SUB_LINE_H: f32 = 18.;
158-/// How far off the bottom of the picture the plate sits.
159-const SUB_BOTTOM: f32 = 8.;
160-/// The subtitle strip under the lanes: thin, because it is a picture of where
161-/// the cues are and nothing on it can be dragged -- `HIT_MIN` binds targets, and
162-/// this row has none.
163-const SUB_LANE_H: f32 = 16.;
164-/// A mark narrower than this is still drawn this wide: a one-frame cue on a
165-/// zoomed-out bed is worth a fraction of a pixel, and a mark nobody can see says
166-/// the track is empty. The silence preview's marks are floored by it too -- they
167-/// are the same kind of thing, a picture of where something is and no target.
168-const SUB_CUE_MIN_W: f32 = 2.;
169-/// How much of the subtitle list in the library column is on screen at once,
170-/// past which it scrolls -- the media list above it is what keeps the height.
171-const SUB_ROWS_H: f32 = 3. * ROW_H;
172-/// The row naming the file a block of tracks came out of. Shorter than a track
173-/// row because nothing on it is clicked -- `HIT_MIN` binds targets and a header
174-/// is a label, not a way in -- and drawn at all only where the column has the
175-/// height to show tracks under it ([`sub_headers_fit`]).
176-const SUB_HEAD_H: f32 = 18.;
177-/// How much of the subtitle list is on screen at the 640x360 floor: one row,
178-/// measured -- the section's own heading and the Add button under it take the
179-/// rest of the 84 px the column has there.
180-const SUB_ROWS_AT_FLOOR: f32 = ROW_H;
181-/// How much of a subtitle row's width the file's name in front of the label may
182-/// take. Half: which file and which language are both worth reading, and a name
183-/// given the whole row is a row where the language is what gets truncated.
184-const SUB_STEM_SHARE: f32 = 0.5;
185-/// Roughly how wide one character of an 11 px list row is. Generous on purpose:
186-/// the element truncates for real, and a budget that overshoots would have the
187-/// element cut the tail off after [`clip_middle`] had already kept it.
188-const LIST_CHAR_W: f32 = 6.;
189-/// The fewest characters a clipped name is cut to, however narrow the column
190-/// gets: past this there is nothing on either side of the gap to read.
191-const LIST_CLIP_MIN: usize = 5;
192-/// How long the export card's Subtitles line may get before it counts tracks
193-/// instead of naming them ([`subtitle_plan`]). Three lines of that row's value
194-/// box, at [`LIST_CHAR_W`] to a character: [`EXPORT_W`] less the row's padding
195-/// and gap, its tick and [`EXPORT_KEY_W`] key column, and the word "Subtitles"
196-/// in front of the value. Not a track count -- what walks the Destination row
197-/// off the bottom of the card is the *wrapping*, and thirty-five one-word
198-/// labels wrap less than three long ones.
199-const SUB_PLAN_CHARS: usize = (3.
200- * (EXPORT_W - 12. - 12. - (10. + 8. + EXPORT_KEY_W + 8. + 9. * LIST_CHAR_W))
201- / LIST_CHAR_W) as usize;
202-
203-/// The one key name this file still spells out, and gpui's spelling of it: it
204-/// is the way out of a capture and out of the overlay, and both have to work
205-/// while the keymap itself is what is being changed -- so neither can go
206-/// through the keymap to find it.
207-const ESCAPE: &str = "escape";
208-
209-/// What the header says with no timeline open, and what the window title reads
210-/// as a program name rather than as a file name.
211-const NO_FILE: &str = "no file open";
212-
213-/// What a press of play says when there is nothing to play: no timeline at all
214-/// and an emptied one are the same answer to the user, so they are one line.
215-const NOTHING_TO_PLAY: &str = "NOTHING TO PLAY — put a clip on the timeline first";
216-
217-/// Whether a press of play would have anything to play. No timeline at all and
218-/// one every clip has been taken off are the same state to a transport, and the
219-/// button and the key both have to give the same answer to it -- so there is
220-/// one of them, and it is free of the window so it can be checked without one.
221-fn nothing_to_play(session: Option<&PlaybackSession>) -> bool {
222- session.is_none_or(PlaybackSession::is_empty)
223-}
224-
225-/// What the monitoring output is set to. Two things, not one: the level the
226-/// user picked, and whether it is being held silent -- so unmuting comes back
227-/// to the level rather than to a guess.
228-///
229-/// The level counts steps rather than carrying an `f32`, because 5% at a time
230-/// down and back up again through a float would not land on the number it
231-/// started from, and the label would eventually read `79%`.
232-///
233-/// Volume and mute stay independent on purpose: turning the level down while
234-/// muted must not be what makes sound come out. Only the mute key unmutes, and
235-/// the button says both things at once ("Muted 80%") so neither is a surprise.
236-#[derive(Clone, Copy, PartialEq, Eq, Debug)]
237-struct Volume {
238- steps: u8,
239- muted: bool,
240-}
241-
242-impl Volume {
243- /// One step is one percent: fine enough that a drag along the slider reads
244- /// as continuous, and still a count rather than a float.
245- const MAX_STEPS: u8 = 100;
246-
247- /// 5% a press: twenty presses across the range, which is what the keys have
248- /// always moved. The slider is what the finer grid is for.
249- const KEY_STEP: u8 = 5;
250-
251- /// What the device is set to: mute wins, and the level is what it returns
252- /// to. `0.0..=1.0`, which is the range the plugin's ABI accepts.
253- fn gain(self) -> f32 {
254- if self.muted { 0. } else { self.along() }
255- }
256-
257- /// One press up or down, clamped at both ends -- saturating, so the count
258- /// cannot wrap past silence into full volume.
259- fn step(&mut self, up: bool) {
260- self.steps = if up {
261- self.steps.saturating_add(Self::KEY_STEP).min(Self::MAX_STEPS)
262- } else {
263- self.steps.saturating_sub(Self::KEY_STEP)
264- };
265- }
266-
267- /// Where the hand let go along the slider, 0..1 from silence to full. The
268- /// grid is the same one the keys land on, so a drag to the top and a key
269- /// held up reach the very same number -- and a drag never touches mute:
270- /// asking for a level while muted is not asking for sound.
271- fn set_along(&mut self, frac: f32) {
272- self.steps = (frac.clamp(0., 1.) * f32::from(Self::MAX_STEPS)).round() as u8;
273- }
274-
275- /// How full the slider is drawn, 0..1. The level and not the gain: a muted
276- /// slider still shows what unmuting comes back to, exactly as the label
277- /// does.
278- fn along(self) -> f32 {
279- f32::from(self.steps) / f32::from(Self::MAX_STEPS)
280- }
281-
282- /// The level as a whole number, for the button's fixed rect: muting swaps
283- /// the glyph beside it, never the width of the box.
284- fn percent(self) -> u32 {
285- u32::from(self.steps) * 100 / u32::from(Self::MAX_STEPS)
286- }
287-
288- /// What the button reads. The level shows while muted too: it is what the
289- /// next press of the mute key brings back.
290- fn label(self) -> String {
291- let percent = u32::from(self.steps) * 100 / u32::from(Self::MAX_STEPS);
292- if self.muted {
293- format!("Muted {percent}%")
294- } else {
295- format!("Vol {percent}%")
296- }
297- }
298-}
299-
300-impl Default for Volume {
301- fn default() -> Self {
302- Self {
303- steps: Self::MAX_STEPS,
304- muted: false,
305- }
306- }
307-}
308-
309-/// The library's three categories, in the order the giants list them: the
310-/// pictures, the sound, and the words. A file is in exactly one of them, so a
311-/// tab is a question with an answer rather than a filter with a guess.
312-#[derive(Clone, Copy, PartialEq, Eq, Debug)]
313-enum LibraryTab {
314- Media,
315- Audio,
316- Text,
317-}
318-
319-const LIBRARY_TABS: [LibraryTab; 3] = [LibraryTab::Media, LibraryTab::Audio, LibraryTab::Text];
320-
321-impl LibraryTab {
322- fn label(self) -> &'static str {
323- match self {
324- LibraryTab::Media => "Media",
325- LibraryTab::Audio => "Audio",
326- LibraryTab::Text => "Text",
327- }
328- }
329-
330- /// Whether a source belongs on this tab. Subtitles are not sources at all
331- /// -- they are the [`Player::subtitle_section`] under the list -- so the
332- /// Text tab holds no rows of its own and says so.
333- fn holds(self, path: &Path) -> bool {
334- match self {
335- LibraryTab::Media => !engine::is_audio(path),
336- LibraryTab::Audio => engine::is_audio(path),
337- LibraryTab::Text => false,
338- }
339- }
340-
341- /// What an empty tab says instead of being a blank column.
342- fn empty(self) -> &'static str {
343- match self {
344- LibraryTab::Media => "No video or stills yet — Import, or drop a file on the window",
345- LibraryTab::Audio => "No sound yet — Import, or drop a file on the window",
346- LibraryTab::Text => {
347- "No subtitles yet — Add subtitles from a file, or drop an .srt on the window"
348- }
349- }
350- }
351-}
352-
353-/// What is known about a source's audio. Three states and not two, because a
354-/// file whose peaks have not come back yet must not be drawn as one that has no
355-/// audio at all: the first shows a bed, the second shows nothing.
356-#[derive(Clone)]
357-enum Wave {
358- /// Asked for; the decode is running on a background thread.
359- Loading,
360- /// The file has no audio track. An answer, not a miss.
361- Silent,
362- /// The decode failed. Drawn as its own mark rather than as [`Self::Silent`]:
363- /// "this file's sound could not be read" and "this file has no sound" look
364- /// the same on a lane, and the first is a bug report waiting to happen.
365- Failed,
366- Peaks(Arc<Vec<(f32, f32)>>),
367-}
368-
369-/// The import a worker is reading, as the line above the panel shows it. No
370-/// fraction anywhere: neither read reports how far into the file it has come,
371-/// so what is honest is the file's name, the stage, and two clocks -- one that
372-/// proves the window is answering, one that says the stage has not moved.
373-struct Import {
374- path: PathBuf,
375- /// When the worker started, for the elapsed clock.
376- started: Instant,
377- /// Written by the worker between its two reads, read here every repaint.
378- stage: Arc<std::sync::atomic::AtomicU8>,
379- /// The stage the line last saw and when it last changed. The pair is the
380- /// whole stall detector: a stage older than [`IMPORT_STALL`] is what the
381- /// honest wording is for.
382- seen: ImportStage,
383- since: Instant,
384- /// Set by the Cancel beside the line ([`Player::cancel_import`]), read at
385- /// the landing: what the worker read is dropped instead of joining the
386- /// timeline.
387- ///
388- /// corner-cut: the *read* is not stopped -- a demuxer walk polls nothing, so
389- /// the worker finishes into a result nobody takes, and the window is given
390- /// back at the click either way. Ceiling: a cancelled cold 24 GB import
391- /// still costs the disk its twenty seconds. Upgrade: a flag
392- /// `engine::demux::Demuxer::open` polls between clusters, which is where an
393- /// export's own cancel already lives ([`engine::ExportHandle::cancel`]).
394- cancelled: Arc<std::sync::atomic::AtomicBool>,
395-}
396-
397-impl Import {
398- /// Reads the worker's stage and keeps the stall clock: it restarts when the
399- /// stage actually changes and at no other time, which is what makes "has
400- /// not moved in five seconds" a fact rather than a guess about the elapsed
401- /// clock. Hands back how long the current stage has stood, so the line has
402- /// one place to ask.
403- fn poll(&mut self) -> f32 {
404- let stage = ImportStage::from_u8(self.stage.load(std::sync::atomic::Ordering::Relaxed));
405- if stage != self.seen {
406- self.seen = stage;
407- self.since = Instant::now();
408- }
409- self.since.elapsed().as_secs_f32()
410- }
411-}
412-
413-/// What a scan is *of*: the source, which of its audio streams, and the clip's
414-/// own `[in, out)` source frames. The range is part of the name because it is
415-/// part of the read -- a clip cut in half is a different, shorter decode than
416-/// the whole take was, and levels read for one are not the other's.
417-type ScanKey = (PathBuf, usize, u32, u32);
418-
419-/// The silence scan a worker is running, as the card shows it. Same two clocks
420-/// as an [`Import`] and for the same reason -- one proves the window answers,
421-/// one says the read has stopped moving -- over a progress that *can* move:
422-/// a decode knows how far into the sound it has come, so the card says so.
423-struct SilenceScan {
424- /// Source, stream and source range being scanned, which is the cache key
425- /// the levels land under and what tells a second open of the same clip from
426- /// a new one.
427- key: ScanKey,
428- /// When the worker started, for the elapsed clock.
429- started: Instant,
430- /// Written by the worker, read here every repaint. The cancel flag in it is
431- /// this side's only word to a scan already running.
432- progress: Arc<engine::silence::Progress>,
433- /// The tenths-of-a-second mark the line last saw and when it last changed:
434- /// the stall detector, exactly [`Import::poll`]'s.
435- seen: u64,
436- since: Instant,
437-}
438-
439-impl SilenceScan {
440- /// Reads the worker's mark and keeps the stall clock, restarting it only
441- /// when the mark actually moves -- [`Import::poll`]'s contract, over a
442- /// number instead of a stage.
443- fn poll(&mut self) -> f32 {
444- let scanned = self.progress.scanned.load(std::sync::atomic::Ordering::Relaxed);
445- if scanned != self.seen {
446- self.seen = scanned;
447- self.since = Instant::now();
448- }
449- self.since.elapsed().as_secs_f32()
450- }
451-}
452-
453-/// A library row being dragged: the file and which of its audio streams that
454-/// row is, which is the whole of what a row names. Where it lands does not
455-/// change what is inserted.
456-struct AssetDrag(PathBuf, usize);
457-
458-/// A clip already on the timeline being dragged: the lane it is on and its index
459-/// there, which is how every other edit names a clip. Unlike an [`AssetDrag`]
460-/// nothing is inserted -- the same clip changes lane and keeps the frames it
461-/// plays -- but where along the bed it is let go is exactly where it lands, less
462-/// the offset the hand grabbed it at ([`Player::grab`]).
463-#[derive(Clone, Copy)]
464-struct ClipDrag {
465- lane: Lane,
466- idx: usize,
467- /// The clip that was picked up, so the drop can find it again: gpui freezes
468- /// the payload for the whole gesture, and an edit made *during* one -- a
469- /// stroke deletes, undoes or pastes, none of which a drag blocks -- ripples
470- /// the indices under it. The index alone would then name a different take at
471- /// the release, and the drag would move a clip nobody touched (see
472- /// [`live_idx`]).
473- clip: Clip,
474-}
475-
476-/// A track *header* being dragged: which track the hand took hold of, to be
477-/// let go over the header of the one whose place it is to take
478-/// ([`Player::reorder_lane`]). The lane alone -- a track carries its own clips
479-/// wherever it goes, so unlike a [`ClipDrag`] there is nothing else to name.
480-#[derive(Clone, Copy)]
481-struct LaneDrag(Lane);
482-
483-/// Where a header drag in flight would leave the track in the hand: the lane
484-/// whose slot it is about to take, and whether the line is drawn at that lane's
485-/// top edge (it is coming up from below) or its bottom one. The drop indicator
486-/// every editor draws between two tracks, and the header answer to the ghost a
487-/// clip drag lays on a lane ([`Ghost`]) -- stale between gestures, which costs
488-/// nothing because it is drawn only while one is live.
489-#[derive(Clone, Copy, PartialEq)]
490-struct LaneDrop {
491- lane: Lane,
492- above: bool,
493-}
494-
495-/// Where the drag in flight would leave what it is carrying: the lane the
496-/// pointer is over, the snapped head the release will commit ([`landing`]), and
497-/// how long the thing is. Drawn on that lane as a translucent box the size of
498-/// the take, so a landing is *seen* before the release rather than discovered
499-/// after it -- the line ([`Player::snap_cue`]) marks the frame, this shows the
500-/// body. `refused` is a drop the lane cannot take -- a picture over an audio
501-/// track, a sound over a video one -- tinted rather than silent, because the
502-/// refusal is coming at the release either way ([`lane_refuses`],
503-/// [`Project::move_clip`]).
504-#[derive(Clone, Copy, PartialEq)]
505-struct Ghost {
506- lane: Lane,
507- start: u32,
508- /// Timeline frames, which a speed has already been counted into: the box is
509- /// as wide as the clip is *long where it lands*. Zero for a library row of
510- /// unknown length, drawn as a head marker.
511- frames: u32,
512- /// The swatch of the file being carried ([`file_tint`]), so the
513- /// ghost reads as the thing in the hand.
514- tint: u32,
515- refused: bool,
516-}
517-
518-/// A clip edge being dragged: which end of which clip, and the timeline frame
519-/// the pointer has pulled it to. The box on screen is drawn from `to` while this
520-/// is set and the engine hears about it once, at the release
521-/// ([`Player::commit_trim`]) -- one edit, one undo step for the whole gesture,
522-/// exactly as an equalizer drag works.
523-#[derive(Clone, Copy)]
524-struct Trim {
525- lane: Lane,
526- idx: usize,
527- edge: Edge,
528- /// Already clamped by `PlaybackSession::trim_room`, so the width drawn from
529- /// it is the width the release commits -- an edge stops under the pointer
530- /// rather than snapping back after the fact.
531- to: u32,
532- /// The dragged clip's group, so its other halves' boxes follow the edge on
533- /// screen exactly as the engine will move them.
534- link: Option<u32>,
535-}
536-
537-/// How wide a clip's edge is as a *target*: the strip at each end where a press
538-/// means "make this longer or shorter" instead of "move this to another lane".
539-/// Wide enough to hit, narrow enough that the middle of even a small box is
540-/// still the body.
541-const EDGE_W: f32 = 6.;
542-
543-/// Whether a clip box this wide gets its two trim strips at all. Below three
544-/// handles wide the pair would occlude the whole box: every press on it would
545-/// trim, and the clip could not be selected, dragged to another lane or picked
546-/// up by its middle -- which is exactly what a jumpcut leaves behind
547-/// ([`Player::cut_silences`] manufactures a great many short clips). Above it,
548-/// what is left between the two strips is a handle's width of body in its own
549-/// right. A clip too short for its handles is trimmed by zooming in first: the
550-/// bed is a magnifier, and the strip grows with the box.
551-fn trims(width: f32) -> bool {
552- width >= 3. * EDGE_W
553-}
554-
555-/// How wide a clip's box is *drawn*, given the width its own length is worth
556-/// (`span`). Never under [`HIT_MIN`], even where that is wider than the clip is
557-/// long: zoomed far out a short take is worth a fraction of a pixel, and a box
558-/// nobody can put a pointer on is a clip that cannot be selected, dragged, given
559-/// a menu or reached at all -- which is strictly worse than one drawn a few
560-/// pixels too wide. The same call [`cue_box`] makes for a mark, and what every
561-/// editor draws.
562-///
563-/// A drawing only: [`Scale::time_at`] still reads the bed, so a press inside the
564-/// padding names the frame it points at, and the box's head is the clip's own.
565-fn clip_width(span: f32) -> f32 {
566- span.max(HIT_MIN)
567-}
568-
569-/// The sheet a card or a menu is painted on: the whole window, and the mouse
570-/// stops at it. Occluding is what tells gpui that nothing under this sheet is
571-/// hovered any more (`Hitbox::is_hovered`) -- without it the window carries on
572-/// hovering behind an open menu and pops *its* tooltip over the menu's items,
573-/// which is a card being painted over by the thing it covers.
574-///
575-/// Every card and every menu takes its sheet from here, so no surface can be
576-/// drawn over the top of one by having been given a plain scrim.
577-fn scrim() -> Div {
578- div().absolute().inset_0().occlude()
579-}
580-
581-/// The sheet a card with a *slider* in it takes instead: the same scrim, with
582-/// the window's own drag listeners on it as well.
583-///
584-/// A scrim occludes, and occluding is where gpui's hit test stops
585-/// (`Hitbox::is_hovered`, window.rs:788) -- so while a card is up the root is
586-/// not hovered anywhere behind it and its `on_mouse_move`/`on_mouse_up` hear
587-/// nothing at all. Every drag in this window is tracked from the root, because
588-/// each of them starts on a strip a few pixels wide that the pointer leaves at
589-/// once ([`Player::drag_move`]), so a card's handles were set by the press and
590-/// then frozen: the value never followed the hand and the release never wrote.
591-/// The scrim is the one surface above the occluder that covers the whole card,
592-/// so the same two listeners go here, and a drag that leaves the card is picked
593-/// up by the root's copy of them without a seam.
594-fn drag_scrim(cx: &mut Context<Player>) -> Div {
595- scrim()
596- .on_mouse_move(cx.listener(Player::drag_move))
597- .on_mouse_up(MouseButton::Left, cx.listener(Player::drag_release))
598-}
599-
600-/// A press that stops here. What every card's body hands its scrim: the scrim
601-/// closes the card on a press, and the card is painted after it, so this listener
602-/// runs first (gpui dispatches topmost-first, window.rs:3705) and a press meant
603-/// for a button never closes the card out from under its own click -- the rule
604-/// the menus already follow ([`Player::library_card`]).
605-fn swallow(_: &MouseDownEvent, _: &mut Window, cx: &mut App) {
606- cx.stop_propagation();
607-}
608-
609-/// How close to an edge a dragged clip has to be let go for it to land *on* it:
610-/// the snap every timeline has, in pixels rather than frames so that it feels
611-/// the same at every zoom. Narrower than [`EDGE_W`] -- a hand aiming between two
612-/// takes must still be able to leave a gap of a few frames there.
613-const SNAP_PX: f64 = 5.;
614-
615-/// An open clip menu: which clip it was opened on, where it hangs, and whether
616-/// it has been turned over to show what that clip *is* instead of what can be
617-/// done to it. The lane and index are the ones the same click selected, so
618-/// every item acts on exactly the box under the pointer.
619-#[derive(Clone, Copy)]
620-struct ContextMenu {
621- lane: Lane,
622- idx: usize,
623- at: Point<Pixels>,
624- details: bool,
625-}
626-
627-/// An open library menu: which row it was opened on -- the file and the stream,
628-/// the pair [`Player::selected_asset`] holds, so a list rebuilt under it (a
629-/// probe landing, a source going) cannot slide another row beneath the menu the
630-/// way a row *index* would -- where it hangs, and whether it has been turned
631-/// over to show what the file *is*.
632-#[derive(Clone)]
633-struct LibraryMenu {
634- path: PathBuf,
635- stream: usize,
636- at: Point<Pixels>,
637- details: bool,
638-}
639-
640-/// An open choice list: which setting it offers and where it hangs. What a
641-/// button that stepped one value on per click used to be -- a setting with more
642-/// than two values is a list to look at, not a thing to click round. Placed by
643-/// [`menu_at`] and closed by a stroke, exactly like the two menus above it.
644-#[derive(Clone, Copy, PartialEq)]
645-struct Picker {
646- of: Pick,
647- at: Point<Pixels>,
648- /// Which row the keyboard is on, from the value in force when the list
649- /// opened. The list answers ↑↓ and enter as well as a click: a setting whose
650- /// only door is a pointer is a setting half this editor's users cannot
651- /// reach, which is the rule `FIXED` already writes down for every card.
652- sel: usize,
653-}
654-
655-/// Which setting an open list is offering. The fit policy names the clip it is
656-/// about, like the clip menu it opens from -- indices move under every edit, so
657-/// the list closes on the first stroke as that menu does.
658-#[derive(Clone, Copy, PartialEq, Eq, Debug)]
659-enum Pick {
660- Resolution,
661- Fps,
662- Fit(Lane, usize),
663- /// What the export's *sound* is coded at. Opened from the card's Sound row,
664- /// which is the only place it means anything.
665- AudioRate,
666- /// Which HDR-to-SDR rendition the project is watched and exported in
667- /// ([`engine::tonemap::Preset`]). Opened from the panel, beside the two
668- /// other settings that are the project's rather than the media's.
669- Tone,
670- /// Which palette the window is painted in ([`ui::theme`]). The one setting
671- /// here that is nobody's project: it is the person's, so it outlives the
672- /// timeline and every file opened in it.
673- Theme,
674-}
675-
676-/// One value a list offers, carrying everything picking it needs -- so a click
677-/// goes straight to the value rather than to a position in a list that was
678-/// built somewhere else.
679-/// `Eq` is off it for the rate: a frame rate is the `f64` the engine is told,
680-/// bit for bit (23.976023976... is not 23.976), and nothing here keys a map on a
681-/// choice -- comparing two is all a list row ever does.
682-#[derive(Clone, Copy, PartialEq, Debug)]
683-enum Choice {
684- Size(u32, u32),
685- Fps(f64),
686- Fit(Lane, usize, FitPolicy),
687- AudioRate(u32),
688- Tone(Preset),
689- Theme(ui::theme::PaletteId),
690-}
691-
692-/// One row of an open list: the value, its name, the small print beside it, and
693-/// whether it is the one in force.
694-type ChoiceRow = (Choice, SharedString, SharedString, bool);
695-
696-/// What a library row's menu offers, in the order it lists them. Unlike the clip
697-/// menu's items none of these is a stroke -- there is no keyboard way to a row --
698-/// so the label and the hint are written here rather than read off the keymap.
699-#[derive(Clone, Copy, PartialEq)]
700-enum RowItem {
701- Add,
702- Remove,
703- Reveal,
704- Properties,
705-}
706-
707-const ROW_ITEMS: [RowItem; 4] = [
708- RowItem::Add,
709- RowItem::Remove,
710- RowItem::Reveal,
711- RowItem::Properties,
712-];
713-
714-impl RowItem {
715- fn label(self) -> &'static str {
716- match self {
717- Self::Add => "Add at playhead",
718- Self::Remove => "Remove from library",
719- Self::Reveal => "Reveal in files",
720- Self::Properties => "Properties",
721- }
722- }
723-
724- /// The dim right-hand column, where the clip menu prints the stroke: what
725- /// the item will do to the timeline, so nothing here is a surprise.
726- fn hint(self) -> &'static str {
727- match self {
728- // Short enough to sit beside its label inside `MENU_W`, the clip
729- // menu's rule for a refusal: this column truncates, and a hint cut
730- // off mid-word says less than a shorter one.
731- Self::Add => "the whole file",
732- Self::Remove => "nothing plays it",
733- Self::Reveal => "file manager",
734- Self::Properties => "…",
735- }
736- }
737-}
738-
739-/// What the menu offers, in the order it lists them. Every one of these is an
740-/// action a stroke already reaches -- the menu is a second way *to* the actions
741-/// and never a second version of them -- so both the label and the hint come
742-/// out of the keymap registry and the two can never disagree.
743-const MENU_ITEMS: [ActionId; 14] = [
744- ActionId::Cut,
745- // The clipboard pair, which had no door but a chord: copy takes the clip the
746- // menu names, and paste is the timeline's rather than this clip's -- the
747- // same kind of global item the mute below already is.
748- ActionId::Copy,
749- ActionId::Paste,
750- ActionId::Delete,
751- ActionId::Lift,
752- ActionId::Regroup,
753- ActionId::Detach,
754- ActionId::Group,
755- ActionId::Equalizer,
756- ActionId::Speed,
757- // The scan is a clip card like the two above it -- opened on whichever half
758- // was clicked -- and a card only a stroke could open is one a pointer never
759- // finds.
760- ActionId::Silence,
761- ActionId::Color,
762- ActionId::Fit,
763- ActionId::ToggleMute,
764-];
765-
766-/// One row of the actions card, in the order it lists them: a heading, then
767-/// every action the registry files under it, then the strokes the modal cards
768-/// answer themselves.
769-///
770-/// A list rather than a loop inside the render, so the card and
771-/// `every_action_is_on_the_actions_card` read the *same* order: an action that
772-/// reaches no row fails a test instead of quietly becoming pointer-unreachable.
773-enum KeyRow {
774- Head(keymap::Category),
775- /// Click its label to do it, click its stroke to change that stroke.
776- Act(ActionId),
777- /// An index into [`keymap::FIXED`]. Shown and never offered: nothing may
778- /// unbind the way out of a card.
779- Fixed(usize),
780-}
781-
782-/// Every action, under its heading, and the card-local strokes beside them.
783-/// Generated from the registry -- [`ActionId::ALL`] in its own order, under
784-/// [`keymap::Category::ALL`] -- so an action added there is on the card the
785-/// moment it exists and there is no second list here to forget.
786-fn keys_rows() -> Vec<KeyRow> {
787- let mut rows = Vec::new();
788- for category in keymap::Category::ALL {
789- rows.push(KeyRow::Head(category));
790- rows.extend(
791- ActionId::ALL
792- .into_iter()
793- .filter(|a| a.category() == category)
794- .map(KeyRow::Act),
795- );
796- rows.extend(
797- keymap::FIXED
798- .iter()
799- .enumerate()
800- .filter(|(_, f)| f.category == category)
801- .map(|(i, _)| KeyRow::Fixed(i)),
802- );
803- }
804- rows
805-}
806-
807-/// [`keys_rows`] with a search applied: the rows whose label or whose stroke
808-/// carries `needle`, and the heading each one lives under. A heading with
809-/// nothing left beneath it goes with them -- an empty "Playback" over a gap
810-/// reads as a list that lost its rows rather than as a search that found none.
811-///
812-/// Each row keeps the index it has in the unfiltered list, so an element id is
813-/// the same one before and after a keystroke: filtering is a look at the list,
814-/// and gpui's per-element state is keyed on that id.
815-///
816-/// Case-insensitive substring, on both columns: people look for an action by
817-/// what it does ("vol") and for a stroke by what they pressed ("ctrl").
818-fn keys_filter(needle: &str, keymap: &Keymap) -> Vec<(usize, KeyRow)> {
819- let needle = needle.trim().to_lowercase();
820- let rows = keys_rows().into_iter().enumerate();
821- if needle.is_empty() {
822- return rows.collect();
823- }
824- let hit = |label: &str, chord: &str| {
825- label.to_lowercase().contains(&needle) || chord.to_lowercase().contains(&needle)
826- };
827- let mut out: Vec<(usize, KeyRow)> = Vec::new();
828- // The heading above the row being looked at, until a row under it earns it
829- // a place -- then it goes in once, ahead of that row.
830- let mut pending: Option<(usize, KeyRow)> = None;
831- for (i, row) in rows {
832- match &row {
833- KeyRow::Head(_) => pending = Some((i, row)),
834- KeyRow::Act(action) => {
835- if hit(action.label(), &keymap.display(*action)) {
836- out.extend(pending.take());
837- out.push((i, row));
838- }
839- }
840- KeyRow::Fixed(f) => {
841- let fixed = &keymap::FIXED[*f];
842- if hit(fixed.label, &fixed.chord) {
843- out.extend(pending.take());
844- out.push((i, row));
845- }
846- }
847- }
848- }
849- out
850-}
851-
852-/// The character a stroke types into the actions card's search box, if it types
853-/// one. gpui reports a printable key as itself and the space bar by name
854-/// (platform.rs:866), and everything else -- the arrows, the function keys --
855-/// is a word this must not spell into the box letter by letter.
856-fn typed(key: &str) -> Option<char> {
857- match key {
858- "space" => Some(' '),
859- _ => key
860- .chars()
861- .next()
862- .filter(|c| c.is_ascii_graphic() && key.chars().count() == 1),
863- }
864-}
865-
866-/// The project resolutions [`Player::cycle_resolution`] offers, largest first.
867-/// A short list of the sizes people name; the media's own is cycled in beside
868-/// them, which is what makes the trip round come back to where it started.
869-const RESOLUTIONS: [(u32, u32); 5] = [
870- (3840, 2160),
871- (2560, 1440),
872- (1920, 1080),
873- (1280, 720),
874- (854, 480),
875-];
876-
877-/// The project frame rates the list offers, slowest first: the rates footage is
878-/// actually shot and delivered at, the NTSC ones written as the ratios they are
879-/// (`24000/1001`, not `23.976`) -- the engine conforms the timeline to the very
880-/// number it is handed, so a rate rounded here would be a rate no timescale can
881-/// name. The media's own is cycled in beside them
882-/// ([`frame_rate_ladder`]), which is what keeps the way back on the list.
883-const FRAME_RATES: [f64; 8] = [
884- 24_000. / 1001.,
885- 24.,
886- 25.,
887- 30_000. / 1001.,
888- 30.,
889- 50.,
890- 60_000. / 1001.,
891- 60.,
892-];
893-
894-/// How far a band may be pushed either way, in dB. The engine clamps nothing
895-/// here -- it will filter whatever it is given -- so this is a UI decision:
896-/// past about this a peaking band stops sounding like tone and starts sounding
897-/// like a fault.
898-const EQ_GAIN_LIMIT: f32 = 12.;
899-
900-/// One dB per keystroke, which is roughly the smallest step anyone hears on a
901-/// single band.
902-const EQ_STEP: f32 = 1.;
903-
904-/// A twentieth of real time per keystroke, in the thousandths a [`Speed`] is
905-/// held in: fine enough to creep up on a rate, coarse enough that the whole
906-/// range is eighty presses and not eight hundred -- and it divides 1000, so
907-/// stepping from anywhere lands on exactly 1.00x on the way past.
908-const SPEED_STEP: i32 = 50;
909-
910-/// The rates the card's buttons offer, so the ones people actually name are one
911-/// click and not a drag. Real time is among them: it is the reset.
912-const SPEED_PRESETS: [u16; 6] = [250, 500, 1000, 1500, 2000, 4000];
913-
914-/// A rate from a number of thousandths that may have run off either end -- what
915-/// a keystroke and a drag both produce. Clamped, not refused: a hand pushing
916-/// past the limit means "as far as it goes", exactly as a trim does.
917-fn speed_at(permille: i32) -> Speed {
918- Speed::from_permille(permille.clamp(0, i32::from(u16::MAX)) as u16)
919-}
920-
921-/// The silence card's rows, in the order it lists them: how wide the apply
922-/// reaches, the threshold and the unit it is read in, the three durations a
923-/// scan is told, and the rate the speed-up plays at. What `silence_field`
924-/// indexes and what [`Player::nudge_silence`] moves.
925-const SILENCE_ROWS: usize = 7;
926-
927-/// How wide a jumpcut reaches. A ripple used to be the whole timeline's
928-/// business and nothing else; it is a *choice* now, because a podcast track's
929-/// silences are not the music track's business -- and the choice has to be on
930-/// screen, because "everything after this moved" is not a thing to discover
931-/// afterwards.
932-#[derive(Clone, Copy, PartialEq, Eq, Debug)]
933-enum Scope {
934- /// The lanes of the take the scanned clip belongs to: its picture and its
935- /// sound stay one take, and nothing else moves. The default, because a clip
936- /// picked on screen is what a person means by "this".
937- Take,
938- /// That clip's lane, alone. Refused by the engine, by name, while the take
939- /// has a half elsewhere -- detaching is how a person says they mean it.
940- Track,
941- /// Every lane, which is what a ripple always was and what the timeline-wide
942- /// jumpcut still is.
943- Everything,
944-}
945-
946-/// The order the card cycles them in.
947-const SCOPES: [Scope; 3] = [Scope::Take, Scope::Track, Scope::Everything];
948-
949-impl Scope {
950- /// What the row says, given the lanes it works out to: the *names* of the
951- /// tracks, because "this take" means nothing until it says which two.
952- fn label(self, lanes: &[Lane]) -> String {
953- let named = lanes
954- .iter()
955- .map(|l| l.label())
956- .collect::<Vec<_>>()
957- .join("+");
958- match self {
959- Scope::Take => format!("this take ({named})"),
960- Scope::Track => format!("this track ({named})"),
961- Scope::Everything => "every track".to_string(),
962- }
963- }
964-}
965-
966-/// One press of a nudge key on each kind of row: a dB on the threshold, a
967-/// twentieth of a second on the three durations, and the speed card's own step
968-/// on the rate.
969-const SILENCE_DB_STEP: f32 = 1.;
970-const SILENCE_SECS_STEP: f64 = 0.05;
971-
972-/// How far each of them may be pushed. UI decisions, all of them: the engine
973-/// takes any finite number, but a forgiveness of ten seconds finds nothing in a
974-/// talking head. The threshold reaches full scale, which calls a whole take
975-/// silent -- that is a thing someone may want to ask for (the preview on the
976-/// lane says what it would cost before anything is cut), so the top is 0 rather
977-/// than a number this card picked for them.
978-const SILENCE_DB_RANGE: (f32, f32) = (-80., 0.);
979-const SILENCE_SECS_RANGE: (f64, f64) = (0., 5.);
980-
981-/// One press of a nudge key on the mix card, in dB: the step every fader and
982-/// the limiter's ceiling moves by. A whole decibel, the smallest move anyone
983-/// hears as a move -- and it lands on round numbers, so a track set by ear
984-/// still reads as a number a person would say.
985-const MIX_DB_STEP: f32 = 1.;
986-
987-/// The mix card's rows below the faders: the limiter's ceiling and its switch.
988-/// One fader per audio track comes first, however many there are.
989-const MIX_MASTER_ROWS: usize = 2;
990-
991-/// The speed-up rate is bounded *below* by real time: a "speed-up" that slows
992-/// the silence down would make the timeline longer, which is the one thing
993-/// neither button may do. The top is [`Speed::MAX`].
994-fn silence_rate(permille: i32) -> Speed {
995- speed_at(permille.clamp(
996- i32::from(Speed::NORMAL.permille()) + SPEED_STEP,
997- i32::from(Speed::MAX.permille()),
998- ))
999-}
1000-
1001-/// The graph's frequency axis: the range an ear works in, and the range every
1002-/// band a file can carry sits inside. Log-spaced, so an octave is an octave
1003-/// wherever it falls.
1004-const EQ_FREQ_LOW: f32 = 20.;
1005-const EQ_FREQ_HIGH: f32 = 20_000.;
1006-
1007-/// The curve box. Tall enough that 1 dB is a visible move at the ±12 dB axis,
1008-/// and short enough that the card still fits a 360 px window.
1009-const EQ_GRAPH_H: f32 = 132.;
1010-
1011-/// How wide the equalizer card is allowed to get. It is the one card that is a
1012-/// *graph*: every pixel across is frequency resolution, and at the 320 px the
1013-/// other cards use, a third of an octave was a couple of pixels. Past this the
1014-/// curve stops gaining anything and the card starts reading as a wall.
1015-const EQ_W_MAX: f32 = 720.;
1016-
1017-/// The gap the card leaves either side of it, so it reads as a card on a scrim
1018-/// rather than as a second window: it takes the width it can get inside that.
1019-const EQ_W_MARGIN: f32 = 32.;
1020-
1021-/// How many bands one clip's equalizer may carry from this card. Ten because
1022-/// the keyboard picks a band with a digit and a keyboard has ten of them --
1023-/// past that a band would be reachable by pointer only. The engine itself caps
1024-/// nothing (`EqParams::bands` is a plain `Vec`), so a file may still carry more
1025-/// and this card will draw and edit every one it finds.
1026-const EQ_BANDS_MAX: usize = 10;
1027-
1028-/// One press of the frequency keys, as a factor: a sixth of an octave, so a
1029-/// band walks the whole axis in about sixty presses and still lands close
1030-/// enough to a named frequency to aim at one.
1031-const EQ_FREQ_STEP: f32 = 1.122_462;
1032-
1033-/// One press of the Q keys, as a factor, and the range they move in. Below the
1034-/// bottom a peak is barely a peak any more; above the top it is a whistle on
1035-/// one frequency. 0.707 -- the flat-shelf value, and the default -- sits inside
1036-/// them, so nothing a file carries has to be dragged into range first.
1037-const EQ_Q_STEP: f32 = 1.25;
1038-const EQ_Q_LOW: f32 = 0.3;
1039-const EQ_Q_HIGH: f32 = 12.;
1040-
1041-/// How many points the curve is drawn from. One per ~3 px across the card:
1042-/// past that the line is smooth and the extra biquad evaluations are wasted.
1043-const EQ_CURVE_STEPS: usize = 96;
1044-
1045-/// A band's handle on the curve. Only the dot -- what is *grabbed* is the whole
1046-/// graph (the nearest band along the frequency axis), so the target is the box.
1047-const EQ_HANDLE: f32 = 10.;
1048-
1049-/// The frequencies the graph names, so the curve can be read as a curve *of
1050-/// something*. The two ends label themselves at the edges.
1051-const EQ_TICKS: [(f32, &str); 5] = [
1052- (20., "20 Hz"),
1053- (100., "100"),
1054- (1000., "1k"),
1055- (10000., "10k"),
1056- (20000., "20k"),
1057-];
1058-
1059-/// The gains the graph rules a line across, besides the 0 dB one it already
1060-/// had: half way to each limit, so a boost can be read as "about six" without
1061-/// counting pixels. The limits themselves are the box's own edges and are
1062-/// named at the corners instead.
1063-const EQ_DB_GRID: [f32; 2] = [6., -6.];
1064-
1065-
1066-/// How many played samples one spectrum frame is transformed from. A power of
1067-/// two ([`fft`] is radix-2) and the whole of the engine's tap: 1024 at 48 kHz
1068-/// is a 47 Hz bin, fine enough that the bass end is a shape and short enough
1069-/// (21 ms) that the analyser moves with the music.
1070-const EQ_FFT: usize = 1024;
1071-
1072-/// The level range the analyser is drawn across, floor to ceiling in dBFS: the
1073-/// bottom of the box is silence and the top is a bin at -12 dBFS, which is
1074-/// about where a mixed track's loudest band sits. A look, not a measurement --
1075-/// the numbers on the axis are the curve's dB, never the analyser's.
1076-const EQ_SPECTRUM_DB: (f32, f32) = (-96., -12.);
1077-
1078-
1079-
1080-
1081-/// The colour card's four controls, in the order it lists them: what each is
1082-/// called and the range it moves in. The order is `ColorParams`' own, which is
1083-/// what [`color_band`] indexes.
1084-const COLOR_BANDS: [(&str, f32, f32); 4] = [
1085- ("Brightness", -1., 1.),
1086- ("Contrast", 0., 2.),
1087- ("Saturation", 0., 2.),
1088- ("Tint (cool–warm)", -1., 1.),
1089-];
1090-
1091-/// A press of a nudge key: a fortieth of a band's range, so a slider crosses it
1092-/// in forty presses and every stop is a number the file can write. A drag lands
1093-/// on the same grid ([`Player::drag_color`]), so the pointer and the keyboard
1094-/// cannot reach two different sets of values.
1095-const COLOR_STEP: f32 = 0.05;
1096-
1097-/// The card's width: a slider row is a label, the bar and the value, and the
1098-/// longest label has to fit beside all three without truncating (measured
1099-/// against "Tint (cool–warm)").
1100-const COLOR_W: f32 = 460.;
1101-/// How much of a slider row the bar itself gets -- what a drag is read against,
1102-/// so it takes the width the two nudge buttons used to.
1103-const COLOR_BAR_W: f32 = 240.;
1104-
1105-/// The histogram's bins per channel. 64 is four codes of an 8-bit ramp per bin:
1106-/// fine enough to see a grade tilt, coarse enough that a subsampled count is
1107-/// not noise.
1108-const HIST_BINS: usize = 64;
1109-
1110-/// How many pixels of a frame the histogram reads. The stride is
1111-/// `pixels / HIST_SAMPLES` (1920x1080 -> every 253rd pixel), which is a
1112-/// thousandth of the frame and walks across columns rather than down one.
1113-const HIST_SAMPLES: usize = 8_192;
1114-
1115-/// The histogram box. Shorter than the equalizer's curve because four slider
1116-/// rows stand under it and the card still has to fit a 360 px window.
1117-const HIST_H: f32 = 96.;
1118-
1119-
1120-/// Where the transport is. The one answer the button's glyph, its label, its
1121-/// enablement, the play key and the repaint loop all read -- there is no play
1122-/// flag anywhere else, because a second one is a second answer.
1123-#[derive(Clone, Copy, PartialEq, Eq, Debug)]
1124-enum Transport {
1125- /// No timeline open. Nothing to play and the transport is dimmed.
1126- Stopped,
1127- Playing,
1128- Paused,
1129- /// Played out: the last frame is on screen, the decoder is finished, and the
1130- /// clock is still running past it -- which is exactly why "is the clock
1131- /// going" is not the same question as "is this playing".
1132- Ended,
1133-}
1134-
1135-impl Transport {
1136- /// The timeline is in motion: two bars on the button, and a repaint owed
1137- /// every vsync.
1138- fn is_playing(self) -> bool {
1139- matches!(self, Transport::Playing)
1140- }
1141-
1142- /// The play key and the transport button start over from the top rather
1143- /// than toggling -- the end of a timeline is where every NLE does this, and
1144- /// the button does it because the key already did.
1145- fn restarts(self) -> bool {
1146- matches!(self, Transport::Ended)
1147- }
1148-}
1149-
1150-/// What a session's own two answers mean: the clock, unless the timeline has
1151-/// been played out -- `played_out` is the engine's end of stream with no frame
1152-/// still waiting on the pump, and it wins, because past the end a running clock
1153-/// is measuring wall time and not a picture.
1154-fn transport(playing: bool, played_out: bool) -> Transport {
1155- match (played_out, playing) {
1156- (true, _) => Transport::Ended,
1157- (_, true) => Transport::Playing,
1158- (_, false) => Transport::Paused,
1159- }
1160-}
1161-
1162 struct Player {71 struct Player {
1163 /// The timeline, once there is one. A run with no file opens without it and72 /// The timeline, once there is one. A run with no file opens without it and
1164 /// waits: the first media import or project load is what fills it, and73 /// waits: the first media import or project load is what fills it, and
@@ -6553,3771 +5462,6 @@ impl Render for Player {
6553 }5462 }
6554 }5463 }
6555 5464
6556-
6557-/// Rate limit for scrub seeks: a video worker reopen costs 72-87 ms on the
6558-/// hardware path for the small files it was measured on (215 ms in software), so
6559-/// one seek per mouse move would only queue workers that are cancelled before
6560-/// they decode anything.
6561-///
6562-/// It is a *floor*, not a bound: the reopen is a demux open
6563-/// ([`engine::decode::open_worker`]), and on a 25 GB film that is 550-750 ms --
6564-/// five to seven times this gap, which therefore gates nothing there. Where the
6565-/// cost had to be bounded rather than thinned -- the colour and speed drags --
6566-/// the gate is the frame the worker delivers ([`Player::flush_drag`]) and no
6567-/// timer at all. The ruler keeps this one: a scrub has no value to hold back,
6568-/// only a position that the next mouse move replaces anyway.
6569-const SCRUB_GAP: Duration = Duration::from_millis(100);
6570-
6571-fn scrub_due(target: u32, last_target: u32, since: Duration) -> bool {
6572- target != last_target && since >= SCRUB_GAP
6573-}
6574-
6575-/// How far the picture may fall behind the sound before it is restarted at the
6576-/// clock instead of left to crawl after it. Past what an eye reads as lip sync
6577-/// (a tenth of a second or so) and above what a single reopen costs to fix, so a
6578-/// picture that is merely a reopen behind is not answered with another one.
6579-const LATE_RESYNC: f64 = 0.4;
6580-/// The least time between two such restarts: the decoder that cannot keep up is
6581-/// the one this fires for, and it will still be behind straight afterwards.
6582-const RESYNC_GAP: Duration = Duration::from_secs(2);
6583-
6584-/// Whether a picture `late` seconds behind the master clock is restarted at it,
6585-/// given when the last restart was ([`Player::pump`]).
6586-fn should_resync(late: f64, last: Option<Instant>) -> bool {
6587- late > LATE_RESYNC && last.is_none_or(|t| t.elapsed() >= RESYNC_GAP)
6588-}
6589-
6590-/// The gate a live drag sample goes through. With the worker still owing a
6591-/// frame (`busy`), writing now would only cancel the open the picture is already
6592-/// waiting for -- the sample is held in `stash` instead, and the frame that
6593-/// lands writes it ([`Player::flush_drag`]). Returns what to write, if anything.
6594-///
6595-/// The press (`first`) never waits: it is the undo step the whole gesture rolls
6596-/// back to, so it has to be taken against the state the hand picked up.
6597-fn stash_or_write<T: Copy>(stash: &mut Option<T>, value: T, first: bool, busy: bool) -> Option<T> {
6598- match busy && !first {
6599- true => {
6600- *stash = Some(value);
6601- None
6602- }
6603- false => Some(value),
6604- }
6605-}
6606-
6607-/// How long an open may stand before the window says so in words. Well past an
6608-/// ordinary seek (a warm reopen is under a tenth of this) and well under what a
6609-/// cold read of a big film takes, which is the only case worth a line.
6610-const SEEK_STALL: Duration = Duration::from_secs(2);
6611-
6612-/// What a seek that has stood past [`SEEK_STALL`] says, and nothing at all
6613-/// before that: a line on every click of the ruler would be a flicker, and the
6614-/// picture holding still for a tenth of a second is not something to explain.
6615-/// The import bar's words, for the import bar's reason -- a window that cannot
6616-/// move and a window that has hung look identical, so this one says which.
6617-fn seek_line(standing: Option<Duration>) -> Option<String> {
6618- let since = standing.filter(|d| *d >= SEEK_STALL)?;
6619- Some(format!(
6620- "still opening the picture — a cold read of a big file is seconds of it, and the window \
6621- is not frozen · {} elapsed",
6622- clock(since.as_secs_f32())
6623- ))
6624-}
6625-
6626-/// How a finished export announces itself. Written by `poll_export` and read
6627-/// by the notice bar, which is what makes that one line clickable.
6628-const EXPORT_DONE: &str = "EXPORT DONE → ";
6629-
6630-/// The path as a URI the bus will take: percent-encoded, because an export
6631-/// lands wherever its source lives and those directories have spaces in them.
6632-/// Bytes, not chars -- a path is not required to be UTF-8.
6633-fn file_uri(path: &std::path::Path) -> String {
6634- use std::os::unix::ffi::OsStrExt;
6635- let mut uri = String::from("file://");
6636- for &b in path.as_os_str().as_bytes() {
6637- match b {
6638- b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' | b'/' => {
6639- uri.push(b as char)
6640- }
6641- _ => uri.push_str(&format!("%{b:02X}")),
6642- }
6643- }
6644- uri
6645-}
6646-
6647-/// Shows a file in the desktop's file manager, selected: the freedesktop
6648-/// interface every major one answers, asked for over the session bus. With no
6649-/// file manager on the bus the folder itself is the next best thing, and with
6650-/// neither there is nothing to say -- the notice the click retired was the
6651-/// answer, and a machine without a desktop opener is not one a second notice
6652-/// would help. Blocks on two child processes, so it is never called on the UI
6653-/// thread.
6654-fn show_in_file_manager(path: &std::path::Path) {
6655- // The URI must be absolute; an export path is only as absolute as the
6656- // source it was built from.
6657- let path = std::fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf());
6658- let shown = std::process::Command::new("busctl")
6659- .args([
6660- "--user",
6661- "call",
6662- "org.freedesktop.FileManager1",
6663- "/org/freedesktop/FileManager1",
6664- "org.freedesktop.FileManager1",
6665- "ShowItems",
6666- "ass",
6667- "1",
6668- &file_uri(&path),
6669- "",
6670- ])
6671- .status()
6672- .is_ok_and(|s| s.success());
6673- if shown {
6674- return;
6675- }
6676- if let Some(dir) = path.parent() {
6677- let _ = std::process::Command::new("xdg-open").arg(dir).status();
6678- }
6679-}
6680-
6681-/// Runs the first chooser that is installed. `Some(None)` is a cancelled
6682-/// dialog; `None` is a machine with no chooser at all, and what still works
6683-/// without one differs per dialog, so the caller words that refusal.
6684-///
6685-/// The desktop's own choosers, asked for by name because gpui 0.2 has no file
6686-/// dialog of its own and none of these is worth a dependency.
6687-fn run_picker(pickers: [(&str, Vec<String>); 2]) -> Option<Option<PathBuf>> {
6688- for (bin, args) in pickers {
6689- // Not installed: try the next one. Anything else (a cancel, a refusal)
6690- // is that chooser's answer and is taken as final.
6691- let Ok(out) = std::process::Command::new(bin).args(args).output() else {
6692- continue;
6693- };
6694- let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
6695- return Some((!path.is_empty()).then(|| PathBuf::from(path)));
6696- }
6697- None
6698-}
6699-
6700-/// `title` is what the dialog calls itself: two buttons open this same chooser
6701-/// for two different questions -- a file to import, a file to take subtitles out
6702-/// of -- and a dialog titled "import" over the second one is the wrong question
6703-/// answered. No extension filter on either: what can be read is the engine's
6704-/// answer (`PlaybackSession::parse_subtitles` takes a container as readily as a
6705-/// `.srt`), and a list of suffixes written here would hide a file edith would
6706-/// have taken.
6707-fn pick_file(title: &str) -> Result<Option<PathBuf>, &'static str> {
6708- run_picker([
6709- (
6710- "zenity",
6711- vec!["--file-selection".into(), format!("--title={title}")],
6712- ),
6713- ("kdialog", vec!["--getopenfilename".into()]),
6714- ])
6715- .ok_or(
6716- "NO FILE CHOOSER — install zenity or kdialog, or drag the file onto this window to import it",
6717- )
6718-}
6719-
6720-/// The save-side dialog, opened on where the export would land anyway: with no
6721-/// chooser installed that default is still what gets written, so this refusal
6722-/// costs the export nothing and says so.
6723-fn pick_save(default: &std::path::Path) -> Result<Option<PathBuf>, &'static str> {
6724- let default = default.to_string_lossy().into_owned();
6725- run_picker([
6726- (
6727- "zenity",
6728- vec![
6729- "--file-selection".into(),
6730- // No `--confirm-overwrite`: zenity 4.2 lists it as deprecated
6731- // and does the confirming itself.
6732- "--save".into(),
6733- "--title=edith — export to".into(),
6734- format!("--filename={default}"),
6735- ],
6736- ),
6737- ("kdialog", vec!["--getsavefilename".into(), default]),
6738- ])
6739- .ok_or(
6740- "NO FILE CHOOSER — install zenity or kdialog to choose where; exporting beside the source",
6741- )
6742-}
6743-
6744-/// Where an export goes: the source path with `.export.mp4` for an extension,
6745-/// so it lands beside the original and can never be the original.
6746-fn export_path(source: impl Into<PathBuf>) -> PathBuf {
6747- let mut path = source.into();
6748- path.set_extension("export.mp4");
6749- path
6750-}
6751-
6752-/// Where a save goes when the timeline did not come from a project file: the
6753-/// media path with `.edith` for an extension, beside it like an export. A
6754-/// project loaded from disk keeps its own path instead, so saving it twice
6755-/// writes the same file.
6756-fn project_path(source: impl Into<PathBuf>) -> PathBuf {
6757- let mut path = source.into();
6758- path.set_extension("edith");
6759- path
6760-}
6761-
6762-/// Whether a dropped or named path is a project rather than media. Exactly the
6763-/// lowercase extension `save_project` writes -- anything else goes to the
6764-/// demuxer, which is the one that can say what it really is.
6765-fn is_project(path: &std::path::Path) -> bool {
6766- path.extension().is_some_and(|e| e == "edith")
6767-}
6768-
6769-/// The tail of a path, for showing. A path that is all root has none, and reads
6770-/// as itself.
6771-fn file_name(path: &std::path::Path) -> String {
6772- path.file_name().map_or_else(
6773- || path.display().to_string(),
6774- |n| n.to_string_lossy().into(),
6775- )
6776-}
6777-
6778-/// How many messages wait behind the one on the bar before the oldest is
6779-/// dropped. A queue with no ceiling is a way for a stuck loop to eat the heap;
6780-/// eight is more than a user will ever answer in a row.
6781-const NOTICES_MAX: usize = 8;
6782-
6783-/// The narrowest a notice's *message* is allowed to be squeezed before its hint
6784-/// gives up the line and drops below it.
6785-///
6786-/// The bar is a message beside a hint, and at the 640x360 floor the picture
6787-/// region it hangs under is narrower than the hint alone -- so the message was
6788-/// squeezed to nothing and wrapped one character per line, which is a failure
6789-/// rendered as a column of letters. Wide enough that a line of it is a phrase
6790-/// rather than a word ladder, and narrow enough to still fit beside the hint in
6791-/// any window worth putting two things on a line in.
6792-const NOTICE_MIN_W: f32 = 180.;
6793-
6794-/// The whole of the queue's policy, where it can be read at once and tested
6795-/// without a window: dedupe against the back, a ceiling, oldest out first.
6796-/// [`Player::notify_user`] is the door every message comes through; this is what
6797-/// the door does.
6798-fn push_notice(notices: &mut std::collections::VecDeque<SharedString>, message: SharedString) {
6799- // A repeat of what is already at the back is dropped -- holding a key that
6800- // refuses would otherwise fill the queue with one sentence, and the count on
6801- // the bar would be a count of how long the key was held.
6802- if notices.back() == Some(&message) {
6803- return;
6804- }
6805- if notices.len() >= NOTICES_MAX {
6806- notices.pop_front();
6807- }
6808- notices.push_back(message);
6809-}
6810-
6811-/// The tail an open/load notice grows when the file has sound the engine cannot
6812-/// decode: it plays perfectly, in silence, and that is the one thing the window
6813-/// would otherwise never say (the engine's own word for it, verbatim).
6814-fn audio_notice(session: &PlaybackSession) -> Option<String> {
6815- session
6816- .audio_disabled_reason()
6817- .map(|reason| format!(" — NO AUDIO: {reason}"))
6818-}
6819-
6820-/// Whether a dropped or named path is a subtitle file rather than media: the
6821-/// formats `engine::subtitle` parses, lowercased, for [`engine::is_audio`]'s
6822-/// reason -- the import door has to know which of the engine's two doors a file
6823-/// goes through before anything is opened.
6824-///
6825-/// `.mks` is one of them, and it is the only Matroska extension that is: it is
6826-/// the *subtitles alone*, so there is no source in it to import and a drop of
6827-/// one used to be refused for having no video track -- while `+ S` on the same
6828-/// bytes took it ([`PlaybackSession::parse_subtitles`] reads it as Matroska).
6829-/// The other two are media and stay media: `.mka` is the sound alone, which
6830-/// [`engine::is_audio`] already imports as a song, and `.mk3d` is a film. Both
6831-/// may *carry* subtitles, which is [`carries_subtitles`] and not this.
6832-fn is_subtitle(path: &std::path::Path) -> bool {
6833- path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
6834- matches!(
6835- e.to_ascii_lowercase().as_str(),
6836- "srt" | "vtt" | "webvtt" | "ass" | "ssa" | "mks"
6837- )
6838- })
6839-}
6840-
6841-/// Whether a media path is a container that can carry subtitle tracks *inside*
6842-/// it -- every Matroska extension and the three ISO-BMFF ones, which is the list
6843-/// [`PlaybackSession::parse_subtitles`] walks (Matroska blocks and mp4 `tx3g`
6844-/// alike). Named for what it gates and not for one of the two families, because
6845-/// an mp4 answers `true` here now.
6846-///
6847-/// Matroska's set is the standard's own and closed by it
6848-/// (`engine::demux::is_matroska`), so it is copied whole rather than trimmed to
6849-/// the two that carry a film: a `.mk3d` opened as media has its tracks walked
6850-/// like the `.mkv` it is, and a `.mka` song can hold a lyric track. A suffix
6851-/// wider than the engine's would be a file taken here and refused deeper down.
6852-fn carries_subtitles(path: &std::path::Path) -> bool {
6853- path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
6854- matches!(
6855- e.to_ascii_lowercase().as_str(),
6856- "mkv" | "mka" | "mks" | "mk3d" | "webm" | "mp4" | "m4v" | "mov"
6857- )
6858- })
6859-}
6860-
6861-/// What a worker hands back, which is the fork [`arrival`] made when it was
6862-/// started. An import is *read* and thrown away; the file argv named is opened
6863-/// outright, because nothing else is going to open it afterwards.
6864-enum Landed {
6865- /// An import into a timeline that is up: the container probed and the
6866- /// subtitle tracks walked, both *kept* -- they are the expensive halves and
6867- /// the worker is where they belong, so [`Player::take_import`] is left with
6868- /// two pushes ([`engine::PlaybackSession::import_probed`],
6869- /// [`subtitle_tail`]).
6870- Read(Subs, Probe),
6871- /// A whole timeline the worker opened, with the tail its subtitle tracks
6872- /// earn, ready to be hung off the window -- or the engine's refusal. `true`
6873- /// is the media argv named, which *becomes* the timeline; `false` is a file
6874- /// arriving at a window that had none, which fills the library and leaves
6875- /// the lanes empty for a drag ([`Player::install_media`]).
6876- Media(Result<(PlaybackSession, String), String>, bool),
6877- /// A `.edith`, restored: argv's, and the one a drop or the Import button
6878- /// brought ([`arrival`]).
6879- Project(Result<PlaybackSession, String>),
6880-}
6881-
6882-/// What the container walk found, for [`Player::take_import`] to register, or
6883-/// the engine's refusal in the words it would have used on the UI thread.
6884-///
6885-/// `None` for the doors that never reach a demuxer: a song, a still and a
6886-/// subtitle file, whose own small reads stay where they were
6887-/// ([`engine::PlaybackSession::import`]).
6888-type Probe = Option<engine::Result<engine::ImportProbe>>;
6889-
6890-/// A media file opened as a session, with the subtitle tracks it carries inside
6891-/// it taken in the same breath -- the two reads a file costs, in the one place
6892-/// both doors ([`Player::open_media`] and the worker below) go through.
6893-///
6894-/// `place` is which door: a file *opened* is the timeline, one *imported* into
6895-/// an empty window fills the library and leaves the lanes empty for a drag.
6896-fn open_session(
6897- path: &std::path::Path,
6898- place: bool,
6899- subs: Subs,
6900-) -> Result<(PlaybackSession, String), String> {
6901- let opened = match place {
6902- true => PlaybackSession::open(path),
6903- false => PlaybackSession::open_library(path),
6904- };
6905- let mut session = opened.map_err(|e| e.to_string())?;
6906- let tail = subtitle_tail(&mut session, subs).unwrap_or_default();
6907- Ok((session, tail))
6908-}
6909-
6910-/// The whole of what a queued file costs, off the UI thread. An import only
6911-/// needs its pages warmed ([`read_ahead`]); the file argv named is *opened*
6912-/// here instead, and that is the difference between a warm launch paying for
6913-/// one header walk and paying for two -- the window is up either way.
6914-fn open_ahead(
6915- what: Landing,
6916- path: &std::path::Path,
6917- stage: &std::sync::atomic::AtomicU8,
6918- gate: Option<engine::ImportGate>,
6919-) -> Landed {
6920- match what {
6921- Landing::Import => read_ahead(path, stage, gate),
6922- Landing::Project => {
6923- let opened = PlaybackSession::open_project(path).map_err(|e| e.to_string());
6924- Landed::Project(opened)
6925- }
6926- Landing::Open => open_whole(path, true, stage),
6927- }
6928-}
6929-
6930-/// A whole timeline, opened here and handed over: the file argv named (`place`,
6931-/// which *is* the timeline) and a file arriving at a window with no timeline to
6932-/// import into, which fills the library instead. One function because they are
6933-/// one read -- the engine's two doors differ by which lanes come up empty
6934-/// ([`engine::PlaybackSession::open_library`]), not by what they walk.
6935-fn open_whole(path: &std::path::Path, place: bool, stage: &std::sync::atomic::AtomicU8) -> Landed {
6936- use std::sync::atomic::Ordering::Relaxed;
6937- let opened = match place {
6938- true => PlaybackSession::open(path),
6939- false => PlaybackSession::open_library(path),
6940- };
6941- // The same two stages a read reports, because they are the same two
6942- // reads: the container, and then the tracks inside it.
6943- stage.store(ImportStage::Subtitles as u8, Relaxed);
6944- Landed::Media(
6945- opened.map_err(|e| e.to_string()).map(|mut session| {
6946- let subs = subtitle_notice(&mut session, path).unwrap_or_default();
6947- (session, subs)
6948- }),
6949- place,
6950- )
6951-}
6952-
6953-/// Reads, off the UI thread, everything the import that follows would have read
6954-/// -- and hands all of it over. Nothing here is a warm-up any more: the
6955-/// container is *probed* ([`engine::PlaybackSession::probe_import`]) and the
6956-/// subtitle tracks are *walked*, and [`Player::take_import`] registers what came
6957-/// back. Measured on the 24 GB 4K HEVC remux: 21.4 s of header cold, 429 ms
6958-/// warm, plus 1-4 s of probing the timeline's own first source, plus the cue
6959-/// walk -- all of it here, and the window keeps painting through it.
6960-///
6961-/// `gate` is the timeline the file is checked against
6962-/// ([`engine::PlaybackSession::import_gate`]), taken before the worker started
6963-/// because a worker cannot reach the session. `None` is a window with no
6964-/// timeline to import into: then there is nothing to check against and nothing
6965-/// to register, so the file is *opened* here instead, whole
6966-/// ([`open_whole`]) -- which is the same twenty seconds, on the same thread,
6967-/// rather than on the one that draws.
6968-///
6969-/// The header error is carried back now rather than dropped: it is the engine's
6970-/// own refusal, from the only walk anybody makes, so it is worded once and shown
6971-/// at the landing. The subtitle refusal travels beside it for the same reason.
6972-///
6973-/// `stage` is what the line above the panel is naming while this runs.
6974-fn read_ahead(
6975- path: &std::path::Path,
6976- stage: &std::sync::atomic::AtomicU8,
6977- gate: Option<engine::ImportGate>,
6978-) -> Landed {
6979- use std::sync::atomic::Ordering::Relaxed;
6980- stage.store(ImportStage::Header as u8, Relaxed);
6981- // Nothing to import into, and nothing a subtitle file needs opened: the
6982- // first opens the library itself, here; the second has no container at all.
6983- let Some(gate) = gate else {
6984- return match is_subtitle(path) {
6985- true => Landed::Read(walk_subtitles(path), None),
6986- false => open_whole(path, false, stage),
6987- };
6988- };
6989- // The three doors an import goes through: a song is measured by its
6990- // duration and a still by its header -- both the engine's own reads, warmed
6991- // here and paid again at the landing, which is a header apiece -- and
6992- // everything else is the container walk, which is handed over whole.
6993- let probe = if engine::is_audio(path) {
6994- engine::AudioSession::duration_secs(path).ok();
6995- None
6996- } else if engine::is_image(path) || is_subtitle(path) {
6997- None
6998- } else {
6999- Some(PlaybackSession::probe_import(gate, path))
7000- };
7001- stage.store(ImportStage::Subtitles as u8, Relaxed);
7002- // ...and the tracks inside it, kept.
7003- Landed::Read(walk_subtitles(path), probe)
7004-}
7005-
7006-/// Every subtitle track a file carries, cues and all -- the walk that costs, in
7007-/// the one place every door that pays it goes through. `Ok` and empty for a file
7008-/// with none to read, which is what a file that is neither a container we can
7009-/// walk ([`carries_subtitles`]) nor a subtitle file is: the same answer
7010-/// `add_subtitle_tracks` gives it, and nothing is opened to find that out.
7011-///
7012-/// Nothing in here is a session, on purpose ([`PlaybackSession::parse_subtitles`]
7013-/// is an associated fn): no borrow crosses the await, so this runs whole on a
7014-/// worker while the window keeps painting.
7015-fn walk_subtitles(path: &std::path::Path) -> Subs {
7016- match carries_subtitles(path) || is_subtitle(path) {
7017- true => PlaybackSession::parse_subtitles(path),
7018- false => Ok(Vec::new()),
7019- }
7020-}
7021-
7022-/// The subtitle tracks a media file carries, taken into the session as it is
7023-/// opened, and the tail the notice grows for them: an mkv or an mp4 with
7024-/// subtitles in it arrives with its subtitles, because a track nobody imported
7025-/// is a track nobody knows is there. Every other container answers `None`
7026-/// without being read.
7027-///
7028-/// A refusal is a tail too, never a failure of the open: the picture and the
7029-/// sound of a film whose subtitle tracks cannot be walked are still the film.
7030-///
7031-/// Both halves at once, which only a *worker* may do: the walk reads the whole
7032-/// file for its cues (`engine::subtitle::of_matroska`) -- ~200 ms on a two-hour
7033-/// 4K remux, 9.7 s on a cold 25 GB one. The one caller is the open beside which
7034-/// this runs on the worker ([`open_ahead`]), never the render thread; an
7035-/// import splits the two halves across the hop instead ([`read_ahead`] walks,
7036-/// [`subtitle_tail`] pushes).
7037-fn subtitle_notice(session: &mut PlaybackSession, path: &std::path::Path) -> Option<String> {
7038- subtitle_tail(session, walk_subtitles(path))
7039-}
7040-
7041-/// What a subtitle walk ([`walk_subtitles`]) gave, on its way from whichever
7042-/// thread paid for it to the timeline. `Send` all the way down (`sendable()`,
7043-/// `engine/tests/subtitles.rs`), which is what lets the walk be a worker's.
7044-type Subs = engine::Result<Vec<engine::subtitle::SubtitleTrack>>;
7045-
7046-/// The tail a file's own subtitle tracks earn on the notice that names it, and
7047-/// the push that puts them on the timeline -- the second half of the walk, the
7048-/// cheap one ([`PlaybackSession::add_subtitle_tracks`]: no open, no seek, no
7049-/// decode). Every door that arrives with a *file* words it here, once: the file
7050-/// argv named, an import, and an import into an empty window cannot say the same
7051-/// thing differently, whichever thread read the cues.
7052-///
7053-/// `None` for a file that gave none and for one whose tracks are on the timeline
7054-/// already -- an import that adds nothing says nothing about subtitles. A
7055-/// refusal is a tail too, never a failure of the import: the picture and the
7056-/// sound of a film whose subtitle tracks cannot be walked are still the film.
7057-fn subtitle_tail(session: &mut PlaybackSession, subs: Subs) -> Option<String> {
7058- match subs {
7059- Ok(tracks) => match session.add_subtitle_tracks(tracks) {
7060- 0 => None,
7061- n => Some(format!(" — {n} subtitle track(s) in the file")),
7062- },
7063- Err(e) => Some(format!(" — SUBTITLES UNREAD: {e}")),
7064- }
7065-}
7066-
7067-/// The push both deliberate add-subtitles doors end on -- `+ S` and its key
7068-/// ([`Player::add_subtitles`]) and a dropped or argv'd subtitle file
7069-/// ([`Player::take_subtitles`]) -- so the two cannot come to word the same file
7070-/// differently.
7071-///
7072-/// The walk having found *nothing* is a refusal and not a count: a container
7073-/// with no subtitle track in it and a file whose tracks are all on the timeline
7074-/// already both push zero rows, and they are opposite answers -- one says look
7075-/// somewhere else, the other says you already have them. The engine's own door
7076-/// draws the same line in the same words
7077-/// ([`PlaybackSession::no_subtitles_in`], asked here because this route splits
7078-/// the walk from the push to keep the walk off the render thread).
7079-///
7080-/// The file itself joins nothing either way: no library row, no lane, no clip.
7081-/// Subtitles are a list the timeline carries, and this is the only thing that
7082-/// touches it.
7083-fn pushed(
7084- session: &mut PlaybackSession,
7085- path: &std::path::Path,
7086- tracks: Vec<engine::subtitle::SubtitleTrack>,
7087-) -> engine::Result<usize> {
7088- match tracks.is_empty() {
7089- true => Err(PlaybackSession::no_subtitles_in(path)),
7090- false => Ok(session.add_subtitle_tracks(tracks)),
7091- }
7092-}
7093-
7094-/// What a subtitle row says under its name: how many cues it holds and whether
7095-/// they are pictures ([`engine::subtitle::SubtitleTrack::is_bitmap`]) -- which
7096-/// is the difference between a track an export writes into the file and one it
7097-/// can only draw -- or, for a track that could not be read, the engine's own
7098-/// reason verbatim. A refusal is still what a row can be *for*: a VobSub track
7099-/// dropped from the list would say the film has no subtitles at all.
7100-fn subtitle_detail(track: &engine::subtitle::SubtitleTrack) -> String {
7101- match (&track.refused, track.is_bitmap()) {
7102- (Some(why), _) => why.clone(),
7103- (None, true) => format!("{} cues — pictures", track.cues.len()),
7104- (None, false) => format!("{} cues", track.cues.len()),
7105- }
7106-}
7107-
7108-/// What the export card's Subtitles row says: the engine's own words for the
7109-/// tracks an export carries (`plan`, [`engine::export::planned_subtitles`] asked
7110-/// about `picks`) and, beside them, the rows it is carrying nothing of.
7111-///
7112-/// `picks` is [`Player::export_subs`] -- every track with a cue left in the
7113-/// exported range -- so a track sitting in the list with eighty-three cues
7114-/// nowhere near a trimmed timeline never reaches the engine at all, and the card
7115-/// said nothing about it while the list went on showing it. Which tracks have
7116-/// cues *here* is this side's answer and nobody else's, so this side words it.
7117-///
7118-/// Past [`SUB_PLAN_CHARS`] the line counts rather than names: every name is more
7119-/// words in a value box `MENU_W` wide, and at 35 tracks the row wrapped to ten
7120-/// lines and pushed the Destination row under the fold of the card. The names
7121-/// are still one row each in the Subtitles list, with the cue count and the
7122-/// reason under them ([`subtitle_detail`]) -- more than this line ever said.
7123-///
7124-/// The counted split follows the engine's own order of reasons (`refused`, then
7125-/// pictures, then no cues), with the last asked of the timeline instead of the
7126-/// track.
7127-///
7128-/// corner-cut: that split reads the same public fields the list rows read
7129-/// (`refused`, [`engine::subtitle::SubtitleTrack::is_bitmap`]) rather than the
7130-/// engine's decision, so a *new* reason to drop a track would be counted here as
7131-/// embedded until this follows it -- the named line, which is the engine's
7132-/// string verbatim, would say it correctly meanwhile. Upgrade path: reasons out
7133-/// of `planned_subtitles` as data rather than as one sentence, which is an
7134-/// engine change.
7135-fn subtitle_plan(
7136- plan: String,
7137- tracks: &[engine::subtitle::SubtitleTrack],
7138- picks: &[usize],
7139-) -> String {
7140- let mut parts: Vec<String> = Vec::new();
7141- // "none" is the engine's word for an empty pick list and would read as a
7142- // verdict on the tracks named after it.
7143- if !picks.is_empty() {
7144- parts.push(plan);
7145- }
7146- parts.extend(
7147- tracks
7148- .iter()
7149- .enumerate()
7150- .filter(|(i, _)| !picks.contains(i))
7151- .map(|(_, track)| format!("{} — no cues here", track.label)),
7152- );
7153- let named = parts.join("; ");
7154- if named.chars().count() <= SUB_PLAN_CHARS {
7155- return match named.is_empty() {
7156- true => "none".to_string(),
7157- false => named,
7158- };
7159- }
7160- let (mut embedded, mut unread, mut pictures, mut off) = (0, 0, 0, 0);
7161- for (i, track) in tracks.iter().enumerate() {
7162- match (
7163- track.refused.is_some(),
7164- track.is_bitmap(),
7165- picks.contains(&i),
7166- ) {
7167- (true, _, _) => unread += 1,
7168- (_, true, _) => pictures += 1,
7169- (_, _, false) => off += 1,
7170- _ => embedded += 1,
7171- }
7172- }
7173- let mut counted = vec![format!("{embedded} of {} → embedded", tracks.len())];
7174- counted.extend(
7175- [
7176- (pictures, "pictures"),
7177- (unread, "unread"),
7178- (off, "no cues here"),
7179- ]
7180- .into_iter()
7181- .filter(|(n, _)| *n > 0)
7182- .map(|(n, why)| format!("{n} {why}")),
7183- );
7184- counted.join("; ")
7185-}
7186-
7187-/// Every subtitle track one file gave, kept together. Plain data, planned
7188-/// before anything is drawn -- the grouping is the branchy part and it is the
7189-/// same answer whatever a styling puts around it.
7190-///
7191-/// [`Player::subtitle_section`] draws one block per group of these, and
7192-/// [`sub_pick_name`] names the pick out of the same answer -- so what a heading
7193-/// says and what a row a person clicked says cannot disagree.
7194-#[derive(Debug, PartialEq)]
7195-struct SubGroup {
7196- /// What the group is called: the file without its extension, which is what
7197- /// a person named the film even when the subtitles came out of a remux.
7198- name: String,
7199- /// What the swatch is asked by ([`file_tint`]) -- the file, so a subtitle
7200- /// row and the media rows of the same file wear one colour. `None` from
7201- /// that lookup for a standalone `.srt`, which is nobody's stream.
7202- path: PathBuf,
7203- rows: Vec<SubRow>,
7204-}
7205-
7206-/// One subtitle track, as a row shows it.
7207-#[derive(Debug, PartialEq)]
7208-struct SubRow {
7209- /// Which track of the session's list this row is: the *flat* index into the
7210- /// add-order Vec `PlaybackSession::subtitles` hands back, which is what a
7211- /// click sets `sub_track` to and what a save writes into the `.edith`.
7212- /// Grouping moves rows around on screen and never touches this number.
7213- track: usize,
7214- /// Which of *this file's* tracks it is, counted from 1 -- the numbering
7215- /// [`row_name`] gives audio streams, for the same reason: two tracks off one
7216- /// remux that both say "eng" are told apart by nothing else.
7217- number: usize,
7218- label: String,
7219- /// The row's second line ([`subtitle_detail`]).
7220- detail: String,
7221- /// Why it cannot be shown, for a track that cannot: the only thing that
7222- /// greys a row out. Listed all the same -- a picker that hides them is a
7223- /// picker that lies.
7224- refused: Option<String>,
7225- /// Pictures rather than lines ([`engine::subtitle::SubtitleTrack::bitmap`]).
7226- bitmap: bool,
7227-}
7228-
7229-/// What a subtitle row is called, off the two fields the container really
7230-/// stated rather than out of the flattened
7231-/// [`label`](engine::subtitle::SubtitleTrack::label). The pair is what an export
7232-/// writes (`TRACK_LANGUAGE` and `TRACK_NAME` are two fields), and reading the
7233-/// display string back apart is the very heuristic that sent every French track
7234-/// out as English: `lang_human` on a whole "und — Signs" matches nothing and
7235-/// names a language nobody speaks.
7236-///
7237-/// The three shapes a track arrives in, all three of them real: a standalone
7238-/// file states no language and is its own name, an embedded one states a
7239-/// language and sometimes a title beside it, and a refused one states neither
7240-/// and keeps the label it was refused under (`SubtitleTrack::refused`).
7241-fn sub_title(sub: &engine::subtitle::SubtitleTrack) -> String {
7242- match (sub.language.as_str(), sub.name.as_str()) {
7243- ("", "") => sub.label.clone(),
7244- ("", name) => name.to_string(),
7245- // A track whose only name is the tag for "nobody said" says that in
7246- // words rather than showing the tag itself.
7247- (lang, "") => lang_human(lang).to_string(),
7248- // ...and one that says "nobody said" *and* gives a title is the title:
7249- // "unknown language — Signs" pads it with a word the file never said.
7250- ("und", name) => name.to_string(),
7251- (lang, name) => format!("{lang} — {name}"),
7252- }
7253-}
7254-
7255-/// The subtitle list as rows under the file each came out of: one group per
7256-/// distinct path, in the order the files first appear, and each file's tracks
7257-/// in the order they were added. Two remuxes' tracks arriving interleaved --
7258-/// which is what importing a second film does -- still read as two films.
7259-fn subtitle_rows(tracks: &[engine::subtitle::SubtitleTrack]) -> Vec<SubGroup> {
7260- let mut groups: Vec<SubGroup> = Vec::new();
7261- for (track, sub) in tracks.iter().enumerate() {
7262- let group = match groups.iter().position(|g| g.path == sub.path) {
7263- Some(i) => &mut groups[i],
7264- None => {
7265- groups.push(SubGroup {
7266- name: sub
7267- .path
7268- .file_stem()
7269- .map_or_else(|| file_name(&sub.path), |s| s.to_string_lossy().into()),
7270- path: sub.path.clone(),
7271- rows: Vec::new(),
7272- });
7273- groups.last_mut().expect("just pushed")
7274- }
7275- };
7276- group.rows.push(SubRow {
7277- track,
7278- number: group.rows.len() + 1,
7279- label: sub_title(sub),
7280- detail: subtitle_detail(sub),
7281- refused: sub.refused.clone(),
7282- bitmap: sub.is_bitmap(),
7283- });
7284- }
7285- groups
7286-}
7287-
7288-/// How the picked track is named wherever the pick is echoed -- the strip
7289-/// header, the section heading, the toggle's own notice. What the track is
7290-/// *and* which file it came out of: two remuxes each carrying an "eng" track
7291-/// give the same word twice, and the file is the only thing that tells them
7292-/// apart. A file that gave several of them numbers them within itself, the way
7293-/// [`row_name`] numbers audio streams, since "eng" twice off one remux is the
7294-/// same problem one file down.
7295-///
7296-/// Goes through [`subtitle_rows`], so the name a header says and the row a
7297-/// person clicked cannot disagree -- and the label is humanised there, so an
7298-/// "und" track is named in words here without being passed through
7299-/// [`lang_human`] twice.
7300-///
7301-/// `None` for an index no track answers to, which is the silence
7302-/// [`Player::subtitle_track`] gives at the same moment.
7303-/// Where the picked subtitle row lands once `removed` has been taken off a list
7304-/// that is `left` long afterwards. The pick follows the list: the same *track*
7305-/// while it is still there -- every index past the one that went moves down
7306-/// ([`engine::Project::remove_subtitles`]) -- the row that slid into the empty
7307-/// place when the picked one is what went, and the last row when that was the
7308-/// last. Zero on an emptied list, which is the index the section is not drawn at
7309-/// all.
7310-///
7311-/// Its own function because the pick is what the overlay draws: left where it
7312-/// was it would name a different track, and the plate over the picture would
7313-/// change language on its own the moment a row above it went. What an export
7314-/// writes is *not* this pick and cannot be desynced by a removal -- it is worked
7315-/// out from the cues on the timeline each time ([`Player::export_subs`]).
7316-fn sub_pick_after_removal(picked: usize, removed: usize, left: usize) -> usize {
7317- let picked = match removed < picked {
7318- true => picked - 1,
7319- false => picked,
7320- };
7321- picked.min(left.saturating_sub(1))
7322-}
7323-
7324-fn sub_pick_name(tracks: &[engine::subtitle::SubtitleTrack], track: usize) -> Option<String> {
7325- subtitle_rows(tracks).into_iter().find_map(|group| {
7326- let row = group.rows.iter().find(|row| row.track == track)?;
7327- let track = match group.rows.len() > 1 {
7328- false => row.label.clone(),
7329- true => format!("{} {}", row.label, row.number),
7330- };
7331- // A standalone `.srt` is already named after its own file: "sub.srt —
7332- // sub" says the one thing twice, and the film is only worth naming
7333- // where it is not in the label yet.
7334- Some(match row.label.starts_with(&group.name) {
7335- true => track,
7336- false => format!("{track} — {}", group.name),
7337- })
7338- })
7339-}
7340-
7341-/// Where a cue is drawn on the bed: left edge and width in pixels, through the
7342-/// same [`Scale`] every clip box goes through -- so a cue and the take it is
7343-/// spoken over line up at every zoom, which is the only reason the strip is
7344-/// worth drawing. Microseconds are the cue's unit and seconds are the scale's,
7345-/// and this is the one place they meet.
7346-///
7347-/// Never narrower than [`SUB_CUE_MIN_W`]: zoomed out, a one-second cue is a
7348-/// fraction of a pixel, and a mark that rounds away reads as a track with
7349-/// nothing in it.
7350-fn cue_box(scale: Scale, cue: &engine::subtitle::Cue) -> (f32, f32) {
7351- let (start, end) = (cue.start_us as f64 / 1e6, cue.end_us as f64 / 1e6);
7352- (
7353- scale.px_at(start),
7354- scale.width_px(end - start).max(SUB_CUE_MIN_W),
7355- )
7356-}
7357-
7358-/// Which cues of a track are on screen at `at` seconds. Half-open, as the cue
7359-/// itself is: one that ends exactly where the next begins hands over rather than
7360-/// overlapping it for a frame, and several that genuinely overlap all come back
7361-/// -- a sign and a line of dialogue are two cues at one moment.
7362-fn cues_at(cues: &[engine::subtitle::Cue], at: f64) -> Vec<&engine::subtitle::Cue> {
7363- let us = (at * 1e6) as i64;
7364- cues.iter()
7365- .filter(|cue| cue.start_us <= us && us < cue.end_us)
7366- .collect()
7367-}
7368-
7369-/// The sources a repaint has not asked about yet. A key that is already there
7370-/// means "asked", whatever state it is in, which is what stops a decode already
7371-/// running from being started again by the next of sixty repaints a second.
7372-fn unseen_sources(
7373- sources: &[Source],
7374- waves: &HashMap<(PathBuf, usize), Wave>,
7375-) -> Vec<(PathBuf, usize)> {
7376- sources
7377- .iter()
7378- .map(|s| (s.path.clone(), s.audio_stream))
7379- .filter(|key| !waves.contains_key(key))
7380- .collect()
7381-}
crates/app/src/menus.rsadded+254 -0
@@ -0,0 +1,254 @@
1+//! The lists the window opens over itself: the clip menu, the pickers, the key rows.
2+
3+use crate::*;
4+
5+/// An open clip menu: which clip it was opened on, where it hangs, and whether
6+/// it has been turned over to show what that clip *is* instead of what can be
7+/// done to it. The lane and index are the ones the same click selected, so
8+/// every item acts on exactly the box under the pointer.
9+#[derive(Clone, Copy)]
10+pub(crate) struct ContextMenu {
11+ pub(crate) lane: Lane,
12+ pub(crate) idx: usize,
13+ pub(crate) at: Point<Pixels>,
14+ pub(crate) details: bool,
15+}
16+
17+/// An open library menu: which row it was opened on -- the file and the stream,
18+/// the pair [`Player::selected_asset`] holds, so a list rebuilt under it (a
19+/// probe landing, a source going) cannot slide another row beneath the menu the
20+/// way a row *index* would -- where it hangs, and whether it has been turned
21+/// over to show what the file *is*.
22+#[derive(Clone)]
23+pub(crate) struct LibraryMenu {
24+ pub(crate) path: PathBuf,
25+ pub(crate) stream: usize,
26+ pub(crate) at: Point<Pixels>,
27+ pub(crate) details: bool,
28+}
29+
30+/// An open choice list: which setting it offers and where it hangs. What a
31+/// button that stepped one value on per click used to be -- a setting with more
32+/// than two values is a list to look at, not a thing to click round. Placed by
33+/// [`menu_at`] and closed by a stroke, exactly like the two menus above it.
34+#[derive(Clone, Copy, PartialEq)]
35+pub(crate) struct Picker {
36+ pub(crate) of: Pick,
37+ pub(crate) at: Point<Pixels>,
38+ /// Which row the keyboard is on, from the value in force when the list
39+ /// opened. The list answers ↑↓ and enter as well as a click: a setting whose
40+ /// only door is a pointer is a setting half this editor's users cannot
41+ /// reach, which is the rule `FIXED` already writes down for every card.
42+ pub(crate) sel: usize,
43+}
44+
45+/// Which setting an open list is offering. The fit policy names the clip it is
46+/// about, like the clip menu it opens from -- indices move under every edit, so
47+/// the list closes on the first stroke as that menu does.
48+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
49+pub(crate) enum Pick {
50+ Resolution,
51+ Fps,
52+ Fit(Lane, usize),
53+ /// What the export's *sound* is coded at. Opened from the card's Sound row,
54+ /// which is the only place it means anything.
55+ AudioRate,
56+ /// Which HDR-to-SDR rendition the project is watched and exported in
57+ /// ([`engine::tonemap::Preset`]). Opened from the panel, beside the two
58+ /// other settings that are the project's rather than the media's.
59+ Tone,
60+ /// Which palette the window is painted in ([`ui::theme`]). The one setting
61+ /// here that is nobody's project: it is the person's, so it outlives the
62+ /// timeline and every file opened in it.
63+ Theme,
64+}
65+
66+/// One value a list offers, carrying everything picking it needs -- so a click
67+/// goes straight to the value rather than to a position in a list that was
68+/// built somewhere else.
69+/// `Eq` is off it for the rate: a frame rate is the `f64` the engine is told,
70+/// bit for bit (23.976023976... is not 23.976), and nothing here keys a map on a
71+/// choice -- comparing two is all a list row ever does.
72+#[derive(Clone, Copy, PartialEq, Debug)]
73+pub(crate) enum Choice {
74+ Size(u32, u32),
75+ Fps(f64),
76+ Fit(Lane, usize, FitPolicy),
77+ AudioRate(u32),
78+ Tone(Preset),
79+ Theme(ui::theme::PaletteId),
80+}
81+
82+/// One row of an open list: the value, its name, the small print beside it, and
83+/// whether it is the one in force.
84+pub(crate) type ChoiceRow = (Choice, SharedString, SharedString, bool);
85+
86+/// What a library row's menu offers, in the order it lists them. Unlike the clip
87+/// menu's items none of these is a stroke -- there is no keyboard way to a row --
88+/// so the label and the hint are written here rather than read off the keymap.
89+#[derive(Clone, Copy, PartialEq)]
90+pub(crate) enum RowItem {
91+ Add,
92+ Remove,
93+ Reveal,
94+ Properties,
95+}
96+
97+pub(crate) const ROW_ITEMS: [RowItem; 4] = [
98+ RowItem::Add,
99+ RowItem::Remove,
100+ RowItem::Reveal,
101+ RowItem::Properties,
102+];
103+
104+impl RowItem {
105+ pub(crate) fn label(self) -> &'static str {
106+ match self {
107+ Self::Add => "Add at playhead",
108+ Self::Remove => "Remove from library",
109+ Self::Reveal => "Reveal in files",
110+ Self::Properties => "Properties",
111+ }
112+ }
113+
114+ /// The dim right-hand column, where the clip menu prints the stroke: what
115+ /// the item will do to the timeline, so nothing here is a surprise.
116+ pub(crate) fn hint(self) -> &'static str {
117+ match self {
118+ // Short enough to sit beside its label inside `MENU_W`, the clip
119+ // menu's rule for a refusal: this column truncates, and a hint cut
120+ // off mid-word says less than a shorter one.
121+ Self::Add => "the whole file",
122+ Self::Remove => "nothing plays it",
123+ Self::Reveal => "file manager",
124+ Self::Properties => "…",
125+ }
126+ }
127+}
128+
129+/// What the menu offers, in the order it lists them. Every one of these is an
130+/// action a stroke already reaches -- the menu is a second way *to* the actions
131+/// and never a second version of them -- so both the label and the hint come
132+/// out of the keymap registry and the two can never disagree.
133+pub(crate) const MENU_ITEMS: [ActionId; 14] = [
134+ ActionId::Cut,
135+ // The clipboard pair, which had no door but a chord: copy takes the clip the
136+ // menu names, and paste is the timeline's rather than this clip's -- the
137+ // same kind of global item the mute below already is.
138+ ActionId::Copy,
139+ ActionId::Paste,
140+ ActionId::Delete,
141+ ActionId::Lift,
142+ ActionId::Regroup,
143+ ActionId::Detach,
144+ ActionId::Group,
145+ ActionId::Equalizer,
146+ ActionId::Speed,
147+ // The scan is a clip card like the two above it -- opened on whichever half
148+ // was clicked -- and a card only a stroke could open is one a pointer never
149+ // finds.
150+ ActionId::Silence,
151+ ActionId::Color,
152+ ActionId::Fit,
153+ ActionId::ToggleMute,
154+];
155+
156+/// One row of the actions card, in the order it lists them: a heading, then
157+/// every action the registry files under it, then the strokes the modal cards
158+/// answer themselves.
159+///
160+/// A list rather than a loop inside the render, so the card and
161+/// `every_action_is_on_the_actions_card` read the *same* order: an action that
162+/// reaches no row fails a test instead of quietly becoming pointer-unreachable.
163+pub(crate) enum KeyRow {
164+ Head(keymap::Category),
165+ /// Click its label to do it, click its stroke to change that stroke.
166+ Act(ActionId),
167+ /// An index into [`keymap::FIXED`]. Shown and never offered: nothing may
168+ /// unbind the way out of a card.
169+ Fixed(usize),
170+}
171+
172+/// Every action, under its heading, and the card-local strokes beside them.
173+/// Generated from the registry -- [`ActionId::ALL`] in its own order, under
174+/// [`keymap::Category::ALL`] -- so an action added there is on the card the
175+/// moment it exists and there is no second list here to forget.
176+pub(crate) fn keys_rows() -> Vec<KeyRow> {
177+ let mut rows = Vec::new();
178+ for category in keymap::Category::ALL {
179+ rows.push(KeyRow::Head(category));
180+ rows.extend(
181+ ActionId::ALL
182+ .into_iter()
183+ .filter(|a| a.category() == category)
184+ .map(KeyRow::Act),
185+ );
186+ rows.extend(
187+ keymap::FIXED
188+ .iter()
189+ .enumerate()
190+ .filter(|(_, f)| f.category == category)
191+ .map(|(i, _)| KeyRow::Fixed(i)),
192+ );
193+ }
194+ rows
195+}
196+
197+/// [`keys_rows`] with a search applied: the rows whose label or whose stroke
198+/// carries `needle`, and the heading each one lives under. A heading with
199+/// nothing left beneath it goes with them -- an empty "Playback" over a gap
200+/// reads as a list that lost its rows rather than as a search that found none.
201+///
202+/// Each row keeps the index it has in the unfiltered list, so an element id is
203+/// the same one before and after a keystroke: filtering is a look at the list,
204+/// and gpui's per-element state is keyed on that id.
205+///
206+/// Case-insensitive substring, on both columns: people look for an action by
207+/// what it does ("vol") and for a stroke by what they pressed ("ctrl").
208+pub(crate) fn keys_filter(needle: &str, keymap: &Keymap) -> Vec<(usize, KeyRow)> {
209+ let needle = needle.trim().to_lowercase();
210+ let rows = keys_rows().into_iter().enumerate();
211+ if needle.is_empty() {
212+ return rows.collect();
213+ }
214+ let hit = |label: &str, chord: &str| {
215+ label.to_lowercase().contains(&needle) || chord.to_lowercase().contains(&needle)
216+ };
217+ let mut out: Vec<(usize, KeyRow)> = Vec::new();
218+ // The heading above the row being looked at, until a row under it earns it
219+ // a place -- then it goes in once, ahead of that row.
220+ let mut pending: Option<(usize, KeyRow)> = None;
221+ for (i, row) in rows {
222+ match &row {
223+ KeyRow::Head(_) => pending = Some((i, row)),
224+ KeyRow::Act(action) => {
225+ if hit(action.label(), &keymap.display(*action)) {
226+ out.extend(pending.take());
227+ out.push((i, row));
228+ }
229+ }
230+ KeyRow::Fixed(f) => {
231+ let fixed = &keymap::FIXED[*f];
232+ if hit(fixed.label, &fixed.chord) {
233+ out.extend(pending.take());
234+ out.push((i, row));
235+ }
236+ }
237+ }
238+ }
239+ out
240+}
241+
242+/// The character a stroke types into the actions card's search box, if it types
243+/// one. gpui reports a printable key as itself and the space bar by name
244+/// (platform.rs:866), and everything else -- the arrows, the function keys --
245+/// is a word this must not spell into the box letter by letter.
246+pub(crate) fn typed(key: &str) -> Option<char> {
247+ match key {
248+ "space" => Some(' '),
249+ _ => key
250+ .chars()
251+ .next()
252+ .filter(|c| c.is_ascii_graphic() && key.chars().count() == 1),
253+ }
254+}
crates/app/src/notices.rsadded+45 -0
@@ -0,0 +1,45 @@
1+//! The notice bar's queue.
2+
3+use crate::*;
4+
5+/// How many messages wait behind the one on the bar before the oldest is
6+/// dropped. A queue with no ceiling is a way for a stuck loop to eat the heap;
7+/// eight is more than a user will ever answer in a row.
8+pub(crate) const NOTICES_MAX: usize = 8;
9+
10+/// The narrowest a notice's *message* is allowed to be squeezed before its hint
11+/// gives up the line and drops below it.
12+///
13+/// The bar is a message beside a hint, and at the 640x360 floor the picture
14+/// region it hangs under is narrower than the hint alone -- so the message was
15+/// squeezed to nothing and wrapped one character per line, which is a failure
16+/// rendered as a column of letters. Wide enough that a line of it is a phrase
17+/// rather than a word ladder, and narrow enough to still fit beside the hint in
18+/// any window worth putting two things on a line in.
19+pub(crate) const NOTICE_MIN_W: f32 = 180.;
20+
21+/// The whole of the queue's policy, where it can be read at once and tested
22+/// without a window: dedupe against the back, a ceiling, oldest out first.
23+/// [`Player::notify_user`] is the door every message comes through; this is what
24+/// the door does.
25+pub(crate) fn push_notice(notices: &mut std::collections::VecDeque<SharedString>, message: SharedString) {
26+ // A repeat of what is already at the back is dropped -- holding a key that
27+ // refuses would otherwise fill the queue with one sentence, and the count on
28+ // the bar would be a count of how long the key was held.
29+ if notices.back() == Some(&message) {
30+ return;
31+ }
32+ if notices.len() >= NOTICES_MAX {
33+ notices.pop_front();
34+ }
35+ notices.push_back(message);
36+}
37+
38+/// The tail an open/load notice grows when the file has sound the engine cannot
39+/// decode: it plays perfectly, in silence, and that is the one thing the window
40+/// would otherwise never say (the engine's own word for it, verbatim).
41+pub(crate) fn audio_notice(session: &PlaybackSession) -> Option<String> {
42+ session
43+ .audio_disabled_reason()
44+ .map(|reason| format!(" — NO AUDIO: {reason}"))
45+}
crates/app/src/oracle.rsadded+293 -0
@@ -0,0 +1,293 @@
1+//! Whether an action can be asked for -- the one answer every surface reads.
2+
3+use crate::*;
4+
5+/// Whether an action can be asked for, and what to say when it cannot. Two
6+/// kinds of no: `Hidden` is about the *kind* of thing the action was aimed at
7+/// -- an audio clip has no picture, so a grade is not a thing that exists for
8+/// it, whatever the editor does next -- and `No` is about the state of this
9+/// moment, which the next click of the playhead can change. The clip menu
10+/// leaves the class refusals *out* and dims the state ones ([`Enable::listed`]);
11+/// the actions card, which is the whole registry laid out, dims both with their
12+/// reason -- an action missing from the one surface that lists everything would
13+/// read as an action that does not exist.
14+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
15+pub(crate) enum Enable {
16+ Yes,
17+ No(&'static str),
18+ Hidden(&'static str),
19+}
20+
21+impl Enable {
22+ /// Whether the row takes a click.
23+ pub(crate) fn yes(self) -> bool {
24+ self == Enable::Yes
25+ }
26+
27+ /// Whether a menu *about this clip* draws the row at all: a class refusal
28+ /// is a thing that does not exist for what was clicked, and a row nothing
29+ /// the user does could ever light is noise between the ones they came for.
30+ pub(crate) fn listed(self) -> bool {
31+ !matches!(self, Enable::Hidden(_))
32+ }
33+
34+ /// What the row says instead of its stroke, if it says anything.
35+ pub(crate) fn why(self) -> Option<&'static str> {
36+ match self {
37+ Enable::Yes => None,
38+ Enable::No(why) | Enable::Hidden(why) => Some(why),
39+ }
40+ }
41+}
42+
43+/// What an enablement question is asked *about*: the clip in question, if there
44+/// is one, and the little of the editor's state the answers need. Handed in
45+/// rather than read off the player, so [`enable`] is a pure function a test can
46+/// ask about a clip without building a window.
47+#[derive(Clone, Copy, Default)]
48+pub(crate) struct Ctx {
49+ /// The clip the question is about -- the one a menu was opened on, or the
50+ /// marked one. `None` means the question is about the editor as a whole,
51+ /// and the clip-relative answers stand aside: those actions find their own
52+ /// clip under the playhead and word their own refusal.
53+ pub(crate) clip: Option<(Clip, Lane)>,
54+ /// The clip plays a still ([`engine::is_image`]), which has no sound to
55+ /// reach at all -- not the lane's business, because a still sits on a video
56+ /// lane exactly like a take whose sound is one lane down.
57+ pub(crate) image: bool,
58+ pub(crate) playhead: u32,
59+ /// A timeline is open.
60+ pub(crate) timeline: bool,
61+ /// Something has been copied.
62+ pub(crate) clipboard: bool,
63+ /// This timeline has at least one subtitle track: a toggle with nothing to
64+ /// show is a switch that does nothing, and it says so rather than flipping.
65+ pub(crate) subtitles: bool,
66+ /// There is something on the lanes to play. A transport with nothing under
67+ /// it is the one refusal that is about the timeline's contents rather than
68+ /// about a clip.
69+ pub(crate) playable: bool,
70+ pub(crate) exporting: bool,
71+}
72+
73+/// Whether `action` can be asked for, on `ctx`. One arm per action and nothing
74+/// else in the editor asks the question: the clip menu dims a row with this,
75+/// the actions card dims a row with this, and the two can never come to
76+/// disagree about what an action needs -- exactly the reason [`Player::act`] is
77+/// one table too.
78+pub(crate) fn enable(action: ActionId, ctx: Ctx) -> Enable {
79+ // The one action that is about the editor rather than about the timeline:
80+ // the list of what everything does, and where a key is changed. An empty
81+ // window has no clips and still has keys -- so this answers ahead of the
82+ // timeline question, and only an export shuts it (a waiting row would
83+ // swallow the escape the progress line promises cancels the export).
84+ // The window's own colours: there is always a window, and repainting it
85+ // touches no timeline -- so this one is live even while an export is
86+ // reading one, which is the only state that dims the list above.
87+ if action == ActionId::Theme {
88+ return Enable::Yes;
89+ }
90+ if action == ActionId::ShowActions {
91+ return match ctx.exporting {
92+ true => Enable::No("an export is running"),
93+ false => Enable::Yes,
94+ };
95+ }
96+ // The four that are about the *editor* and its monitoring rather than
97+ // about the edit list: they work with nothing open, the keyboard has
98+ // always fired them there, and so their buttons are live there too.
99+ if matches!(
100+ action,
101+ ActionId::ToggleSnap | ActionId::ToggleMute | ActionId::VolumeUp | ActionId::VolumeDown
102+ ) {
103+ return match ctx.exporting {
104+ true => Enable::No("an export is running"),
105+ false => Enable::Yes,
106+ };
107+ }
108+ if !ctx.timeline {
109+ return Enable::No("no timeline open");
110+ }
111+ // An export is reading the edit list every other action would change, which
112+ // is the rule the key handler already follows.
113+ if ctx.exporting {
114+ return match action {
115+ ActionId::CancelExport => Enable::Yes,
116+ _ => Enable::No("an export is running"),
117+ };
118+ }
119+ match action {
120+ // -- class: what kind of thing the action is about. The equalizer
121+ // filters samples, and a video clip has none of its own here: the sound
122+ // is the audio lane's, clip for clip.
123+ ActionId::Equalizer => match ctx.clip {
124+ Some((_, lane)) if lane.kind != LaneKind::Audio => Enable::Hidden("this clip is picture"),
125+ _ => Enable::Yes,
126+ },
127+ // A grade is a picture setting and an audio clip has no picture. A fit
128+ // policy is a picture setting for the same reason.
129+ ActionId::Color | ActionId::Fit => match ctx.clip {
130+ Some((_, lane)) if lane.kind != LaneKind::Video => Enable::Hidden("this clip is sound"),
131+ _ => Enable::Yes,
132+ },
133+ // The scan reads samples, and a still has none -- ever, unlike a video
134+ // clip whose sound may be one lane down or simply silent. Exactly what
135+ // `unscannable` says after the fact, said before the row is drawn so
136+ // there is no row left to click.
137+ ActionId::Silence if ctx.image => Enable::Hidden("this clip is a still"),
138+ // -- state: true of this clip now, and the next playhead click or the
139+ // next selection changes the answer. Splits this clip only from inside
140+ // it: at either edge there is nothing to split off -- and, on a speeded
141+ // clip, only at a frame its own rate can address, which is the same
142+ // question `splittable` asks.
143+ ActionId::Cut => match ctx.clip {
144+ Some((clip, _)) if !(clip.start < ctx.playhead && ctx.playhead < clip.end()) => {
145+ Enable::No("only from inside a clip")
146+ }
147+ // Inside it, and still not a cut: a slowed clip shows one frame of
148+ // the file for several frames of the timeline, and only the first of
149+ // those is a frame the file has ([`Speed::split_at`]). Cutting
150+ // between two showings of one frame would leave halves whose lengths
151+ // no longer add up, so it is refused -- and it says *that* rather
152+ // than repeating "inside a clip" at a playhead that plainly is.
153+ Some((clip, _))
154+ if clip
155+ .speed
156+ .split_at(clip.len(), ctx.playhead - clip.start)
157+ .is_none() =>
158+ {
159+ Enable::No("this speed holds one frame here — step to the next")
160+ }
161+ _ => Enable::Yes,
162+ },
163+ // Rejoins whatever meets at the playhead, so it can mean something only
164+ // at an edge of this clip. Whether those two halves were ever one take
165+ // is the engine's question, and it words that refusal itself.
166+ ActionId::Regroup => match ctx.clip {
167+ Some((clip, _)) if ctx.playhead != clip.start && ctx.playhead != clip.end() => {
168+ Enable::No("only where two clips meet")
169+ }
170+ _ => Enable::Yes,
171+ },
172+ // Nothing to take apart in a clip that names no group at all. Whether
173+ // the group it names still has another half is the engine's question,
174+ // like the regroup above.
175+ ActionId::Detach => match ctx.clip {
176+ Some((clip, _)) if clip.link.is_none() => Enable::No("this clip is not grouped"),
177+ _ => Enable::Yes,
178+ },
179+ // The three that act on the marked clip and on nothing else: with none
180+ // marked they would silently do nothing, which is what the Delete
181+ // button's own dimming has always said.
182+ ActionId::Copy | ActionId::Delete | ActionId::Lift if ctx.clip.is_none() => {
183+ Enable::No("click a clip first")
184+ }
185+ ActionId::Paste if !ctx.clipboard => Enable::No("nothing copied yet"),
186+ // Nothing to draw over the picture, so nothing to switch off: the
187+ // library says how subtitles arrive, and this row would flip a state
188+ // with no visible half either way.
189+ // ...and nothing to take off the timeline either, for the same reason:
190+ // the row would name a track that is not there.
191+ ActionId::ToggleSubtitles | ActionId::RemoveSubtitleTrack if !ctx.subtitles => {
192+ Enable::No("no subtitles yet")
193+ }
194+ // Not `No`: with nothing running there is no export for this to be
195+ // about at all, which is what keeps `esc` -- the same key -- a quiet
196+ // way out of a card rather than a line about exports.
197+ ActionId::CancelExport => Enable::Hidden("nothing is exporting"),
198+ // A clock started against an empty timeline is a clock counting
199+ // nothing: the transport says so by being dim, which is what its own
200+ // ad-hoc boolean used to say before the oracle knew the question.
201+ ActionId::Play if !ctx.playable => Enable::No("put a clip on a lane first"),
202+ // A rate applies to a clip of either kind and to its whole group, so
203+ // there is no lane it means nothing on, and the engine words the one
204+ // refusal there is (no room). Everything else is the editor's own and
205+ // needs nothing but a timeline.
206+ _ => Enable::Yes,
207+ }
208+}
209+
210+/// The rows a clip menu draws, for the clip it was opened on: the registry
211+/// filtered by the one availability oracle, and the *only* way that menu is
212+/// built. An action that means nothing for what was right-clicked -- a grade on
213+/// a waveform, an equalizer on a picture -- is not a row at all, so a future
214+/// action cannot appear where it does not apply by being added to
215+/// [`MENU_ITEMS`] alone.
216+pub(crate) fn menu_items(ctx: Ctx) -> Vec<ActionId> {
217+ MENU_ITEMS
218+ .into_iter()
219+ .filter(|&action| enable(action, ctx).listed())
220+ .collect()
221+}
222+
223+/// What a library row's items are asked *about*: the file that was
224+/// right-clicked and the little of the editor's state the answers need. The
225+/// library's [`Ctx`], handed in for the same reason.
226+#[derive(Clone, Copy, Default)]
227+pub(crate) struct RowCtx {
228+ /// A timeline to put it on.
229+ pub(crate) timeline: bool,
230+ pub(crate) exporting: bool,
231+ /// This row can join *this* timeline: what greys it in the list, and what
232+ /// the engine would otherwise refuse the Add with after the click.
233+ pub(crate) usable: bool,
234+ /// How many clips play this exact row -- a source with any is one the
235+ /// engine will not take out of the list.
236+ pub(crate) placed: usize,
237+}
238+
239+/// Whether a library row's item can be asked for. The library's half of
240+/// [`enable`], and the same rule: one table, no second policy in the render.
241+pub(crate) fn row_enable(item: RowItem, ctx: RowCtx) -> Enable {
242+ match item {
243+ // The two that change the timeline, so an export reading it stops them
244+ // both -- the key handler's rule, applied to a menu.
245+ RowItem::Add | RowItem::Remove if ctx.exporting => Enable::No("an export is running"),
246+ RowItem::Add | RowItem::Remove if !ctx.timeline => Enable::No("no timeline open"),
247+ // Dimmed and saying why rather than clicked and refused afterwards: the
248+ // row's own grey already says the file cannot join this timeline.
249+ RowItem::Add if !ctx.usable => Enable::No("it cannot join this one"),
250+ RowItem::Remove if ctx.placed > 0 => Enable::No("clips play it"),
251+ // Neither of these touches the timeline: a file can be found on disk and
252+ // described whatever the editor is doing, with no timeline at all.
253+ _ => Enable::Yes,
254+ }
255+}
256+
257+/// The rows a library menu draws, for the row it was opened on -- the clip
258+/// menu's [`menu_items`] on the other panel, and the only way that menu is
259+/// built.
260+pub(crate) fn row_items(ctx: RowCtx) -> Vec<RowItem> {
261+ ROW_ITEMS
262+ .into_iter()
263+ .filter(|&item| row_enable(item, ctx).listed())
264+ .collect()
265+}
266+
267+/// How tall a menu's list may draw: the whole of it where the window has room,
268+/// and what the window has where it has not -- only then does the list scroll.
269+/// A cap fixed at twelve rows put the last items behind a scroll on a window
270+/// with room to spare, which reads as a menu cut off by the bottom edge.
271+pub(crate) fn menu_rows_h(rows: usize, viewport: Size<Pixels>) -> f32 {
272+ let room = f32::from(viewport.height) - MENU_PAD * 2.;
273+ (rows as f32 * MENU_ROW_H).min(room.max(MENU_ROW_H))
274+}
275+
276+/// Where the menu actually hangs: at the pointer, pulled back inside the window
277+/// when it would not fit -- an item off the bottom edge is an item nobody can
278+/// click. Never negative, so a window smaller than the menu loses the bottom of
279+/// it rather than the top, where the items are.
280+pub(crate) fn menu_at(at: Point<Pixels>, viewport: Size<Pixels>, height: f32) -> (f32, f32) {
281+ let fit = |v: f32, size: f32, room: f32| v.min(room - size).max(0.);
282+ (
283+ fit(f32::from(at.x), MENU_W, f32::from(viewport.width)),
284+ fit(f32::from(at.y), height, f32::from(viewport.height)),
285+ )
286+}
287+
288+/// Whether the Add button does anything: a row picked, a timeline to put it on,
289+/// and no export reading that timeline. A button that would do nothing is dimmed
290+/// and takes no click, like every other one here.
291+pub(crate) fn can_add(picked: Option<&(PathBuf, usize)>, timeline: bool, exporting: bool) -> bool {
292+ picked.is_some() && timeline && !exporting
293+}
crates/app/src/subs.rsadded+589 -0
@@ -0,0 +1,589 @@
1+//! Subtitles: what is parsed, what is listed and what is drawn.
2+
3+use crate::*;
4+
5+/// Whether a dropped or named path is a subtitle file rather than media: the
6+/// formats `engine::subtitle` parses, lowercased, for [`engine::is_audio`]'s
7+/// reason -- the import door has to know which of the engine's two doors a file
8+/// goes through before anything is opened.
9+///
10+/// `.mks` is one of them, and it is the only Matroska extension that is: it is
11+/// the *subtitles alone*, so there is no source in it to import and a drop of
12+/// one used to be refused for having no video track -- while `+ S` on the same
13+/// bytes took it ([`PlaybackSession::parse_subtitles`] reads it as Matroska).
14+/// The other two are media and stay media: `.mka` is the sound alone, which
15+/// [`engine::is_audio`] already imports as a song, and `.mk3d` is a film. Both
16+/// may *carry* subtitles, which is [`carries_subtitles`] and not this.
17+pub(crate) fn is_subtitle(path: &std::path::Path) -> bool {
18+ path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
19+ matches!(
20+ e.to_ascii_lowercase().as_str(),
21+ "srt" | "vtt" | "webvtt" | "ass" | "ssa" | "mks"
22+ )
23+ })
24+}
25+
26+/// Whether a media path is a container that can carry subtitle tracks *inside*
27+/// it -- every Matroska extension and the three ISO-BMFF ones, which is the list
28+/// [`PlaybackSession::parse_subtitles`] walks (Matroska blocks and mp4 `tx3g`
29+/// alike). Named for what it gates and not for one of the two families, because
30+/// an mp4 answers `true` here now.
31+///
32+/// Matroska's set is the standard's own and closed by it
33+/// (`engine::demux::is_matroska`), so it is copied whole rather than trimmed to
34+/// the two that carry a film: a `.mk3d` opened as media has its tracks walked
35+/// like the `.mkv` it is, and a `.mka` song can hold a lyric track. A suffix
36+/// wider than the engine's would be a file taken here and refused deeper down.
37+pub(crate) fn carries_subtitles(path: &std::path::Path) -> bool {
38+ path.extension().and_then(|e| e.to_str()).is_some_and(|e| {
39+ matches!(
40+ e.to_ascii_lowercase().as_str(),
41+ "mkv" | "mka" | "mks" | "mk3d" | "webm" | "mp4" | "m4v" | "mov"
42+ )
43+ })
44+}
45+
46+/// What a worker hands back, which is the fork [`arrival`] made when it was
47+/// started. An import is *read* and thrown away; the file argv named is opened
48+/// outright, because nothing else is going to open it afterwards.
49+pub(crate) enum Landed {
50+ /// An import into a timeline that is up: the container probed and the
51+ /// subtitle tracks walked, both *kept* -- they are the expensive halves and
52+ /// the worker is where they belong, so [`Player::take_import`] is left with
53+ /// two pushes ([`engine::PlaybackSession::import_probed`],
54+ /// [`subtitle_tail`]).
55+ Read(Subs, Probe),
56+ /// A whole timeline the worker opened, with the tail its subtitle tracks
57+ /// earn, ready to be hung off the window -- or the engine's refusal. `true`
58+ /// is the media argv named, which *becomes* the timeline; `false` is a file
59+ /// arriving at a window that had none, which fills the library and leaves
60+ /// the lanes empty for a drag ([`Player::install_media`]).
61+ Media(Result<(PlaybackSession, String), String>, bool),
62+ /// A `.edith`, restored: argv's, and the one a drop or the Import button
63+ /// brought ([`arrival`]).
64+ Project(Result<PlaybackSession, String>),
65+}
66+
67+/// What the container walk found, for [`Player::take_import`] to register, or
68+/// the engine's refusal in the words it would have used on the UI thread.
69+///
70+/// `None` for the doors that never reach a demuxer: a song, a still and a
71+/// subtitle file, whose own small reads stay where they were
72+/// ([`engine::PlaybackSession::import`]).
73+pub(crate) type Probe = Option<engine::Result<engine::ImportProbe>>;
74+
75+/// A media file opened as a session, with the subtitle tracks it carries inside
76+/// it taken in the same breath -- the two reads a file costs, in the one place
77+/// both doors ([`Player::open_media`] and the worker below) go through.
78+///
79+/// `place` is which door: a file *opened* is the timeline, one *imported* into
80+/// an empty window fills the library and leaves the lanes empty for a drag.
81+pub(crate) fn open_session(
82+ path: &std::path::Path,
83+ place: bool,
84+ subs: Subs,
85+) -> Result<(PlaybackSession, String), String> {
86+ let opened = match place {
87+ true => PlaybackSession::open(path),
88+ false => PlaybackSession::open_library(path),
89+ };
90+ let mut session = opened.map_err(|e| e.to_string())?;
91+ let tail = subtitle_tail(&mut session, subs).unwrap_or_default();
92+ Ok((session, tail))
93+}
94+
95+/// The whole of what a queued file costs, off the UI thread. An import only
96+/// needs its pages warmed ([`read_ahead`]); the file argv named is *opened*
97+/// here instead, and that is the difference between a warm launch paying for
98+/// one header walk and paying for two -- the window is up either way.
99+pub(crate) fn open_ahead(
100+ what: Landing,
101+ path: &std::path::Path,
102+ stage: &std::sync::atomic::AtomicU8,
103+ gate: Option<engine::ImportGate>,
104+) -> Landed {
105+ match what {
106+ Landing::Import => read_ahead(path, stage, gate),
107+ Landing::Project => {
108+ let opened = PlaybackSession::open_project(path).map_err(|e| e.to_string());
109+ Landed::Project(opened)
110+ }
111+ Landing::Open => open_whole(path, true, stage),
112+ }
113+}
114+
115+/// A whole timeline, opened here and handed over: the file argv named (`place`,
116+/// which *is* the timeline) and a file arriving at a window with no timeline to
117+/// import into, which fills the library instead. One function because they are
118+/// one read -- the engine's two doors differ by which lanes come up empty
119+/// ([`engine::PlaybackSession::open_library`]), not by what they walk.
120+pub(crate) fn open_whole(path: &std::path::Path, place: bool, stage: &std::sync::atomic::AtomicU8) -> Landed {
121+ use std::sync::atomic::Ordering::Relaxed;
122+ let opened = match place {
123+ true => PlaybackSession::open(path),
124+ false => PlaybackSession::open_library(path),
125+ };
126+ // The same two stages a read reports, because they are the same two
127+ // reads: the container, and then the tracks inside it.
128+ stage.store(ImportStage::Subtitles as u8, Relaxed);
129+ Landed::Media(
130+ opened.map_err(|e| e.to_string()).map(|mut session| {
131+ let subs = subtitle_notice(&mut session, path).unwrap_or_default();
132+ (session, subs)
133+ }),
134+ place,
135+ )
136+}
137+
138+/// Reads, off the UI thread, everything the import that follows would have read
139+/// -- and hands all of it over. Nothing here is a warm-up any more: the
140+/// container is *probed* ([`engine::PlaybackSession::probe_import`]) and the
141+/// subtitle tracks are *walked*, and [`Player::take_import`] registers what came
142+/// back. Measured on the 24 GB 4K HEVC remux: 21.4 s of header cold, 429 ms
143+/// warm, plus 1-4 s of probing the timeline's own first source, plus the cue
144+/// walk -- all of it here, and the window keeps painting through it.
145+///
146+/// `gate` is the timeline the file is checked against
147+/// ([`engine::PlaybackSession::import_gate`]), taken before the worker started
148+/// because a worker cannot reach the session. `None` is a window with no
149+/// timeline to import into: then there is nothing to check against and nothing
150+/// to register, so the file is *opened* here instead, whole
151+/// ([`open_whole`]) -- which is the same twenty seconds, on the same thread,
152+/// rather than on the one that draws.
153+///
154+/// The header error is carried back now rather than dropped: it is the engine's
155+/// own refusal, from the only walk anybody makes, so it is worded once and shown
156+/// at the landing. The subtitle refusal travels beside it for the same reason.
157+///
158+/// `stage` is what the line above the panel is naming while this runs.
159+pub(crate) fn read_ahead(
160+ path: &std::path::Path,
161+ stage: &std::sync::atomic::AtomicU8,
162+ gate: Option<engine::ImportGate>,
163+) -> Landed {
164+ use std::sync::atomic::Ordering::Relaxed;
165+ stage.store(ImportStage::Header as u8, Relaxed);
166+ // Nothing to import into, and nothing a subtitle file needs opened: the
167+ // first opens the library itself, here; the second has no container at all.
168+ let Some(gate) = gate else {
169+ return match is_subtitle(path) {
170+ true => Landed::Read(walk_subtitles(path), None),
171+ false => open_whole(path, false, stage),
172+ };
173+ };
174+ // The three doors an import goes through: a song is measured by its
175+ // duration and a still by its header -- both the engine's own reads, warmed
176+ // here and paid again at the landing, which is a header apiece -- and
177+ // everything else is the container walk, which is handed over whole.
178+ let probe = if engine::is_audio(path) {
179+ engine::AudioSession::duration_secs(path).ok();
180+ None
181+ } else if engine::is_image(path) || is_subtitle(path) {
182+ None
183+ } else {
184+ Some(PlaybackSession::probe_import(gate, path))
185+ };
186+ stage.store(ImportStage::Subtitles as u8, Relaxed);
187+ // ...and the tracks inside it, kept.
188+ Landed::Read(walk_subtitles(path), probe)
189+}
190+
191+/// Every subtitle track a file carries, cues and all -- the walk that costs, in
192+/// the one place every door that pays it goes through. `Ok` and empty for a file
193+/// with none to read, which is what a file that is neither a container we can
194+/// walk ([`carries_subtitles`]) nor a subtitle file is: the same answer
195+/// `add_subtitle_tracks` gives it, and nothing is opened to find that out.
196+///
197+/// Nothing in here is a session, on purpose ([`PlaybackSession::parse_subtitles`]
198+/// is an associated fn): no borrow crosses the await, so this runs whole on a
199+/// worker while the window keeps painting.
200+pub(crate) fn walk_subtitles(path: &std::path::Path) -> Subs {
201+ match carries_subtitles(path) || is_subtitle(path) {
202+ true => PlaybackSession::parse_subtitles(path),
203+ false => Ok(Vec::new()),
204+ }
205+}
206+
207+/// The subtitle tracks a media file carries, taken into the session as it is
208+/// opened, and the tail the notice grows for them: an mkv or an mp4 with
209+/// subtitles in it arrives with its subtitles, because a track nobody imported
210+/// is a track nobody knows is there. Every other container answers `None`
211+/// without being read.
212+///
213+/// A refusal is a tail too, never a failure of the open: the picture and the
214+/// sound of a film whose subtitle tracks cannot be walked are still the film.
215+///
216+/// Both halves at once, which only a *worker* may do: the walk reads the whole
217+/// file for its cues (`engine::subtitle::of_matroska`) -- ~200 ms on a two-hour
218+/// 4K remux, 9.7 s on a cold 25 GB one. The one caller is the open beside which
219+/// this runs on the worker ([`open_ahead`]), never the render thread; an
220+/// import splits the two halves across the hop instead ([`read_ahead`] walks,
221+/// [`subtitle_tail`] pushes).
222+pub(crate) fn subtitle_notice(session: &mut PlaybackSession, path: &std::path::Path) -> Option<String> {
223+ subtitle_tail(session, walk_subtitles(path))
224+}
225+
226+/// What a subtitle walk ([`walk_subtitles`]) gave, on its way from whichever
227+/// thread paid for it to the timeline. `Send` all the way down (`sendable()`,
228+/// `engine/tests/subtitles.rs`), which is what lets the walk be a worker's.
229+pub(crate) type Subs = engine::Result<Vec<engine::subtitle::SubtitleTrack>>;
230+
231+/// The tail a file's own subtitle tracks earn on the notice that names it, and
232+/// the push that puts them on the timeline -- the second half of the walk, the
233+/// cheap one ([`PlaybackSession::add_subtitle_tracks`]: no open, no seek, no
234+/// decode). Every door that arrives with a *file* words it here, once: the file
235+/// argv named, an import, and an import into an empty window cannot say the same
236+/// thing differently, whichever thread read the cues.
237+///
238+/// `None` for a file that gave none and for one whose tracks are on the timeline
239+/// already -- an import that adds nothing says nothing about subtitles. A
240+/// refusal is a tail too, never a failure of the import: the picture and the
241+/// sound of a film whose subtitle tracks cannot be walked are still the film.
242+pub(crate) fn subtitle_tail(session: &mut PlaybackSession, subs: Subs) -> Option<String> {
243+ match subs {
244+ Ok(tracks) => match session.add_subtitle_tracks(tracks) {
245+ 0 => None,
246+ n => Some(format!(" — {n} subtitle track(s) in the file")),
247+ },
248+ Err(e) => Some(format!(" — SUBTITLES UNREAD: {e}")),
249+ }
250+}
251+
252+/// The push both deliberate add-subtitles doors end on -- `+ S` and its key
253+/// ([`Player::add_subtitles`]) and a dropped or argv'd subtitle file
254+/// ([`Player::take_subtitles`]) -- so the two cannot come to word the same file
255+/// differently.
256+///
257+/// The walk having found *nothing* is a refusal and not a count: a container
258+/// with no subtitle track in it and a file whose tracks are all on the timeline
259+/// already both push zero rows, and they are opposite answers -- one says look
260+/// somewhere else, the other says you already have them. The engine's own door
261+/// draws the same line in the same words
262+/// ([`PlaybackSession::no_subtitles_in`], asked here because this route splits
263+/// the walk from the push to keep the walk off the render thread).
264+///
265+/// The file itself joins nothing either way: no library row, no lane, no clip.
266+/// Subtitles are a list the timeline carries, and this is the only thing that
267+/// touches it.
268+pub(crate) fn pushed(
269+ session: &mut PlaybackSession,
270+ path: &std::path::Path,
271+ tracks: Vec<engine::subtitle::SubtitleTrack>,
272+) -> engine::Result<usize> {
273+ match tracks.is_empty() {
274+ true => Err(PlaybackSession::no_subtitles_in(path)),
275+ false => Ok(session.add_subtitle_tracks(tracks)),
276+ }
277+}
278+
279+/// What a subtitle row says under its name: how many cues it holds and whether
280+/// they are pictures ([`engine::subtitle::SubtitleTrack::is_bitmap`]) -- which
281+/// is the difference between a track an export writes into the file and one it
282+/// can only draw -- or, for a track that could not be read, the engine's own
283+/// reason verbatim. A refusal is still what a row can be *for*: a VobSub track
284+/// dropped from the list would say the film has no subtitles at all.
285+pub(crate) fn subtitle_detail(track: &engine::subtitle::SubtitleTrack) -> String {
286+ match (&track.refused, track.is_bitmap()) {
287+ (Some(why), _) => why.clone(),
288+ (None, true) => format!("{} cues — pictures", track.cues.len()),
289+ (None, false) => format!("{} cues", track.cues.len()),
290+ }
291+}
292+
293+/// What the export card's Subtitles row says: the engine's own words for the
294+/// tracks an export carries (`plan`, [`engine::export::planned_subtitles`] asked
295+/// about `picks`) and, beside them, the rows it is carrying nothing of.
296+///
297+/// `picks` is [`Player::export_subs`] -- every track with a cue left in the
298+/// exported range -- so a track sitting in the list with eighty-three cues
299+/// nowhere near a trimmed timeline never reaches the engine at all, and the card
300+/// said nothing about it while the list went on showing it. Which tracks have
301+/// cues *here* is this side's answer and nobody else's, so this side words it.
302+///
303+/// Past [`SUB_PLAN_CHARS`] the line counts rather than names: every name is more
304+/// words in a value box `MENU_W` wide, and at 35 tracks the row wrapped to ten
305+/// lines and pushed the Destination row under the fold of the card. The names
306+/// are still one row each in the Subtitles list, with the cue count and the
307+/// reason under them ([`subtitle_detail`]) -- more than this line ever said.
308+///
309+/// The counted split follows the engine's own order of reasons (`refused`, then
310+/// pictures, then no cues), with the last asked of the timeline instead of the
311+/// track.
312+///
313+/// corner-cut: that split reads the same public fields the list rows read
314+/// (`refused`, [`engine::subtitle::SubtitleTrack::is_bitmap`]) rather than the
315+/// engine's decision, so a *new* reason to drop a track would be counted here as
316+/// embedded until this follows it -- the named line, which is the engine's
317+/// string verbatim, would say it correctly meanwhile. Upgrade path: reasons out
318+/// of `planned_subtitles` as data rather than as one sentence, which is an
319+/// engine change.
320+pub(crate) fn subtitle_plan(
321+ plan: String,
322+ tracks: &[engine::subtitle::SubtitleTrack],
323+ picks: &[usize],
324+) -> String {
325+ let mut parts: Vec<String> = Vec::new();
326+ // "none" is the engine's word for an empty pick list and would read as a
327+ // verdict on the tracks named after it.
328+ if !picks.is_empty() {
329+ parts.push(plan);
330+ }
331+ parts.extend(
332+ tracks
333+ .iter()
334+ .enumerate()
335+ .filter(|(i, _)| !picks.contains(i))
336+ .map(|(_, track)| format!("{} — no cues here", track.label)),
337+ );
338+ let named = parts.join("; ");
339+ if named.chars().count() <= SUB_PLAN_CHARS {
340+ return match named.is_empty() {
341+ true => "none".to_string(),
342+ false => named,
343+ };
344+ }
345+ let (mut embedded, mut unread, mut pictures, mut off) = (0, 0, 0, 0);
346+ for (i, track) in tracks.iter().enumerate() {
347+ match (
348+ track.refused.is_some(),
349+ track.is_bitmap(),
350+ picks.contains(&i),
351+ ) {
352+ (true, _, _) => unread += 1,
353+ (_, true, _) => pictures += 1,
354+ (_, _, false) => off += 1,
355+ _ => embedded += 1,
356+ }
357+ }
358+ let mut counted = vec![format!("{embedded} of {} → embedded", tracks.len())];
359+ counted.extend(
360+ [
361+ (pictures, "pictures"),
362+ (unread, "unread"),
363+ (off, "no cues here"),
364+ ]
365+ .into_iter()
366+ .filter(|(n, _)| *n > 0)
367+ .map(|(n, why)| format!("{n} {why}")),
368+ );
369+ counted.join("; ")
370+}
371+
372+/// Every subtitle track one file gave, kept together. Plain data, planned
373+/// before anything is drawn -- the grouping is the branchy part and it is the
374+/// same answer whatever a styling puts around it.
375+///
376+/// [`Player::subtitle_section`] draws one block per group of these, and
377+/// [`sub_pick_name`] names the pick out of the same answer -- so what a heading
378+/// says and what a row a person clicked says cannot disagree.
379+#[derive(Debug, PartialEq)]
380+pub(crate) struct SubGroup {
381+ /// What the group is called: the file without its extension, which is what
382+ /// a person named the film even when the subtitles came out of a remux.
383+ pub(crate) name: String,
384+ /// What the swatch is asked by ([`file_tint`]) -- the file, so a subtitle
385+ /// row and the media rows of the same file wear one colour. `None` from
386+ /// that lookup for a standalone `.srt`, which is nobody's stream.
387+ pub(crate) path: PathBuf,
388+ pub(crate) rows: Vec<SubRow>,
389+}
390+
391+/// One subtitle track, as a row shows it.
392+#[derive(Debug, PartialEq)]
393+pub(crate) struct SubRow {
394+ /// Which track of the session's list this row is: the *flat* index into the
395+ /// add-order Vec `PlaybackSession::subtitles` hands back, which is what a
396+ /// click sets `sub_track` to and what a save writes into the `.edith`.
397+ /// Grouping moves rows around on screen and never touches this number.
398+ pub(crate) track: usize,
399+ /// Which of *this file's* tracks it is, counted from 1 -- the numbering
400+ /// [`row_name`] gives audio streams, for the same reason: two tracks off one
401+ /// remux that both say "eng" are told apart by nothing else.
402+ pub(crate) number: usize,
403+ pub(crate) label: String,
404+ /// The row's second line ([`subtitle_detail`]).
405+ pub(crate) detail: String,
406+ /// Why it cannot be shown, for a track that cannot: the only thing that
407+ /// greys a row out. Listed all the same -- a picker that hides them is a
408+ /// picker that lies.
409+ pub(crate) refused: Option<String>,
410+ /// Pictures rather than lines ([`engine::subtitle::SubtitleTrack::bitmap`]).
411+ pub(crate) bitmap: bool,
412+}
413+
414+/// What a subtitle row is called, off the two fields the container really
415+/// stated rather than out of the flattened
416+/// [`label`](engine::subtitle::SubtitleTrack::label). The pair is what an export
417+/// writes (`TRACK_LANGUAGE` and `TRACK_NAME` are two fields), and reading the
418+/// display string back apart is the very heuristic that sent every French track
419+/// out as English: `lang_human` on a whole "und — Signs" matches nothing and
420+/// names a language nobody speaks.
421+///
422+/// The three shapes a track arrives in, all three of them real: a standalone
423+/// file states no language and is its own name, an embedded one states a
424+/// language and sometimes a title beside it, and a refused one states neither
425+/// and keeps the label it was refused under (`SubtitleTrack::refused`).
426+pub(crate) fn sub_title(sub: &engine::subtitle::SubtitleTrack) -> String {
427+ match (sub.language.as_str(), sub.name.as_str()) {
428+ ("", "") => sub.label.clone(),
429+ ("", name) => name.to_string(),
430+ // A track whose only name is the tag for "nobody said" says that in
431+ // words rather than showing the tag itself.
432+ (lang, "") => lang_human(lang).to_string(),
433+ // ...and one that says "nobody said" *and* gives a title is the title:
434+ // "unknown language — Signs" pads it with a word the file never said.
435+ ("und", name) => name.to_string(),
436+ (lang, name) => format!("{lang} — {name}"),
437+ }
438+}
439+
440+/// The subtitle list as rows under the file each came out of: one group per
441+/// distinct path, in the order the files first appear, and each file's tracks
442+/// in the order they were added. Two remuxes' tracks arriving interleaved --
443+/// which is what importing a second film does -- still read as two films.
444+pub(crate) fn subtitle_rows(tracks: &[engine::subtitle::SubtitleTrack]) -> Vec<SubGroup> {
445+ let mut groups: Vec<SubGroup> = Vec::new();
446+ for (track, sub) in tracks.iter().enumerate() {
447+ let group = match groups.iter().position(|g| g.path == sub.path) {
448+ Some(i) => &mut groups[i],
449+ None => {
450+ groups.push(SubGroup {
451+ name: sub
452+ .path
453+ .file_stem()
454+ .map_or_else(|| file_name(&sub.path), |s| s.to_string_lossy().into()),
455+ path: sub.path.clone(),
456+ rows: Vec::new(),
457+ });
458+ groups.last_mut().expect("just pushed")
459+ }
460+ };
461+ group.rows.push(SubRow {
462+ track,
463+ number: group.rows.len() + 1,
464+ label: sub_title(sub),
465+ detail: subtitle_detail(sub),
466+ refused: sub.refused.clone(),
467+ bitmap: sub.is_bitmap(),
468+ });
469+ }
470+ groups
471+}
472+
473+/// How the picked track is named wherever the pick is echoed -- the strip
474+/// header, the section heading, the toggle's own notice. What the track is
475+/// *and* which file it came out of: two remuxes each carrying an "eng" track
476+/// give the same word twice, and the file is the only thing that tells them
477+/// apart. A file that gave several of them numbers them within itself, the way
478+/// [`row_name`] numbers audio streams, since "eng" twice off one remux is the
479+/// same problem one file down.
480+///
481+/// Goes through [`subtitle_rows`], so the name a header says and the row a
482+/// person clicked cannot disagree -- and the label is humanised there, so an
483+/// "und" track is named in words here without being passed through
484+/// [`lang_human`] twice.
485+///
486+/// `None` for an index no track answers to, which is the silence
487+/// [`Player::subtitle_track`] gives at the same moment.
488+/// Where the picked subtitle row lands once `removed` has been taken off a list
489+/// that is `left` long afterwards. The pick follows the list: the same *track*
490+/// while it is still there -- every index past the one that went moves down
491+/// ([`engine::Project::remove_subtitles`]) -- the row that slid into the empty
492+/// place when the picked one is what went, and the last row when that was the
493+/// last. Zero on an emptied list, which is the index the section is not drawn at
494+/// all.
495+///
496+/// Its own function because the pick is what the overlay draws: left where it
497+/// was it would name a different track, and the plate over the picture would
498+/// change language on its own the moment a row above it went. What an export
499+/// writes is *not* this pick and cannot be desynced by a removal -- it is worked
500+/// out from the cues on the timeline each time ([`Player::export_subs`]).
501+pub(crate) fn sub_pick_after_removal(picked: usize, removed: usize, left: usize) -> usize {
502+ let picked = match removed < picked {
503+ true => picked - 1,
504+ false => picked,
505+ };
506+ picked.min(left.saturating_sub(1))
507+}
508+
509+pub(crate) fn sub_pick_name(tracks: &[engine::subtitle::SubtitleTrack], track: usize) -> Option<String> {
510+ subtitle_rows(tracks).into_iter().find_map(|group| {
511+ let row = group.rows.iter().find(|row| row.track == track)?;
512+ let track = match group.rows.len() > 1 {
513+ false => row.label.clone(),
514+ true => format!("{} {}", row.label, row.number),
515+ };
516+ // A standalone `.srt` is already named after its own file: "sub.srt —
517+ // sub" says the one thing twice, and the film is only worth naming
518+ // where it is not in the label yet.
519+ Some(match row.label.starts_with(&group.name) {
520+ true => track,
521+ false => format!("{track} — {}", group.name),
522+ })
523+ })
524+}
525+
526+/// Where a cue is drawn on the bed: left edge and width in pixels, through the
527+/// same [`Scale`] every clip box goes through -- so a cue and the take it is
528+/// spoken over line up at every zoom, which is the only reason the strip is
529+/// worth drawing. Microseconds are the cue's unit and seconds are the scale's,
530+/// and this is the one place they meet.
531+///
532+/// Never narrower than [`SUB_CUE_MIN_W`]: zoomed out, a one-second cue is a
533+/// fraction of a pixel, and a mark that rounds away reads as a track with
534+/// nothing in it.
535+pub(crate) fn cue_box(scale: Scale, cue: &engine::subtitle::Cue) -> (f32, f32) {
536+ let (start, end) = (cue.start_us as f64 / 1e6, cue.end_us as f64 / 1e6);
537+ (
538+ scale.px_at(start),
539+ scale.width_px(end - start).max(SUB_CUE_MIN_W),
540+ )
541+}
542+
543+/// Which cues of a track are on screen at `at` seconds. Half-open, as the cue
544+/// itself is: one that ends exactly where the next begins hands over rather than
545+/// overlapping it for a frame, and several that genuinely overlap all come back
546+/// -- a sign and a line of dialogue are two cues at one moment.
547+pub(crate) fn cues_at(cues: &[engine::subtitle::Cue], at: f64) -> Vec<&engine::subtitle::Cue> {
548+ let us = (at * 1e6) as i64;
549+ cues.iter()
550+ .filter(|cue| cue.start_us <= us && us < cue.end_us)
551+ .collect()
552+}
553+
554+/// The sources a repaint has not asked about yet. A key that is already there
555+/// means "asked", whatever state it is in, which is what stops a decode already
556+/// running from being started again by the next of sixty repaints a second.
557+pub(crate) fn unseen_sources(
558+ sources: &[Source],
559+ waves: &HashMap<(PathBuf, usize), Wave>,
560+) -> Vec<(PathBuf, usize)> {
561+ sources
562+ .iter()
563+ .map(|s| (s.path.clone(), s.audio_stream))
564+ .filter(|key| !waves.contains_key(key))
565+ .collect()
566+}
567+
568+/// The same, for the per-file caches: one entry per *file*, however many of its
569+/// streams the timeline plays. Generic in the value, because the stream probe
570+/// and the still's own size are both asked once per file and answered by
571+/// presence in a map.
572+pub(crate) fn unseen_paths<V>(sources: &[Source], seen: &HashMap<PathBuf, V>) -> Vec<PathBuf> {
573+ let mut out: Vec<PathBuf> = Vec::new();
574+ for s in sources {
575+ if !seen.contains_key(&s.path) && !out.contains(&s.path) {
576+ out.push(s.path.clone());
577+ }
578+ }
579+ out
580+}
581+
582+/// Which timeline frame the playhead is on, by the rule the engine's own edits
583+/// use (playback.rs `secs_to_frame`): the frame that has started, with the
584+/// epsilon that keeps a clock sitting exactly on a boundary from reading as the
585+/// frame before it. Only ever a hint here -- what an edit does is still the
586+/// engine's answer, taken from the same seconds.
587+pub(crate) fn frame_at(secs: f64, fps: f64) -> u32 {
588+ (secs * fps + 1e-6).floor().max(0.) as u32
589+}
crates/app/src/timeline_math.rsadded+388 -0
@@ -0,0 +1,388 @@
1+//! The timeline's arithmetic: takes, trims, snapping and envelopes.
2+
3+use crate::*;
4+
5+/// Whether this clip is a whole take, i.e. whether deleting it may close the
6+/// hole under it: a take is what the first pair of lanes carries between them,
7+/// `V1`'s picture and the sound grouped with it, and dropping one moves the
8+/// frames after it on every lane.
9+///
10+/// Everything else is a half or a layer, and is *lifted* instead: a half whose
11+/// picture was lifted (what a lift leaves behind) has no take to ripple, and a
12+/// clip on a further lane is laid over the timeline rather than part of it --
13+/// closing a hole under it would drag the take beneath out of step with it.
14+pub(crate) fn whole_take(session: &PlaybackSession, lane: Lane, idx: usize) -> bool {
15+ let Some(clip) = session.lane_clips(lane).get(idx) else {
16+ return false;
17+ };
18+ let paired = || {
19+ session
20+ .lanes()
21+ .into_iter()
22+ .filter(|&other| other != lane)
23+ .flat_map(|other| session.lane_clips(other))
24+ .any(|o| o.link.is_some() && o.link == clip.link)
25+ };
26+ match (lane.kind, lane.ord) {
27+ (_, 1..) => false,
28+ // The picture of a take -- unless the take has been taken apart: a
29+ // detached picture (a group id no other lane carries, which is also what
30+ // a lift of the sound leaves) is a half like the sound is, and a ripple
31+ // under it would drag away the very half it was detached from. A clip in
32+ // no group at all is not a half but a placement, and on `V1` a placement
33+ // is the take there is.
34+ (LaneKind::Video, _) => clip.link.is_none() || paired(),
35+ // The sound of a take, only while the take is still there: its group is
36+ // carried by a clip on some other lane.
37+ (LaneKind::Audio, _) => paired(),
38+ }
39+}
40+
41+/// The clip a Group would pair this one with: the first clip on another track,
42+/// in the order the lanes are drawn, covering exactly the same frames and not in
43+/// this clip's group already. Exactly the same frames because that is all a
44+/// group id can mean (engine `links_are_consistent`), which is what leaves
45+/// nothing for a second click to choose. `None` when no track has one, and the
46+/// notice says so.
47+pub(crate) fn span_partner(session: &PlaybackSession, lane: Lane, idx: usize) -> Option<(Lane, usize)> {
48+ let clip = *session.lane_clips(lane).get(idx)?;
49+ let matches = |other: Lane| {
50+ let i = session.lane_clips(other).iter().position(|c| {
51+ (c.start, c.end()) == (clip.start, clip.end())
52+ && !(c.link.is_some() && c.link == clip.link)
53+ })?;
54+ Some((other, i))
55+ };
56+ // Sound before picture (and picture before sound): "group this" means the
57+ // other half of the take, and a project whose audio lane was added after a
58+ // second video one has that half *after* the layer in storage order -- which
59+ // is the order the lanes come in. A same-kind lane is still groupable (V1
60+ // and V2 may be one take), but only where no opposite one covers the span.
61+ let (opposite, same): (Vec<Lane>, Vec<Lane>) = session
62+ .lanes()
63+ .into_iter()
64+ .filter(|&other| other != lane)
65+ .partition(|other| other.kind != lane.kind);
66+ opposite.into_iter().chain(same).find_map(matches)
67+}
68+
69+/// Whether a click marks this clip: the clip that was clicked always, and the
70+/// other lane's clip of the same group with it. A clip whose group has no other
71+/// half -- what a lift leaves behind -- marks only itself, which is what makes a
72+/// detached half separately deletable.
73+pub(crate) fn marked(
74+ here: (Lane, usize),
75+ link: Option<u32>,
76+ sel: Option<(Lane, usize)>,
77+ sel_link: Option<u32>,
78+) -> bool {
79+ sel == Some(here) || (link.is_some() && link == sel_link)
80+}
81+
82+/// Whether a clip is wide enough to be worth naming.
83+pub(crate) fn show_label(w: f32) -> bool {
84+ w >= LABEL_MIN_W
85+}
86+
87+/// The clip a trim is *showing*, worked out the way `Project::trim` will write
88+/// it: the timeline room the edge leaves is turned into source frames by the one
89+/// conversion that exists for it ([`Speed::fit`]), and the box is drawn from
90+/// that. The preview and the commit are then the same arithmetic -- a box let go
91+/// of stays where the hand left it at every rate. Assigning the timeline count
92+/// straight to the source field, as this used to, drew a speeded clip's tail
93+/// moving at the wrong rate (it snapped on release) and drew a *head* trim
94+/// moving the clip's other edge, since the length it implied was not the length
95+/// the release would commit.
96+///
97+/// A still grows forward from source frame 0 instead: every frame of it is the
98+/// same picture, so there is no earlier one for an in-point to walk back to.
99+///
100+/// Room too narrow to hold one source frame is the edit the engine refuses, and
101+/// the box is drawn unchanged rather than as something that will not be
102+/// committed.
103+pub(crate) fn trimmed_clip(clip: Clip, edge: Edge, to: u32, still: bool) -> Clip {
104+ // An edge that has not moved is not an edit, and `Project::trim` refuses it
105+ // as one: the press that starts a drag must draw the clip it pressed, not a
106+ // clip a rounding narrower.
107+ if to
108+ == match edge {
109+ Edge::Start => clip.start,
110+ Edge::End => clip.end(),
111+ }
112+ {
113+ return clip;
114+ }
115+ match edge {
116+ Edge::Start => {
117+ // What survives is measured from the *end* -- the frames that stay
118+ // play what they always played, which is what makes this a trim.
119+ let Some(keep) = clip.speed.fit(clip.end().saturating_sub(to)) else {
120+ return clip;
121+ };
122+ match still {
123+ true => Clip {
124+ in_frame: 0,
125+ out_frame: keep,
126+ start: to,
127+ ..clip
128+ },
129+ false => Clip {
130+ in_frame: clip.out_frame - keep.min(clip.out_frame),
131+ start: to,
132+ ..clip
133+ },
134+ }
135+ }
136+ Edge::End => match clip.speed.fit(to.saturating_sub(clip.start)) {
137+ Some(keep) => Clip {
138+ out_frame: clip.in_frame + keep,
139+ ..clip
140+ },
141+ None => clip,
142+ },
143+ }
144+}
145+
146+/// Which index on its own lane a dragged clip is at *now*: the one it was picked
147+/// up at while nothing has moved, and wherever the clip itself has slid to when
148+/// an edit during the drag rippled the lane's indices -- a delete, an undo or a
149+/// paste from a stroke, none of which gpui's frozen drag payload hears about.
150+/// `None` when the clip is gone altogether, and then the drop is not an edit at
151+/// all: moving whatever slid into its place is the one thing the hand did not
152+/// ask for. A lane's clips are disjoint and sorted, so at most one of them can
153+/// be the clip that was picked up.
154+pub(crate) fn live_idx(clips: &[Clip], idx: usize, clip: Clip) -> Option<usize> {
155+ match clips.get(idx) {
156+ Some(&at) if at == clip => Some(idx),
157+ _ => clips.iter().position(|&c| c == clip),
158+ }
159+}
160+
161+/// The part of a clip's box that is on the bed, in the box's own pixels:
162+/// `(left, width)` of its intersection with the visible strip. Everything drawn
163+/// *inside* a box -- its waveform, its name, its speed badge -- is placed in
164+/// here rather than at the box's own edges, which at a deep zoom sit thousands
165+/// of pixels off either side of the screen: a label out there is a label nobody
166+/// can read, and a waveform out there is a path with a point per two pixels of a
167+/// width nobody can see. A bed that has not been measured yet answers with the
168+/// whole box, which is what was drawn before there was a bed to clip to.
169+pub(crate) fn visible_slice(left: f32, width: f32, bed: f32) -> (f32, f32) {
170+ if bed <= 0. {
171+ return (0., width);
172+ }
173+ let from = (-left).clamp(0., width);
174+ let to = (bed - left).clamp(from, width);
175+ (from, to - from)
176+}
177+
178+/// Scales an envelope to its own loudest sample, so a quietly mastered source
179+/// still draws as a shape. The fixtures peak around an eighth of full scale, and
180+/// an eighth of a 30 px lane is a flat line -- which says "silent" about a file
181+/// that is not.
182+pub(crate) fn normalise(mut peaks: Vec<(f32, f32)>) -> Vec<(f32, f32)> {
183+ let loudest = peaks.iter().fold(0f32, |m, &(lo, hi)| m.max(-lo).max(hi));
184+ if loudest > 0. {
185+ for (lo, hi) in &mut peaks {
186+ *lo /= loudest;
187+ *hi /= loudest;
188+ }
189+ }
190+ peaks
191+}
192+
193+/// The min/max envelope of `peaks` over the source seconds `from..to`, as
194+/// `(x, top, bottom)` columns of a `w` x `h` box. Every point is inside that box
195+/// -- a clip's waveform cannot paint over its neighbour -- and every column is
196+/// at least a pixel tall, so silence reads as a line through the middle rather
197+/// than as a polygon with no area.
198+pub(crate) fn envelope(peaks: &[(f32, f32)], from: f64, to: f64, w: f32, h: f32) -> Vec<(f32, f32, f32)> {
199+ if peaks.is_empty() || w <= 0. || h <= 0. {
200+ return Vec::new();
201+ }
202+ let cols = ((w / WAVE_COL).ceil().max(1.) as usize).min(WAVE_COLS_MAX);
203+ let mid = h / 2.;
204+ (0..=cols)
205+ .map(|col| {
206+ let along = col as f64 / cols as f64;
207+ let at = from + (to - from) * along;
208+ // Casting a float to an integer saturates in Rust, so a source
209+ // second past the end of the peaks clamps rather than wrapping.
210+ let bucket = ((at * f64::from(WAVE_BPS)) as usize).min(peaks.len() - 1);
211+ let (lo, hi) = peaks[bucket];
212+ let top = (mid - hi.clamp(0., 1.) * mid).min(mid - 0.5);
213+ let bottom = (mid - lo.clamp(-1., 0.) * mid).max(mid + 0.5);
214+ (w * along as f32, top.max(0.), bottom.min(h))
215+ })
216+ .collect()
217+}
218+
219+
220+
221+
222+
223+
224+
225+
226+/// Records its parent's laid-out box: gpui hands a mouse listener the window
227+/// position only, and the ruler sits behind the panel's padding. Paints
228+/// nothing and takes no hitbox of its own, so the click still reaches the bar.
229+pub(crate) fn bounds_probe(into: Rc<Cell<Bounds<Pixels>>>) -> impl IntoElement {
230+ canvas(move |bounds, _, _| into.set(bounds), |_, _, _, _| ())
231+ .absolute()
232+ .size_full()
233+}
234+
235+/// Where along an element a click landed, 0..1. An element that was never
236+/// painted has no width, and reads as its start rather than as NaN.
237+pub(crate) fn frac_along(x: Pixels, bounds: Bounds<Pixels>) -> f32 {
238+ if bounds.size.width <= px(0.) {
239+ return 0.;
240+ }
241+ ((x - bounds.left()) / bounds.size.width).clamp(0., 1.)
242+}
243+
244+/// Where along an element a click landed, in pixels from its own left edge:
245+/// [`frac_along`] in the units the timeline is drawn in, since a [`Scale`]
246+/// measures in pixels and not in shares of a bed. Clamped to the element -- a
247+/// drag that slid off the end names its end -- and an element that was never
248+/// painted reads as its start.
249+pub(crate) fn px_along(x: Pixels, bounds: Bounds<Pixels>) -> f32 {
250+ f32::from(x - bounds.left()).clamp(0., f32::from(bounds.size.width).max(0.))
251+}
252+
253+/// One turn of the wheel as a single number, positive for a turn *up*, in
254+/// whatever units the device sends (a mouse counts lines, a touchpad pixels).
255+/// A tilt wheel's own axis counts as the same gesture: it is the sideways
256+/// scroll a mouse that has one sends, and the controls this drives have one
257+/// direction each, so the two axes are one answer here.
258+pub(crate) fn wheel_delta(event: &ScrollWheelEvent) -> f32 {
259+ let (dx, dy) = match event.delta {
260+ ScrollDelta::Lines(d) => (d.x, d.y),
261+ ScrollDelta::Pixels(d) => (f32::from(d.x), f32::from(d.y)),
262+ };
263+ match dy == 0. {
264+ true => dx,
265+ false => dy,
266+ }
267+}
268+
269+/// The frame a dropped clip's head lands on: `raw`, unless one of `marks` is
270+/// within `tol` frames of where its head -- or its tail, `len` frames along --
271+/// would come to rest, in which case that edge wins. The snap every timeline
272+/// has: clips meet exactly instead of a frame apart, and the hand does not have
273+/// to aim. The nearest mark wins, and a head landing on one beats a tail at the
274+/// same distance -- what was dragged is the head.
275+pub(crate) fn snapped(raw: u32, len: u32, tol: u32, marks: &[u32]) -> u32 {
276+ let mut best: Option<(u32, u32)> = None;
277+ for &mark in marks {
278+ // Head on the mark, then tail on it -- a clip dragged up against the
279+ // take in front of it snaps by whichever end reaches first.
280+ for start in [Some(mark), mark.checked_sub(len)] {
281+ let Some(start) = start else { continue };
282+ let d = start.abs_diff(raw);
283+ if d <= tol && best.is_none_or(|(near, _)| d < near) {
284+ best = Some((d, start));
285+ }
286+ }
287+ }
288+ best.map_or(raw, |(_, start)| start)
289+}
290+
291+/// The edges worth landing on, off *every* lane: both ends of every clip on the
292+/// timeline, less `skip` -- the clip being dragged, which does not snap to where
293+/// it already is -- and less the other halves of its group, which travel with
294+/// it. `skip` is a lane's place in `lanes` and an index into it. The playhead
295+/// and the head of the timeline go on the end: a clip meets the cursor and the
296+/// start of the show as readily as it meets another take.
297+///
298+/// All lanes rather than the one being dropped on, because a cut is made across
299+/// the timeline: a title on V2 lines up with the shot under it, and a sound
300+/// effect lines up with the frame it belongs to.
301+pub(crate) fn snap_marks(lanes: &[&[Clip]], skip: Option<(usize, usize)>, playhead: u32) -> Vec<u32> {
302+ let link = skip
303+ .and_then(|(lane, idx)| lanes.get(lane)?.get(idx))
304+ .and_then(|clip| clip.link);
305+ let mut marks: Vec<u32> = lanes
306+ .iter()
307+ .enumerate()
308+ .flat_map(|(lane, clips)| {
309+ clips
310+ .iter()
311+ .enumerate()
312+ .filter(move |&(idx, clip)| {
313+ Some((lane, idx)) != skip && !(link.is_some() && clip.link == link)
314+ })
315+ .flat_map(|(_, clip)| [clip.start, clip.end()])
316+ })
317+ .collect();
318+ marks.push(playhead);
319+ marks.push(0);
320+ marks
321+}
322+
323+/// [`snapped`], and the mark that pulled it there -- the line the bed draws
324+/// while the hand is still moving. `None` when nothing was near enough: a line
325+/// standing over open bed would promise a landing that is not going to happen.
326+/// The head is read before the tail, exactly as [`snapped`] prefers it.
327+///
328+/// `on` is the switch ([`ActionId::ToggleSnap`]): off, the gesture lands raw and
329+/// draws no line at all, which is the whole point of being able to turn it off.
330+pub(crate) fn snap_cue(on: bool, raw: u32, len: u32, tol: u32, marks: &[u32]) -> (u32, Option<u32>) {
331+ if !on {
332+ return (raw, None);
333+ }
334+ let start = snapped(raw, len, tol, marks);
335+ let mark = [start, start.saturating_add(len)]
336+ .into_iter()
337+ .find(|mark| marks.contains(mark));
338+ (start, mark)
339+}
340+
341+/// Where a drag lands and the mark that pulled it there: the frame under the
342+/// pointer, less however far into the box the hand grabbed it (so a clip travels
343+/// with the pointer rather than jumping its head under it), snapped by
344+/// [`snap_cue`]. One answer, asked by the shadow drawn in flight
345+/// ([`Player::preview_ghost`]), by the line ([`Player::preview_drop`]) and by
346+/// the drop that commits ([`Player::move_clip`]) -- which is what makes the
347+/// promise and the landing the same frame.
348+pub(crate) fn landing(
349+ under: u32,
350+ grab: u32,
351+ len: u32,
352+ on: bool,
353+ tol: u32,
354+ marks: &[u32],
355+) -> (u32, Option<u32>) {
356+ snap_cue(on, under.saturating_sub(grab), len, tol, marks)
357+}
358+
359+/// Why this file may not go on that lane, in the words the refusal is told in --
360+/// `None` when it may. A file with no picture belongs on an audio lane and
361+/// nowhere else, and a still is silent, so an audio lane is the one place it
362+/// cannot go. Asked twice: by the ghost tinting itself as refused on the way
363+/// down, and by the insert that commits ([`Player::insert_source`]), so what is
364+/// shown as impossible is exactly what is refused.
365+pub(crate) fn lane_refuses(path: &Path, lane: Lane) -> Option<String> {
366+ let name = file_name(path);
367+ let label = lane.label();
368+ match lane.kind {
369+ LaneKind::Video if engine::is_audio(path) => {
370+ Some(format!("NOT ON {label} — {name} has no picture; drop it on an audio lane"))
371+ }
372+ LaneKind::Audio if engine::is_image(path) => {
373+ Some(format!("NOT ON {label} — {name} is a still image; drop it on a video lane"))
374+ }
375+ _ => None,
376+ }
377+}
378+
379+/// Where down an element a pointer sits, 0..1 from the top: the vertical twin
380+/// of [`frac_along`], for the equalizer, whose gain axis is the y one. An
381+/// element that was never painted reads as its middle -- flat, the one answer
382+/// that changes nothing -- rather than as a full boost.
383+pub(crate) fn frac_down(y: Pixels, bounds: Bounds<Pixels>) -> f32 {
384+ if bounds.size.height <= px(0.) {
385+ return 0.5;
386+ }
387+ ((y - bounds.top()) / bounds.size.height).clamp(0., 1.)
388+}
crates/app/src/transport.rsadded+214 -0
@@ -0,0 +1,214 @@
1+//! Where the transport is, how loud it is, and the seek rate limits.
2+
3+use crate::*;
4+
5+/// What the header says with no timeline open, and what the window title reads
6+/// as a program name rather than as a file name.
7+pub(crate) const NO_FILE: &str = "no file open";
8+
9+/// What a press of play says when there is nothing to play: no timeline at all
10+/// and an emptied one are the same answer to the user, so they are one line.
11+pub(crate) const NOTHING_TO_PLAY: &str = "NOTHING TO PLAY — put a clip on the timeline first";
12+
13+/// Whether a press of play would have anything to play. No timeline at all and
14+/// one every clip has been taken off are the same state to a transport, and the
15+/// button and the key both have to give the same answer to it -- so there is
16+/// one of them, and it is free of the window so it can be checked without one.
17+pub(crate) fn nothing_to_play(session: Option<&PlaybackSession>) -> bool {
18+ session.is_none_or(PlaybackSession::is_empty)
19+}
20+
21+/// What the monitoring output is set to. Two things, not one: the level the
22+/// user picked, and whether it is being held silent -- so unmuting comes back
23+/// to the level rather than to a guess.
24+///
25+/// The level counts steps rather than carrying an `f32`, because 5% at a time
26+/// down and back up again through a float would not land on the number it
27+/// started from, and the label would eventually read `79%`.
28+///
29+/// Volume and mute stay independent on purpose: turning the level down while
30+/// muted must not be what makes sound come out. Only the mute key unmutes, and
31+/// the button says both things at once ("Muted 80%") so neither is a surprise.
32+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
33+pub(crate) struct Volume {
34+ pub(crate) steps: u8,
35+ pub(crate) muted: bool,
36+}
37+
38+impl Volume {
39+ /// One step is one percent: fine enough that a drag along the slider reads
40+ /// as continuous, and still a count rather than a float.
41+ pub(crate) const MAX_STEPS: u8 = 100;
42+
43+ /// 5% a press: twenty presses across the range, which is what the keys have
44+ /// always moved. The slider is what the finer grid is for.
45+ pub(crate) const KEY_STEP: u8 = 5;
46+
47+ /// What the device is set to: mute wins, and the level is what it returns
48+ /// to. `0.0..=1.0`, which is the range the plugin's ABI accepts.
49+ pub(crate) fn gain(self) -> f32 {
50+ if self.muted { 0. } else { self.along() }
51+ }
52+
53+ /// One press up or down, clamped at both ends -- saturating, so the count
54+ /// cannot wrap past silence into full volume.
55+ pub(crate) fn step(&mut self, up: bool) {
56+ self.steps = if up {
57+ self.steps.saturating_add(Self::KEY_STEP).min(Self::MAX_STEPS)
58+ } else {
59+ self.steps.saturating_sub(Self::KEY_STEP)
60+ };
61+ }
62+
63+ /// Where the hand let go along the slider, 0..1 from silence to full. The
64+ /// grid is the same one the keys land on, so a drag to the top and a key
65+ /// held up reach the very same number -- and a drag never touches mute:
66+ /// asking for a level while muted is not asking for sound.
67+ pub(crate) fn set_along(&mut self, frac: f32) {
68+ self.steps = (frac.clamp(0., 1.) * f32::from(Self::MAX_STEPS)).round() as u8;
69+ }
70+
71+ /// How full the slider is drawn, 0..1. The level and not the gain: a muted
72+ /// slider still shows what unmuting comes back to, exactly as the label
73+ /// does.
74+ pub(crate) fn along(self) -> f32 {
75+ f32::from(self.steps) / f32::from(Self::MAX_STEPS)
76+ }
77+
78+ /// The level as a whole number, for the button's fixed rect: muting swaps
79+ /// the glyph beside it, never the width of the box.
80+ pub(crate) fn percent(self) -> u32 {
81+ u32::from(self.steps) * 100 / u32::from(Self::MAX_STEPS)
82+ }
83+
84+ /// What the button reads. The level shows while muted too: it is what the
85+ /// next press of the mute key brings back.
86+ pub(crate) fn label(self) -> String {
87+ let percent = u32::from(self.steps) * 100 / u32::from(Self::MAX_STEPS);
88+ if self.muted {
89+ format!("Muted {percent}%")
90+ } else {
91+ format!("Vol {percent}%")
92+ }
93+ }
94+}
95+
96+impl Default for Volume {
97+ fn default() -> Self {
98+ Self {
99+ steps: Self::MAX_STEPS,
100+ muted: false,
101+ }
102+ }
103+}
104+
105+/// Where the transport is. The one answer the button's glyph, its label, its
106+/// enablement, the play key and the repaint loop all read -- there is no play
107+/// flag anywhere else, because a second one is a second answer.
108+#[derive(Clone, Copy, PartialEq, Eq, Debug)]
109+pub(crate) enum Transport {
110+ /// No timeline open. Nothing to play and the transport is dimmed.
111+ Stopped,
112+ Playing,
113+ Paused,
114+ /// Played out: the last frame is on screen, the decoder is finished, and the
115+ /// clock is still running past it -- which is exactly why "is the clock
116+ /// going" is not the same question as "is this playing".
117+ Ended,
118+}
119+
120+impl Transport {
121+ /// The timeline is in motion: two bars on the button, and a repaint owed
122+ /// every vsync.
123+ pub(crate) fn is_playing(self) -> bool {
124+ matches!(self, Transport::Playing)
125+ }
126+
127+ /// The play key and the transport button start over from the top rather
128+ /// than toggling -- the end of a timeline is where every NLE does this, and
129+ /// the button does it because the key already did.
130+ pub(crate) fn restarts(self) -> bool {
131+ matches!(self, Transport::Ended)
132+ }
133+}
134+
135+/// What a session's own two answers mean: the clock, unless the timeline has
136+/// been played out -- `played_out` is the engine's end of stream with no frame
137+/// still waiting on the pump, and it wins, because past the end a running clock
138+/// is measuring wall time and not a picture.
139+pub(crate) fn transport(playing: bool, played_out: bool) -> Transport {
140+ match (played_out, playing) {
141+ (true, _) => Transport::Ended,
142+ (_, true) => Transport::Playing,
143+ (_, false) => Transport::Paused,
144+ }
145+}
146+
147+/// Rate limit for scrub seeks: a video worker reopen costs 72-87 ms on the
148+/// hardware path for the small files it was measured on (215 ms in software), so
149+/// one seek per mouse move would only queue workers that are cancelled before
150+/// they decode anything.
151+///
152+/// It is a *floor*, not a bound: the reopen is a demux open
153+/// ([`engine::decode::open_worker`]), and on a 25 GB film that is 550-750 ms --
154+/// five to seven times this gap, which therefore gates nothing there. Where the
155+/// cost had to be bounded rather than thinned -- the colour and speed drags --
156+/// the gate is the frame the worker delivers ([`Player::flush_drag`]) and no
157+/// timer at all. The ruler keeps this one: a scrub has no value to hold back,
158+/// only a position that the next mouse move replaces anyway.
159+pub(crate) const SCRUB_GAP: Duration = Duration::from_millis(100);
160+
161+pub(crate) fn scrub_due(target: u32, last_target: u32, since: Duration) -> bool {
162+ target != last_target && since >= SCRUB_GAP
163+}
164+
165+/// How far the picture may fall behind the sound before it is restarted at the
166+/// clock instead of left to crawl after it. Past what an eye reads as lip sync
167+/// (a tenth of a second or so) and above what a single reopen costs to fix, so a
168+/// picture that is merely a reopen behind is not answered with another one.
169+pub(crate) const LATE_RESYNC: f64 = 0.4;
170+/// The least time between two such restarts: the decoder that cannot keep up is
171+/// the one this fires for, and it will still be behind straight afterwards.
172+pub(crate) const RESYNC_GAP: Duration = Duration::from_secs(2);
173+
174+/// Whether a picture `late` seconds behind the master clock is restarted at it,
175+/// given when the last restart was ([`Player::pump`]).
176+pub(crate) fn should_resync(late: f64, last: Option<Instant>) -> bool {
177+ late > LATE_RESYNC && last.is_none_or(|t| t.elapsed() >= RESYNC_GAP)
178+}
179+
180+/// The gate a live drag sample goes through. With the worker still owing a
181+/// frame (`busy`), writing now would only cancel the open the picture is already
182+/// waiting for -- the sample is held in `stash` instead, and the frame that
183+/// lands writes it ([`Player::flush_drag`]). Returns what to write, if anything.
184+///
185+/// The press (`first`) never waits: it is the undo step the whole gesture rolls
186+/// back to, so it has to be taken against the state the hand picked up.
187+pub(crate) fn stash_or_write<T: Copy>(stash: &mut Option<T>, value: T, first: bool, busy: bool) -> Option<T> {
188+ match busy && !first {
189+ true => {
190+ *stash = Some(value);
191+ None
192+ }
193+ false => Some(value),
194+ }
195+}
196+
197+/// How long an open may stand before the window says so in words. Well past an
198+/// ordinary seek (a warm reopen is under a tenth of this) and well under what a
199+/// cold read of a big film takes, which is the only case worth a line.
200+pub(crate) const SEEK_STALL: Duration = Duration::from_secs(2);
201+
202+/// What a seek that has stood past [`SEEK_STALL`] says, and nothing at all
203+/// before that: a line on every click of the ruler would be a flicker, and the
204+/// picture holding still for a tenth of a second is not something to explain.
205+/// The import bar's words, for the import bar's reason -- a window that cannot
206+/// move and a window that has hung look identical, so this one says which.
207+pub(crate) fn seek_line(standing: Option<Duration>) -> Option<String> {
208+ let since = standing.filter(|d| *d >= SEEK_STALL)?;
209+ Some(format!(
210+ "still opening the picture — a cold read of a big file is seconds of it, and the window \
211+ is not frozen · {} elapsed",
212+ clock(since.as_secs_f32())
213+ ))
214+}
crates/app/src/viewport.rsadded+296 -0
@@ -0,0 +1,296 @@
1+//! How much timeline is on the bed, and how a time is written.
2+
3+use crate::*;
4+
5+/// What the zoom button says it is showing: how much timeline fits on the bed,
6+/// in the coarsest unit that still tells two zooms apart.
7+pub(crate) fn span_label(span: f64) -> String {
8+ match span {
9+ s if !s.is_finite() || s <= 0. => "—".to_string(),
10+ // Hours once a timeline is long enough to be measured in them: the far
11+ // stop follows the content now, so "315m" is a span a user can be sat
12+ // at, and no one reads a pill in minutes past sixty.
13+ s if s >= 3600. => format!("{:.1}h", s / 3600.),
14+ s if s >= 600. => format!("{:.0}m", s / 60.),
15+ s if s >= 60. => format!("{:.1}m", s / 60.),
16+ s if s >= 10. => format!("{s:.0}s"),
17+ s => secs_label(s),
18+ }
19+}
20+
21+/// A span of seconds as a person reads it: one decimal above a second, two
22+/// below -- [`scaled`]'s rule, for its reason. The tightest zoom is
23+/// [`ZOOM_MIN_FRAMES`] across the bed, which on the 240 fps slow-motion a phone
24+/// writes is 0.03s, and a single frame of quiet at 60 fps is 0.02s: one decimal
25+/// prints both as "0.0s", a pill and a notice saying the thing they are about
26+/// has no length at all.
27+pub(crate) fn secs_label(secs: f64) -> String {
28+ match secs >= 1. {
29+ true => format!("{secs:.1}s"),
30+ false => format!("{secs:.2}s"),
31+ }
32+}
33+
34+/// The mapping the whole panel is drawn and clicked through: `pps` pixels to a
35+/// second of timeline, `start` the moment at the bed's left edge. Absolute --
36+/// how wide a clip is drawn depends on how long the clip is and on nothing
37+/// else, so adding a second clip does not redraw the first one narrower and
38+/// zooming out always makes every box smaller.
39+///
40+/// The one place seconds become pixels: every box, the playhead, a seek and a
41+/// trim all go through it, so none of them can drift away from the others when
42+/// the view moves. What clamps it -- the stops, the scroll, the fit -- needs the
43+/// bed it is drawn on and lives on [`View`].
44+#[derive(Clone, Copy, Debug, PartialEq)]
45+pub(crate) struct Scale {
46+ pub(crate) pps: f64,
47+ pub(crate) start: f64,
48+}
49+
50+impl Default for Scale {
51+ fn default() -> Self {
52+ Scale {
53+ pps: PPS_DEFAULT,
54+ start: 0.,
55+ }
56+ }
57+}
58+
59+impl Scale {
60+ /// Where a moment sits on the bed, in pixels from its left edge. Negative
61+ /// for a moment scrolled off to the left, which is exactly the offset a
62+ /// half-visible clip is drawn at.
63+ pub(crate) fn px_at(self, at: f64) -> f32 {
64+ ((at - self.start) * self.pps) as f32
65+ }
66+
67+ /// How wide a stretch of `len` seconds is drawn. Wider than the bed once
68+ /// zoomed in, which is the point of zooming in; never negative, which gpui
69+ /// has no meaning for.
70+ pub(crate) fn width_px(self, len: f64) -> f32 {
71+ (len * self.pps).max(0.) as f32
72+ }
73+
74+ /// The moment `x` pixels along the bed is pointing at: the inverse of
75+ /// [`Scale::px_at`], and what every seek and every trim reads. Clamped at
76+ /// the head of the timeline only -- there is bed past the last frame now,
77+ /// and a tail dragged into it is a longer clip, not an error.
78+ pub(crate) fn time_at(self, x: f32) -> f64 {
79+ if self.pps > 0. {
80+ (self.start + f64::from(x) / self.pps).max(0.)
81+ } else {
82+ self.start
83+ }
84+ }
85+
86+ /// [`SNAP_PX`] in timeline frames at the scale the bed is drawn at: a snap
87+ /// is a distance on screen, so zoomed right in it is worth less than a frame
88+ /// (no snap at all, which is what a hand placing single frames wants) and
89+ /// zoomed out it is worth many.
90+ pub(crate) fn snap_frames(self, fps: f64) -> u32 {
91+ if self.pps > 0. {
92+ (SNAP_PX / self.pps * fps) as u32
93+ } else {
94+ 0
95+ }
96+ }
97+}
98+
99+/// A [`Scale`] against the bed it is drawn on and the timeline it is drawn
100+/// from. The bed's width is what turns a scale into "how much is on screen",
101+/// and that is all the stops, the scroll clamp and the fit are made of.
102+///
103+/// Built per use out of [`Player::view`] and thrown away again -- the state is
104+/// the `Scale`, and this is what a bed of `bed` px showing `duration` seconds
105+/// at `fps` may do to it. So no call site can measure a moment against a bed or
106+/// a duration that another one did not.
107+#[derive(Clone, Copy, Debug, PartialEq)]
108+pub(crate) struct View {
109+ pub(crate) scale: Scale,
110+ pub(crate) bed: f32,
111+ pub(crate) duration: f64,
112+ pub(crate) fps: f64,
113+}
114+
115+impl View {
116+ /// How much of the timeline is on the bed, in seconds.
117+ pub(crate) fn span(self) -> f64 {
118+ if self.scale.pps > 0. {
119+ f64::from(self.bed) / self.scale.pps
120+ } else {
121+ 0.
122+ }
123+ }
124+
125+ /// The two stops, in pixels per second: [`ZOOM_MIN_FRAMES`] across the bed
126+ /// is as tight as it goes, and as wide as it goes is the whole timeline on
127+ /// the bed with [`ZOOM_OUT_MARGIN`] to spare -- the far stop is *relative*,
128+ /// so the end of a five hour timeline is reachable for the same reason the
129+ /// end of a five minute one is. A fixed far stop could not say that: a
130+ /// timeline longer than it had an end no zoom could reach, which is the bug
131+ /// this is. Short of [`PPS_MIN`] the timeline's own length is not worth
132+ /// widening to and the pixel takes over, so a short import can still be
133+ /// zoomed out of and the resting scale is nobody's content.
134+ ///
135+ /// `None` on a bed that was never painted -- there is nothing to measure
136+ /// them against yet, and a stop guessed off a zero width would throw away a
137+ /// zoom the user asked for.
138+ pub(crate) fn stops(self) -> Option<(f64, f64)> {
139+ (self.bed > 0.).then(|| {
140+ let bed = f64::from(self.bed);
141+ let whole = match self.duration > 0. {
142+ true => bed / (self.duration * ZOOM_OUT_MARGIN),
143+ false => PPS_MIN,
144+ };
145+ let min = whole.min(PPS_MIN);
146+ (min, (bed * self.fps / ZOOM_MIN_FRAMES).max(min))
147+ })
148+ }
149+
150+ /// Clamped to the bed it draws on: between the two stops, and never
151+ /// scrolled past either end of the timeline. Unlike the fractional view
152+ /// this replaced, the *resting* scale is not the content -- a five second
153+ /// timeline zooms out as far as an hour long one does, and both are drawn
154+ /// at [`PPS_DEFAULT`] until someone zooms. Only the far stop knows the
155+ /// length, and only once the length is worth more than [`PPS_MIN`].
156+ pub(crate) fn settled(self) -> Scale {
157+ let pps = match self.scale.pps.is_finite() && self.scale.pps > 0. {
158+ true => self.scale.pps,
159+ false => PPS_DEFAULT,
160+ };
161+ let start = match self.scale.start.is_finite() {
162+ true => self.scale.start,
163+ false => 0.,
164+ };
165+ let Some((min, max)) = self.stops() else {
166+ return Scale {
167+ pps,
168+ start: start.max(0.),
169+ };
170+ };
171+ let pps = pps.clamp(min, max);
172+ let span = f64::from(self.bed) / pps;
173+ Scale {
174+ pps,
175+ start: start.clamp(0., (self.duration - span).max(0.)),
176+ }
177+ }
178+
179+ /// Zoomed by `factor` about `anchor` (pixels along the bed): whatever moment
180+ /// was under that point stays under it, so a zoom magnifies what was being
181+ /// looked at rather than throwing it off the edge.
182+ pub(crate) fn zoomed(self, factor: f32, anchor: f32) -> Scale {
183+ let at = self.scale.time_at(anchor);
184+ // Clamped *before* the offset is worked out, not after: a press that
185+ // runs into either stop must still leave the anchor where it is, and a
186+ // start measured against a scale the stop then took away would slide it.
187+ let raw = self.scale.pps * f64::from(factor);
188+ let pps = match self.stops() {
189+ Some((min, max)) => raw.clamp(min, max),
190+ None => raw,
191+ };
192+ View {
193+ scale: Scale {
194+ pps,
195+ start: at - f64::from(anchor) / pps,
196+ },
197+ ..self
198+ }
199+ .settled()
200+ }
201+
202+ /// Slid along by `by` pixels, later in the timeline for a positive one: the
203+ /// one move that changes what is on the bed without changing how wide a
204+ /// second is drawn, which is what a bare wheel does. Clamped by
205+ /// [`View::settled`] like every other move, so a run at either end stops at
206+ /// the end rather than scrolling the timeline off the bed -- and the extent
207+ /// it stops against is the content's own length, never a number.
208+ pub(crate) fn scrolled(self, by: f32) -> Scale {
209+ let pps = self.settled().pps;
210+ View {
211+ scale: Scale {
212+ pps,
213+ start: self.scale.start + f64::from(by) / pps,
214+ },
215+ ..self
216+ }
217+ .settled()
218+ }
219+
220+ /// The whole timeline across the bed. The one place the content's own
221+ /// length sets the scale, and the only one -- everywhere else a second is a
222+ /// second -- because this is a user pressing a key that asks for exactly
223+ /// that.
224+ pub(crate) fn fit(self) -> Scale {
225+ let pps = match self.duration > 0. && self.bed > 0. {
226+ true => f64::from(self.bed) / self.duration,
227+ false => PPS_DEFAULT,
228+ };
229+ View {
230+ scale: Scale { pps, start: 0. },
231+ ..self
232+ }
233+ .settled()
234+ }
235+
236+ /// The scale a playhead at `at` needs: the same one while it is on the bed,
237+ /// and one centred on it once it has run off -- which is how a zoomed-in
238+ /// timeline scrolls, during playback and after a seek alike. With the whole
239+ /// timeline on the bed this can never fire, so a panel showing all of it is
240+ /// untouched by it.
241+ pub(crate) fn following(self, at: f64) -> Scale {
242+ // Nothing is drawn yet, so nothing has run off anything.
243+ if self.bed <= 0. {
244+ return self.scale;
245+ }
246+ let scale = self.settled();
247+ if self.shows(at) {
248+ return scale;
249+ }
250+ let span = f64::from(self.bed) / scale.pps;
251+ View {
252+ scale: Scale {
253+ start: at - span / 2.,
254+ ..scale
255+ },
256+ ..self
257+ }
258+ .settled()
259+ }
260+
261+ /// Whether the moment `at` is on the bed as it is drawn now. The one
262+ /// question both halves of the follow ask -- [`View::following`] to decide
263+ /// whether to chase a head that has run off, and the render to decide when
264+ /// a hand's own scroll ([`Player::panned`]) has been caught up with and the
265+ /// follow may have the view back -- so the two can never disagree about
266+ /// where the edge of the bed is.
267+ pub(crate) fn shows(self, at: f64) -> bool {
268+ if self.bed <= 0. {
269+ return false;
270+ }
271+ let scale = self.settled();
272+ at >= scale.start && at <= scale.start + f64::from(self.bed) / scale.pps
273+ }
274+}
275+
276+/// NLE timecode: `HH:MM:SS:FF`, the frame counted inside its own second.
277+pub(crate) fn timecode(t: f64, fps: f64) -> String {
278+ let t = t.max(0.);
279+ let secs = t as u64;
280+ let last = (fps.ceil() as u64).saturating_sub(1);
281+ let frame = ((t - secs as f64) * fps) as u64;
282+ format!(
283+ "{:02}:{:02}:{:02}:{:02}",
284+ secs / 3600,
285+ secs / 60 % 60,
286+ secs % 60,
287+ frame.min(last)
288+ )
289+}
290+
291+/// Wall clock for a progress line: `M:SS`, minutes past the hour included
292+/// rather than an hours field nobody reads on an export.
293+pub(crate) fn clock(secs: f32) -> String {
294+ let secs = secs.max(0.) as u64;
295+ format!("{}:{:02}", secs / 60, secs % 60)
296+}