forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiBff99ad6Tahinli6 days ago1055 commits

cards.rs4319 lines, 183.5 KiBHistoryRawDownload
1//! The cards the window opens over itself: the pickers, colour, speed,
2//! silence, the mixer and the equalizer.
3
4use crate::player::project_dialogs::PathFor;
5use crate::ui::settings_stance::SettingsTab;
6use crate::*;
7use engine::project::KeyKind;
8use std::sync::atomic::{AtomicBool, AtomicU32, Ordering};
9use std::sync::{Arc, Mutex};
10
11/// An auto reframe being measured on a thread ([`Player::start_reframe`]).
12pub(crate) struct ReframeRun {
13 lane: Lane,
14 idx: usize,
15 job: engine::reframe::ReframeJob,
16 progress: Arc<AtomicU32>,
17 cancel: Arc<AtomicBool>,
18 result: Arc<Mutex<Option<Result<engine::reframe::Subject, String>>>>,
19}
20
21/// The transform card's More fold: the crop rows live under it, closed by
22/// default and remembered per panel like every other fold.
23pub(crate) const TRANSFORM_CROP_FOLD: &str = "transform-crop";
24
25/// How many transform rows sit above the crop fold: Position X and Y, Scale
26/// and Rotation. The crop rows are the bands after them.
27pub(crate) const TRANSFORM_MAIN_BANDS: usize = 4;
28
29/// A keyboard nudge on a position row, in canvas pixels.
30pub(crate) const POSITION_NUDGE_PX: f32 = 10.;
31/// The scale a picture in picture takes: the Place row's corner pick, and the
32/// Picture in picture button, both put a full-size clip at this size.
33pub(crate) const PIP_SCALE: f32 = 0.3;
34
35/// Position X and Y, the first two transform rows. The engine keeps them as a
36/// fraction of the canvas, so the card reads and drags them in pixels.
37pub(crate) fn is_position_band(band: usize) -> bool {
38 band < 2
39}
40
41/// The canvas span a position band's fraction is taken over: the width for X,
42/// the height for Y.
43fn position_span(band: usize, canvas: (u32, u32)) -> f32 {
44 if band == 0 { canvas.0 } else { canvas.1 }.max(1) as f32
45}
46
47/// A position on its whole-pixel grid, clamped to the band's range. A drag and
48/// a readout agree on the pixel the picture lands on, not a 5% step.
49pub(crate) fn snap_position_px(band: usize, value: f32, canvas: (u32, u32)) -> f32 {
50 let (_, low, high) = TRANSFORM_BANDS[band];
51 let span = position_span(band, canvas);
52 ((value * span).round() / span).clamp(low, high)
53}
54
55/// What an apply acts on: the previewed regions and the lanes they reach.
56type Previewed = (Vec<(u32, u32)>, Vec<Lane>);
57/// Where a slider bar was last laid out, read back by its drag handler.
58type BarCell = Rc<Cell<Bounds<Pixels>>>;
59
60/// The quietest a meter shows, in dBFS: the bottom of its bar.
61pub(crate) const METER_FLOOR_DB: f32 = -60.;
62/// How fast a meter falls back once the sound drops, in dB a second.
63const METER_FALL_DB_PER_S: f32 = 20.;
64/// How long a peak marker holds before it starts to fall.
65const METER_HOLD_S: f32 = 1.;
66/// A pause between two reads longer than this (a stalled window, a sleep) is
67/// counted as this long, so the meters do not fall through the floor at once.
68const METER_MAX_DT_S: f32 = 0.25;
69
70/// dBFS of a linear peak, floored at [`METER_FLOOR_DB`].
71pub(crate) fn meter_db(peak: f32) -> f32 {
72 match peak > 0. {
73 true => (20. * peak.log10()).max(METER_FLOOR_DB),
74 false => METER_FLOOR_DB,
75 }
76}
77
78/// One level meter: how loud the sound is now, and the marker that holds the
79/// loudest it has been for [`METER_HOLD_S`]. Attacks at once and falls at a
80/// fixed rate, so a short peak reads, and a steady one reads as steady.
81#[derive(Clone, Copy, Debug, PartialEq)]
82pub(crate) struct MixMeter {
83 /// dBFS, at or above [`METER_FLOOR_DB`].
84 pub(crate) level_db: f32,
85 /// dBFS of the held marker.
86 pub(crate) hold_db: f32,
87 /// When the marker last rose; `None` before its first reading.
88 held_at: Option<Instant>,
89 /// When this meter was last read, for the fall between two reads.
90 read_at: Option<Instant>,
91}
92
93impl Default for MixMeter {
94 /// Silent, with nothing held.
95 fn default() -> Self {
96 Self {
97 level_db: METER_FLOOR_DB,
98 hold_db: METER_FLOOR_DB,
99 held_at: None,
100 read_at: None,
101 }
102 }
103}
104
105impl MixMeter {
106 /// Takes one reading: `peak` is the linear level the sound reached since
107 /// the last read ([`engine::Levels`]), `now` when it was read.
108 pub(crate) fn feed(&mut self, peak: f32, now: Instant) {
109 let peak_db = meter_db(peak);
110 let dt = self
111 .read_at
112 .map_or(0., |at| now.saturating_duration_since(at).as_secs_f32())
113 .min(METER_MAX_DT_S);
114 self.read_at = Some(now);
115 self.level_db = fall(self.level_db, peak_db, dt);
116 if peak_db >= self.hold_db {
117 self.hold_db = peak_db;
118 self.held_at = Some(now);
119 } else if self
120 .held_at
121 .is_none_or(|at| now.saturating_duration_since(at).as_secs_f32() >= METER_HOLD_S)
122 {
123 self.hold_db = fall(self.hold_db, peak_db, dt);
124 }
125 }
126
127 /// Back to silence: what a paused or stopped meter shows.
128 pub(crate) fn reset(&mut self) {
129 *self = Self::default();
130 }
131}
132
133/// `shown` after `dt` seconds with `peak` read: it rises at once to `peak` and
134/// otherwise falls at [`METER_FALL_DB_PER_S`], never below `peak`.
135fn fall(shown: f32, peak: f32, dt: f32) -> f32 {
136 match peak >= shown {
137 true => peak,
138 false => (shown - METER_FALL_DB_PER_S * dt).max(peak),
139 }
140}
141
142/// The shortest time between two reads of the transport's master meter: 30 Hz is plenty for a
143/// bar and keeps the engine's peaks (and the repaint they cost) off the per-frame path.
144pub(crate) const MASTER_METER_EVERY_S: f32 = 1. / 30.;
145/// How long the clip lamp stays lit after a sample reached full scale.
146pub(crate) const CLIP_LAMP_S: f32 = 3.;
147/// A linear peak this high is a clipped sample (0 dBFS, with a hair of float slack).
148pub(crate) const CLIP_PEAK: f32 = 0.999;
149
150/// The transport's stereo master meter: a [`MixMeter`] per side, read at most
151/// [`MASTER_METER_EVERY_S`] apart, and the clip lamp's latch.
152#[derive(Default)]
153pub(crate) struct MasterMeter {
154 pub(crate) lr: [MixMeter; 2],
155 read_at: Option<Instant>,
156 clip_at: Option<Instant>,
157}
158
159impl MasterMeter {
160 /// One frame's step. Playing, it reads `peaks` (left, right) if the last read was long enough
161 /// ago -- otherwise it leaves them in the engine to pile up for the next read -- and lights
162 /// the lamp for a clipped peak. Not playing, everything falls to silence at once.
163 pub(crate) fn step(&mut self, playing: bool, peaks: impl FnOnce() -> [f32; 2], now: Instant) {
164 if !playing {
165 *self = Self::default();
166 return;
167 }
168 if self
169 .read_at
170 .is_some_and(|at| now.saturating_duration_since(at).as_secs_f32() < MASTER_METER_EVERY_S)
171 {
172 return;
173 }
174 self.read_at = Some(now);
175 let peaks = peaks();
176 for (meter, peak) in self.lr.iter_mut().zip(peaks) {
177 meter.feed(peak, now);
178 }
179 if peaks.iter().any(|&p| p >= CLIP_PEAK) {
180 self.clip_at = Some(now);
181 }
182 }
183
184 /// Whether the clip lamp is lit at `now`.
185 pub(crate) fn clipped(&self, now: Instant) -> bool {
186 self.clip_at
187 .is_some_and(|at| now.saturating_duration_since(at).as_secs_f32() < CLIP_LAMP_S)
188 }
189}
190
191/// The mix card's own state between frames: the meters it reads and the bars
192/// its sliders are read against. Behind a `RefCell` on [`Player`], because the
193/// card draws from `&self` and a meter has to be read at the moment it is drawn.
194#[derive(Default)]
195pub(crate) struct MixPanel {
196 meters: Vec<(Lane, MixMeter)>,
197 master: MixMeter,
198 master_meter: MasterMeter,
199 gain_bars: Vec<(Lane, Rc<Cell<Bounds<Pixels>>>)>,
200 /// The selected clip's volume bar.
201 pub(crate) clip_bar: Rc<Cell<Bounds<Pixels>>>,
202 /// The selected clip's pitch track.
203 pub(crate) pitch_bar: Rc<Cell<Bounds<Pixels>>>,
204 ceiling_bar: Rc<Cell<Bounds<Pixels>>>,
205 /// The bars of the voice-dynamics sliders, one per lane and setting.
206 voice_bars: Vec<((Lane, VoiceParam), BarCell)>,
207 /// The lanes whose dynamics section is unfolded. Folded is the default: a
208 /// strip is a fader first.
209 voice_open: Vec<Lane>,
210}
211
212/// One of a lane's voice processors ([`engine::voice`]).
213#[derive(Clone, Copy, Debug, PartialEq, Eq)]
214pub(crate) enum VoiceProc {
215 Gate,
216 Nr,
217 Comp,
218 Deess,
219}
220
221impl VoiceProc {
222 pub(crate) const ALL: [VoiceProc; 4] = [Self::Gate, Self::Nr, Self::Comp, Self::Deess];
223
224 pub(crate) fn label(self) -> &'static str {
225 match self {
226 Self::Gate => "Gate",
227 Self::Nr => "Noise reduction",
228 Self::Comp => "Compressor",
229 Self::Deess => "De-esser",
230 }
231 }
232
233 pub(crate) fn is_on(self, fx: &engine::voice::VoiceFx) -> bool {
234 match self {
235 Self::Gate => fx.gate.on,
236 Self::Nr => fx.nr.on,
237 Self::Comp => fx.comp.on,
238 Self::Deess => fx.deess.on,
239 }
240 }
241
242 /// The sliders that belong to this processor.
243 pub(crate) fn params(self) -> &'static [VoiceParam] {
244 match self {
245 Self::Gate => &[VoiceParam::GateThreshold],
246 Self::Nr => &[VoiceParam::NrStrength],
247 Self::Comp => &[
248 VoiceParam::CompThreshold,
249 VoiceParam::CompRatio,
250 VoiceParam::CompMakeup,
251 ],
252 Self::Deess => &[VoiceParam::DeessThreshold, VoiceParam::DeessAmount],
253 }
254 }
255}
256
257/// One slider of the dynamics section.
258#[derive(Clone, Copy, Debug, PartialEq, Eq)]
259pub(crate) enum VoiceParam {
260 GateThreshold,
261 NrStrength,
262 CompThreshold,
263 CompRatio,
264 CompMakeup,
265 DeessThreshold,
266 DeessAmount,
267}
268
269impl VoiceParam {
270 pub(crate) fn label(self) -> &'static str {
271 match self {
272 Self::GateThreshold | Self::CompThreshold | Self::DeessThreshold => "Threshold",
273 Self::NrStrength => "Strength",
274 Self::CompRatio => "Ratio",
275 Self::CompMakeup => "Makeup",
276 Self::DeessAmount => "Amount",
277 }
278 }
279
280 /// The range the slider spans and the step a value snaps to.
281 pub(crate) fn range(self) -> (f32, f32, f32) {
282 match self {
283 Self::GateThreshold => (-80., -10., 1.),
284 Self::NrStrength | Self::DeessAmount => (0., 1., 0.05),
285 Self::CompThreshold | Self::DeessThreshold => (-60., 0., 1.),
286 Self::CompRatio => (1., 10., 0.5),
287 Self::CompMakeup => (0., 18., 0.5),
288 }
289 }
290
291 pub(crate) fn get(self, fx: &engine::voice::VoiceFx) -> f32 {
292 match self {
293 Self::GateThreshold => fx.gate.threshold_db,
294 Self::NrStrength => fx.nr.strength,
295 Self::CompThreshold => fx.comp.threshold_db,
296 Self::CompRatio => fx.comp.ratio,
297 Self::CompMakeup => fx.comp.makeup(),
298 Self::DeessThreshold => fx.deess.threshold_db,
299 Self::DeessAmount => fx.deess.amount,
300 }
301 }
302
303 /// Writes `v` snapped to the step. A makeup typed by hand turns the
304 /// automatic makeup off, as the MCP op does.
305 pub(crate) fn set(self, fx: &mut engine::voice::VoiceFx, v: f32) {
306 let (lo, hi, step) = self.range();
307 let v = ((v.clamp(lo, hi) / step).round() * step).clamp(lo, hi);
308 match self {
309 Self::GateThreshold => fx.gate.threshold_db = v,
310 Self::NrStrength => fx.nr.strength = v,
311 Self::CompThreshold => fx.comp.threshold_db = v,
312 Self::CompRatio => fx.comp.ratio = v,
313 Self::CompMakeup => {
314 fx.comp.makeup_db = v;
315 fx.comp.auto_makeup = false;
316 }
317 Self::DeessThreshold => fx.deess.threshold_db = v,
318 Self::DeessAmount => fx.deess.amount = v,
319 }
320 }
321
322 pub(crate) fn text(self, v: f32) -> String {
323 match self {
324 Self::GateThreshold | Self::CompThreshold | Self::DeessThreshold => {
325 format!("{v:.0} dB")
326 }
327 Self::NrStrength | Self::DeessAmount => format!("{:.0}%", v * 100.),
328 Self::CompRatio => format!("{v:.1}:1"),
329 Self::CompMakeup => format!("{v:+.1} dB"),
330 }
331 }
332}
333
334/// One audio lane as the card draws it this frame.
335pub(crate) struct MixStrip {
336 pub(crate) lane: Lane,
337 pub(crate) meter: MixMeter,
338 pub(crate) bar: Rc<Cell<Bounds<Pixels>>>,
339}
340
341/// The mix card's readings for one frame.
342pub(crate) struct MixReading {
343 pub(crate) strips: Vec<MixStrip>,
344 pub(crate) master: MixMeter,
345 pub(crate) ceiling_bar: Rc<Cell<Bounds<Pixels>>>,
346}
347
348/// The slider a mix drag is moving: a track's fader or the limiter's ceiling.
349#[derive(Clone, Copy, Debug, PartialEq)]
350pub(crate) enum MixDrag {
351 Gain(Lane),
352 /// The selected clip's own volume ([`PlaybackSession::set_clip_gain`]).
353 Clip(Lane, usize),
354 /// The selected clip's pitch in semitones ([`PlaybackSession::set_clip_pitch`]).
355 Pitch(Lane, usize),
356 Ceiling,
357 Voice(Lane, VoiceParam),
358}
359
360/// The pointer's place along a slider's bar, 0..1, or `None` when the bar has
361/// not been drawn yet.
362pub(crate) fn bar_fraction(bar: Bounds<Pixels>, x: Pixels) -> Option<f32> {
363 (bar.size.width > px(0.)).then(|| frac_along(x, bar))
364}
365
366/// A value on a range, from its place along the slider.
367pub(crate) fn value_at(fraction: f32, lo: f32, hi: f32) -> f32 {
368 lo + fraction.clamp(0., 1.) * (hi - lo)
369}
370
371/// Where a track's gain sits on its fader, 0..1. The working range, -24..+12 dB, takes the
372/// most of the travel (80%); the quiet tail down to -60 dB takes the rest, so a drag near a
373/// working level moves the gain in fine steps.
374const GAIN_KNEE_DB: f32 = -24.0;
375const GAIN_KNEE_AT: f32 = 0.2;
376
377pub(crate) fn gain_fraction(db: f32, hi: f32) -> f32 {
378 let lo = engine::project::MIN_GAIN_DB;
379 let at = match db < GAIN_KNEE_DB {
380 true => (db - lo) / (GAIN_KNEE_DB - lo) * GAIN_KNEE_AT,
381 false => GAIN_KNEE_AT + (db - GAIN_KNEE_DB) / (hi - GAIN_KNEE_DB) * (1. - GAIN_KNEE_AT),
382 };
383 at.clamp(0., 1.)
384}
385
386/// The gain a place along the fader reads: the inverse of [`gain_fraction`].
387pub(crate) fn gain_at(fraction: f32, hi: f32) -> f32 {
388 let lo = engine::project::MIN_GAIN_DB;
389 let f = fraction.clamp(0., 1.);
390 match f < GAIN_KNEE_AT {
391 true => lo + f / GAIN_KNEE_AT * (GAIN_KNEE_DB - lo),
392 false => GAIN_KNEE_DB + (f - GAIN_KNEE_AT) / (1. - GAIN_KNEE_AT) * (hi - GAIN_KNEE_DB),
393 }
394}
395
396/// The toggled solo set: `lane` leaves it when it is in it, and joins it when
397/// it is not.
398pub(crate) fn solo_toggled(solo: &[Lane], lane: Lane) -> Vec<Lane> {
399 match solo.contains(&lane) {
400 true => solo.iter().copied().filter(|&l| l != lane).collect(),
401 false => solo.iter().copied().chain([lane]).collect(),
402 }
403}
404
405/// Which meter reads `lane`, given the audio lanes that hold something, in the
406/// order the engine's levels are kept. An empty track has none; a timeline
407/// with no sound at all reads its `A1` as the one slot.
408pub(crate) fn meter_slot_in(sounding: &[Lane], lane: Lane) -> Option<usize> {
409 match sounding.is_empty() {
410 true => (lane == Lane::A1).then_some(0),
411 false => sounding.iter().position(|&l| l == lane),
412 }
413}
414
415/// One frame's reading into a meter: the peak while the sound plays, silence
416/// otherwise.
417fn feed_meter(meter: &mut MixMeter, playing: bool, peak: f32, now: Instant) {
418 match playing {
419 true => meter.feed(peak, now),
420 false => meter.reset(),
421 }
422}
423
424/// Gets the entry for `lane`, adding a default one the first time it is asked for.
425fn lane_entry<T: Default>(items: &mut Vec<(Lane, T)>, lane: Lane) -> &mut T {
426 let at = match items.iter().position(|(l, _)| *l == lane) {
427 Some(at) => at,
428 None => {
429 items.push((lane, T::default()));
430 items.len() - 1
431 }
432 };
433 &mut items[at].1
434}
435
436/// Where a rate (in thousandths) sits on the speed bar, 0..1. The bar is
437/// logarithmic, so every doubling takes the same travel: a quarter to a half is
438/// as far along as two to four.
439pub(crate) fn speed_fraction(permille: f32) -> f32 {
440 let lo = f32::from(Speed::MIN.permille());
441 let hi = f32::from(Speed::MAX.permille());
442 ((permille / lo).ln() / (hi / lo).ln()).clamp(0., 1.)
443}
444
445/// The rate under a fraction of the speed bar, on the [`SPEED_STEP`] grid.
446/// Real time is on the grid (1000 divides by 50), so a pointer can land on it.
447pub(crate) fn speed_on_bar(along: f32) -> Speed {
448 let lo = f32::from(Speed::MIN.permille());
449 let hi = f32::from(Speed::MAX.permille());
450 let raw = lo * (hi / lo).powf(along.clamp(0., 1.));
451 speed_at((raw / SPEED_STEP as f32).round() as i32 * SPEED_STEP)
452}
453
454
455/// The next row the arrow keys land on from `from`, skipping the platform's internal fonts (a
456/// name with a leading dot), which the card does not show. Row 0 and the default row never hide,
457/// so the walk always ends.
458fn sub_row_step(fonts: &[String], rows: usize, from: usize, down: bool) -> usize {
459 let mut r = from;
460 loop {
461 r = if down { (r + 1) % rows } else { (r + rows - 1) % rows };
462 let hidden = r >= SUB_ROW_FIRST_FAMILY && fonts[r - SUB_ROW_FIRST_FAMILY].starts_with('.');
463 if !hidden || r == from {
464 return r;
465 }
466 }
467}
468
469impl Player {
470 /// The project resized, whichever asked: the list that names a size
471 /// outright comes through here. With no
472 /// timeline yet the size is held as [`Player::pending_settings`] instead of
473 /// being written anywhere -- there is no session to write it onto -- and
474 /// applied the moment the first one exists.
475 pub(crate) fn apply_resolution(&mut self, width: u32, height: u32, cx: &mut Context<Self>) {
476 if let Some(session) = &mut self.session {
477 if session.set_resolution(width, height) {
478 // A project field written from a click, with no keymap action
479 // behind it to arm it ([`Player::act`]'s list is the action
480 // doors only).
481 self.mark_dirty();
482 self.notify_user(format!("Project: {width}x{height}").into());
483 self.reset_after_reseek();
484 }
485 } else {
486 self.pending_settings.0 = Some((width, height));
487 self.notify_user(
488 format!("Project: {width}x{height} — takes effect on the next file opened").into(),
489 );
490 }
491 cx.notify();
492 }
493
494 /// The project cut at another rate: the list names one and this is where it
495 /// happens, the way [`apply_resolution`](Self::apply_resolution) is for a
496 /// size. The whole timeline is conformed to it by the engine
497 /// ([`PlaybackSession::set_frame_rate`]) -- same seconds, same footage --
498 /// and the rate the app itself counts frames in follows, since every
499 /// timecode, ruler mark and step key here is measured in it.
500 pub(crate) fn apply_frame_rate(&mut self, fps: f64, cx: &mut Context<Self>) {
501 if let Some(session) = &mut self.session {
502 if session.set_frame_rate(fps) {
503 self.fps = session.meta().frame_rate;
504 // [`Self::apply_resolution`]'s own reason. Armed after the
505 // session's own reads, since the borrow outlives nothing.
506 self.mark_dirty();
507 self.notify_user(format!("Project: {} fps", fps_label(fps)).into());
508 self.reset_after_reseek();
509 }
510 } else if fps.is_finite() && fps > 0.0 {
511 // Held the same way a resolution picked before any file is
512 // ([`apply_resolution`](Self::apply_resolution)): there is no
513 // timeline yet to cut at it.
514 self.pending_settings.1 = Some(fps);
515 self.notify_user(
516 format!(
517 "Project: {} fps — takes effect on the next file opened",
518 fps_label(fps)
519 )
520 .into(),
521 );
522 }
523 cx.notify();
524 }
525
526 /// The project's mix cut at another rate: the list names one and this is
527 /// where it happens, the way [`apply_resolution`](Self::apply_resolution)
528 /// is for a size. Nothing to reseek here -- unlike a resolution or a rate,
529 /// this touches no picture and re-times nothing -- so the notice says the
530 /// truth about when it is heard: the next time the sound is rebuilt (a
531 /// seek, an edit, a reopen), not the stream already playing
532 /// ([`engine::PlaybackSession::set_sample_rate`]).
533 pub(crate) fn apply_sample_rate(&mut self, rate: Option<u32>, cx: &mut Context<Self>) {
534 let label = |rate: Option<u32>| {
535 rate.map_or("the source's own rate".to_string(), |r| format!("{r} Hz"))
536 };
537 if let Some(session) = &mut self.session {
538 let was = session.sample_rate();
539 session.set_sample_rate(rate);
540 // The engine's setter takes no answer back, so the arm is gated
541 // on the setting having moved: picking the rate already in force
542 // is not an edit.
543 let changed = session.sample_rate() != was;
544 if changed {
545 self.mark_dirty();
546 }
547 self.notify_user(
548 format!(
549 "Project sound: {} — takes effect on the next seek, edit or reopen",
550 label(rate)
551 )
552 .into(),
553 );
554 } else {
555 self.pending_settings.2 = rate;
556 self.notify_user(
557 format!(
558 "Project sound: {} — takes effect on the next file opened",
559 label(rate)
560 )
561 .into(),
562 );
563 }
564 cx.notify();
565 }
566
567 /// The settings page's still image length, opened for typing in seconds.
568 pub(crate) fn begin_still_num(&mut self, cx: &mut Context<Self>) {
569 let Some(session) = &self.session else {
570 return;
571 };
572 self.still_num = Some(crate::ui::kit::NumberEdit::begin(&format!("{:.1}", session.still_secs())));
573 cx.notify();
574 }
575
576 /// One key while the still length is typed: Enter writes it (clamped to the range a still may
577 /// be), Escape drops it.
578 pub(crate) fn still_num_key(&mut self, key: &str, ctrl: bool, alt: bool, key_char: Option<&str>, cx: &mut Context<Self>) {
579 use crate::player::text_field::FieldKey;
580 let Some(mut edit) = self.still_num.take() else {
581 return;
582 };
583 match edit.key(key, ctrl, alt, key_char) {
584 FieldKey::Edited => self.still_num = Some(edit),
585 FieldKey::Cancel => {}
586 FieldKey::Commit => {
587 if let Some(secs) = edit.commit(engine::project::STILL_MIN_SECS, engine::project::STILL_MAX_SECS) {
588 self.apply_still_secs(secs, cx);
589 }
590 }
591 }
592 cx.notify();
593 }
594
595 /// The project's speech model set (`None` for Auto). One undo step.
596 pub(crate) fn apply_speech_model(&mut self, model: Option<&str>, cx: &mut Context<Self>) {
597 if self.session.as_mut().is_some_and(|s| s.set_speech_model(model)) {
598 self.mark_dirty();
599 }
600 cx.notify();
601 }
602
603 /// The project's speech device set. One undo step.
604 pub(crate) fn apply_speech_device(&mut self, device: engine::speech::DeviceChoice, cx: &mut Context<Self>) {
605 if self.session.as_mut().is_some_and(|s| s.set_speech_device(device)) {
606 self.mark_dirty();
607 }
608 cx.notify();
609 }
610
611 /// Whether a speech model in the picker is not installed for the device the project resolves it to.
612 pub(crate) fn speech_model_missing(&self, choice: Choice) -> bool {
613 match (choice, self.session.as_ref()) {
614 (Choice::SpeechModel(Some(m)), Some(s)) => engine::speech::check_model(m, s.speech_device().resolve(m)).is_err(),
615 _ => false,
616 }
617 }
618
619 /// The project's still length set: stills placed from now on take it, and the ones already
620 /// on the timeline keep theirs. One undo step, and the project reads unsaved.
621 pub(crate) fn apply_still_secs(&mut self, secs: f64, cx: &mut Context<Self>) {
622 let changed = match &mut self.session {
623 Some(session) => session.set_still_secs(secs).then(|| session.still_secs()),
624 None => None,
625 };
626 if let Some(now) = changed {
627 self.mark_dirty();
628 self.notify_user(format!("Still image length: {now:.1} s").into());
629 }
630 cx.notify();
631 }
632
633 /// The project's HDR media shown another way: the list names a rendition and
634 /// this is where it happens, the way [`apply_resolution`](Self::apply_resolution)
635 /// is for a size. The engine remaps the frame under the playhead at once
636 /// ([`PlaybackSession::set_tone`]), so the picture on screen is the picked
637 /// one before the notice has faded -- and an SDR project is unmoved, which
638 /// is what the notice says rather than pretending something happened.
639 pub(crate) fn apply_tone(&mut self, preset: Preset, cx: &mut Context<Self>) {
640 if let Some(session) = &mut self.session
641 && session.set_tone(preset)
642 {
643 // [`Self::apply_resolution`]'s own reason.
644 self.mark_dirty();
645 self.notify_user(format!("HDR: {} — affects HDR media", tone_label(preset)).into());
646 self.reset_after_reseek();
647 }
648 cx.notify();
649 }
650
651 /// Opens a choice list on a setting, where it was asked for. One floating
652 /// thing at a time: the click that opens it is the click that closes
653 /// whatever menu it was opened from.
654 pub(crate) fn open_picker(&mut self, of: Pick, at: Point<Pixels>, cx: &mut Context<Self>) {
655 // On the row that is in force, so the first ↑ or ↓ steps off the
656 // current value rather than off the top of the list.
657 let sel = self
658 .choices(of)
659 .iter()
660 .position(|(.., picked)| *picked)
661 .unwrap_or(0);
662 self.context_menu = None;
663 self.library_menu = None;
664 self.picker = Some(Picker { of, at, sel, floored: true, above: None });
665 cx.notify();
666 }
667
668 /// [`Self::open_picker`] for a list that hangs from the foot of a control in the dock, where
669 /// the picture and timeline floor has nothing to protect.
670 pub(crate) fn picker_under(&mut self, of: Pick, at: Point<Pixels>, cx: &mut Context<Self>) {
671 self.open_picker(of, at, cx);
672 if let Some(p) = &mut self.picker {
673 p.floored = false;
674 }
675 }
676
677 /// [`Self::open_picker`] for a dropdown box: the list hangs from the foot of the control that
678 /// holds `click` (or its top, when there is no room below), never from the pointer.
679 pub(crate) fn picker_at_control(&mut self, of: Pick, click: Point<Pixels>, cx: &mut Context<Self>) {
680 match crate::ui::anchor::control_at(click) {
681 Some(control) => {
682 let (at, above) = crate::ui::anchor::hang(control);
683 self.open_picker(of, at, cx);
684 if let Some(p) = &mut self.picker {
685 p.floored = false;
686 p.above = Some(above);
687 }
688 }
689 None => self.picker_under(of, click, cx),
690 }
691 }
692
693 /// The list a menu-bar row opens beside itself, `None` while its setting has nothing to offer.
694 pub(crate) fn menu_pick(&self, action: ActionId) -> Option<Pick> {
695 match action {
696 ActionId::Resolution => Some(Pick::Resolution),
697 ActionId::ViewZoom => Some(Pick::ViewZoom),
698 ActionId::OutputDisplay => Some(Pick::OutputDisplay),
699 ActionId::PlaybackQuality => Some(Pick::ViewQuality),
700 ActionId::GuideMask => Some(Pick::ViewMask),
701 ActionId::GuideStyle => Some(Pick::ViewGuides),
702 ActionId::Fit => self.fit_target().ok().map(|(lane, idx)| Pick::Fit(lane, idx)),
703 ActionId::ClipLabel => self.label_target().map(|(lane, idx)| Pick::Label(lane, idx)),
704 ActionId::KeyEasing => {
705 let kind = self.ease_kind();
706 self.key_here(kind).map(|_| Pick::KeyEase(kind))
707 }
708 _ => None,
709 }
710 }
711
712 /// Where a list opened from the keyboard hangs: the status-bar item it is about, so it never
713 /// opens at wherever the pointer was left. A list about the selected clip hangs from the
714 /// clip readout, which names that clip.
715 pub(crate) fn ledger_anchor(&self, of: LedgerItem) -> Point<Pixels> {
716 let cells = match of {
717 LedgerItem::Size | LedgerItem::Clip => &self.ledger_readout,
718 };
719 Some(cells.get())
720 .filter(|b| b.size.width > px(0.))
721 .map_or(point(px(600.), px(700.)), |b| point(b.origin.x, b.origin.y))
722 }
723
724 /// A row of the open list was picked. Closes the list first -- the rule
725 /// every menu item here follows -- then does exactly what the stroke for
726 /// that setting does, through the same door.
727 pub(crate) fn choose(&mut self, choice: Choice, cx: &mut Context<Self>) {
728 self.picker = None;
729 match choice {
730 Choice::Size(w, h) => self.apply_resolution(w, h, cx),
731 Choice::Fps(fps) => self.apply_frame_rate(fps, cx),
732 Choice::SampleRate(rate) => self.apply_sample_rate(rate, cx),
733 Choice::SpeechModel(model) => self.apply_speech_model(model, cx),
734 Choice::Fit(lane, idx, fit) => self.apply_fit(lane, idx, fit, cx),
735 Choice::Label(lane, idx, label) => self.apply_label(lane, idx, label, cx),
736 Choice::MarkerColor(idx, color) => self.set_marker_color(idx, color, cx),
737 Choice::KeyEase(kind, ease) => self.set_key_ease_here(kind, ease, cx),
738 Choice::Tone(preset) => self.apply_tone(preset, cx),
739 Choice::ViewZoom(zoom) => self.set_viewer_zoom(zoom, cx),
740 Choice::OutputDisplay(index) => self.set_output_display(index, cx),
741 Choice::ViewQuality(q) => {
742 self.viewer.quality = q;
743 self.viewer_changed(cx);
744 }
745 Choice::ViewGuides(g) => {
746 self.viewer.guide = g;
747 self.viewer_changed(cx);
748 }
749 Choice::ViewMask(m) => {
750 self.viewer.mask = m;
751 self.viewer_changed(cx);
752 }
753 // The project's, like the tone map above and unlike the palette
754 // below: kept in the `.edith` and read straight back out of the
755 // session by the card and by the export.
756 Choice::Encoder(seat) => self.apply_encoder(seat, cx),
757 // In force for the next paint -- every token is read through
758 // [`ui::theme::palette`], so one store repaints the whole window --
759 // and kept for the next launch. A file that could not be written is
760 // said out loud: the difference between "picked" and "picked for
761 // good" is the user's to know.
762 Choice::Theme(id) => {
763 ui::theme::set(id);
764 if let Err(e) = ui::theme::save(id) {
765 let path = ui::theme::config_path();
766 self.notify_user(
767 format!("Theme could not be kept — {} — {e}", path.display()).into(),
768 );
769 }
770 cx.notify();
771 }
772 // Kept for the next launch; a file that cannot be written is said, as the theme's is.
773 Choice::Autosave(secs) => {
774 self.autosave_secs = secs;
775 if let Err(e) = crate::player::library::save_autosave_pref(secs) {
776 self.notify_user(format!("Autosave setting could not be kept: {e}").into());
777 }
778 cx.notify();
779 }
780 Choice::Accent(a) => {
781 ui::theme::set_accent(a);
782 self.keep_accent();
783 cx.notify();
784 }
785 // The same field the row's key steps, set outright: a list picks a
786 // value, it does not step to one.
787 Choice::AudioRate(kbps) => {
788 self.audio_kbps = kbps;
789 self.export_sheet.custom = true;
790 cx.notify();
791 }
792 // The same door the Picture row's `c` steps through, so a refusal
793 // is still said and the destination still follows the format.
794 Choice::Picture(format) => {
795 self.set_format(format);
796 cx.notify();
797 }
798 Choice::Export(pick) => self.apply_export_pick(pick, cx),
799 Choice::Bin(bin) => {
800 let rows = self.picked_assets();
801 self.move_assets_to_bin(rows, bin, cx)
802 }
803 }
804 }
805
806 /// Every value the open list offers, in the order it lists them. Empty
807 /// without a timeline, which is the state where nothing here has a value to
808 /// offer -- and where the surfaces that open the list are dimmed anyway.
809 pub(crate) fn choices(&self, of: Pick) -> Vec<ChoiceRow> {
810 // The palette is not the project's, so it is offered before the
811 // timeline is asked about: an empty window is painted too, and its
812 // Theme button is live there like the snap beside it.
813 if let Pick::Export(row) = of {
814 return self.export_choices(row);
815 }
816 match of {
817 Pick::ViewZoom => {
818 return crate::viewer_view::Zoom::ALL
819 .into_iter()
820 .map(|z| (Choice::ViewZoom(z), z.label().into(), "".into(), z == self.viewer.zoom))
821 .collect();
822 }
823 Pick::OutputDisplay => {
824 let target = self.output_target();
825 return self
826 .output_displays
827 .iter()
828 .enumerate()
829 .map(|(i, (id, name))| (Choice::OutputDisplay(i), name.clone(), "".into(), Some(*id) == target))
830 .collect();
831 }
832 Pick::ViewQuality => {
833 return crate::viewer_view::Quality::ALL
834 .into_iter()
835 .map(|q| (Choice::ViewQuality(q), q.label().into(), q.detail().into(), q == self.viewer.quality))
836 .collect();
837 }
838 Pick::ViewGuides => {
839 return crate::viewer_view::Guide::ALL
840 .into_iter()
841 .map(|g| (Choice::ViewGuides(g), g.label().into(), g.detail().into(), g == self.viewer.guide))
842 .collect();
843 }
844 Pick::ViewMask => {
845 return crate::viewer_view::Mask::ALL
846 .into_iter()
847 .map(|m| (Choice::ViewMask(m), m.label().into(), m.detail().into(), m == self.viewer.mask))
848 .collect();
849 }
850 Pick::Bin => return self.bin_choices(),
851 _ => {}
852 }
853 if of == Pick::Autosave {
854 return crate::player::library::AUTOSAVE_CHOICES
855 .into_iter()
856 .map(|secs| (Choice::Autosave(secs), crate::player::library::autosave_label(secs).into(), crate::player::library::autosave_detail(secs).into(), secs == self.autosave_secs))
857 .collect();
858 }
859 if of == Pick::Accent {
860 let picked = ui::theme::accent();
861 return ui::theme::AccentId::ALL
862 .into_iter()
863 .map(|a| (Choice::Accent(a), a.label().into(), "".into(), a == picked))
864 .collect();
865 }
866 if of == Pick::Theme {
867 return ui::theme::PaletteId::ALL
868 .into_iter()
869 .map(|id| {
870 (
871 Choice::Theme(id),
872 id.label().into(),
873 id.detail().into(),
874 id == ui::theme::active(),
875 )
876 })
877 .collect();
878 }
879 // The file an export is written as is this computer's pick, not the
880 // project's, so the list is offered before a timeline is asked about
881 // -- a refusal rides each row it applies to, and is empty without a
882 // session to refuse anything.
883 if of == Pick::Picture {
884 return crate::ui::settings_stance::picture_choices(self.format, |f| {
885 self.session
886 .as_ref()
887 .and_then(|session| format_refusal(session, f))
888 });
889 }
890 let Some(session) = &self.session else {
891 // Resolution and rate are reachable before any file is open --
892 // they hold as `pending_settings` until one is ([`apply_resolution`],
893 // [`apply_frame_rate`]) -- every other row still needs a session to
894 // have anything to offer.
895 return match of {
896 Pick::Resolution => pending_resolution_choices(self.pending_settings.0),
897 Pick::Fps => pending_fps_choices(self.pending_settings.1),
898 Pick::SampleRate => sample_rate_choices(self.pending_settings.2),
899 _ => Vec::new(),
900 };
901 };
902 match of {
903 Pick::Resolution => {
904 resolution_choices(session.resolution(), session.native_resolution())
905 }
906 Pick::Fps => fps_choices(session.meta().frame_rate, session.native_frame_rate()),
907 Pick::SampleRate => sample_rate_choices(session.sample_rate()),
908 Pick::SpeechModel => {
909 let here = session.speech_model();
910 std::iter::once((Choice::SpeechModel(None), "Auto".into(), "".into(), here.is_none()))
911 .chain(engine::speech::MODELS.iter().map(|&m| {
912 (Choice::SpeechModel(Some(m)), crate::creator::model_label(m).into(), "".into(), here == Some(m))
913 }))
914 .collect()
915 }
916 Pick::Fit(lane, idx) => {
917 fit_choices(lane, idx, session.fit_of(lane, idx), session.resolution())
918 }
919 Pick::AudioRate => audio_rate_choices(self.audio_kbps),
920 Pick::Tone => tone_choices(session.tone()),
921 Pick::Encoder => encoder_choices(session.encoder_seat()),
922 // Answered above, with or without a timeline.
923 Pick::KeyEase(kind) => {
924 let here = self.key_here(kind);
925 engine::transform::KeyEase::ALL
926 .into_iter()
927 .map(|ease| (Choice::KeyEase(kind, ease), crate::export_ui::ease_label(ease).into(), "".into(), here == Some(ease)))
928 .collect()
929 }
930 Pick::Label(lane, idx) => {
931 let here = session.mark_of(lane, idx).label;
932 std::iter::once((Choice::Label(lane, idx, 0), "None".into(), "".into(), here == 0))
933 .chain(engine::project::LABELS.iter().enumerate().map(|(i, (name, _))| {
934 let n = i as u8 + 1;
935 (Choice::Label(lane, idx, n), (*name).into(), "".into(), here == n)
936 }))
937 .collect()
938 }
939 Pick::MarkerColor(idx) => {
940 let here = session.markers().get(idx).map(|m| m.color);
941 engine::project::MarkerColor::ALL
942 .into_iter()
943 .map(|c| {
944 let name = c.name();
945 let label = format!("{}{}", name[..1].to_uppercase(), &name[1..]);
946 (Choice::MarkerColor(idx, c), label.into(), "".into(), here == Some(c))
947 })
948 .collect()
949 }
950 Pick::Theme | Pick::Accent | Pick::Picture | Pick::Export(_) | Pick::ViewZoom | Pick::OutputDisplay | Pick::ViewQuality | Pick::ViewMask | Pick::ViewGuides | Pick::Bin | Pick::Autosave => Vec::new(),
951 }
952 }
953
954 /// Opens the colour card on the clip a grade would go on: the clip that was
955 /// clicked when it is a video one, and otherwise the clip the picture is
956 /// coming from -- the one the engine's own compositing rule picks, which is
957 /// what a person means by "this shot". The fallback stands even now that a
958 /// selection key exists: a grade asked for with nothing selected still means
959 /// the shot on screen.
960 pub(crate) fn open_color(&mut self, cx: &mut Context<Self>) {
961 if self.exporting().is_some() {
962 return;
963 }
964 let Some(session) = &self.session else {
965 self.notify_user("Nothing to grade — no file open".into());
966 cx.notify();
967 return;
968 };
969 // A caption the hand is on names the clip it was pinned to, and the
970 // card opens on that; one in no group has no picture to grade and it
971 // says so, rather than falling to the playhead's clip behind the
972 // hand's back.
973 let target = match self.selected.anchor() {
974 // A caption the hand is on names the clip it was pinned to, and the
975 // grade is that clip's; one in no group has no picture to grade
976 // and it says so, rather than grading the playhead's clip behind
977 // the hand's back.
978 Some((lane, idx)) if lane.kind == LaneKind::Subtitle => {
979 match caption_media_half(session, (lane, idx), LaneKind::Video) {
980 Some(half) => Some(half),
981 None => {
982 self.notify_user("Nothing to grade — a caption has no picture".into());
983 cx.notify();
984 return;
985 }
986 }
987 }
988 // A sound half has no picture of its own: the playhead's clip, as
989 // it always was.
990 Some((lane, _)) if lane.kind == LaneKind::Audio => session.video_clip_at(session.now()),
991 other => other.or_else(|| session.video_clip_at(session.now())),
992 };
993 match target {
994 Some(clip) => {
995 // One card at a time: `close_card` is the single list of
996 // every flag that means "a card is up", so opening this one
997 // starts by closing all of them.
998 self.close_other_cards();
999 self.color_open = Some(clip);
1000 self.color_band = section_bands(self.color_section).start;
1001 self.color_dragging = false;
1002 self.color_wheel_drag = None;
1003 // A sample the last card held back belongs to the clip it was
1004 // dragged on, and this may be another one.
1005 self.pending_color = None;
1006 self.context_menu = None;
1007 }
1008 None => self.notify_user("Nothing to grade — no clip under the playhead".into()),
1009 }
1010 cx.notify();
1011 }
1012
1013 /// What the card's clip is graded by right now -- the identity for one
1014 /// nobody has graded, which is what the sliders start at. A sample a drag is
1015 /// still holding wins over the clip's own: it is what the hand has asked
1016 /// for, so it is what the sliders show and what the next sample builds on.
1017 pub(crate) fn color_params(&self) -> ColorParams {
1018 if let Some(params) = self.pending_color {
1019 return params;
1020 }
1021 let frame = self.key_frame();
1022 self.color_open
1023 .zip(self.session.as_ref())
1024 .and_then(|((lane, idx), session)| session.color_at(lane, idx, frame))
1025 .unwrap_or_default()
1026 }
1027
1028 /// Puts `params` on the card's clip, or takes the grade off when they are
1029 /// the identity -- a slider walked back to the middle leaves the clip
1030 /// ungraded rather than carrying a do-nothing entry, which is what keeps an
1031 /// untouched project byte-identical. The engine reseeks on the edit, so the
1032 /// frame on screen repaints through the new grade; this only owes the flags
1033 /// that reseek clears.
1034 pub(crate) fn set_color(&mut self, params: ColorParams, cx: &mut Context<Self>) {
1035 self.write_color(params, false, cx);
1036 }
1037
1038 /// Both writes: `live` is the one that takes no undo step, which is what
1039 /// every sample *inside* a drag goes through
1040 /// (`PlaybackSession::set_color_live`). Either way the engine reseeks, so
1041 /// the picture -- and the histogram counted off it -- is regraded at once.
1042 pub(crate) fn write_color(&mut self, params: ColorParams, live: bool, cx: &mut Context<Self>) {
1043 self.named_step("Colour", |this| this.write_color_now(params, live, cx));
1044 }
1045
1046 pub(crate) fn write_color_now(&mut self, params: ColorParams, live: bool, cx: &mut Context<Self>) {
1047 // Any write supersedes a held sample, whichever way it arrived -- a key,
1048 // a reset, or the flush that took this one out of the stash.
1049 self.pending_color = None;
1050 let frame = self.key_frame();
1051 let Some((lane, idx)) = self.color_open else {
1052 return;
1053 };
1054 let Some(session) = &mut self.session else {
1055 return;
1056 };
1057 // A LUT is kept even at intensity 0: the file is the hand's choice, and
1058 // the next pull of the bar is on it.
1059 let grade = Some(params).filter(|p| !p.is_identity() || p.look.lut.is_some());
1060 let keyed = session.is_keyed(lane, idx, KeyKind::Color);
1061 let base = session.color_of(lane, idx).copied().unwrap_or_default();
1062 let took = if keyed && base.look != params.look {
1063 // The look holds under the keys: it is the clip's own grade's,
1064 // written there whatever the keys say about the sliders.
1065 let base = Some(ColorParams { look: params.look, ..base })
1066 .filter(|p| !p.is_identity() || p.look.lut.is_some());
1067 match live {
1068 true => session.set_color_live(lane, idx, base),
1069 false => session.set_color(lane, idx, base),
1070 }
1071 } else if keyed {
1072 // A keyed grade: the slider writes the key on the playhead.
1073 session.put_color_key_at(lane, idx, frame, params, !live)
1074 } else {
1075 match live {
1076 true => session.set_color_live(lane, idx, grade),
1077 false => session.set_color(lane, idx, grade),
1078 }
1079 };
1080 if took {
1081 self.mark_dirty();
1082 self.reset_after_reseek();
1083 }
1084 cx.notify();
1085 }
1086
1087 /// Shows another section of the colour card; the arrows then walk its sliders.
1088 pub(crate) fn show_color_section(&mut self, section: ColorSection, cx: &mut Context<Self>) {
1089 self.color_section = section;
1090 self.color_band = section_bands(section).start;
1091 cx.notify();
1092 }
1093
1094 /// What the graph over the colour controls shows. A scope is counted off the
1095 /// next frame; the one on screen is counted now, so the switch shows at once.
1096 pub(crate) fn show_scope(&mut self, view: ScopeView, cx: &mut Context<Self>) {
1097 self.scope_view = view;
1098 self.scopes = None;
1099 if view != ScopeView::Histogram
1100 && let Some(image) = &self.image
1101 && let Some(frame) = image.as_bytes(0)
1102 {
1103 let size = image.size(0);
1104 let (w, h) = (size.width.0 as usize, size.height.0 as usize);
1105 self.scopes = Some(engine::scopes::compute(frame, w, h, SCOPE_COLS));
1106 }
1107 cx.notify();
1108 }
1109
1110 /// Asks for a `.cube` file and puts it on the card's clip at full intensity,
1111 /// or -- `relink` -- points every clip using the clip's current LUT at it.
1112 /// The chooser runs off the UI thread; a file that cannot be read is said so
1113 /// and changes nothing.
1114 pub(crate) fn pick_lut(&mut self, relink: bool, cx: &mut Context<Self>) {
1115 let picked = cx.background_executor().spawn(async { pick_file("edith — LUT (.cube)") });
1116 cx.spawn(async move |this, cx| {
1117 let picked = picked.await;
1118 this.update(cx, |this, cx| match picked {
1119 Ok(Some(path)) => this.set_lut(&path, relink, cx),
1120 Ok(None) => {}
1121 // No chooser here: the same question, typed.
1122 Err(_) => this.open_path_entry(PathFor::Lut { relink }, cx),
1123 })
1124 .ok();
1125 })
1126 .detach();
1127 }
1128
1129 pub(crate) fn set_lut(&mut self, path: &Path, relink: bool, cx: &mut Context<Self>) {
1130 let r = engine::cube::LutRef::reload(path);
1131 if let Some(why) = r.problem() {
1132 self.notify_user(format!("That LUT cannot be used: {why}").into());
1133 cx.notify();
1134 return;
1135 }
1136 let mut params = self.color_params();
1137 let old = params.look.lut;
1138 if relink && let (Some(old), Some(session)) = (old, &mut self.session) {
1139 let n = session.relink_lut(&old.path(), path);
1140 if n > 0 {
1141 self.mark_dirty();
1142 self.reset_after_reseek();
1143 self.notify_user(format!("Relinked the LUT on {}", count_noun(n, "clip", "clips")).into());
1144 }
1145 cx.notify();
1146 return;
1147 }
1148 params.look.lut = Some(r);
1149 params.look.lut_mix = 1.;
1150 self.set_color(params, cx);
1151 }
1152
1153 /// Takes the LUT off the card's clip; the rest of its grade stays.
1154 pub(crate) fn clear_lut(&mut self, cx: &mut Context<Self>) {
1155 let mut params = self.color_params();
1156 params.look.lut = None;
1157 params.look.lut_mix = 1.;
1158 self.set_color(params, cx);
1159 }
1160
1161 /// Moves the picked slider by `steps` of [`COLOR_STEP`], clamped to that
1162 /// band's range. One edit, so one undo step per press.
1163 pub(crate) fn nudge_color(&mut self, steps: f32, cx: &mut Context<Self>) {
1164 let mut params = self.color_params();
1165 let (band, wheel, curve) = (self.color_band, self.color_wheel, self.color_curve);
1166 let (_, low, high, step) = band_spec(band);
1167 let value = (band_value(&params, band, wheel, curve) + steps * step).clamp(low, high);
1168 set_band(&mut params, band, wheel, curve, value);
1169 self.set_color(params, cx);
1170 }
1171
1172 /// Where the pointer sits along a slider, as that band's value: the left end
1173 /// of the bar is the bottom of its range and the right end the top. Called
1174 /// on every pointer sample, so the grade -- and the picture, and the
1175 /// histogram over it -- moves under the hand.
1176 ///
1177 /// `first` is the press: it takes the undo step the whole gesture rolls back
1178 /// to, and every sample after it is live. That is why it writes even when
1179 /// the value did not change -- without that snapshot the rest of the drag
1180 /// would be unundoable.
1181 ///
1182 /// Values land on the [`COLOR_STEP`] grid the keys use, which also bounds
1183 /// one drag to forty-odd entries in the project's colour table.
1184 ///
1185 /// Samples crossed while the worker still owes a frame are held rather than
1186 /// written ([`stash_or_write`]): a reopen costs half a second on a big film,
1187 /// so a bar-wide sweep that wrote every step would queue forty opens, cancel
1188 /// thirty-nine of them and freeze the window for the sum. What is written is
1189 /// one grade per frame the worker actually delivers.
1190 pub(crate) fn drag_color(&mut self, x: Pixels, first: bool, cx: &mut Context<Self>) {
1191 let (band, wheel, curve) = (self.color_band, self.color_wheel, self.color_curve);
1192 let (_, low, high, step) = band_spec(band);
1193 let along = frac_along(x, self.color_bars[band].get());
1194 // The basic bands land on the keys' grid; the wheels and curves on a
1195 // finer one of their own, since a hundredth of a lift already shows.
1196 let raw = low + along * (high - low);
1197 let value = if band < WHEEL_BAND { color_snap(raw) } else { (raw / step).round() * step };
1198 let value = value.clamp(low, high);
1199 let mut params = self.color_params();
1200 if band_value(&params, band, wheel, curve) == value && !first {
1201 return;
1202 }
1203 set_band(&mut params, band, wheel, curve, value);
1204 let busy = self.seek_since.is_some();
1205 match stash_or_write(&mut self.pending_color, params, first, busy) {
1206 Some(params) => self.write_color(params, !first, cx),
1207 // The sliders draw off the held sample, so the handle goes on
1208 // following the hand while the picture catches up.
1209 None => cx.notify(),
1210 }
1211 }
1212
1213 /// One pointer sample on a colour wheel: the puck (`master` false) sets the
1214 /// wheel's R, G and B offsets from its place on the pad, the bar under it sets
1215 /// the master. `first` is the press, which takes the undo step.
1216 pub(crate) fn drag_wheel(&mut self, wheel: usize, master: bool, at: gpui::Point<Pixels>, first: bool, cx: &mut Context<Self>) {
1217 let mut params = self.color_params();
1218 self.color_wheel = wheel;
1219 if master {
1220 let along = frac_along(at.x, self.color_masters[wheel].get());
1221 let v = wheel_snap(along * 2. - 1.);
1222 set_band(&mut params, WHEEL_BAND, wheel, self.color_curve, v);
1223 self.color_band = WHEEL_BAND;
1224 } else {
1225 let b = self.color_pads[wheel].get();
1226 let (w, h) = (f32::from(b.size.width).max(1.), f32::from(b.size.height).max(1.));
1227 let x = (f32::from(at.x - b.origin.x) - w / 2.) / (w / 2.);
1228 let y = (h / 2. - f32::from(at.y - b.origin.y)) / (h / 2.);
1229 for (i, v) in wheel_offsets(x, y).into_iter().enumerate() {
1230 set_band(&mut params, WHEEL_BAND + 1 + i, wheel, self.color_curve, wheel_snap(v));
1231 }
1232 self.color_band = WHEEL_BAND + 1;
1233 }
1234 let busy = self.seek_since.is_some();
1235 match stash_or_write(&mut self.pending_color, params, first, busy) {
1236 Some(params) => self.write_color(params, !first, cx),
1237 None => cx.notify(),
1238 }
1239 }
1240
1241 /// Double-click on a wheel: its puck back to the centre (`master` false) or
1242 /// its master back to zero.
1243 pub(crate) fn reset_wheel(&mut self, wheel: usize, master: bool, cx: &mut Context<Self>) {
1244 let mut params = self.color_params();
1245 let bands = if master { WHEEL_BAND..WHEEL_BAND + 1 } else { WHEEL_BAND + 1..CURVE_BAND };
1246 for band in bands {
1247 set_band(&mut params, band, wheel, self.color_curve, 0.);
1248 }
1249 self.set_color(params, cx);
1250 }
1251
1252 /// Opens the transform card on the clip a placement would go on --
1253 /// [`open_color`](Self::open_color)'s own rule, since it targets the same
1254 /// clip a grade would.
1255 pub(crate) fn open_transform(&mut self, cx: &mut Context<Self>) {
1256 if self.exporting().is_some() {
1257 return;
1258 }
1259 let Some(session) = &self.session else {
1260 self.notify_user("Nothing to place — no file open".into());
1261 cx.notify();
1262 return;
1263 };
1264 let target = match self.selected.anchor() {
1265 Some((lane, idx)) if lane.kind == LaneKind::Subtitle => {
1266 match caption_media_half(session, (lane, idx), LaneKind::Video) {
1267 Some(half) => Some(half),
1268 None => {
1269 self.notify_user("Nothing to place — a caption has no picture".into());
1270 cx.notify();
1271 return;
1272 }
1273 }
1274 }
1275 Some((lane, _)) if lane.kind == LaneKind::Audio => session.video_clip_at(session.now()),
1276 other => other.or_else(|| session.video_clip_at(session.now())),
1277 };
1278 match target {
1279 Some(clip) => {
1280 // One card at a time -- `close_card`'s own rule.
1281 self.close_other_cards();
1282 self.transform_open = Some(clip);
1283 self.transform_band = 0;
1284 self.transform_dragging = false;
1285 self.pending_transform = None;
1286 self.place_open = false;
1287 self.title_in_open = false;
1288 self.title_out_open = false;
1289 self.context_menu = None;
1290 }
1291 None => self.notify_user("Nothing to place — no clip under the playhead".into()),
1292 }
1293 cx.notify();
1294 }
1295
1296 /// What the card's clip is placed by right now -- [`color_params`](Self::color_params)'s
1297 /// own rule.
1298 pub(crate) fn transform_params(&self) -> TransformParams {
1299 if let Some(params) = self.pending_transform {
1300 return params;
1301 }
1302 let frame = self.key_frame();
1303 self.transform_open
1304 .zip(self.session.as_ref())
1305 .map(|((lane, idx), session)| {
1306 let mut params = session.transform_at(lane, idx, frame).unwrap_or_default();
1307 if session.is_keyed(lane, idx, KeyKind::Opacity) {
1308 params.opacity = session.opacity_at(lane, idx, frame);
1309 }
1310 params
1311 })
1312 .unwrap_or_default()
1313 }
1314
1315 /// Puts `params` on the card's clip, or takes the placement off when they
1316 /// are the identity -- [`set_color`](Self::set_color)'s own rule.
1317 pub(crate) fn set_transform(&mut self, params: TransformParams, cx: &mut Context<Self>) {
1318 self.write_transform(params, false, cx);
1319 }
1320
1321 /// Both writes: `live` is the one that takes no undo step, which is what
1322 /// every sample *inside* a drag goes through --
1323 /// [`write_color`](Self::write_color)'s own rule.
1324 pub(crate) fn write_transform(&mut self, params: TransformParams, live: bool, cx: &mut Context<Self>) {
1325 self.named_step("Transform", |this| this.write_transform_now(params, live, cx));
1326 }
1327
1328 fn write_transform_now(&mut self, params: TransformParams, live: bool, cx: &mut Context<Self>) {
1329 self.pending_transform = None;
1330 let frame = self.key_frame();
1331 let Some((lane, idx)) = self.transform_open else {
1332 return;
1333 };
1334 let Some(session) = &mut self.session else {
1335 return;
1336 };
1337 let mut params = params;
1338 let mut took = false;
1339 if session.is_keyed(lane, idx, KeyKind::Opacity) {
1340 // Keyed opacity: the slider writes its key, and the placement keeps
1341 // the opacity it had.
1342 if session.opacity_at(lane, idx, frame) != params.opacity {
1343 took = session.put_opacity_key_at(lane, idx, frame, params.opacity, !live);
1344 }
1345 params.opacity = session
1346 .transform_at(lane, idx, frame)
1347 .map_or(1.0, |t| t.opacity);
1348 }
1349 if session.is_keyed(lane, idx, KeyKind::Placement) {
1350 if session.transform_at(lane, idx, frame) != Some(params) {
1351 took |= session.put_transform_key_at(lane, idx, frame, params, !live && !took);
1352 }
1353 } else {
1354 let placement = Some(params).filter(|p| !p.is_identity());
1355 if session.transform_at(lane, idx, frame) != placement || !took {
1356 took |= match live {
1357 true => session.set_transform_live(lane, idx, placement),
1358 false => session.set_transform(lane, idx, placement),
1359 };
1360 }
1361 }
1362 if took {
1363 self.mark_dirty();
1364 self.reset_after_reseek();
1365 }
1366 cx.notify();
1367 }
1368
1369 /// The canvas the placement is measured on: position is a fraction of it,
1370 /// so the pixel readout and the pixel drag both need its size. The card
1371 /// only opens with a file, so the project default stands in for nothing.
1372 pub(crate) fn transform_canvas(&self) -> (u32, u32) {
1373 self.session
1374 .as_ref()
1375 .map_or((1920, 1080), |session| session.resolution())
1376 }
1377
1378 /// The pixel size of the picture the card's clip shows, as the engine
1379 /// measures it: a video's from its probed facts, a still's from its header.
1380 /// `None` for sound, a generated clip, or a video whose facts are still
1381 /// being read.
1382 pub(crate) fn clip_picture_size(&self, lane: Lane, idx: usize) -> Option<(u32, u32)> {
1383 let session = self.session.as_ref()?;
1384 let clip = session.lane_clips(lane).get(idx)?;
1385 let path = &session.sources().get(clip.source)?.path;
1386 if engine::is_image(path) {
1387 return engine::decode::image_size(path).ok();
1388 }
1389 let video = self.facts.get(path)?.as_ref()?.video.as_ref()?;
1390 Some((video.width, video.height))
1391 }
1392
1393 /// Puts the card's clip in `corner`, at `scale` when one is given. Without
1394 /// one, a corner pick on a clip still at full size makes it a picture in
1395 /// picture ([`PIP_SCALE`]), so the picture is smaller than the frame it sits
1396 /// in. Keeps the default corner margin. One undo step, as every placement is
1397 /// ([`set_transform`](Self::set_transform)).
1398 pub(crate) fn place_in_corner(&mut self, corner: engine::transform::Corner, scale: Option<f32>, cx: &mut Context<Self>) {
1399 let Some((lane, idx)) = self.transform_open else {
1400 return;
1401 };
1402 let Some(size) = self.clip_picture_size(lane, idx) else {
1403 return;
1404 };
1405 let mut params = self.transform_params();
1406 if let Some(scale) = scale {
1407 params.scale = scale;
1408 } else if corner != engine::transform::Corner::Centre && params.scale == TransformParams::default().scale {
1409 params.scale = PIP_SCALE;
1410 }
1411 let canvas = self.transform_canvas();
1412 let (x, y) = engine::transform::corner_placement(corner, &params, size, canvas, engine::transform::CORNER_MARGIN_PX);
1413 params.pos_x = x;
1414 params.pos_y = y;
1415 self.set_transform(params, cx);
1416 }
1417
1418 /// Puts the picture at `scale` as a scale change: a picture in a corner stays
1419 /// in that corner ([`engine::transform::keep_corner`]), at the card's clip's
1420 /// own picture size. `old` is what the picture was before the change.
1421 pub(crate) fn scaled_in_place(&self, old: TransformParams, new: TransformParams) -> TransformParams {
1422 let Some((lane, idx)) = self.transform_open else {
1423 return new;
1424 };
1425 let (Some(size), canvas) = (self.clip_picture_size(lane, idx), self.transform_canvas()) else {
1426 return new;
1427 };
1428 engine::transform::keep_corner(&old, new, size, canvas, engine::transform::CORNER_MARGIN_PX)
1429 }
1430
1431 /// Whether the crop rows are unfolded.
1432 pub(crate) fn transform_crop_open(&self) -> bool {
1433 self.folds.contains(TRANSFORM_CROP_FOLD)
1434 }
1435
1436 /// Opens or closes the crop rows and remembers it. Closing them moves a
1437 /// picked crop row back to the first one, so the arrows never move a slider
1438 /// nobody can see.
1439 pub(crate) fn toggle_transform_crop(&mut self, cx: &mut Context<Self>) {
1440 if self.folds.contains(TRANSFORM_CROP_FOLD) {
1441 self.folds.remove(TRANSFORM_CROP_FOLD);
1442 if self.transform_band >= TRANSFORM_MAIN_BANDS {
1443 self.transform_band = 0;
1444 }
1445 } else {
1446 self.folds.insert(TRANSFORM_CROP_FOLD.to_owned());
1447 }
1448 save_folds(&self.folds);
1449 cx.notify();
1450 }
1451
1452 /// Moves the picked row one down or up, skipping the crop rows while their
1453 /// fold is shut.
1454 pub(crate) fn move_transform_band(&mut self, down: bool) {
1455 let n = if self.transform_crop_open() {
1456 TRANSFORM_BANDS.len()
1457 } else {
1458 TRANSFORM_MAIN_BANDS
1459 };
1460 if self.transform_band >= n {
1461 self.transform_band = 0;
1462 }
1463 self.transform_band = if down {
1464 (self.transform_band + 1) % n
1465 } else {
1466 (self.transform_band + n - 1) % n
1467 };
1468 }
1469
1470 /// Moves the picked slider by `steps` -- [`nudge_color`](Self::nudge_color)'s
1471 /// own rule, except rotation wraps into its range on [`transform_snap`]
1472 /// instead of clamping, and a position moves in whole canvas pixels.
1473 pub(crate) fn nudge_transform(&mut self, steps: f32, cx: &mut Context<Self>) {
1474 let mut params = self.transform_params();
1475 let band = self.transform_band;
1476 let (_, low, high) = TRANSFORM_BANDS[band];
1477 let canvas = self.transform_canvas();
1478 let old = params;
1479 let value = transform_band_mut(&mut params, band);
1480 *value = if band == ROTATE_BAND {
1481 transform_snap(band, *value + steps * ROTATE_STEP)
1482 } else if is_position_band(band) {
1483 let raw = *value + steps * POSITION_NUDGE_PX / position_span(band, canvas);
1484 snap_position_px(band, raw, canvas)
1485 } else {
1486 (*value + steps * TRANSFORM_STEP).clamp(low, high)
1487 };
1488 if band == SCALE_BAND {
1489 params = self.scaled_in_place(old, params);
1490 }
1491 self.set_transform(params, cx);
1492 }
1493
1494 /// Where the pointer sits along a slider, as that band's value --
1495 /// [`drag_color`](Self::drag_color)'s own rule, on the pixel grid for a
1496 /// position.
1497 pub(crate) fn drag_transform(&mut self, x: Pixels, first: bool, cx: &mut Context<Self>) {
1498 if self.opacity_drag {
1499 self.drag_opacity(x, first, cx);
1500 return;
1501 }
1502 let band = self.transform_band;
1503 let (low, high) = slider_range(band);
1504 let along = frac_along(x, self.transform_bars[band].get());
1505 let raw = low + along * (high - low);
1506 let value = if is_position_band(band) {
1507 snap_position_px(band, raw, self.transform_canvas())
1508 } else {
1509 transform_snap(band, raw)
1510 };
1511 let old = self.transform_params();
1512 let mut params = old;
1513 let at = transform_band_mut(&mut params, band);
1514 if *at == value && !first {
1515 return;
1516 }
1517 *at = value;
1518 if band == SCALE_BAND {
1519 params = self.scaled_in_place(old, params);
1520 }
1521 let busy = self.seek_since.is_some();
1522 match stash_or_write(&mut self.pending_transform, params, first, busy) {
1523 Some(params) => self.write_transform(params, !first, cx),
1524 None => cx.notify(),
1525 }
1526 }
1527
1528 /// Where the pointer sits along the opacity bar, as the clip's opacity, on a
1529 /// whole percent. The row shares the transform card's drag flag, so the root
1530 /// hands its samples here while [`Self::opacity_drag`] is set.
1531 pub(crate) fn drag_opacity(&mut self, x: Pixels, first: bool, cx: &mut Context<Self>) {
1532 let value = (frac_along(x, self.opacity_bar.get()) * 100.).round() / 100.;
1533 let mut params = self.transform_params();
1534 if params.opacity == value && !first {
1535 return;
1536 }
1537 params.opacity = value;
1538 let busy = self.seek_since.is_some();
1539 match stash_or_write(&mut self.pending_transform, params, first, busy) {
1540 Some(params) => self.write_transform(params, !first, cx),
1541 None => cx.notify(),
1542 }
1543 }
1544
1545 /// The clip a speed action acts on: the selected one, or the clip the picture
1546 /// is coming from. A caption names the clip it was pinned to, and a caption in
1547 /// no group has no rate -- said out loud, since a card that reads 1.00x and
1548 /// writes nothing is worse than a refusal. `None` when there is nothing to act on,
1549 /// and the refusal has been said.
1550 pub(crate) fn speed_anchor(&mut self, cx: &mut Context<Self>) -> Option<(Lane, usize)> {
1551 let Some(session) = self.session.as_ref() else {
1552 self.notify_user("Nothing to re-time — no file open".into());
1553 cx.notify();
1554 return None;
1555 };
1556 let anchor = match self
1557 .selected
1558 .anchor()
1559 .or_else(|| session.video_clip_at(session.now()))
1560 {
1561 Some((lane, idx)) if lane.kind == LaneKind::Subtitle => {
1562 match caption_media_half(session, (lane, idx), LaneKind::Video) {
1563 Some(half) => Some(half),
1564 None => {
1565 self.notify_user(
1566 "Nothing to re-time — a caption has no speed of its own".into(),
1567 );
1568 cx.notify();
1569 None
1570 }
1571 }
1572 }
1573 other => other,
1574 };
1575 if anchor.is_none() {
1576 self.notify_user("Nothing to re-time — no clip under the playhead".into());
1577 cx.notify();
1578 }
1579 anchor
1580 }
1581
1582 /// Opens the speed card on the clip whose rate is to change: the selected
1583 /// one, or -- with nothing selected -- the clip the picture is coming from,
1584 /// which is what a person means by "this shot". Either half of a take will
1585 /// do: a rate applies to the whole group, so opening it on the sound and
1586 /// opening it on the picture are the same card.
1587 pub(crate) fn open_speed(&mut self, cx: &mut Context<Self>) {
1588 if self.exporting().is_some() {
1589 return;
1590 }
1591 let anchor = self.speed_anchor(cx);
1592 match anchor {
1593 Some(clip) => {
1594 // One card at a time -- `close_card`'s own rule.
1595 self.close_other_cards();
1596 self.speed_open = Some(clip);
1597 self.speed_dragging = false;
1598 // The colour card's rule: a held sample is the last clip's.
1599 self.pending_speed = None;
1600 self.ramp_key_speed = None;
1601 // A clip that already ramps opens on its keys.
1602 self.speed_ramp_mode = self
1603 .session
1604 .as_ref()
1605 .and_then(|s| s.lane_clips(clip.0).get(clip.1))
1606 .is_some_and(|c| !c.speed_keys.is_empty());
1607 self.context_menu = None;
1608 }
1609 None => return,
1610 }
1611 cx.notify();
1612 }
1613
1614 /// What the card's clip plays at right now -- real time for one nobody has
1615 /// touched, which is where the bar starts.
1616 pub(crate) fn card_speed(&self) -> Speed {
1617 if let Some(speed) = self.pending_speed {
1618 return speed;
1619 }
1620 // The ramp mode's bar is the next key's speed, not the clip's.
1621 if self.speed_ramp_mode {
1622 return self.ramp_key_speed.unwrap_or_else(|| self.ramp_default_speed());
1623 }
1624 self.speed_open
1625 .zip(self.session.as_ref())
1626 .map_or(Speed::NORMAL, |((lane, idx), session)| {
1627 session.speed_of(lane, idx)
1628 })
1629 }
1630
1631 /// Writes a rate at the card's clip and its whole group -- one undo step for
1632 /// the lot ([`engine::PlaybackSession::set_speed`]). The engine reseeks, so
1633 /// the picture runs at the new rate and the sound is time-stretched from the
1634 /// next chunk on, pitch kept; a refusal (a slower clip would run into its neighbour) comes
1635 /// back in the engine's own words and *names* the clip in the way, because
1636 /// "it did not fit" is not something a person can go and fix.
1637 pub(crate) fn set_speed(&mut self, speed: Speed, cx: &mut Context<Self>) {
1638 self.write_speed(speed, false, cx);
1639 }
1640
1641 /// Both writes: `live` is the one that takes no undo step, which is what
1642 /// every sample *inside* a drag goes through -- so a drag from 1.00x to
1643 /// 2.00x is one undo press and lands back where the hand picked it up, and
1644 /// the whole linked group comes back with it.
1645 pub(crate) fn write_speed(&mut self, speed: Speed, live: bool, cx: &mut Context<Self>) {
1646 self.named_step("Speed", |this| this.write_speed_now(speed, live, cx));
1647 }
1648
1649 fn write_speed_now(&mut self, speed: Speed, live: bool, cx: &mut Context<Self>) {
1650 // The colour card's rule: a write supersedes whatever a drag was holding.
1651 self.pending_speed = None;
1652 if self.speed_ramp_mode {
1653 // Nothing is written until a key is added: the bar picks its speed.
1654 self.ramp_key_speed = Some(speed);
1655 cx.notify();
1656 return;
1657 }
1658 let Some((lane, idx)) = self.speed_open else {
1659 return;
1660 };
1661 let Some(session) = &mut self.session else {
1662 return;
1663 };
1664 if speed != session.speed_of(lane, idx) {
1665 let wrote = match live {
1666 true => session.set_speed_live(lane, idx, speed),
1667 false => session.set_speed(lane, idx, speed),
1668 };
1669 match wrote {
1670 Ok(()) => {
1671 self.mark_dirty();
1672 self.reset_after_reseek();
1673 }
1674 Err(e) => self.notify_user(e.to_string().into()),
1675 }
1676 }
1677 cx.notify();
1678 }
1679
1680 /// Reverses the clip the speed card is open on, or the one the menu and the
1681 /// palette mean (the selection, else the picture under the playhead --
1682 /// `open_speed`'s rule), and its whole group: one undo step. Said once on
1683 /// the toast so the toggle has an answer when the card is closed.
1684 pub(crate) fn toggle_reverse(&mut self, cx: &mut Context<Self>) {
1685 let Some(session) = &self.session else {
1686 self.notify_user("Nothing to reverse — no file open".into());
1687 cx.notify();
1688 return;
1689 };
1690 let anchor = self
1691 .selected
1692 .anchor()
1693 .or_else(|| session.video_clip_at(session.now()))
1694 .filter(|(lane, _)| lane.kind != LaneKind::Subtitle);
1695 match anchor {
1696 Some((lane, idx)) => {
1697 let on = !session.reversed_of(lane, idx);
1698 self.write_reverse(lane, idx, on, cx);
1699 }
1700 None => {
1701 self.notify_user("Nothing to reverse — select a clip".into());
1702 cx.notify();
1703 }
1704 }
1705 }
1706
1707 /// Writes the direction at `(lane, idx)` and its group
1708 /// ([`engine::PlaybackSession::set_reverse`]); the engine reseeks, so the
1709 /// picture and the sound run the new way from the next frame.
1710 pub(crate) fn write_reverse(&mut self, lane: Lane, idx: usize, on: bool, cx: &mut Context<Self>) {
1711 let Some(session) = &mut self.session else {
1712 return;
1713 };
1714 match session.set_reverse(lane, idx, on) {
1715 Ok(()) => {
1716 self.mark_dirty();
1717 self.reset_after_reseek();
1718 }
1719 Err(e) => self.notify_user(e.to_string().into()),
1720 }
1721 cx.notify();
1722 }
1723
1724 /// The clip a ramp edit acts on: the open card's, else the speed actions' own pick.
1725 fn ramp_target(&mut self, cx: &mut Context<Self>) -> Option<(Lane, usize)> {
1726 match self.speed_open {
1727 Some(clip) => Some(clip),
1728 None => self.speed_anchor(cx),
1729 }
1730 }
1731
1732 /// The playhead's frame counted from the start of the clip at `clip`, when the
1733 /// playhead is on it.
1734 fn ramp_playhead(&self, clip: (Lane, usize)) -> Option<u32> {
1735 let session = self.session.as_ref()?;
1736 let c = session.lane_clips(clip.0).get(clip.1)?;
1737 let at = crate::subs::frame_at(session.now(), self.fps);
1738 (at >= c.start && at < c.end()).then(|| at - c.start)
1739 }
1740
1741 /// The speed the ramp runs at the playhead on the card's clip (or the clip's
1742 /// constant one without a ramp): what the bar holds for the next key until a
1743 /// hand moves it.
1744 pub(crate) fn ramp_default_speed(&self) -> Speed {
1745 let Some(clip) = self.speed_open else {
1746 return Speed::NORMAL;
1747 };
1748 let Some(c) = self
1749 .session
1750 .as_ref()
1751 .and_then(|s| s.lane_clips(clip.0).get(clip.1))
1752 else {
1753 return Speed::NORMAL;
1754 };
1755 match self.ramp_playhead(clip) {
1756 Some(rel) if !c.speed_keys.is_empty() => {
1757 engine::project::ramp_speed_at(&c.speed_keys, rel)
1758 }
1759 _ => c.speed,
1760 }
1761 }
1762
1763 /// Writes `keys` as the ramp of `clip` and its group -- one undo step -- and
1764 /// reseeks. Empty keys clear the ramp. A refusal (the longer clip would run into
1765 /// its neighbour) comes back in the engine's words, as the constant rate's does.
1766 fn write_ramp(&mut self, clip: (Lane, usize), keys: &[engine::project::SpeedKey], cx: &mut Context<Self>) {
1767 let Some(session) = &mut self.session else {
1768 return;
1769 };
1770 let before = session.lane_clips(clip.0).get(clip.1).map(|c| c.frames());
1771 match session.set_speed_ramp(clip.0, clip.1, keys) {
1772 Ok(()) => {
1773 let after = self.session.as_ref().and_then(|s| s.lane_clips(clip.0).get(clip.1)).map(|c| c.frames());
1774 self.mark_dirty();
1775 self.reset_after_reseek();
1776 if self.speed_open == Some(clip) {
1777 self.speed_ramp_mode = !keys.is_empty() || self.speed_ramp_mode;
1778 self.ramp_key_speed = None;
1779 }
1780 // A ramp that runs shorter leaves its space empty: nothing ripples, so say so.
1781 if let (Some(before), Some(after)) = (before, after)
1782 && after < before
1783 {
1784 let secs = f64::from(after) / self.fps.max(1.);
1785 self.notify_user(
1786 format!("Shortened to {secs:.1} s. The space after it is empty: Close gap removes it.").into(),
1787 );
1788 }
1789 }
1790 Err(e) => self.notify_user(e.to_string().into()),
1791 }
1792 cx.notify();
1793 }
1794
1795 /// Lays a ramp shape across the target clip's length on the timeline.
1796 pub(crate) fn set_ramp_preset(&mut self, preset: RampPreset, cx: &mut Context<Self>) {
1797 if self.exporting().is_some() {
1798 return;
1799 }
1800 let Some(clip) = self.ramp_target(cx) else {
1801 return;
1802 };
1803 let frames = self
1804 .session
1805 .as_ref()
1806 .and_then(|s| s.lane_clips(clip.0).get(clip.1))
1807 .map_or(0, Clip::frames);
1808 match preset.keys(frames) {
1809 Some(keys) => {
1810 self.write_ramp(clip, &keys, cx);
1811 if self.speed_open == Some(clip) {
1812 self.speed_ramp_mode = true;
1813 }
1814 }
1815 None => {
1816 self.notify_user("This clip is too short for that speed ramp".into());
1817 cx.notify();
1818 }
1819 }
1820 }
1821
1822 /// Puts a key at the playhead on the target clip: the bar's speed when the card
1823 /// is up, else the speed the ramp already runs there. The first key on a clip with
1824 /// no ramp is joined by one at its start holding the constant speed, so the ramp
1825 /// eases into the key instead of being a constant at it.
1826 pub(crate) fn add_ramp_key(&mut self, cx: &mut Context<Self>) {
1827 if self.exporting().is_some() {
1828 return;
1829 }
1830 let Some(clip) = self.ramp_target(cx) else {
1831 return;
1832 };
1833 let Some(rel) = self.ramp_playhead(clip) else {
1834 self.notify_user("Put the playhead on the clip to key its speed there".into());
1835 cx.notify();
1836 return;
1837 };
1838 let Some(c) = self
1839 .session
1840 .as_ref()
1841 .and_then(|s| s.lane_clips(clip.0).get(clip.1))
1842 .cloned()
1843 else {
1844 return;
1845 };
1846 let speed = match self.speed_open == Some(clip) && self.speed_ramp_mode {
1847 true => self.card_speed(),
1848 false => match c.speed_keys.is_empty() {
1849 true => c.speed,
1850 false => engine::project::ramp_speed_at(&c.speed_keys, rel),
1851 },
1852 };
1853 let base = match c.speed_keys.is_empty() && rel > 0 {
1854 true => vec![engine::project::SpeedKey { at: 0, speed: c.speed }],
1855 false => c.speed_keys.clone(),
1856 };
1857 match ramp_with_key(&base, rel, speed) {
1858 Some(keys) => self.write_ramp(clip, &keys, cx),
1859 None => {
1860 self.notify_user(
1861 format!("A speed ramp holds at most {} keys", engine::project::MAX_SPEED_KEYS)
1862 .into(),
1863 );
1864 cx.notify();
1865 }
1866 }
1867 }
1868
1869 /// Takes the `i`th key off the card's ramp.
1870 pub(crate) fn remove_ramp_key(&mut self, i: usize, cx: &mut Context<Self>) {
1871 let Some(clip) = self.speed_open else {
1872 return;
1873 };
1874 let Some(c) = self
1875 .session
1876 .as_ref()
1877 .and_then(|s| s.lane_clips(clip.0).get(clip.1))
1878 else {
1879 return;
1880 };
1881 let keys = ramp_without_key(&c.speed_keys, i);
1882 self.write_ramp(clip, &keys, cx);
1883 }
1884
1885 /// Moves the `i`th key's speed by `steps` quarters.
1886 pub(crate) fn step_ramp_key(&mut self, i: usize, steps: i32, cx: &mut Context<Self>) {
1887 let Some(clip) = self.speed_open else {
1888 return;
1889 };
1890 let Some(c) = self
1891 .session
1892 .as_ref()
1893 .and_then(|s| s.lane_clips(clip.0).get(clip.1))
1894 else {
1895 return;
1896 };
1897 let keys = ramp_key_stepped(&c.speed_keys, i, steps);
1898 self.write_ramp(clip, &keys, cx);
1899 }
1900
1901 /// Takes the target clip's speed ramp off: its constant speed comes back.
1902 pub(crate) fn clear_ramp(&mut self, cx: &mut Context<Self>) {
1903 if self.exporting().is_some() {
1904 return;
1905 }
1906 let Some(clip) = self.ramp_target(cx) else {
1907 return;
1908 };
1909 let had = self
1910 .session
1911 .as_ref()
1912 .and_then(|s| s.lane_clips(clip.0).get(clip.1))
1913 .is_some_and(|c| !c.speed_keys.is_empty());
1914 if had {
1915 self.write_ramp(clip, &[], cx);
1916 }
1917 if self.speed_open == Some(clip) {
1918 self.speed_ramp_mode = false;
1919 self.ramp_key_speed = None;
1920 }
1921 cx.notify();
1922 }
1923
1924 /// Starts an auto reframe of the clip: its subject is found on a thread of its
1925 /// own ([`engine::reframe::analyse`]), shown as a percent in the status bar, and
1926 /// [`Self::poll_reframe`] writes the keys -- one undo step -- when it lands.
1927 pub(crate) fn start_reframe(&mut self, lane: Lane, idx: usize, cx: &mut Context<Self>) {
1928 if self.reframe_run.is_some() {
1929 self.notify_user("Auto reframe is already measuring a clip".into());
1930 cx.notify();
1931 return;
1932 }
1933 let Some(job) = self.session.as_ref().and_then(|s| s.reframe_job(lane, idx)) else {
1934 self.notify_user("Auto reframe: select a video clip".into());
1935 cx.notify();
1936 return;
1937 };
1938 let run = ReframeRun {
1939 lane,
1940 idx,
1941 job: job.clone(),
1942 progress: Arc::new(AtomicU32::new(0)),
1943 cancel: Arc::new(AtomicBool::new(false)),
1944 result: Arc::new(Mutex::new(None)),
1945 };
1946 let (progress, cancel, result) = (run.progress.clone(), run.cancel.clone(), run.result.clone());
1947 std::thread::spawn(move || {
1948 let r = engine::reframe::analyse(&job.path, job.lo, job.hi, &progress, &cancel).map_err(|e| e.to_string());
1949 if let Ok(mut slot) = result.lock() {
1950 *slot = Some(r);
1951 }
1952 });
1953 self.reframe_run = Some(run);
1954 cx.notify();
1955 }
1956
1957 /// Auto reframe of the selected clip ([`ActionId::Reframe`]).
1958 pub(crate) fn reframe_selected(&mut self, cx: &mut Context<Self>) {
1959 match self.selected.anchor() {
1960 Some((lane, idx)) => self.start_reframe(lane, idx, cx),
1961 None => {
1962 self.notify_user("Auto reframe: select a video clip".into());
1963 cx.notify();
1964 }
1965 }
1966 }
1967
1968 /// Stops the running reframe measurement.
1969 pub(crate) fn cancel_reframe(&mut self, cx: &mut Context<Self>) {
1970 if let Some(run) = &self.reframe_run {
1971 run.cancel.store(true, Ordering::Relaxed);
1972 }
1973 cx.notify();
1974 }
1975
1976 /// The status bar's words for a running reframe, `Reframing 42%`.
1977 pub(crate) fn reframe_words(&self) -> Option<String> {
1978 let run = self.reframe_run.as_ref()?;
1979 Some(format!("Reframing {}%", run.progress.load(Ordering::Relaxed) / 10))
1980 }
1981
1982 /// Lands a finished reframe: the keys are written if the clip is still the one
1983 /// that was measured, and a failure or a stop is said once.
1984 pub(crate) fn poll_reframe(&mut self) {
1985 let Some(run) = &self.reframe_run else { return };
1986 let Some(outcome) = run.result.lock().ok().and_then(|mut r| r.take()) else { return };
1987 let run = self.reframe_run.take().expect("checked above");
1988 let said = match outcome {
1989 Err(e) if run.cancel.load(Ordering::Relaxed) => {
1990 let _ = e;
1991 "Auto reframe stopped".to_string()
1992 }
1993 Err(e) => format!("Auto reframe failed: {e}"),
1994 Ok(subject) => {
1995 let Some(session) = &mut self.session else { return };
1996 // The clip may have moved or changed while it was measured.
1997 let same = session
1998 .reframe_job(run.lane, run.idx)
1999 .is_some_and(|j| j.path == run.job.path && (j.lo, j.hi) == (run.job.lo, run.job.hi) && j.target.in_frame == run.job.target.in_frame);
2000 if !same {
2001 "Auto reframe: the clip changed while it was measured; run it again".to_string()
2002 } else {
2003 let keys = engine::reframe::keys(&subject, &run.job.target, engine::reframe::DEFAULT_SMOOTHNESS);
2004 let n = keys.len();
2005 if session.apply_reframe(run.lane, run.idx, keys) {
2006 self.reframed = Some((run.lane, run.idx, n));
2007 self.mark_dirty();
2008 self.reset_after_reseek();
2009 format!("Reframed to the project with {n} key{} (Ctrl+Z undoes it)", if n == 1 { "" } else { "s" })
2010 } else {
2011 "Auto reframe: no change — the clip is already framed this way".to_string()
2012 }
2013 }
2014 }
2015 };
2016 self.notify_user(said.into());
2017 }
2018
2019 /// Turns the clip's stabilisation on with `st`, or off with `None`, as one
2020 /// undo step. Turning it on starts its analysis in the background, and the
2021 /// clip is waited on ([`Self::poll_stabilise`]) until it lands.
2022 pub(crate) fn write_stabilise(
2023 &mut self,
2024 lane: Lane,
2025 idx: usize,
2026 st: Option<engine::stabilise::Stabilise>,
2027 cx: &mut Context<Self>,
2028 ) {
2029 let Some(session) = &mut self.session else {
2030 return;
2031 };
2032 if session.set_stabilise(lane, idx, st) {
2033 self.mark_dirty();
2034 self.reset_after_reseek();
2035 }
2036 self.wait_stabilise(lane, idx);
2037 cx.notify();
2038 }
2039
2040 /// Sets how the clip's interlaced source is deinterlaced (one undo step).
2041 pub(crate) fn write_deinterlace(
2042 &mut self,
2043 lane: Lane,
2044 idx: usize,
2045 mode: engine::project::Deinterlace,
2046 cx: &mut Context<Self>,
2047 ) {
2048 if self.lane_locked_refusal(lane) {
2049 cx.notify();
2050 return;
2051 }
2052 let Some(session) = &mut self.session else {
2053 return;
2054 };
2055 if session.set_deinterlace(lane, idx, mode) {
2056 self.mark_dirty();
2057 }
2058 cx.notify();
2059 }
2060
2061 /// Starts (again, after a failure) the clip's analysis and waits on it.
2062 pub(crate) fn wait_stabilise(&mut self, lane: Lane, idx: usize) {
2063 let Some(session) = &self.session else {
2064 return;
2065 };
2066 if session.stabilise_of(lane, idx).is_none() {
2067 return;
2068 }
2069 if let (Some(range), Some(engine::stabilise::Status::Running(_))) =
2070 (session.stabilise_range(lane, idx), session.stabilise_start(lane, idx))
2071 && !self.stab_waiting.contains(&range)
2072 {
2073 self.stab_waiting.push(range);
2074 }
2075 }
2076
2077 /// Stops the clip's running analysis; the clip stays switched on and plays
2078 /// as it is until it is analysed.
2079 pub(crate) fn cancel_stabilise(&mut self, lane: Lane, idx: usize, cx: &mut Context<Self>) {
2080 if let Some(session) = &self.session {
2081 session.stabilise_cancel(lane, idx);
2082 }
2083 cx.notify();
2084 }
2085
2086 /// Lands every finished analysis: the picture is redrawn with its
2087 /// correction, and a failure is said once.
2088 pub(crate) fn poll_stabilise(&mut self) {
2089 if self.stab_waiting.is_empty() {
2090 return;
2091 }
2092 let mut landed = false;
2093 let mut said = Vec::new();
2094 self.stab_waiting.retain(|(path, lo, hi)| match engine::stabilise::status(path, *lo, *hi) {
2095 engine::stabilise::Status::Running(_) => true,
2096 engine::stabilise::Status::Ready => {
2097 landed = true;
2098 false
2099 }
2100 engine::stabilise::Status::Failed(e) => {
2101 said.push(format!("Stabilise stopped for {}: {e}", file_name(path)));
2102 false
2103 }
2104 engine::stabilise::Status::Missing => false,
2105 });
2106 if landed && let Some(session) = &mut self.session {
2107 session.stabilise_refresh();
2108 self.reset_after_reseek();
2109 }
2110 for text in said {
2111 self.notify_user(text.into());
2112 }
2113 }
2114
2115 /// One [`SPEED_STEP`] per keystroke, clamped to what a [`Speed`] can hold.
2116 pub(crate) fn nudge_speed(&mut self, steps: i32, cx: &mut Context<Self>) {
2117 let at = i32::from(self.card_speed().permille()) + steps * SPEED_STEP;
2118 self.set_speed(speed_at(at), cx);
2119 }
2120
2121 /// Where the pointer sits along the bar, as a rate: the left end is
2122 /// [`Speed::MIN`] and the right end [`Speed::MAX`], on a log scale, and
2123 /// snapped to the same [`SPEED_STEP`] grid the keys move on -- so a drag can
2124 /// land on exactly 1.00x and the same drag twice is one entry, not forty.
2125 /// `first` is the press: it takes the undo step the whole gesture rolls back
2126 /// to, and every sample after it is live -- the colour card's rule, for the
2127 /// colour card's reason.
2128 pub(crate) fn drag_speed(&mut self, x: Pixels, first: bool, cx: &mut Context<Self>) {
2129 let along = frac_along(x, self.speed_bar.get());
2130 // Held back while the worker is busy, the colour card's way and for a
2131 // sharper reason: a live rate also restarts the sound, so a sweep that
2132 // wrote every step would restart it forty times.
2133 let busy = self.seek_since.is_some();
2134 match stash_or_write(&mut self.pending_speed, speed_on_bar(along), first, busy) {
2135 Some(speed) => self.write_speed(speed, !first, cx),
2136 None => cx.notify(),
2137 }
2138 }
2139
2140 /// Writes what a slider drag held back, now that the worker has delivered.
2141 /// The gate is the frame that landed and never a timer: a 100 ms tick
2142 /// ([`SCRUB_GAP`]) says nothing about a reopen that costs half a second, and
2143 /// a drag gated on one would still queue opens nobody sees.
2144 ///
2145 /// Called again by the release, where readiness is beside the point: the
2146 /// value the hand let go on is owed whatever the worker is doing, and a
2147 /// gesture may not end on a sample that was dropped.
2148 pub(crate) fn flush_drag(&mut self, cx: &mut Context<Self>) {
2149 if let Some(params) = self.pending_color.take() {
2150 self.write_color(params, true, cx);
2151 }
2152 if let Some(speed) = self.pending_speed.take() {
2153 self.write_speed(speed, true, cx);
2154 }
2155 if let Some((_, hue, sat)) = self.pending_viz.take() {
2156 // Live, as the two above are: the press is the one step this
2157 // gesture rolls back to (`Player::write_viz_hs`).
2158 self.write_viz_hs(hue, sat, true, cx);
2159 }
2160 }
2161
2162 /// Opens the silence card on the clip to be scanned: the selected one, or
2163 /// -- with nothing selected -- the clip the picture is coming from, which is
2164 /// the rule the speed card follows and what a person means by "this shot".
2165 /// Either half of a take will do: both halves of an A/V take name the same
2166 /// file and play the same source frames, which is the whole of what a scan
2167 /// is of ([`ScanKey`]).
2168 ///
2169 /// The card is up on the next frame whatever the file is: a still is
2170 /// refused by name here, where the answer costs a look at the path, and
2171 /// everything the decoder has to open the file to know -- a track that is
2172 /// not there, a read that fails -- is refused the same way when the scan
2173 /// lands, because a fifty-second decode is not a thing to open a card
2174 /// behind ([`Player::start_silence_scan`]).
2175 pub(crate) fn open_silence(&mut self, cx: &mut Context<Self>) {
2176 if self.exporting().is_some() {
2177 return;
2178 }
2179 let Some(session) = &self.session else {
2180 self.notify_user("Nothing to scan — no file open".into());
2181 cx.notify();
2182 return;
2183 };
2184 // A caption the hand is on names the sound its group plays: the card
2185 // scans that half. A caption with no sound behind it -- alone, or
2186 // grouped with clips that have none -- is a scan with nothing to hear,
2187 // and it says so instead of returning without a word.
2188 let anchor = match self
2189 .selected
2190 .anchor()
2191 .or_else(|| session.video_clip_at(session.now()))
2192 {
2193 Some((lane, idx)) if lane.kind == LaneKind::Subtitle => {
2194 match caption_media_half(session, (lane, idx), LaneKind::Audio) {
2195 Some(half) => Some(half),
2196 None => {
2197 self.notify_user(
2198 "Nothing to scan — a caption has no sound of its own".into(),
2199 );
2200 cx.notify();
2201 return;
2202 }
2203 }
2204 }
2205 other => other,
2206 };
2207 match anchor.map(|clip| audio_half(session, clip)) {
2208 Some((lane, idx)) => {
2209 let found = self.session.as_ref().and_then(|session| {
2210 let clip = session.lane_clips(lane).get(idx)?.clone();
2211 Some((session.sources().get(clip.source)?.clone(), clip))
2212 });
2213 // A still is asked *before* the decoder is: handing a png to the
2214 // mp4 demuxer answers "a box with a larger size than it", which
2215 // is a true sentence about a container and nothing a person can
2216 // act on. A picture has no sound for the same reason a silent
2217 // video has none, so it is refused in the same words.
2218 let Some((source, clip)) = found else {
2219 cx.notify();
2220 return;
2221 };
2222 if engine::is_image(&source.path) {
2223 self.notify_user(unscannable(lane, idx, &source.path).into());
2224 cx.notify();
2225 return;
2226 }
2227 // One card at a time -- `close_card`'s own rule. This clears
2228 // `silence_open` too when the same clip is reopened; the
2229 // marks it drops come back below from the levels cache
2230 // (`scan_plan`/`silence_cached`), which `close_card` never
2231 // touches.
2232 self.close_other_cards();
2233 self.silence_open = Some((lane, idx));
2234 // Nothing picked: the card works on the whole timeline, and says so.
2235 if self.selected.anchor().is_none() {
2236 self.silence_scope = Scope::Everything;
2237 }
2238 self.silence_field = 0;
2239 self.context_menu = None;
2240 // The clip's own range, not the file's: the scan reads what this
2241 // clip plays and nothing else, so a take cut in half costs half
2242 // the decode and finds only what is still on the timeline.
2243 let key = (
2244 source.path.clone(),
2245 source.audio_stream,
2246 clip.in_frame,
2247 clip.out_frame,
2248 );
2249 match scan_plan(
2250 // The whole-source background scan counts as "cached"
2251 // too: a card opened after import finds the levels a
2252 // repaint has already been decoding since the file
2253 // arrived ([`Player::cache_media`]), and `scan_silences`
2254 // is what slices this clip's stretch out of them.
2255 silence_cached(&self.silence_levels, &key),
2256 self.silence_scan.as_ref().map(|scan| &scan.key),
2257 &key,
2258 ) {
2259 ScanPlan::Marks => self.scan_silences(),
2260 ScanPlan::Start => self.start_silence_scan(key, cx),
2261 ScanPlan::Wait => {}
2262 }
2263 }
2264 None => self.notify_user("Nothing to scan — no clip under the playhead".into()),
2265 }
2266 cx.notify();
2267 }
2268
2269 /// Opens the mix card. `lane` is the row it lands on -- the track whose
2270 /// header was clicked -- and `None` starts at the top, which is what the
2271 /// stroke means.
2272 ///
2273 /// Nothing here is a clip's, so nothing is refused for want of a selection:
2274 /// a timeline with no audio track at all still has a limiter to set, and a
2275 /// fader on an empty track is the level the next take lands at.
2276 pub(crate) fn open_mix(&mut self, lane: Option<Lane>, cx: &mut Context<Self>) {
2277 if self.exporting().is_some() {
2278 return;
2279 }
2280 // One card at a time -- `close_card`'s own rule.
2281 self.close_other_cards();
2282 self.mix_open = true;
2283 self.reissue_mix_solo();
2284 self.mix_field = lane
2285 .and_then(|lane| self.mix_lanes().iter().position(|&l| l == lane))
2286 .unwrap_or(0);
2287 self.context_menu = None;
2288 // Param cards live in the Clip tab. Route every opening door here so a
2289 // lane header never opens a card behind Sources.
2290 self.dock_src_active = false;
2291 crate::ui::dock_stance::save(false);
2292 cx.notify();
2293 }
2294
2295 /// The audio tracks the card shows a fader for, top to bottom: *every* one
2296 /// of them, empty ones included -- what the timeline lays out, not what the
2297 /// mixer happens to open (`Project::audio_lanes` leaves an empty track out,
2298 /// and a fader that disappeared when a track was cleared would be a setting
2299 /// nobody could reach).
2300 pub(crate) fn mix_lanes(&self) -> Vec<Lane> {
2301 self.session.as_ref().map_or_else(Vec::new, |session| {
2302 session
2303 .lanes()
2304 .into_iter()
2305 .filter(|l| l.kind == LaneKind::Audio)
2306 .collect()
2307 })
2308 }
2309
2310 /// Moves the row the card has picked: a fader by [`MIX_DB_STEP`], the
2311 /// ceiling by the same, and the switch either way (a ring of two, like the
2312 /// silence card's unit row).
2313 ///
2314 /// Every one of them goes through the session, which hands it straight to
2315 /// the running mixer: what the ear hears while the arrow is held is the mix
2316 /// that is being set, and nothing is rebuilt to make that true -- no reseek,
2317 /// so no `reset_after_reseek` and no blink in the picture behind the card
2318 /// ([`engine::PlaybackSession::set_lane_gain_db`]).
2319 pub(crate) fn nudge_mix(&mut self, steps: i32, cx: &mut Context<Self>) {
2320 let lanes = self.mix_lanes();
2321 if self.session.is_none() {
2322 return;
2323 }
2324 let Some(session) = self.session.as_mut() else {
2325 return;
2326 };
2327 // The arm rides the door's answer, not the press: a fader already
2328 // against its wall, a ceiling already at its clamp and a limiter
2329 // switch that did not move are *not* edits, and `set_lane_gain_db` /
2330 // `set_limiter` each answer `false` for exactly those (an unchanged
2331 // value). Arming before the ask lit the ledger's `unsaved` ghost,
2332 // wrote an autosave sidecar and put the close prompt up over a
2333 // project whose bytes had not moved.
2334 let took = match lanes.get(self.mix_field) {
2335 Some(&lane) => {
2336 let at = session.lane_gain_db(lane) + steps as f32 * MIX_DB_STEP;
2337 session.set_lane_gain_db(lane, at)
2338 }
2339 None => {
2340 let limiter = session.limiter();
2341 let at = match self.mix_field - lanes.len() {
2342 0 => Limiter {
2343 on: limiter.on,
2344 ..limiter
2345 }
2346 .with_ceiling(limiter.ceiling_db + steps as f32 * MIX_DB_STEP),
2347 _ => Limiter {
2348 on: !limiter.on,
2349 ..limiter
2350 },
2351 };
2352 session.set_limiter(at)
2353 }
2354 };
2355 if took {
2356 self.mark_dirty();
2357 }
2358 cx.notify();
2359 }
2360
2361 /// The transport's stereo master meter for this frame (left and right, and whether the clip
2362 /// lamp is lit). Reads the stereo peaks only, so it and the mix card's meters (which read the
2363 /// mono master and the lane peaks) never starve each other.
2364 pub(crate) fn master_reading(&self, now: Instant) -> ([MixMeter; 2], bool) {
2365 let session = self.session.as_ref();
2366 let playing = session.is_some_and(|s| s.is_playing());
2367 let mut panel = self.mix_panel.borrow_mut();
2368 let meter = &mut panel.master_meter;
2369 meter.step(
2370 playing,
2371 || session.map_or([0.; 2], |s| s.master_peaks_lr()),
2372 now,
2373 );
2374 (meter.lr, meter.clipped(now))
2375 }
2376
2377
2378 /// Reads the mix card's meters for one frame: the peaks the sound reached
2379 /// since the last read, fed into each lane's meter. Paused or stopped, every
2380 /// meter falls to silence at once, so a paused card never holds a level.
2381 pub(crate) fn mix_reading(&self, now: Instant) -> MixReading {
2382 let lanes = self.mix_lanes();
2383 let session = self.session.as_ref();
2384 let playing = session.is_some_and(|s| s.is_playing());
2385 let levels = session.map(|s| s.levels());
2386 let sounding: Vec<Lane> = session.map_or_else(Vec::new, |s| {
2387 s.lanes()
2388 .into_iter()
2389 .filter(|&l| l.kind == LaneKind::Audio && !s.lane_clips(l).is_empty())
2390 .collect()
2391 });
2392 let mut panel = self.mix_panel.borrow_mut();
2393 let panel = &mut *panel;
2394 let mut strips = Vec::with_capacity(lanes.len());
2395 for &lane in &lanes {
2396 let peak = match (levels.as_ref(), meter_slot_in(&sounding, lane)) {
2397 (Some(levels), Some(at)) => levels.lanes.get(at).copied().unwrap_or(0.),
2398 _ => 0.,
2399 };
2400 let meter = lane_entry(&mut panel.meters, lane);
2401 feed_meter(meter, playing, peak, now);
2402 let bar = lane_entry(&mut panel.gain_bars, lane).clone();
2403 strips.push(MixStrip {
2404 lane,
2405 meter: *meter,
2406 bar,
2407 });
2408 }
2409 feed_meter(
2410 &mut panel.master,
2411 playing,
2412 levels.as_ref().map_or(0., |l| l.master),
2413 now,
2414 );
2415 MixReading {
2416 strips,
2417 master: panel.master,
2418 ceiling_bar: panel.ceiling_bar.clone(),
2419 }
2420 }
2421
2422 /// The bar a fader's slider is read against, as the card last drew it.
2423 fn mix_gain_bar(&self, lane: Lane) -> Rc<Cell<Bounds<Pixels>>> {
2424 self.mix_panel
2425 .borrow()
2426 .gain_bars
2427 .iter()
2428 .find(|(l, _)| *l == lane)
2429 .map(|(_, bar)| bar.clone())
2430 .unwrap_or_default()
2431 }
2432
2433 /// The bar a dynamics slider is read against, as the card last drew it.
2434 pub(crate) fn mix_voice_bar(&self, lane: Lane, param: VoiceParam) -> Rc<Cell<Bounds<Pixels>>> {
2435 let mut panel = self.mix_panel.borrow_mut();
2436 match panel.voice_bars.iter().find(|(k, _)| *k == (lane, param)) {
2437 Some((_, bar)) => bar.clone(),
2438 None => {
2439 let bar: Rc<Cell<Bounds<Pixels>>> = Default::default();
2440 panel.voice_bars.push(((lane, param), bar.clone()));
2441 bar
2442 }
2443 }
2444 }
2445
2446 /// Whether a lane's dynamics section is unfolded.
2447 pub(crate) fn mix_voice_open(&self, lane: Lane) -> bool {
2448 self.mix_panel.borrow().voice_open.contains(&lane)
2449 }
2450
2451 /// Unfolds or folds a lane's dynamics section.
2452 pub(crate) fn toggle_voice_section(&mut self, lane: Lane, cx: &mut Context<Self>) {
2453 let mut panel = self.mix_panel.borrow_mut();
2454 match panel.voice_open.iter().position(|&l| l == lane) {
2455 Some(at) => {
2456 panel.voice_open.remove(at);
2457 }
2458 None => panel.voice_open.push(lane),
2459 }
2460 drop(panel);
2461 cx.notify();
2462 }
2463
2464 /// Sets one dynamics slider; `true` when it moved. The processor keeps its
2465 /// on/off state: a slider is a setting, the switch beside it is the bypass.
2466 pub(crate) fn set_voice_param(&mut self, lane: Lane, param: VoiceParam, v: f32) -> bool {
2467 match self.session.as_mut() {
2468 Some(session) => {
2469 let mut fx = session.lane_voice(lane);
2470 param.set(&mut fx, v);
2471 session.set_lane_voice(lane, fx)
2472 }
2473 None => false,
2474 }
2475 }
2476
2477 /// Switches one processor on or off, keeping its settings. The noise
2478 /// reduction learns its profile the first time it is switched on.
2479 pub(crate) fn toggle_voice_proc(&mut self, lane: Lane, which: VoiceProc, cx: &mut Context<Self>) {
2480 if self.exporting().is_some() {
2481 return;
2482 }
2483 let Some(session) = self.session.as_mut() else {
2484 return;
2485 };
2486 let mut fx = session.lane_voice(lane);
2487 let on = !which.is_on(&fx);
2488 match which {
2489 VoiceProc::Gate => fx.gate.on = on,
2490 VoiceProc::Comp => fx.comp.on = on,
2491 VoiceProc::Deess => fx.deess.on = on,
2492 VoiceProc::Nr => {
2493 if on && fx.nr.profile.is_empty() {
2494 match session.learn_noise(lane, None) {
2495 Ok(learned) => fx.nr.profile = learned.profile,
2496 Err(e) => {
2497 self.notify_user(format!("Noise reduction stays off — {e}").into());
2498 cx.notify();
2499 return;
2500 }
2501 }
2502 }
2503 fx.nr.on = on;
2504 }
2505 }
2506 if session.set_lane_voice(lane, fx) {
2507 self.mark_dirty();
2508 }
2509 cx.notify();
2510 }
2511
2512 /// The one-click **Clean voice**: gate, noise reduction (its profile learned
2513 /// from the lane's quietest stretch), compressor and de-esser at `strength`,
2514 /// as one undo step ([`engine::voice::VoiceFx::clean_voice`], the same preset
2515 /// the MCP tool sets).
2516 pub(crate) fn clean_mix_voice(
2517 &mut self,
2518 lane: Lane,
2519 strength: engine::voice::Strength,
2520 cx: &mut Context<Self>,
2521 ) {
2522 if self.exporting().is_some() {
2523 return;
2524 }
2525 let Some(session) = self.session.as_mut() else {
2526 return;
2527 };
2528 if lane.kind != LaneKind::Audio || session.lane_clips(lane).is_empty() {
2529 self.notify_user(format!("Nothing to clean — {} holds no sound", lane.label()).into());
2530 cx.notify();
2531 return;
2532 }
2533 // No quiet stretch to learn from is not a failure: the rest still applies.
2534 let learned = session.learn_noise(lane, None).ok();
2535 let fx = engine::voice::VoiceFx::clean_voice(
2536 strength,
2537 learned.as_ref().map(|l| l.profile.clone()).unwrap_or_default(),
2538 learned.as_ref().map(|l| l.noise_db),
2539 );
2540 let took = session.set_lane_voice(lane, fx);
2541 let message = match (took, learned.is_some()) {
2542 (false, _) => format!("{} is already clean at {}", lane.label(), strength.name()),
2543 (true, true) => format!("Cleaned {} ({})", lane.label(), strength.name()),
2544 (true, false) => format!(
2545 "Cleaned {} ({}) — no quiet stretch found, noise reduction left off",
2546 lane.label(),
2547 strength.name()
2548 ),
2549 };
2550 if took {
2551 self.mark_dirty();
2552 }
2553 self.notify_user(message.into());
2554 cx.notify();
2555 }
2556
2557 /// The audio lane the Clean voice command works on: the selected clip's if
2558 /// it is sound, else the mix card's picked strip, else the first track with
2559 /// something on it.
2560 pub(crate) fn voice_target_lane(&self) -> Option<Lane> {
2561 let session = self.session.as_ref()?;
2562 if let Some((lane, _)) = self.selected.anchor().filter(|(l, _)| l.kind == LaneKind::Audio) {
2563 return Some(lane);
2564 }
2565 let lanes = self.mix_lanes();
2566 if self.mix_open
2567 && let Some(&lane) = lanes.get(self.mix_field)
2568 {
2569 return Some(lane);
2570 }
2571 lanes.into_iter().find(|&l| !session.lane_clips(l).is_empty())
2572 }
2573
2574 /// Mutes or unmutes a track. Saved with the project, one undo step.
2575 pub(crate) fn toggle_mix_mute(&mut self, lane: Lane, cx: &mut Context<Self>) {
2576 if self.exporting().is_some() {
2577 return;
2578 }
2579 let changed = match self.session.as_mut() {
2580 Some(session) => {
2581 let on = !session.lane_muted(lane);
2582 session.set_lane_muted(lane, on)
2583 }
2584 None => false,
2585 };
2586 if changed {
2587 self.mark_dirty();
2588 }
2589 cx.notify();
2590 }
2591
2592 /// Solos or un-solos a track for listening. Not saved and not an undo step:
2593 /// the session is handed the set, and nothing else is touched.
2594 pub(crate) fn toggle_mix_solo(&mut self, lane: Lane, cx: &mut Context<Self>) {
2595 self.mix_solo = solo_toggled(&self.mix_solo, lane);
2596 self.push_mix_solo();
2597 cx.notify();
2598 }
2599
2600 /// Hands the session the solo set. A lane that is gone, or that is not an
2601 /// audio lane, is left out, so a stale handle cannot silence the wrong track.
2602 fn push_mix_solo(&mut self) {
2603 if let Some(session) = self.session.as_mut() {
2604 session.set_solo(&self.mix_solo);
2605 }
2606 }
2607
2608 /// Re-issues the solo set after the lanes may have changed under it: a
2609 /// handle names a position, so one whose lane has gone is dropped first.
2610 pub(crate) fn reissue_mix_solo(&mut self) {
2611 if let Some(session) = self.session.as_ref() {
2612 let lanes = session.lanes();
2613 self.mix_solo.retain(|l| lanes.contains(l));
2614 }
2615 self.push_mix_solo();
2616 }
2617
2618 /// A mix slider was pressed: the drag it starts, and the value under the press.
2619 pub(crate) fn press_mix(&mut self, drag: MixDrag, x: Pixels, cx: &mut Context<Self>) {
2620 if self.exporting().is_some() {
2621 return;
2622 }
2623 self.mix_field = match drag {
2624 MixDrag::Gain(lane) | MixDrag::Clip(lane, _) | MixDrag::Pitch(lane, _) => self
2625 .mix_lanes()
2626 .iter()
2627 .position(|&l| l == lane)
2628 .unwrap_or(0),
2629 MixDrag::Ceiling => self.mix_lanes().len(),
2630 MixDrag::Voice(lane, _) => self
2631 .mix_lanes()
2632 .iter()
2633 .position(|&l| l == lane)
2634 .unwrap_or(0),
2635 };
2636 self.mix_drag = Some(drag);
2637 self.drag_mix(x, cx);
2638 }
2639
2640 /// The held slider follows the pointer: a fader or the ceiling takes the
2641 /// value under `x` on its bar, and nothing is rebuilt to make it heard.
2642 pub(crate) fn drag_mix(&mut self, x: Pixels, cx: &mut Context<Self>) {
2643 let Some(drag) = self.mix_drag else {
2644 return;
2645 };
2646 let (bar, lo, hi) = match drag {
2647 MixDrag::Gain(lane) => (
2648 self.mix_gain_bar(lane),
2649 engine::project::MIN_GAIN_DB,
2650 engine::project::MAX_GAIN_DB,
2651 ),
2652 MixDrag::Clip(..) => (
2653 self.mix_panel.borrow().clip_bar.clone(),
2654 engine::project::MIN_CLIP_GAIN_DB,
2655 engine::project::MAX_CLIP_GAIN_DB,
2656 ),
2657 MixDrag::Pitch(..) => (
2658 self.mix_panel.borrow().pitch_bar.clone(),
2659 engine::project::MIN_CLIP_PITCH,
2660 engine::project::MAX_CLIP_PITCH,
2661 ),
2662 MixDrag::Ceiling => (
2663 self.mix_panel.borrow().ceiling_bar.clone(),
2664 Limiter::MIN_DB,
2665 Limiter::MAX_DB,
2666 ),
2667 MixDrag::Voice(lane, param) => {
2668 let (lo, hi, _) = param.range();
2669 (self.mix_voice_bar(lane, param), lo, hi)
2670 }
2671 };
2672 if let Some(fraction) = bar_fraction(bar.get(), x) {
2673 // The faders share the knee: the clip's volume reads and drags on the same curve as the track's.
2674 let at = match drag {
2675 MixDrag::Gain(_) | MixDrag::Clip(..) => gain_at(fraction, hi),
2676 _ => value_at(fraction, lo, hi),
2677 };
2678 let took = match drag {
2679 MixDrag::Gain(lane) => self.set_mix_gain(lane, at),
2680 MixDrag::Clip(lane, idx) => self.set_clip_volume(lane, idx, at),
2681 // Whole semitones, which is what is stored.
2682 MixDrag::Pitch(lane, idx) => self.set_clip_pitch_mix(lane, idx, at.round() as i32),
2683 MixDrag::Ceiling => self.set_mix_ceiling(at),
2684 MixDrag::Voice(lane, param) => self.set_voice_param(lane, param, at),
2685 };
2686 if took {
2687 self.mark_dirty();
2688 }
2689 }
2690 cx.notify();
2691 }
2692
2693 /// Lets go of a mix slider.
2694 pub(crate) fn release_mix(&mut self, cx: &mut Context<Self>) {
2695 self.mix_drag = None;
2696 // The card's pan fields are scrubbed here too, and a release over the card never reaches the root.
2697 self.pan_scrub_end(cx);
2698 cx.notify();
2699 }
2700
2701 /// Sets a track's fader; `true` when it moved.
2702 pub(crate) fn set_mix_gain(&mut self, lane: Lane, db: f32) -> bool {
2703 match self.session.as_mut() {
2704 Some(session) => session.set_lane_gain_db(lane, db),
2705 None => false,
2706 }
2707 }
2708
2709 /// Sets the selected clip's volume; `true` when it moved.
2710 pub(crate) fn set_clip_volume(&mut self, lane: Lane, idx: usize, db: f32) -> bool {
2711 match self.session.as_mut() {
2712 Some(session) => session.set_clip_gain(lane, idx, db),
2713 None => false,
2714 }
2715 }
2716
2717 /// Sets the selected clip's pitch in semitones; `true` when it moved.
2718 pub(crate) fn set_clip_pitch_mix(&mut self, lane: Lane, idx: usize, semitones: i32) -> bool {
2719 match self.session.as_mut() {
2720 Some(session) => session.set_clip_pitch(lane, idx, semitones as f32),
2721 None => false,
2722 }
2723 }
2724
2725 /// Sets the limiter's ceiling; `true` when it moved.
2726 pub(crate) fn set_mix_ceiling(&mut self, db: f32) -> bool {
2727 match self.session.as_mut() {
2728 Some(session) => {
2729 let limiter = session.limiter();
2730 session.set_limiter(limiter.with_ceiling(db))
2731 }
2732 None => false,
2733 }
2734 }
2735
2736 /// A fader or the ceiling back to its default, from its own Reset.
2737 pub(crate) fn reset_mix(&mut self, drag: MixDrag, cx: &mut Context<Self>) {
2738 let took = match drag {
2739 MixDrag::Gain(lane) => self.set_mix_gain(lane, 0.),
2740 MixDrag::Clip(lane, idx) => self.set_clip_volume(lane, idx, 0.),
2741 MixDrag::Pitch(lane, idx) => self.set_clip_pitch_mix(lane, idx, 0),
2742 MixDrag::Ceiling => self.set_mix_ceiling(Limiter::default().ceiling_db),
2743 MixDrag::Voice(lane, param) => {
2744 let at = param.get(&engine::voice::VoiceFx::default());
2745 self.set_voice_param(lane, param, at)
2746 }
2747 };
2748 if took {
2749 self.mark_dirty();
2750 }
2751 cx.notify();
2752 }
2753
2754 /// Opens the subtitle style card: the platform's font list, asked for
2755 /// once and kept while the card is up, and the size stepper beside it.
2756 /// Nothing here is a clip's or even the project's -- it never reaches the
2757 /// export, which never burns a cue into the picture -- so like the mix
2758 /// card it opens with no timeline required and nothing to refuse.
2759 /// Opens the settings page (three tabs -- PROJECT/EDITOR/EXPORT -- over
2760 /// whichever section is showing, `ui::settings_stance`): the one door for
2761 /// "edit project and editor settings" -- refused while an export is
2762 /// running, same as every other card here, since the exporting card owns
2763 /// this same modal slot (`oracle.rs` agrees: `ActionId::Settings` is `No`
2764 /// there too, for the same reason).
2765 pub(crate) fn open_settings(&mut self, cx: &mut Context<Self>) {
2766 if self.exporting().is_some() {
2767 return;
2768 }
2769 // One card at a time -- `close_card`'s own rule -- except the Export
2770 // tab, which is a tab: closing Settings lands back on it.
2771 let on_export = self.export_open;
2772 self.close_card();
2773 self.export_open = on_export;
2774 self.settings_open = true;
2775 self.context_menu = None;
2776 cx.notify();
2777 }
2778
2779 /// Which of the settings page's three tabs is showing -- the strip's one
2780 /// door, and the page's only piece of state that [`Self::close_card`]
2781 /// leaves alone, so a close and a reopen come back to the section a hand
2782 /// left rather than snapping back to PROJECT. Display state and nothing
2783 /// else: no row reads it, it writes no project value, and it therefore
2784 /// never lights the ledger or arms autosave -- picking a tab is not an
2785 /// edit, which is why this is a setter with no [`Self::mark_dirty`] in
2786 /// it, unlike every row the page carries that writes a value.
2787 pub(crate) fn set_settings_tab(&mut self, tab: SettingsTab, cx: &mut Context<Self>) {
2788 self.settings_tab = tab;
2789 // The keyboard's row is the showing tab's; a new tab starts at rest.
2790 self.settings_focus = None;
2791 cx.notify();
2792 }
2793
2794 pub(crate) fn open_subtitle_style(&mut self, cx: &mut Context<Self>) {
2795 // One card at a time -- `close_card`'s own rule.
2796 self.close_card();
2797 // Only the families a caption can be set in: a symbol, emoji, math or mono face is left out.
2798 let text = cx.text_system().clone();
2799 self.subtitle_fonts = cx
2800 .text_system()
2801 .all_font_names()
2802 .into_iter()
2803 .filter(|name| crate::ui::cards::substyle::family_face_ok(&text, name))
2804 .collect();
2805 self.subtitle_style_open = true;
2806 self.subtitle_style_field = 0;
2807 // A drag cut off by a close never saw its button come up.
2808 self.sub_dragging = false;
2809 self.sub_font_open = false;
2810 self.sub_font_query.clear();
2811 self.context_menu = None;
2812 cx.notify();
2813 }
2814
2815 /// Picks a family outright -- a click on a row, the card's rule for a
2816 /// list rather than a stepper. `None` is the top row, the platform's own
2817 /// choice, which is what a family nobody can spell as a fallback would
2818 /// leave silently wrong instead.
2819 pub(crate) fn set_sub_family(&mut self, family: Option<String>, cx: &mut Context<Self>) {
2820 self.sub_family = family;
2821 self.keep_subtitle_style(cx);
2822 }
2823
2824 /// One [`SUB_SIZE_STEP`] per keystroke or stepper press, clamped to
2825 /// [`SUB_SIZE_RANGE`].
2826 pub(crate) fn nudge_sub_size(&mut self, steps: i32, cx: &mut Context<Self>) {
2827 self.set_sub_size(self.sub_text + steps as f32 * SUB_SIZE_STEP, cx);
2828 }
2829
2830 /// Sets the size, clamped to [`SUB_SIZE_RANGE`], and keeps it.
2831 pub(crate) fn set_sub_size(&mut self, size: f32, cx: &mut Context<Self>) {
2832 self.sub_text = size.clamp(SUB_SIZE_RANGE.0, SUB_SIZE_RANGE.1);
2833 self.keep_subtitle_style(cx);
2834 }
2835
2836 /// A slider drag: the size follows the pointer on screen but is not kept
2837 /// until the button comes up ([`Self::end_sub_drag`]), so a sweep is one
2838 /// write to the file and not one per pixel.
2839 pub(crate) fn drag_sub_size(&mut self, x: Pixels, bar: Bounds<Pixels>, cx: &mut Context<Self>) {
2840 self.sub_text = sub_size_at(frac_along(x, bar));
2841 cx.notify();
2842 }
2843
2844 pub(crate) fn end_sub_drag(&mut self, cx: &mut Context<Self>) {
2845 if self.sub_dragging {
2846 self.sub_dragging = false;
2847 self.keep_subtitle_style(cx);
2848 }
2849 }
2850
2851 pub(crate) fn set_sub_outline(&mut self, outline: SubOutline, cx: &mut Context<Self>) {
2852 self.sub_outline = outline;
2853 self.keep_subtitle_style(cx);
2854 }
2855
2856 pub(crate) fn set_sub_boxed(&mut self, boxed: bool, cx: &mut Context<Self>) {
2857 self.sub_boxed = boxed;
2858 self.keep_subtitle_style(cx);
2859 }
2860
2861 pub(crate) fn set_sub_place(&mut self, place: SubPlace, cx: &mut Context<Self>) {
2862 self.sub_place = place;
2863 self.keep_subtitle_style(cx);
2864 }
2865
2866 /// A press on the highlight colour's hex field: it opens for typing with all of it selected.
2867 pub(crate) fn begin_sub_highlight_hex(&mut self, cx: &mut Context<Self>) {
2868 self.commit_gen_hex(cx);
2869 let [r, g, b] = self.session.as_ref().map(|s| s.caption_style()).unwrap_or_default().highlight;
2870 let rgb = (u32::from(r) << 16) | (u32::from(g) << 8) | u32::from(b);
2871 self.gen_hex = Some((
2872 crate::player::generators::GenPaint::SubHighlight,
2873 crate::player::text_field::TextField::selected(crate::ui::kit::hex_text(rgb)),
2874 ));
2875 cx.notify();
2876 }
2877
2878 /// Writes the typed highlight colour (`#RRGGBB`, `RRGGBB` or `#RGB`) as the caption style's own,
2879 /// exactly as typed. Anything else keeps the old colour and says so.
2880 pub(crate) fn commit_sub_highlight_hex(&mut self, text: &str, cx: &mut Context<Self>) {
2881 match crate::ui::kit::parse_hex(text) {
2882 Some(c) => self.edit_caption_style(|cs| cs.highlight = [(c >> 16) as u8, (c >> 8) as u8, c as u8], cx),
2883 None => {
2884 self.notify_user("A colour is six hex digits, such as FFD600 — kept the old one".into());
2885 cx.notify();
2886 }
2887 }
2888 }
2889
2890 /// Changes the project's caption style (the animation a burn draws) with `f`: one undo
2891 /// step, and the project is dirty. Nothing without a project open.
2892 pub(crate) fn edit_caption_style(
2893 &mut self,
2894 f: impl FnOnce(&mut engine::captionanim::CaptionStyle),
2895 cx: &mut Context<Self>,
2896 ) {
2897 if let Some(session) = &mut self.session {
2898 let mut cs = session.caption_style();
2899 f(&mut cs);
2900 if session.set_caption_style(cs) {
2901 self.mark_dirty();
2902 }
2903 }
2904 cx.notify();
2905 }
2906
2907 /// The arrow keys on the picked row: left and right move the size, walk
2908 /// the outline, or flip the box or the place. Families and the default
2909 /// have no step, only a pick.
2910 pub(crate) fn step_sub_field(&mut self, dir: i32, cx: &mut Context<Self>) {
2911 match self.subtitle_style_field {
2912 SUB_ROW_SIZE => self.nudge_sub_size(dir, cx),
2913 SUB_ROW_OUTLINE => self.set_sub_outline(self.sub_outline.step(dir), cx),
2914 SUB_ROW_BOX => self.set_sub_boxed(!self.sub_boxed, cx),
2915 SUB_ROW_PLACE => self.set_sub_place(
2916 match self.sub_place {
2917 SubPlace::Bottom => SubPlace::Top,
2918 SubPlace::Top => SubPlace::Bottom,
2919 },
2920 cx,
2921 ),
2922 SUB_ROW_ANIM => self.edit_caption_style(
2923 |cs| {
2924 use engine::captionanim::CaptionAnim;
2925 let all = CaptionAnim::ALL;
2926 let at = all.iter().position(|a| *a == cs.anim).unwrap_or(0) as i32;
2927 cs.anim = all[(at + dir).rem_euclid(all.len() as i32) as usize];
2928 },
2929 cx,
2930 ),
2931 SUB_ROW_HIGHLIGHT => self.edit_caption_style(
2932 |cs| {
2933 let at = HIGHLIGHT_SWATCHES.iter().position(|(_, c)| *c == cs.highlight);
2934 let n = HIGHLIGHT_SWATCHES.len() as i32;
2935 let next = at.map_or(0, |a| (a as i32 + dir).rem_euclid(n) as usize);
2936 cs.highlight = HIGHLIGHT_SWATCHES[next].1;
2937 },
2938 cx,
2939 ),
2940 SUB_ROW_HL_BOX => self.edit_caption_style(|cs| cs.hl_box = !cs.hl_box, cx),
2941 SUB_ROW_UPPERCASE => self.edit_caption_style(|cs| cs.uppercase = !cs.uppercase, cx),
2942 SUB_ROW_WORDS => self.edit_caption_style(
2943 |cs| {
2944 let max = i32::from(engine::captionanim::MAX_WORDS_PER_LINE);
2945 cs.words_per_line = (i32::from(cs.words_per_line) + dir).clamp(0, max) as u8;
2946 },
2947 cx,
2948 ),
2949 _ => {}
2950 }
2951 }
2952
2953 /// Writes the style to disk and repaints: every change to any field
2954 /// goes through here, so the file on disk and the plate on screen never
2955 /// disagree about which session's edit is in force.
2956 pub(crate) fn keep_subtitle_style(&mut self, cx: &mut Context<Self>) {
2957 let style = SubStyle {
2958 family: self.sub_family.clone(),
2959 size: self.sub_text,
2960 outline: self.sub_outline,
2961 boxed: self.sub_boxed,
2962 place: self.sub_place,
2963 };
2964 if let Err(e) = save_subtitle_style(&style) {
2965 let path = subtitle_style_path();
2966 self.notify_user(
2967 format!(
2968 "Subtitle style could not be kept — {} — {e}",
2969 path.display()
2970 )
2971 .into(),
2972 );
2973 }
2974 cx.notify();
2975 }
2976
2977 /// Closes it and drops the preview with it: marks left on the lane after
2978 /// the card is gone would name frames the next edit has already moved.
2979 pub(crate) fn close_silence(&mut self) {
2980 self.silence_open = None;
2981 self.silence_marks.clear();
2982 self.cancel_silence_scan();
2983 }
2984
2985 /// Tells the worker nobody is waiting any more. It gives up at its next
2986 /// chunk and the levels it had are dropped: half a track is not an answer,
2987 /// and the flag stays set on the [`Arc`] the landing closure holds, which is
2988 /// how that closure knows to keep its hands off the card.
2989 pub(crate) fn cancel_silence_scan(&mut self) {
2990 if let Some(scan) = self.silence_scan.take() {
2991 scan.progress
2992 .cancel
2993 .store(true, std::sync::atomic::Ordering::Relaxed);
2994 }
2995 }
2996
2997 /// Hands the decode to a worker and returns at once -- the card is drawn by
2998 /// the very next frame, saying it is scanning. Fifty-one seconds on a 25 GB
2999 /// film is what this used to cost on the render thread, with the card
3000 /// marked open and nothing on screen.
3001 ///
3002 /// Whatever was scanning is cancelled first: one card, one scan, and the
3003 /// clip that has just been asked about is the one worth the disk.
3004 ///
3005 /// Only the clip's own `[in, out)` is read -- source frames over the
3006 /// project's rate, the same seconds [`engine::Project`] hands the decoder
3007 /// for playback -- so half a take is half a wait.
3008 pub(crate) fn start_silence_scan(&mut self, key: ScanKey, cx: &mut Context<Self>) {
3009 self.cancel_silence_scan();
3010 self.silence_marks.clear();
3011 let progress = Arc::new(engine::silence::Progress::default());
3012 let range = source_secs(&key, self.fps);
3013 let scan = cx.background_executor().spawn({
3014 let (key, progress) = (key.clone(), Arc::clone(&progress));
3015 async move { engine::silence::levels_with_progress(&key.0, key.1, range, &progress) }
3016 });
3017 let now = Instant::now();
3018 self.silence_scan = Some(SilenceScan {
3019 key: key.clone(),
3020 started: now,
3021 progress: Arc::clone(&progress),
3022 seen: 0,
3023 since: now,
3024 });
3025 cx.spawn(async move |this, cx| {
3026 let landed = scan.await;
3027 this.update(cx, |this, cx| {
3028 // Cancelled means the card moved on or closed: the levels are a
3029 // prefix of a track nobody asked about any more.
3030 if progress.cancel.load(std::sync::atomic::Ordering::Relaxed) {
3031 return;
3032 }
3033 this.silence_scan = None;
3034 match landed {
3035 Ok(Some(levels)) => {
3036 this.silence_levels.insert(key.clone(), Arc::new(levels));
3037 this.scan_silences();
3038 }
3039 // A source with no audio track is not one long silence: it
3040 // is a clip this card has nothing to say about, named so the
3041 // user knows which one it meant.
3042 Ok(None) => {
3043 if let Some((lane, idx)) = this.silence_open {
3044 this.notify_user(unscannable(lane, idx, &key.0).into());
3045 }
3046 this.close_silence();
3047 }
3048 Err(e) => {
3049 this.close_silence();
3050 this.notify_user(format!("Scan failed: {e}").into());
3051 }
3052 }
3053 cx.notify();
3054 })
3055 .ok();
3056 })
3057 .detach();
3058 cx.notify();
3059 }
3060
3061 /// Keeps the scanning line's stall clock, for [`Player::poll_import`]'s
3062 /// reason: sampled once per frame rather than while drawing.
3063 pub(crate) fn poll_silence(&mut self) {
3064 if let Some(scan) = &mut self.silence_scan {
3065 scan.poll();
3066 }
3067 }
3068
3069 /// Applies the settings to levels already in hand and replaces the preview
3070 /// -- never stacks on it. Arithmetic only: the decode is
3071 /// [`Player::start_silence_scan`]'s and happens once per source, so every
3072 /// run here is numbers already read, which is what makes moving a threshold
3073 /// feel like moving a slider. A source still being scanned has no marks yet
3074 /// and says so on the card.
3075 ///
3076 /// Changes nothing about the project: a preview is not an edit, and no undo
3077 /// step is spent until a button is pressed.
3078 pub(crate) fn scan_silences(&mut self) {
3079 let Some((lane, idx)) = self.silence_open else {
3080 return;
3081 };
3082 self.silence_marks.clear();
3083 // Copied out before anything is written back: the cache below lives on
3084 // the same struct the session does.
3085 let Some((clip, source)) = self.session.as_ref().and_then(|session| {
3086 let clip = session.lane_clips(lane).get(idx)?.clone();
3087 let source = session.sources().get(clip.source)?.clone();
3088 Some((clip, source))
3089 }) else {
3090 return;
3091 };
3092 // Nothing read yet: the worker is running and the card is drawing its
3093 // line. The marks arrive with the levels.
3094 //
3095 // The clip's own read first -- an on-demand scan already asked for
3096 // exactly this stretch -- and failing that, this clip's slice of the
3097 // whole-source background scan ([`Player::cache_media`]), which is
3098 // what makes the card answer at once for a file that arrived a
3099 // repaint or two ago.
3100 let key = (
3101 source.path.clone(),
3102 source.audio_stream,
3103 clip.in_frame,
3104 clip.out_frame,
3105 );
3106 let levels = match self.silence_levels.get(&key).cloned() {
3107 Some(levels) => Some(levels),
3108 None => self
3109 .silence_levels
3110 .get(&full_scan_key(&source.path, source.audio_stream))
3111 .map(|whole| {
3112 Arc::new(slice_whole_levels(
3113 whole,
3114 self.fps,
3115 clip.in_frame,
3116 clip.out_frame,
3117 ))
3118 }),
3119 };
3120 let Some(levels) = levels else {
3121 return;
3122 };
3123 // Keep-only flips what the applies act on: the *speech* between the
3124 // quiet stretches, so a cut removes the words and leaves the room
3125 // tone. Skipped when nothing was quiet -- inverting an empty scan
3126 // would mark the whole clip, the one press this card must never make
3127 // by accident.
3128 let quiet = engine::silence::regions(&levels, self.silence);
3129 let source = if self.silence_keep_only && !quiet.is_empty() {
3130 let duration = levels.len() as f64 / f64::from(engine::silence::WINDOWS_PER_SEC);
3131 engine::silence::invert(duration, &quiet)
3132 } else {
3133 quiet
3134 };
3135 self.silence_marks = engine::silence::timeline_regions(&clip, self.fps, &source);
3136 }
3137
3138 /// Keep-only-silence off and on, the marks going with it: the same scan,
3139 /// the complement of the quiet when it is on. A preview is not an edit,
3140 /// so a flip costs nothing and changes nothing but what is marked.
3141 pub(crate) fn toggle_silence_keep_only(&mut self) {
3142 self.silence_keep_only = !self.silence_keep_only;
3143 self.scan_silences();
3144 }
3145
3146 /// Moves the picked row by `steps` and re-runs the scan against it, so the
3147 /// marks on the lane are always what the numbers on the card say.
3148 pub(crate) fn nudge_silence(&mut self, steps: i32) {
3149 let secs = |at: f64| {
3150 (at + f64::from(steps) * SILENCE_SECS_STEP)
3151 .clamp(SILENCE_SECS_RANGE.0, SILENCE_SECS_RANGE.1)
3152 };
3153 match self.silence_field {
3154 // Round either way, like the fit policy's cycle: three choices are
3155 // a ring, not a range.
3156 0 => {
3157 let at = SCOPES.iter().position(|&s| s == self.silence_scope);
3158 let step = steps.rem_euclid(SCOPES.len() as i32) as usize;
3159 self.silence_scope = SCOPES[(at.unwrap_or(0) + step) % SCOPES.len()];
3160 }
3161 1 => {
3162 self.silence.threshold_db = (self.silence.threshold_db
3163 + steps as f32 * SILENCE_DB_STEP)
3164 .clamp(SILENCE_DB_RANGE.0, SILENCE_DB_RANGE.1)
3165 }
3166 // Two spellings of the same level, so either arrow flips it -- a
3167 // ring of two, like the scope row's.
3168 2 => self.silence_dbfs = !self.silence_dbfs,
3169 3 => self.silence.min_silence = secs(self.silence.min_silence),
3170 4 => self.silence.padding = secs(self.silence.padding),
3171 5 => self.silence.min_keep = secs(self.silence.min_keep),
3172 _ => {
3173 self.silence_factor =
3174 silence_rate(i32::from(self.silence_factor.permille()) + steps * SPEED_STEP)
3175 }
3176 }
3177 // Neither the scope nor the rate is part of the scan, but re-running is
3178 // cheap (the levels are cached) and one path is one place for the marks
3179 // to come from.
3180 self.scan_silences();
3181 }
3182
3183 /// The rows the silence card shows before its `More …` fold, in the order
3184 /// it lists them: the scope, the threshold, the forgiveness and the rate.
3185 pub(crate) const SILENCE_MAIN_ROWS: [usize; 4] = [0, 1, 3, 6];
3186 /// The rows behind the fold: the unit the level is read in, the padding and
3187 /// the sliver floor -- settings a first run does not need.
3188 pub(crate) const SILENCE_MORE_ROWS: [usize; 3] = [2, 4, 5];
3189 /// The fold's id in the panel-folds file ([`crate::ui::widgets::load_folds`]).
3190 pub(crate) const SILENCE_MORE_FOLD: &'static str = "silence-more";
3191
3192 /// Whether the card's `More …` fold is open.
3193 pub(crate) fn silence_more_open(&self) -> bool {
3194 self.folds.contains(Self::SILENCE_MORE_FOLD)
3195 }
3196
3197 /// The rows in the order the arrows walk them and the card draws them: the
3198 /// main rows, then the fold's when it is open.
3199 pub(crate) fn silence_fields(&self) -> Vec<usize> {
3200 const {
3201 assert!(
3202 Self::SILENCE_MAIN_ROWS.len() + Self::SILENCE_MORE_ROWS.len() == SILENCE_ROWS,
3203 "every silence row is on the card, main or behind the fold"
3204 )
3205 };
3206 let mut rows = Self::SILENCE_MAIN_ROWS.to_vec();
3207 if self.silence_more_open() {
3208 rows.extend(Self::SILENCE_MORE_ROWS);
3209 }
3210 rows
3211 }
3212
3213 /// Moves the picked row one place along [`Self::silence_fields`], wrapping.
3214 pub(crate) fn step_silence_field(&mut self, by: i32) {
3215 let rows = self.silence_fields();
3216 let at = rows
3217 .iter()
3218 .position(|&n| n == self.silence_field)
3219 .unwrap_or(0);
3220 let next = (at as i32 + by).rem_euclid(rows.len() as i32) as usize;
3221 self.silence_field = rows[next];
3222 }
3223
3224 /// Opens or closes the fold and saves it with the other panels' folds. A
3225 /// picked row behind the fold hands the arrows back to the first row.
3226 pub(crate) fn toggle_silence_more(&mut self, cx: &mut Context<Self>) {
3227 if !self.folds.remove(Self::SILENCE_MORE_FOLD) {
3228 self.folds.insert(Self::SILENCE_MORE_FOLD.to_string());
3229 }
3230 if !self.silence_more_open() && !Self::SILENCE_MAIN_ROWS.contains(&self.silence_field) {
3231 self.silence_field = 0;
3232 }
3233 crate::ui::widgets::save_folds(&self.folds);
3234 cx.notify();
3235 }
3236
3237 /// The range a slider row sweeps and the grid its value snaps to: the
3238 /// threshold in dB, the three durations in seconds, the rate in thousandths
3239 /// (never below real time -- see [`silence_rate`]). `None` for the two rows
3240 /// that are choices, not numbers.
3241 pub(crate) fn silence_range(field: usize) -> Option<(f64, f64, f64)> {
3242 match field {
3243 1 => Some((
3244 f64::from(SILENCE_DB_RANGE.0),
3245 f64::from(SILENCE_DB_RANGE.1),
3246 f64::from(SILENCE_DB_STEP),
3247 )),
3248 3..=5 => Some((
3249 SILENCE_SECS_RANGE.0,
3250 SILENCE_SECS_RANGE.1,
3251 SILENCE_SECS_STEP,
3252 )),
3253 6 => Some((
3254 f64::from(Speed::NORMAL.permille()) + f64::from(SPEED_STEP),
3255 f64::from(Speed::MAX.permille()),
3256 f64::from(SPEED_STEP),
3257 )),
3258 _ => None,
3259 }
3260 }
3261
3262 /// What a slider row says its value is, in the unit its range is in.
3263 pub(crate) fn silence_value(&self, field: usize) -> f64 {
3264 match field {
3265 1 => f64::from(self.silence.threshold_db),
3266 3 => self.silence.min_silence,
3267 4 => self.silence.padding,
3268 5 => self.silence.min_keep,
3269 6 => f64::from(self.silence_factor.permille()),
3270 _ => 0.,
3271 }
3272 }
3273
3274 /// The value a fresh card opens with, for the same row.
3275 pub(crate) fn silence_default(field: usize) -> f64 {
3276 let fresh = engine::silence::Settings::default();
3277 match field {
3278 1 => f64::from(fresh.threshold_db),
3279 3 => fresh.min_silence,
3280 4 => fresh.padding,
3281 5 => fresh.min_keep,
3282 _ => f64::from(Speed::MAX.permille()),
3283 }
3284 }
3285
3286 /// Whether a slider row has moved off its default -- the ink1 and the
3287 /// Reset button both say so.
3288 pub(crate) fn silence_changed(&self, field: usize) -> bool {
3289 (self.silence_value(field) - Self::silence_default(field)).abs() > 1e-9
3290 }
3291
3292 /// Where a slider row's value sits on its track, 0..1.
3293 pub(crate) fn silence_fraction(&self, field: usize) -> f32 {
3294 match Self::silence_range(field) {
3295 Some((lo, hi, _)) => {
3296 slider_fraction(self.silence_value(field) as f32, lo as f32, hi as f32)
3297 }
3298 None => 0.,
3299 }
3300 }
3301
3302 /// Writes one slider row's value, clamped by the caller. The rate goes
3303 /// through [`silence_rate`], whose floor is real time plus one step.
3304 fn write_silence(&mut self, field: usize, at: f64) {
3305 match field {
3306 1 => self.silence.threshold_db = at as f32,
3307 3 => self.silence.min_silence = at,
3308 4 => self.silence.padding = at,
3309 5 => self.silence.min_keep = at,
3310 6 => self.silence_factor = silence_rate(at as i32),
3311 _ => {}
3312 }
3313 }
3314
3315 /// A press on a slider row: the value at `along` of its track, snapped to
3316 /// its grid. A preview like the arrows, so it re-runs the scan and touches
3317 /// no project value.
3318 pub(crate) fn press_silence(&mut self, field: usize, along: f32) {
3319 let Some(at) = Self::silence_snap(field, along) else {
3320 return;
3321 };
3322 self.silence_field = field;
3323 self.write_silence(field, at);
3324 self.scan_silences();
3325 }
3326
3327 /// The value at `along` of a slider row's track, snapped to its grid and
3328 /// kept inside its range. `None` for a row that is not a slider.
3329 pub(crate) fn silence_snap(field: usize, along: f32) -> Option<f64> {
3330 let (lo, hi, step) = Self::silence_range(field)?;
3331 let raw = lo + f64::from(along.clamp(0., 1.)) * (hi - lo);
3332 Some(((raw / step).round() * step).clamp(lo, hi))
3333 }
3334
3335 /// One slider row back to its default: its own Reset button.
3336 pub(crate) fn reset_silence_field(&mut self, field: usize, cx: &mut Context<Self>) {
3337 self.silence_field = field;
3338 self.write_silence(field, Self::silence_default(field));
3339 self.scan_silences();
3340 cx.notify();
3341 }
3342
3343 /// Whether any row is off its default, which is when the head offers
3344 /// `Reset all`.
3345 pub(crate) fn silence_any_changed(&self) -> bool {
3346 !self.silence_dbfs
3347 || [1, 3, 4, 5, 6]
3348 .into_iter()
3349 .any(|field| self.silence_changed(field))
3350 }
3351
3352 /// Every row back to what a fresh card opens with: the head's `Reset all`.
3353 /// The keep-only switch stays where the hand left it -- it is a mode, not
3354 /// a setting.
3355 pub(crate) fn reset_silence(&mut self, cx: &mut Context<Self>) {
3356 self.silence = engine::silence::Settings::default();
3357 self.silence_factor = Speed::MAX;
3358 self.silence_scope = Scope::Take;
3359 self.silence_dbfs = true;
3360 self.scan_silences();
3361 cx.notify();
3362 }
3363
3364 /// Which lanes an apply reaches, as the card's scope row says it: the
3365 /// lanes of the take the scanned clip belongs to, that clip's lane alone,
3366 /// or every lane there is.
3367 ///
3368 /// The take's lanes are the ones carrying its group id -- a link is one
3369 /// span on however many lanes, so "the take" is exactly the set of lanes
3370 /// that would otherwise be pulled apart. Nothing widens behind the user's
3371 /// back: [`Project::cut_regions`] refuses a scope that would split a take,
3372 /// and this row is how the user says the take instead.
3373 pub(crate) fn silence_lanes(&self) -> Vec<Lane> {
3374 let (Some((lane, idx)), Some(session)) = (self.silence_open, self.session.as_ref()) else {
3375 return Vec::new();
3376 };
3377 match self.silence_scope {
3378 Scope::Track => vec![lane],
3379 Scope::Everything => session.lanes(),
3380 Scope::Take => match session.lane_clips(lane).get(idx).and_then(|c| c.link) {
3381 None => vec![lane],
3382 Some(id) => session
3383 .lanes()
3384 .into_iter()
3385 .filter(|&l| {
3386 l == lane
3387 || session.lane_clips(l).iter().any(|c| c.link == Some(id))
3388 // The caption pinned to the take travels with it:
3389 // the ripple closes its lane too, or the words
3390 // would stay put while the clip under them moved.
3391 || session.sub_lane(l).iter().any(|s| s.link == Some(id))
3392 })
3393 .collect(),
3394 },
3395 }
3396 }
3397
3398 /// What an apply acts on: the previewed set and the lanes it reaches, or
3399 /// nothing at all with a notice saying so in the numbers that found
3400 /// nothing.
3401 pub(crate) fn previewed(&mut self) -> Option<Previewed> {
3402 if self.silence_marks.is_empty() {
3403 self.notify_user(if self.silence_keep_only {
3404 "No speech to cut — keep-only-silence needs silence and speech".into()
3405 } else {
3406 format!(
3407 "No silence — under {:.0} dBFS lasting {:.2} s",
3408 self.silence.threshold_db, self.silence.min_silence
3409 )
3410 .into()
3411 });
3412 return None;
3413 }
3414 Some((self.silence_marks.clone(), self.silence_lanes()))
3415 }
3416
3417 /// What an apply says afterwards: which tracks it reached, and -- when that
3418 /// was not all of them -- that the rest were left where they were. The
3419 /// scope is a choice, so the confirmation has to name the choice.
3420 pub(crate) fn silence_reach(&self, lanes: &[Lane]) -> String {
3421 let named = lanes
3422 .iter()
3423 .map(|l| l.label())
3424 .collect::<Vec<_>>()
3425 .join("+");
3426 match self.silence_scope {
3427 Scope::Everything => "on every track".to_string(),
3428 _ => format!("on {named} — other tracks untouched"),
3429 }
3430 }
3431
3432 /// Cuts every previewed silence out of the lanes the scope names, rippling
3433 /// each hole closed -- one edit and **one** undo press however many there
3434 /// were ([`engine::PlaybackSession::cut_regions`]). Tracks outside the
3435 /// scope do not move; a scope that would take half a take with it comes
3436 /// back refused in the engine's own words, naming both halves.
3437 pub(crate) fn cut_silences(&mut self, cx: &mut Context<Self>) {
3438 let Some((regions, lanes)) = self.previewed() else {
3439 cx.notify();
3440 return;
3441 };
3442 let saved = f64::from(regions.iter().map(|&(_, len)| len).sum::<u32>()) / self.fps;
3443 let (count, reach) = (regions.len(), self.silence_reach(&lanes));
3444 let Some(session) = self.session.as_mut() else {
3445 cx.notify();
3446 return;
3447 };
3448 match session.cut_regions(&regions, &lanes) {
3449 Ok(()) => {
3450 self.close_silence();
3451 // Every hole closed moves the clips after it up a place, so the
3452 // selection now names a different clip than the one that is
3453 // highlighted -- dropped here as after every other edit that
3454 // moves indexes (a delete, a paste, an undo).
3455 self.selected.clear();
3456 self.reset_after_reseek();
3457 let what = if self.silence_keep_only {
3458 format!("{count} speech")
3459 } else {
3460 count_noun(count, "silence", "silences")
3461 };
3462 self.notify_user(
3463 format!(
3464 "{what} cut {reach} — {} shorter · undo {}",
3465 secs_label(saved),
3466 self.keymap.display(ActionId::Undo)
3467 )
3468 .into(),
3469 );
3470 }
3471 Err(e) => self.notify_user(e.to_string().into()),
3472 }
3473 cx.notify();
3474 }
3475
3476 /// Plays them fast instead of cutting them, closing the room each one no
3477 /// longer needs. One undo press like the cut, and the same scope; the
3478 /// refusals (a clip lapping over a silence, a scope that would split a
3479 /// take) come back in the engine's own words and name the lane and frame,
3480 /// and the card stays up so the numbers that produced it are still on
3481 /// screen.
3482 pub(crate) fn speed_silences(&mut self, cx: &mut Context<Self>) {
3483 let Some((regions, lanes)) = self.previewed() else {
3484 cx.notify();
3485 return;
3486 };
3487 let (count, rate) = (regions.len(), self.silence_factor);
3488 let reach = self.silence_reach(&lanes);
3489 let Some(session) = self.session.as_mut() else {
3490 cx.notify();
3491 return;
3492 };
3493 match session.speed_regions(&regions, rate, &lanes) {
3494 Ok(()) => {
3495 self.close_silence();
3496 // Splitting each silence out and closing the room it no longer
3497 // needs moves indexes exactly as the cut does: the selection
3498 // goes with them.
3499 self.selected.clear();
3500 self.reset_after_reseek();
3501 let what = if self.silence_keep_only {
3502 "speech"
3503 } else {
3504 "silences"
3505 };
3506 self.notify_user(
3507 format!(
3508 "{count} {what} at {rate} {reach} · undo {}",
3509 self.keymap.display(ActionId::Undo)
3510 )
3511 .into(),
3512 );
3513 }
3514 Err(e) => self.notify_user(e.to_string().into()),
3515 }
3516 cx.notify();
3517 }
3518
3519 /// Whether a card owns the window. While one does the timeline under it is
3520 /// out of reach, so a right-click there opens no menu -- the same rule the
3521 /// key handler and the drop target already follow.
3522 /// Whether anything at all is drawn over the window -- a card, a menu or an
3523 /// open list. What the hover labels stand aside for ([`OVERLAID`]): a
3524 /// tooltip belongs to the surface the pointer is on, and while one of these
3525 /// is up that surface is behind it.
3526 pub(crate) fn overlaid(&self) -> bool {
3527 self.modal()
3528 || self.context_menu.is_some()
3529 || self.cue_menu.is_some()
3530 || self.library_menu.is_some()
3531 || self.picker.is_some()
3532 }
3533
3534 /// Whether a card owns the screen. A running export is deliberately not
3535 /// in here: it is a *state* the oracle answers for action by action (the
3536 /// editor stays usable from the keyboard, and what must wait is spoken as
3537 /// a refusal), not a surface sitting on the keys. The darkroom's key guard
3538 /// ([`ui::stance`]'s `on_key_down`) reads [`Player::card_open`] for the same
3539 /// reason, so a keystroke during an export reaches `enable()`/`act()`.
3540 pub(crate) fn modal(&self) -> bool {
3541 self.card_open()
3542 }
3543
3544 /// Whether an actual card owns the screen -- the card half of
3545 /// [`Player::modal`], which is this now. Kept as its own name because the
3546 /// key guard reads it, and `tests/cards.rs` pins that it never grows an
3547 /// `exporting` read.
3548 pub(crate) fn card_open(&self) -> bool {
3549 // Not `keys_open`: since 2026-09-09 that is the dock's KEYS *tab*
3550 // showing, a region like any other, not a surface sitting on the
3551 // keyboard -- every stroke still means what the spine says it means
3552 // while the list is up.
3553 self.settings_open
3554 || self.proj_dialog.is_some()
3555 || self.export_open
3556 || self.eq_open.is_some()
3557 || self.color_open.is_some()
3558 || self.transform_open.is_some()
3559 || self.speed_open.is_some()
3560 || self.effects_open.is_some()
3561 || self.silence_open.is_some()
3562 || self.beats_open.is_some()
3563 || self.mix_open
3564 || self.markers_open
3565 || self.history_open
3566 || self.tools.is_some()
3567 || self.subtitle_style_open
3568 }
3569
3570 /// Whether the Export tab is the only card up: escape leaves it showing.
3571 pub(crate) fn only_export_tab(&self) -> bool {
3572 self.export_open
3573 && !(self.settings_open
3574 || self.proj_dialog.is_some()
3575 || self.eq_open.is_some()
3576 || self.color_open.is_some()
3577 || self.transform_open.is_some()
3578 || self.speed_open.is_some()
3579 || self.effects_open.is_some()
3580 || self.silence_open.is_some()
3581 || self.mix_open
3582 || self.markers_open
3583 || self.history_open
3584 || self.history_open
3585 || self.tools.is_some()
3586 || self.subtitle_style_open)
3587 }
3588
3589 /// Whether something covers the room's pointer doors (the timeline's menus, drags and clicks).
3590 /// Only a real overlay does: Settings and the project dialogs. Every card docked in the right
3591 /// panel (Tools, Markers, Silence, EQ, Export, ...) shades nothing, so none of them may eat a
3592 /// right-click, a drag or a click on the timeline -- that was the regression, three times.
3593 /// Floating plates and menus answer for themselves ([`Player::overlaid`]).
3594 pub(crate) fn covers_room(&self) -> bool {
3595 self.settings_open || self.proj_dialog.is_some()
3596 }
3597
3598 /// Whether the only thing up is a card docked in the right panel (grade, transform, speed,
3599 /// effects, EQ, silence, mix, markers, tools, subtitle style): it shares the dock with
3600 /// everything else and draws nothing over the timeline, so it must not behave as the invisible
3601 /// modal the sheets are -- the transport keys keep their meaning while it shows. The Export
3602 /// tab keeps its own key list ([`export_tab_action`]).
3603 pub(crate) fn docked_card_only(&self) -> bool {
3604 self.card_open() && !self.covers_room() && !self.export_open
3605 }
3606
3607 /// The invariant behind every card-opening door (menu, context menu,
3608 /// palette, key, hook): a card that mounts in the Clip tab is never up
3609 /// while the dock shows Media, so the dock swings to the Clip tab. One
3610 /// place, read each frame, instead of a line in each `open_*` -- the
3611 /// five that forgot it left the card invisible behind Sources. Returns
3612 /// whether it moved the tab.
3613 pub(crate) fn sync_dock_tab(&mut self) -> bool {
3614 if self.dock_src_active && (self.clip_card_open() || self.export_open || self.transcript_open) {
3615 self.dock_src_active = false;
3616 crate::ui::dock_stance::save(false);
3617 return true;
3618 }
3619 false
3620 }
3621
3622 /// What a right-click on the bench may do: refused only under a sheet that covers the room.
3623 /// A docked card stays as it is while the menu opens.
3624 pub(crate) fn menu_allowed(&mut self) -> bool {
3625 !self.covers_room()
3626 }
3627
3628 /// Whether one of the dock's Clip-tab cards is up (every card but the
3629 /// export panel and Settings): the Clip tab then shows it in place of the
3630 /// verb list, and the dock switches to that tab on its own.
3631 pub(crate) fn clip_card_open(&self) -> bool {
3632 self.eq_open.is_some()
3633 || self.color_open.is_some()
3634 || self.transform_open.is_some()
3635 || self.speed_open.is_some()
3636 || self.effects_open.is_some()
3637 || self.silence_open.is_some()
3638 || self.beats_open.is_some()
3639 || self.mix_open
3640 || self.markers_open
3641 || self.history_open
3642 || self.tools.is_some()
3643 || self.subtitle_style_open
3644 }
3645
3646 /// The pointer's way out of whatever card is up: what every scrim's press
3647 /// calls, so `esc` is *a* way out and never the only one. One list, and the
3648 /// same one [`Player::modal`] reads -- a card that can be counted there but
3649 /// not closed here is a card a hand alone cannot shut, which is what
3650 /// `every_card_closes_without_the_keyboard` fails on.
3651 ///
3652 /// Every card at once because only one is ever up (`export_open`): closing
3653 /// "the" card and closing all of them are the same act.
3654 pub(crate) fn close_card(&mut self) {
3655 // A clip card closes back to the Clip tab's list, never to Media.
3656 if self.clip_card_open() {
3657 self.dock_src_active = false;
3658 }
3659 self.keys_open = false;
3660 self.keys_filter.clear();
3661 self.settings_open = false;
3662 self.export_open = false;
3663 // A finished or failed face belongs to the export that made it; once
3664 // the card is closed the tab opens on fresh settings.
3665 if self.export.is_none() {
3666 self.export_sheet.done = None;
3667 self.export_sheet.failed = None;
3668 }
3669 self.transcript_open = false;
3670 self.transcript.search_edit = false;
3671 // The two things typed *into* the export moment go with it: a field
3672 // left open would take the next keystroke for a card that is gone.
3673 self.budget_edit = None;
3674 self.picker = None;
3675 self.eq_open = None;
3676 self.eq_dragging = false;
3677 self.color_open = None;
3678 self.transform_open = None;
3679 self.speed_open = None;
3680 self.speed_ramp_mode = false;
3681 self.ramp_key_speed = None;
3682 self.effects_open = None;
3683 self.effects_drag = None;
3684 self.effects_draft = None;
3685 self.effects_adding = false;
3686 // Marks and a running scan go with this one, which is why it is a call
3687 // and not an assignment ([`Player::close_silence`]).
3688 if self.silence_open.is_some() {
3689 self.close_silence();
3690 }
3691 self.close_beats();
3692 self.mix_open = false;
3693 self.markers_open = false;
3694 self.history_open = false;
3695 // A running listen or speak stops with the card that shows it.
3696 self.close_tools();
3697 // A name half-typed goes with the card it was typed into.
3698 self.marker_edit = None;
3699 self.subtitle_style_open = false;
3700 self.sub_anim_open = false;
3701 }
3702
3703 /// Opening one of the Clip tab's sections: closes every card that is not itself a docked section
3704 /// (Settings, Export, markers, tools, caption style, silence, a menu) and leaves the sections
3705 /// that are open as they are, so several can be open at once (P7). [`Player::close_card`] stays
3706 /// the one way out of everything.
3707 pub(crate) fn close_other_cards(&mut self) {
3708 let kept = (
3709 self.eq_open.take(),
3710 self.color_open.take(),
3711 self.transform_open.take(),
3712 self.speed_open.take(),
3713 (self.speed_ramp_mode, self.ramp_key_speed),
3714 self.effects_open.take(),
3715 (self.effects_drag.take(), self.effects_draft.take(), self.effects_adding),
3716 self.mix_open,
3717 );
3718 self.close_card();
3719 self.eq_open = kept.0;
3720 self.color_open = kept.1;
3721 self.transform_open = kept.2;
3722 self.speed_open = kept.3;
3723 (self.speed_ramp_mode, self.ramp_key_speed) = kept.4;
3724 self.effects_open = kept.5;
3725 (self.effects_drag, self.effects_draft, self.effects_adding) = kept.6;
3726 self.mix_open = kept.7;
3727 }
3728
3729 /// Escape's one door to every dismissible overlay the room can have up
3730 /// (`ui::stance::render`'s root `on_key_down`'s own escape branches,
3731 /// mirrored here exactly): a focus surface with its own escape branch
3732 /// (dock/inspector's `cycle_on_key_down`, the bench's handler) calls
3733 /// this FIRST, before its own ring-exit behavior, so an overlay opened
3734 /// by a click into that surface still closes on the first escape
3735 /// instead of the ring's `stop_propagation` swallowing the key before
3736 /// the root ever sees it (the "esc does not close menus opened by
3737 /// clicking in the clip section" report). Returns whether it closed
3738 /// something, so a caller only falls through to its own ring-exit
3739 /// behavior when nothing was open to close.
3740 pub(crate) fn escape_closes_overlay(&mut self, cx: &mut Context<Self>) -> bool {
3741 // Words being typed in a caption take escape first: they are given up and the card stays.
3742 if self.escape_cue_edit() {
3743 cx.notify();
3744 return true;
3745 }
3746 if self.card_open()
3747 || self.context_menu.is_some()
3748 || self.cue_menu.is_some()
3749 || self.library_menu.is_some()
3750 || self.picker.is_some()
3751 || self.about_open
3752 {
3753 self.about_open = false;
3754 // A popup over a tab goes alone, and so does Settings over the
3755 // Export tab: escape never takes the tab itself away.
3756 if self.context_menu.is_some() || self.cue_menu.is_some() || self.library_menu.is_some() || self.picker.is_some() {
3757 self.context_menu = None;
3758 self.cue_menu = None;
3759 self.library_menu = None;
3760 self.picker = None;
3761 cx.notify();
3762 return true;
3763 }
3764 if self.export_open && self.settings_open {
3765 self.settings_open = false;
3766 self.keys_filter.clear();
3767 cx.notify();
3768 return true;
3769 }
3770 if self.only_export_tab() {
3771 return true;
3772 }
3773 // The font list is a pick inside the style card: escape closes that list alone, and the
3774 // card (and its section) stays as it was.
3775 if self.subtitle_style_open && self.sub_font_open {
3776 self.sub_font_open = false;
3777 cx.notify();
3778 return true;
3779 }
3780 self.close_card();
3781 self.context_menu = None;
3782 self.library_menu = None;
3783 self.picker = None;
3784 cx.notify();
3785 return true;
3786 }
3787 if self.preview_session.is_some() {
3788 self.close_preview(cx);
3789 return true;
3790 }
3791 false
3792 }
3793
3794 /// The one switch every param card's expand affordance and its `m`
3795 /// chord both flip (`dark_card_head`, [`Player::param_card_key`]):
3796 /// whichever card is open trades its usual capped, floating size for the
3797 /// bench/ledger rows' own room, in place -- layout only, no value on the
3798 /// card changes. Persisted like the dock tab pick so a maximized EQ is
3799 /// still maximized after the room closes and reopens.
3800 pub(crate) fn toggle_maximize(&mut self) {
3801 // A card that fills the room floats over the viewer, which the dock
3802 // design forbids (every card opens in the Clip tab): the switch stays
3803 // for the chord and the saved flag, but the card stays docked.
3804 self.card_maximized = false;
3805 ui::dock_stance::save_maximized(false);
3806 }
3807
3808 /// Opens the equalizer on the selected clip. Audio only, and it says so
3809 /// rather than opening a card of bands that would reach nothing: a video
3810 /// clip carries no sound of its own here (the sound is the audio lane's),
3811 /// and the model would take the setting without anything ever playing it.
3812 pub(crate) fn open_eq(&mut self, cx: &mut Context<Self>) {
3813 if self.exporting().is_some() {
3814 return;
3815 }
3816 // A caption the hand is on names the sound its group plays, and the
3817 // card opens on that; one in no group has no sound to equalize and
3818 // falls to the lane refusal below, in the words it always used.
3819 let anchor = match (self.selected.anchor(), self.session.as_ref()) {
3820 (Some((lane, idx)), Some(session)) if lane.kind == LaneKind::Subtitle => {
3821 caption_media_half(session, (lane, idx), LaneKind::Audio).or(self.selected.anchor())
3822 }
3823 _ => self.selected.anchor(),
3824 };
3825 // A video clip's sound is its linked audio half, so Alt+4 on a picked film opens on that.
3826 let anchor = match anchor {
3827 Some((lane, idx)) if lane.kind == LaneKind::Video => self
3828 .linked_partners((lane, idx))
3829 .into_iter()
3830 .find(|(l, _)| l.kind == LaneKind::Audio)
3831 .or(anchor),
3832 _ => anchor,
3833 };
3834 let refusal = match (anchor, &self.session) {
3835 (_, None) => Some("No timeline — no file open".to_string()),
3836 (None, _) => Some(format!(
3837 "Nothing selected · select all {}",
3838 self.keymap.display(ActionId::Select)
3839 )),
3840 (Some((lane, _)), _) if lane.kind != LaneKind::Audio => {
3841 Some("Not an audio clip — the equalizer works on sound".to_string())
3842 }
3843 _ => None,
3844 };
3845 if let Some(refusal) = refusal {
3846 self.notify_user(refusal.into());
3847 cx.notify();
3848 return;
3849 }
3850 let (lane, idx) = anchor.expect("checked above");
3851 let session = self.session.as_ref().expect("checked above");
3852 // What the clip already plays through, or the flat default -- so the
3853 // card opens on the curve that is in force and a reopen shows the last
3854 // drag rather than a fresh set of zeroes.
3855 self.eq_params = session
3856 .eq_of(lane, idx)
3857 .cloned()
3858 .unwrap_or_else(EqParams::default_layout);
3859 // One card at a time -- `close_card`'s own rule.
3860 self.close_other_cards();
3861 self.eq_band = 0;
3862 self.eq_dragging = false;
3863 self.eq_open = Some((lane, idx));
3864 self.context_menu = None;
3865 cx.notify();
3866 }
3867
3868 /// Writes what the card is showing at its clip: one undo step, one entry in
3869 /// the append-only equalizer table, so this is called once per *gesture* --
3870 /// the end of a drag, a keystroke -- and never per pointer sample.
3871 ///
3872 /// A curve that moves nothing is stored as *no* equalizer at all, which is
3873 /// what keeps a clip nobody has touched on the identity path through
3874 /// playback and export (`engine::eq::EqParams::is_identity`).
3875 pub(crate) fn commit_eq(&mut self, cx: &mut Context<Self>) {
3876 let Some((lane, idx)) = self.eq_open else {
3877 return;
3878 };
3879 let params = (!self.eq_params.is_identity()).then(|| self.eq_params.clone());
3880 if let Some(session) = &mut self.session {
3881 // `set_eq` answers "the index was there and the curve is finite"
3882 // -- it snapshots and rewrites the very slot it already holds for
3883 // a curve that is already in force -- so on its own bool a
3884 // re-commit of the same curve armed autosave, the ledger's
3885 // `unsaved` ghost and the close prompt over a project whose bytes
3886 // had not moved. The arm rides the curve having moved, the
3887 // comparison `apply_fit` reads for `set_fit`
3888 // ([`Player::apply_fit`]), and then the door's own answer.
3889 let moved = session.eq_of(lane, idx).cloned() != params;
3890 if moved && session.set_eq(lane, idx, params) {
3891 self.mark_dirty();
3892 // `set_eq` reseeks inside the engine -- that is what makes the
3893 // change audible at once -- and a reseek is what these flags
3894 // are about. Nothing was written, so nothing was reseeked.
3895 self.reset_after_reseek();
3896 }
3897 }
3898 cx.notify();
3899 }
3900
3901 /// Changes the picked band in place and says whether anything moved. Every
3902 /// edit of a band goes through here -- the drag, each key, each stepper
3903 /// button -- so the card has exactly one place that clamps a band into what
3904 /// the graph can draw, and no caller has to remember the limits.
3905 pub(crate) fn set_band(&mut self, change: impl FnOnce(&mut Band)) -> bool {
3906 let Some(band) = self.eq_params.bands.get_mut(self.eq_band) else {
3907 return false;
3908 };
3909 let was = *band;
3910 change(band);
3911 band.freq_hz = band.freq_hz.clamp(EQ_FREQ_LOW, EQ_FREQ_HIGH);
3912 band.gain_db = band.gain_db.clamp(-EQ_GAIN_LIMIT, EQ_GAIN_LIMIT);
3913 band.q = band.q.clamp(EQ_Q_LOW, EQ_Q_HIGH);
3914 *band != was
3915 }
3916
3917 /// The keyboard's and the buttons' version of a drag: one step on the picked
3918 /// band, committed straight away -- neither has a release to wait for.
3919 pub(crate) fn nudge_band(&mut self, change: impl FnOnce(&mut Band), cx: &mut Context<Self>) {
3920 if self.set_band(change) {
3921 self.commit_eq(cx);
3922 }
3923 }
3924
3925 /// Where the pointer sits in the graph, as the picked band's frequency and
3926 /// gain: across is the frequency axis and down is the gain one, so the
3927 /// handle follows the hand both ways rather than sliding up a rail. Called
3928 /// on every pointer sample, so the curve bends under it; the write is the
3929 /// release's ([`commit_eq`](Player::commit_eq)).
3930 pub(crate) fn drag_band(&mut self, at: Point<Pixels>, cx: &mut Context<Self>) {
3931 let bounds = self.eq_graph.get();
3932 let gain = (0.5 - frac_down(at.y, bounds)) * 2. * EQ_GAIN_LIMIT;
3933 let freq = eq_freq(frac_along(at.x, bounds));
3934 if self.set_band(|b| {
3935 b.gain_db = gain;
3936 b.freq_hz = freq;
3937 }) {
3938 cx.notify();
3939 }
3940 }
3941
3942 /// A band added beside the picked one, at the frequency with the most room
3943 /// around it ([`inserted_band`]), and picked so the next keystroke moves the
3944 /// band that was just made. Refused rather than silently ignored at the cap.
3945 pub(crate) fn add_band(&mut self, cx: &mut Context<Self>) {
3946 if self.eq_params.bands.len() >= EQ_BANDS_MAX {
3947 self.notify_user(format!("Equalizer full — {EQ_BANDS_MAX} bands").into());
3948 cx.notify();
3949 return;
3950 }
3951 let band = inserted_band(&self.eq_params.bands, self.eq_band);
3952 self.eq_band = (self.eq_band + 1).min(self.eq_params.bands.len());
3953 self.eq_params.bands.insert(self.eq_band, band);
3954 self.commit_eq(cx);
3955 }
3956
3957 /// Takes the picked band out. The last one stays: an equalizer of no bands
3958 /// is a card with nothing to edit, and flattening is what "off" means here.
3959 pub(crate) fn remove_band(&mut self, cx: &mut Context<Self>) {
3960 if self.eq_params.bands.len() <= 1 {
3961 self.notify_user("Last band · flatten r".into());
3962 cx.notify();
3963 return;
3964 }
3965 self.eq_params.bands.remove(self.eq_band);
3966 self.eq_band = self.eq_band.min(self.eq_params.bands.len() - 1);
3967 self.commit_eq(cx);
3968 }
3969
3970 /// Which band a press on the graph grabs: the nearest one along the
3971 /// frequency axis, so the whole box is the handle rather than a 10 px dot
3972 /// -- and a press that misses every dot still moves the band it is under.
3973 pub(crate) fn nearest_band(&self, x: Pixels) -> usize {
3974 let at = frac_along(x, self.eq_graph.get());
3975 self.eq_params
3976 .bands
3977 .iter()
3978 .enumerate()
3979 .min_by(|(_, a), (_, b)| {
3980 (eq_x(a.freq_hz) - at)
3981 .abs()
3982 .total_cmp(&(eq_x(b.freq_hz) - at).abs())
3983 })
3984 .map_or(0, |(i, _)| i)
3985 }
3986
3987 /// Every param card's own key branch (EQ, Colour, Transform, Speed,
3988 /// Silence, Mix, Subtitle style), factored out of the legacy tree's
3989 /// `render.rs` handler so a second stance (`ui/stance.rs`) can drive the
3990 /// same cards without a second, divergent copy of this logic -- the
3991 /// defect class DESIGN §6's "drag while playing... `r` resets" was
3992 /// missing from the darkroom for. Returns `true` when a card was open
3993 /// and ate the key, the caller's cue to `cx.notify()` and stop exactly
3994 /// where each of these branches used to `return` inline.
3995 pub(crate) fn param_card_key(
3996 &mut self,
3997 key: &str,
3998 shift: bool,
3999 cx: &mut Context<Self>,
4000 ) -> bool {
4001 // The one chord every param card answers to, wherever the pointer
4002 // toggle sits in `dark_card_head` -- mouse and key reach the same
4003 // switch (DESIGN's repeated "some options are only reachable via
4004 // keyboard shortcut" complaint). Checked once, ahead of the seven
4005 // card-local branches below, because it means the same thing in all
4006 // of them: none of the seven uses bare "m" for anything else.
4007 if key == "m"
4008 && (self.eq_open.is_some()
4009 || self.color_open.is_some()
4010 || self.transform_open.is_some()
4011 || self.speed_open.is_some()
4012 || self.effects_open.is_some()
4013 || self.silence_open.is_some()
4014 || self.mix_open
4015 || self.subtitle_style_open)
4016 {
4017 self.toggle_maximize();
4018 return true;
4019 }
4020 if self.eq_open.is_some() {
4021 if key == ESCAPE {
4022 // Maximized comes off before the card does -- "esc always
4023 // retreats" one step at a time (DESIGN.md:146).
4024 if self.card_maximized {
4025 self.toggle_maximize();
4026 return true;
4027 }
4028 // Nothing to undo: every change is already at the clip, and
4029 // undo is undo's own key.
4030 self.eq_open = None;
4031 self.eq_dragging = false;
4032 } else if key == "up" {
4033 self.nudge_band(|b| b.gain_db += EQ_STEP, cx);
4034 } else if key == "down" {
4035 self.nudge_band(|b| b.gain_db -= EQ_STEP, cx);
4036 } else if key == "left" && shift {
4037 self.nudge_band(|b| b.q /= EQ_Q_STEP, cx);
4038 } else if key == "right" && shift {
4039 self.nudge_band(|b| b.q *= EQ_Q_STEP, cx);
4040 } else if key == "left" {
4041 self.nudge_band(|b| b.freq_hz /= EQ_FREQ_STEP, cx);
4042 } else if key == "right" {
4043 self.nudge_band(|b| b.freq_hz *= EQ_FREQ_STEP, cx);
4044 } else if key == "r" {
4045 for band in &mut self.eq_params.bands {
4046 band.gain_db = 0.;
4047 }
4048 self.commit_eq(cx);
4049 } else if key == "f" {
4050 // This one band back to flat, which is the undo of one hand
4051 // movement -- `r` is the undo of the whole card.
4052 self.nudge_band(|b| b.gain_db = 0., cx);
4053 } else if key == "a" {
4054 self.add_band(cx);
4055 } else if key == "x" {
4056 self.remove_band(cx);
4057 } else if key == "s" {
4058 // The analyser off and on. Nothing is committed: it is what
4059 // the card *shows*, so it survives no further than this
4060 // window.
4061 self.eq_spectrum = !self.eq_spectrum;
4062 } else if key == "tab" {
4063 let n = self.eq_params.bands.len().max(1);
4064 self.eq_band = if shift { (self.eq_band + n - 1) % n } else { (self.eq_band + 1) % n };
4065 } else {
4066 return false;
4067 }
4068 return true;
4069 }
4070 // The colour card owns the keyboard the same way the export card
4071 // does, and its keys mean nothing outside it: the arrows pick a
4072 // slider and move it, and `r` takes the grade off. Not keymap
4073 // bindings for exactly that reason -- see `FIXED`, where the keys
4074 // menu still lists them.
4075 if self.color_open.is_some() {
4076 match color_key(key) {
4077 Some(ColorKey::Close) if self.card_maximized => self.toggle_maximize(),
4078 Some(ColorKey::Close) => {
4079 self.color_open = None;
4080 self.color_dragging = false;
4081 self.color_wheel_drag = None;
4082 }
4083 Some(ColorKey::Band(step)) => {
4084 let bands = section_bands(self.color_section);
4085 let n = bands.len();
4086 let at = self.color_band.saturating_sub(bands.start).min(n - 1);
4087 // `up` arrives as the last band of the four; walk this section's own.
4088 let step = if step == COLOR_BANDS.len() - 1 { n - 1 } else { step };
4089 self.color_band = bands.start + (at + step) % n;
4090 }
4091 Some(ColorKey::Nudge(steps)) => self.nudge_color(steps, cx),
4092 Some(ColorKey::Reset) => {
4093 self.set_color(ColorParams::default(), cx);
4094 }
4095 None => return false,
4096 }
4097 return true;
4098 }
4099 // The transform card, the same way again: the arrows pick a slider
4100 // and move it, and `r` puts the placement back to identity.
4101 // Card-local, [`ActionId::Color`]'s own reason (see `FIXED`, where
4102 // the keys menu still lists them).
4103 if self.transform_open.is_some() {
4104 if key == ESCAPE && self.card_maximized {
4105 self.toggle_maximize();
4106 } else if key == ESCAPE {
4107 self.transform_open = None;
4108 self.transform_dragging = false;
4109 } else if key == "down" {
4110 self.move_transform_band(true);
4111 } else if key == "up" {
4112 self.move_transform_band(false);
4113 } else if key == "right" {
4114 self.nudge_transform(1., cx);
4115 } else if key == "left" {
4116 self.nudge_transform(-1., cx);
4117 } else if key == "r" {
4118 self.set_transform(TransformParams::default(), cx);
4119 } else {
4120 return false;
4121 }
4122 return true;
4123 }
4124 // The speed card, the same way again: its arrows move the rate and
4125 // `r` puts it back to real time, and neither means anything outside
4126 // the card -- so neither is a binding (see `FIXED`, where the keys
4127 // menu still lists them).
4128 if self.speed_open.is_some() {
4129 match color_key(key) {
4130 Some(ColorKey::Close) if self.card_maximized => self.toggle_maximize(),
4131 Some(ColorKey::Close) => {
4132 self.speed_open = None;
4133 self.speed_dragging = false;
4134 }
4135 // The card has one value, so the pair that picks a slider on
4136 // the colour card moves this one by a whole preset's worth
4137 // instead of a step.
4138 Some(ColorKey::Band(step)) => self.nudge_speed(if step == 1 { -2 } else { 2 }, cx),
4139 Some(ColorKey::Nudge(steps)) => self.nudge_speed(steps as i32, cx),
4140 Some(ColorKey::Reset) => self.set_speed(Speed::NORMAL, cx),
4141 None => return false,
4142 }
4143 return true;
4144 }
4145 // The silence card, the same way again: the arrows pick one of its
4146 // rows and move it, its two apply keys are the two things it can do
4147 // to the timeline, and `k` flips which half of the sound they act
4148 // on. Card-local, every one of them -- and listed in the keys menu
4149 // (keymap.rs `FIXED`), because a key that cuts forty places at once
4150 // is not a secret.
4151 if self.silence_open.is_some() {
4152 if key == ESCAPE && self.card_maximized {
4153 self.toggle_maximize();
4154 } else if key == ESCAPE {
4155 // Nothing to undo: a preview is not an edit.
4156 self.close_silence();
4157 } else if key == "down" {
4158 self.step_silence_field(1);
4159 } else if key == "up" {
4160 self.step_silence_field(-1);
4161 } else if key == "right" {
4162 self.nudge_silence(1);
4163 } else if key == "left" {
4164 self.nudge_silence(-1);
4165 } else if key == "enter" {
4166 self.cut_silences(cx);
4167 } else if key == "f" {
4168 self.speed_silences(cx);
4169 } else if key == "k" {
4170 self.toggle_silence_keep_only();
4171 cx.notify();
4172 } else {
4173 return false;
4174 }
4175 return true;
4176 }
4177 // The mix card, the same way again: up/down pick a row -- a track's
4178 // fader, the limiter's ceiling or its switch -- and left/right move
4179 // it, held or pressed. Card-local like the four above it.
4180 // The effects card: its bars and buttons are pointer-driven, so a key only
4181 // leaves it, maximized first.
4182 if self.effects_open.is_some() {
4183 if key == ESCAPE && self.card_maximized {
4184 self.toggle_maximize();
4185 } else if key == ESCAPE {
4186 self.close_card();
4187 } else {
4188 return false;
4189 }
4190 return true;
4191 }
4192 // The markers card: up/down pick a marker, enter retypes its name.
4193 if self.markers_open {
4194 return self.markers_card_key(key, shift, cx);
4195 }
4196 if self.tools.is_some() {
4197 return self.tools_card_key(key, cx);
4198 }
4199 if self.mix_open {
4200 let rows = self.mix_lanes().len() + MIX_MASTER_ROWS;
4201 if key == ESCAPE && self.card_maximized {
4202 self.toggle_maximize();
4203 } else if key == ESCAPE {
4204 self.mix_open = false;
4205 } else if key == "down" {
4206 self.mix_field = (self.mix_field + 1) % rows;
4207 } else if key == "up" {
4208 self.mix_field = (self.mix_field + rows - 1) % rows;
4209 } else if key == "right" {
4210 self.nudge_mix(1, cx);
4211 } else if key == "left" {
4212 self.nudge_mix(-1, cx);
4213 } else {
4214 return false;
4215 }
4216 return true;
4217 }
4218 // The subtitle style card, the same way again: up/down walk its rows
4219 // (the size, the three chip rows, the platform default, then every
4220 // family in `subtitle_fonts`), left/right moves the picked row, and
4221 // `enter` steps a chip row or picks a family -- since a hand with no
4222 // mouse still has to be able to leave the platform default.
4223 if self.subtitle_style_open {
4224 let rows = SUB_ROW_FIRST_FAMILY + self.subtitle_fonts.len();
4225 let field = self.subtitle_style_field;
4226 self.sub_keys_used = true;
4227 if key == ESCAPE && self.card_maximized {
4228 self.toggle_maximize();
4229 } else if key == ESCAPE {
4230 self.subtitle_style_open = false;
4231 self.sub_anim_open = false;
4232 } else if key == "down" {
4233 self.subtitle_style_field = sub_row_step(&self.subtitle_fonts, rows, field, true);
4234 } else if key == "up" {
4235 self.subtitle_style_field = sub_row_step(&self.subtitle_fonts, rows, field, false);
4236 } else if key == "right" {
4237 self.step_sub_field(1, cx);
4238 } else if key == "left" {
4239 self.step_sub_field(-1, cx);
4240 } else if key == "enter" && field == SUB_ROW_DEFAULT {
4241 self.set_sub_family(None, cx);
4242 } else if key == "enter" && (SUB_ROW_OUTLINE..SUB_ROW_DEFAULT).contains(&field) {
4243 self.step_sub_field(1, cx);
4244 } else if key == "enter" && field >= SUB_ROW_FIRST_FAMILY {
4245 let family = self.subtitle_fonts[field - SUB_ROW_FIRST_FAMILY].clone();
4246 self.set_sub_family(Some(family), cx);
4247 } else {
4248 return false;
4249 }
4250 return true;
4251 }
4252 // The Clip tab's colour field (`Player::edit_viz_hex`): the
4253 // transition row's own keyboard door, and its free-text half --
4254 // checked here, beside it, for its reason (the Clip tab is always on
4255 // screen, not modal). Every printable stroke lands in the buffer, so
4256 // a letter that is also a room chord types into the field while it is
4257 // open, exactly as the dock's source filter does.
4258 if self.viz_hex_edit.is_some() {
4259 match key {
4260 ESCAPE => self.viz_hex_edit = None,
4261 "enter" => self.commit_viz_hex(cx),
4262 "backspace" => {
4263 if let Some(edit) = self.viz_hex_edit.as_mut() {
4264 edit.backspace();
4265 }
4266 }
4267 _ => match typed(key) {
4268 Some(c) => {
4269 if let Some(edit) = self.viz_hex_edit.as_mut() {
4270 edit.typed(c);
4271 }
4272 }
4273 None => return false,
4274 },
4275 }
4276 return true;
4277 }
4278 // The Clip tab's transition length field: typed digits, `.`, Enter and
4279 // Escape, checked first since it can be open while no card is (the Clip
4280 // tab is always on screen, not modal).
4281 if self.transition_edit.is_some() && self.transition_key(key, cx) {
4282 return true;
4283 }
4284 // The settings page: card-local like the colour and transform
4285 // branches above, so escape still closes the page and every other key
4286 // falls through to the room.
4287 if self.settings_open {
4288 // The arrows walk the choice rows and step the focused one
4289 // ([`crate::ui::settings_stance::settings_arrow`]); an open list
4290 // keeps them for itself.
4291 if self.picker.is_none() && crate::ui::settings_stance::settings_arrow(self, key, cx) {
4292 return true;
4293 }
4294 match key {
4295 // The Level row's own three, and they have to be *here*:
4296 // this page counts as a card in [`Self::card_open`], so a
4297 // stroke that falls through this branch is swallowed by the
4298 // darkroom's modal guard rather than reaching the keymap --
4299 // `m` did nothing at all with the page up (caught in the
4300 // harness, not by a guard). Same setter the keymap's
4301 // [`ActionId::ToggleMute`]/`VolumeUp`/`VolumeDown` call, so
4302 // the row cannot drift from the chord it wears.
4303 "m" => self.set_volume(|volume| volume.muted = !volume.muted, cx),
4304 "=" => self.set_volume(|volume| volume.step(true), cx),
4305 "-" => self.set_volume(|volume| volume.step(false), cx),
4306 _ => return false,
4307 }
4308 return true;
4309 }
4310 // The export moment: its own chords, and every other stroke
4311 // swallowed while it is up -- a chord this surface consumes must
4312 // never also reach the room's keymap underneath it
4313 // ([`Player::export_moment_key`]).
4314 if self.export_moment_key(key, shift, cx) {
4315 return true;
4316 }
4317 false
4318 }
4319}