forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB8c7bf80Tahinli3 months ago114 commits

main.rs5851 lines, 255.3 KiBHistoryRawDownload
1mod keymap;
2
3use keymap::{ActionId, Keymap};
4
5use std::cell::Cell;
6use std::collections::HashMap;
7use std::path::{Path, PathBuf};
8use std::rc::Rc;
9use std::sync::Arc;
10use std::time::{Duration, Instant};
11
12use engine::audio::StreamInfo;
13use engine::color::ColorParams;
14use engine::eq::{Band, BandKind, EqParams};
15use engine::export::{ExportSettings, Format};
16use engine::project::{Lane, LaneKind, Source};
17use engine::scale::FitPolicy;
18use engine::{Clip, ExportHandle, Frame, PlaybackSession};
19use gpui::{
20 AnyElement, App, Application, Bounds, ClickEvent, Context, Div, FocusHandle, KeyDownEvent,
21 MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, Point,
22 RenderImage, SharedString, Size, Stateful, TitlebarOptions, Window, WindowBounds,
23 WindowOptions, canvas, div, img, point, prelude::*, px, relative, rgb, rgba, size,
24};
25
26/// Editor chrome: three grays and one accent, all darker than the picture so the
27/// frame is what the eye lands on. `LETTERBOX` stays the video's own bed.
28const LETTERBOX: u32 = 0x101010;
29const CHROME: u32 = 0x242424;
30const SURFACE: u32 = 0x333333;
31const INK: u32 = 0xc8c8c8;
32const ACCENT: u32 = 0x4a9eff;
33/// The accent at surface brightness: a selected clip is tinted, not lit up.
34const SELECTED: u32 = 0x2a4a6b;
35/// One per source, so a clip that came from an imported file reads as coming
36/// from somewhere else. Same brightness as `SURFACE` and only the hue moves:
37/// the lane stays in the dark family the rest of the chrome lives in
38/// (ledger:187), and the first source keeps `SURFACE` exactly.
39const SOURCE_TINTS: [u32; 4] = [SURFACE, 0x3b3329, 0x293b33, 0x33293b];
40/// One step lighter than whatever it sits on: the pointer's answer that this is
41/// clickable. Two of them, because buttons stand on `SURFACE` and the scrub
42/// strip stands on `CHROME`.
43const HOVER: u32 = 0x3f3f3f;
44const HOVER_DIM: u32 = 0x2c2c2c;
45/// Secondary text -- shortcuts, dismissal hints. Dimmer than `INK` and still
46/// past 4.5:1 on both `SURFACE` and `CHROME`.
47const INK_DIM: u32 = 0xa0a0a0;
48
49/// Fixed so the video region takes every pixel the window gains and the controls
50/// never clip at 640x360.
51const HEADER_H: f32 = 32.;
52// 28 button row + 24 scrub strip + two 48 lanes + the timecode line + the gaps
53// between them, with a few px of slack so a taller text line cannot push a lane
54// off the bottom.
55const PANEL_H: f32 = 220.;
56/// How many lane rows are drawn before the lane column starts scrolling: past
57/// this the panel would be taller than the picture it belongs under, and a
58/// timeline that pushes the video off the window is not a timeline.
59const LANES_MAX: usize = 6;
60const LANE_H: f32 = 48.;
61/// The lane header column: wide enough for `V1`/`A1` and fixed, so both lanes
62/// and the ruler above them start at the same pixel and are the same width --
63/// one x-to-time mapping for the whole timeline. `HEADER_GAP` is part of that
64/// offset and is therefore shared by all three rows.
65const HEADER_W: f32 = 40.;
66const HEADER_GAP: f32 = 4.;
67/// The label row inside a clip; a waveform paints under it, never through it.
68const LABEL_H: f32 = 15.;
69/// A clip narrower than this shows no name: two characters and an ellipsis say
70/// nothing that the tint has not already said, and cost the picture a smear.
71const LABEL_MIN_W: f32 = 36.;
72/// Peak buckets per second of source. Fixed and modest on purpose: `peaks`
73/// allocates one bucket per window, so a rate taken from anything the user can
74/// influence is an allocation bomb -- and 40 is already finer than the pixels a
75/// clip is ever given.
76const WAVE_BPS: u32 = 40;
77/// Pixels per envelope column. Coarser than a pixel: the eye reads the shape,
78/// and a path with a point per pixel is a path per repaint.
79const WAVE_COL: f32 = 2.;
80/// WCAG 2.5.8: nothing clickable is smaller than this. The scrub bar stays 6 px
81/// to look at -- `RULER_HIT_H` is the strip that has to be hit.
82const HIT_MIN: f32 = 24.;
83/// The media library's column: a share of the window rather than a fixed width,
84/// so it yields on a narrow one, and never more than a third of it -- the
85/// picture is what this program is for and keeps the majority at every size.
86/// The floor is what a file name and a timecode need to be readable at all.
87const LIBRARY_FRAC: f32 = 0.2;
88const LIBRARY_MIN_W: f32 = 120.;
89const LIBRARY_MAX_W: f32 = 220.;
90/// A library row: a name over its duration, two lines and a click target, so
91/// `HIT_MIN` binds it like every other one.
92const ROW_H: f32 = 32.;
93/// The tint swatch down the left of a row: the same colour that source's clips
94/// wear in the lanes, which is the whole of the panel<->timeline association.
95const SWATCH_W: f32 = 4.;
96const CONTROL_H: f32 = 28.;
97const RULER_HIT_H: f32 = HIT_MIN;
98/// Wide enough for `HH:MM:SS:FF / HH:MM:SS:FF`, and fixed so changing digits
99/// cannot push the layout around.
100const TIME_W: f32 = 200.;
101/// The keybindings card: a row per action, a title and a status line, inside a
102/// 360 px tall window. The rows are click targets, so `HIT_MIN` binds them too.
103const KEYS_W: f32 = 320.;
104const KEYS_ROW_H: f32 = HIT_MIN;
105/// How much of the row list is on screen at once; past this it scrolls. What
106/// keeps the card inside the smallest window no matter how many actions the
107/// editor grows -- ten rows fit here, and the eleventh is a scroll away.
108const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H;
109/// The same for the export card, which carries a fixed-format line and a button
110/// under its list and so has less room: destination, six formats and five
111/// qualities are twelve rows, eight of them on screen.
112const EXPORT_ROWS_H: f32 = 8. * KEYS_ROW_H;
113/// The menu a right-click on a clip opens: wide enough for the longest label
114/// beside the stroke that does the same thing, with the click targets `HIT_MIN`
115/// binds like every other list here.
116const MENU_W: f32 = 260.;
117const MENU_ROW_H: f32 = HIT_MIN;
118const MENU_PAD: f32 = 6.;
119
120/// The one key name this file still spells out, and gpui's spelling of it: it
121/// is the way out of a capture and out of the overlay, and both have to work
122/// while the keymap itself is what is being changed -- so neither can go
123/// through the keymap to find it.
124const ESCAPE: &str = "escape";
125
126/// What the header says with no timeline open, and what the window title reads
127/// as a program name rather than as a file name.
128const NO_FILE: &str = "no file open";
129
130/// What the monitoring output is set to. Two things, not one: the level the
131/// user picked, and whether it is being held silent -- so unmuting comes back
132/// to the level rather than to a guess.
133///
134/// The level counts steps rather than carrying an `f32`, because 5% at a time
135/// down and back up again through a float would not land on the number it
136/// started from, and the label would eventually read `79%`.
137///
138/// Volume and mute stay independent on purpose: turning the level down while
139/// muted must not be what makes sound come out. Only the mute key unmutes, and
140/// the button says both things at once ("Muted 80%") so neither is a surprise.
141#[derive(Clone, Copy, PartialEq, Eq, Debug)]
142struct Volume {
143 steps: u8,
144 muted: bool,
145}
146
147impl Volume {
148 /// 5% a press: twenty of them across the range.
149 const MAX_STEPS: u8 = 20;
150
151 /// What the device is set to: mute wins, and the level is what it returns
152 /// to. `0.0..=1.0`, which is the range the plugin's ABI accepts.
153 fn gain(self) -> f32 {
154 if self.muted {
155 0.
156 } else {
157 f32::from(self.steps) / f32::from(Self::MAX_STEPS)
158 }
159 }
160
161 /// One press up or down, clamped at both ends -- saturating, so the count
162 /// cannot wrap past silence into full volume.
163 fn step(&mut self, up: bool) {
164 self.steps = if up {
165 self.steps.saturating_add(1).min(Self::MAX_STEPS)
166 } else {
167 self.steps.saturating_sub(1)
168 };
169 }
170
171 /// What the button reads. The level shows while muted too: it is what the
172 /// next press of the mute key brings back.
173 fn label(self) -> String {
174 let percent = u32::from(self.steps) * 100 / u32::from(Self::MAX_STEPS);
175 if self.muted {
176 format!("Muted {percent}%")
177 } else {
178 format!("Vol {percent}%")
179 }
180 }
181}
182
183impl Default for Volume {
184 fn default() -> Self {
185 Self {
186 steps: Self::MAX_STEPS,
187 muted: false,
188 }
189 }
190}
191
192/// What is known about a source's audio. Three states and not two, because a
193/// file whose peaks have not come back yet must not be drawn as one that has no
194/// audio at all: the first shows a bed, the second shows nothing.
195#[derive(Clone)]
196enum Wave {
197 /// Asked for; the decode is running on a background thread.
198 Loading,
199 /// The file has no audio track. An answer, not a miss.
200 Silent,
201 Peaks(Arc<Vec<(f32, f32)>>),
202}
203
204/// A library row being dragged: the file and which of its audio streams that
205/// row is, which is the whole of what a row names. Where it lands does not
206/// change what is inserted.
207struct AssetDrag(PathBuf, usize);
208
209/// An open clip menu: which clip it was opened on, where it hangs, and whether
210/// it has been turned over to show what that clip *is* instead of what can be
211/// done to it. The lane and index are the ones the same click selected, so
212/// every item acts on exactly the box under the pointer.
213#[derive(Clone, Copy)]
214struct ContextMenu {
215 lane: Lane,
216 idx: usize,
217 at: Point<Pixels>,
218 details: bool,
219}
220
221/// What the menu offers, in the order it lists them. Every one of these is an
222/// action a stroke already reaches -- the menu is a second way *to* the actions
223/// and never a second version of them -- so both the label and the hint come
224/// out of the keymap registry and the two can never disagree.
225const MENU_ITEMS: [ActionId; 8] = [
226 ActionId::Cut,
227 ActionId::Delete,
228 ActionId::Lift,
229 ActionId::Regroup,
230 ActionId::Equalizer,
231 ActionId::Color,
232 ActionId::Fit,
233 ActionId::ToggleMute,
234];
235
236/// The project resolutions [`Player::cycle_resolution`] offers, largest first.
237/// A short list of the sizes people name; the media's own is cycled in beside
238/// them, which is what makes the trip round come back to where it started.
239const RESOLUTIONS: [(u32, u32); 4] = [(3840, 2160), (1920, 1080), (1280, 720), (854, 480)];
240
241/// How far a band may be pushed either way, in dB. The engine clamps nothing
242/// here -- it will filter whatever it is given -- so this is a UI decision:
243/// past about this a peaking band stops sounding like tone and starts sounding
244/// like a fault.
245const EQ_GAIN_LIMIT: f32 = 12.;
246
247/// One dB per keystroke, which is roughly the smallest step anyone hears on a
248/// single band.
249const EQ_STEP: f32 = 1.;
250
251/// The gain bar's height inside a band row.
252const EQ_BAR_H: f32 = 6.;
253
254/// The colour card's four controls, in the order it lists them: what each is
255/// called and the range it moves in. The order is `ColorParams`' own, which is
256/// what [`color_band`] indexes.
257const COLOR_BANDS: [(&str, f32, f32); 4] = [
258 ("Brightness", -1., 1.),
259 ("Contrast", 0., 2.),
260 ("Saturation", 0., 2.),
261 ("Tint (cool–warm)", -1., 1.),
262];
263
264/// A press of a nudge key or button: a fortieth of a band's range, so a slider
265/// crosses it in forty presses and every stop is a number the file can write.
266const COLOR_STEP: f32 = 0.05;
267
268/// The card's width: a slider row is a label, two buttons, the bar and the
269/// value, and the longest label has to fit beside all four without truncating
270/// (measured against "Tint (cool–warm)" at 460).
271const COLOR_W: f32 = 460.;
272/// How much of a slider row the bar itself gets.
273const COLOR_BAR_W: f32 = 140.;
274
275struct Player {
276 /// The timeline, once there is one. A run with no file opens without it and
277 /// waits: the first media import or project load is what fills it, and
278 /// until then every action that needs a timeline says so instead of acting.
279 session: Option<PlaybackSession>,
280 /// Timeline seconds -> frame index, so the clock can be compared to what
281 /// the decoder hands over.
282 fps: f64,
283 name: SharedString,
284 image: Option<Arc<RenderImage>>,
285 /// A frame that arrived before its time; shown on the tick it comes due.
286 held: Option<Frame>,
287 /// The decoder's channel closed. Frames may still be waiting in `held`.
288 eos: bool,
289 /// Last frame shown; nothing left to animate.
290 done: bool,
291 /// A seek is waiting for its frame. Keeps the repaint loop alive while
292 /// paused, which is the only way the new still ever reaches the screen.
293 pending_seek: bool,
294 /// The ruler's own box, recorded at prepaint: a mouse listener is handed
295 /// the window position and nothing else.
296 ruler: Rc<Cell<Bounds<Pixels>>>,
297 /// Which clip the edit keys act on: the lane it is in and its index there.
298 /// The *clicked* half, not the group -- a group is what gets marked on
299 /// screen, but Lift has to know which half it was aimed at. Indices move
300 /// under every edit, so this is cleared by all of them.
301 selected: Option<(Lane, usize)>,
302 /// The clip menu a right-click opened, if one is up. Holds an index like
303 /// `selected` does, so it is closed by anything that can move indices --
304 /// every stroke, and every item of its own.
305 context_menu: Option<ContextMenu>,
306 /// Which library row is picked: the file and the audio stream that row
307 /// names, which is what an insert needs and what survives a row list being
308 /// rebuilt. Its own selection and not the timeline's: Delete keeps acting
309 /// on the clip that was clicked in a lane, whatever the library is showing.
310 selected_asset: Option<(PathBuf, usize)>,
311 /// What is known about each source's audio, taken once and kept. Keyed on
312 /// the path *and stream* -- two streams of one file are two envelopes -- and
313 /// the key is inserted the moment the decode is *started*: presence means
314 /// "asked", so a repaint mid-decode cannot ask again.
315 waves: HashMap<(PathBuf, usize), Wave>,
316 /// Which audio streams each imported file has, as its header describes
317 /// them: one library row per entry. Keyed and filled like `waves` --
318 /// presence means "asked" -- and an empty list is a silent file, which is
319 /// exactly one row and no stream tags.
320 streams: HashMap<PathBuf, Vec<StreamInfo>>,
321 /// The copied clip. Frame ranges only, so it survives the clip it was taken
322 /// from being deleted -- and it outlives the selection.
323 clipboard: Option<Clip>,
324 /// A drag that started on the ruler. Moves anywhere in the window scrub
325 /// while it is set; the release commits the exact position.
326 scrubbing: bool,
327 last_scrub: Instant,
328 last_target: u32,
329 /// The running export. While it owns the UI the editor is read-only.
330 export: Option<ExportHandle>,
331 /// The export above was cancelled and is only winding down. The editor is
332 /// already free -- the worker took its own copy of the edit list -- but the
333 /// handle is held until the worker settles, because its last act is to
334 /// delete the output file and a second export must not be what it deletes.
335 cancelling: bool,
336 /// Where an export writes. Built once from the source path, which is not
337 /// otherwise kept.
338 export_path: PathBuf,
339 /// Where the save action writes: the project this timeline was loaded from,
340 /// or the one derived beside the media it started as. Saving twice
341 /// overwrites the same file rather than making a second one.
342 project_path: PathBuf,
343 /// Which stroke means what, and what every shortcut on screen is called.
344 /// The one place either question is answered.
345 keymap: Keymap,
346 /// How loud the monitoring is, and whether it is muted. Lives here rather
347 /// than in the session so it survives closing one file and opening the
348 /// next -- it is a setting of the player, not of the timeline, which is
349 /// also why it is not written to the project file and cannot reach an
350 /// export. [`Player::apply_volume`] is what pushes it at a session.
351 volume: Volume,
352 /// The keybindings overlay is up. While it is, it owns the keyboard and the
353 /// pointer: a stroke or a click meant for a row must not also cut the
354 /// timeline.
355 keys_open: bool,
356 /// The export options card is up: what the export action opens now, so
357 /// nothing is written until the card's own button says so. One card at a
358 /// time -- opening either closes the other, since both are the whole window
359 /// and two stacked scrims say nothing about which one is listening.
360 export_open: bool,
361 /// Which quality row the card has picked, and the megabits typed against
362 /// the custom one. Kept across closes, so a second export offers what the
363 /// first one chose.
364 quality: Quality,
365 custom_mbps: u32,
366 /// Which file the card will write. Kept across closes like the quality, and
367 /// what [`Player::export_path`](Player) is named after.
368 format: Format,
369 /// The equalizer card is up on this clip -- the lane and index it was
370 /// opened on. Held rather than re-read from `selected` every paint because
371 /// the card is modal: while it is up nothing else can move an index, and
372 /// the one edit it makes (`set_eq`) moves none.
373 eq_open: Option<(Lane, usize)>,
374 /// The curve the card is showing, which is the clip's own or the flat
375 /// five-band default. Edited live and written at the clip once per gesture
376 /// ([`Player::commit_eq`]): the project's equalizer table is append-only, so
377 /// a write per pointer sample would be a table entry -- and an undo step --
378 /// per pixel.
379 eq_params: EqParams,
380 /// Which band the keyboard moves, and which one a drag is holding.
381 eq_band: usize,
382 /// A band's bar is being dragged. Tracked on the root like `scrubbing`, for
383 /// the same reason: the pointer leaves the 6 px bar immediately.
384 eq_dragging: bool,
385 /// A band bar's own box, recorded at prepaint. One probe for five rows:
386 /// they are laid out identically and only the *x* of a click is read
387 /// ([`frac_along`]), so whichever row painted last answers for all of them.
388 eq_bar: Rc<Cell<Bounds<Pixels>>>,
389 /// The colour card is up on this clip -- the lane it is on and its index
390 /// there. `None` when it is closed, which is the only place that state
391 /// lives: the grade itself is the project's.
392 color_open: Option<(Lane, usize)>,
393 /// Which of the card's four sliders the arrow keys and the buttons move.
394 /// The card's own focus, since nothing in it takes gpui's (ledger:182).
395 color_band: usize,
396 /// The action whose row is waiting for a stroke. The next key that is
397 /// neither escape nor a lone modifier becomes the whole of what reaches it.
398 rebinding: Option<ActionId>,
399 /// What the last file action had to say. Holds its own bar above the panel
400 /// until it is answered -- any key retires it, so does a click on it -- so a
401 /// failure is read in full instead of blinking past.
402 notice: Option<SharedString>,
403 /// What the compositor was last told this window is called. Setting a title
404 /// is a protocol round trip and a repaint is sixty a second, so the title is
405 /// pushed only when it is not this any more.
406 titled: String,
407 displayed: u32,
408 dropped: u32,
409 /// Wall clock of the first displayed frame -- the real-speed measurement.
410 started: Option<Instant>,
411 focus: FocusHandle,
412}
413
414impl Player {
415 /// Catches the display up to the clock: everything already due is taken off
416 /// the channel and only the last of them is shown, which *is* the
417 /// drop-when-behind policy. A frame that is not due yet waits in `held`.
418 fn pump(&mut self, window: &mut Window) {
419 // No timeline, nothing to catch up to: the window is showing its empty
420 // state and there is no decoder to drain.
421 let Some(session) = &mut self.session else {
422 return;
423 };
424 let target = session.now() * self.fps;
425 let mut newest: Option<Frame> = None;
426 loop {
427 let frame = match self.held.take() {
428 Some(frame) => frame,
429 // Nothing waiting means either a clip boundary being rebuilt or
430 // the real end of the timeline, and only the engine can tell
431 // them apart -- `frame.index` is already a timeline index.
432 None => match session.try_frame() {
433 Some(frame) => frame,
434 None => {
435 self.eos = session.is_eos();
436 break;
437 }
438 },
439 };
440 if f64::from(frame.index) <= target {
441 self.dropped += u32::from(newest.is_some());
442 newest = Some(frame);
443 } else {
444 self.held = Some(frame);
445 break;
446 }
447 }
448
449 if let Some(frame) = newest {
450 self.displayed += 1;
451 self.pending_seek = false;
452 self.started.get_or_insert_with(|| {
453 eprintln!("first frame displayed (index {})", frame.index);
454 Instant::now()
455 });
456 let buf = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra)
457 .expect("frame buffer sized width*height*4");
458 let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)]));
459 if let Some(old) = self.image.replace(next) {
460 // Every RenderImage gets a fresh id and its own atlas tile:
461 // without this the sprite atlas grows for the whole video.
462 let _ = window.drop_image(old);
463 }
464 }
465
466 if self.eos && self.held.is_none() && !self.done {
467 self.done = true;
468 // A seek whose worker never produced a frame (vanished file) would
469 // otherwise repaint at vsync forever.
470 self.pending_seek = false;
471 let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64());
472 eprintln!(
473 "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s",
474 self.displayed,
475 self.dropped,
476 session.now()
477 );
478 }
479 }
480
481 /// Every end-of-stream flag is app state and the engine knows nothing about
482 /// it, so clearing them after a reseek is what stops the picture from
483 /// staying frozen on the old last frame. Edits reseek inside the engine and
484 /// still owe this.
485 fn reset_after_reseek(&mut self) {
486 self.held = None;
487 self.eos = false;
488 self.done = false;
489 self.pending_seek = true;
490 }
491
492 /// What an action does, wherever it was asked for -- a stroke, or the clip
493 /// menu item that names the same action. One table, so the two can never
494 /// come to mean different things.
495 fn act(&mut self, action: ActionId, cx: &mut Context<Self>) {
496 match action {
497 ActionId::Play => self.toggle_or_restart(cx),
498 ActionId::Export => self.open_export(cx),
499 ActionId::Save => self.save_project(cx),
500 ActionId::Copy => self.copy_selected(),
501 ActionId::Paste => self.paste(cx),
502 ActionId::Cut => self.cut(cx),
503 ActionId::Regroup => self.regroup(cx),
504 ActionId::Select => self.select_under_playhead(cx),
505 ActionId::SelectNext => self.select_step(true, cx),
506 ActionId::SelectPrev => self.select_step(false, cx),
507 ActionId::Delete => self.delete_selected(cx),
508 ActionId::Lift => self.lift_selected(cx),
509 ActionId::Color => self.open_color(cx),
510 ActionId::Fit => self.cycle_fit(cx),
511 ActionId::Resolution => self.cycle_resolution(cx),
512 ActionId::Undo => self.undo(cx),
513 ActionId::AddVideoLane => self.add_lane(LaneKind::Video, cx),
514 ActionId::AddAudioLane => self.add_lane(LaneKind::Audio, cx),
515 ActionId::ToggleMute => self.set_volume(|volume| volume.muted = !volume.muted, cx),
516 ActionId::VolumeUp => self.set_volume(|volume| volume.step(true), cx),
517 ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx),
518 ActionId::Equalizer => self.open_eq(cx),
519 // Nothing to cancel while nothing is exporting; the export guard in
520 // the key handler is what answers this one while there is.
521 ActionId::CancelExport => {}
522 }
523 }
524
525 /// The one place a clip becomes *the* selected one: a click, a right-click
526 /// that opens the menu, and every selection key go through here, so what a
527 /// keyboard marks and what a pointer marks are the same state marked the
528 /// same way (group and all -- see [`marked`]).
529 fn select(&mut self, target: (Lane, usize), cx: &mut Context<Self>) {
530 self.selected = Some(target);
531 cx.notify();
532 }
533
534 /// Every clip the playhead is over, one per lane, in the order the lanes are
535 /// drawn -- video first, which is the order [`PlaybackSession::lanes`] comes
536 /// in. What the select key walks.
537 fn under_playhead(&self) -> Vec<(Lane, usize)> {
538 let Some(session) = &self.session else {
539 return Vec::new();
540 };
541 let now = session.now();
542 session
543 .lanes()
544 .into_iter()
545 .filter_map(|lane| Some((lane, session.lane_clip_at(lane, now)?)))
546 .collect()
547 }
548
549 /// Selects the clip under the playhead, and on a repeat press the next
550 /// lane's -- so one key reaches every clip the playhead is over, which is
551 /// what makes selection (and everything that acts on a selection: delete,
552 /// lift, the equalizer, the grade) reachable with no pointer at all.
553 fn select_under_playhead(&mut self, cx: &mut Context<Self>) {
554 let under = self.under_playhead();
555 let Some(&first) = under.first() else {
556 self.notice = Some("NOTHING UNDER THE PLAYHEAD — move it onto a clip first".into());
557 cx.notify();
558 return;
559 };
560 // Where the current selection sits in that walk decides what "again"
561 // means; a selection off the playhead starts the walk over.
562 let next = self
563 .selected
564 .and_then(|sel| under.iter().position(|&clip| clip == sel))
565 .map_or(first, |at| under[(at + 1) % under.len()]);
566 self.select(next, cx);
567 }
568
569 /// Walks the selection along its own lane, wrapping at either end. Nothing
570 /// selected means nothing to walk from, so it selects under the playhead
571 /// exactly as the select key does: either key can start as well as continue.
572 fn select_step(&mut self, forward: bool, cx: &mut Context<Self>) {
573 let clips = self
574 .selected
575 .zip(self.session.as_ref())
576 .map_or(0, |((lane, _), session)| session.lane_clips(lane).len());
577 match (self.selected, clips) {
578 // An empty lane is a selection nothing can be stepped from -- as is
579 // no selection at all, and the playhead answers both.
580 (Some((lane, idx)), len) if len > 0 => {
581 let next = if forward {
582 (idx + 1) % len
583 } else {
584 (idx + len - 1) % len
585 };
586 self.select((lane, next), cx);
587 }
588 _ => self.select_under_playhead(cx),
589 }
590 }
591
592 /// Cycles the fit policy of the clip the picture is coming from -- the
593 /// clicked one when it is a video clip, else the composite's own, exactly as
594 /// the colour card picks its target. A whole card for one four-valued
595 /// setting would be a card to close; a stroke that cycles it and says what
596 /// it landed on is the same setting with nothing to dismiss.
597 ///
598 /// Only means anything when the clip is not the project's size -- a clip
599 /// that already fills the canvas looks the same under all four -- so the
600 /// notice says the size it is placing, not just the word.
601 fn cycle_fit(&mut self, cx: &mut Context<Self>) {
602 if self.exporting().is_some() {
603 return;
604 }
605 let Some(session) = &mut self.session else {
606 self.notice = Some("no timeline to fit — open a file first".into());
607 cx.notify();
608 return;
609 };
610 let target = self
611 .selected
612 .filter(|(lane, _)| lane.kind == LaneKind::Video)
613 .or_else(|| session.video_clip_at(session.now()));
614 let Some((lane, idx)) = target else {
615 self.notice = Some("no clip under the playhead to fit".into());
616 cx.notify();
617 return;
618 };
619 let next = next_fit(session.fit_of(lane, idx));
620 if session.set_fit(lane, idx, next) {
621 let (w, h) = session.resolution();
622 self.notice = Some(format!("FIT POLICY: {} on {w}x{h}", fit_label(next)).into());
623 self.reset_after_reseek();
624 }
625 cx.notify();
626 }
627
628 /// Cycles the *project's* resolution through [`RESOLUTIONS`], starting from
629 /// the media's own -- the one size that must stay reachable, since a project
630 /// moved off it has no other way back (the resolution is not an undo step).
631 /// Every clip is recomposed onto it, so this is what makes "the project
632 /// resolution and the media's are different things" a thing a user can see.
633 fn cycle_resolution(&mut self, cx: &mut Context<Self>) {
634 if self.exporting().is_some() {
635 return;
636 }
637 let Some(session) = &mut self.session else {
638 self.notice = Some("no timeline to resize — open a file first".into());
639 cx.notify();
640 return;
641 };
642 let (width, height) = next_resolution(session.resolution(), session.native_resolution());
643 if session.set_resolution(width, height) {
644 self.notice = Some(format!("PROJECT: {width}x{height}").into());
645 self.reset_after_reseek();
646 }
647 cx.notify();
648 }
649
650 /// Opens the colour card on the clip a grade would go on: the clip that was
651 /// clicked when it is a video one, and otherwise the clip the picture is
652 /// coming from -- the one the engine's own compositing rule picks, which is
653 /// what a person means by "this shot". The fallback stands even now that a
654 /// selection key exists: a grade asked for with nothing selected still means
655 /// the shot on screen.
656 fn open_color(&mut self, cx: &mut Context<Self>) {
657 if self.exporting().is_some() {
658 return;
659 }
660 let Some(session) = &self.session else {
661 self.notice = Some("no timeline to grade — open a file first".into());
662 cx.notify();
663 return;
664 };
665 let target = self
666 .selected
667 .filter(|(lane, _)| lane.kind == LaneKind::Video)
668 .or_else(|| session.video_clip_at(session.now()));
669 match target {
670 Some(clip) => {
671 self.color_open = Some(clip);
672 self.color_band = 0;
673 // One card at a time, the rule both the others already follow.
674 self.keys_open = false;
675 self.export_open = false;
676 self.context_menu = None;
677 }
678 None => self.notice = Some("no clip under the playhead to grade".into()),
679 }
680 cx.notify();
681 }
682
683 /// What the card's clip is graded by right now -- the identity for one
684 /// nobody has graded, which is what the sliders start at.
685 fn color_params(&self) -> ColorParams {
686 self.color_open
687 .zip(self.session.as_ref())
688 .and_then(|((lane, idx), session)| session.color_of(lane, idx).copied())
689 .unwrap_or_default()
690 }
691
692 /// Puts `params` on the card's clip, or takes the grade off when they are
693 /// the identity -- a slider walked back to the middle leaves the clip
694 /// ungraded rather than carrying a do-nothing entry, which is what keeps an
695 /// untouched project byte-identical. The engine reseeks on the edit, so the
696 /// frame on screen repaints through the new grade; this only owes the flags
697 /// that reseek clears.
698 fn set_color(&mut self, params: ColorParams, cx: &mut Context<Self>) {
699 let Some((lane, idx)) = self.color_open else {
700 return;
701 };
702 let Some(session) = &mut self.session else {
703 return;
704 };
705 let grade = Some(params).filter(|p| !p.is_identity());
706 if session.set_color(lane, idx, grade) {
707 self.reset_after_reseek();
708 }
709 cx.notify();
710 }
711
712 /// Moves the picked slider by `steps` of [`COLOR_STEP`], clamped to that
713 /// band's range. One edit, so one undo step per press.
714 fn nudge_color(&mut self, steps: f32, cx: &mut Context<Self>) {
715 let mut params = self.color_params();
716 let (_, low, high) = COLOR_BANDS[self.color_band];
717 let value = band_mut(&mut params, self.color_band);
718 *value = (*value + steps * COLOR_STEP).clamp(low, high);
719 self.set_color(params, cx);
720 }
721
722 /// Whether a card owns the window. While one does the timeline under it is
723 /// out of reach, so a right-click there opens no menu -- the same rule the
724 /// key handler and the drop target already follow.
725 fn modal(&self) -> bool {
726 self.keys_open
727 || self.export_open
728 || self.eq_open.is_some()
729 || self.color_open.is_some()
730 || self.exporting().is_some()
731 }
732
733 /// Opens the equalizer on the selected clip. Audio only, and it says so
734 /// rather than opening a card of bands that would reach nothing: a video
735 /// clip carries no sound of its own here (the sound is the audio lane's),
736 /// and the model would take the setting without anything ever playing it.
737 fn open_eq(&mut self, cx: &mut Context<Self>) {
738 if self.exporting().is_some() {
739 return;
740 }
741 let refusal = match (self.selected, &self.session) {
742 (_, None) => Some("NO TIMELINE — open a file first".to_string()),
743 (None, _) => Some(format!(
744 "NOTHING SELECTED — click an audio clip or press {}, then ask again",
745 self.keymap.display(ActionId::Select)
746 )),
747 (Some((lane, _)), _) if lane.kind != LaneKind::Audio => Some(
748 "NOT AN AUDIO CLIP — the equalizer works on the sound, so pick a clip in an audio lane".to_string(),
749 ),
750 _ => None,
751 };
752 if let Some(refusal) = refusal {
753 self.notice = Some(refusal.into());
754 cx.notify();
755 return;
756 }
757 let (lane, idx) = self.selected.expect("checked above");
758 let session = self.session.as_ref().expect("checked above");
759 // What the clip already plays through, or the flat default -- so the
760 // card opens on the curve that is in force and a reopen shows the last
761 // drag rather than a fresh set of zeroes.
762 self.eq_params = session
763 .eq_of(lane, idx)
764 .cloned()
765 .unwrap_or_else(EqParams::default_layout);
766 self.eq_band = 0;
767 self.eq_dragging = false;
768 self.eq_open = Some((lane, idx));
769 // One card at a time, the rule the other two already follow.
770 self.keys_open = false;
771 self.export_open = false;
772 self.context_menu = None;
773 cx.notify();
774 }
775
776 /// Writes what the card is showing at its clip: one undo step, one entry in
777 /// the append-only equalizer table, so this is called once per *gesture* --
778 /// the end of a drag, a keystroke -- and never per pointer sample.
779 ///
780 /// A curve that moves nothing is stored as *no* equalizer at all, which is
781 /// what keeps a clip nobody has touched on the identity path through
782 /// playback and export (`engine::eq::EqParams::is_identity`).
783 fn commit_eq(&mut self, cx: &mut Context<Self>) {
784 let Some((lane, idx)) = self.eq_open else {
785 return;
786 };
787 let params = (!self.eq_params.is_identity()).then(|| self.eq_params.clone());
788 if let Some(session) = &mut self.session {
789 session.set_eq(lane, idx, params);
790 }
791 // `set_eq` reseeks inside the engine -- that is what makes the change
792 // audible at once -- and a reseek is what these flags are about.
793 self.reset_after_reseek();
794 cx.notify();
795 }
796
797 /// Moves one band and says whether anything changed. Live only: the write
798 /// is [`commit_eq`](Player::commit_eq)'s.
799 fn set_band(&mut self, band: usize, gain_db: f32) -> bool {
800 let gain_db = gain_db.clamp(-EQ_GAIN_LIMIT, EQ_GAIN_LIMIT);
801 match self.eq_params.bands.get_mut(band) {
802 Some(b) if b.gain_db != gain_db => {
803 b.gain_db = gain_db;
804 true
805 }
806 _ => false,
807 }
808 }
809
810 /// The keyboard's version of a drag: one step on the picked band, committed
811 /// straight away -- a keystroke has no release to wait for.
812 fn nudge_band(&mut self, by: f32, cx: &mut Context<Self>) {
813 let gain = self
814 .eq_params
815 .bands
816 .get(self.eq_band)
817 .map_or(0., |b| b.gain_db);
818 if self.set_band(self.eq_band, gain + by) {
819 self.commit_eq(cx);
820 }
821 }
822
823 /// Where the pointer sits along a band's bar, as a gain: the middle is flat
824 /// and the two ends are the limit either way.
825 fn drag_band(&mut self, x: Pixels, cx: &mut Context<Self>) {
826 let gain = (frac_along(x, self.eq_bar.get()) * 2. - 1.) * EQ_GAIN_LIMIT;
827 if self.set_band(self.eq_band, gain) {
828 cx.notify();
829 }
830 }
831
832 /// Jumps the timeline.
833 fn seek(&mut self, t: f64, cx: &mut Context<Self>) {
834 if self.exporting().is_some() {
835 return;
836 }
837 let Some(session) = &mut self.session else {
838 return;
839 };
840 session.seek(t);
841 self.reset_after_reseek();
842 cx.notify();
843 }
844
845 /// Splits the clip under the playhead. Metadata only: the timeline->source
846 /// mapping is unchanged, so nothing reseeks and no flag is touched.
847 fn cut(&mut self, cx: &mut Context<Self>) {
848 if self.exporting().is_some() {
849 return;
850 }
851 if let Some(session) = &mut self.session {
852 session.cut_at(session.now());
853 }
854 self.selected = None;
855 cx.notify();
856 }
857
858 /// Rejoins whatever meets under the playhead and puts it back in one group
859 /// -- the inverse of [`Player::cut`], and metadata only like it. The engine
860 /// decides what is joinable; a refusal is worded here, because `false` is
861 /// all it says and a key that looks broken is worse than one that explains
862 /// itself.
863 fn regroup(&mut self, cx: &mut Context<Self>) {
864 if self.exporting().is_some() {
865 return;
866 }
867 if let Some(session) = &mut self.session {
868 if session.regroup_at(session.now()) {
869 self.selected = None;
870 } else {
871 self.notice = Some(
872 "NOTHING TO REGROUP — put the playhead where two clips meet, on frames that were cut apart"
873 .into(),
874 );
875 }
876 }
877 cx.notify();
878 }
879
880 /// Drops the selected clip and closes the hole: a whole take goes, both
881 /// lanes of it, and everything after it moves up. A half with no take under
882 /// it in the video lane -- what a lift leaves behind -- has nothing to
883 /// ripple, so that one is lifted instead. The engine reseeks itself, so all
884 /// this owes is the flag reset.
885 fn delete_selected(&mut self, cx: &mut Context<Self>) {
886 if self.exporting().is_some() {
887 return;
888 }
889 let selected = self.selected.take();
890 // Whichever lane it was clicked in: the index is that lane's own, and
891 // the ripple cuts the clip's span out of every lane -- a group covers
892 // one span, so deleting a take by its audio half is the same edit as by
893 // its picture. What is not a whole take is lifted instead, which is what
894 // reaches a clip on an added track ([`whole_take`]).
895 let deleted = match (&mut self.session, selected) {
896 (Some(session), Some((lane, idx))) => match whole_take(session, lane, idx) {
897 true => session.delete_clip(lane, idx),
898 false => session.lift_clip(lane, idx),
899 },
900 _ => false,
901 };
902 if selected.is_some() && !deleted {
903 self.notice = Some("NOTHING DELETED — the timeline cannot be emptied".into());
904 }
905 if deleted {
906 self.reset_after_reseek();
907 }
908 cx.notify();
909 }
910
911 /// Lifts the selected half out and leaves the hole: black picture there if
912 /// it was the video lane, silence if it was the audio one, and nothing else
913 /// moves. What Delete is not.
914 fn lift_selected(&mut self, cx: &mut Context<Self>) {
915 if self.exporting().is_some() {
916 return;
917 }
918 match (&mut self.session, self.selected.take()) {
919 (Some(session), Some((lane, idx))) => {
920 if session.lift_clip(lane, idx) {
921 self.reset_after_reseek();
922 } else {
923 self.notice = Some("NOTHING LIFTED — the timeline cannot be emptied".into());
924 }
925 }
926 (Some(_), None) => {
927 self.notice = Some("NOTHING LIFTED — click the half to remove first".into())
928 }
929 (None, _) => {}
930 }
931 cx.notify();
932 }
933
934 /// Copies the selected clip. Nothing on screen changes, so no notify.
935 fn copy_selected(&mut self) {
936 let session = self.session.as_ref();
937 // Out of the lane it was clicked in: the audio half of a group is a
938 // different clip from the video one, and copying the wrong lane's
939 // frames is a paste of the wrong thing.
940 if let Some(clip) = self
941 .selected
942 .and_then(|(lane, idx)| session?.lane_clips(lane).get(idx).copied())
943 {
944 self.clipboard = Some(clip);
945 }
946 }
947
948 /// Starts a peak decode -- and a stream probe -- for every source that has
949 /// arrived since the last
950 /// repaint. One call from the render rather than three at the doors,
951 /// because argv, an import and a project load are all doors and only this
952 /// one is guaranteed to run after each of them.
953 ///
954 /// The decode itself runs on a background thread, like the file chooser:
955 /// whole-file audio decode is ~1 s for a half-hour source, and on the render
956 /// path that is the window not painting for a second. The lane draws a bed
957 /// meanwhile and the repaint comes with the peaks. The entry is written
958 /// *before* the spawn, so the sixty repaints that happen while a decode runs
959 /// start no further ones.
960 fn cache_media(&mut self, cx: &mut Context<Self>) {
961 let Some(session) = &self.session else {
962 return;
963 };
964 // Which audio streams each file has, for the library's rows. Header
965 // only, but a big file's sample tables are not free to parse, so it
966 // goes off the render thread like the peaks do.
967 for path in unseen_paths(session.sources(), &self.streams) {
968 self.streams.insert(path.clone(), Vec::new());
969 let probed = cx.background_executor().spawn({
970 let path = path.clone();
971 async move { engine::AudioSession::probe_streams(&path).unwrap_or_default() }
972 });
973 cx.spawn(async move |this, cx| {
974 let probed = probed.await;
975 this.update(cx, |this, cx| {
976 this.streams.insert(path, probed);
977 cx.notify();
978 })
979 .ok();
980 })
981 .detach();
982 }
983 for key in unseen_sources(session.sources(), &self.waves) {
984 self.waves.insert(key.clone(), Wave::Loading);
985 let decoded = cx.background_executor().spawn({
986 let (path, stream) = key.clone();
987 async move {
988 engine::waveform::peaks(&path, stream, WAVE_BPS)
989 .ok()
990 .flatten()
991 .map(|peaks| Arc::new(normalise(peaks)))
992 }
993 });
994 cx.spawn(async move |this, cx| {
995 let decoded = decoded.await;
996 this.update(cx, |this, cx| {
997 this.waves.insert(
998 key,
999 match decoded {
1000 Some(peaks) => Wave::Peaks(peaks),
1001 // Either no audio track or a file we could not read
1002 // it from; both mean the lane has nothing to draw,
1003 // and neither is worth asking about again.
1004 None => Wave::Silent,
1005 },
1006 );
1007 cx.notify();
1008 })
1009 .ok();
1010 })
1011 .detach();
1012 }
1013 }
1014
1015 /// The group id of the clicked clip, which is what marks the other half.
1016 fn selected_link(&self) -> Option<u32> {
1017 let (lane, idx) = self.selected?;
1018 self.session.as_ref()?.lane_clips(lane).get(idx)?.link
1019 }
1020
1021 /// Drops the copied clip in at the playhead. The engine reseeks itself, so
1022 /// like a delete this owes the flag reset -- and the selection, whose index
1023 /// the insert has just moved.
1024 fn paste(&mut self, cx: &mut Context<Self>) {
1025 let pasted = match (&mut self.session, self.clipboard) {
1026 (Some(session), Some(clip)) => session.paste_at(session.now(), clip),
1027 _ => false,
1028 };
1029 if pasted {
1030 self.selected = None;
1031 self.reset_after_reseek();
1032 }
1033 cx.notify();
1034 }
1035
1036 /// The one way a library row reaches the timeline: the Add button and a row
1037 /// dragged onto a lane both come here, so there is a single answer to what
1038 /// "add this source" does. The whole source goes in at the playhead as one
1039 /// grouped take -- the same insert a paste makes, so everything after it
1040 /// moves along rather than being painted over. Reseeks like every other
1041 /// edit, and drops the timeline's selection with it: the insert has just
1042 /// moved the indices it pointed at.
1043 fn insert_source(
1044 &mut self,
1045 path: &Path,
1046 stream: usize,
1047 onto: Option<Lane>,
1048 cx: &mut Context<Self>,
1049 ) {
1050 if self.exporting().is_some() {
1051 return;
1052 }
1053 // A file with no picture belongs on an audio lane and nowhere else:
1054 // dropped on a video lane it is refused by name, and asked for by the
1055 // Add button (which names no lane) it goes to the audio one -- which is
1056 // the engine's choice, in `place_stream_at`, not one made twice here.
1057 if engine::is_audio(path) && onto.is_some_and(|lane| lane.kind == LaneKind::Video) {
1058 let name = file_name(path);
1059 let lane = onto.expect("checked above").label();
1060 self.notice = Some(
1061 format!("NOT ON {lane} — {name} has no picture; drop it on an audio lane").into(),
1062 );
1063 cx.notify();
1064 return;
1065 }
1066 let frames = self.session.as_ref().map_or(0, |session| {
1067 source_frames(lane_clips(session), session.sources(), path)
1068 });
1069 // Zero means nothing on the timeline plays from that file any more
1070 // -- an undone import leaves the source entry behind (project.rs:264)
1071 // -- so there is no length to insert and no file to ask for one.
1072 let placed = match (&mut self.session, frames) {
1073 (Some(session), 1..) => {
1074 session.place_stream_at(session.now(), path, stream, frames, onto)
1075 }
1076 _ => Ok(false),
1077 };
1078 match placed {
1079 Ok(true) => {
1080 self.selected = None;
1081 self.reset_after_reseek();
1082 }
1083 // The engine's own words: a stream that cannot join this timeline
1084 // says which property disagrees, exactly as a refused import does.
1085 Err(e) => self.notice = Some(format!("NOTHING ADDED — {e}").into()),
1086 Ok(false) => {
1087 self.notice = Some(
1088 "NOTHING ADDED — no clip on the timeline plays from that file any more".into(),
1089 )
1090 }
1091 }
1092 cx.notify();
1093 }
1094
1095 /// The rate and layout the whole timeline's audio is, taken from source 0's
1096 /// own stream: what a library row has to match to be placeable. `None`
1097 /// until that file has been probed, and then nothing is greyed for it.
1098 fn timeline_audio(&self) -> Option<(u32, u16)> {
1099 let first = self.session.as_ref()?.sources().first()?;
1100 let info = self
1101 .streams
1102 .get(&first.path)?
1103 .iter()
1104 .find(|s| s.index == first.audio_stream)?;
1105 Some((info.sample_rate, info.channels))
1106 }
1107
1108 /// Appends a file to the end of the timeline. A drop is not a key press, so
1109 /// the export guard on the key handler does not cover it and this checks for
1110 /// itself. The engine reseeks, so like a delete it owes the flag reset; a
1111 /// refusal is shown as the engine worded it and changes nothing.
1112 fn import(&mut self, path: &std::path::Path, cx: &mut Context<Self>) {
1113 if self.exporting().is_some() {
1114 return;
1115 }
1116 // An empty window has nothing to append to: there the first file *is*
1117 // the timeline and is opened as one, which is the same fork a launch
1118 // makes between its first argument and the rest.
1119 let text = match self.session.as_mut().map(|session| session.import(path)) {
1120 Some(Ok(())) => {
1121 self.reset_after_reseek();
1122 format!("IMPORTED {}", file_name(path))
1123 }
1124 Some(Err(e)) => format!("IMPORT FAILED: {e}"),
1125 None => self.open_media(path),
1126 };
1127 eprintln!("{text}");
1128 self.notice = Some(text.into());
1129 cx.notify();
1130 }
1131
1132 /// Takes a file as the whole timeline, which is what an empty window is
1133 /// waiting for. Everything derived from the media -- the clock, the title,
1134 /// where an export and a save go -- is set here, exactly as a launch with a
1135 /// file argument sets it. Paused with its first frame showing, like every
1136 /// other way a timeline arrives.
1137 fn open_media(&mut self, path: &std::path::Path) -> String {
1138 match PlaybackSession::open(path) {
1139 Ok(session) => {
1140 self.fps = session.meta().frame_rate;
1141 // Read before the session moves: a file that plays silent says
1142 // so here or nowhere.
1143 let silent = audio_notice(&session);
1144 self.session = Some(session);
1145 // A fresh session comes up at full volume; the player's own
1146 // setting outlives the file, so it is pushed at every new one.
1147 self.apply_volume();
1148 // Beside the new file, but still the format the card is set to:
1149 // opening another clip is not a change of mind about that.
1150 self.export_path = retarget(&export_path(path), self.format);
1151 self.project_path = project_path(path);
1152 self.name = file_name(path).into();
1153 self.reset_after_reseek();
1154 format!("OPENED {}{}", file_name(path), silent.unwrap_or_default())
1155 }
1156 Err(e) => format!("OPEN FAILED: {e}"),
1157 }
1158 }
1159
1160 /// The Import button: asks the desktop for a path and takes it the same way
1161 /// a drop would. The chooser is another process and the user may sit in it,
1162 /// so it runs on a background thread -- blocking here would freeze the
1163 /// window behind the dialog.
1164 fn pick_and_import(&mut self, cx: &mut Context<Self>) {
1165 if self.exporting().is_some() {
1166 return;
1167 }
1168 let picked = cx.background_executor().spawn(async { pick_file() });
1169 cx.spawn(async move |this, cx| {
1170 let picked = picked.await;
1171 this.update(cx, |this, cx| match picked {
1172 // The same fork the drop handler makes: a project replaces the
1173 // timeline, media is appended to it.
1174 Ok(Some(path)) if is_project(&path) => this.load_project(&path, cx),
1175 Ok(Some(path)) => this.import(&path, cx),
1176 // Cancelled: the user already knows what happened.
1177 Ok(None) => {}
1178 Err(text) => {
1179 eprintln!("{text}");
1180 this.notice = Some(text.into());
1181 cx.notify();
1182 }
1183 })
1184 .ok();
1185 })
1186 .detach();
1187 }
1188
1189 /// Swaps the whole timeline for one restored from a `.edith`. Like an
1190 /// import this arrives by drop and so checks the export guard for itself.
1191 /// The new session is built before anything is replaced, so a refusal is
1192 /// shown as the engine worded it and leaves what is playing alone.
1193 fn load_project(&mut self, path: &std::path::Path, cx: &mut Context<Self>) {
1194 if self.exporting().is_some() {
1195 return;
1196 }
1197 let text = match PlaybackSession::open_project(path) {
1198 Ok(session) => {
1199 self.fps = session.meta().frame_rate;
1200 let silent = audio_notice(&session);
1201 // A project is named after itself but still exports beside its
1202 // media: that is the only place an export has ever landed.
1203 self.export_path = retarget(&export_path(&session.sources()[0].path), self.format);
1204 self.session = Some(session);
1205 self.apply_volume();
1206 self.project_path = path.to_path_buf();
1207 self.name = file_name(path).into();
1208 // A copied clip names its source by index, which means a
1209 // different file -- or none -- in another project.
1210 self.clipboard = None;
1211 self.selected = None;
1212 // A menu can be up while a project is dropped on the window --
1213 // the scrim swallows clicks, never a drop -- and its index
1214 // would name some other timeline's clip. The two clip cards
1215 // hold a (lane, idx) of the old timeline for the same reason.
1216 self.context_menu = None;
1217 self.eq_open = None;
1218 self.color_open = None;
1219 // A different set of sources: the row that was picked is not
1220 // the file that index names any more.
1221 self.selected_asset = None;
1222 // The counters describe one timeline; the eof line must not
1223 // report the old one's frames against the new one.
1224 self.displayed = 0;
1225 self.dropped = 0;
1226 self.started = None;
1227 // Loaded paused at its saved playhead, so the still it owes
1228 // reaches the screen the way a seek's does. The old picture is
1229 // released by the swap in `pump`, as after any other seek.
1230 self.reset_after_reseek();
1231 format!("LOADED {}{}", file_name(path), silent.unwrap_or_default())
1232 }
1233 Err(e) => format!("OPEN FAILED: {e}"),
1234 };
1235 eprintln!("{text}");
1236 self.notice = Some(text.into());
1237 cx.notify();
1238 }
1239
1240 /// Writes the timeline back to its project file. Overwrites silently, like
1241 /// an export: the path was chosen once and the notice is the confirmation.
1242 fn save_project(&mut self, cx: &mut Context<Self>) {
1243 let saved = self
1244 .session
1245 .as_ref()
1246 .map(|session| session.save_project(&self.project_path));
1247 let text = match saved {
1248 Some(Ok(())) => format!("SAVED {}", file_name(&self.project_path)),
1249 Some(Err(e)) => format!("SAVE FAILED: {e}"),
1250 None => "NOTHING TO SAVE — open a file first".to_string(),
1251 };
1252 eprintln!("{text}");
1253 self.notice = Some(text.into());
1254 cx.notify();
1255 }
1256
1257 /// A new empty track under the ones already there. One undo step in the
1258 /// engine, so the stroke that takes back an edit takes back a track too, and
1259 /// no reseek: nothing plays differently until something is dropped on it.
1260 /// The selection stays -- the lanes it indexes into have not moved.
1261 fn add_lane(&mut self, kind: LaneKind, cx: &mut Context<Self>) {
1262 if self.exporting().is_some() {
1263 return;
1264 }
1265 match &mut self.session {
1266 Some(session) => {
1267 let lane = session.add_lane(kind);
1268 self.notice = Some(
1269 format!(
1270 "{} ADDED — drag a clip onto it, {} takes it back",
1271 lane.label(),
1272 self.keymap.display(ActionId::Undo)
1273 )
1274 .into(),
1275 );
1276 }
1277 None => self.notice = Some("NO TRACK ADDED — open a file first".into()),
1278 }
1279 cx.notify();
1280 }
1281
1282 fn undo(&mut self, cx: &mut Context<Self>) {
1283 if self.session.as_mut().is_some_and(PlaybackSession::undo) {
1284 self.reset_after_reseek();
1285 }
1286 self.selected = None;
1287 cx.notify();
1288 }
1289
1290 /// The stroke a waiting row was after: it becomes the whole of what reaches
1291 /// that action, which is what the row was showing. A chord another action
1292 /// already holds is refused by the keymap and the row keeps waiting, so the
1293 /// next stroke is another try rather than a lost one. A binding that took
1294 /// holds either way:
1295 /// what a failed write costs is only the next run, which is what the notice
1296 /// is for.
1297 fn capture(&mut self, action: ActionId, key: &str, ctrl: bool) {
1298 let chord = keymap::Chord {
1299 key: key.to_string(),
1300 ctrl,
1301 };
1302 // Only a stroke the file can spell and read back as itself: gpui reports
1303 // "+" for shift+=, which is the chord grammar's separator, so binding it
1304 // would write a line the next load would have to drop. Refused here, in
1305 // front of the user, rather than silently costing that binding later.
1306 // The row keeps waiting, as it does for a stroke already taken.
1307 if !chord.bindable() {
1308 let text = format!("THAT KEY CANNOT BE BOUND — {}", chord.pretty());
1309 eprintln!("{text}");
1310 self.notice = Some(text.into());
1311 return;
1312 }
1313 let text = match self.keymap.rebind_action(action, chord.clone()) {
1314 Ok(()) => {
1315 self.rebinding = None;
1316 match self.keymap.save() {
1317 Ok(()) => return,
1318 Err(e) => format!(
1319 "KEYBINDINGS NOT SAVED — {}: {e}",
1320 Keymap::config_path().display()
1321 ),
1322 }
1323 }
1324 Err(holder) => format!("ALREADY BOUND — {} is {}", chord.pretty(), holder.label()),
1325 };
1326 eprintln!("{text}");
1327 self.notice = Some(text.into());
1328 }
1329
1330 /// Seeks to where the pointer sits along the ruler. `commit` is the press
1331 /// and the release, which must land exactly even when the throttle below
1332 /// would have skipped them.
1333 fn scrub_to(&mut self, x: Pixels, commit: bool, cx: &mut Context<Self>) {
1334 let Some(session) = &self.session else {
1335 return;
1336 };
1337 let t = f64::from(frac_along(x, self.ruler.get())) * session.timeline_duration();
1338 let target = (t * self.fps) as u32;
1339 if commit || scrub_due(target, self.last_target, self.last_scrub.elapsed()) {
1340 self.last_target = target;
1341 self.last_scrub = Instant::now();
1342 self.seek(t, cx);
1343 }
1344 }
1345
1346 /// The play binding and the transport button share it: once the timeline is finished
1347 /// the only sensible "play" is from the top.
1348 /// Pushes the current volume at the session, which is the only place it is
1349 /// ever pushed: after a change here, and after a session arrives. A session
1350 /// starts at full volume, so a file opened while muted has to be told --
1351 /// that is the whole reason this is not just called from the key handler.
1352 /// Silent no-op with no timeline, or with a run that has no audio device.
1353 fn apply_volume(&self) {
1354 if let Some(session) = &self.session {
1355 session.set_gain(self.volume.gain());
1356 }
1357 }
1358
1359 /// The mute key and the two volume keys, and the click on the button. The
1360 /// picture is not touched: silencing the output is not pausing it, so the
1361 /// clock -- which the device still drives -- runs straight through.
1362 fn set_volume(&mut self, change: impl FnOnce(&mut Volume), cx: &mut Context<Self>) {
1363 change(&mut self.volume);
1364 self.apply_volume();
1365 cx.notify();
1366 }
1367
1368 fn toggle_or_restart(&mut self, cx: &mut Context<Self>) {
1369 if self.exporting().is_some() {
1370 return;
1371 }
1372 if self.done {
1373 self.seek(0., cx);
1374 if let Some(session) = &mut self.session {
1375 session.play();
1376 }
1377 } else if let Some(session) = &mut self.session {
1378 session.toggle();
1379 // Past EOF nothing else asks for a repaint.
1380 cx.notify();
1381 }
1382 }
1383
1384 /// The export that owns the UI, if any. A cancelled one does not: it has
1385 /// its own copy of the edit list and owes only its own cleanup.
1386 fn exporting(&self) -> Option<&ExportHandle> {
1387 self.export.as_ref().filter(|_| !self.cancelling)
1388 }
1389
1390 /// What the export action does now: opens the card, which is where the
1391 /// quality, the destination and the decision to write at all are. Nothing
1392 /// is encoded until the button in it is pressed.
1393 fn open_export(&mut self, cx: &mut Context<Self>) {
1394 if self.export.is_some() {
1395 return;
1396 }
1397 // Nothing to write out, and a refusal rather than a card about it: the
1398 // window is empty and the export path is not even chosen yet.
1399 if self.session.is_none() {
1400 self.notice = Some("NOTHING TO EXPORT — open a file first".into());
1401 cx.notify();
1402 return;
1403 }
1404 self.export_open = true;
1405 // One card at a time, and a waiting row must not outlive the card it
1406 // was waiting in.
1407 self.keys_open = false;
1408 self.rebinding = None;
1409 cx.notify();
1410 }
1411
1412 /// A format row was clicked. The destination follows it at once -- a WAV
1413 /// written to a path ending in `.mp4` is a file every player will lie
1414 /// about -- keeping whatever stem the save dialog last left there.
1415 fn set_format(&mut self, format: Format) {
1416 // The one door both the row and its initial go through, so a format the
1417 // card greys out cannot be picked by keyboard either.
1418 if let (Format::Mp4, Some(why)) = (format, self.session.as_ref().and_then(mp4_refusal)) {
1419 self.notice = Some(format!("NOT MP4 — {why}").into());
1420 return;
1421 }
1422 self.format = format;
1423 self.export_path = retarget(&self.export_path, format);
1424 }
1425
1426 /// The card's Destination row: the desktop's save dialog, on a background
1427 /// thread like the import chooser -- the user may sit in it and the window
1428 /// behind must not freeze. No chooser at all leaves the default path, which
1429 /// is what the refusal says.
1430 fn pick_destination(&mut self, cx: &mut Context<Self>) {
1431 let default = self.export_path.clone();
1432 let picked = cx
1433 .background_executor()
1434 .spawn(async move { pick_save(&default) });
1435 cx.spawn(async move |this, cx| {
1436 let picked = picked.await;
1437 this.update(cx, |this, cx| {
1438 // The dialog outlives the card: an export started meanwhile
1439 // took the old path and its notice must name what it wrote.
1440 if this.export.is_some() {
1441 return;
1442 }
1443 match picked {
1444 // The stem is the user's, the extension is the format's: a
1445 // FLAC named `.mp4` is a file every player lies about.
1446 Ok(Some(path)) => this.export_path = retarget(&path, this.format),
1447 // Cancelled: the default stands, as it did before.
1448 Ok(None) => {}
1449 Err(text) => {
1450 eprintln!("{text}");
1451 this.notice = Some(text.into());
1452 }
1453 }
1454 cx.notify();
1455 })
1456 .ok();
1457 })
1458 .detach();
1459 }
1460
1461 /// Writes the edit list out, at the settings the card was left at. Playback
1462 /// stops first: the exporter opens its own decoder -- and, on the hardware
1463 /// path, an encoder -- so a running player would only compete with it for
1464 /// the GPU. A cancelled export still winding down holds this off for the
1465 /// frame it takes to notice, which is what keeps its `remove_file` off the
1466 /// new output.
1467 fn start_export(&mut self, cx: &mut Context<Self>) {
1468 if self.export.is_some() {
1469 return;
1470 }
1471 let settings = export_settings(self.quality, self.custom_mbps, self.format);
1472 let Some(session) = &mut self.session else {
1473 self.notice = Some("NOTHING TO EXPORT — open a file first".into());
1474 cx.notify();
1475 return;
1476 };
1477 session.pause();
1478 self.export = Some(session.export_to_with(&self.export_path, &settings));
1479 // The card has been answered; the progress line takes the panel from
1480 // here, and it is the running export's escape that matters now.
1481 self.export_open = false;
1482 cx.notify();
1483 }
1484
1485 /// Gives the editor back at once and leaves the worker to stop at its next
1486 /// frame and delete what it has written.
1487 fn cancel_export(&mut self) {
1488 if let Some(export) = &self.export {
1489 export.cancel();
1490 self.cancelling = true;
1491 }
1492 }
1493
1494 /// Takes the export's verdict once it has one. The only place the app
1495 /// touches the handle's completion side.
1496 fn poll_export(&mut self) {
1497 let Some(result) = self.export.as_ref().and_then(ExportHandle::result) else {
1498 return;
1499 };
1500 self.export = None;
1501 // A cancellation is reported as an error, and the one who asked for it
1502 // has had the editor back since the keystroke. Nothing to say.
1503 if std::mem::take(&mut self.cancelling) {
1504 return;
1505 }
1506 let text = match result {
1507 Ok(()) => format!("EXPORT DONE → {}", file_name(&self.export_path)),
1508 Err(e) => format!("EXPORT FAILED: {e}"),
1509 };
1510 eprintln!("{text}");
1511 self.notice = Some(text.into());
1512 }
1513}
1514
1515impl Render for Player {
1516 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1517 // A file that has just been opened sits on its first frame with the
1518 // clock stopped: opening is not playing, whichever way the file
1519 // arrived. The play binding and the transport button start it.
1520 if let Some(session) = &mut self.session {
1521 session.tick();
1522 }
1523 self.pump(window);
1524 self.poll_export();
1525 // Every way a source can arrive -- argv, an import, a project load --
1526 // has been through a repaint by the time its clips are drawn, so this
1527 // is the one place that has to notice a new one.
1528 self.cache_media(cx);
1529 // What the compositor calls this window. Pushed only when it changes:
1530 // it is a protocol round trip and this runs at vsync.
1531 let title = window_title(&self.name);
1532 if title != self.titled {
1533 window.set_window_title(&title);
1534 self.titled = title;
1535 }
1536 // No shadow flag: the clock is the only truth about play state.
1537 let playing = self
1538 .session
1539 .as_ref()
1540 .is_some_and(PlaybackSession::is_playing);
1541 // A paused timeline has nothing to animate; the toggle handlers notify,
1542 // which is what starts the loop again. A paused seek keeps the loop
1543 // running by itself until `pump` has the frame it asked for. An export
1544 // pauses playback and still needs the loop: its progress only reaches
1545 // the screen on a repaint. A notice does not: it waits to be dismissed
1546 // rather than for a clock, so keeping the loop alive for it would spin
1547 // the GPU until someone answered it.
1548 if (playing && !self.done) || self.pending_seek || self.export.is_some() {
1549 window.request_animation_frame();
1550 }
1551
1552 // Read per render, never cached: a delete shortens the timeline and the
1553 // timecode, the ruler and the clamp below all have to follow it.
1554 let duration = self
1555 .session
1556 .as_ref()
1557 .map_or(0., PlaybackSession::timeline_duration);
1558 // The clock keeps running after the last frame (wall time takes over at
1559 // audio EOF) while the picture is frozen, so the timeline the UI shows is
1560 // the clamped one, pinned to the out-point once playback is done.
1561 let position = if self.done {
1562 duration
1563 } else {
1564 self.session
1565 .as_ref()
1566 .map_or(0., PlaybackSession::now)
1567 .clamp(0., duration)
1568 };
1569
1570 div()
1571 .track_focus(&self.focus)
1572 .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| {
1573 // `is_held` filters auto-repeat, which would otherwise toggle
1574 // playback -- or cut the timeline -- many times a second.
1575 if event.is_held {
1576 return;
1577 }
1578 // Any key retires the last message, whatever it was -- and owes
1579 // the repaint itself: a notice no longer keeps the render loop
1580 // alive, and the arms below that do notify are not all of them
1581 // (an unbound key, or the copy chord, changes nothing else).
1582 if this.notice.take().is_some() {
1583 cx.notify();
1584 }
1585 let key = event.keystroke.key.as_str();
1586 // A row is waiting for a stroke, and while it is, that stroke is
1587 // data: it means the binding and nothing else, which is why this
1588 // answers before the export guard and before the keymap is
1589 // consulted at all.
1590 if let Some(action) = this.rebinding {
1591 if key == ESCAPE {
1592 this.rebinding = None;
1593 } else if !is_bare_modifier(key) {
1594 this.capture(action, key, event.keystroke.modifiers.control);
1595 }
1596 cx.notify();
1597 return;
1598 }
1599 // On linux gpui reports the copy chord as key "c" with the
1600 // control modifier set (the control code is mapped back), which
1601 // is why the keymap is keyed on the pair and never on the key
1602 // alone.
1603 let action = this.keymap.lookup(key, event.keystroke.modifiers.control);
1604 // An export is reading the edit list every other action here
1605 // would change, so cancelling is the only one that means
1606 // anything until it is over.
1607 if this.exporting().is_some() {
1608 if cancels_export(key, action) {
1609 this.cancel_export();
1610 }
1611 cx.notify();
1612 return;
1613 }
1614 // The overlay owns the keyboard while it is up: a stroke aimed
1615 // at a row must not also cut the timeline, and the way out of it
1616 // is the same key that gets out of a capture.
1617 if this.keys_open {
1618 if key == ESCAPE {
1619 this.keys_open = false;
1620 cx.notify();
1621 }
1622 return;
1623 }
1624 // The export card owns it the same way, and for the same
1625 // reason. Escape closes it -- nothing has been written yet, so
1626 // there is nothing here to cancel -- and a digit is the custom
1627 // bitrate being typed: the card has no text field (nothing in
1628 // it takes focus, ledger:182) so this listener is its input,
1629 // exactly as it is a waiting row's.
1630 if this.export_open {
1631 if key == ESCAPE {
1632 this.export_open = false;
1633 } else if key == "enter" {
1634 // The card's own button, by keyboard: the one thing in
1635 // it that writes a file must not be pointer-only either.
1636 this.start_export(cx);
1637 } else if let Some(format) = format_key(key) {
1638 // The format rows by their initial, so the card can be
1639 // driven without a mouse -- the same card-local input
1640 // the typed bitrate is, and for the same reason: a
1641 // choice reachable only by pointer is not reachable by
1642 // everyone. Not a keymap binding: it means nothing
1643 // outside this card, exactly like the digits.
1644 this.set_format(format);
1645 } else if let Ok(digit) = key.parse::<u32>() {
1646 this.custom_mbps = push_digit(this.custom_mbps, digit);
1647 this.quality = Quality::Custom;
1648 } else if key == "backspace" {
1649 this.custom_mbps /= 10;
1650 this.quality = Quality::Custom;
1651 }
1652 cx.notify();
1653 return;
1654 }
1655 // And the equalizer card, the same way again. Its own strokes
1656 // are the card's input, exactly as the export card's digits
1657 // are: a band reachable only by dragging is a band a keyboard
1658 // cannot move at all, and every one of them is listed in the
1659 // keys menu (keymap.rs `FIXED`) rather than being a secret.
1660 if this.eq_open.is_some() {
1661 if key == ESCAPE {
1662 // Nothing to undo: every change is already at the clip,
1663 // and undo is undo's own key.
1664 this.eq_open = None;
1665 this.eq_dragging = false;
1666 } else if key == "up" {
1667 this.nudge_band(EQ_STEP, cx);
1668 } else if key == "down" {
1669 this.nudge_band(-EQ_STEP, cx);
1670 } else if key == "r" {
1671 for band in &mut this.eq_params.bands {
1672 band.gain_db = 0.;
1673 }
1674 this.commit_eq(cx);
1675 } else if let Ok(digit) = key.parse::<usize>() {
1676 // 1-based, as the rows are numbered on screen; a digit
1677 // past the last band picks nothing rather than panics.
1678 if let Some(band) = digit.checked_sub(1)
1679 && band < this.eq_params.bands.len()
1680 {
1681 this.eq_band = band;
1682 }
1683 }
1684 cx.notify();
1685 return;
1686 }
1687 // The colour card owns the keyboard the same way the export
1688 // card does, and its keys mean nothing outside it: the arrows
1689 // pick a slider and move it, and `r` takes the grade off. Not
1690 // keymap bindings for exactly that reason -- see `FIXED`, where
1691 // the keys menu still lists them.
1692 if this.color_open.is_some() {
1693 match color_key(key) {
1694 Some(ColorKey::Close) => this.color_open = None,
1695 Some(ColorKey::Band(step)) => {
1696 this.color_band = (this.color_band + step) % COLOR_BANDS.len();
1697 }
1698 Some(ColorKey::Nudge(steps)) => this.nudge_color(steps, cx),
1699 Some(ColorKey::Reset) => {
1700 this.set_color(ColorParams::default(), cx);
1701 }
1702 None => {}
1703 }
1704 cx.notify();
1705 return;
1706 }
1707 // A clip menu names an index, and every edit below moves
1708 // indices -- so a stroke closes it before it acts. Escape means
1709 // that and nothing else, which is the `esc` the keys menu
1710 // already lists (keymap.rs `FIXED`).
1711 if this.context_menu.take().is_some() {
1712 cx.notify();
1713 if key == ESCAPE {
1714 return;
1715 }
1716 }
1717 if let Some(action) = action {
1718 this.act(action, cx);
1719 }
1720 }))
1721 // The whole window is the drop target: gpui turns an external file
1722 // drop into an `ExternalPaths` drag (window.rs:3626) delivered as a
1723 // mouse-up to every hovered hitbox, and the root's is the only one
1724 // that covers the picture as well as the panel.
1725 .on_drop(cx.listener(|this, paths: &gpui::ExternalPaths, _, cx| {
1726 // The overlay owns the pointer as well as the keyboard, and a
1727 // drop is a click the scrim cannot swallow: gpui delivers it to
1728 // the root's hitbox, which is under the scrim but is not a
1729 // sibling it can stop. The export card is over the timeline for
1730 // the same reason: importing under it would change the very
1731 // edit list the card is about to write out.
1732 if this.modal() {
1733 return;
1734 }
1735 for path in paths.paths() {
1736 // A project replaces the timeline, media is appended to it.
1737 if is_project(path) {
1738 this.load_project(path, cx);
1739 } else {
1740 this.import(path, cx);
1741 }
1742 }
1743 }))
1744 // Scrubbing is tracked on the root because the pointer leaves the
1745 // 6 px ruler on the first drag and its own listeners then stop
1746 // firing; the root's hitbox is the whole window.
1747 .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _, cx| {
1748 // A band's bar is 6 px tall and the pointer leaves it at once,
1749 // so the equalizer drag is tracked here for the ruler's reason.
1750 if this.eq_dragging {
1751 if event.pressed_button == Some(MouseButton::Left) {
1752 this.drag_band(event.position.x, cx);
1753 } else {
1754 // Released outside the window: the up below never came,
1755 // so this is where the gesture ends -- and it still owes
1756 // the one write the whole drag is worth.
1757 this.eq_dragging = false;
1758 this.commit_eq(cx);
1759 }
1760 return;
1761 }
1762 if !this.scrubbing {
1763 return;
1764 }
1765 if event.pressed_button == Some(MouseButton::Left) {
1766 this.scrub_to(event.position.x, false, cx);
1767 } else {
1768 // A release outside the window never reaches the handler
1769 // below, so the first button-up move is when we learn the
1770 // drag is over. Without this the next hover would scrub.
1771 this.scrubbing = false;
1772 }
1773 }))
1774 .on_mouse_up(
1775 MouseButton::Left,
1776 cx.listener(|this, event: &MouseUpEvent, _, cx| {
1777 if std::mem::take(&mut this.eq_dragging) {
1778 // The release lands exactly, then the gesture is written
1779 // once -- the append-only table's whole reason.
1780 this.drag_band(event.position.x, cx);
1781 this.commit_eq(cx);
1782 return;
1783 }
1784 if std::mem::take(&mut this.scrubbing) {
1785 this.scrub_to(event.position.x, true, cx);
1786 }
1787 }),
1788 )
1789 .size_full()
1790 .flex()
1791 .flex_col()
1792 .bg(rgb(LETTERBOX))
1793 .text_color(rgb(INK))
1794 .text_size(px(13.))
1795 .child(
1796 div()
1797 .flex_none()
1798 .h(px(HEADER_H))
1799 .flex()
1800 .items_center()
1801 .px(px(12.))
1802 .bg(rgb(CHROME))
1803 .child(self.name.clone()),
1804 )
1805 // The library beside the picture rather than under it: a media pool
1806 // is a column in every editor that has one, and the timeline below
1807 // already owns the full width. `library_w` is what keeps the
1808 // picture the majority of the row at every window size.
1809 .child(
1810 div()
1811 .flex_1()
1812 .min_h(px(0.))
1813 .flex()
1814 .child(self.library(library_w(f32::from(window.viewport_size().width)), cx))
1815 .child(
1816 div()
1817 .flex_1()
1818 .min_w(px(0.))
1819 .overflow_hidden()
1820 .flex()
1821 .justify_center()
1822 .items_center()
1823 .children(
1824 self.image
1825 .clone()
1826 .map(|i| {
1827 img(i)
1828 .size_full()
1829 .object_fit(gpui::ObjectFit::Contain)
1830 .into_any_element()
1831 })
1832 // With no file open the letterbox is the
1833 // whole window, and a black rectangle says
1834 // only that something is broken -- so it
1835 // says what it wants instead. The window is
1836 // already the drop target.
1837 .or_else(|| {
1838 self.session
1839 .is_none()
1840 .then(|| empty_hint().into_any_element())
1841 }),
1842 ),
1843 ),
1844 )
1845 // Above the panel and only when there is one to show, so it costs
1846 // the picture nothing the rest of the time.
1847 .children(self.notice_bar(cx))
1848 .child(self.panel(position, duration, playing, cx))
1849 // Over the panel it was opened on, and under the cards: it is only
1850 // ever up while neither of them is (`modal`).
1851 .children(self.context_card(window.viewport_size(), cx))
1852 // Last, so they are over everything -- they take no room in the
1853 // column, and only one of the two is ever up.
1854 .children(self.keys_overlay(cx))
1855 .children(self.export_card(cx))
1856 .children(self.eq_card(cx))
1857 .children(self.color_card(cx))
1858 }
1859}
1860
1861impl Player {
1862 /// The media library: a row per source the timeline knows, in the order
1863 /// they arrived, each wearing the tint its clips wear in the lanes -- the
1864 /// swatch *is* what says which boxes down there came from this file. A
1865 /// click picks a row, the button under the list drops that source in at the
1866 /// playhead, and a row dragged onto either lane does the same thing through
1867 /// the same call.
1868 ///
1869 /// Import lives here, because this is the list it adds to. Plain divs like
1870 /// the rest of this window: nothing in it takes focus, so the root keeps
1871 /// the keyboard and the play key still works after a row is clicked
1872 /// (ledger:182).
1873 fn library(&self, width: f32, cx: &mut Context<Self>) -> impl IntoElement {
1874 let exporting = self.exporting().is_some();
1875 let sources = self
1876 .session
1877 .as_ref()
1878 .map_or(&[][..], PlaybackSession::sources);
1879 // Every source matches the first in size and rate or it was refused at
1880 // the door (the import policy, ledger:436), so the session's own meta
1881 // describes every row and nothing has to be probed to say so.
1882 let meta = self.session.as_ref().map(PlaybackSession::meta);
1883 let clips: Vec<Clip> = self
1884 .session
1885 .as_ref()
1886 .map_or_else(Vec::new, |session| lane_clips(session).copied().collect());
1887 let rows: Vec<_> = library_rows(sources, &self.streams, self.timeline_audio(), |path| {
1888 source_frames(clips.iter(), sources, path)
1889 })
1890 .into_iter()
1891 .enumerate()
1892 .map(|(i, row)| {
1893 let picked = self
1894 .selected_asset
1895 .as_ref()
1896 .is_some_and(|p| *p == (row.path.clone(), row.stream));
1897 let name: SharedString = row.name.clone().into();
1898 let tip: SharedString = match (&row.unusable, meta) {
1899 // A greyed row says why in full, where its length would be:
1900 // the list is the one place the file's own tracks are named.
1901 (Some(why), _) => format!("{} — {why}", row.path.display()),
1902 // A file with no picture has no size and no frame rate to
1903 // report, and only one lane it can go on: saying so is the
1904 // difference between a hint and a lie.
1905 (None, _) if engine::is_audio(&row.path) => format!(
1906 "{} — audio only · drag onto the audio lane, or Add at playhead",
1907 row.path.display()
1908 ),
1909 (None, Some(meta)) => format!(
1910 "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead",
1911 row.path.display(),
1912 meta.width,
1913 meta.height,
1914 meta.frame_rate
1915 ),
1916 (None, None) => row.path.display().to_string(),
1917 }
1918 .into();
1919 let ghost = name.clone();
1920 // What the second line says: the stream, then either its length or
1921 // the reason it cannot be used.
1922 let under = match &row.unusable {
1923 Some(why) => join_detail(&row.detail, why),
1924 None => join_detail(
1925 &row.detail,
1926 &timecode(f64::from(row.frames) / self.fps, self.fps),
1927 ),
1928 };
1929 let usable = row.unusable.is_none();
1930 let (path, stream) = (row.path.clone(), row.stream);
1931 let dragged = (path.clone(), stream);
1932 div()
1933 .id(("asset", i))
1934 .flex_none()
1935 .h(px(ROW_H))
1936 .flex()
1937 .items_center()
1938 .gap(px(6.))
1939 .pr(px(6.))
1940 .rounded(px(3.))
1941 // A row that cannot be placed takes no click and no drag, and
1942 // reads as unavailable rather than merely unlucky.
1943 .when(!usable, |d| d.text_color(rgb(INK_DIM)).opacity(0.55))
1944 .when(usable, |d| {
1945 d.cursor_pointer()
1946 .hover(|s| s.bg(rgb(HOVER)))
1947 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
1948 this.selected_asset = Some((path.clone(), stream));
1949 cx.notify();
1950 }))
1951 // The drag carries the row's file and stream and the
1952 // row's name: one for the drop to insert, one for the
1953 // pointer to carry, so what is being dragged is legible
1954 // on the way down.
1955 .on_drag(AssetDrag(dragged.0, dragged.1), move |_, _, _, cx| {
1956 cx.new(|_| Tip(ghost.clone()))
1957 })
1958 })
1959 .when(picked, |d| d.bg(rgb(SELECTED)).border_1())
1960 .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())
1961 // Full height and hard against the edge: the tint reads as
1962 // the lane's colour continuing into the list, not as a chip
1963 // that happens to be near it.
1964 .child(
1965 div()
1966 .flex_none()
1967 .w(px(SWATCH_W))
1968 .h_full()
1969 .rounded(px(2.))
1970 .bg(rgb(source_tint(row.tint))),
1971 )
1972 .child(
1973 div()
1974 .flex_1()
1975 .min_w(px(0.))
1976 .flex()
1977 .flex_col()
1978 // Two lines rather than two columns: at the width
1979 // this panel yields to, a name and a timecode side
1980 // by side leave room for neither.
1981 .child(div().truncate().text_size(px(11.)).child(name))
1982 .child(
1983 div()
1984 .truncate()
1985 .text_size(px(10.))
1986 .text_color(rgb(INK_DIM))
1987 .child(under),
1988 ),
1989 )
1990 })
1991 .collect();
1992 div()
1993 .flex_none()
1994 .w(px(width))
1995 .h_full()
1996 .flex()
1997 .flex_col()
1998 .gap(px(6.))
1999 .p(px(8.))
2000 .bg(rgb(CHROME))
2001 .child(
2002 div()
2003 .flex_none()
2004 .flex()
2005 .items_center()
2006 .gap(px(6.))
2007 .child(
2008 div()
2009 .flex_1()
2010 .min_w(px(0.))
2011 .truncate()
2012 .text_size(px(11.))
2013 .text_color(rgb(INK_DIM))
2014 .child("Media"),
2015 )
2016 .child(control(
2017 "import",
2018 None,
2019 "Import",
2020 "opens a file chooser — or drop a file on the window".to_string(),
2021 !exporting,
2022 cx.listener(|this, _: &ClickEvent, _, cx| this.pick_and_import(cx)),
2023 )),
2024 )
2025 .child(
2026 div()
2027 .id("library-rows")
2028 .flex_1()
2029 .min_h(px(0.))
2030 .flex()
2031 .flex_col()
2032 .gap(px(2.))
2033 .overflow_y_scroll()
2034 // Never a blank column: with nothing imported the list is
2035 // where the way in is said.
2036 .when(rows.is_empty(), |d| {
2037 d.child(
2038 div()
2039 .text_size(px(11.))
2040 .text_color(rgb(INK_DIM))
2041 .child("No media yet — Import, or drop a file on the window"),
2042 )
2043 })
2044 .children(rows),
2045 )
2046 .child(control(
2047 "add-asset",
2048 None,
2049 "Add at playhead",
2050 match self.selected_asset {
2051 Some(_) => "inserts the picked file at the playhead".to_string(),
2052 None => "click a file above first — or drag one onto a lane".to_string(),
2053 },
2054 can_add(
2055 self.selected_asset.as_ref(),
2056 self.session.is_some(),
2057 exporting,
2058 ),
2059 cx.listener(|this, _: &ClickEvent, _, cx| {
2060 if let Some((path, stream)) = this.selected_asset.clone() {
2061 // No lane: the button means "wherever this belongs",
2062 // which for a file with no picture is the audio lane.
2063 this.insert_source(&path, stream, None, cx);
2064 }
2065 }),
2066 ))
2067 }
2068
2069 /// Transport, edit and file buttons, timecode, playhead, clips lane.
2070 fn panel(
2071 &self,
2072 position: f64,
2073 duration: f64,
2074 playing: bool,
2075 cx: &mut Context<Self>,
2076 ) -> impl IntoElement {
2077 let filled = if duration > 0. {
2078 (position / duration) as f32
2079 } else {
2080 0.
2081 };
2082 // An export owns the hint slot and the ruler while it runs: the
2083 // percentage and the accent bar are the same number, so the playhead
2084 // fill doubles as the progress bar for free.
2085 let exporting = self.exporting().is_some();
2086 // Everything but Import and Keys needs a timeline to act on: with none
2087 // open they are dimmed rather than silently doing nothing.
2088 let live = self.session.is_some() && !exporting;
2089 let key = |action| self.keymap.display(action);
2090 // The lanes the project has, or the pair a fresh one starts with so the
2091 // panel reads the same before a file is open as after.
2092 let lanes = self
2093 .session
2094 .as_ref()
2095 .map_or_else(|| vec![Lane::V1, Lane::A1], PlaybackSession::lanes);
2096 // A loop rather than a `map`: each row takes `cx` in turn, where a
2097 // closure would hold it for as long as the iterator lives.
2098 let mut rows = Vec::new();
2099 for &lane in &lanes {
2100 rows.push(self.lane_row(lane, duration, filled, cx));
2101 }
2102 let (hint, filled) = if let Some(export) = self.exporting() {
2103 let progress = export.progress();
2104 (
2105 format!(
2106 "EXPORTING {}% — {} cancels",
2107 (progress * 100.) as u32,
2108 key(ActionId::CancelExport)
2109 ),
2110 progress,
2111 )
2112 } else {
2113 // The strokes no button carries; the rest ride on the buttons'
2114 // tooltips. Keys first: at a 640 px window the tail is what a
2115 // truncation eats, and the two hints at the end are also on the
2116 // ruler's and Import's tooltips.
2117 (
2118 format!(
2119 "{} copy · {} paste · {} undo · click the bar to seek · drop a file to import",
2120 key(ActionId::Copy),
2121 key(ActionId::Paste),
2122 key(ActionId::Undo)
2123 ),
2124 filled,
2125 )
2126 };
2127 div()
2128 .flex_none()
2129 .h(px(panel_h(lanes.len())))
2130 .flex()
2131 .flex_col()
2132 .gap(px(8.))
2133 .px(px(12.))
2134 .py(px(8.))
2135 .bg(rgb(CHROME))
2136 // Transport | edit | file: three groups, so the eye can skip two of
2137 // them. Every button says what it does; the tooltip adds its key.
2138 .child(
2139 div()
2140 .flex_none()
2141 .flex()
2142 .items_center()
2143 .gap(px(8.))
2144 .child(control(
2145 "transport",
2146 Some(transport_glyph(playing).into_any_element()),
2147 if playing { "Pause" } else { "Play" },
2148 key(ActionId::Play),
2149 live,
2150 cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_or_restart(cx)),
2151 ))
2152 .child(separator())
2153 .child(control(
2154 "cut",
2155 Some(cut_glyph().into_any_element()),
2156 "Cut",
2157 format!(
2158 "{} — splits the clip under the playhead",
2159 key(ActionId::Cut)
2160 ),
2161 live,
2162 cx.listener(|this, _: &ClickEvent, _, cx| this.cut(cx)),
2163 ))
2164 .child(control(
2165 "delete",
2166 Some(delete_glyph().into_any_element()),
2167 "Delete",
2168 if self.selected.is_some() {
2169 key(ActionId::Delete)
2170 } else {
2171 format!("{} — click a clip below first", key(ActionId::Delete))
2172 },
2173 live && self.selected.is_some(),
2174 cx.listener(|this, _: &ClickEvent, _, cx| this.delete_selected(cx)),
2175 ))
2176 // With the edit group, beside the buttons that change the
2177 // edit list: a track is a row of it, and adding one is an
2178 // undoable edit like the rest. Two buttons rather than one
2179 // with a choice, because the choice is the whole action.
2180 .child(control(
2181 "add-video-lane",
2182 None,
2183 "+ V",
2184 format!(
2185 "{} — adds a video track under the ones there",
2186 key(ActionId::AddVideoLane)
2187 ),
2188 live,
2189 cx.listener(|this, _: &ClickEvent, _, cx| {
2190 this.add_lane(LaneKind::Video, cx)
2191 }),
2192 ))
2193 .child(control(
2194 "add-audio-lane",
2195 None,
2196 "+ A",
2197 format!(
2198 "{} — adds an audio track under the ones there",
2199 key(ActionId::AddAudioLane)
2200 ),
2201 live,
2202 cx.listener(|this, _: &ClickEvent, _, cx| {
2203 this.add_lane(LaneKind::Audio, cx)
2204 }),
2205 ))
2206 // With the transport, not the edit group: it changes what
2207 // the file sounds like, never what it is. Reads as its own
2208 // state, so muted is legible without a tooltip.
2209 .child(control(
2210 "volume",
2211 None,
2212 self.volume.label(),
2213 format!(
2214 "{} mutes · {} louder · {} quieter",
2215 key(ActionId::ToggleMute),
2216 key(ActionId::VolumeUp),
2217 key(ActionId::VolumeDown)
2218 ),
2219 live,
2220 cx.listener(|this, _: &ClickEvent, _, cx| {
2221 this.set_volume(|volume| volume.muted = !volume.muted, cx)
2222 }),
2223 ))
2224 .child(separator())
2225 // Import is not here: it belongs to the media list it adds
2226 // to, and two doors into one action is a question about
2227 // which one is the real one.
2228 .child(control(
2229 "export",
2230 None,
2231 "Export",
2232 format!(
2233 "{} — quality and destination, then writes the timeline out",
2234 key(ActionId::Export)
2235 ),
2236 live && self.export.is_none(),
2237 cx.listener(|this, _: &ClickEvent, _, cx| this.open_export(cx)),
2238 ))
2239 .child(control(
2240 "save",
2241 None,
2242 "Save",
2243 format!("{} — writes the project file", key(ActionId::Save)),
2244 live,
2245 cx.listener(|this, _: &ClickEvent, _, cx| this.save_project(cx)),
2246 ))
2247 // No shortcut of its own -- and closed while an export runs,
2248 // which is what keeps a waiting row from swallowing the
2249 // escape the progress line promises cancels the export.
2250 .child(control(
2251 "keys",
2252 None,
2253 "Keys",
2254 "show and change the keybindings".to_string(),
2255 !exporting,
2256 cx.listener(|this, _: &ClickEvent, _, cx| {
2257 this.keys_open = !this.keys_open;
2258 this.rebinding = None;
2259 // One card at a time, both ways round.
2260 this.export_open = false;
2261 cx.notify();
2262 }),
2263 )),
2264 )
2265 .child(
2266 div()
2267 .flex_none()
2268 .flex()
2269 .items_center()
2270 .gap(px(12.))
2271 // Fixed width and one line: changing digits must not push
2272 // the row around, nor wrap and change its height.
2273 .child(div().flex_none().w(px(TIME_W)).truncate().child(format!(
2274 "{} / {}",
2275 timecode(position, self.fps),
2276 timecode(duration, self.fps)
2277 )))
2278 .child(
2279 div()
2280 .flex_1()
2281 .min_w(px(0.))
2282 .truncate()
2283 .text_size(px(11.))
2284 .text_color(rgb(INK_DIM))
2285 .child(hint),
2286 ),
2287 )
2288 // Press to seek, drag to scrub: the move and release halves live on
2289 // the root, since the pointer leaves the bar immediately. The bar
2290 // stays 6 px to look at; the strip that takes the click is 24, so
2291 // it can be hit without aiming (WCAG 2.5.8).
2292 .child(
2293 div()
2294 .flex_none()
2295 .flex()
2296 .gap(px(HEADER_GAP))
2297 // The lanes' header column, empty here: the ruler's own bar
2298 // has to start where their beds start, or the playhead
2299 // would point at a different moment in each row.
2300 .child(div().flex_none().w(px(HEADER_W)))
2301 .child(
2302 div()
2303 .id("ruler")
2304 .flex_1()
2305 .min_w(px(0.))
2306 .h(px(RULER_HIT_H))
2307 .flex()
2308 .flex_col()
2309 .justify_center()
2310 .rounded(px(3.))
2311 .cursor_pointer()
2312 .hover(|s| s.bg(rgb(HOVER_DIM)))
2313 // The strip carries no text, so the tooltip is the only
2314 // place it can say what it is.
2315 .tooltip(|_, cx| cx.new(|_| Tip("Seek — click or drag".into())).into())
2316 .on_mouse_down(
2317 MouseButton::Left,
2318 cx.listener(|this, event: &MouseDownEvent, _, cx| {
2319 this.scrubbing = true;
2320 this.scrub_to(event.position.x, true, cx);
2321 }),
2322 )
2323 .child(
2324 div()
2325 .w_full()
2326 .h(px(6.))
2327 .rounded(px(3.))
2328 .bg(rgb(SURFACE))
2329 .child(bounds_probe(self.ruler.clone()))
2330 .child(
2331 div()
2332 .h_full()
2333 .w(relative(filled))
2334 .rounded(px(3.))
2335 .bg(rgb(ACCENT)),
2336 ),
2337 ),
2338 ),
2339 )
2340 // Every lane the project has, in its own order -- and its own
2341 // column, so a project with more lanes than the panel is tall
2342 // scrolls its tracks instead of pushing the picture off the window.
2343 // The gap is the panel's own, so two lanes lay out exactly as they
2344 // did when they were two children of it.
2345 .child(
2346 div()
2347 .id("lanes")
2348 .flex_none()
2349 .flex()
2350 .flex_col()
2351 .gap(px(8.))
2352 .max_h(px(lanes_h(LANES_MAX)))
2353 .overflow_y_scroll()
2354 .children(rows),
2355 )
2356 }
2357
2358 /// A notice holds its own bar, full width, until it is answered: any key
2359 /// retires it (the key handler) and so does a click on it. Its own surface
2360 /// because the message is the point -- a failure cut to the timecode's slot
2361 /// is a failure nobody read.
2362 fn notice_bar(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2363 let notice = self.notice.clone()?;
2364 Some(
2365 div()
2366 .id("notice")
2367 .flex_none()
2368 .flex()
2369 .items_start()
2370 .gap(px(12.))
2371 .px(px(12.))
2372 .py(px(6.))
2373 .bg(rgb(SURFACE))
2374 .cursor_pointer()
2375 .hover(|s| s.bg(rgb(HOVER)))
2376 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
2377 this.notice = None;
2378 cx.notify();
2379 }))
2380 .child(div().flex_1().min_w(px(0.)).child(notice))
2381 .child(
2382 div()
2383 .flex_none()
2384 .text_size(px(11.))
2385 .text_color(rgb(INK_DIM))
2386 .child("click or press any key to dismiss"),
2387 ),
2388 )
2389 }
2390
2391 /// Every binding, and the way to change one: a row per entry, click it and
2392 /// the next stroke becomes its chord. Over the whole window, because while
2393 /// it is up nothing under it may answer -- the scrim stops the clicks
2394 /// (gpui dispatches mouse listeners topmost-first, window.rs:3705) and the
2395 /// key handler's own branch stops the strokes.
2396 ///
2397 /// Plain divs, like every control here: nothing in it takes focus, so the
2398 /// root is still the one reading the keyboard -- which is exactly what a
2399 /// waiting row depends on.
2400 fn keys_overlay(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2401 if !self.keys_open {
2402 return None;
2403 }
2404 // The way out, spelled the way the rows spell a chord.
2405 let out = keymap::Chord {
2406 key: ESCAPE.to_string(),
2407 ctrl: false,
2408 }
2409 .pretty();
2410 // Every stroke that works, under its heading, and both halves of the
2411 // list come from the registry: one row per action -- an action with two
2412 // strokes reads as one line ("x or delete") and a rebind replaces that
2413 // whole set -- then the strokes the modal cards answer to, which are
2414 // shown but not offered, because nothing may unbind the way out.
2415 let mut rows: Vec<AnyElement> = Vec::new();
2416 for category in keymap::Category::ALL {
2417 let actions = ActionId::ALL
2418 .into_iter()
2419 .enumerate()
2420 .filter(|(_, a)| a.category() == category);
2421 let fixed = keymap::FIXED.iter().filter(|f| f.category == category);
2422 let mut headed = false;
2423 let mut head = |rows: &mut Vec<AnyElement>| {
2424 if !std::mem::replace(&mut headed, true) {
2425 rows.push(
2426 div()
2427 .flex_none()
2428 .px(px(6.))
2429 .pt(px(4.))
2430 .text_size(px(11.))
2431 .text_color(rgb(INK_DIM))
2432 .child(category.label())
2433 .into_any_element(),
2434 );
2435 }
2436 };
2437 for (i, action) in actions {
2438 head(&mut rows);
2439 let capturing = self.rebinding == Some(action);
2440 let out = out.clone();
2441 rows.push(
2442 div()
2443 .id(("bind", i))
2444 .flex()
2445 // The floor, not the height: a row that needed two lines
2446 // would otherwise paint over the one under it.
2447 .min_h(px(KEYS_ROW_H))
2448 .items_center()
2449 .justify_between()
2450 .gap(px(12.))
2451 .px(px(6.))
2452 .rounded(px(3.))
2453 .cursor_pointer()
2454 .hover(|s| s.bg(rgb(HOVER)))
2455 .when(capturing, |d| d.bg(rgb(SELECTED)))
2456 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
2457 this.rebinding = Some(action);
2458 cx.notify();
2459 }))
2460 .child(action.label())
2461 .child(if capturing {
2462 div()
2463 .text_color(rgb(INK_DIM))
2464 .child(format!("press a key — {out} cancels"))
2465 } else {
2466 div().child(self.keymap.display(action))
2467 })
2468 .into_any_element(),
2469 );
2470 }
2471 for f in fixed {
2472 head(&mut rows);
2473 rows.push(
2474 div()
2475 .flex()
2476 .min_h(px(KEYS_ROW_H))
2477 .items_center()
2478 .justify_between()
2479 .gap(px(12.))
2480 .px(px(6.))
2481 .child(f.label)
2482 // Dim, and no hover: this one is not a row you can click.
2483 .child(div().text_color(rgb(INK_DIM)).child(f.chord))
2484 .into_any_element(),
2485 );
2486 }
2487 }
2488 Some(
2489 div()
2490 .absolute()
2491 .inset_0()
2492 .flex()
2493 .justify_center()
2494 .items_center()
2495 // The picture behind is out of reach, and looks it. The press is
2496 // swallowed here so a button under the scrim cannot take it.
2497 .bg(rgba(0x101010cc))
2498 .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| {
2499 cx.stop_propagation()
2500 })
2501 .child(
2502 div()
2503 .w(px(KEYS_W))
2504 .flex()
2505 .flex_col()
2506 .gap(px(2.))
2507 .p(px(12.))
2508 .rounded(px(6.))
2509 .bg(rgb(SURFACE))
2510 // Title and instruction are two children, never one
2511 // wrapping line: a fixed-height slot whose text wrapped
2512 // painted its second line over the first row.
2513 .child(div().flex_none().px(px(6.)).child("Keybindings"))
2514 // One status line, under the title where the eye starts.
2515 // A refusal takes it over -- it is the more urgent of the
2516 // two, and the notice bar it would otherwise appear in is
2517 // under the scrim.
2518 //
2519 // The row list below is capped and scrolls, so neither a
2520 // wrapped refusal here nor another action added to `ALL`
2521 // can push the card past a 360 px window any more.
2522 .child(
2523 div()
2524 .flex_none()
2525 .px(px(6.))
2526 .text_size(px(11.))
2527 .text_color(rgb(INK_DIM))
2528 .child(
2529 self.notice
2530 .clone()
2531 .unwrap_or_else(|| "click a row, then press a key".into()),
2532 ),
2533 )
2534 // Capped and scrolling rather than as tall as the action
2535 // list happens to be: the list grows with the editor,
2536 // the smallest window does not.
2537 .child(
2538 div()
2539 .id("keys-rows")
2540 .flex()
2541 .flex_col()
2542 .gap(px(2.))
2543 .max_h(px(KEYS_ROWS_H))
2544 .overflow_y_scroll()
2545 .children(rows),
2546 ),
2547 ),
2548 )
2549 }
2550
2551 /// What an export is going to be, before there is one: the destination, the
2552 /// quality rows, and the two things that are not a choice at all. The same
2553 /// scrim, width and row shape as the keybindings overlay -- two cards of
2554 /// different builds over one window read as two different programs -- and
2555 /// the same plain divs, so the root keeps the keyboard and a typed digit
2556 /// reaches the custom row.
2557 fn export_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2558 if !self.export_open {
2559 return None;
2560 }
2561 let row = |id: (&'static str, usize)| {
2562 div()
2563 .id(id)
2564 .flex()
2565 // The floor, not the height: the destination's path wraps on a
2566 // long name and must not paint over the row under it.
2567 .min_h(px(KEYS_ROW_H))
2568 .items_center()
2569 .justify_between()
2570 .gap(px(12.))
2571 .px(px(6.))
2572 .rounded(px(3.))
2573 };
2574 // A row that cannot be picked is dimmed and takes no click, exactly as
2575 // an inapplicable item in the clip menu is: it still says its piece.
2576 let live = |d: Stateful<Div>, enabled: bool| {
2577 d.when(!enabled, |d| d.opacity(0.4).cursor_not_allowed())
2578 .when(enabled, |d| d.cursor_pointer().hover(|s| s.bg(rgb(HOVER))))
2579 };
2580 // The formats first: the quality rows below are *video* bitrate, so
2581 // which file is being written decides whether they mean anything.
2582 // An mp4 this timeline cannot be written as reads exactly like the
2583 // formats there is no encoder for: dimmed, unclickable, and carrying its
2584 // own reason instead of the detail line.
2585 let refused = self.session.as_ref().and_then(mp4_refusal);
2586 let formats: Vec<_> = FORMATS
2587 .into_iter()
2588 .enumerate()
2589 .map(|(i, (format, label, detail))| {
2590 let blocked = format == Some(Format::Mp4) && refused.is_some();
2591 let detail: SharedString = match &refused {
2592 Some(why) if blocked => why.clone().into(),
2593 _ => detail.into(),
2594 };
2595 let picked = format == Some(self.format) && !blocked;
2596 let format = format.filter(|_| !blocked);
2597 live(row(("format", i)), format.is_some())
2598 .when(picked, |d| d.bg(rgb(SELECTED)))
2599 .when_some(format, |d, format| {
2600 d.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
2601 this.set_format(format);
2602 cx.notify();
2603 }))
2604 })
2605 .child(label)
2606 .child(
2607 div()
2608 .text_size(px(11.))
2609 .text_color(rgb(INK_DIM))
2610 .child(detail),
2611 )
2612 })
2613 .collect();
2614 let video = self.format.has_video();
2615 let rows: Vec<_> = Quality::ALL
2616 .into_iter()
2617 .enumerate()
2618 .map(|(i, quality)| {
2619 live(row(("quality", i)), video)
2620 .when(video && self.quality == quality, |d| d.bg(rgb(SELECTED)))
2621 .when(video, |d| {
2622 d.on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
2623 this.quality = quality;
2624 cx.notify();
2625 }))
2626 })
2627 .child(quality.label())
2628 .child(
2629 div()
2630 .text_size(px(11.))
2631 .text_color(rgb(INK_DIM))
2632 .child(quality.detail(self.custom_mbps)),
2633 )
2634 })
2635 .collect();
2636 Some(
2637 div()
2638 .absolute()
2639 .inset_0()
2640 .flex()
2641 .justify_center()
2642 .items_center()
2643 .bg(rgba(0x101010cc))
2644 .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| {
2645 cx.stop_propagation()
2646 })
2647 .child(
2648 div()
2649 .w(px(KEYS_W))
2650 .flex()
2651 .flex_col()
2652 .gap(px(2.))
2653 .p(px(12.))
2654 .rounded(px(6.))
2655 .bg(rgb(SURFACE))
2656 .child(div().flex_none().px(px(6.)).child("Export"))
2657 // The status line, where a refusal from the save dialog
2658 // lands: the notice bar it would otherwise take is under
2659 // the scrim.
2660 .child(
2661 div()
2662 .flex_none()
2663 .px(px(6.))
2664 .text_size(px(11.))
2665 .text_color(rgb(INK_DIM))
2666 .child(self.notice.clone().unwrap_or_else(|| {
2667 "pick a format (m/w/f), then Export — esc closes".into()
2668 })),
2669 )
2670 // Capped and scrolling like the keybindings list: the
2671 // destination, six formats and five qualities are more
2672 // rows than a 360 px window has room for, and it is the
2673 // list that scrolls, never the card that grows.
2674 .child(
2675 div()
2676 .id("export-rows")
2677 .flex()
2678 .flex_col()
2679 .gap(px(2.))
2680 .max_h(px(EXPORT_ROWS_H))
2681 .overflow_y_scroll()
2682 .child(
2683 live(row(("destination", 0)), true)
2684 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
2685 this.pick_destination(cx)
2686 }))
2687 .child("Destination")
2688 .child(
2689 div()
2690 .text_size(px(11.))
2691 .text_color(rgb(INK_DIM))
2692 .child(file_name(&self.export_path)),
2693 ),
2694 )
2695 .children(formats)
2696 .children(rows),
2697 )
2698 // What the picked row really writes. `moov` last is the
2699 // muxer's own shape -- an mp4 is playable only once it
2700 // is finished. The project's resolution is on the same
2701 // line because it *is* what the file comes out at,
2702 // whatever size the media on the timeline are: this is
2703 // the one place the number is shown, and ctrl+r is what
2704 // changes it.
2705 .child(
2706 div()
2707 .flex_none()
2708 .px(px(6.))
2709 .text_size(px(11.))
2710 .text_color(rgb(INK_DIM))
2711 .child(export_line(self.format, self.session.as_ref())),
2712 )
2713 .child(
2714 div()
2715 .id("export-confirm")
2716 .mt(px(4.))
2717 .flex()
2718 .h(px(CONTROL_H))
2719 .items_center()
2720 .justify_center()
2721 .rounded(px(3.))
2722 .bg(rgb(SELECTED))
2723 .cursor_pointer()
2724 .hover(|s| s.bg(rgb(HOVER)))
2725 .on_click(
2726 cx.listener(|this, _: &ClickEvent, _, cx| {
2727 this.start_export(cx)
2728 }),
2729 )
2730 .child("Export"),
2731 ),
2732 ),
2733 )
2734 }
2735
2736 /// The equalizer of one audio clip: a row per band, each a bar that reads
2737 /// flat in the middle and is dragged either way, and a row that flattens
2738 /// them all. The same scrim, width and rows as the other two cards, and the
2739 /// same plain divs -- nothing here takes focus, so the root keeps the
2740 /// keyboard and the card's own strokes (`1`–`5`, up, down, `r`) reach it.
2741 ///
2742 /// Every change is written at the clip as it is made
2743 /// ([`Player::commit_eq`]), so what the card shows is always what is
2744 /// playing: there is no OK button to forget, and closing it changes
2745 /// nothing. What takes a curve back off is undo, like every other edit.
2746 fn eq_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2747 let (lane, idx) = self.eq_open?;
2748 let rows: Vec<_> = self
2749 .eq_params
2750 .bands
2751 .iter()
2752 .enumerate()
2753 .map(|(i, band)| {
2754 let (left, width) = eq_fill(band.gain_db);
2755 div()
2756 .id(("eq-band", i))
2757 .flex()
2758 .min_h(px(KEYS_ROW_H))
2759 .items_center()
2760 .gap(px(12.))
2761 .px(px(6.))
2762 .rounded(px(3.))
2763 .cursor_pointer()
2764 .when(i == self.eq_band, |d| d.bg(rgb(SELECTED)))
2765 .hover(|s| s.bg(rgb(HOVER)))
2766 // The press picks the band *and* is already the first
2767 // sample of the drag, so a plain click sets a value.
2768 .on_mouse_down(
2769 MouseButton::Left,
2770 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
2771 this.eq_band = i;
2772 this.eq_dragging = true;
2773 this.drag_band(event.position.x, cx);
2774 }),
2775 )
2776 .child(
2777 div()
2778 .flex_none()
2779 // Wide enough for "12 kHz high shelf", so the bars
2780 // below each other all start at the same pixel.
2781 .w(px(112.))
2782 .text_size(px(11.))
2783 .child(format!("{} {}", i + 1, band_label(band))),
2784 )
2785 .child(
2786 div()
2787 .flex_1()
2788 .h(px(EQ_BAR_H))
2789 .rounded(px(3.))
2790 .bg(rgb(SURFACE))
2791 .child(bounds_probe(self.eq_bar.clone()))
2792 .child(
2793 div()
2794 .absolute()
2795 .left(relative(left))
2796 .w(relative(width))
2797 .h_full()
2798 .rounded(px(3.))
2799 .bg(rgb(ACCENT)),
2800 ),
2801 )
2802 .child(
2803 div()
2804 .flex_none()
2805 // Fixed, so a sign or a second digit appearing does
2806 // not shift the bar beside it mid-drag.
2807 .w(px(56.))
2808 .text_size(px(11.))
2809 .text_color(rgb(INK_DIM))
2810 .child(format!("{:+.1} dB", band.gain_db)),
2811 )
2812 })
2813 .collect();
2814 Some(
2815 div()
2816 .absolute()
2817 .inset_0()
2818 .flex()
2819 .justify_center()
2820 .items_center()
2821 .bg(rgba(0x101010cc))
2822 .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| {
2823 cx.stop_propagation()
2824 })
2825 .child(
2826 div()
2827 .w(px(KEYS_W))
2828 .flex()
2829 .flex_col()
2830 .gap(px(2.))
2831 .p(px(12.))
2832 .rounded(px(6.))
2833 .bg(rgb(SURFACE))
2834 // Which clip, because the card is modal and the lane it
2835 // was opened from is behind a scrim by the time it is up.
2836 .child(div().flex_none().px(px(6.)).child(format!(
2837 "Equalizer — {} clip {}",
2838 lane.label(),
2839 idx + 1
2840 )))
2841 .child(
2842 div()
2843 .flex_none()
2844 .px(px(6.))
2845 .text_size(px(11.))
2846 .text_color(rgb(INK_DIM))
2847 .child(self.notice.clone().unwrap_or_else(|| {
2848 "drag a band, or 1–5 then up/down — esc closes".into()
2849 })),
2850 )
2851 // Five rows fit a 360 px window, but the layout is data
2852 // (a file may carry any number of bands), so the list
2853 // scrolls like the other two cards' do.
2854 .child(
2855 div()
2856 .id("eq-rows")
2857 .flex()
2858 .flex_col()
2859 .gap(px(2.))
2860 .max_h(px(EXPORT_ROWS_H))
2861 .overflow_y_scroll()
2862 .children(rows),
2863 )
2864 .child(
2865 div()
2866 .id("eq-reset")
2867 .mt(px(4.))
2868 .flex()
2869 .h(px(CONTROL_H))
2870 .items_center()
2871 .justify_center()
2872 .rounded(px(3.))
2873 .bg(rgb(SELECTED))
2874 .cursor_pointer()
2875 .hover(|s| s.bg(rgb(HOVER)))
2876 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
2877 for band in &mut this.eq_params.bands {
2878 band.gain_db = 0.;
2879 }
2880 this.commit_eq(cx);
2881 }))
2882 .child("Flatten"),
2883 ),
2884 ),
2885 )
2886 }
2887
2888 /// The colour card: a row per control, each showing where in its range it
2889 /// stands and carrying the pair of buttons that move it -- the same move the
2890 /// arrow keys make, because a control only the pointer can reach is not one
2891 /// everyone can reach. Same scrim, surface and row shape as the other two
2892 /// cards, and the same plain divs, so the root keeps the keyboard.
2893 ///
2894 /// The values are read from the project every render: what is drawn is what
2895 /// the decoder is grading with, never a copy that could drift from it.
2896 fn color_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
2897 let (lane, idx) = self.color_open?;
2898 let params = self.color_params();
2899 let rows: Vec<_> = COLOR_BANDS
2900 .iter()
2901 .enumerate()
2902 .map(|(i, &(label, low, high))| {
2903 let mut read = params;
2904 let value = *band_mut(&mut read, i);
2905 let frac = ((value - low) / (high - low)).clamp(0., 1.);
2906 let picked = i == self.color_band;
2907 // Both buttons of a row do what the arrows do, so there is one
2908 // rule for what a press is worth and one place it is clamped.
2909 let step = |name: &'static str, steps: f32| {
2910 div()
2911 .id((name, i))
2912 .w(px(CONTROL_H))
2913 .h(px(CONTROL_H))
2914 .flex()
2915 .items_center()
2916 .justify_center()
2917 .rounded(px(3.))
2918 .bg(rgb(CHROME))
2919 .cursor_pointer()
2920 .hover(|s| s.bg(rgb(HOVER)))
2921 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
2922 this.color_band = i;
2923 this.nudge_color(steps, cx);
2924 }))
2925 .child(if steps < 0. { "–" } else { "+" })
2926 };
2927 div()
2928 .id(("color-row", i))
2929 .flex()
2930 .min_h(px(KEYS_ROW_H))
2931 .items_center()
2932 .gap(px(8.))
2933 .px(px(6.))
2934 .rounded(px(3.))
2935 .cursor_pointer()
2936 .when(picked, |d| d.bg(rgb(SELECTED)))
2937 .hover(|s| s.bg(rgb(HOVER)))
2938 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
2939 this.color_band = i;
2940 cx.notify();
2941 }))
2942 .child(div().flex_1().min_w(px(0.)).truncate().child(label))
2943 .child(step("color-down", -1.))
2944 .child(
2945 div()
2946 .w(px(COLOR_BAR_W))
2947 .h(px(4.))
2948 .rounded(px(2.))
2949 .bg(rgb(CHROME))
2950 .child(
2951 div()
2952 .h_full()
2953 .w(relative(frac))
2954 .rounded(px(2.))
2955 .bg(rgb(ACCENT)),
2956 ),
2957 )
2958 .child(step("color-up", 1.))
2959 .child(
2960 div()
2961 .w(px(44.))
2962 .text_size(px(11.))
2963 .text_color(rgb(INK_DIM))
2964 .child(format!("{value:.2}")),
2965 )
2966 })
2967 .collect();
2968 Some(
2969 div()
2970 .absolute()
2971 .inset_0()
2972 .flex()
2973 .justify_center()
2974 .items_center()
2975 .bg(rgba(0x101010cc))
2976 .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| {
2977 cx.stop_propagation()
2978 })
2979 .child(
2980 div()
2981 .w(px(COLOR_W))
2982 .flex()
2983 .flex_col()
2984 .gap(px(2.))
2985 .p(px(12.))
2986 .rounded(px(6.))
2987 .bg(rgb(SURFACE))
2988 .child(div().flex_none().px(px(6.)).child(format!(
2989 "Colour — {} clip {}",
2990 lane.label(),
2991 idx + 1
2992 )))
2993 .child(
2994 div()
2995 .flex_none()
2996 .px(px(6.))
2997 .text_size(px(11.))
2998 .text_color(rgb(INK_DIM))
2999 .child("↑↓ picks a slider, ←→ moves it, r resets — esc closes"),
3000 )
3001 .children(rows)
3002 .child(
3003 div()
3004 .id("color-reset")
3005 .mt(px(4.))
3006 .flex()
3007 .h(px(CONTROL_H))
3008 .items_center()
3009 .justify_center()
3010 .rounded(px(3.))
3011 .bg(rgb(SELECTED))
3012 .cursor_pointer()
3013 .hover(|s| s.bg(rgb(HOVER)))
3014 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
3015 this.set_color(ColorParams::default(), cx);
3016 }))
3017 .child("Reset"),
3018 ),
3019 ),
3020 )
3021 }
3022
3023 /// The menu a right-click on a clip opens: what that clip can be given,
3024 /// each item beside the stroke that does the very same thing, and a
3025 /// turn-over side that says what the clip *is*. An item that would do
3026 /// nothing where the playhead is standing is dimmed and takes no click
3027 /// rather than disappearing, so the menu reads the same every time.
3028 ///
3029 /// Every item goes through [`Player::act`], the table the key handler uses:
3030 /// an item is its stroke, asked for with the mouse. Plain divs like the
3031 /// rest of this window, so the root keeps the keyboard and escape still
3032 /// reaches the handler that closes this.
3033 fn context_card(
3034 &self,
3035 viewport: Size<Pixels>,
3036 cx: &mut Context<Self>,
3037 ) -> Option<impl IntoElement> {
3038 let menu = self.context_menu?;
3039 let session = self.session.as_ref()?;
3040 let clip = *session.lane_clips(menu.lane).get(menu.idx)?;
3041 let playhead = frame_at(session.now(), self.fps);
3042 let source = session.sources().get(clip.source).cloned()?;
3043 let secs = |frames: u32| timecode(f64::from(frames) / self.fps, self.fps);
3044 let row = |n: usize| {
3045 div()
3046 .id(("menu", n))
3047 .flex()
3048 // The floor, not the height: a long label wrapping must not
3049 // paint over the item under it.
3050 .min_h(px(MENU_ROW_H))
3051 .items_center()
3052 .justify_between()
3053 .gap(px(12.))
3054 .px(px(6.))
3055 .rounded(px(3.))
3056 };
3057 let mut rows: Vec<AnyElement> = Vec::new();
3058 if menu.details {
3059 // Read-only, so no ids and no hover: this side is a card, not a
3060 // list of things to click. Each value is one truncated line, which
3061 // is what keeps the height below the one the clamp was given.
3062 for (label, value) in [
3063 ("File", file_name(&source.path)),
3064 ("Path", source.path.display().to_string()),
3065 (
3066 "Source range",
3067 format!("{} – {}", secs(clip.in_frame), secs(clip.out_frame)),
3068 ),
3069 ("This clip", secs(clip.len())),
3070 (
3071 "Source duration",
3072 secs(source_frames(
3073 lane_clips(session),
3074 session.sources(),
3075 &source.path,
3076 )),
3077 ),
3078 ] {
3079 rows.push(
3080 row(rows.len())
3081 .child(label)
3082 .child(
3083 div()
3084 .min_w(px(0.))
3085 .truncate()
3086 // A size smaller than the labels: a timecode
3087 // pair is 25 characters and has to fit beside
3088 // its label inside `MENU_W`.
3089 .text_size(px(11.))
3090 .text_color(rgb(INK_DIM))
3091 .child(value),
3092 )
3093 .into_any_element(),
3094 );
3095 }
3096 } else {
3097 for action in MENU_ITEMS {
3098 let enabled = applicable(&clip, menu.lane, action, playhead);
3099 // The one item that is not about this clip says so, and says it
3100 // here rather than in the registry: the stroke is global too,
3101 // but its row in the keys menu is not sitting on a clip.
3102 let label = if action == ActionId::ToggleMute {
3103 format!("{} (global)", action.label())
3104 } else {
3105 action.label().to_string()
3106 };
3107 rows.push(
3108 row(rows.len())
3109 .child(label)
3110 .child(
3111 div()
3112 .text_color(rgb(INK_DIM))
3113 .child(self.keymap.display(action)),
3114 )
3115 .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed())
3116 .when(enabled, |d| {
3117 d.cursor_pointer()
3118 .hover(|s| s.bg(rgb(HOVER)))
3119 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
3120 // Closed first: the action moves the very
3121 // indices this menu is holding.
3122 this.context_menu = None;
3123 this.act(action, cx);
3124 }))
3125 })
3126 .into_any_element(),
3127 );
3128 }
3129 rows.push(
3130 row(rows.len())
3131 .cursor_pointer()
3132 .hover(|s| s.bg(rgb(HOVER)))
3133 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
3134 if let Some(menu) = &mut this.context_menu {
3135 menu.details = true;
3136 }
3137 cx.notify();
3138 }))
3139 .child("Properties")
3140 // No stroke reaches this one, and a blank column would read
3141 // as one that was forgotten.
3142 .child(div().text_color(rgb(INK_DIM)).child("…"))
3143 .into_any_element(),
3144 );
3145 }
3146 let (x, y) = menu_at(
3147 menu.at,
3148 viewport,
3149 MENU_PAD * 2. + rows.len() as f32 * MENU_ROW_H,
3150 );
3151 let full: SharedString = source.path.display().to_string().into();
3152 Some(
3153 div()
3154 .absolute()
3155 .inset_0()
3156 // Click away closes it, either button, and the press is
3157 // swallowed so nothing under the menu also takes it. No tint,
3158 // unlike the modal cards: the timeline this menu is about has
3159 // to stay readable behind it.
3160 .on_mouse_down(
3161 MouseButton::Left,
3162 cx.listener(|this, _: &MouseDownEvent, _, cx| {
3163 this.context_menu = None;
3164 cx.notify();
3165 cx.stop_propagation();
3166 }),
3167 )
3168 .on_mouse_down(
3169 MouseButton::Right,
3170 cx.listener(|this, _: &MouseDownEvent, _, cx| {
3171 this.context_menu = None;
3172 cx.notify();
3173 cx.stop_propagation();
3174 }),
3175 )
3176 .child(
3177 div()
3178 // Only so the details side can carry a tooltip, which
3179 // gpui gives to identified elements alone.
3180 .id("menu-card")
3181 .absolute()
3182 .left(px(x))
3183 .top(px(y))
3184 .w(px(MENU_W))
3185 .flex()
3186 .flex_col()
3187 .p(px(MENU_PAD))
3188 .rounded(px(6.))
3189 .bg(rgb(SURFACE))
3190 // Painted after the scrim, so this listener runs first
3191 // (gpui bubbles mouse events in reverse, window.rs:3705)
3192 // and a press meant for an item never closes the menu
3193 // out from under its own click.
3194 .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| {
3195 cx.stop_propagation()
3196 })
3197 .on_mouse_down(MouseButton::Right, |_: &MouseDownEvent, _, cx| {
3198 cx.stop_propagation()
3199 })
3200 // The one value the details side has to truncate.
3201 .when(menu.details, |d| {
3202 d.tooltip(move |_, cx| cx.new(|_| Tip(full.clone())).into())
3203 })
3204 .children(rows),
3205 ),
3206 )
3207 }
3208
3209 /// One lane of the edit list made visible: a fixed header saying which lane
3210 /// it is, then a bed with a box per clip, placed and sized by its share of
3211 /// the timeline. A cut adds a box without moving anything, a delete closes
3212 /// the hole, a lift leaves one. A clip too narrow for its name says what it
3213 /// is by its tint, and the tooltip is where every box says what clicking it
3214 /// does. Never focusable, so the root keeps focus and the play binding still
3215 /// works after a click (ledger:182).
3216 fn lane_row(
3217 &self,
3218 lane: Lane,
3219 duration: f64,
3220 filled: f32,
3221 cx: &mut Context<Self>,
3222 // Borrows nothing it was given (`use<>`): the rows are built one after
3223 // another into a list, and a row still holding `cx` would be the only
3224 // one that could be built.
3225 ) -> impl IntoElement + use<> {
3226 // The bed's own width, measured last repaint off the ruler's bar: the
3227 // two are laid out identically (same header offset, same `flex_1`), so
3228 // one probe answers for both. Zero before the first paint, which only
3229 // costs the labels one frame.
3230 let bed_w = f32::from(self.ruler.get().size.width);
3231 let clips = self
3232 .session
3233 .as_ref()
3234 .map_or(&[][..], |session| session.lane_clips(lane));
3235 // The group ids some *other* lane carries: a clip whose id is in here
3236 // has a half elsewhere, and one whose is not is a detached half however
3237 // many lanes there are.
3238 let others: Vec<u32> = self.session.as_ref().map_or_else(Vec::new, |session| {
3239 session
3240 .lanes()
3241 .into_iter()
3242 .filter(|&other| other != lane)
3243 .flat_map(|other| session.lane_clips(other))
3244 .filter_map(|clip| clip.link)
3245 .collect()
3246 });
3247 let name = lane.label();
3248 let row_id: SharedString = format!("{name}-clip").into();
3249 let sources = self
3250 .session
3251 .as_ref()
3252 .map_or(&[][..], PlaybackSession::sources);
3253 let (sel, sel_link) = (self.selected, self.selected_link());
3254 let audio = lane.kind == LaneKind::Audio;
3255 let tip: SharedString = format!(
3256 "Select (or {} under the playhead, {}/{} along the lane) — {} removes the take, {} leaves a gap, {} rejoins a cut",
3257 self.keymap.display(ActionId::Select),
3258 self.keymap.display(ActionId::SelectPrev),
3259 self.keymap.display(ActionId::SelectNext),
3260 self.keymap.display(ActionId::Delete),
3261 self.keymap.display(ActionId::Lift),
3262 self.keymap.display(ActionId::Regroup)
3263 )
3264 .into();
3265 div()
3266 .flex_none()
3267 .h(px(LANE_H))
3268 .flex()
3269 .gap(px(HEADER_GAP))
3270 // The fixed column the ruler above is offset by as well. Full lane
3271 // height, so it reads as the bed continuing rather than as a chip.
3272 .child(
3273 div()
3274 .flex_none()
3275 .w(px(HEADER_W))
3276 .h_full()
3277 .flex()
3278 .items_center()
3279 .justify_center()
3280 .rounded(px(3.))
3281 .bg(rgb(SURFACE))
3282 .text_size(px(11.))
3283 .text_color(rgb(INK_DIM))
3284 .child(name),
3285 )
3286 .child(
3287 // Clips are placed at their own start rather than queued edge
3288 // to edge: a lift leaves a hole in the lane, and the bare bed
3289 // showing through it *is* how a gap looks.
3290 div()
3291 .relative()
3292 .flex_1()
3293 .min_w(px(0.))
3294 .h_full()
3295 .rounded(px(3.))
3296 .bg(rgb(LETTERBOX))
3297 .overflow_hidden()
3298 // A library row let go over a lane is the same insert the
3299 // Add button makes, through the same call -- at the
3300 // playhead, not at the pointer: clips here are placed end
3301 // to end, so where along the bed it landed says nothing.
3302 .on_drop(cx.listener(move |this, drag: &AssetDrag, _, cx| {
3303 this.insert_source(&drag.0.clone(), drag.1, Some(lane), cx)
3304 }))
3305 .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))
3306 .children(clips.iter().enumerate().map(|(i, clip)| {
3307 let (start, len) = (
3308 f64::from(clip.start) / self.fps,
3309 f64::from(clip.len()) / self.fps,
3310 );
3311 let on = marked((lane, i), clip.link, sel, sel_link);
3312 // A group with a half in the other lane wears its tint;
3313 // one without is outlined, so a detached half is visible
3314 // as detached before anyone clicks it.
3315 let grouped = clip.link.is_some_and(|link| others.contains(&link));
3316 // Tinted by *file*, not by source entry: two audio
3317 // streams of one file are two sources, and the library
3318 // gives them one swatch because they are one file.
3319 let tint = source_tint(
3320 sources
3321 .get(clip.source)
3322 .and_then(|s| sources.iter().position(|o| o.path == s.path))
3323 .unwrap_or(clip.source),
3324 );
3325 let width = width_frac(len, duration);
3326 let label = sources.get(clip.source).map(|s| file_name(&s.path));
3327 let wave = sources
3328 .get(clip.source)
3329 .and_then(|s| self.waves.get(&(s.path.clone(), s.audio_stream)))
3330 .cloned();
3331 let (from, to) = (
3332 f64::from(clip.in_frame) / self.fps,
3333 f64::from(clip.out_frame) / self.fps,
3334 );
3335 let tip = tip.clone();
3336 div()
3337 // Named per lane: two rows numbering their clips
3338 // from zero would hand gpui the same id twice.
3339 .id((row_id.clone(), i))
3340 .absolute()
3341 .top_0()
3342 .h_full()
3343 .left(relative(start_frac(start, duration)))
3344 .w(relative(width))
3345 .overflow_hidden()
3346 .rounded(px(3.))
3347 .border_1()
3348 .border_color(rgb(if on {
3349 ACCENT
3350 } else if grouped {
3351 tint
3352 } else {
3353 INK_DIM
3354 }))
3355 .bg(rgb(if on { SELECTED } else { tint }))
3356 .cursor_pointer()
3357 .hover(|s| s.border_color(rgb(ACCENT)))
3358 .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())
3359 .on_mouse_down(
3360 MouseButton::Left,
3361 cx.listener(move |this, _: &MouseDownEvent, _, cx| {
3362 this.select((lane, i), cx);
3363 }),
3364 )
3365 // The right button selects exactly as the left one
3366 // does -- the menu acts on the clip it names, so
3367 // opening one has to pick it -- and then hangs the
3368 // menu at the pointer.
3369 .on_mouse_down(
3370 MouseButton::Right,
3371 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
3372 if this.modal() {
3373 return;
3374 }
3375 this.select((lane, i), cx);
3376 this.context_menu = Some(ContextMenu {
3377 lane,
3378 idx: i,
3379 at: event.position,
3380 details: false,
3381 });
3382 cx.notify();
3383 }),
3384 )
3385 // Under the label row, never through it.
3386 .children(wave.filter(|_| audio).and_then(|wave| {
3387 let inner: AnyElement = match wave {
3388 Wave::Peaks(peaks) => {
3389 waveform(peaks, from, to).into_any_element()
3390 }
3391 // A bed while the decode runs, and dimmer
3392 // than any waveform is drawn: a flat
3393 // `INK_DIM` line here would be the shape a
3394 // silent file makes, which this file is not
3395 // known to be yet.
3396 Wave::Loading => div()
3397 .h_full()
3398 .flex()
3399 .items_center()
3400 .child(div().w_full().h(px(1.)).bg(rgb(HOVER)))
3401 .into_any_element(),
3402 // No audio track: nothing, never a fake.
3403 Wave::Silent => return None,
3404 };
3405 Some(
3406 div()
3407 .absolute()
3408 .left_0()
3409 .right_0()
3410 .top(px(LABEL_H))
3411 .bottom_0()
3412 .child(inner),
3413 )
3414 }))
3415 .when_some(label.filter(|_| show_label(bed_w * width)), |d, label| {
3416 d.child(
3417 div()
3418 .relative()
3419 .h(px(LABEL_H))
3420 .px(px(4.))
3421 .truncate()
3422 .text_size(px(10.))
3423 .child(label),
3424 )
3425 })
3426 }))
3427 // Last, so it is over the clips: the same fraction in both
3428 // lanes, which is the playhead being one line.
3429 .child(
3430 div()
3431 .absolute()
3432 .top_0()
3433 .h_full()
3434 .left(relative(filled))
3435 .w(px(1.))
3436 .bg(rgb(ACCENT)),
3437 ),
3438 )
3439 }
3440}
3441
3442/// Rate limit for scrub seeks: a video worker reopen costs 72-87 ms on the
3443/// hardware path (215 ms in software), so one seek per mouse move would only
3444/// queue workers that are cancelled before they decode anything.
3445const SCRUB_GAP: Duration = Duration::from_millis(100);
3446
3447fn scrub_due(target: u32, last_target: u32, since: Duration) -> bool {
3448 target != last_target && since >= SCRUB_GAP
3449}
3450
3451/// Runs the first chooser that is installed. `Some(None)` is a cancelled
3452/// dialog; `None` is a machine with no chooser at all, and what still works
3453/// without one differs per dialog, so the caller words that refusal.
3454///
3455/// The desktop's own choosers, asked for by name because gpui 0.2 has no file
3456/// dialog of its own and none of these is worth a dependency.
3457fn run_picker(pickers: [(&str, Vec<String>); 2]) -> Option<Option<PathBuf>> {
3458 for (bin, args) in pickers {
3459 // Not installed: try the next one. Anything else (a cancel, a refusal)
3460 // is that chooser's answer and is taken as final.
3461 let Ok(out) = std::process::Command::new(bin).args(args).output() else {
3462 continue;
3463 };
3464 let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
3465 return Some((!path.is_empty()).then(|| PathBuf::from(path)));
3466 }
3467 None
3468}
3469
3470fn pick_file() -> Result<Option<PathBuf>, &'static str> {
3471 run_picker([
3472 (
3473 "zenity",
3474 vec!["--file-selection".into(), "--title=edith — import".into()],
3475 ),
3476 ("kdialog", vec!["--getopenfilename".into()]),
3477 ])
3478 .ok_or(
3479 "NO FILE CHOOSER — install zenity or kdialog, or drag the file onto this window to import it",
3480 )
3481}
3482
3483/// The save-side dialog, opened on where the export would land anyway: with no
3484/// chooser installed that default is still what gets written, so this refusal
3485/// costs the export nothing and says so.
3486fn pick_save(default: &std::path::Path) -> Result<Option<PathBuf>, &'static str> {
3487 let default = default.to_string_lossy().into_owned();
3488 run_picker([
3489 (
3490 "zenity",
3491 vec![
3492 "--file-selection".into(),
3493 // No `--confirm-overwrite`: zenity 4.2 lists it as deprecated
3494 // and does the confirming itself.
3495 "--save".into(),
3496 "--title=edith — export to".into(),
3497 format!("--filename={default}"),
3498 ],
3499 ),
3500 ("kdialog", vec!["--getsavefilename".into(), default]),
3501 ])
3502 .ok_or(
3503 "NO FILE CHOOSER — install zenity or kdialog to choose where; exporting beside the source",
3504 )
3505}
3506
3507/// Where an export goes: the source path with `.export.mp4` for an extension,
3508/// so it lands beside the original and can never be the original.
3509fn export_path(source: impl Into<PathBuf>) -> PathBuf {
3510 let mut path = source.into();
3511 path.set_extension("export.mp4");
3512 path
3513}
3514
3515/// Where a save goes when the timeline did not come from a project file: the
3516/// media path with `.edith` for an extension, beside it like an export. A
3517/// project loaded from disk keeps its own path instead, so saving it twice
3518/// writes the same file.
3519fn project_path(source: impl Into<PathBuf>) -> PathBuf {
3520 let mut path = source.into();
3521 path.set_extension("edith");
3522 path
3523}
3524
3525/// Whether a dropped or named path is a project rather than media. Exactly the
3526/// lowercase extension `save_project` writes -- anything else goes to the
3527/// demuxer, which is the one that can say what it really is.
3528fn is_project(path: &std::path::Path) -> bool {
3529 path.extension().is_some_and(|e| e == "edith")
3530}
3531
3532/// The tail of a path, for showing. A path that is all root has none, and reads
3533/// as itself.
3534fn file_name(path: &std::path::Path) -> String {
3535 path.file_name().map_or_else(
3536 || path.display().to_string(),
3537 |n| n.to_string_lossy().into(),
3538 )
3539}
3540
3541/// The tail an open/load notice grows when the file has sound the engine cannot
3542/// decode: it plays perfectly, in silence, and that is the one thing the window
3543/// would otherwise never say (the engine's own word for it, verbatim).
3544fn audio_notice(session: &PlaybackSession) -> Option<String> {
3545 session
3546 .audio_disabled_reason()
3547 .map(|reason| format!(" — NO AUDIO: {reason}"))
3548}
3549
3550/// The sources a repaint has not asked about yet. A key that is already there
3551/// means "asked", whatever state it is in, which is what stops a decode already
3552/// running from being started again by the next of sixty repaints a second.
3553fn unseen_sources(
3554 sources: &[Source],
3555 waves: &HashMap<(PathBuf, usize), Wave>,
3556) -> Vec<(PathBuf, usize)> {
3557 sources
3558 .iter()
3559 .map(|s| (s.path.clone(), s.audio_stream))
3560 .filter(|key| !waves.contains_key(key))
3561 .collect()
3562}
3563
3564/// The same, for the per-file stream probe: one entry per *file*, however many
3565/// of its streams the timeline plays.
3566fn unseen_paths(sources: &[Source], streams: &HashMap<PathBuf, Vec<StreamInfo>>) -> Vec<PathBuf> {
3567 let mut out: Vec<PathBuf> = Vec::new();
3568 for s in sources {
3569 if !streams.contains_key(&s.path) && !out.contains(&s.path) {
3570 out.push(s.path.clone());
3571 }
3572 }
3573 out
3574}
3575
3576/// Every lane's clips, which is everything the timeline knows about its sources.
3577/// Every lane, not the first two: a clip that plays only on `V2` is still a clip
3578/// the source is used by, and a walk that missed it would call the file unused.
3579fn lane_clips(session: &PlaybackSession) -> impl Iterator<Item = &Clip> {
3580 session
3581 .lanes()
3582 .into_iter()
3583 .flat_map(|lane| session.lane_clips(lane))
3584}
3585
3586/// How long a source is, as the timeline knows it: the furthest frame any clip
3587/// plays from *the file*. Exact for a source the timeline still holds whole --
3588/// which is every source the moment it is imported -- and never longer than the
3589/// file, since every clip was checked against it, so a clip built from this can
3590/// always be played. Zero for a file nothing plays from any more.
3591///
3592/// By file rather than by source entry, because a second audio stream of a file
3593/// already on the timeline is a row that has no clips of its own yet, and every
3594/// stream of a file is the same length -- the picture is what the length is.
3595///
3596/// ponytail: a source trimmed on the timeline reads as its trimmed length. The
3597/// file's own length would need a `Demuxer::open` probe per source, off the
3598/// render path like the peak decode is -- that is the upgrade path.
3599fn source_frames<'a>(
3600 clips: impl Iterator<Item = &'a Clip>,
3601 sources: &[Source],
3602 path: &Path,
3603) -> u32 {
3604 clips
3605 .filter(|clip| sources.get(clip.source).is_some_and(|s| s.path == path))
3606 .map(|clip| clip.out_frame)
3607 .max()
3608 .unwrap_or(0)
3609}
3610
3611/// Which timeline frame the playhead is on, by the rule the engine's own edits
3612/// use (playback.rs `secs_to_frame`): the frame that has started, with the
3613/// epsilon that keeps a clock sitting exactly on a boundary from reading as the
3614/// frame before it. Only ever a hint here -- what an edit does is still the
3615/// engine's answer, taken from the same seconds.
3616fn frame_at(secs: f64, fps: f64) -> u32 {
3617 (secs * fps + 1e-6).floor().max(0.) as u32
3618}
3619
3620/// A band's bar as `(left, width)` in fractions of the track: the fill grows
3621/// out of the *middle*, which is flat, towards whichever end the gain went --
3622/// a bar that filled from the left would read a -12 dB cut as an empty control
3623/// and 0 dB as a half-off one. The inverse of [`Player::drag_band`]'s reading
3624/// of a click, and clamped like it, so a curve loaded from a file with a gain
3625/// past the card's limit paints at the end of the bar rather than outside it.
3626fn eq_fill(gain_db: f32) -> (f32, f32) {
3627 let at = (gain_db / EQ_GAIN_LIMIT).clamp(-1., 1.) / 2. + 0.5;
3628 match at >= 0.5 {
3629 true => (0.5, at - 0.5),
3630 false => (at, 0.5 - at),
3631 }
3632}
3633
3634/// What a band row calls itself: the corner or centre frequency, and for a
3635/// shelf the fact that it tilts everything past it -- which is the difference
3636/// between "12 kHz" moving the last octave and moving one band inside it.
3637fn band_label(band: &Band) -> String {
3638 let freq = match band.freq_hz >= 1000. {
3639 true => format!("{:.0} kHz", band.freq_hz / 1000.),
3640 false => format!("{:.0} Hz", band.freq_hz),
3641 };
3642 match band.kind {
3643 BandKind::LowShelf => format!("{freq} low shelf"),
3644 BandKind::HighShelf => format!("{freq} high shelf"),
3645 BandKind::Peak => freq,
3646 }
3647}
3648
3649/// Whether the clip menu offers `action` on the clip it was opened on. Two of
3650/// the items act on the *playhead* rather than on the clip, so a menu opened
3651/// away from it dims them instead of looking broken when they are clicked, and
3652/// one acts on sound, which only an audio lane's clip has.
3653fn applicable(clip: &Clip, lane: Lane, action: ActionId, playhead: u32) -> bool {
3654 match action {
3655 // The equalizer filters samples, and a video clip has none of its own
3656 // here: the sound is the audio lane's, clip for clip.
3657 ActionId::Equalizer => lane.kind == LaneKind::Audio,
3658 // A grade is a picture setting and an audio clip has no picture: the
3659 // item is there on every clip, and dimmed where it would mean nothing.
3660 // A fit policy is a picture setting for the same reason.
3661 ActionId::Color | ActionId::Fit => lane.kind == LaneKind::Video,
3662 // Splits this clip only from inside it: at either edge there is nothing
3663 // to split off (project.rs `splittable`).
3664 ActionId::Cut => clip.start < playhead && playhead < clip.end(),
3665 // Rejoins whatever meets at the playhead, so it can mean something only
3666 // at an edge of this clip. Whether those two halves were ever one take
3667 // is the engine's question, and it words that refusal itself.
3668 ActionId::Regroup => playhead == clip.start || playhead == clip.end(),
3669 _ => true,
3670 }
3671}
3672
3673/// Where the menu actually hangs: at the pointer, pulled back inside the window
3674/// when it would not fit -- an item off the bottom edge is an item nobody can
3675/// click. Never negative, so a window smaller than the menu loses the bottom of
3676/// it rather than the top, where the items are.
3677fn menu_at(at: Point<Pixels>, viewport: Size<Pixels>, height: f32) -> (f32, f32) {
3678 let fit = |v: f32, size: f32, room: f32| v.min(room - size).max(0.);
3679 (
3680 fit(f32::from(at.x), MENU_W, f32::from(viewport.width)),
3681 fit(f32::from(at.y), height, f32::from(viewport.height)),
3682 )
3683}
3684
3685/// Whether the Add button does anything: a row picked, a timeline to put it on,
3686/// and no export reading that timeline. A button that would do nothing is dimmed
3687/// and takes no click, like every other one here.
3688fn can_add(picked: Option<&(PathBuf, usize)>, timeline: bool, exporting: bool) -> bool {
3689 picked.is_some() && timeline && !exporting
3690}
3691
3692/// One library row: a file and one of its audio streams. Plain data, planned
3693/// before anything is drawn -- which rows exist at all is the branchy part.
3694#[derive(Debug, PartialEq)]
3695struct Row {
3696 path: PathBuf,
3697 stream: usize,
3698 /// The file, plus which stream this is when the file has several.
3699 name: String,
3700 /// What the stream is, or blank for a file with a single one.
3701 detail: String,
3702 /// Why it cannot be put on this timeline, for a row that cannot: shown in
3703 /// place of the length and the only thing that greys a row out.
3704 unusable: Option<String>,
3705 /// Frames of the *file*, for the length line.
3706 frames: u32,
3707 /// Index into `SOURCE_TINTS`, shared by every stream of one file: the
3708 /// swatch says which file, and the lanes tint their clips the same way.
3709 tint: usize,
3710}
3711
3712/// Every row the library shows: one per source entry, plus one for each further
3713/// audio stream those files have that no clip plays yet -- a remux with a track
3714/// per language lists them all, the ones this engine cannot use greyed out
3715/// rather than hidden. Streams a file has not been probed for yet simply are
3716/// not there; the row for what *is* on the timeline is always there.
3717///
3718/// `timeline_audio` is the rate and layout of source 0's stream, which every
3719/// other source must match: one output device and one copied AAC track for the
3720/// whole timeline (`PlaybackSession::place_stream_at`). `None` while unknown,
3721/// and then nothing is greyed for it -- the engine still refuses.
3722fn library_rows(
3723 sources: &[Source],
3724 streams: &HashMap<PathBuf, Vec<StreamInfo>>,
3725 timeline_audio: Option<(u32, u16)>,
3726 frames: impl Fn(&Path) -> u32,
3727) -> Vec<Row> {
3728 let mut rows = Vec::new();
3729 for (i, source) in sources.iter().enumerate() {
3730 let of_file = streams.get(&source.path).map_or(&[][..], Vec::as_slice);
3731 let info = of_file.iter().find(|s| s.index == source.audio_stream);
3732 let tint = sources
3733 .iter()
3734 .position(|s| s.path == source.path)
3735 .expect("a source finds itself");
3736 rows.push(Row {
3737 path: source.path.clone(),
3738 stream: source.audio_stream,
3739 name: row_name(&source.path, source.audio_stream, of_file.len() > 1),
3740 // Only where there is a choice to describe: a file with one audio
3741 // track is the row it has always been, name and length, and the
3742 // length is what would be squeezed out at the panel's least width.
3743 detail: info
3744 .filter(|_| of_file.len() > 1)
3745 .map_or_else(String::new, stream_detail),
3746 // A stream already on the timeline is playing: whatever a probe
3747 // would say about it now, it is usable by demonstration.
3748 unusable: None,
3749 frames: frames(&source.path),
3750 tint,
3751 });
3752 // The file's other streams, listed once, right after the last entry
3753 // that names the file -- so a file's rows sit together.
3754 if sources[i + 1..].iter().any(|s| s.path == source.path) {
3755 continue;
3756 }
3757 for info in of_file {
3758 if sources
3759 .iter()
3760 .any(|s| s.path == source.path && s.audio_stream == info.index)
3761 {
3762 continue; // it has a row of its own above
3763 }
3764 rows.push(Row {
3765 path: source.path.clone(),
3766 stream: info.index,
3767 name: row_name(&source.path, info.index, true),
3768 detail: stream_detail(info),
3769 unusable: unusable(info, timeline_audio),
3770 frames: frames(&source.path),
3771 tint,
3772 });
3773 }
3774 }
3775 rows
3776}
3777
3778/// The row's second line: what the stream is and then either how long it is or
3779/// why it cannot be used, with the separator only where both halves exist (a
3780/// single-stream file says nothing about its stream).
3781fn join_detail(detail: &str, tail: &str) -> String {
3782 match detail.is_empty() {
3783 true => tail.to_string(),
3784 false => format!("{detail} · {tail}"),
3785 }
3786}
3787
3788/// How a row names its file: the file alone when it has one audio stream or
3789/// none, and the file plus which stream this row is when it has several --
3790/// counted from 1, the way a player numbers tracks.
3791fn row_name(path: &Path, stream: usize, several: bool) -> String {
3792 match several {
3793 false => file_name(path),
3794 true => format!("{} [audio {}]", file_name(path), stream + 1),
3795 }
3796}
3797
3798/// What a stream is, for the row's second line: the language if the file says
3799/// one, then rate and layout. A field the header does not give is left out
3800/// rather than shown as a zero -- a stream we cannot parse says nothing about
3801/// itself, and saying "0 Hz" would be saying something.
3802fn stream_detail(info: &StreamInfo) -> String {
3803 let mut parts: Vec<String> = Vec::new();
3804 if let Some(lang) = &info.lang {
3805 parts.push(lang.clone());
3806 }
3807 if info.sample_rate > 0 {
3808 parts.push(format!("{} kHz", f64::from(info.sample_rate) / 1000.));
3809 }
3810 parts.extend(layout(info.channels));
3811 parts.join(" ")
3812}
3813
3814fn layout(channels: u16) -> Option<String> {
3815 match channels {
3816 0 => None,
3817 1 => Some("mono".to_string()),
3818 2 => Some("stereo".to_string()),
3819 n => Some(format!("{n} ch")),
3820 }
3821}
3822
3823/// Why a stream cannot go on this timeline, or `None` if it can. Both answers
3824/// are shown: a stream nothing can be done with is listed greyed with the
3825/// reason, never dropped from the list -- a file has the tracks it has, and a
3826/// picker that hides them is a picker that lies.
3827fn unusable(info: &StreamInfo, timeline_audio: Option<(u32, u16)>) -> Option<String> {
3828 if !info.decodable {
3829 // AAC and AC-3 name themselves (`StreamInfo::codec`, which reads the
3830 // stsd fourcc by hand); anything else mp4 0.14 does not parse has no
3831 // name to give, and a row with no name still says why it is greyed.
3832 return Some(match info.codec.as_str() {
3833 "unknown" => "unsupported codec".to_string(),
3834 codec => format!("{codec} is not supported"),
3835 });
3836 }
3837 let (rate, channels) = timeline_audio?;
3838 ((info.sample_rate, info.channels) != (rate, channels)).then(|| {
3839 format!(
3840 "the timeline is {} kHz {}",
3841 f64::from(rate) / 1000.,
3842 layout(channels).unwrap_or_else(|| "silent".to_string())
3843 )
3844 })
3845}
3846
3847/// What the media list is given of the window. A share of it, so a narrow
3848/// window gives the panel less rather than giving the picture nothing, floored
3849/// where a name stops being readable and capped at a third of the window --
3850/// the picture is what the program is for and keeps the majority at every size.
3851fn library_w(window_w: f32) -> f32 {
3852 (window_w * LIBRARY_FRAC)
3853 .clamp(LIBRARY_MIN_W, LIBRARY_MAX_W)
3854 .min(window_w / 3.)
3855}
3856
3857/// What the window is called: the program, and what is open in it. The name is
3858/// what the header shows, so an empty window says the program alone rather than
3859/// "no file open — edith".
3860fn window_title(name: &str) -> String {
3861 if name == NO_FILE {
3862 "edith".to_string()
3863 } else {
3864 format!("{name} — edith")
3865 }
3866}
3867
3868/// The tint a clip from source `n` wears. Cycled rather than extended: past the
3869/// palette two sources share a colour, which is a smaller lie than a fifth tint
3870/// bright enough to leave the family.
3871fn source_tint(source: usize) -> u32 {
3872 SOURCE_TINTS[source % SOURCE_TINTS.len()]
3873}
3874
3875/// What the export card offers, top to bottom. Bitrate is the only thing the
3876/// encoder actually takes: the codec and the container are what this program
3877/// can write and nothing else, so the card states them rather than offering
3878/// them.
3879#[derive(Clone, Copy, PartialEq, Debug)]
3880enum Quality {
3881 Auto,
3882 Low,
3883 Medium,
3884 High,
3885 Custom,
3886}
3887
3888impl Quality {
3889 const ALL: [Quality; 5] = [
3890 Quality::Auto,
3891 Quality::Low,
3892 Quality::Medium,
3893 Quality::High,
3894 Quality::Custom,
3895 ];
3896
3897 fn label(self) -> &'static str {
3898 match self {
3899 Quality::Auto => "Auto",
3900 Quality::Low => "Low",
3901 Quality::Medium => "Medium",
3902 Quality::High => "High",
3903 Quality::Custom => "Custom",
3904 }
3905 }
3906
3907 /// The figure the row stands for, said in the units the row is chosen by.
3908 fn detail(self, custom_mbps: u32) -> String {
3909 match self {
3910 Quality::Auto => "from the picture size and frame rate".to_string(),
3911 Quality::Custom => format!("{custom_mbps} Mbps — type a number, 1–20"),
3912 other => format!(
3913 "{} Mbps",
3914 export_settings(other, 0, Format::Mp4)
3915 .bitrate
3916 .unwrap_or_default()
3917 / 1_000_000
3918 ),
3919 }
3920 }
3921}
3922
3923/// The export card's format rows: what this program can write, and what it
3924/// cannot with the reason it cannot. A format with no entry at all would read
3925/// as an oversight, and a menu of three as a claim that nothing else exists --
3926/// so the refusals are rows too, dimmed and unclickable.
3927///
3928/// `None` is exactly that kind of row. The MP3 reason is a *licence* and not a
3929/// capability: `shine-rs` encodes mp3 in pure Rust under LGPL-2.0, which is a
3930/// decision about this project rather than about the code, and the row says so
3931/// instead of pretending the encoder does not exist.
3932const FORMATS: [(Option<Format>, &str, &str); 6] = [
3933 (Some(Format::Mp4), "MP4", "H.264 picture + copied AAC"),
3934 (Some(Format::Wav), "WAV", "16-bit PCM — audio only"),
3935 (Some(Format::Flac), "FLAC", "lossless — audio only"),
3936 (None, "MP3", "encoder is LGPL — licence decision pending"),
3937 (None, "OGG", "no pure-Rust Vorbis or Opus encoder"),
3938 (None, "AAC", "no pure-Rust AAC encoder"),
3939];
3940
3941/// The format a key picks while the export card is up: the row's own initial,
3942/// which is unambiguous across the three that can be picked. `None` for
3943/// everything else, digits included -- those are the bitrate's.
3944fn format_key(key: &str) -> Option<Format> {
3945 FORMATS
3946 .into_iter()
3947 .filter_map(|(format, label, _)| format.zip(label.get(..1)))
3948 .find(|(_, initial)| initial.eq_ignore_ascii_case(key))
3949 .map(|(format, _)| format)
3950}
3951
3952/// What one of the colour card's own strokes does. Its keys are card-local --
3953/// they mean nothing outside it -- so they are a table here rather than keymap
3954/// bindings, exactly as the export card's format initials are. Listed in
3955/// `keymap::FIXED` all the same, which is how the keys menu still says so.
3956enum ColorKey {
3957 Close,
3958 /// Steps down the four sliders, wrapping.
3959 Band(usize),
3960 /// Moves the picked slider, in [`COLOR_STEP`]s.
3961 Nudge(f32),
3962 Reset,
3963}
3964
3965fn color_key(key: &str) -> Option<ColorKey> {
3966 Some(match key {
3967 ESCAPE => ColorKey::Close,
3968 "down" => ColorKey::Band(1),
3969 "up" => ColorKey::Band(COLOR_BANDS.len() - 1),
3970 "right" => ColorKey::Nudge(1.),
3971 "left" => ColorKey::Nudge(-1.),
3972 "r" => ColorKey::Reset,
3973 _ => return None,
3974 })
3975}
3976
3977/// The band'th control of a grade, to read or to write. The order is
3978/// [`COLOR_BANDS`]', which is the order the card lists them in.
3979fn band_mut(params: &mut ColorParams, band: usize) -> &mut f32 {
3980 match band {
3981 0 => &mut params.brightness,
3982 1 => &mut params.contrast,
3983 2 => &mut params.saturation,
3984 _ => &mut params.tint,
3985 }
3986}
3987
3988/// The line under the rows: what the picked format really writes, in the terms
3989/// a file is judged by afterwards.
3990/// The next policy round the cycle, in the order the action's label reads.
3991fn next_fit(fit: FitPolicy) -> FitPolicy {
3992 match fit {
3993 FitPolicy::Fit => FitPolicy::Fill,
3994 FitPolicy::Fill => FitPolicy::Stretch,
3995 FitPolicy::Stretch => FitPolicy::Center,
3996 FitPolicy::Center => FitPolicy::Fit,
3997 }
3998}
3999
4000/// What a person calls one, said as what it does to the picture.
4001fn fit_label(fit: FitPolicy) -> &'static str {
4002 match fit {
4003 FitPolicy::Fit => "fit (whole picture, bars)",
4004 FitPolicy::Fill => "fill (cropped, no bars)",
4005 FitPolicy::Stretch => "stretch (aspect broken)",
4006 FitPolicy::Center => "centre (1:1, no resample)",
4007 }
4008}
4009
4010/// The next project resolution after `current`, over [`RESOLUTIONS`] with the
4011/// media's own size cycled in at its place by size -- so the trip round always
4012/// comes back to the media, whatever odd shape it is, and a project already at a
4013/// listed size does not see it twice.
4014fn next_resolution(current: (u32, u32), native: (u32, u32)) -> (u32, u32) {
4015 let mut sizes: Vec<(u32, u32)> = RESOLUTIONS.to_vec();
4016 if !sizes.contains(&native) {
4017 // By area, descending, like the list itself: the cycle then reads as one
4018 // ladder rather than a list with a stray rung at the end.
4019 let at = sizes
4020 .iter()
4021 .position(|&(w, h)| {
4022 u64::from(w) * u64::from(h) < u64::from(native.0) * u64::from(native.1)
4023 })
4024 .unwrap_or(sizes.len());
4025 sizes.insert(at, native);
4026 }
4027 let at = sizes.iter().position(|&s| s == current);
4028 // A project at a size nobody listed (a hand-edited file) joins the cycle at
4029 // the top rather than being stuck.
4030 sizes[at.map_or(0, |at| (at + 1) % sizes.len())]
4031}
4032
4033/// [`format_line`] plus the project's resolution, which is what a video export
4034/// is written at however many sizes the media on the timeline are. Only for the
4035/// formats that carry a picture -- a WAV has no resolution to state.
4036fn export_line(format: Format, session: Option<&PlaybackSession>) -> String {
4037 let line = format_line(format);
4038 match session.filter(|_| format.has_video()) {
4039 Some(session) => {
4040 let (w, h) = session.resolution();
4041 format!("{line} · project {w}x{h}")
4042 }
4043 None => line.to_string(),
4044 }
4045}
4046
4047fn format_line(format: Format) -> &'static str {
4048 match format {
4049 Format::Mp4 => "H.264 · MP4 · moov at end",
4050 Format::Wav => "16-bit PCM · WAV · timeline audio only",
4051 Format::Flac => "FLAC · lossless · timeline audio only",
4052 }
4053}
4054
4055/// The destination under a format: `take.export.mp4` becomes `take.export.wav`.
4056/// The stem is untouched, so a name typed into the save dialog survives a
4057/// change of mind about the format -- only the extension is the format's to say.
4058fn retarget(path: &std::path::Path, format: Format) -> PathBuf {
4059 let mut path = path.to_path_buf();
4060 path.set_extension(format.ext());
4061 path
4062}
4063
4064/// The card's rows as the engine takes them. `Auto` leaves the bitrate to the
4065/// exporter, which derives it from the picture; the fixed rows are figures that
4066/// hold from 720p to 1080p, and a typed one is passed exactly as typed -- the
4067/// engine clamps every explicit bitrate to 1..20 Mbps (export.rs:290), so this
4068/// must not clamp it a second time and disagree about where the edge is.
4069///
4070/// The bitrate travels even for an audio format, where the engine ignores it:
4071/// one settings value, and a row the card has dimmed cannot have been changed.
4072fn export_settings(quality: Quality, custom_mbps: u32, format: Format) -> ExportSettings {
4073 ExportSettings {
4074 format,
4075 bitrate: match quality {
4076 Quality::Auto => None,
4077 Quality::Low => Some(2_000_000),
4078 Quality::Medium => Some(6_000_000),
4079 Quality::High => Some(12_000_000),
4080 Quality::Custom => Some(u64::from(custom_mbps) * 1_000_000),
4081 },
4082 // No row of its own: the software pin is for a driver that encodes
4083 // badly, which is a thing about the machine and not about the output --
4084 // `VE_SW_ENC` already says it, and to the whole run rather than once.
4085 force_sw: false,
4086 }
4087}
4088
4089/// A digit typed against the custom row, appended to what is already there.
4090/// Refused rather than truncated past two digits: the engine's ceiling is
4091/// 20 Mbps, so a third digit can only be a mistake, and a silently dropped one
4092/// would leave the card showing a number nobody typed.
4093fn push_digit(mbps: u32, digit: u32) -> u32 {
4094 let next = mbps * 10 + digit;
4095 if next <= 99 { next } else { mbps }
4096}
4097
4098/// Whether a stroke gets out of a running export. Escape does, whatever
4099/// modifiers are held with it, for the same reason it gets out of a capture and
4100/// out of the overlay: it is this window's way out, and a way out that only
4101/// works with the right modifiers is not one. Whatever the keymap has on cancel
4102/// works too, so rebinding it adds a way rather than replacing the one that
4103/// always worked -- and that binding is still what the progress line shows.
4104fn cancels_export(key: &str, action: Option<ActionId>) -> bool {
4105 key == ESCAPE || action == Some(ActionId::CancelExport)
4106}
4107
4108/// The keys that are only ever half a chord. gpui delivers a lone modifier
4109/// press as a keystroke of its own, and taking one as a binding would leave an
4110/// action that fires the moment the user reaches for any chord that uses it --
4111/// so a capture waits through them instead.
4112fn is_bare_modifier(key: &str) -> bool {
4113 matches!(
4114 key,
4115 "control" | "shift" | "alt" | "super" | "platform" | "function" | "fn" | "meta" | "command"
4116 )
4117}
4118
4119/// A clip's share of the lane. A timeline with no length reads as one full-width
4120/// box rather than as NaN, which gpui would carry into layout.
4121/// Why this timeline cannot be written as an mp4, if it cannot: the mp4 path
4122/// *copies* one AAC track and there is no encoder here to mix several with, so a
4123/// timeline whose sound is spread over more than one audio lane is refused by
4124/// the engine (`export::run`). Said on the row, before a destination has been
4125/// picked, rather than after the write has started.
4126fn mp4_refusal(session: &PlaybackSession) -> Option<String> {
4127 let lanes = session
4128 .lanes()
4129 .into_iter()
4130 .filter(|&lane| lane.kind == LaneKind::Audio && !session.lane_clips(lane).is_empty())
4131 .count();
4132 (lanes > 1).then(|| format!("{lanes} audio lanes — an mp4 copies one"))
4133}
4134
4135/// How tall a column of `lanes` rows is, gaps included -- the panel's own gap
4136/// between them, since the rows sit in it.
4137fn lanes_h(lanes: usize) -> f32 {
4138 match lanes {
4139 0 => 0.,
4140 n => n as f32 * LANE_H + (n - 1) as f32 * 8.,
4141 }
4142}
4143
4144/// How tall the panel is with `lanes` tracks in it: [`PANEL_H`] is sized for the
4145/// two a project starts with, and every further one adds its own row -- up to
4146/// [`LANES_MAX`], past which the lane column scrolls instead and the panel stops
4147/// growing.
4148fn panel_h(lanes: usize) -> f32 {
4149 PANEL_H + lanes_h(lanes.clamp(2, LANES_MAX)) - lanes_h(2)
4150}
4151
4152fn width_frac(len: f64, total: f64) -> f32 {
4153 if total > 0. { (len / total) as f32 } else { 1. }
4154}
4155
4156/// Where along the lane a clip starts, 0..1. Unlike [`width_frac`] a timeline
4157/// with no length pins this to the left edge -- a full-width offset would push
4158/// the box out of the lane it belongs to.
4159fn start_frac(start: f64, total: f64) -> f32 {
4160 if total > 0. {
4161 (start / total).clamp(0., 1.) as f32
4162 } else {
4163 0.
4164 }
4165}
4166
4167/// Whether this clip is a whole take, i.e. whether deleting it may close the
4168/// hole under it: a take is what the first pair of lanes carries between them,
4169/// `V1`'s picture and the sound grouped with it, and dropping one moves the
4170/// frames after it on every lane.
4171///
4172/// Everything else is a half or a layer, and is *lifted* instead: a half whose
4173/// picture was lifted (what a lift leaves behind) has no take to ripple, and a
4174/// clip on a further lane is laid over the timeline rather than part of it --
4175/// closing a hole under it would drag the take beneath out of step with it.
4176fn whole_take(session: &PlaybackSession, lane: Lane, idx: usize) -> bool {
4177 let Some(clip) = session.lane_clips(lane).get(idx) else {
4178 return false;
4179 };
4180 match (lane.kind, lane.ord) {
4181 (_, 1..) => false,
4182 (LaneKind::Video, _) => true,
4183 // The sound of a take, only while the take is still there: its group is
4184 // carried by a clip on some other lane.
4185 (LaneKind::Audio, _) => session
4186 .lanes()
4187 .into_iter()
4188 .filter(|&other| other != lane)
4189 .flat_map(|other| session.lane_clips(other))
4190 .any(|o| o.link.is_some() && o.link == clip.link),
4191 }
4192}
4193
4194/// Whether a click marks this clip: the clip that was clicked always, and the
4195/// other lane's clip of the same group with it. A clip whose group has no other
4196/// half -- what a lift leaves behind -- marks only itself, which is what makes a
4197/// detached half separately deletable.
4198fn marked(
4199 here: (Lane, usize),
4200 link: Option<u32>,
4201 sel: Option<(Lane, usize)>,
4202 sel_link: Option<u32>,
4203) -> bool {
4204 sel == Some(here) || (link.is_some() && link == sel_link)
4205}
4206
4207/// Whether a clip is wide enough to be worth naming.
4208fn show_label(w: f32) -> bool {
4209 w >= LABEL_MIN_W
4210}
4211
4212/// Scales an envelope to its own loudest sample, so a quietly mastered source
4213/// still draws as a shape. The fixtures peak around an eighth of full scale, and
4214/// an eighth of a 30 px lane is a flat line -- which says "silent" about a file
4215/// that is not.
4216fn normalise(mut peaks: Vec<(f32, f32)>) -> Vec<(f32, f32)> {
4217 let loudest = peaks.iter().fold(0f32, |m, &(lo, hi)| m.max(-lo).max(hi));
4218 if loudest > 0. {
4219 for (lo, hi) in &mut peaks {
4220 *lo /= loudest;
4221 *hi /= loudest;
4222 }
4223 }
4224 peaks
4225}
4226
4227/// The min/max envelope of `peaks` over the source seconds `from..to`, as
4228/// `(x, top, bottom)` columns of a `w` x `h` box. Every point is inside that box
4229/// -- a clip's waveform cannot paint over its neighbour -- and every column is
4230/// at least a pixel tall, so silence reads as a line through the middle rather
4231/// than as a polygon with no area.
4232fn envelope(peaks: &[(f32, f32)], from: f64, to: f64, w: f32, h: f32) -> Vec<(f32, f32, f32)> {
4233 if peaks.is_empty() || w <= 0. || h <= 0. {
4234 return Vec::new();
4235 }
4236 let cols = (w / WAVE_COL).ceil().max(1.) as usize;
4237 let mid = h / 2.;
4238 (0..=cols)
4239 .map(|col| {
4240 let along = col as f64 / cols as f64;
4241 let at = from + (to - from) * along;
4242 // Casting a float to an integer saturates in Rust, so a source
4243 // second past the end of the peaks clamps rather than wrapping.
4244 let bucket = ((at * f64::from(WAVE_BPS)) as usize).min(peaks.len() - 1);
4245 let (lo, hi) = peaks[bucket];
4246 let top = (mid - hi.clamp(0., 1.) * mid).min(mid - 0.5);
4247 let bottom = (mid - lo.clamp(-1., 0.) * mid).max(mid + 0.5);
4248 (w * along as f32, top.max(0.), bottom.min(h))
4249 })
4250 .collect()
4251}
4252
4253/// One clip's audio, drawn as a filled min/max envelope inside whatever box it
4254/// is given. Peaks are the source's whole envelope; `from`/`to` are the source
4255/// seconds this clip plays, so a cut clip shows its own stretch of the file.
4256fn waveform(peaks: Arc<Vec<(f32, f32)>>, from: f64, to: f64) -> impl IntoElement {
4257 canvas(
4258 |_, _, _| (),
4259 move |bounds, _, window, _| {
4260 let (o, s) = (bounds.origin, bounds.size);
4261 let cols = envelope(&peaks, from, to, f32::from(s.width), f32::from(s.height));
4262 if cols.len() < 2 {
4263 return;
4264 }
4265 // Down the tops and back along the bottoms: one closed outline of
4266 // the whole envelope, which is one path rather than a path a column.
4267 let mut points: Vec<Point<Pixels>> = cols
4268 .iter()
4269 .map(|&(x, top, _)| point(o.x + px(x), o.y + px(top)))
4270 .collect();
4271 points.extend(
4272 cols.iter()
4273 .rev()
4274 .map(|&(x, _, bottom)| point(o.x + px(x), o.y + px(bottom))),
4275 );
4276 let mut path = PathBuilder::fill();
4277 path.add_polygon(&points, true);
4278 if let Ok(path) = path.build() {
4279 window.paint_path(path, rgb(INK_DIM));
4280 }
4281 },
4282 )
4283 .size_full()
4284}
4285
4286/// A toolbar button: its glyph, its name, and its key on hover. `id` only buys
4287/// `on_click` and the tooltip -- it is still not focusable, so the root's own
4288/// key listener keeps working after a press, and the click lands on mouse-up
4289/// inside the button (a press that slides off does nothing).
4290///
4291/// A button that would do nothing says so: dimmed, no pointer, no listener.
4292fn control(
4293 id: &'static str,
4294 glyph: Option<AnyElement>,
4295 // Not `&'static str`: the volume button's label is its state.
4296 label: impl Into<SharedString>,
4297 shortcut: String,
4298 enabled: bool,
4299 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
4300) -> impl IntoElement {
4301 let label = label.into();
4302 let tip: SharedString = format!("{label} — {shortcut}").into();
4303 div()
4304 .id(id)
4305 .flex_none()
4306 .h(px(CONTROL_H))
4307 .flex()
4308 .items_center()
4309 .gap(px(6.))
4310 .px(px(8.))
4311 .rounded(px(3.))
4312 .bg(rgb(SURFACE))
4313 .children(glyph)
4314 .child(label)
4315 .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())
4316 .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed())
4317 .when(enabled, |d| {
4318 d.cursor_pointer()
4319 .hover(|s| s.bg(rgb(HOVER)))
4320 .on_click(on_click)
4321 })
4322}
4323
4324/// The line between two groups of buttons.
4325fn separator() -> impl IntoElement {
4326 div()
4327 .flex_none()
4328 .mx(px(4.))
4329 .w(px(1.))
4330 .h(px(18.))
4331 .bg(rgb(HOVER))
4332}
4333
4334/// A tooltip is a view in gpui and nothing smaller, so this is the smallest one
4335/// that carries a line of text. It paints outside the window's element tree and
4336/// therefore owns its colours.
4337struct Tip(SharedString);
4338
4339impl Render for Tip {
4340 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
4341 div()
4342 .px(px(6.))
4343 .py(px(3.))
4344 .rounded(px(3.))
4345 .border_1()
4346 .border_color(rgb(SURFACE))
4347 .bg(rgb(CHROME))
4348 .text_color(rgb(INK))
4349 .text_size(px(12.))
4350 .child(self.0.clone())
4351 }
4352}
4353
4354/// Scissors: two blades crossed. Drawn this way and not as a split clip because
4355/// two bars is what the transport wears when it is playing -- the one glyph a
4356/// cut must never be mistaken for.
4357fn cut_glyph() -> impl IntoElement {
4358 canvas(
4359 |_, _, _| (),
4360 |bounds, _, window, _| {
4361 let (o, s) = (bounds.origin, bounds.size);
4362 let mut path = PathBuilder::stroke(px(1.5));
4363 path.move_to(point(o.x + s.width * 0.15, o.y + s.height));
4364 path.line_to(point(o.x + s.width * 0.9, o.y + s.height * 0.1));
4365 path.move_to(point(o.x + s.width * 0.85, o.y + s.height));
4366 path.line_to(point(o.x + s.width * 0.1, o.y + s.height * 0.1));
4367 if let Ok(path) = path.build() {
4368 window.paint_path(path, rgb(INK));
4369 }
4370 },
4371 )
4372 .w(px(13.))
4373 .h(px(13.))
4374}
4375
4376/// A lid over a bin.
4377fn delete_glyph() -> impl IntoElement {
4378 div()
4379 .flex()
4380 .flex_col()
4381 .items_center()
4382 .gap(px(2.))
4383 .child(div().w(px(13.)).h(px(2.)).bg(rgb(INK)))
4384 .child(div().w(px(9.)).h(px(9.)).bg(rgb(INK)))
4385}
4386
4387/// Records its parent's laid-out box: gpui hands a mouse listener the window
4388/// position only, and the ruler sits behind the panel's padding. Paints
4389/// nothing and takes no hitbox of its own, so the click still reaches the bar.
4390fn bounds_probe(into: Rc<Cell<Bounds<Pixels>>>) -> impl IntoElement {
4391 canvas(move |bounds, _, _| into.set(bounds), |_, _, _, _| ())
4392 .absolute()
4393 .size_full()
4394}
4395
4396/// Where along an element a click landed, 0..1. An element that was never
4397/// painted has no width, and reads as its start rather than as NaN.
4398fn frac_along(x: Pixels, bounds: Bounds<Pixels>) -> f32 {
4399 if bounds.size.width <= px(0.) {
4400 return 0.;
4401 }
4402 ((x - bounds.left()) / bounds.size.width).clamp(0., 1.)
4403}
4404
4405/// What a window with no file open is waiting for. Both ways in are already
4406/// built -- the whole window is the drop target and the Import chooser takes a
4407/// project as readily as media -- so this only has to say so.
4408fn empty_hint() -> impl IntoElement {
4409 div()
4410 .flex()
4411 .flex_col()
4412 .items_center()
4413 .gap(px(6.))
4414 .text_color(rgb(INK_DIM))
4415 .child("Drop a video or an .edith project here")
4416 .child(
4417 div()
4418 .text_size(px(11.))
4419 .child("or click Import in the media list"),
4420 )
4421}
4422
4423/// Two bars while playing, a triangle while paused. Drawn, so there is no icon
4424/// font and no glyph coverage to depend on.
4425fn transport_glyph(playing: bool) -> impl IntoElement {
4426 div()
4427 .flex()
4428 .items_center()
4429 .gap(px(4.))
4430 .when(playing, |d| {
4431 d.child(div().w(px(3.)).h(px(12.)).bg(rgb(INK)))
4432 .child(div().w(px(3.)).h(px(12.)).bg(rgb(INK)))
4433 })
4434 .when(!playing, |d| {
4435 d.child(
4436 canvas(
4437 |_, _, _| (),
4438 |bounds, _, window, _| {
4439 let (o, s) = (bounds.origin, bounds.size);
4440 let mut path = PathBuilder::fill();
4441 path.move_to(o);
4442 path.line_to(point(o.x + s.width, o.y + s.height / 2.));
4443 path.line_to(point(o.x, o.y + s.height));
4444 path.close();
4445 if let Ok(path) = path.build() {
4446 window.paint_path(path, rgb(INK));
4447 }
4448 },
4449 )
4450 .w(px(11.))
4451 .h(px(13.)),
4452 )
4453 })
4454}
4455
4456/// NLE timecode: `HH:MM:SS:FF`, the frame counted inside its own second.
4457fn timecode(t: f64, fps: f64) -> String {
4458 let t = t.max(0.);
4459 let secs = t as u64;
4460 let last = (fps.ceil() as u64).saturating_sub(1);
4461 let frame = ((t - secs as f64) * fps) as u64;
4462 format!(
4463 "{:02}:{:02}:{:02}:{:02}",
4464 secs / 3600,
4465 secs / 60 % 60,
4466 secs % 60,
4467 frame.min(last)
4468 )
4469}
4470
4471#[cfg(test)]
4472mod tests {
4473 use super::{
4474 ACCENT, CONTROL_H, Clip, EQ_BAR_H, EQ_GAIN_LIMIT, EXPORT_ROWS_H, FORMATS, Format,
4475 HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM, KEYS_ROW_H, KEYS_ROWS_H, KEYS_W, LABEL_H,
4476 LABEL_MIN_W, LANE_H, LANES_MAX, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W, Lane, MENU_ITEMS,
4477 MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED, SOURCE_TINTS, SURFACE,
4478 SWATCH_W, Source, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave, applicable, band_label,
4479 can_add, cancels_export, envelope, eq_fill, export_path, export_settings, format_line,
4480 frac_along, frame_at, is_bare_modifier, is_project, keymap, lane_clips, lanes_h, marked,
4481 menu_at, mp4_refusal, normalise, panel_h, project_path, push_digit, retarget, scrub_due,
4482 show_label, source_frames, source_tint, start_frac, timecode, unseen_paths, unseen_sources,
4483 whole_take, width_frac, window_title,
4484 };
4485 use super::{file_name, library_rows};
4486 use engine::PlaybackSession;
4487 use engine::scale::FitPolicy;
4488 use gpui::{Bounds, Pixels, point, px, size};
4489 use std::collections::HashMap;
4490 use std::path::{Path, PathBuf};
4491 use std::time::Duration;
4492
4493 fn asset(name: &str) -> PathBuf {
4494 Path::new(env!("CARGO_MANIFEST_DIR"))
4495 .join("../../assets")
4496 .join(name)
4497 }
4498
4499 /// A clip of `source`, `frames` long, at the top of the timeline. Only the
4500 /// two fields the library reads are meant to be looked at.
4501 fn clip(source: usize, frames: u32) -> Clip {
4502 Clip {
4503 start: 0,
4504 in_frame: 0,
4505 out_frame: frames,
4506 source,
4507 link: None,
4508 eq: None,
4509 color: None,
4510 fit: FitPolicy::default(),
4511 }
4512 }
4513
4514 /// A source entry for `path` on `stream`, as the project keeps them.
4515 fn source(path: &str, stream: usize) -> Source {
4516 Source {
4517 path: PathBuf::from(path),
4518 audio_stream: stream,
4519 }
4520 }
4521
4522 /// The whole of the library's row data comes off the clips: which files
4523 /// there are, how long each one is, and therefore which tint each row wears
4524 /// -- one index into one list, so a swatch cannot name a different file from
4525 /// the boxes it is meant to point at.
4526 #[test]
4527 fn a_rows_swatch_and_duration_come_off_the_clips_that_name_it() {
4528 // Source 0 whole, source 1 trimmed to half of what it was, source 2 on
4529 // the audio lane only (its picture was lifted), source 3 imported and
4530 // then undone -- an entry with nothing playing from it.
4531 let sources: Vec<Source> = (0..4).map(|i| source(&format!("/m/{i}.mp4"), 0)).collect();
4532 let video = [clip(0, 150), clip(1, 60)];
4533 let audio = [clip(0, 150), clip(1, 30), clip(2, 90)];
4534 for (row, frames) in [(0, 150), (1, 60), (2, 90), (3, 0)] {
4535 assert_eq!(
4536 source_frames(video.iter().chain(&audio), &sources, &sources[row].path),
4537 frames,
4538 "row {row}"
4539 );
4540 // The swatch is the clip colour, by the same index and the same
4541 // function -- what makes the panel and the lanes one association.
4542 assert_eq!(source_tint(row), SOURCE_TINTS[row % SOURCE_TINTS.len()]);
4543 }
4544 // The longest clip of a file wins, whichever lane it is in and
4545 // whatever order the lanes are read in.
4546 let one = [source("/m/0.mp4", 0)];
4547 let path = &one[0].path;
4548 assert_eq!(
4549 source_frames([clip(0, 10), clip(0, 90)].iter(), &one, path),
4550 90
4551 );
4552 assert_eq!(
4553 source_frames([clip(0, 90), clip(0, 10)].iter(), &one, path),
4554 90
4555 );
4556 assert_eq!(source_frames([].iter(), &one, path), 0);
4557 // Two audio streams of one file are two source entries and one length:
4558 // the second stream's row is placeable the moment the file is there,
4559 // before any clip names that entry.
4560 let two = [source("/m/0.mp4", 0), source("/m/0.mp4", 1)];
4561 assert_eq!(source_frames([clip(0, 90)].iter(), &two, &two[1].path), 90);
4562 }
4563
4564 fn info(
4565 index: usize,
4566 rate: u32,
4567 channels: u16,
4568 lang: Option<&str>,
4569 decodable: bool,
4570 ) -> StreamInfo {
4571 StreamInfo {
4572 index,
4573 codec: if decodable { "aac" } else { "unknown" }.into(),
4574 channels,
4575 sample_rate: rate,
4576 lang: lang.map(str::to_string),
4577 decodable,
4578 }
4579 }
4580
4581 /// A file's every audio track gets a row: the ones the timeline can take
4582 /// are placeable, the ones it cannot are listed greyed with the reason.
4583 /// Which rows exist at all is the branchy part of the panel, so it is
4584 /// planned as data and checked here rather than through the pointer.
4585 #[test]
4586 fn every_audio_stream_of_a_file_is_a_row_usable_or_not() {
4587 let multi = PathBuf::from("/m/movie.mp4");
4588 let sources = [source("/m/movie.mp4", 0)];
4589 let mut streams = HashMap::new();
4590 streams.insert(
4591 multi.clone(),
4592 vec![
4593 info(0, 44_100, 2, None, true),
4594 info(1, 44_100, 2, Some("fra"), true),
4595 info(2, 22_050, 1, Some("deu"), true),
4596 info(3, 0, 0, None, false),
4597 ],
4598 );
4599 let rows = library_rows(&sources, &streams, Some((44_100, 2)), |_| 90);
4600 assert_eq!(
4601 rows.iter().map(|r| r.stream).collect::<Vec<_>>(),
4602 [0, 1, 2, 3],
4603 "one row per audio stream, in file order"
4604 );
4605 assert!(
4606 rows.iter().all(|r| r.path == multi && r.tint == 0),
4607 "every stream of one file wears the file's own tint"
4608 );
4609 assert_eq!(rows[0].name, "movie.mp4 [audio 1]");
4610 assert_eq!(rows[1].name, "movie.mp4 [audio 2]");
4611 assert_eq!(rows[1].detail, "fra 44.1 kHz stereo");
4612 // Placeable: the one already on the timeline, and the one that matches
4613 // it. The 22 kHz mono track cannot join a 44.1 kHz stereo timeline --
4614 // one device and one copied AAC track for the whole of it -- and the
4615 // codec we cannot read cannot join anything. Both say which.
4616 assert_eq!((&rows[0].unusable, &rows[1].unusable), (&None, &None));
4617 assert_eq!(
4618 rows[2].unusable.as_deref(),
4619 Some("the timeline is 44.1 kHz stereo")
4620 );
4621 assert_eq!(rows[3].unusable.as_deref(), Some("unsupported codec"));
4622 assert_eq!(
4623 rows[3].detail, "",
4624 "a stream we cannot parse claims nothing"
4625 );
4626 // Every row is the same file, so every row is that file's length.
4627 assert!(rows.iter().all(|r| r.frames == 90));
4628
4629 // The single-stream case is exactly one row and no stream tag: no
4630 // regression for the media everything else in the world is.
4631 let plain = [source("/m/plain.mp4", 0)];
4632 let mut one = HashMap::new();
4633 one.insert(
4634 PathBuf::from("/m/plain.mp4"),
4635 vec![info(0, 44_100, 2, None, true)],
4636 );
4637 let rows = library_rows(&plain, &one, Some((44_100, 2)), |_| 90);
4638 assert_eq!(rows.len(), 1);
4639 assert_eq!(rows[0].name, "plain.mp4");
4640 assert_eq!(
4641 rows[0].detail, "",
4642 "one audio track is the row it has always been: name and length"
4643 );
4644 // ...as is a silent file, and a file not probed yet.
4645 let mut silent = HashMap::new();
4646 silent.insert(PathBuf::from("/m/plain.mp4"), Vec::new());
4647 for probe in [silent, HashMap::new()] {
4648 let rows = library_rows(&plain, &probe, None, |_| 90);
4649 assert_eq!(rows.len(), 1);
4650 assert_eq!(rows[0].name, "plain.mp4");
4651 assert_eq!(rows[0].detail, "");
4652 }
4653
4654 // A second stream *placed* on the timeline is a source entry of its
4655 // own: it keeps its row, no duplicate appears for it, and the rows of
4656 // one file stay together whatever order the entries came in.
4657 let placed = [
4658 source("/m/movie.mp4", 0),
4659 source("/m/other.mp4", 0),
4660 source("/m/movie.mp4", 2),
4661 ];
4662 streams.insert(
4663 PathBuf::from("/m/other.mp4"),
4664 vec![info(0, 44_100, 2, None, true)],
4665 );
4666 let rows = library_rows(&placed, &streams, Some((44_100, 2)), |_| 90);
4667 assert_eq!(
4668 rows.iter()
4669 .map(|r| (file_name(&r.path), r.stream))
4670 .collect::<Vec<_>>(),
4671 [
4672 ("movie.mp4".to_string(), 0),
4673 ("other.mp4".to_string(), 0),
4674 ("movie.mp4".to_string(), 2),
4675 ("movie.mp4".to_string(), 1),
4676 ("movie.mp4".to_string(), 3),
4677 ]
4678 );
4679 assert!(
4680 rows[2].unusable.is_none(),
4681 "a stream already on the timeline is playing, whatever a probe says"
4682 );
4683 assert_eq!(rows[1].tint, 1, "the other file is the other tint");
4684 }
4685
4686 /// What the clip menu offers, and where it hangs. The two items that act on
4687 /// the playhead rather than on the clicked clip are the ones that can be
4688 /// inapplicable, and a menu at the edge of the window has to come back
4689 /// inside it or its last item cannot be clicked at all.
4690 #[test]
4691 fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() {
4692 use keymap::{ActionId, Keymap};
4693 // Frames 30..90 of the timeline, taken from the head of its source.
4694 let clip = Clip {
4695 start: 30,
4696 in_frame: 0,
4697 out_frame: 60,
4698 source: 0,
4699 link: None,
4700 eq: None,
4701 color: None,
4702 fit: FitPolicy::default(),
4703 };
4704 assert_eq!(clip.end(), 90);
4705 // Cut splits from inside only: neither edge has anything to split off.
4706 let a1 = Lane::A1;
4707 let v1 = Lane::V1;
4708 assert!(applicable(&clip, v1, ActionId::Cut, 31));
4709 assert!(applicable(&clip, v1, ActionId::Cut, 89));
4710 assert!(!applicable(&clip, v1, ActionId::Cut, 30));
4711 assert!(!applicable(&clip, v1, ActionId::Cut, 90));
4712 assert!(!applicable(&clip, v1, ActionId::Cut, 200));
4713 // Regroup is the other way round: only where this clip meets another.
4714 assert!(applicable(&clip, v1, ActionId::Regroup, 30));
4715 assert!(applicable(&clip, v1, ActionId::Regroup, 90));
4716 assert!(!applicable(&clip, v1, ActionId::Regroup, 60));
4717 // The equalizer is the one item the *lane* decides: it filters samples,
4718 // and a video clip has none of its own. Never the playhead's business.
4719 assert!(applicable(&clip, a1, ActionId::Equalizer, 0));
4720 assert!(applicable(&clip, a1, ActionId::Equalizer, 60));
4721 assert!(!applicable(&clip, v1, ActionId::Equalizer, 60));
4722 // The rest act on the clip that was clicked, so they always mean
4723 // something -- the engine words its own refusals.
4724 for action in [ActionId::Delete, ActionId::Lift, ActionId::ToggleMute] {
4725 assert!(applicable(&clip, v1, action, 0));
4726 assert!(applicable(&clip, a1, action, 60));
4727 }
4728 // Except the grade, which is a picture setting: offered on a video
4729 // clip wherever the playhead is, dimmed on a waveform.
4730 assert!(applicable(&clip, v1, ActionId::Color, 0));
4731 assert!(!applicable(&clip, a1, ActionId::Color, 60));
4732 // The playhead frame is the engine's own rule, boundary included.
4733 assert_eq!(frame_at(1.0, 30.), 30);
4734 assert_eq!(frame_at(0.0, 30.), 0);
4735 assert_eq!(frame_at(-1.0, 30.), 0);
4736 // Where it hangs: at the pointer when it fits, back inside when not.
4737 let viewport = size(px(800.), px(400.));
4738 assert_eq!(menu_at(point(px(10.), px(10.)), viewport, 150.), (10., 10.));
4739 assert_eq!(
4740 menu_at(point(px(700.), px(380.)), viewport, 150.),
4741 (800. - MENU_W, 250.)
4742 );
4743 // A window smaller than the menu loses its bottom, never its top.
4744 assert_eq!(
4745 menu_at(point(px(90.), px(40.)), size(px(100.), px(50.)), 150.),
4746 (0., 0.)
4747 );
4748 // Every item is an action the registry knows, so the menu and the keys
4749 // menu say the same thing about it -- and none of them is unreachable
4750 // by keyboard, which is what makes the hint column worth drawing.
4751 let keymap = Keymap::defaults();
4752 for action in MENU_ITEMS {
4753 assert!(ActionId::ALL.contains(&action), "{action:?} is not listed");
4754 assert_ne!(keymap.display(action), "unbound", "{action:?}");
4755 }
4756 }
4757
4758 /// The refusal path, end to end against the real files: an incompatible
4759 /// import changes nothing, and the library mirrors `sources()` 1:1, so a
4760 /// refused file cannot leave a row behind.
4761 #[test]
4762 fn a_refused_import_leaves_no_row_and_an_accepted_one_is_whole() {
4763 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
4764 // Silent like the engine suite: this opens the real device.
4765 session.set_gain(0.0);
4766 assert_eq!(session.sources().len(), 1);
4767 // 640x360 would join now (the project canvas places it); this file is
4768 // also silent, and a silent file cannot join a timeline with sound.
4769 let refusal = session
4770 .import(&asset("test_mismatch.mp4"))
4771 .expect_err("a silent file must not join a timeline with audio")
4772 .to_string();
4773 assert!(refusal.contains("audio"), "refusal must name it: {refusal}");
4774 assert_eq!(session.sources().len(), 1, "a refusal added a row");
4775 // An accepted one does add a row, and it reads as the whole file: 4 s
4776 // at 30 fps, exactly what was appended.
4777 session.import(&asset("test_av2.mp4")).expect("av2 matches");
4778 assert_eq!(session.sources().len(), 2);
4779 let second = session.sources()[1].path.clone();
4780 assert_eq!(
4781 source_frames(lane_clips(&session), session.sources(), &second),
4782 120
4783 );
4784 assert_eq!(timecode(120. / 30., 30.), "00:00:04:00");
4785 }
4786
4787 /// What the Add button and a dropped row both do, minus the pointer: the
4788 /// clip [`Player::insert_source`] builds, put in where the playhead is. One
4789 /// call, so what a drop does cannot drift from what the button does.
4790 #[test]
4791 fn adding_a_row_drops_the_whole_source_in_at_the_playhead() {
4792 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
4793 session.set_gain(0.0);
4794 session.import(&asset("test_av2.mp4")).expect("av2 matches");
4795 assert_eq!(session.timeline_duration(), 9.0);
4796 // Two seconds in, which is inside the first take: the insert splits it.
4797 session.seek(2.0);
4798 let second = session.sources()[1].path.clone();
4799 let frames = source_frames(lane_clips(&session), session.sources(), &second);
4800 // Through the engine door `insert_source` uses, with the row's own
4801 // stream: the button, the drop and this are one call.
4802 assert!(
4803 session
4804 .place_stream_at(2.0, &second, 0, frames, None)
4805 .expect("av2 is already on the timeline")
4806 );
4807 // The whole of source 1 went in and nothing was painted over: the
4808 // timeline is longer by exactly that file.
4809 assert_eq!(session.timeline_duration(), 13.0);
4810 let (video, audio) = (session.lane_clips(Lane::V1), session.lane_clips(Lane::A1));
4811 // One take, not a video clip with no sound under it: both lanes hold
4812 // the same clip at the same place, in the same group.
4813 let at = |lane: &[Clip]| {
4814 *lane
4815 .iter()
4816 .find(|c| c.start == 60)
4817 .expect("inserted at 2 s")
4818 };
4819 assert_eq!(at(video), at(audio));
4820 assert_eq!(at(video).source, 1);
4821 assert_eq!(at(video).len(), frames);
4822 assert!(at(video).link.is_some());
4823 assert_eq!(video.len(), audio.len());
4824
4825 // The same door with a *second audio stream* of a file already there:
4826 // a new source entry, the same picture, and the row that was dragged
4827 // is what plays. This is the whole user-facing point of the slice.
4828 let mut session =
4829 PlaybackSession::open(asset("test_multilang.mp4")).expect("open the fixture");
4830 session.set_gain(0.0);
4831 let path = session.sources()[0].path.clone();
4832 let frames = source_frames(lane_clips(&session), session.sources(), &path);
4833 let end = session.timeline_duration();
4834 assert!(
4835 session
4836 .place_stream_at(end, &path, 1, frames, None)
4837 .expect("the French track shares the timeline's parameters")
4838 );
4839 assert_eq!(session.sources()[1].audio_stream, 1);
4840 assert_eq!(session.timeline_duration(), end * 2.0);
4841 // Both rows are the same file, so both rows are that file's length --
4842 // the second one before any clip of its own existed.
4843 assert_eq!(
4844 source_frames(lane_clips(&session), session.sources(), &path),
4845 frames
4846 );
4847 }
4848
4849 /// The add-a-track path end to end through the doors the buttons and the
4850 /// drop use: `+ V` adds a row, a library row let go over it lands there and
4851 /// nowhere else, Delete on it leaves the lanes under it where they are, and
4852 /// undo takes the whole thing back one step at a time.
4853 #[test]
4854 fn a_track_can_be_added_dropped_on_edited_and_taken_back() {
4855 use engine::project::LaneKind;
4856
4857 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
4858 session.set_gain(0.0);
4859 assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1]);
4860 // What the `+ V` button asks for, and what the row it draws is called.
4861 let v2 = session.add_lane(LaneKind::Video);
4862 assert_eq!(v2.label(), "V2");
4863 assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1, v2]);
4864 assert!(session.lane_clips(v2).is_empty());
4865 // A library row let go over that row: the same door the Add button
4866 // uses, told which lane it was let go over.
4867 let path = session.sources()[0].path.clone();
4868 let frames = source_frames(lane_clips(&session), session.sources(), &path);
4869 assert!(
4870 session
4871 .place_stream_at(1.0, &path, 0, frames, Some(v2))
4872 .expect("its own file is on this timeline")
4873 );
4874 assert_eq!(session.lane_clips(v2).len(), 1, "the drop landed on V2");
4875 assert_eq!(session.lane_clips(v2)[0].start, 30, "at the playhead");
4876 // And nowhere else: the first pair is exactly as it was, one take each.
4877 assert_eq!(session.lane_clips(Lane::V1).len(), 1);
4878 assert_eq!(session.lane_clips(Lane::A1).len(), 1);
4879 // Delete on the layer is a lift: it is laid over the timeline, so
4880 // closing a hole under it would drag the take beneath out of step with
4881 // it. The take on the first pair is still a take, and still ripples.
4882 assert!(!whole_take(&session, v2, 0));
4883 assert!(whole_take(&session, Lane::V1, 0));
4884 assert!(whole_take(&session, Lane::A1, 0));
4885 assert!(session.lift_clip(v2, 0));
4886 assert!(session.lane_clips(v2).is_empty());
4887 assert_eq!(session.lane_clips(Lane::V1).len(), 1, "V1 stayed put");
4888
4889 // A second audio lane carrying sound is what an mp4 export cannot
4890 // write, so the card greys that row before a destination is picked.
4891 assert_eq!(mp4_refusal(&session), None);
4892 let a2 = session.add_lane(LaneKind::Audio);
4893 assert_eq!(a2.label(), "A2");
4894 assert_eq!(mp4_refusal(&session), None, "an empty lane carries nothing");
4895 assert!(
4896 session
4897 .place_stream_at(0.0, &path, 0, frames, Some(a2))
4898 .expect("its own file is on this timeline")
4899 );
4900 assert_eq!(
4901 mp4_refusal(&session).as_deref(),
4902 Some("2 audio lanes — an mp4 copies one")
4903 );
4904
4905 // Undo, one edit at a time and backwards: the drop on A2, the lane A2
4906 // itself, the lift, the drop on V2, and last the lane V2 -- an added
4907 // track is one step like every other edit.
4908 for lanes in [4, 3, 3, 3, 2] {
4909 assert!(session.undo());
4910 assert_eq!(session.lanes().len(), lanes);
4911 }
4912 assert_eq!(session.lanes(), vec![Lane::V1, Lane::A1]);
4913 assert_eq!(session.lane_clips(Lane::V1).len(), 1);
4914 assert_eq!(mp4_refusal(&session), None);
4915 }
4916
4917 #[test]
4918 fn a_source_is_only_ever_asked_for_its_peaks_once() {
4919 let (a, b) = (asset("test_av.mp4"), asset("test_av2.mp4"));
4920 // Two files, and two streams of the first: three envelopes, because
4921 // one file's two audio tracks are two different waveforms.
4922 let sources = [
4923 Source {
4924 path: a.clone(),
4925 audio_stream: 0,
4926 },
4927 Source {
4928 path: a.clone(),
4929 audio_stream: 1,
4930 },
4931 Source {
4932 path: b.clone(),
4933 audio_stream: 0,
4934 },
4935 ];
4936 let keys = |s: &[Source]| {
4937 s.iter()
4938 .map(|s| (s.path.clone(), s.audio_stream))
4939 .collect::<Vec<_>>()
4940 };
4941 let mut waves: HashMap<(PathBuf, usize), Wave> = HashMap::new();
4942 assert_eq!(unseen_sources(&sources, &waves), keys(&sources));
4943 // The entry goes in when the decode *starts*, so the sixty repaints a
4944 // second that happen while it runs must not start it again -- which is
4945 // what this asserts about a key whose value is not an answer yet.
4946 waves.insert((a.clone(), 0), Wave::Loading);
4947 assert_eq!(
4948 unseen_sources(&sources, &waves),
4949 keys(&sources[1..]),
4950 "the file's other stream is a key of its own"
4951 );
4952 // A file with no audio is an answer like any other: never re-asked.
4953 waves.insert((a, 1), Wave::Silent);
4954 waves.insert((b.clone(), 0), Wave::Silent);
4955 assert!(unseen_sources(&sources, &waves).is_empty());
4956 // The stream probe is per *file*: the two entries of `a` ask once.
4957 let mut streams: HashMap<PathBuf, Vec<StreamInfo>> = HashMap::new();
4958 assert_eq!(
4959 unseen_paths(&sources, &streams),
4960 vec![asset("test_av.mp4"), b]
4961 );
4962 streams.insert(asset("test_av.mp4"), Vec::new());
4963 assert_eq!(unseen_paths(&sources, &streams).len(), 1);
4964 }
4965
4966 #[test]
4967 fn the_add_button_is_dead_unless_it_would_do_something() {
4968 let picked = (PathBuf::from("/m/0.mp4"), 0);
4969 assert!(can_add(Some(&picked), true, false));
4970 // Nothing picked, nothing to put it on, or an export reading the very
4971 // edit list this would change.
4972 assert!(!can_add(None, true, false));
4973 assert!(!can_add(Some(&picked), false, false));
4974 assert!(!can_add(Some(&picked), true, true));
4975 }
4976
4977 #[test]
4978 fn the_media_column_never_takes_the_picture_over() {
4979 for window in [360., 640., 1280., 1920., 3840.] {
4980 let w = super::library_w(window);
4981 // The whole point of the budget: the picture keeps the majority of
4982 // the row at every size a window can be.
4983 assert!(w <= window / 3., "{window}px window gave the list {w}px");
4984 assert!(w >= LIBRARY_MIN_W.min(window / 3.), "{window}px: {w}px");
4985 assert!(w <= LIBRARY_MAX_W);
4986 }
4987 // It yields: a narrower window gives the list less, never the same.
4988 assert!(super::library_w(640.) < super::library_w(1280.));
4989 // Rows are clickable, so WCAG 2.5.8 binds them like every other target,
4990 // and a name over a timecode has to fit inside one.
4991 assert!(ROW_H >= HIT_MIN);
4992 assert!(SWATCH_W < LIBRARY_MIN_W);
4993 }
4994
4995 #[test]
4996 fn the_window_is_named_after_the_program_and_what_is_open() {
4997 assert_eq!(window_title("test_av.mp4"), "test_av.mp4 — edith");
4998 // An empty window is the program, not "no file open — edith".
4999 assert_eq!(window_title(NO_FILE), "edith");
5000 }
5001
5002 #[test]
5003 fn frac_along_measures_from_the_elements_own_left_edge() {
5004 // A ruler inset by the panel's 12 px padding: window x is not bar x.
5005 let bar: Bounds<Pixels> = Bounds {
5006 origin: point(px(12.), px(400.)),
5007 size: size(px(200.), px(6.)),
5008 };
5009 assert_eq!(frac_along(px(12.), bar), 0.);
5010 assert_eq!(frac_along(px(112.), bar), 0.5);
5011 assert_eq!(frac_along(px(212.), bar), 1.);
5012 // Outside the bar (a click that slid off) clamps, never extrapolates.
5013 assert_eq!(frac_along(px(0.), bar), 0.);
5014 assert_eq!(frac_along(px(9999.), bar), 1.);
5015 // Never painted: no division by zero, no NaN reaching seek().
5016 assert_eq!(frac_along(px(50.), Bounds::default()), 0.);
5017 }
5018
5019 #[test]
5020 fn timecode_counts_frames_inside_the_second() {
5021 assert_eq!(timecode(0., 30.), "00:00:00:00");
5022 assert_eq!(timecode(-1., 30.), "00:00:00:00"); // clamped, never negative
5023 assert_eq!(timecode(4.9667, 30.), "00:00:04:29"); // last frame of a 5 s clip
5024 assert_eq!(timecode(5., 30.), "00:00:05:00");
5025 assert_eq!(timecode(3661.5, 30.), "01:01:01:15");
5026 // Rounding must not spill into a frame the second does not have.
5027 assert_eq!(timecode(1. - f64::EPSILON, 30.), "00:00:00:29");
5028 assert_eq!(timecode(0.999, 29.97), "00:00:00:29");
5029 }
5030
5031 #[test]
5032 fn scrub_seeks_only_on_a_new_frame_and_only_every_100ms() {
5033 let (slow, fast) = (Duration::from_millis(100), Duration::from_millis(99));
5034 // Both halves must hold: a moved pointer that has not crossed a frame
5035 // boundary would reopen the decoder for the same picture.
5036 assert!(scrub_due(31, 30, slow));
5037 assert!(!scrub_due(30, 30, slow));
5038 assert!(!scrub_due(31, 30, fast));
5039 assert!(!scrub_due(30, 30, fast));
5040 // Exactly at the gap counts, and a long stall never blocks.
5041 assert!(scrub_due(1, 0, Duration::from_secs(9)));
5042 }
5043
5044 #[test]
5045 fn export_lands_beside_the_source_and_never_on_it() {
5046 // The whole point: the export of an .mp4 is never that .mp4.
5047 assert_eq!(
5048 export_path("assets/test_baseline.mp4"),
5049 std::path::Path::new("assets/test_baseline.export.mp4")
5050 );
5051 // A second export of an export is still not its own source.
5052 assert_eq!(
5053 export_path("a.export.mp4"),
5054 std::path::Path::new("a.export.export.mp4")
5055 );
5056 // Extensionless and dotted-directory names keep the directory intact.
5057 assert_eq!(export_path("clip"), std::path::Path::new("clip.export.mp4"));
5058 assert_eq!(
5059 export_path("/v.1/clip.MP4"),
5060 std::path::Path::new("/v.1/clip.export.mp4")
5061 );
5062 }
5063
5064 #[test]
5065 fn the_first_save_lands_beside_the_media() {
5066 assert_eq!(
5067 project_path("assets/test_av.mp4"),
5068 std::path::Path::new("assets/test_av.edith")
5069 );
5070 // The same rule an export follows: only the last extension moves.
5071 assert_eq!(
5072 project_path("a.export.mp4"),
5073 std::path::Path::new("a.export.edith")
5074 );
5075 assert_eq!(project_path("clip"), std::path::Path::new("clip.edith"));
5076 // Saving a loaded project writes the file it came from, not a second.
5077 assert_eq!(project_path("a.edith"), std::path::Path::new("a.edith"));
5078 }
5079
5080 #[test]
5081 fn only_an_exact_edith_extension_is_a_project() {
5082 let p = std::path::Path::new;
5083 assert!(is_project(p("a.edith")));
5084 // A dotted directory must not decide it -- the file name does.
5085 assert!(is_project(p("/v.mp4/a.edith")));
5086 assert!(!is_project(p("a.mp4")));
5087 assert!(!is_project(p("/v.edith/a.mp4")));
5088 // Exactly what `save_project` writes: a dropped `.EDITH` goes to the
5089 // demuxer and is refused there, not parsed as a project.
5090 assert!(!is_project(p("a.EDITH")));
5091 // An extension, never a bare name.
5092 assert!(!is_project(p("edith")));
5093 assert!(!is_project(p("a.edith.mp4")));
5094 }
5095
5096 /// The keys menu is the registry drawn, so a *bindable* stroke cannot go
5097 /// missing from it by construction. The strokes the modal cards read for
5098 /// themselves are the ones that could: this reads the key handler's own
5099 /// source and fails on any key it answers to that the menu never mentions.
5100 #[test]
5101 fn no_stroke_is_missing_from_the_keys_menu() {
5102 use keymap::{ActionId, Keymap};
5103 // Everything above the test module -- the handler, and the helpers it
5104 // asks. The tests below compare keys too, and are not shortcuts.
5105 let handler = include_str!("main.rs")
5106 .split("#[cfg(test)]")
5107 .next()
5108 .unwrap();
5109 let keymap = Keymap::defaults();
5110 let listed = |key: &str| {
5111 let pretty = keymap::Chord {
5112 key: key.to_string(),
5113 ctrl: false,
5114 }
5115 .pretty();
5116 keymap.lookup(key, false).is_some() || keymap::FIXED.iter().any(|f| f.chord == pretty)
5117 };
5118 let mut compared = 0;
5119 for (at, needle) in handler.match_indices("key == ") {
5120 let rest = &handler[at + needle.len()..];
5121 let key = match rest.strip_prefix('"') {
5122 Some(literal) => {
5123 literal[..literal.find('"').expect("unterminated key")].to_string()
5124 }
5125 // A named constant: the escape the cards get out by.
5126 None if rest.starts_with("ESCAPE") => super::ESCAPE.to_string(),
5127 None => panic!("a key compared against something this cannot read: {rest:.20}"),
5128 };
5129 assert!(
5130 listed(&key),
5131 "the handler answers to {key:?} and the keys menu never says so"
5132 );
5133 compared += 1;
5134 }
5135 // The scan is only a guard while it still finds the comparisons: a
5136 // rewrite that spells them differently must come back here.
5137 assert!(
5138 compared >= 4,
5139 "the key comparisons moved; this scan is blind"
5140 );
5141 // The one branch that is not a comparison -- any digit is a bitrate.
5142 assert!(handler.contains("key.parse::<u32>()"));
5143 assert!(keymap::FIXED.iter().any(|f| f.chord == "0–9"));
5144 // And every entry of both halves lands under a heading the menu draws.
5145 for action in ActionId::ALL {
5146 assert!(keymap::Category::ALL.contains(&action.category()));
5147 }
5148 for fixed in &keymap::FIXED {
5149 assert!(keymap::Category::ALL.contains(&fixed.category));
5150 }
5151 }
5152
5153 #[test]
5154 fn clip_boxes_split_the_lane_by_duration() {
5155 // 1 s + 3 s of a 4 s timeline: a quarter and three quarters.
5156 assert_eq!(width_frac(1., 4.), 0.25);
5157 assert_eq!(width_frac(3., 4.), 0.75);
5158 assert_eq!(width_frac(4., 4.), 1.);
5159 // A timeline with no length must not hand gpui a NaN width.
5160 assert_eq!(width_frac(0., 0.), 1.);
5161 }
5162
5163 #[test]
5164 fn escape_gets_out_of_an_export_whatever_is_held_with_it() {
5165 use keymap::ActionId;
5166 // The regression this guards: looking the stroke up in the keymap made
5167 // ctrl+escape mean nothing, and an export that a modifier could trap
5168 // the user inside of is worse than an unbound chord.
5169 assert!(cancels_export("escape", None));
5170 assert!(cancels_export("escape", Some(ActionId::CancelExport)));
5171 // A rebound cancel works as well -- it adds a way out, never replaces
5172 // the one that always worked.
5173 assert!(cancels_export("q", Some(ActionId::CancelExport)));
5174 // Nothing else does, whatever it means outside an export.
5175 assert!(!cancels_export("e", Some(ActionId::Export)));
5176 assert!(!cancels_export("space", Some(ActionId::Play)));
5177 assert!(!cancels_export("q", None));
5178 }
5179
5180 #[test]
5181 fn a_capture_waits_through_a_lone_modifier() {
5182 // gpui delivers these on their own; taking one as a binding would make
5183 // the action fire on the way to every chord that uses it.
5184 for key in [
5185 "control", "shift", "alt", "super", "platform", "function", "fn", "meta", "command",
5186 ] {
5187 assert!(is_bare_modifier(key), "{key}");
5188 }
5189 // Everything a binding is actually made of, escape included -- the
5190 // capture branch turns that one away itself.
5191 for key in ["c", "x", "space", "escape", "delete", "f1", "z"] {
5192 assert!(!is_bare_modifier(key), "{key}");
5193 }
5194 }
5195
5196 #[test]
5197 fn the_keybindings_card_fits_the_smallest_window() {
5198 // The row list is capped and scrolls, so the card's height no longer
5199 // depends on how many actions there are: a title, a status line and the
5200 // viewport, inside the 640x360 the rest of the layout is sized for.
5201 let title = 17.; // 13 px text on its own line
5202 let status = 28.; // 11 px text, two lines: a refusal wraps
5203 let gaps = 3. * 2.;
5204 let padding = 24.;
5205 assert!(
5206 title + status + KEYS_ROWS_H + gaps + padding <= 360.,
5207 "card too tall"
5208 );
5209 // The cap is only honest if it is the taller list that scrolls, not the
5210 // card that grows: every action must be reachable by scrolling, and
5211 // enough of them visible that the list reads as a list.
5212 assert!(
5213 KEYS_ROWS_H / KEYS_ROW_H >= 8.,
5214 "too few rows visible to scan"
5215 );
5216 assert!(KEYS_W <= 640., "card too wide");
5217 // The rows are clickable, so WCAG 2.5.8 binds them like every other
5218 // target in this window.
5219 assert!(KEYS_ROW_H >= HIT_MIN);
5220 }
5221
5222 /// The equalizer card: what its bars paint, and that it fits the window the
5223 /// other two cards are sized for. The bar is the one bit of geometry in the
5224 /// card, and it is signed -- a fill that grew from the left would read a cut
5225 /// as an empty control -- so it is checked against the reading of a click,
5226 /// which is the same mapping backwards ([`Player::drag_band`]).
5227 #[test]
5228 fn the_equalizer_bar_grows_out_of_flat_and_the_card_fits_the_smallest_window() {
5229 use engine::eq::{Band, BandKind, EqParams};
5230 // Flat is the middle and paints nothing: a band nobody has touched must
5231 // not look like one that has been turned down.
5232 assert_eq!(eq_fill(0.), (0.5, 0.));
5233 // Full boost fills the right half, full cut the left one.
5234 assert_eq!(eq_fill(EQ_GAIN_LIMIT), (0.5, 0.5));
5235 assert_eq!(eq_fill(-EQ_GAIN_LIMIT), (0., 0.5));
5236 assert_eq!(eq_fill(EQ_GAIN_LIMIT / 2.), (0.5, 0.25));
5237 assert_eq!(eq_fill(-EQ_GAIN_LIMIT / 2.), (0.25, 0.25));
5238 // A file may carry a gain past what this card offers (the format writes
5239 // any finite value): it paints at the end, never off the track.
5240 assert_eq!(eq_fill(400.), (0.5, 0.5));
5241 assert_eq!(eq_fill(-400.), (0., 0.5));
5242
5243 // A click reads back as the gain that paints where it landed, which is
5244 // what makes a drag land where the pointer is.
5245 for gain in [-12., -6., 0., 6., 12.] {
5246 let (left, width) = eq_fill(gain);
5247 let at = if gain >= 0. { left + width } else { left };
5248 let read = (at * 2. - 1.) * EQ_GAIN_LIMIT;
5249 assert!((read - gain).abs() < 1e-4, "{gain} read back as {read}");
5250 }
5251
5252 // Every default band says what it is, and a shelf says so: "12 kHz"
5253 // alone would not tell anyone it tilts the whole top octave.
5254 let labels: Vec<String> = EqParams::default_layout()
5255 .bands
5256 .iter()
5257 .map(band_label)
5258 .collect();
5259 assert_eq!(
5260 labels,
5261 [
5262 "80 Hz low shelf",
5263 "250 Hz",
5264 "1 kHz",
5265 "4 kHz",
5266 "12 kHz high shelf"
5267 ]
5268 );
5269 assert_eq!(
5270 band_label(&Band {
5271 freq_hz: 2600.,
5272 gain_db: 0.,
5273 q: 1.,
5274 kind: BandKind::Peak
5275 }),
5276 "3 kHz",
5277 "rounded, because a band label is not a measurement"
5278 );
5279
5280 // The same shape as the other two cards, so it fits where they do.
5281 let (title, status, gaps, padding) = (17., 28., 3. * 2., 24.);
5282 assert!(
5283 title + status + EXPORT_ROWS_H + gaps + padding + CONTROL_H <= 360.,
5284 "card too tall"
5285 );
5286 assert!(KEYS_W <= 640., "card too wide");
5287 // The rows are dragged, so WCAG 2.5.8 binds them like every other
5288 // target in this window -- the 6 px bar is inside a full-height row.
5289 assert!(KEYS_ROW_H >= HIT_MIN);
5290 assert!(EQ_BAR_H < KEYS_ROW_H);
5291 }
5292
5293 /// Mute and level are one control with two states, and the whole point is
5294 /// that mute keeps the level: the user gets back what they had, not 100%.
5295 #[test]
5296 fn muting_keeps_the_level_it_comes_back_to() {
5297 let mut volume = Volume::default();
5298 assert_eq!(volume.gain(), 1.0);
5299 assert_eq!(volume.label(), "Vol 100%");
5300
5301 // Four presses down, then muted: the gain is silence but the level is
5302 // still what it was, and the button keeps saying so.
5303 for _ in 0..4 {
5304 volume.step(false);
5305 }
5306 assert_eq!(volume.gain(), 0.8);
5307 volume.muted = true;
5308 assert_eq!(volume.gain(), 0.0);
5309 assert_eq!(volume.label(), "Muted 80%");
5310
5311 // Turning it down while muted stays muted -- the one thing a mute
5312 // button must never do is get louder because you asked for quieter.
5313 volume.step(false);
5314 assert_eq!(volume.gain(), 0.0);
5315 assert!(volume.muted);
5316
5317 // Unmute returns to the level, including the step taken while silent.
5318 volume.muted = false;
5319 assert_eq!(volume.gain(), 0.75);
5320 }
5321
5322 /// Both ends hold under a key held down: the ABI only accepts `0.0..=1.0`,
5323 /// and a wrapped step count would hand it something else.
5324 #[test]
5325 fn the_volume_stops_at_both_ends() {
5326 let mut volume = Volume::default();
5327 for _ in 0..40 {
5328 volume.step(true);
5329 }
5330 assert_eq!(volume.gain(), 1.0);
5331 assert_eq!(volume.steps, Volume::MAX_STEPS);
5332
5333 for _ in 0..40 {
5334 volume.step(false);
5335 }
5336 assert_eq!(volume.gain(), 0.0);
5337 assert_eq!(volume.label(), "Vol 0%");
5338
5339 // Silent by the level rather than by the flag is still not muted: the
5340 // button says which, because only one of them survives a step up.
5341 assert!(!volume.muted);
5342 volume.step(true);
5343 assert_eq!(volume.gain(), 0.05);
5344 }
5345
5346 #[test]
5347 fn a_quality_row_is_the_bitrate_it_promises() {
5348 // Auto is the one row that says nothing: the exporter derives it, and
5349 // a number typed against the custom row must not leak into it.
5350 let mp4 = Format::Mp4;
5351 assert_eq!(export_settings(Quality::Auto, 7, mp4).bitrate, None);
5352 assert_eq!(
5353 export_settings(Quality::Low, 0, mp4).bitrate,
5354 Some(2_000_000)
5355 );
5356 assert_eq!(
5357 export_settings(Quality::Medium, 0, mp4).bitrate,
5358 Some(6_000_000)
5359 );
5360 assert_eq!(
5361 export_settings(Quality::High, 0, mp4).bitrate,
5362 Some(12_000_000)
5363 );
5364 // Megabits as typed, and as the row says it back.
5365 assert_eq!(
5366 export_settings(Quality::Custom, 7, mp4).bitrate,
5367 Some(7_000_000)
5368 );
5369 assert_eq!(Quality::Low.detail(0), "2 Mbps");
5370 // The picked format travels, or the card's rows would be a picture of a
5371 // choice the engine never hears about.
5372 for format in [Format::Mp4, Format::Wav, Format::Flac] {
5373 assert_eq!(export_settings(Quality::Auto, 0, format).format, format);
5374 }
5375 // Every fixed row sits inside the engine's clamp (export.rs:290), so no
5376 // row can promise a bitrate the exporter silently changes.
5377 for quality in Quality::ALL {
5378 let settings = export_settings(quality, 7, mp4);
5379 if let Some(bitrate) = settings.bitrate {
5380 assert!(
5381 (1_000_000..=20_000_000).contains(&bitrate),
5382 "{quality:?} outside the engine clamp"
5383 );
5384 }
5385 // The software pin is the environment's to set, never a row's.
5386 assert!(!settings.force_sw);
5387 }
5388 }
5389
5390 #[test]
5391 fn a_typed_bitrate_stops_at_two_digits() {
5392 assert_eq!(push_digit(0, 8), 8);
5393 assert_eq!(push_digit(1, 2), 12);
5394 // A third digit is refused whole: the ceiling is 20 Mbps, so it can
5395 // only be a mistake, and dropping it silently would leave the card
5396 // showing a number nobody typed.
5397 assert_eq!(push_digit(12, 3), 12);
5398 assert_eq!(push_digit(99, 9), 99);
5399 // Never past what the clamp can take back to a real bitrate.
5400 assert!(u64::from(push_digit(99, 9)) * 1_000_000 < u64::from(u32::MAX));
5401 }
5402
5403 #[test]
5404 fn the_export_card_fits_the_smallest_window() {
5405 // Same 640x360 floor the keybindings card is measured against: the
5406 // capped row list, the fixed-format line and the confirm button, under
5407 // a title and a status line.
5408 let title = 17.;
5409 let status = 28.;
5410 let fixed = 17.;
5411 let gaps = 4. * 2.;
5412 let padding = 24.;
5413 assert!(
5414 title + status + EXPORT_ROWS_H + fixed + CONTROL_H + 4. + gaps + padding <= 360.,
5415 "card too tall"
5416 );
5417 // The cap is only honest if enough of the list is on screen to read as
5418 // one -- the destination and the first formats, not a slot.
5419 assert!(EXPORT_ROWS_H / KEYS_ROW_H >= 6.);
5420 // Clickable rows, so WCAG 2.5.8 binds them as it binds the panel's.
5421 assert!(KEYS_ROW_H >= HIT_MIN);
5422 assert!(CONTROL_H >= HIT_MIN);
5423 }
5424
5425 #[test]
5426 fn every_format_row_is_offered_or_says_why_not() {
5427 // The three this program can write are rows that pick, each named after
5428 // its own extension so a destination can never disagree with its bytes.
5429 let offered: Vec<Format> = FORMATS.iter().filter_map(|&(f, ..)| f).collect();
5430 assert_eq!(offered, vec![Format::Mp4, Format::Wav, Format::Flac]);
5431 for (format, label, _) in FORMATS {
5432 match format {
5433 Some(format) => assert_eq!(format.ext(), label.to_lowercase()),
5434 // A refused format is a row with a reason, never a hidden one:
5435 // an empty detail column would read as an oversight.
5436 None => assert!(!label.is_empty()),
5437 }
5438 }
5439 for (format, label, detail) in FORMATS {
5440 assert!(!detail.is_empty(), "{label} says nothing");
5441 // Only mp4 carries the picture, so only mp4 leaves the bitrate rows
5442 // live -- the card dims them off exactly this.
5443 assert_eq!(
5444 format.is_some_and(Format::has_video),
5445 format == Some(Format::Mp4)
5446 );
5447 }
5448 // The destination follows the format and keeps the stem, mp4 included.
5449 assert_eq!(
5450 retarget(std::path::Path::new("/a/take.export.mp4"), Format::Wav),
5451 std::path::Path::new("/a/take.export.wav")
5452 );
5453 assert_eq!(
5454 retarget(std::path::Path::new("/a/take.export.wav"), Format::Mp4),
5455 std::path::Path::new("/a/take.export.mp4")
5456 );
5457 assert!(format_line(Format::Flac).contains("audio only"));
5458 }
5459
5460 #[test]
5461 fn nothing_clickable_is_smaller_than_the_wcag_minimum() {
5462 // Every hit target in the panel, including the scrub strip -- whose bar
5463 // is 6 px to look at and whose click area must not be.
5464 assert!(CONTROL_H >= HIT_MIN);
5465 assert!(RULER_HIT_H >= HIT_MIN);
5466 assert!(LANE_H >= HIT_MIN);
5467 }
5468
5469 /// WCAG 2.1 relative luminance of a packed `0xRRGGBB`.
5470 fn luminance(colour: u32) -> f64 {
5471 let channel = |shift: u32| {
5472 let s = f64::from((colour >> shift) & 0xff) / 255.;
5473 if s <= 0.03928 {
5474 s / 12.92
5475 } else {
5476 ((s + 0.055) / 1.055).powf(2.4)
5477 }
5478 };
5479 0.2126 * channel(16) + 0.7152 * channel(8) + 0.0722 * channel(0)
5480 }
5481
5482 /// WCAG 2.1 contrast ratio, 1..=21.
5483 fn contrast(a: u32, b: u32) -> f64 {
5484 let (a, b) = (luminance(a), luminance(b));
5485 (a.max(b) + 0.05) / (a.min(b) + 0.05)
5486 }
5487
5488 #[test]
5489 fn a_lane_row_is_a_fixed_header_and_a_bed_that_can_be_hit() {
5490 // The header column is what the ruler is offset by as well, so both
5491 // numbers are shared rather than repeated per row (A-MUST1/A-MUST2).
5492 assert!(HEADER_W > 0. && HEADER_GAP >= 0.);
5493 // Two lanes, a ruler, a button row and the timecode line, inside the
5494 // panel the window is sized for.
5495 assert!(
5496 CONTROL_H + RULER_HIT_H + 2. * LANE_H + 17. + 4. * 8. + 16. <= PANEL_H,
5497 "the second lane does not fit the panel"
5498 );
5499 // Headers and clip boxes are as tall as the lane, and the lane is a
5500 // click target (WCAG 2.5.8).
5501 assert!(LANE_H >= HIT_MIN);
5502 // A label row that ate the whole lane would leave no waveform.
5503 assert!(LABEL_H < LANE_H / 2.);
5504 // An added track adds its own row to the panel, and the two a project
5505 // starts with leave it exactly the height it has always been.
5506 assert_eq!(panel_h(2), PANEL_H);
5507 assert_eq!(panel_h(1), PANEL_H);
5508 assert_eq!(panel_h(3), PANEL_H + LANE_H + 8.);
5509 assert_eq!(
5510 panel_h(LANES_MAX),
5511 PANEL_H + lanes_h(LANES_MAX) - lanes_h(2)
5512 );
5513 // Past the cap the column scrolls instead: the panel stops growing, so
5514 // no number of tracks can push the picture off the window.
5515 assert_eq!(panel_h(LANES_MAX + 1), panel_h(LANES_MAX));
5516 assert_eq!(panel_h(50), panel_h(LANES_MAX));
5517 assert_eq!(lanes_h(0), 0.);
5518 assert_eq!(lanes_h(1), LANE_H);
5519 assert_eq!(lanes_h(2), 2. * LANE_H + 8.);
5520 }
5521
5522 #[test]
5523 fn a_click_marks_the_whole_group_and_nothing_else() {
5524 let (v, a) = ((Lane::V1, 0), (Lane::A1, 0));
5525 // Clicking the video half of group 1 marks the audio half with it.
5526 assert!(marked(v, Some(1), Some(v), Some(1)));
5527 assert!(marked(a, Some(1), Some(v), Some(1)));
5528 // Another group's clips stay unmarked, in either lane.
5529 assert!(!marked((Lane::V1, 1), Some(2), Some(v), Some(1)));
5530 assert!(!marked((Lane::A1, 1), Some(2), Some(v), Some(1)));
5531 // A half a lift left behind has no group: it marks itself only, which
5532 // is what makes it separately deletable. Two ungrouped clips must not
5533 // mark each other by both being ungrouped.
5534 assert!(marked(a, None, Some(a), None));
5535 assert!(!marked(v, None, Some(a), None));
5536 // Nothing selected marks nothing.
5537 assert!(!marked(v, Some(1), None, None));
5538 }
5539
5540 #[test]
5541 fn a_name_is_dropped_rather_than_smeared_across_a_thin_clip() {
5542 assert!(show_label(LABEL_MIN_W));
5543 assert!(show_label(400.));
5544 assert!(!show_label(LABEL_MIN_W - 0.1));
5545 // A timeline with no length must not put a box outside its lane.
5546 assert_eq!(start_frac(3., 0.), 0.);
5547 assert_eq!(start_frac(1., 4.), 0.25);
5548 // Past the end clamps rather than running off the bed.
5549 assert_eq!(start_frac(8., 4.), 1.);
5550 }
5551
5552 #[test]
5553 fn an_envelope_stays_inside_the_box_it_is_drawn_in() {
5554 // A ramp: silence at the start, full scale at the end.
5555 let peaks: Vec<(f32, f32)> = (0..40)
5556 .map(|i| (-(i as f32) / 39., i as f32 / 39.))
5557 .collect();
5558 let (w, h) = (100., 30.);
5559 let cols = envelope(&peaks, 0., 1., w, h);
5560 assert_eq!(cols.len(), (w / WAVE_COL) as usize + 1);
5561 for &(x, top, bottom) in &cols {
5562 assert!((0. ..=w).contains(&x), "x {x} outside 0..{w}");
5563 assert!((0. ..=h).contains(&top), "top {top} outside 0..{h}");
5564 assert!(
5565 (0. ..=h).contains(&bottom),
5566 "bottom {bottom} outside 0..{h}"
5567 );
5568 // Never inverted, and never a polygon with no area: silence has to
5569 // read as a line rather than as nothing at all.
5570 assert!(
5571 bottom - top >= 1.,
5572 "column {top}..{bottom} is thinner than a pixel"
5573 );
5574 }
5575 // The ramp is drawn as a ramp: the last column is taller than the first.
5576 let height = |&(_, top, bottom): &(f32, f32, f32)| bottom - top;
5577 assert!(height(cols.last().unwrap()) > height(cols.first().unwrap()) + 5.);
5578 // Degenerate inputs draw nothing rather than panicking.
5579 assert!(envelope(&[], 0., 1., w, h).is_empty());
5580 assert!(envelope(&peaks, 0., 1., 0., h).is_empty());
5581 // A clip whose range runs past the peaks clamps to the last bucket.
5582 assert!(!envelope(&peaks, 0., 99., w, h).is_empty());
5583 }
5584
5585 #[test]
5586 fn a_quiet_source_still_draws_as_a_shape() {
5587 // An eighth of full scale, which is about where the fixtures sit.
5588 let quiet: Vec<(f32, f32)> = vec![(-0.125, 0.125), (-0.0625, 0.0625)];
5589 let loud = normalise(quiet.clone());
5590 assert_eq!(loud[0], (-1., 1.));
5591 assert_eq!(loud[1], (-0.5, 0.5));
5592 // Digital silence has no loudest sample to scale to; it must not divide
5593 // by zero and must stay flat.
5594 assert_eq!(normalise(vec![(0., 0.)]), vec![(0., 0.)]);
5595 assert!(normalise(Vec::new()).is_empty());
5596 }
5597
5598 /// The whole waveform path, from the file on disk to the columns that get
5599 /// painted: what no screenshot can assert about the shape.
5600 #[test]
5601 fn the_fixtures_waveform_reaches_the_lane_as_a_shape() {
5602 let asset = |name: &str| {
5603 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
5604 .join("../../assets")
5605 .join(name)
5606 };
5607 let peaks = normalise(
5608 engine::waveform::peaks(asset("test_av.mp4"), 0, WAVE_BPS)
5609 .expect("open the fixture")
5610 .expect("test_av.mp4 has audio"),
5611 );
5612 // 5 s of source at the rate the lane asks for.
5613 assert!(peaks.len().abs_diff(5 * WAVE_BPS as usize) <= WAVE_BPS as usize);
5614 let cols = envelope(&peaks, 0., 5., 600., 30.);
5615 let height = |&(_, top, bottom): &(f32, f32, f32)| bottom - top;
5616 let tallest = cols.iter().map(height).fold(0., f32::max);
5617 let flattest = cols.iter().map(height).fold(f32::MAX, f32::min);
5618 // The fixture's 1 Hz pulse: a full-scale peak and a near-silent dip in
5619 // every second, so the drawn envelope is a shape and not a bar.
5620 assert!(tallest > 25., "loudest column only {tallest} px of 30");
5621 assert!(
5622 flattest < 8.,
5623 "quietest column {flattest} px -- no dips drawn"
5624 );
5625 // A video-only source draws no waveform at all rather than a flat fake.
5626 assert!(
5627 engine::waveform::peaks(asset("test_baseline.mp4"), 0, WAVE_BPS)
5628 .expect("open the fixture")
5629 .is_none()
5630 );
5631 }
5632
5633 #[test]
5634 fn every_mark_on_a_clip_is_legible_on_it() {
5635 for (i, tint) in SOURCE_TINTS.iter().enumerate() {
5636 // WCAG 1.4.3: the clip's name is body text on its tint.
5637 assert!(
5638 contrast(INK, *tint) >= 4.5,
5639 "source {i}: label contrast {:.2}",
5640 contrast(INK, *tint)
5641 );
5642 // WCAG 1.4.11: the waveform is a non-text graphic on it.
5643 assert!(
5644 contrast(INK_DIM, *tint) >= 3.,
5645 "source {i}: waveform contrast {:.2}",
5646 contrast(INK_DIM, *tint)
5647 );
5648 }
5649 // A selected clip's bed is the same two marks on a different colour.
5650 assert!(contrast(INK, SELECTED) >= 4.5);
5651 assert!(contrast(INK_DIM, SELECTED) >= 3.);
5652 // The bed a gap shows through has to read as a hole in the lane, and
5653 // the accent playhead has to be findable on it.
5654 assert!(contrast(LETTERBOX, SURFACE) >= 1.5);
5655 assert!(contrast(ACCENT, LETTERBOX) >= 3.);
5656 // The sanity check on the ratio itself: black on white is 21:1.
5657 assert!((contrast(0xffffff, 0x000000) - 21.).abs() < 0.01);
5658 }
5659
5660 #[test]
5661 fn source_tints_differ_per_source_and_cycle() {
5662 // The file the session opened with is the unchanged lane colour.
5663 assert_eq!(source_tint(0), SURFACE);
5664 // Neighbouring sources must not share one, or an import is invisible.
5665 assert_ne!(source_tint(0), source_tint(1));
5666 assert_ne!(source_tint(1), source_tint(2));
5667 assert_ne!(source_tint(2), source_tint(3));
5668 // Past the palette it wraps -- never an index panic.
5669 assert_eq!(source_tint(4), source_tint(0));
5670 assert_eq!(source_tint(9), source_tint(1));
5671 assert_eq!(source_tint(usize::MAX), SOURCE_TINTS[usize::MAX % 4]);
5672 }
5673}
5674
5675fn main() {
5676 let arg = std::env::args().nth(1).map(PathBuf::from);
5677 // A `.edith` restores a whole timeline, anything else *is* the timeline.
5678 // Either way the rest of argv is appended to what comes out. No argument at
5679 // all opens the window empty -- the timeline then arrives by drop or by the
5680 // Import button, and everything below is derived from it at that point
5681 // instead.
5682 let mut session = match &arg {
5683 Some(arg) => {
5684 let opened = if is_project(arg) {
5685 PlaybackSession::open_project(arg)
5686 } else {
5687 PlaybackSession::open(arg)
5688 };
5689 match opened {
5690 Ok(v) => Some(v),
5691 Err(e) => {
5692 // A failed load by drop leaves the running session alone;
5693 // here a file was named and could not be opened, so the
5694 // refusal is the whole run.
5695 eprintln!("cannot open {}: {e}", arg.display());
5696 std::process::exit(1);
5697 }
5698 }
5699 }
5700 None => None,
5701 };
5702 // A keymap file that cannot be read leaves the defaults in force, and takes
5703 // the notice slot ahead of an import refusal below: it is about every key
5704 // the window has, and the import refusal is on stderr either way.
5705 let (keymap, mut notice) = Keymap::load();
5706 if let Some(text) = &notice {
5707 eprintln!("{text}");
5708 }
5709 // The first file makes the timeline, the rest are appended to it. A refusal
5710 // is not fatal -- the others still load -- but the window must not open
5711 // silently pretending the file was taken, so the first one seeds the notice.
5712 for extra in std::env::args().skip(2) {
5713 // Only reachable with a first argument, so there is a timeline.
5714 if let Some(session) = &mut session
5715 && let Err(e) = session.import(std::path::Path::new(&extra))
5716 {
5717 let text = format!("IMPORT FAILED: {e}");
5718 eprintln!("{extra}: {text}");
5719 notice.get_or_insert(text);
5720 }
5721 }
5722 // A file that plays silent is as much news at launch as it is on a drop, and
5723 // behind the keymap notice for the same reason an import refusal is.
5724 if let Some(reason) = session
5725 .as_ref()
5726 .and_then(PlaybackSession::audio_disabled_reason)
5727 {
5728 let text = format!("NO AUDIO: {reason}");
5729 eprintln!("{text}");
5730 notice.get_or_insert(text);
5731 }
5732 let meta = session.as_ref().map(|session| *session.meta());
5733 // Beside the media even for a project: an export has never landed anywhere
5734 // but next to the picture it came from.
5735 let out = session.as_ref().map_or_else(PathBuf::new, |session| {
5736 export_path(&session.sources()[0].path)
5737 });
5738 let project = match &arg {
5739 Some(arg) if is_project(arg) => arg.clone(),
5740 Some(arg) => project_path(arg),
5741 // Chosen with the file, once there is one to choose it from.
5742 None => PathBuf::new(),
5743 };
5744 let name: SharedString = arg
5745 .as_deref()
5746 .map_or_else(|| NO_FILE.into(), |arg| file_name(arg).into());
5747 if let (Some(arg), Some(meta)) = (&arg, &meta) {
5748 println!(
5749 "{}: {}x{} @ {:.2} fps, {} samples",
5750 arg.display(),
5751 meta.width,
5752 meta.height,
5753 meta.frame_rate,
5754 meta.frame_count
5755 );
5756 }
5757
5758 Application::new().run(move |cx: &mut App| {
5759 // The picture's own size, or 720p when there is no picture yet: the
5760 // empty window is a landing pad, not a sliver.
5761 let (w, h) = meta.map_or((1280., 720.), |meta| {
5762 (meta.width as f32, meta.height as f32)
5763 });
5764 let bounds = Bounds::centered(None, size(px(w), px(h)), cx);
5765 cx.open_window(
5766 WindowOptions {
5767 window_bounds: Some(WindowBounds::Windowed(bounds)),
5768 titlebar: Some(TitlebarOptions {
5769 title: Some("edith".into()),
5770 ..Default::default()
5771 }),
5772 // What a desktop groups this window under. The title beside it
5773 // is pushed from the render, because wayland takes neither of
5774 // them from the titlebar options above (gpui's wayland window
5775 // reads only `app_id`, window.rs:1202 / window.rs:939) and the
5776 // title has to follow the file being opened anyway.
5777 app_id: Some("edith".to_string()),
5778 ..Default::default()
5779 },
5780 |window, cx| {
5781 let player = cx.new(|cx| Player {
5782 // A file named on the command line owes its first frame the
5783 // same repaint a seek's still owes: nothing plays by
5784 // itself, so this is what carries the poster frame to the
5785 // screen. An empty window has none to wait for.
5786 pending_seek: session.is_some(),
5787 session,
5788 // Full and unmuted, which is what the session it was just
5789 // handed is already set to: nothing to push at startup.
5790 volume: Volume::default(),
5791 // Only ever used with a timeline; 30 keeps the empty
5792 // timecode reading in frames rather than in NaN.
5793 fps: meta.map_or(30., |meta| meta.frame_rate),
5794 name: name.clone(),
5795 image: None,
5796 held: None,
5797 eos: false,
5798 done: false,
5799 ruler: Rc::default(),
5800 selected: None,
5801 context_menu: None,
5802 selected_asset: None,
5803 waves: HashMap::new(),
5804 streams: HashMap::new(),
5805 clipboard: None,
5806 scrubbing: false,
5807 last_scrub: Instant::now(),
5808 last_target: 0,
5809 export: None,
5810 cancelling: false,
5811 export_path: out.clone(),
5812 project_path: project.clone(),
5813 keymap: keymap.clone(),
5814 keys_open: false,
5815 export_open: false,
5816 eq_open: None,
5817 // Replaced by the clip's own curve the moment the card
5818 // opens; nothing reads it before that.
5819 eq_params: EqParams::default(),
5820 eq_band: 0,
5821 eq_dragging: false,
5822 eq_bar: Rc::default(),
5823 color_open: None,
5824 color_band: 0,
5825 // What an export is until someone says otherwise: the
5826 // bitrate the picture asks for.
5827 quality: Quality::Auto,
5828 custom_mbps: 0,
5829 // Picture and sound, which is what an export was before
5830 // there was anything to pick.
5831 format: Format::default(),
5832 rebinding: None,
5833 notice: notice.clone().map(SharedString::from),
5834 // Nothing pushed yet, and never a real title: the first
5835 // render is what names the window.
5836 titled: String::new(),
5837 displayed: 0,
5838 dropped: 0,
5839 started: None,
5840 focus: cx.focus_handle(),
5841 });
5842 // Nothing else takes focus, and without it the key listener
5843 // above is never reached.
5844 window.focus(&player.read(cx).focus);
5845 player
5846 },
5847 )
5848 .unwrap();
5849 cx.activate(true);
5850 });
5851}