forge
Explore
Log in

Don't you dare go Hollow

edith

Clone
★ 0

0 watching0 forksRust18.3 MiB2e2ed69Tahinli3 months ago69 commits

main.rs4388 lines, 188.5 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::export::ExportSettings;
14use engine::project::{Lane, Source};
15use engine::{Clip, ExportHandle, Frame, PlaybackSession};
16use gpui::{
17 AnyElement, App, Application, Bounds, ClickEvent, Context, FocusHandle, KeyDownEvent,
18 MouseButton, MouseDownEvent, MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, Point,
19 RenderImage, SharedString, Size, TitlebarOptions, Window, WindowBounds, WindowOptions, canvas,
20 div, img, point, prelude::*, px, relative, rgb, rgba, size,
21};
22
23/// Editor chrome: three grays and one accent, all darker than the picture so the
24/// frame is what the eye lands on. `LETTERBOX` stays the video's own bed.
25const LETTERBOX: u32 = 0x101010;
26const CHROME: u32 = 0x242424;
27const SURFACE: u32 = 0x333333;
28const INK: u32 = 0xc8c8c8;
29const ACCENT: u32 = 0x4a9eff;
30/// The accent at surface brightness: a selected clip is tinted, not lit up.
31const SELECTED: u32 = 0x2a4a6b;
32/// One per source, so a clip that came from an imported file reads as coming
33/// from somewhere else. Same brightness as `SURFACE` and only the hue moves:
34/// the lane stays in the dark family the rest of the chrome lives in
35/// (ledger:187), and the first source keeps `SURFACE` exactly.
36const SOURCE_TINTS: [u32; 4] = [SURFACE, 0x3b3329, 0x293b33, 0x33293b];
37/// One step lighter than whatever it sits on: the pointer's answer that this is
38/// clickable. Two of them, because buttons stand on `SURFACE` and the scrub
39/// strip stands on `CHROME`.
40const HOVER: u32 = 0x3f3f3f;
41const HOVER_DIM: u32 = 0x2c2c2c;
42/// Secondary text -- shortcuts, dismissal hints. Dimmer than `INK` and still
43/// past 4.5:1 on both `SURFACE` and `CHROME`.
44const INK_DIM: u32 = 0xa0a0a0;
45
46/// Fixed so the video region takes every pixel the window gains and the controls
47/// never clip at 640x360.
48const HEADER_H: f32 = 32.;
49// 28 button row + 24 scrub strip + two 48 lanes + the timecode line + the gaps
50// between them, with a few px of slack so a taller text line cannot push a lane
51// off the bottom.
52const PANEL_H: f32 = 220.;
53const LANE_H: f32 = 48.;
54/// The lane header column: wide enough for `V1`/`A1` and fixed, so both lanes
55/// and the ruler above them start at the same pixel and are the same width --
56/// one x-to-time mapping for the whole timeline. `HEADER_GAP` is part of that
57/// offset and is therefore shared by all three rows.
58const HEADER_W: f32 = 40.;
59const HEADER_GAP: f32 = 4.;
60/// The label row inside a clip; a waveform paints under it, never through it.
61const LABEL_H: f32 = 15.;
62/// A clip narrower than this shows no name: two characters and an ellipsis say
63/// nothing that the tint has not already said, and cost the picture a smear.
64const LABEL_MIN_W: f32 = 36.;
65/// Peak buckets per second of source. Fixed and modest on purpose: `peaks`
66/// allocates one bucket per window, so a rate taken from anything the user can
67/// influence is an allocation bomb -- and 40 is already finer than the pixels a
68/// clip is ever given.
69const WAVE_BPS: u32 = 40;
70/// Pixels per envelope column. Coarser than a pixel: the eye reads the shape,
71/// and a path with a point per pixel is a path per repaint.
72const WAVE_COL: f32 = 2.;
73/// WCAG 2.5.8: nothing clickable is smaller than this. The scrub bar stays 6 px
74/// to look at -- `RULER_HIT_H` is the strip that has to be hit.
75const HIT_MIN: f32 = 24.;
76/// The media library's column: a share of the window rather than a fixed width,
77/// so it yields on a narrow one, and never more than a third of it -- the
78/// picture is what this program is for and keeps the majority at every size.
79/// The floor is what a file name and a timecode need to be readable at all.
80const LIBRARY_FRAC: f32 = 0.2;
81const LIBRARY_MIN_W: f32 = 120.;
82const LIBRARY_MAX_W: f32 = 220.;
83/// A library row: a name over its duration, two lines and a click target, so
84/// `HIT_MIN` binds it like every other one.
85const ROW_H: f32 = 32.;
86/// The tint swatch down the left of a row: the same colour that source's clips
87/// wear in the lanes, which is the whole of the panel<->timeline association.
88const SWATCH_W: f32 = 4.;
89const CONTROL_H: f32 = 28.;
90const RULER_HIT_H: f32 = HIT_MIN;
91/// Wide enough for `HH:MM:SS:FF / HH:MM:SS:FF`, and fixed so changing digits
92/// cannot push the layout around.
93const TIME_W: f32 = 200.;
94/// The keybindings card: a row per action, a title and a status line, inside a
95/// 360 px tall window. The rows are click targets, so `HIT_MIN` binds them too.
96const KEYS_W: f32 = 320.;
97const KEYS_ROW_H: f32 = HIT_MIN;
98/// How much of the row list is on screen at once; past this it scrolls. What
99/// keeps the card inside the smallest window no matter how many actions the
100/// editor grows -- ten rows fit here, and the eleventh is a scroll away.
101const KEYS_ROWS_H: f32 = 10. * KEYS_ROW_H;
102/// The menu a right-click on a clip opens: wide enough for the longest label
103/// beside the stroke that does the same thing, with the click targets `HIT_MIN`
104/// binds like every other list here.
105const MENU_W: f32 = 260.;
106const MENU_ROW_H: f32 = HIT_MIN;
107const MENU_PAD: f32 = 6.;
108
109/// The one key name this file still spells out, and gpui's spelling of it: it
110/// is the way out of a capture and out of the overlay, and both have to work
111/// while the keymap itself is what is being changed -- so neither can go
112/// through the keymap to find it.
113const ESCAPE: &str = "escape";
114
115/// What the header says with no timeline open, and what the window title reads
116/// as a program name rather than as a file name.
117const NO_FILE: &str = "no file open";
118
119/// What the monitoring output is set to. Two things, not one: the level the
120/// user picked, and whether it is being held silent -- so unmuting comes back
121/// to the level rather than to a guess.
122///
123/// The level counts steps rather than carrying an `f32`, because 5% at a time
124/// down and back up again through a float would not land on the number it
125/// started from, and the label would eventually read `79%`.
126///
127/// Volume and mute stay independent on purpose: turning the level down while
128/// muted must not be what makes sound come out. Only the mute key unmutes, and
129/// the button says both things at once ("Muted 80%") so neither is a surprise.
130#[derive(Clone, Copy, PartialEq, Eq, Debug)]
131struct Volume {
132 steps: u8,
133 muted: bool,
134}
135
136impl Volume {
137 /// 5% a press: twenty of them across the range.
138 const MAX_STEPS: u8 = 20;
139
140 /// What the device is set to: mute wins, and the level is what it returns
141 /// to. `0.0..=1.0`, which is the range the plugin's ABI accepts.
142 fn gain(self) -> f32 {
143 if self.muted {
144 0.
145 } else {
146 f32::from(self.steps) / f32::from(Self::MAX_STEPS)
147 }
148 }
149
150 /// One press up or down, clamped at both ends -- saturating, so the count
151 /// cannot wrap past silence into full volume.
152 fn step(&mut self, up: bool) {
153 self.steps = if up {
154 self.steps.saturating_add(1).min(Self::MAX_STEPS)
155 } else {
156 self.steps.saturating_sub(1)
157 };
158 }
159
160 /// What the button reads. The level shows while muted too: it is what the
161 /// next press of the mute key brings back.
162 fn label(self) -> String {
163 let percent = u32::from(self.steps) * 100 / u32::from(Self::MAX_STEPS);
164 if self.muted {
165 format!("Muted {percent}%")
166 } else {
167 format!("Vol {percent}%")
168 }
169 }
170}
171
172impl Default for Volume {
173 fn default() -> Self {
174 Self {
175 steps: Self::MAX_STEPS,
176 muted: false,
177 }
178 }
179}
180
181/// What is known about a source's audio. Three states and not two, because a
182/// file whose peaks have not come back yet must not be drawn as one that has no
183/// audio at all: the first shows a bed, the second shows nothing.
184#[derive(Clone)]
185enum Wave {
186 /// Asked for; the decode is running on a background thread.
187 Loading,
188 /// The file has no audio track. An answer, not a miss.
189 Silent,
190 Peaks(Arc<Vec<(f32, f32)>>),
191}
192
193/// A library row being dragged: the file and which of its audio streams that
194/// row is, which is the whole of what a row names. Where it lands does not
195/// change what is inserted.
196struct AssetDrag(PathBuf, usize);
197
198/// An open clip menu: which clip it was opened on, where it hangs, and whether
199/// it has been turned over to show what that clip *is* instead of what can be
200/// done to it. The lane and index are the ones the same click selected, so
201/// every item acts on exactly the box under the pointer.
202#[derive(Clone, Copy)]
203struct ContextMenu {
204 lane: Lane,
205 idx: usize,
206 at: Point<Pixels>,
207 details: bool,
208}
209
210/// What the menu offers, in the order it lists them. Every one of these is an
211/// action a stroke already reaches -- the menu is a second way *to* the actions
212/// and never a second version of them -- so both the label and the hint come
213/// out of the keymap registry and the two can never disagree.
214const MENU_ITEMS: [ActionId; 5] = [
215 ActionId::Cut,
216 ActionId::Delete,
217 ActionId::Lift,
218 ActionId::Regroup,
219 ActionId::ToggleMute,
220];
221
222struct Player {
223 /// The timeline, once there is one. A run with no file opens without it and
224 /// waits: the first media import or project load is what fills it, and
225 /// until then every action that needs a timeline says so instead of acting.
226 session: Option<PlaybackSession>,
227 /// Timeline seconds -> frame index, so the clock can be compared to what
228 /// the decoder hands over.
229 fps: f64,
230 name: SharedString,
231 image: Option<Arc<RenderImage>>,
232 /// A frame that arrived before its time; shown on the tick it comes due.
233 held: Option<Frame>,
234 /// The decoder's channel closed. Frames may still be waiting in `held`.
235 eos: bool,
236 /// Last frame shown; nothing left to animate.
237 done: bool,
238 /// A seek is waiting for its frame. Keeps the repaint loop alive while
239 /// paused, which is the only way the new still ever reaches the screen.
240 pending_seek: bool,
241 /// The ruler's own box, recorded at prepaint: a mouse listener is handed
242 /// the window position and nothing else.
243 ruler: Rc<Cell<Bounds<Pixels>>>,
244 /// Which clip the edit keys act on: the lane it is in and its index there.
245 /// The *clicked* half, not the group -- a group is what gets marked on
246 /// screen, but Lift has to know which half it was aimed at. Indices move
247 /// under every edit, so this is cleared by all of them.
248 selected: Option<(Lane, usize)>,
249 /// The clip menu a right-click opened, if one is up. Holds an index like
250 /// `selected` does, so it is closed by anything that can move indices --
251 /// every stroke, and every item of its own.
252 context_menu: Option<ContextMenu>,
253 /// Which library row is picked: the file and the audio stream that row
254 /// names, which is what an insert needs and what survives a row list being
255 /// rebuilt. Its own selection and not the timeline's: Delete keeps acting
256 /// on the clip that was clicked in a lane, whatever the library is showing.
257 selected_asset: Option<(PathBuf, usize)>,
258 /// What is known about each source's audio, taken once and kept. Keyed on
259 /// the path *and stream* -- two streams of one file are two envelopes -- and
260 /// the key is inserted the moment the decode is *started*: presence means
261 /// "asked", so a repaint mid-decode cannot ask again.
262 waves: HashMap<(PathBuf, usize), Wave>,
263 /// Which audio streams each imported file has, as its header describes
264 /// them: one library row per entry. Keyed and filled like `waves` --
265 /// presence means "asked" -- and an empty list is a silent file, which is
266 /// exactly one row and no stream tags.
267 streams: HashMap<PathBuf, Vec<StreamInfo>>,
268 /// The copied clip. Frame ranges only, so it survives the clip it was taken
269 /// from being deleted -- and it outlives the selection.
270 clipboard: Option<Clip>,
271 /// A drag that started on the ruler. Moves anywhere in the window scrub
272 /// while it is set; the release commits the exact position.
273 scrubbing: bool,
274 last_scrub: Instant,
275 last_target: u32,
276 /// The running export. While it owns the UI the editor is read-only.
277 export: Option<ExportHandle>,
278 /// The export above was cancelled and is only winding down. The editor is
279 /// already free -- the worker took its own copy of the edit list -- but the
280 /// handle is held until the worker settles, because its last act is to
281 /// delete the output file and a second export must not be what it deletes.
282 cancelling: bool,
283 /// Where an export writes. Built once from the source path, which is not
284 /// otherwise kept.
285 export_path: PathBuf,
286 /// Where the save action writes: the project this timeline was loaded from,
287 /// or the one derived beside the media it started as. Saving twice
288 /// overwrites the same file rather than making a second one.
289 project_path: PathBuf,
290 /// Which stroke means what, and what every shortcut on screen is called.
291 /// The one place either question is answered.
292 keymap: Keymap,
293 /// How loud the monitoring is, and whether it is muted. Lives here rather
294 /// than in the session so it survives closing one file and opening the
295 /// next -- it is a setting of the player, not of the timeline, which is
296 /// also why it is not written to the project file and cannot reach an
297 /// export. [`Player::apply_volume`] is what pushes it at a session.
298 volume: Volume,
299 /// The keybindings overlay is up. While it is, it owns the keyboard and the
300 /// pointer: a stroke or a click meant for a row must not also cut the
301 /// timeline.
302 keys_open: bool,
303 /// The export options card is up: what the export action opens now, so
304 /// nothing is written until the card's own button says so. One card at a
305 /// time -- opening either closes the other, since both are the whole window
306 /// and two stacked scrims say nothing about which one is listening.
307 export_open: bool,
308 /// Which quality row the card has picked, and the megabits typed against
309 /// the custom one. Kept across closes, so a second export offers what the
310 /// first one chose.
311 quality: Quality,
312 custom_mbps: u32,
313 /// The action whose row is waiting for a stroke. The next key that is
314 /// neither escape nor a lone modifier becomes the whole of what reaches it.
315 rebinding: Option<ActionId>,
316 /// What the last file action had to say. Holds its own bar above the panel
317 /// until it is answered -- any key retires it, so does a click on it -- so a
318 /// failure is read in full instead of blinking past.
319 notice: Option<SharedString>,
320 /// What the compositor was last told this window is called. Setting a title
321 /// is a protocol round trip and a repaint is sixty a second, so the title is
322 /// pushed only when it is not this any more.
323 titled: String,
324 displayed: u32,
325 dropped: u32,
326 /// Wall clock of the first displayed frame -- the real-speed measurement.
327 started: Option<Instant>,
328 focus: FocusHandle,
329}
330
331impl Player {
332 /// Catches the display up to the clock: everything already due is taken off
333 /// the channel and only the last of them is shown, which *is* the
334 /// drop-when-behind policy. A frame that is not due yet waits in `held`.
335 fn pump(&mut self, window: &mut Window) {
336 // No timeline, nothing to catch up to: the window is showing its empty
337 // state and there is no decoder to drain.
338 let Some(session) = &mut self.session else {
339 return;
340 };
341 let target = session.now() * self.fps;
342 let mut newest: Option<Frame> = None;
343 loop {
344 let frame = match self.held.take() {
345 Some(frame) => frame,
346 // Nothing waiting means either a clip boundary being rebuilt or
347 // the real end of the timeline, and only the engine can tell
348 // them apart -- `frame.index` is already a timeline index.
349 None => match session.try_frame() {
350 Some(frame) => frame,
351 None => {
352 self.eos = session.is_eos();
353 break;
354 }
355 },
356 };
357 if f64::from(frame.index) <= target {
358 self.dropped += u32::from(newest.is_some());
359 newest = Some(frame);
360 } else {
361 self.held = Some(frame);
362 break;
363 }
364 }
365
366 if let Some(frame) = newest {
367 self.displayed += 1;
368 self.pending_seek = false;
369 self.started.get_or_insert_with(|| {
370 eprintln!("first frame displayed (index {})", frame.index);
371 Instant::now()
372 });
373 let buf = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra)
374 .expect("frame buffer sized width*height*4");
375 let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)]));
376 if let Some(old) = self.image.replace(next) {
377 // Every RenderImage gets a fresh id and its own atlas tile:
378 // without this the sprite atlas grows for the whole video.
379 let _ = window.drop_image(old);
380 }
381 }
382
383 if self.eos && self.held.is_none() && !self.done {
384 self.done = true;
385 // A seek whose worker never produced a frame (vanished file) would
386 // otherwise repaint at vsync forever.
387 self.pending_seek = false;
388 let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64());
389 eprintln!(
390 "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s",
391 self.displayed,
392 self.dropped,
393 session.now()
394 );
395 }
396 }
397
398 /// Every end-of-stream flag is app state and the engine knows nothing about
399 /// it, so clearing them after a reseek is what stops the picture from
400 /// staying frozen on the old last frame. Edits reseek inside the engine and
401 /// still owe this.
402 fn reset_after_reseek(&mut self) {
403 self.held = None;
404 self.eos = false;
405 self.done = false;
406 self.pending_seek = true;
407 }
408
409 /// What an action does, wherever it was asked for -- a stroke, or the clip
410 /// menu item that names the same action. One table, so the two can never
411 /// come to mean different things.
412 fn act(&mut self, action: ActionId, cx: &mut Context<Self>) {
413 match action {
414 ActionId::Play => self.toggle_or_restart(cx),
415 ActionId::Export => self.open_export(cx),
416 ActionId::Save => self.save_project(cx),
417 ActionId::Copy => self.copy_selected(),
418 ActionId::Paste => self.paste(cx),
419 ActionId::Cut => self.cut(cx),
420 ActionId::Regroup => self.regroup(cx),
421 ActionId::Delete => self.delete_selected(cx),
422 ActionId::Lift => self.lift_selected(cx),
423 ActionId::Undo => self.undo(cx),
424 ActionId::ToggleMute => self.set_volume(|volume| volume.muted = !volume.muted, cx),
425 ActionId::VolumeUp => self.set_volume(|volume| volume.step(true), cx),
426 ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx),
427 // Nothing to cancel while nothing is exporting; the export guard in
428 // the key handler is what answers this one while there is.
429 ActionId::CancelExport => {}
430 }
431 }
432
433 /// Whether a card owns the window. While one does the timeline under it is
434 /// out of reach, so a right-click there opens no menu -- the same rule the
435 /// key handler and the drop target already follow.
436 fn modal(&self) -> bool {
437 self.keys_open || self.export_open || self.exporting().is_some()
438 }
439
440 /// Jumps the timeline.
441 fn seek(&mut self, t: f64, cx: &mut Context<Self>) {
442 if self.exporting().is_some() {
443 return;
444 }
445 let Some(session) = &mut self.session else {
446 return;
447 };
448 session.seek(t);
449 self.reset_after_reseek();
450 cx.notify();
451 }
452
453 /// Splits the clip under the playhead. Metadata only: the timeline->source
454 /// mapping is unchanged, so nothing reseeks and no flag is touched.
455 fn cut(&mut self, cx: &mut Context<Self>) {
456 if self.exporting().is_some() {
457 return;
458 }
459 if let Some(session) = &mut self.session {
460 session.cut_at(session.now());
461 }
462 self.selected = None;
463 cx.notify();
464 }
465
466 /// Rejoins whatever meets under the playhead and puts it back in one group
467 /// -- the inverse of [`Player::cut`], and metadata only like it. The engine
468 /// decides what is joinable; a refusal is worded here, because `false` is
469 /// all it says and a key that looks broken is worse than one that explains
470 /// itself.
471 fn regroup(&mut self, cx: &mut Context<Self>) {
472 if self.exporting().is_some() {
473 return;
474 }
475 if let Some(session) = &mut self.session {
476 if session.regroup_at(session.now()) {
477 self.selected = None;
478 } else {
479 self.notice = Some(
480 "NOTHING TO REGROUP — put the playhead where two clips meet, on frames that were cut apart"
481 .into(),
482 );
483 }
484 }
485 cx.notify();
486 }
487
488 /// Drops the selected clip and closes the hole: a whole take goes, both
489 /// lanes of it, and everything after it moves up. A half with no take under
490 /// it in the video lane -- what a lift leaves behind -- has nothing to
491 /// ripple, so that one is lifted instead. The engine reseeks itself, so all
492 /// this owes is the flag reset.
493 fn delete_selected(&mut self, cx: &mut Context<Self>) {
494 if self.exporting().is_some() {
495 return;
496 }
497 let deleted = match (&mut self.session, self.selected.take()) {
498 (Some(session), Some((Lane::Video, idx))) => session.delete_clip(idx),
499 (Some(session), Some((Lane::Audio, idx))) => match video_half(session, idx) {
500 Some(video) => session.delete_clip(video),
501 None => session.lift_clip(Lane::Audio, idx),
502 },
503 _ => false,
504 };
505 if deleted {
506 self.reset_after_reseek();
507 }
508 cx.notify();
509 }
510
511 /// Lifts the selected half out and leaves the hole: black picture there if
512 /// it was the video lane, silence if it was the audio one, and nothing else
513 /// moves. What Delete is not.
514 fn lift_selected(&mut self, cx: &mut Context<Self>) {
515 if self.exporting().is_some() {
516 return;
517 }
518 match (&mut self.session, self.selected.take()) {
519 (Some(session), Some((lane, idx))) => {
520 if session.lift_clip(lane, idx) {
521 self.reset_after_reseek();
522 } else {
523 self.notice = Some("NOTHING LIFTED — the timeline cannot be emptied".into());
524 }
525 }
526 (Some(_), None) => {
527 self.notice = Some("NOTHING LIFTED — click the half to remove first".into())
528 }
529 (None, _) => {}
530 }
531 cx.notify();
532 }
533
534 /// Copies the selected clip. Nothing on screen changes, so no notify.
535 fn copy_selected(&mut self) {
536 let session = self.session.as_ref();
537 // Out of the lane it was clicked in: the audio half of a group is a
538 // different clip from the video one, and copying the wrong lane's
539 // frames is a paste of the wrong thing.
540 if let Some(clip) = self
541 .selected
542 .and_then(|(lane, idx)| session?.lane_clips(lane).get(idx).copied())
543 {
544 self.clipboard = Some(clip);
545 }
546 }
547
548 /// Starts a peak decode -- and a stream probe -- for every source that has
549 /// arrived since the last
550 /// repaint. One call from the render rather than three at the doors,
551 /// because argv, an import and a project load are all doors and only this
552 /// one is guaranteed to run after each of them.
553 ///
554 /// The decode itself runs on a background thread, like the file chooser:
555 /// whole-file audio decode is ~1 s for a half-hour source, and on the render
556 /// path that is the window not painting for a second. The lane draws a bed
557 /// meanwhile and the repaint comes with the peaks. The entry is written
558 /// *before* the spawn, so the sixty repaints that happen while a decode runs
559 /// start no further ones.
560 fn cache_media(&mut self, cx: &mut Context<Self>) {
561 let Some(session) = &self.session else {
562 return;
563 };
564 // Which audio streams each file has, for the library's rows. Header
565 // only, but a big file's sample tables are not free to parse, so it
566 // goes off the render thread like the peaks do.
567 for path in unseen_paths(session.sources(), &self.streams) {
568 self.streams.insert(path.clone(), Vec::new());
569 let probed = cx.background_executor().spawn({
570 let path = path.clone();
571 async move { engine::AudioSession::probe_streams(&path).unwrap_or_default() }
572 });
573 cx.spawn(async move |this, cx| {
574 let probed = probed.await;
575 this.update(cx, |this, cx| {
576 this.streams.insert(path, probed);
577 cx.notify();
578 })
579 .ok();
580 })
581 .detach();
582 }
583 for key in unseen_sources(session.sources(), &self.waves) {
584 self.waves.insert(key.clone(), Wave::Loading);
585 let decoded = cx.background_executor().spawn({
586 let (path, stream) = key.clone();
587 async move {
588 engine::waveform::peaks(&path, stream, WAVE_BPS)
589 .ok()
590 .flatten()
591 .map(|peaks| Arc::new(normalise(peaks)))
592 }
593 });
594 cx.spawn(async move |this, cx| {
595 let decoded = decoded.await;
596 this.update(cx, |this, cx| {
597 this.waves.insert(
598 key,
599 match decoded {
600 Some(peaks) => Wave::Peaks(peaks),
601 // Either no audio track or a file we could not read
602 // it from; both mean the lane has nothing to draw,
603 // and neither is worth asking about again.
604 None => Wave::Silent,
605 },
606 );
607 cx.notify();
608 })
609 .ok();
610 })
611 .detach();
612 }
613 }
614
615 /// The group id of the clicked clip, which is what marks the other half.
616 fn selected_link(&self) -> Option<u32> {
617 let (lane, idx) = self.selected?;
618 self.session.as_ref()?.lane_clips(lane).get(idx)?.link
619 }
620
621 /// Drops the copied clip in at the playhead. The engine reseeks itself, so
622 /// like a delete this owes the flag reset -- and the selection, whose index
623 /// the insert has just moved.
624 fn paste(&mut self, cx: &mut Context<Self>) {
625 let pasted = match (&mut self.session, self.clipboard) {
626 (Some(session), Some(clip)) => session.paste_at(session.now(), clip),
627 _ => false,
628 };
629 if pasted {
630 self.selected = None;
631 self.reset_after_reseek();
632 }
633 cx.notify();
634 }
635
636 /// The one way a library row reaches the timeline: the Add button and a row
637 /// dragged onto a lane both come here, so there is a single answer to what
638 /// "add this source" does. The whole source goes in at the playhead as one
639 /// grouped take -- the same insert a paste makes, so everything after it
640 /// moves along rather than being painted over. Reseeks like every other
641 /// edit, and drops the timeline's selection with it: the insert has just
642 /// moved the indices it pointed at.
643 fn insert_source(&mut self, path: &Path, stream: usize, cx: &mut Context<Self>) {
644 if self.exporting().is_some() {
645 return;
646 }
647 let frames = self.session.as_ref().map_or(0, |session| {
648 source_frames(lane_clips(session), session.sources(), path)
649 });
650 // Zero means nothing on the timeline plays from that file any more
651 // -- an undone import leaves the source entry behind (project.rs:264)
652 // -- so there is no length to insert and no file to ask for one.
653 let placed = match (&mut self.session, frames) {
654 (Some(session), 1..) => session.place_stream_at(session.now(), path, stream, frames),
655 _ => Ok(false),
656 };
657 match placed {
658 Ok(true) => {
659 self.selected = None;
660 self.reset_after_reseek();
661 }
662 // The engine's own words: a stream that cannot join this timeline
663 // says which property disagrees, exactly as a refused import does.
664 Err(e) => self.notice = Some(format!("NOTHING ADDED — {e}").into()),
665 Ok(false) => {
666 self.notice = Some(
667 "NOTHING ADDED — no clip on the timeline plays from that file any more".into(),
668 )
669 }
670 }
671 cx.notify();
672 }
673
674 /// The rate and layout the whole timeline's audio is, taken from source 0's
675 /// own stream: what a library row has to match to be placeable. `None`
676 /// until that file has been probed, and then nothing is greyed for it.
677 fn timeline_audio(&self) -> Option<(u32, u16)> {
678 let first = self.session.as_ref()?.sources().first()?;
679 let info = self
680 .streams
681 .get(&first.path)?
682 .iter()
683 .find(|s| s.index == first.audio_stream)?;
684 Some((info.sample_rate, info.channels))
685 }
686
687 /// Appends a file to the end of the timeline. A drop is not a key press, so
688 /// the export guard on the key handler does not cover it and this checks for
689 /// itself. The engine reseeks, so like a delete it owes the flag reset; a
690 /// refusal is shown as the engine worded it and changes nothing.
691 fn import(&mut self, path: &std::path::Path, cx: &mut Context<Self>) {
692 if self.exporting().is_some() {
693 return;
694 }
695 // An empty window has nothing to append to: there the first file *is*
696 // the timeline and is opened as one, which is the same fork a launch
697 // makes between its first argument and the rest.
698 let text = match self.session.as_mut().map(|session| session.import(path)) {
699 Some(Ok(())) => {
700 self.reset_after_reseek();
701 format!("IMPORTED {}", file_name(path))
702 }
703 Some(Err(e)) => format!("IMPORT FAILED: {e}"),
704 None => self.open_media(path),
705 };
706 eprintln!("{text}");
707 self.notice = Some(text.into());
708 cx.notify();
709 }
710
711 /// Takes a file as the whole timeline, which is what an empty window is
712 /// waiting for. Everything derived from the media -- the clock, the title,
713 /// where an export and a save go -- is set here, exactly as a launch with a
714 /// file argument sets it. Paused with its first frame showing, like every
715 /// other way a timeline arrives.
716 fn open_media(&mut self, path: &std::path::Path) -> String {
717 match PlaybackSession::open(path) {
718 Ok(session) => {
719 self.fps = session.meta().frame_rate;
720 // Read before the session moves: a file that plays silent says
721 // so here or nowhere.
722 let silent = audio_notice(&session);
723 self.session = Some(session);
724 // A fresh session comes up at full volume; the player's own
725 // setting outlives the file, so it is pushed at every new one.
726 self.apply_volume();
727 self.export_path = export_path(path);
728 self.project_path = project_path(path);
729 self.name = file_name(path).into();
730 self.reset_after_reseek();
731 format!("OPENED {}{}", file_name(path), silent.unwrap_or_default())
732 }
733 Err(e) => format!("OPEN FAILED: {e}"),
734 }
735 }
736
737 /// The Import button: asks the desktop for a path and takes it the same way
738 /// a drop would. The chooser is another process and the user may sit in it,
739 /// so it runs on a background thread -- blocking here would freeze the
740 /// window behind the dialog.
741 fn pick_and_import(&mut self, cx: &mut Context<Self>) {
742 if self.exporting().is_some() {
743 return;
744 }
745 let picked = cx.background_executor().spawn(async { pick_file() });
746 cx.spawn(async move |this, cx| {
747 let picked = picked.await;
748 this.update(cx, |this, cx| match picked {
749 // The same fork the drop handler makes: a project replaces the
750 // timeline, media is appended to it.
751 Ok(Some(path)) if is_project(&path) => this.load_project(&path, cx),
752 Ok(Some(path)) => this.import(&path, cx),
753 // Cancelled: the user already knows what happened.
754 Ok(None) => {}
755 Err(text) => {
756 eprintln!("{text}");
757 this.notice = Some(text.into());
758 cx.notify();
759 }
760 })
761 .ok();
762 })
763 .detach();
764 }
765
766 /// Swaps the whole timeline for one restored from a `.edith`. Like an
767 /// import this arrives by drop and so checks the export guard for itself.
768 /// The new session is built before anything is replaced, so a refusal is
769 /// shown as the engine worded it and leaves what is playing alone.
770 fn load_project(&mut self, path: &std::path::Path, cx: &mut Context<Self>) {
771 if self.exporting().is_some() {
772 return;
773 }
774 let text = match PlaybackSession::open_project(path) {
775 Ok(session) => {
776 self.fps = session.meta().frame_rate;
777 let silent = audio_notice(&session);
778 // A project is named after itself but still exports beside its
779 // media: that is the only place an export has ever landed.
780 self.export_path = export_path(&session.sources()[0].path);
781 self.session = Some(session);
782 self.apply_volume();
783 self.project_path = path.to_path_buf();
784 self.name = file_name(path).into();
785 // A copied clip names its source by index, which means a
786 // different file -- or none -- in another project.
787 self.clipboard = None;
788 self.selected = None;
789 // A menu can be up while a project is dropped on the window --
790 // the scrim swallows clicks, never a drop -- and its index
791 // would name some other timeline's clip.
792 self.context_menu = None;
793 // A different set of sources: the row that was picked is not
794 // the file that index names any more.
795 self.selected_asset = None;
796 // The counters describe one timeline; the eof line must not
797 // report the old one's frames against the new one.
798 self.displayed = 0;
799 self.dropped = 0;
800 self.started = None;
801 // Loaded paused at its saved playhead, so the still it owes
802 // reaches the screen the way a seek's does. The old picture is
803 // released by the swap in `pump`, as after any other seek.
804 self.reset_after_reseek();
805 format!("LOADED {}{}", file_name(path), silent.unwrap_or_default())
806 }
807 Err(e) => format!("OPEN FAILED: {e}"),
808 };
809 eprintln!("{text}");
810 self.notice = Some(text.into());
811 cx.notify();
812 }
813
814 /// Writes the timeline back to its project file. Overwrites silently, like
815 /// an export: the path was chosen once and the notice is the confirmation.
816 fn save_project(&mut self, cx: &mut Context<Self>) {
817 let saved = self
818 .session
819 .as_ref()
820 .map(|session| session.save_project(&self.project_path));
821 let text = match saved {
822 Some(Ok(())) => format!("SAVED {}", file_name(&self.project_path)),
823 Some(Err(e)) => format!("SAVE FAILED: {e}"),
824 None => "NOTHING TO SAVE — open a file first".to_string(),
825 };
826 eprintln!("{text}");
827 self.notice = Some(text.into());
828 cx.notify();
829 }
830
831 fn undo(&mut self, cx: &mut Context<Self>) {
832 if self.session.as_mut().is_some_and(PlaybackSession::undo) {
833 self.reset_after_reseek();
834 }
835 self.selected = None;
836 cx.notify();
837 }
838
839 /// The stroke a waiting row was after: it becomes the whole of what reaches
840 /// that action, which is what the row was showing. A chord another action
841 /// already holds is refused by the keymap and the row keeps waiting, so the
842 /// next stroke is another try rather than a lost one. A binding that took
843 /// holds either way:
844 /// what a failed write costs is only the next run, which is what the notice
845 /// is for.
846 fn capture(&mut self, action: ActionId, key: &str, ctrl: bool) {
847 let chord = keymap::Chord {
848 key: key.to_string(),
849 ctrl,
850 };
851 let text = match self.keymap.rebind_action(action, chord.clone()) {
852 Ok(()) => {
853 self.rebinding = None;
854 match self.keymap.save() {
855 Ok(()) => return,
856 Err(e) => format!(
857 "KEYBINDINGS NOT SAVED — {}: {e}",
858 Keymap::config_path().display()
859 ),
860 }
861 }
862 Err(holder) => format!("ALREADY BOUND — {} is {}", chord.pretty(), holder.label()),
863 };
864 eprintln!("{text}");
865 self.notice = Some(text.into());
866 }
867
868 /// Seeks to where the pointer sits along the ruler. `commit` is the press
869 /// and the release, which must land exactly even when the throttle below
870 /// would have skipped them.
871 fn scrub_to(&mut self, x: Pixels, commit: bool, cx: &mut Context<Self>) {
872 let Some(session) = &self.session else {
873 return;
874 };
875 let t = f64::from(frac_along(x, self.ruler.get())) * session.timeline_duration();
876 let target = (t * self.fps) as u32;
877 if commit || scrub_due(target, self.last_target, self.last_scrub.elapsed()) {
878 self.last_target = target;
879 self.last_scrub = Instant::now();
880 self.seek(t, cx);
881 }
882 }
883
884 /// The play binding and the transport button share it: once the timeline is finished
885 /// the only sensible "play" is from the top.
886 /// Pushes the current volume at the session, which is the only place it is
887 /// ever pushed: after a change here, and after a session arrives. A session
888 /// starts at full volume, so a file opened while muted has to be told --
889 /// that is the whole reason this is not just called from the key handler.
890 /// Silent no-op with no timeline, or with a run that has no audio device.
891 fn apply_volume(&self) {
892 if let Some(session) = &self.session {
893 session.set_gain(self.volume.gain());
894 }
895 }
896
897 /// The mute key and the two volume keys, and the click on the button. The
898 /// picture is not touched: silencing the output is not pausing it, so the
899 /// clock -- which the device still drives -- runs straight through.
900 fn set_volume(&mut self, change: impl FnOnce(&mut Volume), cx: &mut Context<Self>) {
901 change(&mut self.volume);
902 self.apply_volume();
903 cx.notify();
904 }
905
906 fn toggle_or_restart(&mut self, cx: &mut Context<Self>) {
907 if self.exporting().is_some() {
908 return;
909 }
910 if self.done {
911 self.seek(0., cx);
912 if let Some(session) = &mut self.session {
913 session.play();
914 }
915 } else if let Some(session) = &mut self.session {
916 session.toggle();
917 // Past EOF nothing else asks for a repaint.
918 cx.notify();
919 }
920 }
921
922 /// The export that owns the UI, if any. A cancelled one does not: it has
923 /// its own copy of the edit list and owes only its own cleanup.
924 fn exporting(&self) -> Option<&ExportHandle> {
925 self.export.as_ref().filter(|_| !self.cancelling)
926 }
927
928 /// What the export action does now: opens the card, which is where the
929 /// quality, the destination and the decision to write at all are. Nothing
930 /// is encoded until the button in it is pressed.
931 fn open_export(&mut self, cx: &mut Context<Self>) {
932 if self.export.is_some() {
933 return;
934 }
935 // Nothing to write out, and a refusal rather than a card about it: the
936 // window is empty and the export path is not even chosen yet.
937 if self.session.is_none() {
938 self.notice = Some("NOTHING TO EXPORT — open a file first".into());
939 cx.notify();
940 return;
941 }
942 self.export_open = true;
943 // One card at a time, and a waiting row must not outlive the card it
944 // was waiting in.
945 self.keys_open = false;
946 self.rebinding = None;
947 cx.notify();
948 }
949
950 /// The card's Destination row: the desktop's save dialog, on a background
951 /// thread like the import chooser -- the user may sit in it and the window
952 /// behind must not freeze. No chooser at all leaves the default path, which
953 /// is what the refusal says.
954 fn pick_destination(&mut self, cx: &mut Context<Self>) {
955 let default = self.export_path.clone();
956 let picked = cx
957 .background_executor()
958 .spawn(async move { pick_save(&default) });
959 cx.spawn(async move |this, cx| {
960 let picked = picked.await;
961 this.update(cx, |this, cx| {
962 // The dialog outlives the card: an export started meanwhile
963 // took the old path and its notice must name what it wrote.
964 if this.export.is_some() {
965 return;
966 }
967 match picked {
968 Ok(Some(path)) => this.export_path = path,
969 // Cancelled: the default stands, as it did before.
970 Ok(None) => {}
971 Err(text) => {
972 eprintln!("{text}");
973 this.notice = Some(text.into());
974 }
975 }
976 cx.notify();
977 })
978 .ok();
979 })
980 .detach();
981 }
982
983 /// Writes the edit list out, at the settings the card was left at. Playback
984 /// stops first: the exporter opens its own decoder -- and, on the hardware
985 /// path, an encoder -- so a running player would only compete with it for
986 /// the GPU. A cancelled export still winding down holds this off for the
987 /// frame it takes to notice, which is what keeps its `remove_file` off the
988 /// new output.
989 fn start_export(&mut self, cx: &mut Context<Self>) {
990 if self.export.is_some() {
991 return;
992 }
993 let settings = export_settings(self.quality, self.custom_mbps);
994 let Some(session) = &mut self.session else {
995 self.notice = Some("NOTHING TO EXPORT — open a file first".into());
996 cx.notify();
997 return;
998 };
999 session.pause();
1000 self.export = Some(session.export_to_with(&self.export_path, &settings));
1001 // The card has been answered; the progress line takes the panel from
1002 // here, and it is the running export's escape that matters now.
1003 self.export_open = false;
1004 cx.notify();
1005 }
1006
1007 /// Gives the editor back at once and leaves the worker to stop at its next
1008 /// frame and delete what it has written.
1009 fn cancel_export(&mut self) {
1010 if let Some(export) = &self.export {
1011 export.cancel();
1012 self.cancelling = true;
1013 }
1014 }
1015
1016 /// Takes the export's verdict once it has one. The only place the app
1017 /// touches the handle's completion side.
1018 fn poll_export(&mut self) {
1019 let Some(result) = self.export.as_ref().and_then(ExportHandle::result) else {
1020 return;
1021 };
1022 self.export = None;
1023 // A cancellation is reported as an error, and the one who asked for it
1024 // has had the editor back since the keystroke. Nothing to say.
1025 if std::mem::take(&mut self.cancelling) {
1026 return;
1027 }
1028 let text = match result {
1029 Ok(()) => format!("EXPORT DONE → {}", file_name(&self.export_path)),
1030 Err(e) => format!("EXPORT FAILED: {e}"),
1031 };
1032 eprintln!("{text}");
1033 self.notice = Some(text.into());
1034 }
1035}
1036
1037impl Render for Player {
1038 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
1039 // A file that has just been opened sits on its first frame with the
1040 // clock stopped: opening is not playing, whichever way the file
1041 // arrived. The play binding and the transport button start it.
1042 if let Some(session) = &mut self.session {
1043 session.tick();
1044 }
1045 self.pump(window);
1046 self.poll_export();
1047 // Every way a source can arrive -- argv, an import, a project load --
1048 // has been through a repaint by the time its clips are drawn, so this
1049 // is the one place that has to notice a new one.
1050 self.cache_media(cx);
1051 // What the compositor calls this window. Pushed only when it changes:
1052 // it is a protocol round trip and this runs at vsync.
1053 let title = window_title(&self.name);
1054 if title != self.titled {
1055 window.set_window_title(&title);
1056 self.titled = title;
1057 }
1058 // No shadow flag: the clock is the only truth about play state.
1059 let playing = self
1060 .session
1061 .as_ref()
1062 .is_some_and(PlaybackSession::is_playing);
1063 // A paused timeline has nothing to animate; the toggle handlers notify,
1064 // which is what starts the loop again. A paused seek keeps the loop
1065 // running by itself until `pump` has the frame it asked for. An export
1066 // pauses playback and still needs the loop: its progress only reaches
1067 // the screen on a repaint. A notice does not: it waits to be dismissed
1068 // rather than for a clock, so keeping the loop alive for it would spin
1069 // the GPU until someone answered it.
1070 if (playing && !self.done) || self.pending_seek || self.export.is_some() {
1071 window.request_animation_frame();
1072 }
1073
1074 // Read per render, never cached: a delete shortens the timeline and the
1075 // timecode, the ruler and the clamp below all have to follow it.
1076 let duration = self
1077 .session
1078 .as_ref()
1079 .map_or(0., PlaybackSession::timeline_duration);
1080 // The clock keeps running after the last frame (wall time takes over at
1081 // audio EOF) while the picture is frozen, so the timeline the UI shows is
1082 // the clamped one, pinned to the out-point once playback is done.
1083 let position = if self.done {
1084 duration
1085 } else {
1086 self.session
1087 .as_ref()
1088 .map_or(0., PlaybackSession::now)
1089 .clamp(0., duration)
1090 };
1091
1092 div()
1093 .track_focus(&self.focus)
1094 .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| {
1095 // `is_held` filters auto-repeat, which would otherwise toggle
1096 // playback -- or cut the timeline -- many times a second.
1097 if event.is_held {
1098 return;
1099 }
1100 // Any key retires the last message, whatever it was -- and owes
1101 // the repaint itself: a notice no longer keeps the render loop
1102 // alive, and the arms below that do notify are not all of them
1103 // (an unbound key, or the copy chord, changes nothing else).
1104 if this.notice.take().is_some() {
1105 cx.notify();
1106 }
1107 let key = event.keystroke.key.as_str();
1108 // A row is waiting for a stroke, and while it is, that stroke is
1109 // data: it means the binding and nothing else, which is why this
1110 // answers before the export guard and before the keymap is
1111 // consulted at all.
1112 if let Some(action) = this.rebinding {
1113 if key == ESCAPE {
1114 this.rebinding = None;
1115 } else if !is_bare_modifier(key) {
1116 this.capture(action, key, event.keystroke.modifiers.control);
1117 }
1118 cx.notify();
1119 return;
1120 }
1121 // On linux gpui reports the copy chord as key "c" with the
1122 // control modifier set (the control code is mapped back), which
1123 // is why the keymap is keyed on the pair and never on the key
1124 // alone.
1125 let action = this.keymap.lookup(key, event.keystroke.modifiers.control);
1126 // An export is reading the edit list every other action here
1127 // would change, so cancelling is the only one that means
1128 // anything until it is over.
1129 if this.exporting().is_some() {
1130 if cancels_export(key, action) {
1131 this.cancel_export();
1132 }
1133 cx.notify();
1134 return;
1135 }
1136 // The overlay owns the keyboard while it is up: a stroke aimed
1137 // at a row must not also cut the timeline, and the way out of it
1138 // is the same key that gets out of a capture.
1139 if this.keys_open {
1140 if key == ESCAPE {
1141 this.keys_open = false;
1142 cx.notify();
1143 }
1144 return;
1145 }
1146 // The export card owns it the same way, and for the same
1147 // reason. Escape closes it -- nothing has been written yet, so
1148 // there is nothing here to cancel -- and a digit is the custom
1149 // bitrate being typed: the card has no text field (nothing in
1150 // it takes focus, ledger:182) so this listener is its input,
1151 // exactly as it is a waiting row's.
1152 if this.export_open {
1153 if key == ESCAPE {
1154 this.export_open = false;
1155 } else if let Ok(digit) = key.parse::<u32>() {
1156 this.custom_mbps = push_digit(this.custom_mbps, digit);
1157 this.quality = Quality::Custom;
1158 } else if key == "backspace" {
1159 this.custom_mbps /= 10;
1160 this.quality = Quality::Custom;
1161 }
1162 cx.notify();
1163 return;
1164 }
1165 // A clip menu names an index, and every edit below moves
1166 // indices -- so a stroke closes it before it acts. Escape means
1167 // that and nothing else, which is the `esc` the keys menu
1168 // already lists (keymap.rs `FIXED`).
1169 if this.context_menu.take().is_some() {
1170 cx.notify();
1171 if key == ESCAPE {
1172 return;
1173 }
1174 }
1175 if let Some(action) = action {
1176 this.act(action, cx);
1177 }
1178 }))
1179 // The whole window is the drop target: gpui turns an external file
1180 // drop into an `ExternalPaths` drag (window.rs:3626) delivered as a
1181 // mouse-up to every hovered hitbox, and the root's is the only one
1182 // that covers the picture as well as the panel.
1183 .on_drop(cx.listener(|this, paths: &gpui::ExternalPaths, _, cx| {
1184 // The overlay owns the pointer as well as the keyboard, and a
1185 // drop is a click the scrim cannot swallow: gpui delivers it to
1186 // the root's hitbox, which is under the scrim but is not a
1187 // sibling it can stop. The export card is over the timeline for
1188 // the same reason: importing under it would change the very
1189 // edit list the card is about to write out.
1190 if this.keys_open || this.export_open {
1191 return;
1192 }
1193 for path in paths.paths() {
1194 // A project replaces the timeline, media is appended to it.
1195 if is_project(path) {
1196 this.load_project(path, cx);
1197 } else {
1198 this.import(path, cx);
1199 }
1200 }
1201 }))
1202 // Scrubbing is tracked on the root because the pointer leaves the
1203 // 6 px ruler on the first drag and its own listeners then stop
1204 // firing; the root's hitbox is the whole window.
1205 .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _, cx| {
1206 if !this.scrubbing {
1207 return;
1208 }
1209 if event.pressed_button == Some(MouseButton::Left) {
1210 this.scrub_to(event.position.x, false, cx);
1211 } else {
1212 // A release outside the window never reaches the handler
1213 // below, so the first button-up move is when we learn the
1214 // drag is over. Without this the next hover would scrub.
1215 this.scrubbing = false;
1216 }
1217 }))
1218 .on_mouse_up(
1219 MouseButton::Left,
1220 cx.listener(|this, event: &MouseUpEvent, _, cx| {
1221 if std::mem::take(&mut this.scrubbing) {
1222 this.scrub_to(event.position.x, true, cx);
1223 }
1224 }),
1225 )
1226 .size_full()
1227 .flex()
1228 .flex_col()
1229 .bg(rgb(LETTERBOX))
1230 .text_color(rgb(INK))
1231 .text_size(px(13.))
1232 .child(
1233 div()
1234 .flex_none()
1235 .h(px(HEADER_H))
1236 .flex()
1237 .items_center()
1238 .px(px(12.))
1239 .bg(rgb(CHROME))
1240 .child(self.name.clone()),
1241 )
1242 // The library beside the picture rather than under it: a media pool
1243 // is a column in every editor that has one, and the timeline below
1244 // already owns the full width. `library_w` is what keeps the
1245 // picture the majority of the row at every window size.
1246 .child(
1247 div()
1248 .flex_1()
1249 .min_h(px(0.))
1250 .flex()
1251 .child(self.library(library_w(f32::from(window.viewport_size().width)), cx))
1252 .child(
1253 div()
1254 .flex_1()
1255 .min_w(px(0.))
1256 .overflow_hidden()
1257 .flex()
1258 .justify_center()
1259 .items_center()
1260 .children(
1261 self.image
1262 .clone()
1263 .map(|i| {
1264 img(i)
1265 .size_full()
1266 .object_fit(gpui::ObjectFit::Contain)
1267 .into_any_element()
1268 })
1269 // With no file open the letterbox is the
1270 // whole window, and a black rectangle says
1271 // only that something is broken -- so it
1272 // says what it wants instead. The window is
1273 // already the drop target.
1274 .or_else(|| {
1275 self.session
1276 .is_none()
1277 .then(|| empty_hint().into_any_element())
1278 }),
1279 ),
1280 ),
1281 )
1282 // Above the panel and only when there is one to show, so it costs
1283 // the picture nothing the rest of the time.
1284 .children(self.notice_bar(cx))
1285 .child(self.panel(position, duration, playing, cx))
1286 // Over the panel it was opened on, and under the cards: it is only
1287 // ever up while neither of them is (`modal`).
1288 .children(self.context_card(window.viewport_size(), cx))
1289 // Last, so they are over everything -- they take no room in the
1290 // column, and only one of the two is ever up.
1291 .children(self.keys_overlay(cx))
1292 .children(self.export_card(cx))
1293 }
1294}
1295
1296impl Player {
1297 /// The media library: a row per source the timeline knows, in the order
1298 /// they arrived, each wearing the tint its clips wear in the lanes -- the
1299 /// swatch *is* what says which boxes down there came from this file. A
1300 /// click picks a row, the button under the list drops that source in at the
1301 /// playhead, and a row dragged onto either lane does the same thing through
1302 /// the same call.
1303 ///
1304 /// Import lives here, because this is the list it adds to. Plain divs like
1305 /// the rest of this window: nothing in it takes focus, so the root keeps
1306 /// the keyboard and the play key still works after a row is clicked
1307 /// (ledger:182).
1308 fn library(&self, width: f32, cx: &mut Context<Self>) -> impl IntoElement {
1309 let exporting = self.exporting().is_some();
1310 let sources = self
1311 .session
1312 .as_ref()
1313 .map_or(&[][..], PlaybackSession::sources);
1314 // Every source matches the first in size and rate or it was refused at
1315 // the door (the import policy, ledger:436), so the session's own meta
1316 // describes every row and nothing has to be probed to say so.
1317 let meta = self.session.as_ref().map(PlaybackSession::meta);
1318 let clips: Vec<Clip> = self
1319 .session
1320 .as_ref()
1321 .map_or_else(Vec::new, |session| lane_clips(session).copied().collect());
1322 let rows: Vec<_> = library_rows(sources, &self.streams, self.timeline_audio(), |path| {
1323 source_frames(clips.iter(), sources, path)
1324 })
1325 .into_iter()
1326 .enumerate()
1327 .map(|(i, row)| {
1328 let picked = self
1329 .selected_asset
1330 .as_ref()
1331 .is_some_and(|p| *p == (row.path.clone(), row.stream));
1332 let name: SharedString = row.name.clone().into();
1333 let tip: SharedString = match (&row.unusable, meta) {
1334 // A greyed row says why in full, where its length would be:
1335 // the list is the one place the file's own tracks are named.
1336 (Some(why), _) => format!("{} — {why}", row.path.display()),
1337 (None, Some(meta)) => format!(
1338 "{} — {}x{} @ {:.2} fps · drag onto a lane, or Add at playhead",
1339 row.path.display(),
1340 meta.width,
1341 meta.height,
1342 meta.frame_rate
1343 ),
1344 (None, None) => row.path.display().to_string(),
1345 }
1346 .into();
1347 let ghost = name.clone();
1348 // What the second line says: the stream, then either its length or
1349 // the reason it cannot be used.
1350 let under = match &row.unusable {
1351 Some(why) => join_detail(&row.detail, why),
1352 None => join_detail(
1353 &row.detail,
1354 &timecode(f64::from(row.frames) / self.fps, self.fps),
1355 ),
1356 };
1357 let usable = row.unusable.is_none();
1358 let (path, stream) = (row.path.clone(), row.stream);
1359 let dragged = (path.clone(), stream);
1360 div()
1361 .id(("asset", i))
1362 .flex_none()
1363 .h(px(ROW_H))
1364 .flex()
1365 .items_center()
1366 .gap(px(6.))
1367 .pr(px(6.))
1368 .rounded(px(3.))
1369 // A row that cannot be placed takes no click and no drag, and
1370 // reads as unavailable rather than merely unlucky.
1371 .when(!usable, |d| d.text_color(rgb(INK_DIM)).opacity(0.55))
1372 .when(usable, |d| {
1373 d.cursor_pointer()
1374 .hover(|s| s.bg(rgb(HOVER)))
1375 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
1376 this.selected_asset = Some((path.clone(), stream));
1377 cx.notify();
1378 }))
1379 // The drag carries the row's file and stream and the
1380 // row's name: one for the drop to insert, one for the
1381 // pointer to carry, so what is being dragged is legible
1382 // on the way down.
1383 .on_drag(AssetDrag(dragged.0, dragged.1), move |_, _, _, cx| {
1384 cx.new(|_| Tip(ghost.clone()))
1385 })
1386 })
1387 .when(picked, |d| d.bg(rgb(SELECTED)).border_1())
1388 .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())
1389 // Full height and hard against the edge: the tint reads as
1390 // the lane's colour continuing into the list, not as a chip
1391 // that happens to be near it.
1392 .child(
1393 div()
1394 .flex_none()
1395 .w(px(SWATCH_W))
1396 .h_full()
1397 .rounded(px(2.))
1398 .bg(rgb(source_tint(row.tint))),
1399 )
1400 .child(
1401 div()
1402 .flex_1()
1403 .min_w(px(0.))
1404 .flex()
1405 .flex_col()
1406 // Two lines rather than two columns: at the width
1407 // this panel yields to, a name and a timecode side
1408 // by side leave room for neither.
1409 .child(div().truncate().text_size(px(11.)).child(name))
1410 .child(
1411 div()
1412 .truncate()
1413 .text_size(px(10.))
1414 .text_color(rgb(INK_DIM))
1415 .child(under),
1416 ),
1417 )
1418 })
1419 .collect();
1420 div()
1421 .flex_none()
1422 .w(px(width))
1423 .h_full()
1424 .flex()
1425 .flex_col()
1426 .gap(px(6.))
1427 .p(px(8.))
1428 .bg(rgb(CHROME))
1429 .child(
1430 div()
1431 .flex_none()
1432 .flex()
1433 .items_center()
1434 .gap(px(6.))
1435 .child(
1436 div()
1437 .flex_1()
1438 .min_w(px(0.))
1439 .truncate()
1440 .text_size(px(11.))
1441 .text_color(rgb(INK_DIM))
1442 .child("Media"),
1443 )
1444 .child(control(
1445 "import",
1446 None,
1447 "Import",
1448 "opens a file chooser — or drop a file on the window".to_string(),
1449 !exporting,
1450 cx.listener(|this, _: &ClickEvent, _, cx| this.pick_and_import(cx)),
1451 )),
1452 )
1453 .child(
1454 div()
1455 .id("library-rows")
1456 .flex_1()
1457 .min_h(px(0.))
1458 .flex()
1459 .flex_col()
1460 .gap(px(2.))
1461 .overflow_y_scroll()
1462 // Never a blank column: with nothing imported the list is
1463 // where the way in is said.
1464 .when(rows.is_empty(), |d| {
1465 d.child(
1466 div()
1467 .text_size(px(11.))
1468 .text_color(rgb(INK_DIM))
1469 .child("No media yet — Import, or drop a file on the window"),
1470 )
1471 })
1472 .children(rows),
1473 )
1474 .child(control(
1475 "add-asset",
1476 None,
1477 "Add at playhead",
1478 match self.selected_asset {
1479 Some(_) => "inserts the picked file at the playhead".to_string(),
1480 None => "click a file above first — or drag one onto a lane".to_string(),
1481 },
1482 can_add(
1483 self.selected_asset.as_ref(),
1484 self.session.is_some(),
1485 exporting,
1486 ),
1487 cx.listener(|this, _: &ClickEvent, _, cx| {
1488 if let Some((path, stream)) = this.selected_asset.clone() {
1489 this.insert_source(&path, stream, cx);
1490 }
1491 }),
1492 ))
1493 }
1494
1495 /// Transport, edit and file buttons, timecode, playhead, clips lane.
1496 fn panel(
1497 &self,
1498 position: f64,
1499 duration: f64,
1500 playing: bool,
1501 cx: &mut Context<Self>,
1502 ) -> impl IntoElement {
1503 let filled = if duration > 0. {
1504 (position / duration) as f32
1505 } else {
1506 0.
1507 };
1508 // An export owns the hint slot and the ruler while it runs: the
1509 // percentage and the accent bar are the same number, so the playhead
1510 // fill doubles as the progress bar for free.
1511 let exporting = self.exporting().is_some();
1512 // Everything but Import and Keys needs a timeline to act on: with none
1513 // open they are dimmed rather than silently doing nothing.
1514 let live = self.session.is_some() && !exporting;
1515 let key = |action| self.keymap.display(action);
1516 let (hint, filled) = if let Some(export) = self.exporting() {
1517 let progress = export.progress();
1518 (
1519 format!(
1520 "EXPORTING {}% — {} cancels",
1521 (progress * 100.) as u32,
1522 key(ActionId::CancelExport)
1523 ),
1524 progress,
1525 )
1526 } else {
1527 // The strokes no button carries; the rest ride on the buttons'
1528 // tooltips. Keys first: at a 640 px window the tail is what a
1529 // truncation eats, and the two hints at the end are also on the
1530 // ruler's and Import's tooltips.
1531 (
1532 format!(
1533 "{} copy · {} paste · {} undo · click the bar to seek · drop a file to import",
1534 key(ActionId::Copy),
1535 key(ActionId::Paste),
1536 key(ActionId::Undo)
1537 ),
1538 filled,
1539 )
1540 };
1541 div()
1542 .flex_none()
1543 .h(px(PANEL_H))
1544 .flex()
1545 .flex_col()
1546 .gap(px(8.))
1547 .px(px(12.))
1548 .py(px(8.))
1549 .bg(rgb(CHROME))
1550 // Transport | edit | file: three groups, so the eye can skip two of
1551 // them. Every button says what it does; the tooltip adds its key.
1552 .child(
1553 div()
1554 .flex_none()
1555 .flex()
1556 .items_center()
1557 .gap(px(8.))
1558 .child(control(
1559 "transport",
1560 Some(transport_glyph(playing).into_any_element()),
1561 if playing { "Pause" } else { "Play" },
1562 key(ActionId::Play),
1563 live,
1564 cx.listener(|this, _: &ClickEvent, _, cx| this.toggle_or_restart(cx)),
1565 ))
1566 .child(separator())
1567 .child(control(
1568 "cut",
1569 Some(cut_glyph().into_any_element()),
1570 "Cut",
1571 format!(
1572 "{} — splits the clip under the playhead",
1573 key(ActionId::Cut)
1574 ),
1575 live,
1576 cx.listener(|this, _: &ClickEvent, _, cx| this.cut(cx)),
1577 ))
1578 .child(control(
1579 "delete",
1580 Some(delete_glyph().into_any_element()),
1581 "Delete",
1582 if self.selected.is_some() {
1583 key(ActionId::Delete)
1584 } else {
1585 format!("{} — click a clip below first", key(ActionId::Delete))
1586 },
1587 live && self.selected.is_some(),
1588 cx.listener(|this, _: &ClickEvent, _, cx| this.delete_selected(cx)),
1589 ))
1590 // With the transport, not the edit group: it changes what
1591 // the file sounds like, never what it is. Reads as its own
1592 // state, so muted is legible without a tooltip.
1593 .child(control(
1594 "volume",
1595 None,
1596 self.volume.label(),
1597 format!(
1598 "{} mutes · {} louder · {} quieter",
1599 key(ActionId::ToggleMute),
1600 key(ActionId::VolumeUp),
1601 key(ActionId::VolumeDown)
1602 ),
1603 live,
1604 cx.listener(|this, _: &ClickEvent, _, cx| {
1605 this.set_volume(|volume| volume.muted = !volume.muted, cx)
1606 }),
1607 ))
1608 .child(separator())
1609 // Import is not here: it belongs to the media list it adds
1610 // to, and two doors into one action is a question about
1611 // which one is the real one.
1612 .child(control(
1613 "export",
1614 None,
1615 "Export",
1616 format!(
1617 "{} — quality and destination, then writes the timeline out",
1618 key(ActionId::Export)
1619 ),
1620 live && self.export.is_none(),
1621 cx.listener(|this, _: &ClickEvent, _, cx| this.open_export(cx)),
1622 ))
1623 .child(control(
1624 "save",
1625 None,
1626 "Save",
1627 format!("{} — writes the project file", key(ActionId::Save)),
1628 live,
1629 cx.listener(|this, _: &ClickEvent, _, cx| this.save_project(cx)),
1630 ))
1631 // No shortcut of its own -- and closed while an export runs,
1632 // which is what keeps a waiting row from swallowing the
1633 // escape the progress line promises cancels the export.
1634 .child(control(
1635 "keys",
1636 None,
1637 "Keys",
1638 "show and change the keybindings".to_string(),
1639 !exporting,
1640 cx.listener(|this, _: &ClickEvent, _, cx| {
1641 this.keys_open = !this.keys_open;
1642 this.rebinding = None;
1643 // One card at a time, both ways round.
1644 this.export_open = false;
1645 cx.notify();
1646 }),
1647 )),
1648 )
1649 .child(
1650 div()
1651 .flex_none()
1652 .flex()
1653 .items_center()
1654 .gap(px(12.))
1655 // Fixed width and one line: changing digits must not push
1656 // the row around, nor wrap and change its height.
1657 .child(div().flex_none().w(px(TIME_W)).truncate().child(format!(
1658 "{} / {}",
1659 timecode(position, self.fps),
1660 timecode(duration, self.fps)
1661 )))
1662 .child(
1663 div()
1664 .flex_1()
1665 .min_w(px(0.))
1666 .truncate()
1667 .text_size(px(11.))
1668 .text_color(rgb(INK_DIM))
1669 .child(hint),
1670 ),
1671 )
1672 // Press to seek, drag to scrub: the move and release halves live on
1673 // the root, since the pointer leaves the bar immediately. The bar
1674 // stays 6 px to look at; the strip that takes the click is 24, so
1675 // it can be hit without aiming (WCAG 2.5.8).
1676 .child(
1677 div()
1678 .flex_none()
1679 .flex()
1680 .gap(px(HEADER_GAP))
1681 // The lanes' header column, empty here: the ruler's own bar
1682 // has to start where their beds start, or the playhead
1683 // would point at a different moment in each row.
1684 .child(div().flex_none().w(px(HEADER_W)))
1685 .child(
1686 div()
1687 .id("ruler")
1688 .flex_1()
1689 .min_w(px(0.))
1690 .h(px(RULER_HIT_H))
1691 .flex()
1692 .flex_col()
1693 .justify_center()
1694 .rounded(px(3.))
1695 .cursor_pointer()
1696 .hover(|s| s.bg(rgb(HOVER_DIM)))
1697 // The strip carries no text, so the tooltip is the only
1698 // place it can say what it is.
1699 .tooltip(|_, cx| cx.new(|_| Tip("Seek — click or drag".into())).into())
1700 .on_mouse_down(
1701 MouseButton::Left,
1702 cx.listener(|this, event: &MouseDownEvent, _, cx| {
1703 this.scrubbing = true;
1704 this.scrub_to(event.position.x, true, cx);
1705 }),
1706 )
1707 .child(
1708 div()
1709 .w_full()
1710 .h(px(6.))
1711 .rounded(px(3.))
1712 .bg(rgb(SURFACE))
1713 .child(bounds_probe(self.ruler.clone()))
1714 .child(
1715 div()
1716 .h_full()
1717 .w(relative(filled))
1718 .rounded(px(3.))
1719 .bg(rgb(ACCENT)),
1720 ),
1721 ),
1722 ),
1723 )
1724 .child(self.lane_row(Lane::Video, "V1", duration, filled, cx))
1725 .child(self.lane_row(Lane::Audio, "A1", duration, filled, cx))
1726 }
1727
1728 /// A notice holds its own bar, full width, until it is answered: any key
1729 /// retires it (the key handler) and so does a click on it. Its own surface
1730 /// because the message is the point -- a failure cut to the timecode's slot
1731 /// is a failure nobody read.
1732 fn notice_bar(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
1733 let notice = self.notice.clone()?;
1734 Some(
1735 div()
1736 .id("notice")
1737 .flex_none()
1738 .flex()
1739 .items_start()
1740 .gap(px(12.))
1741 .px(px(12.))
1742 .py(px(6.))
1743 .bg(rgb(SURFACE))
1744 .cursor_pointer()
1745 .hover(|s| s.bg(rgb(HOVER)))
1746 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
1747 this.notice = None;
1748 cx.notify();
1749 }))
1750 .child(div().flex_1().min_w(px(0.)).child(notice))
1751 .child(
1752 div()
1753 .flex_none()
1754 .text_size(px(11.))
1755 .text_color(rgb(INK_DIM))
1756 .child("click or press any key to dismiss"),
1757 ),
1758 )
1759 }
1760
1761 /// Every binding, and the way to change one: a row per entry, click it and
1762 /// the next stroke becomes its chord. Over the whole window, because while
1763 /// it is up nothing under it may answer -- the scrim stops the clicks
1764 /// (gpui dispatches mouse listeners topmost-first, window.rs:3705) and the
1765 /// key handler's own branch stops the strokes.
1766 ///
1767 /// Plain divs, like every control here: nothing in it takes focus, so the
1768 /// root is still the one reading the keyboard -- which is exactly what a
1769 /// waiting row depends on.
1770 fn keys_overlay(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
1771 if !self.keys_open {
1772 return None;
1773 }
1774 // The way out, spelled the way the rows spell a chord.
1775 let out = keymap::Chord {
1776 key: ESCAPE.to_string(),
1777 ctrl: false,
1778 }
1779 .pretty();
1780 // Every stroke that works, under its heading, and both halves of the
1781 // list come from the registry: one row per action -- an action with two
1782 // strokes reads as one line ("x or delete") and a rebind replaces that
1783 // whole set -- then the strokes the modal cards answer to, which are
1784 // shown but not offered, because nothing may unbind the way out.
1785 let mut rows: Vec<AnyElement> = Vec::new();
1786 for category in keymap::Category::ALL {
1787 let actions = ActionId::ALL
1788 .into_iter()
1789 .enumerate()
1790 .filter(|(_, a)| a.category() == category);
1791 let fixed = keymap::FIXED.iter().filter(|f| f.category == category);
1792 let mut headed = false;
1793 let mut head = |rows: &mut Vec<AnyElement>| {
1794 if !std::mem::replace(&mut headed, true) {
1795 rows.push(
1796 div()
1797 .flex_none()
1798 .px(px(6.))
1799 .pt(px(4.))
1800 .text_size(px(11.))
1801 .text_color(rgb(INK_DIM))
1802 .child(category.label())
1803 .into_any_element(),
1804 );
1805 }
1806 };
1807 for (i, action) in actions {
1808 head(&mut rows);
1809 let capturing = self.rebinding == Some(action);
1810 let out = out.clone();
1811 rows.push(
1812 div()
1813 .id(("bind", i))
1814 .flex()
1815 // The floor, not the height: a row that needed two lines
1816 // would otherwise paint over the one under it.
1817 .min_h(px(KEYS_ROW_H))
1818 .items_center()
1819 .justify_between()
1820 .gap(px(12.))
1821 .px(px(6.))
1822 .rounded(px(3.))
1823 .cursor_pointer()
1824 .hover(|s| s.bg(rgb(HOVER)))
1825 .when(capturing, |d| d.bg(rgb(SELECTED)))
1826 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
1827 this.rebinding = Some(action);
1828 cx.notify();
1829 }))
1830 .child(action.label())
1831 .child(if capturing {
1832 div()
1833 .text_color(rgb(INK_DIM))
1834 .child(format!("press a key — {out} cancels"))
1835 } else {
1836 div().child(self.keymap.display(action))
1837 })
1838 .into_any_element(),
1839 );
1840 }
1841 for f in fixed {
1842 head(&mut rows);
1843 rows.push(
1844 div()
1845 .flex()
1846 .min_h(px(KEYS_ROW_H))
1847 .items_center()
1848 .justify_between()
1849 .gap(px(12.))
1850 .px(px(6.))
1851 .child(f.label)
1852 // Dim, and no hover: this one is not a row you can click.
1853 .child(div().text_color(rgb(INK_DIM)).child(f.chord))
1854 .into_any_element(),
1855 );
1856 }
1857 }
1858 Some(
1859 div()
1860 .absolute()
1861 .inset_0()
1862 .flex()
1863 .justify_center()
1864 .items_center()
1865 // The picture behind is out of reach, and looks it. The press is
1866 // swallowed here so a button under the scrim cannot take it.
1867 .bg(rgba(0x101010cc))
1868 .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| {
1869 cx.stop_propagation()
1870 })
1871 .child(
1872 div()
1873 .w(px(KEYS_W))
1874 .flex()
1875 .flex_col()
1876 .gap(px(2.))
1877 .p(px(12.))
1878 .rounded(px(6.))
1879 .bg(rgb(SURFACE))
1880 // Title and instruction are two children, never one
1881 // wrapping line: a fixed-height slot whose text wrapped
1882 // painted its second line over the first row.
1883 .child(div().flex_none().px(px(6.)).child("Keybindings"))
1884 // One status line, under the title where the eye starts.
1885 // A refusal takes it over -- it is the more urgent of the
1886 // two, and the notice bar it would otherwise appear in is
1887 // under the scrim.
1888 //
1889 // The row list below is capped and scrolls, so neither a
1890 // wrapped refusal here nor another action added to `ALL`
1891 // can push the card past a 360 px window any more.
1892 .child(
1893 div()
1894 .flex_none()
1895 .px(px(6.))
1896 .text_size(px(11.))
1897 .text_color(rgb(INK_DIM))
1898 .child(
1899 self.notice
1900 .clone()
1901 .unwrap_or_else(|| "click a row, then press a key".into()),
1902 ),
1903 )
1904 // Capped and scrolling rather than as tall as the action
1905 // list happens to be: the list grows with the editor,
1906 // the smallest window does not.
1907 .child(
1908 div()
1909 .id("keys-rows")
1910 .flex()
1911 .flex_col()
1912 .gap(px(2.))
1913 .max_h(px(KEYS_ROWS_H))
1914 .overflow_y_scroll()
1915 .children(rows),
1916 ),
1917 ),
1918 )
1919 }
1920
1921 /// What an export is going to be, before there is one: the destination, the
1922 /// quality rows, and the two things that are not a choice at all. The same
1923 /// scrim, width and row shape as the keybindings overlay -- two cards of
1924 /// different builds over one window read as two different programs -- and
1925 /// the same plain divs, so the root keeps the keyboard and a typed digit
1926 /// reaches the custom row.
1927 fn export_card(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
1928 if !self.export_open {
1929 return None;
1930 }
1931 let row = |id: (&'static str, usize)| {
1932 div()
1933 .id(id)
1934 .flex()
1935 // The floor, not the height: the destination's path wraps on a
1936 // long name and must not paint over the row under it.
1937 .min_h(px(KEYS_ROW_H))
1938 .items_center()
1939 .justify_between()
1940 .gap(px(12.))
1941 .px(px(6.))
1942 .rounded(px(3.))
1943 .cursor_pointer()
1944 .hover(|s| s.bg(rgb(HOVER)))
1945 };
1946 let rows: Vec<_> = Quality::ALL
1947 .into_iter()
1948 .enumerate()
1949 .map(|(i, quality)| {
1950 row(("quality", i))
1951 .when(self.quality == quality, |d| d.bg(rgb(SELECTED)))
1952 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
1953 this.quality = quality;
1954 cx.notify();
1955 }))
1956 .child(quality.label())
1957 .child(
1958 div()
1959 .text_size(px(11.))
1960 .text_color(rgb(INK_DIM))
1961 .child(quality.detail(self.custom_mbps)),
1962 )
1963 })
1964 .collect();
1965 Some(
1966 div()
1967 .absolute()
1968 .inset_0()
1969 .flex()
1970 .justify_center()
1971 .items_center()
1972 .bg(rgba(0x101010cc))
1973 .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| {
1974 cx.stop_propagation()
1975 })
1976 .child(
1977 div()
1978 .w(px(KEYS_W))
1979 .flex()
1980 .flex_col()
1981 .gap(px(2.))
1982 .p(px(12.))
1983 .rounded(px(6.))
1984 .bg(rgb(SURFACE))
1985 .child(div().flex_none().px(px(6.)).child("Export"))
1986 // The status line, where a refusal from the save dialog
1987 // lands: the notice bar it would otherwise take is under
1988 // the scrim.
1989 .child(
1990 div()
1991 .flex_none()
1992 .px(px(6.))
1993 .text_size(px(11.))
1994 .text_color(rgb(INK_DIM))
1995 .child(self.notice.clone().unwrap_or_else(|| {
1996 "pick a quality, then Export — esc closes".into()
1997 })),
1998 )
1999 .child(
2000 row(("destination", 0))
2001 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
2002 this.pick_destination(cx)
2003 }))
2004 .child("Destination")
2005 .child(
2006 div()
2007 .text_size(px(11.))
2008 .text_color(rgb(INK_DIM))
2009 .child(file_name(&self.export_path)),
2010 ),
2011 )
2012 .children(rows)
2013 // Not offered, so said: these are what this program can
2014 // write, and a menu of one is a lie about the other
2015 // entries. `moov` last is the muxer's own shape -- the
2016 // file is playable only once it is finished.
2017 .child(
2018 div()
2019 .flex_none()
2020 .px(px(6.))
2021 .text_size(px(11.))
2022 .text_color(rgb(INK_DIM))
2023 .child("H.264 · MP4 · moov at end"),
2024 )
2025 .child(
2026 div()
2027 .id("export-confirm")
2028 .mt(px(4.))
2029 .flex()
2030 .h(px(CONTROL_H))
2031 .items_center()
2032 .justify_center()
2033 .rounded(px(3.))
2034 .bg(rgb(SELECTED))
2035 .cursor_pointer()
2036 .hover(|s| s.bg(rgb(HOVER)))
2037 .on_click(
2038 cx.listener(|this, _: &ClickEvent, _, cx| {
2039 this.start_export(cx)
2040 }),
2041 )
2042 .child("Export"),
2043 ),
2044 ),
2045 )
2046 }
2047
2048 /// The menu a right-click on a clip opens: what that clip can be given,
2049 /// each item beside the stroke that does the very same thing, and a
2050 /// turn-over side that says what the clip *is*. An item that would do
2051 /// nothing where the playhead is standing is dimmed and takes no click
2052 /// rather than disappearing, so the menu reads the same every time.
2053 ///
2054 /// Every item goes through [`Player::act`], the table the key handler uses:
2055 /// an item is its stroke, asked for with the mouse. Plain divs like the
2056 /// rest of this window, so the root keeps the keyboard and escape still
2057 /// reaches the handler that closes this.
2058 fn context_card(
2059 &self,
2060 viewport: Size<Pixels>,
2061 cx: &mut Context<Self>,
2062 ) -> Option<impl IntoElement> {
2063 let menu = self.context_menu?;
2064 let session = self.session.as_ref()?;
2065 let clip = *session.lane_clips(menu.lane).get(menu.idx)?;
2066 let playhead = frame_at(session.now(), self.fps);
2067 let source = session.sources().get(clip.source).cloned()?;
2068 let secs = |frames: u32| timecode(f64::from(frames) / self.fps, self.fps);
2069 let row = |n: usize| {
2070 div()
2071 .id(("menu", n))
2072 .flex()
2073 // The floor, not the height: a long label wrapping must not
2074 // paint over the item under it.
2075 .min_h(px(MENU_ROW_H))
2076 .items_center()
2077 .justify_between()
2078 .gap(px(12.))
2079 .px(px(6.))
2080 .rounded(px(3.))
2081 };
2082 let mut rows: Vec<AnyElement> = Vec::new();
2083 if menu.details {
2084 // Read-only, so no ids and no hover: this side is a card, not a
2085 // list of things to click. Each value is one truncated line, which
2086 // is what keeps the height below the one the clamp was given.
2087 for (label, value) in [
2088 ("File", file_name(&source.path)),
2089 ("Path", source.path.display().to_string()),
2090 (
2091 "Source range",
2092 format!("{} – {}", secs(clip.in_frame), secs(clip.out_frame)),
2093 ),
2094 ("This clip", secs(clip.len())),
2095 (
2096 "Source duration",
2097 secs(source_frames(
2098 lane_clips(session),
2099 session.sources(),
2100 &source.path,
2101 )),
2102 ),
2103 ] {
2104 rows.push(
2105 row(rows.len())
2106 .child(label)
2107 .child(
2108 div()
2109 .min_w(px(0.))
2110 .truncate()
2111 // A size smaller than the labels: a timecode
2112 // pair is 25 characters and has to fit beside
2113 // its label inside `MENU_W`.
2114 .text_size(px(11.))
2115 .text_color(rgb(INK_DIM))
2116 .child(value),
2117 )
2118 .into_any_element(),
2119 );
2120 }
2121 } else {
2122 for action in MENU_ITEMS {
2123 let enabled = applicable(&clip, action, playhead);
2124 // The one item that is not about this clip says so, and says it
2125 // here rather than in the registry: the stroke is global too,
2126 // but its row in the keys menu is not sitting on a clip.
2127 let label = if action == ActionId::ToggleMute {
2128 format!("{} (global)", action.label())
2129 } else {
2130 action.label().to_string()
2131 };
2132 rows.push(
2133 row(rows.len())
2134 .child(label)
2135 .child(
2136 div()
2137 .text_color(rgb(INK_DIM))
2138 .child(self.keymap.display(action)),
2139 )
2140 .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed())
2141 .when(enabled, |d| {
2142 d.cursor_pointer()
2143 .hover(|s| s.bg(rgb(HOVER)))
2144 .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
2145 // Closed first: the action moves the very
2146 // indices this menu is holding.
2147 this.context_menu = None;
2148 this.act(action, cx);
2149 }))
2150 })
2151 .into_any_element(),
2152 );
2153 }
2154 rows.push(
2155 row(rows.len())
2156 .cursor_pointer()
2157 .hover(|s| s.bg(rgb(HOVER)))
2158 .on_click(cx.listener(|this, _: &ClickEvent, _, cx| {
2159 if let Some(menu) = &mut this.context_menu {
2160 menu.details = true;
2161 }
2162 cx.notify();
2163 }))
2164 .child("Properties")
2165 // No stroke reaches this one, and a blank column would read
2166 // as one that was forgotten.
2167 .child(div().text_color(rgb(INK_DIM)).child("…"))
2168 .into_any_element(),
2169 );
2170 }
2171 let (x, y) = menu_at(
2172 menu.at,
2173 viewport,
2174 MENU_PAD * 2. + rows.len() as f32 * MENU_ROW_H,
2175 );
2176 let full: SharedString = source.path.display().to_string().into();
2177 Some(
2178 div()
2179 .absolute()
2180 .inset_0()
2181 // Click away closes it, either button, and the press is
2182 // swallowed so nothing under the menu also takes it. No tint,
2183 // unlike the modal cards: the timeline this menu is about has
2184 // to stay readable behind it.
2185 .on_mouse_down(
2186 MouseButton::Left,
2187 cx.listener(|this, _: &MouseDownEvent, _, cx| {
2188 this.context_menu = None;
2189 cx.notify();
2190 cx.stop_propagation();
2191 }),
2192 )
2193 .on_mouse_down(
2194 MouseButton::Right,
2195 cx.listener(|this, _: &MouseDownEvent, _, cx| {
2196 this.context_menu = None;
2197 cx.notify();
2198 cx.stop_propagation();
2199 }),
2200 )
2201 .child(
2202 div()
2203 // Only so the details side can carry a tooltip, which
2204 // gpui gives to identified elements alone.
2205 .id("menu-card")
2206 .absolute()
2207 .left(px(x))
2208 .top(px(y))
2209 .w(px(MENU_W))
2210 .flex()
2211 .flex_col()
2212 .p(px(MENU_PAD))
2213 .rounded(px(6.))
2214 .bg(rgb(SURFACE))
2215 // Painted after the scrim, so this listener runs first
2216 // (gpui bubbles mouse events in reverse, window.rs:3705)
2217 // and a press meant for an item never closes the menu
2218 // out from under its own click.
2219 .on_mouse_down(MouseButton::Left, |_: &MouseDownEvent, _, cx| {
2220 cx.stop_propagation()
2221 })
2222 .on_mouse_down(MouseButton::Right, |_: &MouseDownEvent, _, cx| {
2223 cx.stop_propagation()
2224 })
2225 // The one value the details side has to truncate.
2226 .when(menu.details, |d| {
2227 d.tooltip(move |_, cx| cx.new(|_| Tip(full.clone())).into())
2228 })
2229 .children(rows),
2230 ),
2231 )
2232 }
2233
2234 /// One lane of the edit list made visible: a fixed header saying which lane
2235 /// it is, then a bed with a box per clip, placed and sized by its share of
2236 /// the timeline. A cut adds a box without moving anything, a delete closes
2237 /// the hole, a lift leaves one. A clip too narrow for its name says what it
2238 /// is by its tint, and the tooltip is where every box says what clicking it
2239 /// does. Never focusable, so the root keeps focus and the play binding still
2240 /// works after a click (ledger:182).
2241 fn lane_row(
2242 &self,
2243 lane: Lane,
2244 name: &'static str,
2245 duration: f64,
2246 filled: f32,
2247 cx: &mut Context<Self>,
2248 ) -> impl IntoElement {
2249 // The bed's own width, measured last repaint off the ruler's bar: the
2250 // two are laid out identically (same header offset, same `flex_1`), so
2251 // one probe answers for both. Zero before the first paint, which only
2252 // costs the labels one frame.
2253 let bed_w = f32::from(self.ruler.get().size.width);
2254 let (clips, others) = match &self.session {
2255 Some(session) => (
2256 session.lane_clips(lane),
2257 session.lane_clips(match lane {
2258 Lane::Video => Lane::Audio,
2259 Lane::Audio => Lane::Video,
2260 }),
2261 ),
2262 None => (&[][..], &[][..]),
2263 };
2264 let sources = self
2265 .session
2266 .as_ref()
2267 .map_or(&[][..], PlaybackSession::sources);
2268 let (sel, sel_link) = (self.selected, self.selected_link());
2269 let audio = lane == Lane::Audio;
2270 let tip: SharedString = format!(
2271 "Select — {} removes the take, {} leaves a gap, {} rejoins a cut",
2272 self.keymap.display(ActionId::Delete),
2273 self.keymap.display(ActionId::Lift),
2274 self.keymap.display(ActionId::Regroup)
2275 )
2276 .into();
2277 div()
2278 .flex_none()
2279 .h(px(LANE_H))
2280 .flex()
2281 .gap(px(HEADER_GAP))
2282 // The fixed column the ruler above is offset by as well. Full lane
2283 // height, so it reads as the bed continuing rather than as a chip.
2284 .child(
2285 div()
2286 .flex_none()
2287 .w(px(HEADER_W))
2288 .h_full()
2289 .flex()
2290 .items_center()
2291 .justify_center()
2292 .rounded(px(3.))
2293 .bg(rgb(SURFACE))
2294 .text_size(px(11.))
2295 .text_color(rgb(INK_DIM))
2296 .child(name),
2297 )
2298 .child(
2299 // Clips are placed at their own start rather than queued edge
2300 // to edge: a lift leaves a hole in the lane, and the bare bed
2301 // showing through it *is* how a gap looks.
2302 div()
2303 .relative()
2304 .flex_1()
2305 .min_w(px(0.))
2306 .h_full()
2307 .rounded(px(3.))
2308 .bg(rgb(LETTERBOX))
2309 .overflow_hidden()
2310 // A library row let go over a lane is the same insert the
2311 // Add button makes, through the same call -- at the
2312 // playhead, not at the pointer: clips here are placed end
2313 // to end, so where along the bed it landed says nothing.
2314 .on_drop(cx.listener(|this, drag: &AssetDrag, _, cx| {
2315 this.insert_source(&drag.0.clone(), drag.1, cx)
2316 }))
2317 .drag_over::<AssetDrag>(|s, _, _, _| s.bg(rgb(HOVER_DIM)))
2318 .children(clips.iter().enumerate().map(|(i, clip)| {
2319 let (start, len) = (
2320 f64::from(clip.start) / self.fps,
2321 f64::from(clip.len()) / self.fps,
2322 );
2323 let on = marked((lane, i), clip.link, sel, sel_link);
2324 // A group with a half in the other lane wears its tint;
2325 // one without is outlined, so a detached half is visible
2326 // as detached before anyone clicks it.
2327 let grouped =
2328 clip.link.is_some() && others.iter().any(|o| o.link == clip.link);
2329 // Tinted by *file*, not by source entry: two audio
2330 // streams of one file are two sources, and the library
2331 // gives them one swatch because they are one file.
2332 let tint = source_tint(
2333 sources
2334 .get(clip.source)
2335 .and_then(|s| sources.iter().position(|o| o.path == s.path))
2336 .unwrap_or(clip.source),
2337 );
2338 let width = width_frac(len, duration);
2339 let label = sources.get(clip.source).map(|s| file_name(&s.path));
2340 let wave = sources
2341 .get(clip.source)
2342 .and_then(|s| self.waves.get(&(s.path.clone(), s.audio_stream)))
2343 .cloned();
2344 let (from, to) = (
2345 f64::from(clip.in_frame) / self.fps,
2346 f64::from(clip.out_frame) / self.fps,
2347 );
2348 let tip = tip.clone();
2349 div()
2350 .id((if audio { "aclip" } else { "vclip" }, i))
2351 .absolute()
2352 .top_0()
2353 .h_full()
2354 .left(relative(start_frac(start, duration)))
2355 .w(relative(width))
2356 .overflow_hidden()
2357 .rounded(px(3.))
2358 .border_1()
2359 .border_color(rgb(if on {
2360 ACCENT
2361 } else if grouped {
2362 tint
2363 } else {
2364 INK_DIM
2365 }))
2366 .bg(rgb(if on { SELECTED } else { tint }))
2367 .cursor_pointer()
2368 .hover(|s| s.border_color(rgb(ACCENT)))
2369 .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())
2370 .on_mouse_down(
2371 MouseButton::Left,
2372 cx.listener(move |this, _: &MouseDownEvent, _, cx| {
2373 this.selected = Some((lane, i));
2374 cx.notify();
2375 }),
2376 )
2377 // The right button selects exactly as the left one
2378 // does -- the menu acts on the clip it names, so
2379 // opening one has to pick it -- and then hangs the
2380 // menu at the pointer.
2381 .on_mouse_down(
2382 MouseButton::Right,
2383 cx.listener(move |this, event: &MouseDownEvent, _, cx| {
2384 if this.modal() {
2385 return;
2386 }
2387 this.selected = Some((lane, i));
2388 this.context_menu = Some(ContextMenu {
2389 lane,
2390 idx: i,
2391 at: event.position,
2392 details: false,
2393 });
2394 cx.notify();
2395 }),
2396 )
2397 // Under the label row, never through it.
2398 .children(wave.filter(|_| audio).and_then(|wave| {
2399 let inner: AnyElement = match wave {
2400 Wave::Peaks(peaks) => {
2401 waveform(peaks, from, to).into_any_element()
2402 }
2403 // A bed while the decode runs, and dimmer
2404 // than any waveform is drawn: a flat
2405 // `INK_DIM` line here would be the shape a
2406 // silent file makes, which this file is not
2407 // known to be yet.
2408 Wave::Loading => div()
2409 .h_full()
2410 .flex()
2411 .items_center()
2412 .child(div().w_full().h(px(1.)).bg(rgb(HOVER)))
2413 .into_any_element(),
2414 // No audio track: nothing, never a fake.
2415 Wave::Silent => return None,
2416 };
2417 Some(
2418 div()
2419 .absolute()
2420 .left_0()
2421 .right_0()
2422 .top(px(LABEL_H))
2423 .bottom_0()
2424 .child(inner),
2425 )
2426 }))
2427 .when_some(label.filter(|_| show_label(bed_w * width)), |d, label| {
2428 d.child(
2429 div()
2430 .relative()
2431 .h(px(LABEL_H))
2432 .px(px(4.))
2433 .truncate()
2434 .text_size(px(10.))
2435 .child(label),
2436 )
2437 })
2438 }))
2439 // Last, so it is over the clips: the same fraction in both
2440 // lanes, which is the playhead being one line.
2441 .child(
2442 div()
2443 .absolute()
2444 .top_0()
2445 .h_full()
2446 .left(relative(filled))
2447 .w(px(1.))
2448 .bg(rgb(ACCENT)),
2449 ),
2450 )
2451 }
2452}
2453
2454/// Rate limit for scrub seeks: a video worker reopen costs 72-87 ms on the
2455/// hardware path (215 ms in software), so one seek per mouse move would only
2456/// queue workers that are cancelled before they decode anything.
2457const SCRUB_GAP: Duration = Duration::from_millis(100);
2458
2459fn scrub_due(target: u32, last_target: u32, since: Duration) -> bool {
2460 target != last_target && since >= SCRUB_GAP
2461}
2462
2463/// Runs the first chooser that is installed. `Some(None)` is a cancelled
2464/// dialog; `None` is a machine with no chooser at all, and what still works
2465/// without one differs per dialog, so the caller words that refusal.
2466///
2467/// The desktop's own choosers, asked for by name because gpui 0.2 has no file
2468/// dialog of its own and none of these is worth a dependency.
2469fn run_picker(pickers: [(&str, Vec<String>); 2]) -> Option<Option<PathBuf>> {
2470 for (bin, args) in pickers {
2471 // Not installed: try the next one. Anything else (a cancel, a refusal)
2472 // is that chooser's answer and is taken as final.
2473 let Ok(out) = std::process::Command::new(bin).args(args).output() else {
2474 continue;
2475 };
2476 let path = String::from_utf8_lossy(&out.stdout).trim().to_string();
2477 return Some((!path.is_empty()).then(|| PathBuf::from(path)));
2478 }
2479 None
2480}
2481
2482fn pick_file() -> Result<Option<PathBuf>, &'static str> {
2483 run_picker([
2484 (
2485 "zenity",
2486 vec!["--file-selection".into(), "--title=edith — import".into()],
2487 ),
2488 ("kdialog", vec!["--getopenfilename".into()]),
2489 ])
2490 .ok_or(
2491 "NO FILE CHOOSER — install zenity or kdialog, or drag the file onto this window to import it",
2492 )
2493}
2494
2495/// The save-side dialog, opened on where the export would land anyway: with no
2496/// chooser installed that default is still what gets written, so this refusal
2497/// costs the export nothing and says so.
2498fn pick_save(default: &std::path::Path) -> Result<Option<PathBuf>, &'static str> {
2499 let default = default.to_string_lossy().into_owned();
2500 run_picker([
2501 (
2502 "zenity",
2503 vec![
2504 "--file-selection".into(),
2505 // No `--confirm-overwrite`: zenity 4.2 lists it as deprecated
2506 // and does the confirming itself.
2507 "--save".into(),
2508 "--title=edith — export to".into(),
2509 format!("--filename={default}"),
2510 ],
2511 ),
2512 ("kdialog", vec!["--getsavefilename".into(), default]),
2513 ])
2514 .ok_or(
2515 "NO FILE CHOOSER — install zenity or kdialog to choose where; exporting beside the source",
2516 )
2517}
2518
2519/// Where an export goes: the source path with `.export.mp4` for an extension,
2520/// so it lands beside the original and can never be the original.
2521fn export_path(source: impl Into<PathBuf>) -> PathBuf {
2522 let mut path = source.into();
2523 path.set_extension("export.mp4");
2524 path
2525}
2526
2527/// Where a save goes when the timeline did not come from a project file: the
2528/// media path with `.edith` for an extension, beside it like an export. A
2529/// project loaded from disk keeps its own path instead, so saving it twice
2530/// writes the same file.
2531fn project_path(source: impl Into<PathBuf>) -> PathBuf {
2532 let mut path = source.into();
2533 path.set_extension("edith");
2534 path
2535}
2536
2537/// Whether a dropped or named path is a project rather than media. Exactly the
2538/// lowercase extension `save_project` writes -- anything else goes to the
2539/// demuxer, which is the one that can say what it really is.
2540fn is_project(path: &std::path::Path) -> bool {
2541 path.extension().is_some_and(|e| e == "edith")
2542}
2543
2544/// The tail of a path, for showing. A path that is all root has none, and reads
2545/// as itself.
2546fn file_name(path: &std::path::Path) -> String {
2547 path.file_name().map_or_else(
2548 || path.display().to_string(),
2549 |n| n.to_string_lossy().into(),
2550 )
2551}
2552
2553/// The tail an open/load notice grows when the file has sound the engine cannot
2554/// decode: it plays perfectly, in silence, and that is the one thing the window
2555/// would otherwise never say (the engine's own word for it, verbatim).
2556fn audio_notice(session: &PlaybackSession) -> Option<String> {
2557 session
2558 .audio_disabled_reason()
2559 .map(|reason| format!(" — NO AUDIO: {reason}"))
2560}
2561
2562/// The sources a repaint has not asked about yet. A key that is already there
2563/// means "asked", whatever state it is in, which is what stops a decode already
2564/// running from being started again by the next of sixty repaints a second.
2565fn unseen_sources(
2566 sources: &[Source],
2567 waves: &HashMap<(PathBuf, usize), Wave>,
2568) -> Vec<(PathBuf, usize)> {
2569 sources
2570 .iter()
2571 .map(|s| (s.path.clone(), s.audio_stream))
2572 .filter(|key| !waves.contains_key(key))
2573 .collect()
2574}
2575
2576/// The same, for the per-file stream probe: one entry per *file*, however many
2577/// of its streams the timeline plays.
2578fn unseen_paths(sources: &[Source], streams: &HashMap<PathBuf, Vec<StreamInfo>>) -> Vec<PathBuf> {
2579 let mut out: Vec<PathBuf> = Vec::new();
2580 for s in sources {
2581 if !streams.contains_key(&s.path) && !out.contains(&s.path) {
2582 out.push(s.path.clone());
2583 }
2584 }
2585 out
2586}
2587
2588/// Both lanes' clips, which is everything the timeline knows about its sources.
2589fn lane_clips(session: &PlaybackSession) -> impl Iterator<Item = &Clip> {
2590 session
2591 .lane_clips(Lane::Video)
2592 .iter()
2593 .chain(session.lane_clips(Lane::Audio))
2594}
2595
2596/// How long a source is, as the timeline knows it: the furthest frame any clip
2597/// plays from *the file*. Exact for a source the timeline still holds whole --
2598/// which is every source the moment it is imported -- and never longer than the
2599/// file, since every clip was checked against it, so a clip built from this can
2600/// always be played. Zero for a file nothing plays from any more.
2601///
2602/// By file rather than by source entry, because a second audio stream of a file
2603/// already on the timeline is a row that has no clips of its own yet, and every
2604/// stream of a file is the same length -- the picture is what the length is.
2605///
2606/// ponytail: a source trimmed on the timeline reads as its trimmed length. The
2607/// file's own length would need a `Demuxer::open` probe per source, off the
2608/// render path like the peak decode is -- that is the upgrade path.
2609fn source_frames<'a>(
2610 clips: impl Iterator<Item = &'a Clip>,
2611 sources: &[Source],
2612 path: &Path,
2613) -> u32 {
2614 clips
2615 .filter(|clip| sources.get(clip.source).is_some_and(|s| s.path == path))
2616 .map(|clip| clip.out_frame)
2617 .max()
2618 .unwrap_or(0)
2619}
2620
2621/// Which timeline frame the playhead is on, by the rule the engine's own edits
2622/// use (playback.rs `secs_to_frame`): the frame that has started, with the
2623/// epsilon that keeps a clock sitting exactly on a boundary from reading as the
2624/// frame before it. Only ever a hint here -- what an edit does is still the
2625/// engine's answer, taken from the same seconds.
2626fn frame_at(secs: f64, fps: f64) -> u32 {
2627 (secs * fps + 1e-6).floor().max(0.) as u32
2628}
2629
2630/// Whether the clip menu offers `action` on the clip it was opened on. Two of
2631/// the items act on the *playhead* rather than on the clip, so a menu opened
2632/// away from it dims them instead of looking broken when they are clicked.
2633fn applicable(clip: &Clip, action: ActionId, playhead: u32) -> bool {
2634 match action {
2635 // Splits this clip only from inside it: at either edge there is nothing
2636 // to split off (project.rs `splittable`).
2637 ActionId::Cut => clip.start < playhead && playhead < clip.end(),
2638 // Rejoins whatever meets at the playhead, so it can mean something only
2639 // at an edge of this clip. Whether those two halves were ever one take
2640 // is the engine's question, and it words that refusal itself.
2641 ActionId::Regroup => playhead == clip.start || playhead == clip.end(),
2642 _ => true,
2643 }
2644}
2645
2646/// Where the menu actually hangs: at the pointer, pulled back inside the window
2647/// when it would not fit -- an item off the bottom edge is an item nobody can
2648/// click. Never negative, so a window smaller than the menu loses the bottom of
2649/// it rather than the top, where the items are.
2650fn menu_at(at: Point<Pixels>, viewport: Size<Pixels>, height: f32) -> (f32, f32) {
2651 let fit = |v: f32, size: f32, room: f32| v.min(room - size).max(0.);
2652 (
2653 fit(f32::from(at.x), MENU_W, f32::from(viewport.width)),
2654 fit(f32::from(at.y), height, f32::from(viewport.height)),
2655 )
2656}
2657
2658/// Whether the Add button does anything: a row picked, a timeline to put it on,
2659/// and no export reading that timeline. A button that would do nothing is dimmed
2660/// and takes no click, like every other one here.
2661fn can_add(picked: Option<&(PathBuf, usize)>, timeline: bool, exporting: bool) -> bool {
2662 picked.is_some() && timeline && !exporting
2663}
2664
2665/// One library row: a file and one of its audio streams. Plain data, planned
2666/// before anything is drawn -- which rows exist at all is the branchy part.
2667#[derive(Debug, PartialEq)]
2668struct Row {
2669 path: PathBuf,
2670 stream: usize,
2671 /// The file, plus which stream this is when the file has several.
2672 name: String,
2673 /// What the stream is, or blank for a file with a single one.
2674 detail: String,
2675 /// Why it cannot be put on this timeline, for a row that cannot: shown in
2676 /// place of the length and the only thing that greys a row out.
2677 unusable: Option<String>,
2678 /// Frames of the *file*, for the length line.
2679 frames: u32,
2680 /// Index into `SOURCE_TINTS`, shared by every stream of one file: the
2681 /// swatch says which file, and the lanes tint their clips the same way.
2682 tint: usize,
2683}
2684
2685/// Every row the library shows: one per source entry, plus one for each further
2686/// audio stream those files have that no clip plays yet -- a remux with a track
2687/// per language lists them all, the ones this engine cannot use greyed out
2688/// rather than hidden. Streams a file has not been probed for yet simply are
2689/// not there; the row for what *is* on the timeline is always there.
2690///
2691/// `timeline_audio` is the rate and layout of source 0's stream, which every
2692/// other source must match: one output device and one copied AAC track for the
2693/// whole timeline (`PlaybackSession::place_stream_at`). `None` while unknown,
2694/// and then nothing is greyed for it -- the engine still refuses.
2695fn library_rows(
2696 sources: &[Source],
2697 streams: &HashMap<PathBuf, Vec<StreamInfo>>,
2698 timeline_audio: Option<(u32, u16)>,
2699 frames: impl Fn(&Path) -> u32,
2700) -> Vec<Row> {
2701 let mut rows = Vec::new();
2702 for (i, source) in sources.iter().enumerate() {
2703 let of_file = streams.get(&source.path).map_or(&[][..], Vec::as_slice);
2704 let info = of_file.iter().find(|s| s.index == source.audio_stream);
2705 let tint = sources
2706 .iter()
2707 .position(|s| s.path == source.path)
2708 .expect("a source finds itself");
2709 rows.push(Row {
2710 path: source.path.clone(),
2711 stream: source.audio_stream,
2712 name: row_name(&source.path, source.audio_stream, of_file.len() > 1),
2713 // Only where there is a choice to describe: a file with one audio
2714 // track is the row it has always been, name and length, and the
2715 // length is what would be squeezed out at the panel's least width.
2716 detail: info
2717 .filter(|_| of_file.len() > 1)
2718 .map_or_else(String::new, stream_detail),
2719 // A stream already on the timeline is playing: whatever a probe
2720 // would say about it now, it is usable by demonstration.
2721 unusable: None,
2722 frames: frames(&source.path),
2723 tint,
2724 });
2725 // The file's other streams, listed once, right after the last entry
2726 // that names the file -- so a file's rows sit together.
2727 if sources[i + 1..].iter().any(|s| s.path == source.path) {
2728 continue;
2729 }
2730 for info in of_file {
2731 if sources
2732 .iter()
2733 .any(|s| s.path == source.path && s.audio_stream == info.index)
2734 {
2735 continue; // it has a row of its own above
2736 }
2737 rows.push(Row {
2738 path: source.path.clone(),
2739 stream: info.index,
2740 name: row_name(&source.path, info.index, true),
2741 detail: stream_detail(info),
2742 unusable: unusable(info, timeline_audio),
2743 frames: frames(&source.path),
2744 tint,
2745 });
2746 }
2747 }
2748 rows
2749}
2750
2751/// The row's second line: what the stream is and then either how long it is or
2752/// why it cannot be used, with the separator only where both halves exist (a
2753/// single-stream file says nothing about its stream).
2754fn join_detail(detail: &str, tail: &str) -> String {
2755 match detail.is_empty() {
2756 true => tail.to_string(),
2757 false => format!("{detail} · {tail}"),
2758 }
2759}
2760
2761/// How a row names its file: the file alone when it has one audio stream or
2762/// none, and the file plus which stream this row is when it has several --
2763/// counted from 1, the way a player numbers tracks.
2764fn row_name(path: &Path, stream: usize, several: bool) -> String {
2765 match several {
2766 false => file_name(path),
2767 true => format!("{} [audio {}]", file_name(path), stream + 1),
2768 }
2769}
2770
2771/// What a stream is, for the row's second line: the language if the file says
2772/// one, then rate and layout. A field the header does not give is left out
2773/// rather than shown as a zero -- a stream we cannot parse says nothing about
2774/// itself, and saying "0 Hz" would be saying something.
2775fn stream_detail(info: &StreamInfo) -> String {
2776 let mut parts: Vec<String> = Vec::new();
2777 if let Some(lang) = &info.lang {
2778 parts.push(lang.clone());
2779 }
2780 if info.sample_rate > 0 {
2781 parts.push(format!("{} kHz", f64::from(info.sample_rate) / 1000.));
2782 }
2783 parts.extend(layout(info.channels));
2784 parts.join(" ")
2785}
2786
2787fn layout(channels: u16) -> Option<String> {
2788 match channels {
2789 0 => None,
2790 1 => Some("mono".to_string()),
2791 2 => Some("stereo".to_string()),
2792 n => Some(format!("{n} ch")),
2793 }
2794}
2795
2796/// Why a stream cannot go on this timeline, or `None` if it can. Both answers
2797/// are shown: a stream nothing can be done with is listed greyed with the
2798/// reason, never dropped from the list -- a file has the tracks it has, and a
2799/// picker that hides them is a picker that lies.
2800fn unusable(info: &StreamInfo, timeline_audio: Option<(u32, u16)>) -> Option<String> {
2801 if !info.decodable {
2802 // ponytail: mp4 0.14 keeps no fourcc for a sample entry it does not
2803 // parse (`StreamInfo::codec`), so an AC-3 track can only be named as
2804 // unsupported, not as AC-3. Upgrade path is reading the stsd ourselves.
2805 return Some(match info.codec.as_str() {
2806 "unknown" => "unsupported codec".to_string(),
2807 codec => format!("{codec} is not supported"),
2808 });
2809 }
2810 let (rate, channels) = timeline_audio?;
2811 ((info.sample_rate, info.channels) != (rate, channels)).then(|| {
2812 format!(
2813 "the timeline is {} kHz {}",
2814 f64::from(rate) / 1000.,
2815 layout(channels).unwrap_or_else(|| "silent".to_string())
2816 )
2817 })
2818}
2819
2820/// What the media list is given of the window. A share of it, so a narrow
2821/// window gives the panel less rather than giving the picture nothing, floored
2822/// where a name stops being readable and capped at a third of the window --
2823/// the picture is what the program is for and keeps the majority at every size.
2824fn library_w(window_w: f32) -> f32 {
2825 (window_w * LIBRARY_FRAC)
2826 .clamp(LIBRARY_MIN_W, LIBRARY_MAX_W)
2827 .min(window_w / 3.)
2828}
2829
2830/// What the window is called: the program, and what is open in it. The name is
2831/// what the header shows, so an empty window says the program alone rather than
2832/// "no file open — edith".
2833fn window_title(name: &str) -> String {
2834 if name == NO_FILE {
2835 "edith".to_string()
2836 } else {
2837 format!("{name} — edith")
2838 }
2839}
2840
2841/// The tint a clip from source `n` wears. Cycled rather than extended: past the
2842/// palette two sources share a colour, which is a smaller lie than a fifth tint
2843/// bright enough to leave the family.
2844fn source_tint(source: usize) -> u32 {
2845 SOURCE_TINTS[source % SOURCE_TINTS.len()]
2846}
2847
2848/// What the export card offers, top to bottom. Bitrate is the only thing the
2849/// encoder actually takes: the codec and the container are what this program
2850/// can write and nothing else, so the card states them rather than offering
2851/// them.
2852#[derive(Clone, Copy, PartialEq, Debug)]
2853enum Quality {
2854 Auto,
2855 Low,
2856 Medium,
2857 High,
2858 Custom,
2859}
2860
2861impl Quality {
2862 const ALL: [Quality; 5] = [
2863 Quality::Auto,
2864 Quality::Low,
2865 Quality::Medium,
2866 Quality::High,
2867 Quality::Custom,
2868 ];
2869
2870 fn label(self) -> &'static str {
2871 match self {
2872 Quality::Auto => "Auto",
2873 Quality::Low => "Low",
2874 Quality::Medium => "Medium",
2875 Quality::High => "High",
2876 Quality::Custom => "Custom",
2877 }
2878 }
2879
2880 /// The figure the row stands for, said in the units the row is chosen by.
2881 fn detail(self, custom_mbps: u32) -> String {
2882 match self {
2883 Quality::Auto => "from the picture size and frame rate".to_string(),
2884 Quality::Custom => format!("{custom_mbps} Mbps — type a number, 1–20"),
2885 other => format!(
2886 "{} Mbps",
2887 export_settings(other, 0).bitrate.unwrap_or_default() / 1_000_000
2888 ),
2889 }
2890 }
2891}
2892
2893/// The card's rows as the engine takes them. `Auto` leaves the bitrate to the
2894/// exporter, which derives it from the picture; the fixed rows are figures that
2895/// hold from 720p to 1080p, and a typed one is passed exactly as typed -- the
2896/// engine clamps every explicit bitrate to 1..20 Mbps (export.rs:290), so this
2897/// must not clamp it a second time and disagree about where the edge is.
2898fn export_settings(quality: Quality, custom_mbps: u32) -> ExportSettings {
2899 ExportSettings {
2900 bitrate: match quality {
2901 Quality::Auto => None,
2902 Quality::Low => Some(2_000_000),
2903 Quality::Medium => Some(6_000_000),
2904 Quality::High => Some(12_000_000),
2905 Quality::Custom => Some(u64::from(custom_mbps) * 1_000_000),
2906 },
2907 // No row of its own: the software pin is for a driver that encodes
2908 // badly, which is a thing about the machine and not about the output --
2909 // `VE_SW_ENC` already says it, and to the whole run rather than once.
2910 force_sw: false,
2911 }
2912}
2913
2914/// A digit typed against the custom row, appended to what is already there.
2915/// Refused rather than truncated past two digits: the engine's ceiling is
2916/// 20 Mbps, so a third digit can only be a mistake, and a silently dropped one
2917/// would leave the card showing a number nobody typed.
2918fn push_digit(mbps: u32, digit: u32) -> u32 {
2919 let next = mbps * 10 + digit;
2920 if next <= 99 { next } else { mbps }
2921}
2922
2923/// Whether a stroke gets out of a running export. Escape does, whatever
2924/// modifiers are held with it, for the same reason it gets out of a capture and
2925/// out of the overlay: it is this window's way out, and a way out that only
2926/// works with the right modifiers is not one. Whatever the keymap has on cancel
2927/// works too, so rebinding it adds a way rather than replacing the one that
2928/// always worked -- and that binding is still what the progress line shows.
2929fn cancels_export(key: &str, action: Option<ActionId>) -> bool {
2930 key == ESCAPE || action == Some(ActionId::CancelExport)
2931}
2932
2933/// The keys that are only ever half a chord. gpui delivers a lone modifier
2934/// press as a keystroke of its own, and taking one as a binding would leave an
2935/// action that fires the moment the user reaches for any chord that uses it --
2936/// so a capture waits through them instead.
2937fn is_bare_modifier(key: &str) -> bool {
2938 matches!(
2939 key,
2940 "control" | "shift" | "alt" | "super" | "platform" | "function" | "fn" | "meta" | "command"
2941 )
2942}
2943
2944/// A clip's share of the lane. A timeline with no length reads as one full-width
2945/// box rather than as NaN, which gpui would carry into layout.
2946fn width_frac(len: f64, total: f64) -> f32 {
2947 if total > 0. { (len / total) as f32 } else { 1. }
2948}
2949
2950/// Where along the lane a clip starts, 0..1. Unlike [`width_frac`] a timeline
2951/// with no length pins this to the left edge -- a full-width offset would push
2952/// the box out of the lane it belongs to.
2953fn start_frac(start: f64, total: f64) -> f32 {
2954 if total > 0. {
2955 (start / total).clamp(0., 1.) as f32
2956 } else {
2957 0.
2958 }
2959}
2960
2961/// The video-lane index of the take an audio clip belongs to, if the video lane
2962/// still holds that half. `None` for a half whose picture was lifted -- which is
2963/// what makes it a thing of its own to delete.
2964fn video_half(session: &PlaybackSession, audio: usize) -> Option<usize> {
2965 let link = session.lane_clips(Lane::Audio).get(audio)?.link?;
2966 session
2967 .lane_clips(Lane::Video)
2968 .iter()
2969 .position(|clip| clip.link == Some(link))
2970}
2971
2972/// Whether a click marks this clip: the clip that was clicked always, and the
2973/// other lane's clip of the same group with it. A clip whose group has no other
2974/// half -- what a lift leaves behind -- marks only itself, which is what makes a
2975/// detached half separately deletable.
2976fn marked(
2977 here: (Lane, usize),
2978 link: Option<u32>,
2979 sel: Option<(Lane, usize)>,
2980 sel_link: Option<u32>,
2981) -> bool {
2982 sel == Some(here) || (link.is_some() && link == sel_link)
2983}
2984
2985/// Whether a clip is wide enough to be worth naming.
2986fn show_label(w: f32) -> bool {
2987 w >= LABEL_MIN_W
2988}
2989
2990/// Scales an envelope to its own loudest sample, so a quietly mastered source
2991/// still draws as a shape. The fixtures peak around an eighth of full scale, and
2992/// an eighth of a 30 px lane is a flat line -- which says "silent" about a file
2993/// that is not.
2994fn normalise(mut peaks: Vec<(f32, f32)>) -> Vec<(f32, f32)> {
2995 let loudest = peaks.iter().fold(0f32, |m, &(lo, hi)| m.max(-lo).max(hi));
2996 if loudest > 0. {
2997 for (lo, hi) in &mut peaks {
2998 *lo /= loudest;
2999 *hi /= loudest;
3000 }
3001 }
3002 peaks
3003}
3004
3005/// The min/max envelope of `peaks` over the source seconds `from..to`, as
3006/// `(x, top, bottom)` columns of a `w` x `h` box. Every point is inside that box
3007/// -- a clip's waveform cannot paint over its neighbour -- and every column is
3008/// at least a pixel tall, so silence reads as a line through the middle rather
3009/// than as a polygon with no area.
3010fn envelope(peaks: &[(f32, f32)], from: f64, to: f64, w: f32, h: f32) -> Vec<(f32, f32, f32)> {
3011 if peaks.is_empty() || w <= 0. || h <= 0. {
3012 return Vec::new();
3013 }
3014 let cols = (w / WAVE_COL).ceil().max(1.) as usize;
3015 let mid = h / 2.;
3016 (0..=cols)
3017 .map(|col| {
3018 let along = col as f64 / cols as f64;
3019 let at = from + (to - from) * along;
3020 // Casting a float to an integer saturates in Rust, so a source
3021 // second past the end of the peaks clamps rather than wrapping.
3022 let bucket = ((at * f64::from(WAVE_BPS)) as usize).min(peaks.len() - 1);
3023 let (lo, hi) = peaks[bucket];
3024 let top = (mid - hi.clamp(0., 1.) * mid).min(mid - 0.5);
3025 let bottom = (mid - lo.clamp(-1., 0.) * mid).max(mid + 0.5);
3026 (w * along as f32, top.max(0.), bottom.min(h))
3027 })
3028 .collect()
3029}
3030
3031/// One clip's audio, drawn as a filled min/max envelope inside whatever box it
3032/// is given. Peaks are the source's whole envelope; `from`/`to` are the source
3033/// seconds this clip plays, so a cut clip shows its own stretch of the file.
3034fn waveform(peaks: Arc<Vec<(f32, f32)>>, from: f64, to: f64) -> impl IntoElement {
3035 canvas(
3036 |_, _, _| (),
3037 move |bounds, _, window, _| {
3038 let (o, s) = (bounds.origin, bounds.size);
3039 let cols = envelope(&peaks, from, to, f32::from(s.width), f32::from(s.height));
3040 if cols.len() < 2 {
3041 return;
3042 }
3043 // Down the tops and back along the bottoms: one closed outline of
3044 // the whole envelope, which is one path rather than a path a column.
3045 let mut points: Vec<Point<Pixels>> = cols
3046 .iter()
3047 .map(|&(x, top, _)| point(o.x + px(x), o.y + px(top)))
3048 .collect();
3049 points.extend(
3050 cols.iter()
3051 .rev()
3052 .map(|&(x, _, bottom)| point(o.x + px(x), o.y + px(bottom))),
3053 );
3054 let mut path = PathBuilder::fill();
3055 path.add_polygon(&points, true);
3056 if let Ok(path) = path.build() {
3057 window.paint_path(path, rgb(INK_DIM));
3058 }
3059 },
3060 )
3061 .size_full()
3062}
3063
3064/// A toolbar button: its glyph, its name, and its key on hover. `id` only buys
3065/// `on_click` and the tooltip -- it is still not focusable, so the root's own
3066/// key listener keeps working after a press, and the click lands on mouse-up
3067/// inside the button (a press that slides off does nothing).
3068///
3069/// A button that would do nothing says so: dimmed, no pointer, no listener.
3070fn control(
3071 id: &'static str,
3072 glyph: Option<AnyElement>,
3073 // Not `&'static str`: the volume button's label is its state.
3074 label: impl Into<SharedString>,
3075 shortcut: String,
3076 enabled: bool,
3077 on_click: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
3078) -> impl IntoElement {
3079 let label = label.into();
3080 let tip: SharedString = format!("{label} — {shortcut}").into();
3081 div()
3082 .id(id)
3083 .flex_none()
3084 .h(px(CONTROL_H))
3085 .flex()
3086 .items_center()
3087 .gap(px(6.))
3088 .px(px(8.))
3089 .rounded(px(3.))
3090 .bg(rgb(SURFACE))
3091 .children(glyph)
3092 .child(label)
3093 .tooltip(move |_, cx| cx.new(|_| Tip(tip.clone())).into())
3094 .when(!enabled, |d| d.opacity(0.4).cursor_not_allowed())
3095 .when(enabled, |d| {
3096 d.cursor_pointer()
3097 .hover(|s| s.bg(rgb(HOVER)))
3098 .on_click(on_click)
3099 })
3100}
3101
3102/// The line between two groups of buttons.
3103fn separator() -> impl IntoElement {
3104 div()
3105 .flex_none()
3106 .mx(px(4.))
3107 .w(px(1.))
3108 .h(px(18.))
3109 .bg(rgb(HOVER))
3110}
3111
3112/// A tooltip is a view in gpui and nothing smaller, so this is the smallest one
3113/// that carries a line of text. It paints outside the window's element tree and
3114/// therefore owns its colours.
3115struct Tip(SharedString);
3116
3117impl Render for Tip {
3118 fn render(&mut self, _: &mut Window, _: &mut Context<Self>) -> impl IntoElement {
3119 div()
3120 .px(px(6.))
3121 .py(px(3.))
3122 .rounded(px(3.))
3123 .border_1()
3124 .border_color(rgb(SURFACE))
3125 .bg(rgb(CHROME))
3126 .text_color(rgb(INK))
3127 .text_size(px(12.))
3128 .child(self.0.clone())
3129 }
3130}
3131
3132/// Scissors: two blades crossed. Drawn this way and not as a split clip because
3133/// two bars is what the transport wears when it is playing -- the one glyph a
3134/// cut must never be mistaken for.
3135fn cut_glyph() -> impl IntoElement {
3136 canvas(
3137 |_, _, _| (),
3138 |bounds, _, window, _| {
3139 let (o, s) = (bounds.origin, bounds.size);
3140 let mut path = PathBuilder::stroke(px(1.5));
3141 path.move_to(point(o.x + s.width * 0.15, o.y + s.height));
3142 path.line_to(point(o.x + s.width * 0.9, o.y + s.height * 0.1));
3143 path.move_to(point(o.x + s.width * 0.85, o.y + s.height));
3144 path.line_to(point(o.x + s.width * 0.1, o.y + s.height * 0.1));
3145 if let Ok(path) = path.build() {
3146 window.paint_path(path, rgb(INK));
3147 }
3148 },
3149 )
3150 .w(px(13.))
3151 .h(px(13.))
3152}
3153
3154/// A lid over a bin.
3155fn delete_glyph() -> impl IntoElement {
3156 div()
3157 .flex()
3158 .flex_col()
3159 .items_center()
3160 .gap(px(2.))
3161 .child(div().w(px(13.)).h(px(2.)).bg(rgb(INK)))
3162 .child(div().w(px(9.)).h(px(9.)).bg(rgb(INK)))
3163}
3164
3165/// Records its parent's laid-out box: gpui hands a mouse listener the window
3166/// position only, and the ruler sits behind the panel's padding. Paints
3167/// nothing and takes no hitbox of its own, so the click still reaches the bar.
3168fn bounds_probe(into: Rc<Cell<Bounds<Pixels>>>) -> impl IntoElement {
3169 canvas(move |bounds, _, _| into.set(bounds), |_, _, _, _| ())
3170 .absolute()
3171 .size_full()
3172}
3173
3174/// Where along an element a click landed, 0..1. An element that was never
3175/// painted has no width, and reads as its start rather than as NaN.
3176fn frac_along(x: Pixels, bounds: Bounds<Pixels>) -> f32 {
3177 if bounds.size.width <= px(0.) {
3178 return 0.;
3179 }
3180 ((x - bounds.left()) / bounds.size.width).clamp(0., 1.)
3181}
3182
3183/// What a window with no file open is waiting for. Both ways in are already
3184/// built -- the whole window is the drop target and the Import chooser takes a
3185/// project as readily as media -- so this only has to say so.
3186fn empty_hint() -> impl IntoElement {
3187 div()
3188 .flex()
3189 .flex_col()
3190 .items_center()
3191 .gap(px(6.))
3192 .text_color(rgb(INK_DIM))
3193 .child("Drop a video or an .edith project here")
3194 .child(
3195 div()
3196 .text_size(px(11.))
3197 .child("or click Import in the media list"),
3198 )
3199}
3200
3201/// Two bars while playing, a triangle while paused. Drawn, so there is no icon
3202/// font and no glyph coverage to depend on.
3203fn transport_glyph(playing: bool) -> impl IntoElement {
3204 div()
3205 .flex()
3206 .items_center()
3207 .gap(px(4.))
3208 .when(playing, |d| {
3209 d.child(div().w(px(3.)).h(px(12.)).bg(rgb(INK)))
3210 .child(div().w(px(3.)).h(px(12.)).bg(rgb(INK)))
3211 })
3212 .when(!playing, |d| {
3213 d.child(
3214 canvas(
3215 |_, _, _| (),
3216 |bounds, _, window, _| {
3217 let (o, s) = (bounds.origin, bounds.size);
3218 let mut path = PathBuilder::fill();
3219 path.move_to(o);
3220 path.line_to(point(o.x + s.width, o.y + s.height / 2.));
3221 path.line_to(point(o.x, o.y + s.height));
3222 path.close();
3223 if let Ok(path) = path.build() {
3224 window.paint_path(path, rgb(INK));
3225 }
3226 },
3227 )
3228 .w(px(11.))
3229 .h(px(13.)),
3230 )
3231 })
3232}
3233
3234/// NLE timecode: `HH:MM:SS:FF`, the frame counted inside its own second.
3235fn timecode(t: f64, fps: f64) -> String {
3236 let t = t.max(0.);
3237 let secs = t as u64;
3238 let last = (fps.ceil() as u64).saturating_sub(1);
3239 let frame = ((t - secs as f64) * fps) as u64;
3240 format!(
3241 "{:02}:{:02}:{:02}:{:02}",
3242 secs / 3600,
3243 secs / 60 % 60,
3244 secs % 60,
3245 frame.min(last)
3246 )
3247}
3248
3249#[cfg(test)]
3250mod tests {
3251 use super::{
3252 ACCENT, CONTROL_H, Clip, HEADER_GAP, HEADER_W, HIT_MIN, INK, INK_DIM, KEYS_ROW_H,
3253 KEYS_ROWS_H, KEYS_W, LABEL_H, LABEL_MIN_W, LANE_H, LETTERBOX, LIBRARY_MAX_W, LIBRARY_MIN_W,
3254 Lane, MENU_ITEMS, MENU_W, NO_FILE, PANEL_H, Quality, ROW_H, RULER_HIT_H, SELECTED,
3255 SOURCE_TINTS, SURFACE, SWATCH_W, Source, StreamInfo, Volume, WAVE_BPS, WAVE_COL, Wave,
3256 applicable, can_add, cancels_export, envelope, export_path, export_settings, frac_along,
3257 frame_at, is_bare_modifier, is_project, keymap, lane_clips, marked, menu_at, normalise,
3258 project_path, push_digit, scrub_due, show_label, source_frames, source_tint, start_frac,
3259 timecode, unseen_paths, unseen_sources, width_frac, window_title,
3260 };
3261 use super::{file_name, library_rows};
3262 use engine::PlaybackSession;
3263 use gpui::{Bounds, Pixels, point, px, size};
3264 use std::collections::HashMap;
3265 use std::path::{Path, PathBuf};
3266 use std::time::Duration;
3267
3268 fn asset(name: &str) -> PathBuf {
3269 Path::new(env!("CARGO_MANIFEST_DIR"))
3270 .join("../../assets")
3271 .join(name)
3272 }
3273
3274 /// A clip of `source`, `frames` long, at the top of the timeline. Only the
3275 /// two fields the library reads are meant to be looked at.
3276 fn clip(source: usize, frames: u32) -> Clip {
3277 Clip {
3278 start: 0,
3279 in_frame: 0,
3280 out_frame: frames,
3281 source,
3282 link: None,
3283 }
3284 }
3285
3286 /// A source entry for `path` on `stream`, as the project keeps them.
3287 fn source(path: &str, stream: usize) -> Source {
3288 Source {
3289 path: PathBuf::from(path),
3290 audio_stream: stream,
3291 }
3292 }
3293
3294 /// The whole of the library's row data comes off the clips: which files
3295 /// there are, how long each one is, and therefore which tint each row wears
3296 /// -- one index into one list, so a swatch cannot name a different file from
3297 /// the boxes it is meant to point at.
3298 #[test]
3299 fn a_rows_swatch_and_duration_come_off_the_clips_that_name_it() {
3300 // Source 0 whole, source 1 trimmed to half of what it was, source 2 on
3301 // the audio lane only (its picture was lifted), source 3 imported and
3302 // then undone -- an entry with nothing playing from it.
3303 let sources: Vec<Source> = (0..4).map(|i| source(&format!("/m/{i}.mp4"), 0)).collect();
3304 let video = [clip(0, 150), clip(1, 60)];
3305 let audio = [clip(0, 150), clip(1, 30), clip(2, 90)];
3306 for (row, frames) in [(0, 150), (1, 60), (2, 90), (3, 0)] {
3307 assert_eq!(
3308 source_frames(video.iter().chain(&audio), &sources, &sources[row].path),
3309 frames,
3310 "row {row}"
3311 );
3312 // The swatch is the clip colour, by the same index and the same
3313 // function -- what makes the panel and the lanes one association.
3314 assert_eq!(source_tint(row), SOURCE_TINTS[row % SOURCE_TINTS.len()]);
3315 }
3316 // The longest clip of a file wins, whichever lane it is in and
3317 // whatever order the lanes are read in.
3318 let one = [source("/m/0.mp4", 0)];
3319 let path = &one[0].path;
3320 assert_eq!(
3321 source_frames([clip(0, 10), clip(0, 90)].iter(), &one, path),
3322 90
3323 );
3324 assert_eq!(
3325 source_frames([clip(0, 90), clip(0, 10)].iter(), &one, path),
3326 90
3327 );
3328 assert_eq!(source_frames([].iter(), &one, path), 0);
3329 // Two audio streams of one file are two source entries and one length:
3330 // the second stream's row is placeable the moment the file is there,
3331 // before any clip names that entry.
3332 let two = [source("/m/0.mp4", 0), source("/m/0.mp4", 1)];
3333 assert_eq!(source_frames([clip(0, 90)].iter(), &two, &two[1].path), 90);
3334 }
3335
3336 fn info(
3337 index: usize,
3338 rate: u32,
3339 channels: u16,
3340 lang: Option<&str>,
3341 decodable: bool,
3342 ) -> StreamInfo {
3343 StreamInfo {
3344 index,
3345 codec: if decodable { "aac" } else { "unknown" }.into(),
3346 channels,
3347 sample_rate: rate,
3348 lang: lang.map(str::to_string),
3349 decodable,
3350 }
3351 }
3352
3353 /// A file's every audio track gets a row: the ones the timeline can take
3354 /// are placeable, the ones it cannot are listed greyed with the reason.
3355 /// Which rows exist at all is the branchy part of the panel, so it is
3356 /// planned as data and checked here rather than through the pointer.
3357 #[test]
3358 fn every_audio_stream_of_a_file_is_a_row_usable_or_not() {
3359 let multi = PathBuf::from("/m/movie.mp4");
3360 let sources = [source("/m/movie.mp4", 0)];
3361 let mut streams = HashMap::new();
3362 streams.insert(
3363 multi.clone(),
3364 vec![
3365 info(0, 44_100, 2, None, true),
3366 info(1, 44_100, 2, Some("fra"), true),
3367 info(2, 22_050, 1, Some("deu"), true),
3368 info(3, 0, 0, None, false),
3369 ],
3370 );
3371 let rows = library_rows(&sources, &streams, Some((44_100, 2)), |_| 90);
3372 assert_eq!(
3373 rows.iter().map(|r| r.stream).collect::<Vec<_>>(),
3374 [0, 1, 2, 3],
3375 "one row per audio stream, in file order"
3376 );
3377 assert!(
3378 rows.iter().all(|r| r.path == multi && r.tint == 0),
3379 "every stream of one file wears the file's own tint"
3380 );
3381 assert_eq!(rows[0].name, "movie.mp4 [audio 1]");
3382 assert_eq!(rows[1].name, "movie.mp4 [audio 2]");
3383 assert_eq!(rows[1].detail, "fra 44.1 kHz stereo");
3384 // Placeable: the one already on the timeline, and the one that matches
3385 // it. The 22 kHz mono track cannot join a 44.1 kHz stereo timeline --
3386 // one device and one copied AAC track for the whole of it -- and the
3387 // codec we cannot read cannot join anything. Both say which.
3388 assert_eq!((&rows[0].unusable, &rows[1].unusable), (&None, &None));
3389 assert_eq!(
3390 rows[2].unusable.as_deref(),
3391 Some("the timeline is 44.1 kHz stereo")
3392 );
3393 assert_eq!(rows[3].unusable.as_deref(), Some("unsupported codec"));
3394 assert_eq!(
3395 rows[3].detail, "",
3396 "a stream we cannot parse claims nothing"
3397 );
3398 // Every row is the same file, so every row is that file's length.
3399 assert!(rows.iter().all(|r| r.frames == 90));
3400
3401 // The single-stream case is exactly one row and no stream tag: no
3402 // regression for the media everything else in the world is.
3403 let plain = [source("/m/plain.mp4", 0)];
3404 let mut one = HashMap::new();
3405 one.insert(
3406 PathBuf::from("/m/plain.mp4"),
3407 vec![info(0, 44_100, 2, None, true)],
3408 );
3409 let rows = library_rows(&plain, &one, Some((44_100, 2)), |_| 90);
3410 assert_eq!(rows.len(), 1);
3411 assert_eq!(rows[0].name, "plain.mp4");
3412 assert_eq!(
3413 rows[0].detail, "",
3414 "one audio track is the row it has always been: name and length"
3415 );
3416 // ...as is a silent file, and a file not probed yet.
3417 let mut silent = HashMap::new();
3418 silent.insert(PathBuf::from("/m/plain.mp4"), Vec::new());
3419 for probe in [silent, HashMap::new()] {
3420 let rows = library_rows(&plain, &probe, None, |_| 90);
3421 assert_eq!(rows.len(), 1);
3422 assert_eq!(rows[0].name, "plain.mp4");
3423 assert_eq!(rows[0].detail, "");
3424 }
3425
3426 // A second stream *placed* on the timeline is a source entry of its
3427 // own: it keeps its row, no duplicate appears for it, and the rows of
3428 // one file stay together whatever order the entries came in.
3429 let placed = [
3430 source("/m/movie.mp4", 0),
3431 source("/m/other.mp4", 0),
3432 source("/m/movie.mp4", 2),
3433 ];
3434 streams.insert(
3435 PathBuf::from("/m/other.mp4"),
3436 vec![info(0, 44_100, 2, None, true)],
3437 );
3438 let rows = library_rows(&placed, &streams, Some((44_100, 2)), |_| 90);
3439 assert_eq!(
3440 rows.iter()
3441 .map(|r| (file_name(&r.path), r.stream))
3442 .collect::<Vec<_>>(),
3443 [
3444 ("movie.mp4".to_string(), 0),
3445 ("other.mp4".to_string(), 0),
3446 ("movie.mp4".to_string(), 2),
3447 ("movie.mp4".to_string(), 1),
3448 ("movie.mp4".to_string(), 3),
3449 ]
3450 );
3451 assert!(
3452 rows[2].unusable.is_none(),
3453 "a stream already on the timeline is playing, whatever a probe says"
3454 );
3455 assert_eq!(rows[1].tint, 1, "the other file is the other tint");
3456 }
3457
3458 /// What the clip menu offers, and where it hangs. The two items that act on
3459 /// the playhead rather than on the clicked clip are the ones that can be
3460 /// inapplicable, and a menu at the edge of the window has to come back
3461 /// inside it or its last item cannot be clicked at all.
3462 #[test]
3463 fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() {
3464 use keymap::{ActionId, Keymap};
3465 // Frames 30..90 of the timeline, taken from the head of its source.
3466 let clip = Clip {
3467 start: 30,
3468 in_frame: 0,
3469 out_frame: 60,
3470 source: 0,
3471 link: None,
3472 };
3473 assert_eq!(clip.end(), 90);
3474 // Cut splits from inside only: neither edge has anything to split off.
3475 assert!(applicable(&clip, ActionId::Cut, 31));
3476 assert!(applicable(&clip, ActionId::Cut, 89));
3477 assert!(!applicable(&clip, ActionId::Cut, 30));
3478 assert!(!applicable(&clip, ActionId::Cut, 90));
3479 assert!(!applicable(&clip, ActionId::Cut, 200));
3480 // Regroup is the other way round: only where this clip meets another.
3481 assert!(applicable(&clip, ActionId::Regroup, 30));
3482 assert!(applicable(&clip, ActionId::Regroup, 90));
3483 assert!(!applicable(&clip, ActionId::Regroup, 60));
3484 // The rest act on the clip that was clicked, so they always mean
3485 // something -- the engine words its own refusals.
3486 for action in [ActionId::Delete, ActionId::Lift, ActionId::ToggleMute] {
3487 assert!(applicable(&clip, action, 0));
3488 assert!(applicable(&clip, action, 60));
3489 }
3490 // The playhead frame is the engine's own rule, boundary included.
3491 assert_eq!(frame_at(1.0, 30.), 30);
3492 assert_eq!(frame_at(0.0, 30.), 0);
3493 assert_eq!(frame_at(-1.0, 30.), 0);
3494 // Where it hangs: at the pointer when it fits, back inside when not.
3495 let viewport = size(px(800.), px(400.));
3496 assert_eq!(menu_at(point(px(10.), px(10.)), viewport, 150.), (10., 10.));
3497 assert_eq!(
3498 menu_at(point(px(700.), px(380.)), viewport, 150.),
3499 (800. - MENU_W, 250.)
3500 );
3501 // A window smaller than the menu loses its bottom, never its top.
3502 assert_eq!(
3503 menu_at(point(px(90.), px(40.)), size(px(100.), px(50.)), 150.),
3504 (0., 0.)
3505 );
3506 // Every item is an action the registry knows, so the menu and the keys
3507 // menu say the same thing about it -- and none of them is unreachable
3508 // by keyboard, which is what makes the hint column worth drawing.
3509 let keymap = Keymap::defaults();
3510 for action in MENU_ITEMS {
3511 assert!(ActionId::ALL.contains(&action), "{action:?} is not listed");
3512 assert_ne!(keymap.display(action), "unbound", "{action:?}");
3513 }
3514 }
3515
3516 /// The refusal path, end to end against the real files: an incompatible
3517 /// import changes nothing, and the library mirrors `sources()` 1:1, so a
3518 /// refused file cannot leave a row behind.
3519 #[test]
3520 fn a_refused_import_leaves_no_row_and_an_accepted_one_is_whole() {
3521 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
3522 // Silent like the engine suite: this opens the real device.
3523 session.set_gain(0.0);
3524 assert_eq!(session.sources().len(), 1);
3525 let refusal = session
3526 .import(&asset("test_mismatch.mp4"))
3527 .expect_err("640x360 must not join a 1280x720 timeline")
3528 .to_string();
3529 assert!(refusal.contains("640"), "refusal must name it: {refusal}");
3530 assert_eq!(session.sources().len(), 1, "a refusal added a row");
3531 // An accepted one does add a row, and it reads as the whole file: 4 s
3532 // at 30 fps, exactly what was appended.
3533 session.import(&asset("test_av2.mp4")).expect("av2 matches");
3534 assert_eq!(session.sources().len(), 2);
3535 let second = session.sources()[1].path.clone();
3536 assert_eq!(
3537 source_frames(lane_clips(&session), session.sources(), &second),
3538 120
3539 );
3540 assert_eq!(timecode(120. / 30., 30.), "00:00:04:00");
3541 }
3542
3543 /// What the Add button and a dropped row both do, minus the pointer: the
3544 /// clip [`Player::insert_source`] builds, put in where the playhead is. One
3545 /// call, so what a drop does cannot drift from what the button does.
3546 #[test]
3547 fn adding_a_row_drops_the_whole_source_in_at_the_playhead() {
3548 let mut session = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
3549 session.set_gain(0.0);
3550 session.import(&asset("test_av2.mp4")).expect("av2 matches");
3551 assert_eq!(session.timeline_duration(), 9.0);
3552 // Two seconds in, which is inside the first take: the insert splits it.
3553 session.seek(2.0);
3554 let second = session.sources()[1].path.clone();
3555 let frames = source_frames(lane_clips(&session), session.sources(), &second);
3556 // Through the engine door `insert_source` uses, with the row's own
3557 // stream: the button, the drop and this are one call.
3558 assert!(
3559 session
3560 .place_stream_at(2.0, &second, 0, frames)
3561 .expect("av2 is already on the timeline")
3562 );
3563 // The whole of source 1 went in and nothing was painted over: the
3564 // timeline is longer by exactly that file.
3565 assert_eq!(session.timeline_duration(), 13.0);
3566 let (video, audio) = (
3567 session.lane_clips(Lane::Video),
3568 session.lane_clips(Lane::Audio),
3569 );
3570 // One take, not a video clip with no sound under it: both lanes hold
3571 // the same clip at the same place, in the same group.
3572 let at = |lane: &[Clip]| {
3573 *lane
3574 .iter()
3575 .find(|c| c.start == 60)
3576 .expect("inserted at 2 s")
3577 };
3578 assert_eq!(at(video), at(audio));
3579 assert_eq!(at(video).source, 1);
3580 assert_eq!(at(video).len(), frames);
3581 assert!(at(video).link.is_some());
3582 assert_eq!(video.len(), audio.len());
3583
3584 // The same door with a *second audio stream* of a file already there:
3585 // a new source entry, the same picture, and the row that was dragged
3586 // is what plays. This is the whole user-facing point of the slice.
3587 let mut session =
3588 PlaybackSession::open(asset("test_multilang.mp4")).expect("open the fixture");
3589 session.set_gain(0.0);
3590 let path = session.sources()[0].path.clone();
3591 let frames = source_frames(lane_clips(&session), session.sources(), &path);
3592 let end = session.timeline_duration();
3593 assert!(
3594 session
3595 .place_stream_at(end, &path, 1, frames)
3596 .expect("the French track shares the timeline's parameters")
3597 );
3598 assert_eq!(session.sources()[1].audio_stream, 1);
3599 assert_eq!(session.timeline_duration(), end * 2.0);
3600 // Both rows are the same file, so both rows are that file's length --
3601 // the second one before any clip of its own existed.
3602 assert_eq!(
3603 source_frames(lane_clips(&session), session.sources(), &path),
3604 frames
3605 );
3606 }
3607
3608 #[test]
3609 fn a_source_is_only_ever_asked_for_its_peaks_once() {
3610 let (a, b) = (asset("test_av.mp4"), asset("test_av2.mp4"));
3611 // Two files, and two streams of the first: three envelopes, because
3612 // one file's two audio tracks are two different waveforms.
3613 let sources = [
3614 Source {
3615 path: a.clone(),
3616 audio_stream: 0,
3617 },
3618 Source {
3619 path: a.clone(),
3620 audio_stream: 1,
3621 },
3622 Source {
3623 path: b.clone(),
3624 audio_stream: 0,
3625 },
3626 ];
3627 let keys = |s: &[Source]| {
3628 s.iter()
3629 .map(|s| (s.path.clone(), s.audio_stream))
3630 .collect::<Vec<_>>()
3631 };
3632 let mut waves: HashMap<(PathBuf, usize), Wave> = HashMap::new();
3633 assert_eq!(unseen_sources(&sources, &waves), keys(&sources));
3634 // The entry goes in when the decode *starts*, so the sixty repaints a
3635 // second that happen while it runs must not start it again -- which is
3636 // what this asserts about a key whose value is not an answer yet.
3637 waves.insert((a.clone(), 0), Wave::Loading);
3638 assert_eq!(
3639 unseen_sources(&sources, &waves),
3640 keys(&sources[1..]),
3641 "the file's other stream is a key of its own"
3642 );
3643 // A file with no audio is an answer like any other: never re-asked.
3644 waves.insert((a, 1), Wave::Silent);
3645 waves.insert((b.clone(), 0), Wave::Silent);
3646 assert!(unseen_sources(&sources, &waves).is_empty());
3647 // The stream probe is per *file*: the two entries of `a` ask once.
3648 let mut streams: HashMap<PathBuf, Vec<StreamInfo>> = HashMap::new();
3649 assert_eq!(
3650 unseen_paths(&sources, &streams),
3651 vec![asset("test_av.mp4"), b]
3652 );
3653 streams.insert(asset("test_av.mp4"), Vec::new());
3654 assert_eq!(unseen_paths(&sources, &streams).len(), 1);
3655 }
3656
3657 #[test]
3658 fn the_add_button_is_dead_unless_it_would_do_something() {
3659 let picked = (PathBuf::from("/m/0.mp4"), 0);
3660 assert!(can_add(Some(&picked), true, false));
3661 // Nothing picked, nothing to put it on, or an export reading the very
3662 // edit list this would change.
3663 assert!(!can_add(None, true, false));
3664 assert!(!can_add(Some(&picked), false, false));
3665 assert!(!can_add(Some(&picked), true, true));
3666 }
3667
3668 #[test]
3669 fn the_media_column_never_takes_the_picture_over() {
3670 for window in [360., 640., 1280., 1920., 3840.] {
3671 let w = super::library_w(window);
3672 // The whole point of the budget: the picture keeps the majority of
3673 // the row at every size a window can be.
3674 assert!(w <= window / 3., "{window}px window gave the list {w}px");
3675 assert!(w >= LIBRARY_MIN_W.min(window / 3.), "{window}px: {w}px");
3676 assert!(w <= LIBRARY_MAX_W);
3677 }
3678 // It yields: a narrower window gives the list less, never the same.
3679 assert!(super::library_w(640.) < super::library_w(1280.));
3680 // Rows are clickable, so WCAG 2.5.8 binds them like every other target,
3681 // and a name over a timecode has to fit inside one.
3682 assert!(ROW_H >= HIT_MIN);
3683 assert!(SWATCH_W < LIBRARY_MIN_W);
3684 }
3685
3686 #[test]
3687 fn the_window_is_named_after_the_program_and_what_is_open() {
3688 assert_eq!(window_title("test_av.mp4"), "test_av.mp4 — edith");
3689 // An empty window is the program, not "no file open — edith".
3690 assert_eq!(window_title(NO_FILE), "edith");
3691 }
3692
3693 #[test]
3694 fn frac_along_measures_from_the_elements_own_left_edge() {
3695 // A ruler inset by the panel's 12 px padding: window x is not bar x.
3696 let bar: Bounds<Pixels> = Bounds {
3697 origin: point(px(12.), px(400.)),
3698 size: size(px(200.), px(6.)),
3699 };
3700 assert_eq!(frac_along(px(12.), bar), 0.);
3701 assert_eq!(frac_along(px(112.), bar), 0.5);
3702 assert_eq!(frac_along(px(212.), bar), 1.);
3703 // Outside the bar (a click that slid off) clamps, never extrapolates.
3704 assert_eq!(frac_along(px(0.), bar), 0.);
3705 assert_eq!(frac_along(px(9999.), bar), 1.);
3706 // Never painted: no division by zero, no NaN reaching seek().
3707 assert_eq!(frac_along(px(50.), Bounds::default()), 0.);
3708 }
3709
3710 #[test]
3711 fn timecode_counts_frames_inside_the_second() {
3712 assert_eq!(timecode(0., 30.), "00:00:00:00");
3713 assert_eq!(timecode(-1., 30.), "00:00:00:00"); // clamped, never negative
3714 assert_eq!(timecode(4.9667, 30.), "00:00:04:29"); // last frame of a 5 s clip
3715 assert_eq!(timecode(5., 30.), "00:00:05:00");
3716 assert_eq!(timecode(3661.5, 30.), "01:01:01:15");
3717 // Rounding must not spill into a frame the second does not have.
3718 assert_eq!(timecode(1. - f64::EPSILON, 30.), "00:00:00:29");
3719 assert_eq!(timecode(0.999, 29.97), "00:00:00:29");
3720 }
3721
3722 #[test]
3723 fn scrub_seeks_only_on_a_new_frame_and_only_every_100ms() {
3724 let (slow, fast) = (Duration::from_millis(100), Duration::from_millis(99));
3725 // Both halves must hold: a moved pointer that has not crossed a frame
3726 // boundary would reopen the decoder for the same picture.
3727 assert!(scrub_due(31, 30, slow));
3728 assert!(!scrub_due(30, 30, slow));
3729 assert!(!scrub_due(31, 30, fast));
3730 assert!(!scrub_due(30, 30, fast));
3731 // Exactly at the gap counts, and a long stall never blocks.
3732 assert!(scrub_due(1, 0, Duration::from_secs(9)));
3733 }
3734
3735 #[test]
3736 fn export_lands_beside_the_source_and_never_on_it() {
3737 // The whole point: the export of an .mp4 is never that .mp4.
3738 assert_eq!(
3739 export_path("assets/test_baseline.mp4"),
3740 std::path::Path::new("assets/test_baseline.export.mp4")
3741 );
3742 // A second export of an export is still not its own source.
3743 assert_eq!(
3744 export_path("a.export.mp4"),
3745 std::path::Path::new("a.export.export.mp4")
3746 );
3747 // Extensionless and dotted-directory names keep the directory intact.
3748 assert_eq!(export_path("clip"), std::path::Path::new("clip.export.mp4"));
3749 assert_eq!(
3750 export_path("/v.1/clip.MP4"),
3751 std::path::Path::new("/v.1/clip.export.mp4")
3752 );
3753 }
3754
3755 #[test]
3756 fn the_first_save_lands_beside_the_media() {
3757 assert_eq!(
3758 project_path("assets/test_av.mp4"),
3759 std::path::Path::new("assets/test_av.edith")
3760 );
3761 // The same rule an export follows: only the last extension moves.
3762 assert_eq!(
3763 project_path("a.export.mp4"),
3764 std::path::Path::new("a.export.edith")
3765 );
3766 assert_eq!(project_path("clip"), std::path::Path::new("clip.edith"));
3767 // Saving a loaded project writes the file it came from, not a second.
3768 assert_eq!(project_path("a.edith"), std::path::Path::new("a.edith"));
3769 }
3770
3771 #[test]
3772 fn only_an_exact_edith_extension_is_a_project() {
3773 let p = std::path::Path::new;
3774 assert!(is_project(p("a.edith")));
3775 // A dotted directory must not decide it -- the file name does.
3776 assert!(is_project(p("/v.mp4/a.edith")));
3777 assert!(!is_project(p("a.mp4")));
3778 assert!(!is_project(p("/v.edith/a.mp4")));
3779 // Exactly what `save_project` writes: a dropped `.EDITH` goes to the
3780 // demuxer and is refused there, not parsed as a project.
3781 assert!(!is_project(p("a.EDITH")));
3782 // An extension, never a bare name.
3783 assert!(!is_project(p("edith")));
3784 assert!(!is_project(p("a.edith.mp4")));
3785 }
3786
3787 /// The keys menu is the registry drawn, so a *bindable* stroke cannot go
3788 /// missing from it by construction. The strokes the modal cards read for
3789 /// themselves are the ones that could: this reads the key handler's own
3790 /// source and fails on any key it answers to that the menu never mentions.
3791 #[test]
3792 fn no_stroke_is_missing_from_the_keys_menu() {
3793 use keymap::{ActionId, Keymap};
3794 // Everything above the test module -- the handler, and the helpers it
3795 // asks. The tests below compare keys too, and are not shortcuts.
3796 let handler = include_str!("main.rs")
3797 .split("#[cfg(test)]")
3798 .next()
3799 .unwrap();
3800 let keymap = Keymap::defaults();
3801 let listed = |key: &str| {
3802 let pretty = keymap::Chord {
3803 key: key.to_string(),
3804 ctrl: false,
3805 }
3806 .pretty();
3807 keymap.lookup(key, false).is_some() || keymap::FIXED.iter().any(|f| f.chord == pretty)
3808 };
3809 let mut compared = 0;
3810 for (at, needle) in handler.match_indices("key == ") {
3811 let rest = &handler[at + needle.len()..];
3812 let key = match rest.strip_prefix('"') {
3813 Some(literal) => {
3814 literal[..literal.find('"').expect("unterminated key")].to_string()
3815 }
3816 // A named constant: the escape the cards get out by.
3817 None if rest.starts_with("ESCAPE") => super::ESCAPE.to_string(),
3818 None => panic!("a key compared against something this cannot read: {rest:.20}"),
3819 };
3820 assert!(
3821 listed(&key),
3822 "the handler answers to {key:?} and the keys menu never says so"
3823 );
3824 compared += 1;
3825 }
3826 // The scan is only a guard while it still finds the comparisons: a
3827 // rewrite that spells them differently must come back here.
3828 assert!(
3829 compared >= 4,
3830 "the key comparisons moved; this scan is blind"
3831 );
3832 // The one branch that is not a comparison -- any digit is a bitrate.
3833 assert!(handler.contains("key.parse::<u32>()"));
3834 assert!(keymap::FIXED.iter().any(|f| f.chord == "0–9"));
3835 // And every entry of both halves lands under a heading the menu draws.
3836 for action in ActionId::ALL {
3837 assert!(keymap::Category::ALL.contains(&action.category()));
3838 }
3839 for fixed in &keymap::FIXED {
3840 assert!(keymap::Category::ALL.contains(&fixed.category));
3841 }
3842 }
3843
3844 #[test]
3845 fn clip_boxes_split_the_lane_by_duration() {
3846 // 1 s + 3 s of a 4 s timeline: a quarter and three quarters.
3847 assert_eq!(width_frac(1., 4.), 0.25);
3848 assert_eq!(width_frac(3., 4.), 0.75);
3849 assert_eq!(width_frac(4., 4.), 1.);
3850 // A timeline with no length must not hand gpui a NaN width.
3851 assert_eq!(width_frac(0., 0.), 1.);
3852 }
3853
3854 #[test]
3855 fn escape_gets_out_of_an_export_whatever_is_held_with_it() {
3856 use keymap::ActionId;
3857 // The regression this guards: looking the stroke up in the keymap made
3858 // ctrl+escape mean nothing, and an export that a modifier could trap
3859 // the user inside of is worse than an unbound chord.
3860 assert!(cancels_export("escape", None));
3861 assert!(cancels_export("escape", Some(ActionId::CancelExport)));
3862 // A rebound cancel works as well -- it adds a way out, never replaces
3863 // the one that always worked.
3864 assert!(cancels_export("q", Some(ActionId::CancelExport)));
3865 // Nothing else does, whatever it means outside an export.
3866 assert!(!cancels_export("e", Some(ActionId::Export)));
3867 assert!(!cancels_export("space", Some(ActionId::Play)));
3868 assert!(!cancels_export("q", None));
3869 }
3870
3871 #[test]
3872 fn a_capture_waits_through_a_lone_modifier() {
3873 // gpui delivers these on their own; taking one as a binding would make
3874 // the action fire on the way to every chord that uses it.
3875 for key in [
3876 "control", "shift", "alt", "super", "platform", "function", "fn", "meta", "command",
3877 ] {
3878 assert!(is_bare_modifier(key), "{key}");
3879 }
3880 // Everything a binding is actually made of, escape included -- the
3881 // capture branch turns that one away itself.
3882 for key in ["c", "x", "space", "escape", "delete", "f1", "z"] {
3883 assert!(!is_bare_modifier(key), "{key}");
3884 }
3885 }
3886
3887 #[test]
3888 fn the_keybindings_card_fits_the_smallest_window() {
3889 // The row list is capped and scrolls, so the card's height no longer
3890 // depends on how many actions there are: a title, a status line and the
3891 // viewport, inside the 640x360 the rest of the layout is sized for.
3892 let title = 17.; // 13 px text on its own line
3893 let status = 28.; // 11 px text, two lines: a refusal wraps
3894 let gaps = 3. * 2.;
3895 let padding = 24.;
3896 assert!(
3897 title + status + KEYS_ROWS_H + gaps + padding <= 360.,
3898 "card too tall"
3899 );
3900 // The cap is only honest if it is the taller list that scrolls, not the
3901 // card that grows: every action must be reachable by scrolling, and
3902 // enough of them visible that the list reads as a list.
3903 assert!(
3904 KEYS_ROWS_H / KEYS_ROW_H >= 8.,
3905 "too few rows visible to scan"
3906 );
3907 assert!(KEYS_W <= 640., "card too wide");
3908 // The rows are clickable, so WCAG 2.5.8 binds them like every other
3909 // target in this window.
3910 assert!(KEYS_ROW_H >= HIT_MIN);
3911 }
3912
3913 /// Mute and level are one control with two states, and the whole point is
3914 /// that mute keeps the level: the user gets back what they had, not 100%.
3915 #[test]
3916 fn muting_keeps_the_level_it_comes_back_to() {
3917 let mut volume = Volume::default();
3918 assert_eq!(volume.gain(), 1.0);
3919 assert_eq!(volume.label(), "Vol 100%");
3920
3921 // Four presses down, then muted: the gain is silence but the level is
3922 // still what it was, and the button keeps saying so.
3923 for _ in 0..4 {
3924 volume.step(false);
3925 }
3926 assert_eq!(volume.gain(), 0.8);
3927 volume.muted = true;
3928 assert_eq!(volume.gain(), 0.0);
3929 assert_eq!(volume.label(), "Muted 80%");
3930
3931 // Turning it down while muted stays muted -- the one thing a mute
3932 // button must never do is get louder because you asked for quieter.
3933 volume.step(false);
3934 assert_eq!(volume.gain(), 0.0);
3935 assert!(volume.muted);
3936
3937 // Unmute returns to the level, including the step taken while silent.
3938 volume.muted = false;
3939 assert_eq!(volume.gain(), 0.75);
3940 }
3941
3942 /// Both ends hold under a key held down: the ABI only accepts `0.0..=1.0`,
3943 /// and a wrapped step count would hand it something else.
3944 #[test]
3945 fn the_volume_stops_at_both_ends() {
3946 let mut volume = Volume::default();
3947 for _ in 0..40 {
3948 volume.step(true);
3949 }
3950 assert_eq!(volume.gain(), 1.0);
3951 assert_eq!(volume.steps, Volume::MAX_STEPS);
3952
3953 for _ in 0..40 {
3954 volume.step(false);
3955 }
3956 assert_eq!(volume.gain(), 0.0);
3957 assert_eq!(volume.label(), "Vol 0%");
3958
3959 // Silent by the level rather than by the flag is still not muted: the
3960 // button says which, because only one of them survives a step up.
3961 assert!(!volume.muted);
3962 volume.step(true);
3963 assert_eq!(volume.gain(), 0.05);
3964 }
3965
3966 #[test]
3967 fn a_quality_row_is_the_bitrate_it_promises() {
3968 // Auto is the one row that says nothing: the exporter derives it, and
3969 // a number typed against the custom row must not leak into it.
3970 assert_eq!(export_settings(Quality::Auto, 7).bitrate, None);
3971 assert_eq!(export_settings(Quality::Low, 0).bitrate, Some(2_000_000));
3972 assert_eq!(export_settings(Quality::Medium, 0).bitrate, Some(6_000_000));
3973 assert_eq!(export_settings(Quality::High, 0).bitrate, Some(12_000_000));
3974 // Megabits as typed, and as the row says it back.
3975 assert_eq!(export_settings(Quality::Custom, 7).bitrate, Some(7_000_000));
3976 assert_eq!(Quality::Low.detail(0), "2 Mbps");
3977 // Every fixed row sits inside the engine's clamp (export.rs:290), so no
3978 // row can promise a bitrate the exporter silently changes.
3979 for quality in Quality::ALL {
3980 let settings = export_settings(quality, 7);
3981 if let Some(bitrate) = settings.bitrate {
3982 assert!(
3983 (1_000_000..=20_000_000).contains(&bitrate),
3984 "{quality:?} outside the engine clamp"
3985 );
3986 }
3987 // The software pin is the environment's to set, never a row's.
3988 assert!(!settings.force_sw);
3989 }
3990 }
3991
3992 #[test]
3993 fn a_typed_bitrate_stops_at_two_digits() {
3994 assert_eq!(push_digit(0, 8), 8);
3995 assert_eq!(push_digit(1, 2), 12);
3996 // A third digit is refused whole: the ceiling is 20 Mbps, so it can
3997 // only be a mistake, and dropping it silently would leave the card
3998 // showing a number nobody typed.
3999 assert_eq!(push_digit(12, 3), 12);
4000 assert_eq!(push_digit(99, 9), 99);
4001 // Never past what the clamp can take back to a real bitrate.
4002 assert!(u64::from(push_digit(99, 9)) * 1_000_000 < u64::from(u32::MAX));
4003 }
4004
4005 #[test]
4006 fn the_export_card_fits_the_smallest_window() {
4007 // Same 640x360 floor the keybindings card is measured against: a
4008 // destination row, one row per quality, the fixed-format line and the
4009 // confirm button, under a title and a status line.
4010 let rows = Quality::ALL.len() as f32 + 1.;
4011 let title = 17.;
4012 let status = 28.;
4013 let fixed = 17.;
4014 let gaps = (rows + 3.) * 2.;
4015 let padding = 24.;
4016 assert!(
4017 title + status + rows * KEYS_ROW_H + fixed + CONTROL_H + 4. + gaps + padding <= 360.,
4018 "card too tall"
4019 );
4020 // Clickable rows, so WCAG 2.5.8 binds them as it binds the panel's.
4021 assert!(KEYS_ROW_H >= HIT_MIN);
4022 assert!(CONTROL_H >= HIT_MIN);
4023 }
4024
4025 #[test]
4026 fn nothing_clickable_is_smaller_than_the_wcag_minimum() {
4027 // Every hit target in the panel, including the scrub strip -- whose bar
4028 // is 6 px to look at and whose click area must not be.
4029 assert!(CONTROL_H >= HIT_MIN);
4030 assert!(RULER_HIT_H >= HIT_MIN);
4031 assert!(LANE_H >= HIT_MIN);
4032 }
4033
4034 /// WCAG 2.1 relative luminance of a packed `0xRRGGBB`.
4035 fn luminance(colour: u32) -> f64 {
4036 let channel = |shift: u32| {
4037 let s = f64::from((colour >> shift) & 0xff) / 255.;
4038 if s <= 0.03928 {
4039 s / 12.92
4040 } else {
4041 ((s + 0.055) / 1.055).powf(2.4)
4042 }
4043 };
4044 0.2126 * channel(16) + 0.7152 * channel(8) + 0.0722 * channel(0)
4045 }
4046
4047 /// WCAG 2.1 contrast ratio, 1..=21.
4048 fn contrast(a: u32, b: u32) -> f64 {
4049 let (a, b) = (luminance(a), luminance(b));
4050 (a.max(b) + 0.05) / (a.min(b) + 0.05)
4051 }
4052
4053 #[test]
4054 fn a_lane_row_is_a_fixed_header_and_a_bed_that_can_be_hit() {
4055 // The header column is what the ruler is offset by as well, so both
4056 // numbers are shared rather than repeated per row (A-MUST1/A-MUST2).
4057 assert!(HEADER_W > 0. && HEADER_GAP >= 0.);
4058 // Two lanes, a ruler, a button row and the timecode line, inside the
4059 // panel the window is sized for.
4060 assert!(
4061 CONTROL_H + RULER_HIT_H + 2. * LANE_H + 17. + 4. * 8. + 16. <= PANEL_H,
4062 "the second lane does not fit the panel"
4063 );
4064 // Headers and clip boxes are as tall as the lane, and the lane is a
4065 // click target (WCAG 2.5.8).
4066 assert!(LANE_H >= HIT_MIN);
4067 // A label row that ate the whole lane would leave no waveform.
4068 assert!(LABEL_H < LANE_H / 2.);
4069 }
4070
4071 #[test]
4072 fn a_click_marks_the_whole_group_and_nothing_else() {
4073 let (v, a) = ((Lane::Video, 0), (Lane::Audio, 0));
4074 // Clicking the video half of group 1 marks the audio half with it.
4075 assert!(marked(v, Some(1), Some(v), Some(1)));
4076 assert!(marked(a, Some(1), Some(v), Some(1)));
4077 // Another group's clips stay unmarked, in either lane.
4078 assert!(!marked((Lane::Video, 1), Some(2), Some(v), Some(1)));
4079 assert!(!marked((Lane::Audio, 1), Some(2), Some(v), Some(1)));
4080 // A half a lift left behind has no group: it marks itself only, which
4081 // is what makes it separately deletable. Two ungrouped clips must not
4082 // mark each other by both being ungrouped.
4083 assert!(marked(a, None, Some(a), None));
4084 assert!(!marked(v, None, Some(a), None));
4085 // Nothing selected marks nothing.
4086 assert!(!marked(v, Some(1), None, None));
4087 }
4088
4089 #[test]
4090 fn a_name_is_dropped_rather_than_smeared_across_a_thin_clip() {
4091 assert!(show_label(LABEL_MIN_W));
4092 assert!(show_label(400.));
4093 assert!(!show_label(LABEL_MIN_W - 0.1));
4094 // A timeline with no length must not put a box outside its lane.
4095 assert_eq!(start_frac(3., 0.), 0.);
4096 assert_eq!(start_frac(1., 4.), 0.25);
4097 // Past the end clamps rather than running off the bed.
4098 assert_eq!(start_frac(8., 4.), 1.);
4099 }
4100
4101 #[test]
4102 fn an_envelope_stays_inside_the_box_it_is_drawn_in() {
4103 // A ramp: silence at the start, full scale at the end.
4104 let peaks: Vec<(f32, f32)> = (0..40)
4105 .map(|i| (-(i as f32) / 39., i as f32 / 39.))
4106 .collect();
4107 let (w, h) = (100., 30.);
4108 let cols = envelope(&peaks, 0., 1., w, h);
4109 assert_eq!(cols.len(), (w / WAVE_COL) as usize + 1);
4110 for &(x, top, bottom) in &cols {
4111 assert!((0. ..=w).contains(&x), "x {x} outside 0..{w}");
4112 assert!((0. ..=h).contains(&top), "top {top} outside 0..{h}");
4113 assert!(
4114 (0. ..=h).contains(&bottom),
4115 "bottom {bottom} outside 0..{h}"
4116 );
4117 // Never inverted, and never a polygon with no area: silence has to
4118 // read as a line rather than as nothing at all.
4119 assert!(
4120 bottom - top >= 1.,
4121 "column {top}..{bottom} is thinner than a pixel"
4122 );
4123 }
4124 // The ramp is drawn as a ramp: the last column is taller than the first.
4125 let height = |&(_, top, bottom): &(f32, f32, f32)| bottom - top;
4126 assert!(height(cols.last().unwrap()) > height(cols.first().unwrap()) + 5.);
4127 // Degenerate inputs draw nothing rather than panicking.
4128 assert!(envelope(&[], 0., 1., w, h).is_empty());
4129 assert!(envelope(&peaks, 0., 1., 0., h).is_empty());
4130 // A clip whose range runs past the peaks clamps to the last bucket.
4131 assert!(!envelope(&peaks, 0., 99., w, h).is_empty());
4132 }
4133
4134 #[test]
4135 fn a_quiet_source_still_draws_as_a_shape() {
4136 // An eighth of full scale, which is about where the fixtures sit.
4137 let quiet: Vec<(f32, f32)> = vec![(-0.125, 0.125), (-0.0625, 0.0625)];
4138 let loud = normalise(quiet.clone());
4139 assert_eq!(loud[0], (-1., 1.));
4140 assert_eq!(loud[1], (-0.5, 0.5));
4141 // Digital silence has no loudest sample to scale to; it must not divide
4142 // by zero and must stay flat.
4143 assert_eq!(normalise(vec![(0., 0.)]), vec![(0., 0.)]);
4144 assert!(normalise(Vec::new()).is_empty());
4145 }
4146
4147 /// The whole waveform path, from the file on disk to the columns that get
4148 /// painted: what no screenshot can assert about the shape.
4149 #[test]
4150 fn the_fixtures_waveform_reaches_the_lane_as_a_shape() {
4151 let asset = |name: &str| {
4152 std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
4153 .join("../../assets")
4154 .join(name)
4155 };
4156 let peaks = normalise(
4157 engine::waveform::peaks(asset("test_av.mp4"), 0, WAVE_BPS)
4158 .expect("open the fixture")
4159 .expect("test_av.mp4 has audio"),
4160 );
4161 // 5 s of source at the rate the lane asks for.
4162 assert!(peaks.len().abs_diff(5 * WAVE_BPS as usize) <= WAVE_BPS as usize);
4163 let cols = envelope(&peaks, 0., 5., 600., 30.);
4164 let height = |&(_, top, bottom): &(f32, f32, f32)| bottom - top;
4165 let tallest = cols.iter().map(height).fold(0., f32::max);
4166 let flattest = cols.iter().map(height).fold(f32::MAX, f32::min);
4167 // The fixture's 1 Hz pulse: a full-scale peak and a near-silent dip in
4168 // every second, so the drawn envelope is a shape and not a bar.
4169 assert!(tallest > 25., "loudest column only {tallest} px of 30");
4170 assert!(
4171 flattest < 8.,
4172 "quietest column {flattest} px -- no dips drawn"
4173 );
4174 // A video-only source draws no waveform at all rather than a flat fake.
4175 assert!(
4176 engine::waveform::peaks(asset("test_baseline.mp4"), 0, WAVE_BPS)
4177 .expect("open the fixture")
4178 .is_none()
4179 );
4180 }
4181
4182 #[test]
4183 fn every_mark_on_a_clip_is_legible_on_it() {
4184 for (i, tint) in SOURCE_TINTS.iter().enumerate() {
4185 // WCAG 1.4.3: the clip's name is body text on its tint.
4186 assert!(
4187 contrast(INK, *tint) >= 4.5,
4188 "source {i}: label contrast {:.2}",
4189 contrast(INK, *tint)
4190 );
4191 // WCAG 1.4.11: the waveform is a non-text graphic on it.
4192 assert!(
4193 contrast(INK_DIM, *tint) >= 3.,
4194 "source {i}: waveform contrast {:.2}",
4195 contrast(INK_DIM, *tint)
4196 );
4197 }
4198 // A selected clip's bed is the same two marks on a different colour.
4199 assert!(contrast(INK, SELECTED) >= 4.5);
4200 assert!(contrast(INK_DIM, SELECTED) >= 3.);
4201 // The bed a gap shows through has to read as a hole in the lane, and
4202 // the accent playhead has to be findable on it.
4203 assert!(contrast(LETTERBOX, SURFACE) >= 1.5);
4204 assert!(contrast(ACCENT, LETTERBOX) >= 3.);
4205 // The sanity check on the ratio itself: black on white is 21:1.
4206 assert!((contrast(0xffffff, 0x000000) - 21.).abs() < 0.01);
4207 }
4208
4209 #[test]
4210 fn source_tints_differ_per_source_and_cycle() {
4211 // The file the session opened with is the unchanged lane colour.
4212 assert_eq!(source_tint(0), SURFACE);
4213 // Neighbouring sources must not share one, or an import is invisible.
4214 assert_ne!(source_tint(0), source_tint(1));
4215 assert_ne!(source_tint(1), source_tint(2));
4216 assert_ne!(source_tint(2), source_tint(3));
4217 // Past the palette it wraps -- never an index panic.
4218 assert_eq!(source_tint(4), source_tint(0));
4219 assert_eq!(source_tint(9), source_tint(1));
4220 assert_eq!(source_tint(usize::MAX), SOURCE_TINTS[usize::MAX % 4]);
4221 }
4222}
4223
4224fn main() {
4225 let arg = std::env::args().nth(1).map(PathBuf::from);
4226 // A `.edith` restores a whole timeline, anything else *is* the timeline.
4227 // Either way the rest of argv is appended to what comes out. No argument at
4228 // all opens the window empty -- the timeline then arrives by drop or by the
4229 // Import button, and everything below is derived from it at that point
4230 // instead.
4231 let mut session = match &arg {
4232 Some(arg) => {
4233 let opened = if is_project(arg) {
4234 PlaybackSession::open_project(arg)
4235 } else {
4236 PlaybackSession::open(arg)
4237 };
4238 match opened {
4239 Ok(v) => Some(v),
4240 Err(e) => {
4241 // A failed load by drop leaves the running session alone;
4242 // here a file was named and could not be opened, so the
4243 // refusal is the whole run.
4244 eprintln!("cannot open {}: {e}", arg.display());
4245 std::process::exit(1);
4246 }
4247 }
4248 }
4249 None => None,
4250 };
4251 // A keymap file that cannot be read leaves the defaults in force, and takes
4252 // the notice slot ahead of an import refusal below: it is about every key
4253 // the window has, and the import refusal is on stderr either way.
4254 let (keymap, mut notice) = Keymap::load();
4255 if let Some(text) = &notice {
4256 eprintln!("{text}");
4257 }
4258 // The first file makes the timeline, the rest are appended to it. A refusal
4259 // is not fatal -- the others still load -- but the window must not open
4260 // silently pretending the file was taken, so the first one seeds the notice.
4261 for extra in std::env::args().skip(2) {
4262 // Only reachable with a first argument, so there is a timeline.
4263 if let Some(session) = &mut session
4264 && let Err(e) = session.import(std::path::Path::new(&extra))
4265 {
4266 let text = format!("IMPORT FAILED: {e}");
4267 eprintln!("{extra}: {text}");
4268 notice.get_or_insert(text);
4269 }
4270 }
4271 // A file that plays silent is as much news at launch as it is on a drop, and
4272 // behind the keymap notice for the same reason an import refusal is.
4273 if let Some(reason) = session
4274 .as_ref()
4275 .and_then(PlaybackSession::audio_disabled_reason)
4276 {
4277 let text = format!("NO AUDIO: {reason}");
4278 eprintln!("{text}");
4279 notice.get_or_insert(text);
4280 }
4281 let meta = session.as_ref().map(|session| *session.meta());
4282 // Beside the media even for a project: an export has never landed anywhere
4283 // but next to the picture it came from.
4284 let out = session.as_ref().map_or_else(PathBuf::new, |session| {
4285 export_path(&session.sources()[0].path)
4286 });
4287 let project = match &arg {
4288 Some(arg) if is_project(arg) => arg.clone(),
4289 Some(arg) => project_path(arg),
4290 // Chosen with the file, once there is one to choose it from.
4291 None => PathBuf::new(),
4292 };
4293 let name: SharedString = arg
4294 .as_deref()
4295 .map_or_else(|| NO_FILE.into(), |arg| file_name(arg).into());
4296 if let (Some(arg), Some(meta)) = (&arg, &meta) {
4297 println!(
4298 "{}: {}x{} @ {:.2} fps, {} samples",
4299 arg.display(),
4300 meta.width,
4301 meta.height,
4302 meta.frame_rate,
4303 meta.frame_count
4304 );
4305 }
4306
4307 Application::new().run(move |cx: &mut App| {
4308 // The picture's own size, or 720p when there is no picture yet: the
4309 // empty window is a landing pad, not a sliver.
4310 let (w, h) = meta.map_or((1280., 720.), |meta| {
4311 (meta.width as f32, meta.height as f32)
4312 });
4313 let bounds = Bounds::centered(None, size(px(w), px(h)), cx);
4314 cx.open_window(
4315 WindowOptions {
4316 window_bounds: Some(WindowBounds::Windowed(bounds)),
4317 titlebar: Some(TitlebarOptions {
4318 title: Some("edith".into()),
4319 ..Default::default()
4320 }),
4321 // What a desktop groups this window under. The title beside it
4322 // is pushed from the render, because wayland takes neither of
4323 // them from the titlebar options above (gpui's wayland window
4324 // reads only `app_id`, window.rs:1202 / window.rs:939) and the
4325 // title has to follow the file being opened anyway.
4326 app_id: Some("edith".to_string()),
4327 ..Default::default()
4328 },
4329 |window, cx| {
4330 let player = cx.new(|cx| Player {
4331 // A file named on the command line owes its first frame the
4332 // same repaint a seek's still owes: nothing plays by
4333 // itself, so this is what carries the poster frame to the
4334 // screen. An empty window has none to wait for.
4335 pending_seek: session.is_some(),
4336 session,
4337 // Full and unmuted, which is what the session it was just
4338 // handed is already set to: nothing to push at startup.
4339 volume: Volume::default(),
4340 // Only ever used with a timeline; 30 keeps the empty
4341 // timecode reading in frames rather than in NaN.
4342 fps: meta.map_or(30., |meta| meta.frame_rate),
4343 name: name.clone(),
4344 image: None,
4345 held: None,
4346 eos: false,
4347 done: false,
4348 ruler: Rc::default(),
4349 selected: None,
4350 context_menu: None,
4351 selected_asset: None,
4352 waves: HashMap::new(),
4353 streams: HashMap::new(),
4354 clipboard: None,
4355 scrubbing: false,
4356 last_scrub: Instant::now(),
4357 last_target: 0,
4358 export: None,
4359 cancelling: false,
4360 export_path: out.clone(),
4361 project_path: project.clone(),
4362 keymap: keymap.clone(),
4363 keys_open: false,
4364 export_open: false,
4365 // What an export is until someone says otherwise: the
4366 // bitrate the picture asks for.
4367 quality: Quality::Auto,
4368 custom_mbps: 0,
4369 rebinding: None,
4370 notice: notice.clone().map(SharedString::from),
4371 // Nothing pushed yet, and never a real title: the first
4372 // render is what names the window.
4373 titled: String::new(),
4374 displayed: 0,
4375 dropped: 0,
4376 started: None,
4377 focus: cx.focus_handle(),
4378 });
4379 // Nothing else takes focus, and without it the key listener
4380 // above is never reached.
4381 window.focus(&player.read(cx).focus);
4382 player
4383 },
4384 )
4385 .unwrap();
4386 cx.activate(true);
4387 });
4388}