forge
Explore
Log in

Don't you dare go Hollow

The window's doing moves out from under its being

Browse files at this commit

47b29eafcdde4ab605511d2093ce8a971613fe48Ahmet Kaan GümüşParent: 963252a
  • chore
    • the window's doing moves out from under its being
Show full message
🔧 chore(app): the window's doing moves out from under its being

`impl Player` was 4,330 lines of it -- the pump, the dispatch, the
selection, every card, the whole timeline edit, the library door and the
export -- in one block under the struct it acts on. Each of those is a
kind of doing, so each is a module: `player/{transport,actions,view,
cards,timeline_edit,library,export}.rs`, seven detached `impl Player`
blocks beside the state rather than inside it.

`struct Player` and `impl Render for Player` stay in `main.rs`, which is
what keeps this invisible: the state and the paint are still one file,
and nothing that reads them had to move or be renamed.

Pure motion: 164 methods, each exactly once, every line the line it was,
with pub(crate) added because a module boundary now stands between them
and their callers. Player::enable still delegates to the one oracle.

9 changed files +4382 -4331

crates/app/src/main.rsmodified+1 -4331

Diff too large; view file

@@ -1,4 +1,5 @@
11 mod keymap;
2+mod player;
23 mod ui;
34
45 mod audio_cards;
@@ -502,4337 +503,6 @@ struct Player {
502503 focus: FocusHandle,
503504 }
504505
505-impl Player {
506- /// Catches the display up to the clock: everything already due is taken off
507- /// the channel and only the last of them is shown, which *is* the
508- /// drop-when-behind policy. A frame that is not due yet waits in `held`, and
509- /// while the clock is paused *nothing* is due -- a repaint re-presents the
510- /// frame already on screen, whatever asked for the repaint.
511- fn pump(&mut self, window: &mut Window) {
512- // Where the transport was before this drain, so the crossing into
513- // `Ended` can be recognised as the one transition it is.
514- let was = self.transport();
515- // No timeline, nothing to catch up to: the window is showing its empty
516- // state and there is no decoder to drain.
517- let Some(session) = &mut self.session else {
518- return;
519- };
520- let target = session.now() * self.fps;
521- let mut newest: Option<Frame> = None;
522- // A frame the screen is owed: a seek's landing, and the one readiness
523- // signal there is ([`Player::reset_after_reseek`]).
524- let owed = self.seek_since.is_some();
525- // Paused, the clock is frozen and *nothing new is due*. Whatever the
526- // decoder is still handing over is the backlog it was behind by when
527- // the pause landed -- frames at a position the transport has already
528- // left -- and taking one per repaint is what walked the picture on
529- // after the sound had stopped, at exactly the rate the pointer was
530- // moved over the timeline. Gated here, at the one place a frame ever
531- // reaches the screen, rather than in the handlers that repaint: a
532- // hover, a notice, a resize and a vsync are all the same event to this.
533- // An owed frame is still taken, playing or not -- a scrub is paused by
534- // definition, and its landing is the whole point of it.
535- while session.is_playing() || owed {
536- let frame = match self.held.take() {
537- Some(frame) => frame,
538- // Nothing waiting means either a clip boundary being rebuilt or
539- // the real end of the timeline, and only the engine can tell
540- // them apart -- `frame.index` is already a timeline index.
541- None => match session.try_frame() {
542- Some(frame) => frame,
543- None => break,
544- },
545- };
546- if f64::from(frame.index) <= target {
547- self.dropped += u32::from(newest.is_some());
548- newest = Some(frame);
549- } else {
550- self.held = Some(frame);
551- break;
552- }
553- }
554-
555- // How far behind the master clock the picture just handed over is, in
556- // seconds. Measured off a frame that really arrived and nothing else: a
557- // clip boundary being reopened delivers nothing at all for hundreds of
558- // milliseconds, and restarting *that* would only cancel the open it is
559- // waiting on.
560- let late = newest
561- .as_ref()
562- .map_or(0., |f| (target - f64::from(f.index)) / self.fps);
563-
564- if let Some(frame) = newest {
565- self.displayed += 1;
566- self.seek_since = None;
567- self.started.get_or_insert_with(|| {
568- eprintln!("first frame displayed (index {})", frame.index);
569- Instant::now()
570- });
571- let buf = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra)
572- .expect("frame buffer sized width*height*4");
573- // Counted here rather than under `color_open`, because the card
574- // opens on a frame that was pumped before it: gating this on the
575- // card would leave its graph flat until something reseeked. A
576- // thousandth of the pixels, against a conversion that just touched
577- // all of them.
578- self.histogram = histogram(buf.as_raw());
579- let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)]));
580- if let Some(old) = self.image.replace(next) {
581- // Every RenderImage gets a fresh id and its own atlas tile:
582- // without this the sprite atlas grows for the whole video.
583- let _ = window.drop_image(old);
584- }
585- }
586-
587- // Audio is the master clock and a decoder that cannot keep up with it
588- // never gets back on its own: it hands over every frame in order,
589- // whether or not its moment has passed, so what it is behind by only
590- // grows -- a minute in, the picture is seconds behind what is being
591- // heard, and that is the whole of "the video can't catch the audio".
592- // Past `LATE_RESYNC` the backlog is abandoned and the picture restarted
593- // at the clock, which touches neither the sound nor the clock
594- // (`PlaybackSession::resync_picture`), so nothing the ear is following
595- // moves. Never on a frame a seek owed: that one is late by however long
596- // its own reopen took, and answering it with another reopen is a loop.
597- //
598- // corner-cut: on a machine that cannot decode the file in real time at
599- // all this settles into one restart per `RESYNC_GAP` -- in sync, and
600- // stuttering, which is the honest picture of what that machine can do.
601- // The upgrade path is dropping late frames *inside* the worker (skip
602- // the convert and the send for anything already past due), which needs
603- // the deadline shared with it.
604- if !owed && session.is_playing() && should_resync(late, self.resynced) {
605- eprintln!("picture {late:.3}s behind the clock: restarting it there");
606- session.resync_picture();
607- self.held = None;
608- self.resynced = Some(Instant::now());
609- }
610-
611- if self.transport() == Transport::Ended {
612- // A seek whose worker never produced a frame (vanished file) would
613- // otherwise repaint at vsync forever. Held clear for as long as the
614- // state does, not just on the crossing: nothing else is coming.
615- self.seek_since = None;
616- if was != Transport::Ended {
617- // Ended is a *stopped* transport, so the clock stops with it,
618- // on the out point the timecode and the playhead have been
619- // showing all along. Nothing else ever stopped it: past the
620- // last frame wall time takes over and `now()` walks off the end
621- // of the timeline for as long as the window is left open -- and
622- // the playhead is what a cut, a paste, an insert and the
623- // analyser all act at, so every one of them was aiming into
624- // empty space (measured: a 5 s timeline recognised its end at
625- // clock 17.5 s under a slow renderer). End of stream is left
626- // set, so this is still `Ended` and the next press restarts.
627- if let Some(session) = &mut self.session {
628- session.halt_at_end();
629- }
630- let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64());
631- eprintln!(
632- "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s",
633- self.displayed,
634- self.dropped,
635- self.session.as_ref().map_or(0., PlaybackSession::now)
636- );
637- }
638- }
639- }
640-
641- /// Where the transport is, asked of the session rather than remembered:
642- /// end of stream is the engine's own flag (any seek clears it, which is why
643- /// an edit past the end revives the picture) and so is the clock. A held
644- /// frame is one still owed to the screen, so the end is not the end yet.
645- fn transport(&self) -> Transport {
646- let Some(session) = &self.session else {
647- return Transport::Stopped;
648- };
649- transport(
650- session.is_playing(),
651- session.is_eos() && self.held.is_none(),
652- )
653- }
654-
655- /// A frame owed to the screen after a reseek, and the buffered one dropped:
656- /// what stops the picture from staying frozen on the old last frame. The
657- /// end-of-stream flag itself is the engine's and its own seek clears it --
658- /// edits reseek inside the engine and still owe this.
659- fn reset_after_reseek(&mut self) {
660- self.held = None;
661- // Restarted on every reseek, not only on the first: what it measures is
662- // the open now standing, which is what a person is waiting on.
663- self.seek_since = Some(Instant::now());
664- // A seek is a person saying where to look, so it takes the view back
665- // from an earlier scroll: the frame asked for is the one to be shown.
666- self.panned = false;
667- // An edit moves the indices a drag in flight is holding -- a stroke
668- // during one is exactly that -- and an edge committed against a moved
669- // index would trim a clip nobody grabbed. Dropping it is the whole fix:
670- // nothing has been written yet.
671- self.trim = None;
672- // ...and the shadow a drag is drawn under promises a landing on a lane
673- // this edit has just reshaped. The next move of the drag draws it
674- // again; until then it says nothing.
675- self.ghost = None;
676- }
677-
678- /// What an action does, wherever it was asked for -- a stroke, or the clip
679- /// menu item that names the same action. One table, so the two can never
680- /// come to mean different things.
681- fn act(&mut self, action: ActionId, cx: &mut Context<Self>) {
682- // Two doors, one oracle. This used to be the asymmetry the whole
683- // toolbar was built on: the buttons dimmed themselves off
684- // [`enable`] while the keyboard walked straight past it, so with no
685- // file open `s` toggled the snap and `v` added a track while the very
686- // same controls sat dim and *dead* to the pointer. Whatever refuses the
687- // button refuses the key, in the oracle's own words -- and a refusal
688- // that is silent from the keyboard is a bug the same size.
689- match self.enable(action, None) {
690- Enable::Yes => {}
691- // A state refusal is spoken: the thing exists and cannot happen
692- // *now*, which is exactly what a silent key press fails to say.
693- Enable::No(why) => {
694- self.notify_user(format!("{} — {why}", action.label()).into());
695- cx.notify();
696- return;
697- }
698- // A class refusal is not: the action does not exist for what is in
699- // front of the user, and `esc` with nothing exporting must not
700- // answer with a line about exports.
701- Enable::Hidden(_) => return,
702- }
703- match action {
704- ActionId::Play => self.toggle_or_restart(cx),
705- ActionId::StepBack => self.step(-1, cx),
706- ActionId::StepForward => self.step(1, cx),
707- // A second is however many frames this timeline runs at.
708- ActionId::JumpBack => self.step(-(self.fps.round() as i64), cx),
709- ActionId::JumpForward => self.step(self.fps.round() as i64, cx),
710- // The ends, as a step nothing can be far enough from.
711- ActionId::GoStart => self.step(i64::MIN, cx),
712- ActionId::GoEnd => self.step(i64::MAX, cx),
713- // Not a step at all: the grid these land on is the *source's*, and
714- // where the next one is depends on the file rather than on the rate.
715- ActionId::PrevSyncPoint => self.jump_sync(false, cx),
716- ActionId::NextSyncPoint => self.jump_sync(true, cx),
717- ActionId::Export => self.open_export(cx),
718- ActionId::Save => self.save_project(cx),
719- ActionId::Copy => self.copy_selected(),
720- ActionId::Paste => self.paste(cx),
721- ActionId::Cut => self.cut(cx),
722- ActionId::Regroup => self.regroup(cx),
723- ActionId::Detach => self.detach(cx),
724- ActionId::Group => self.group(cx),
725- ActionId::Select => self.select_under_playhead(cx),
726- ActionId::SelectNext => self.select_step(true, cx),
727- ActionId::SelectPrev => self.select_step(false, cx),
728- ActionId::Delete => self.delete_selected(cx),
729- ActionId::Lift => self.lift_selected(cx),
730- ActionId::Color => self.open_color(cx),
731- ActionId::Fit => self.cycle_fit(cx),
732- ActionId::Resolution => self.cycle_resolution(cx),
733- // The playhead is what a key zoom is aimed at: it is the one place
734- // on the timeline the user is certainly looking at, and keeping it
735- // still is what every editor does.
736- ActionId::ZoomIn => self.zoom(ZOOM_STEP, None, cx),
737- ActionId::ZoomOut => self.zoom(1. / ZOOM_STEP, None, cx),
738- ActionId::ZoomFit => self.zoom_fit(cx),
739- ActionId::Undo => self.undo(cx),
740- ActionId::AddVideoLane => self.add_lane(LaneKind::Video, cx),
741- ActionId::AddAudioLane => self.add_lane(LaneKind::Audio, cx),
742- // The last track of that kind: the one the add key put there, so the
743- // two strokes undo each other press for press. Any other track goes
744- // through the × in its own header.
745- ActionId::RemoveVideoLane => self.remove_last_lane(LaneKind::Video, cx),
746- ActionId::RemoveAudioLane => self.remove_last_lane(LaneKind::Audio, cx),
747- // The same chooser the + S button opens, and the picked row -- the
748- // one the panel draws highlighted -- for the removal: the × on any
749- // other row is that row's own door, and both doors are one call.
750- ActionId::AddSubtitleTrack => self.pick_and_add_subtitles(cx),
751- ActionId::RemoveSubtitleTrack => self.remove_subtitle_track(self.sub_track, cx),
752- ActionId::ToggleMute => self.set_volume(|volume| volume.muted = !volume.muted, cx),
753- ActionId::VolumeUp => self.set_volume(|volume| volume.step(true), cx),
754- ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx),
755- ActionId::Equalizer => self.open_eq(cx),
756- ActionId::Speed => self.open_speed(cx),
757- ActionId::Silence => self.open_silence(cx),
758- ActionId::Mix => self.open_mix(None, cx),
759- ActionId::ToggleSnap => self.toggle_snap(cx),
760- ActionId::ToggleSubtitles => self.toggle_subtitles(cx),
761- // The keyboard's door to the same list the toolbar button opens.
762- // At the window's corner, since a stroke names no place -- and
763- // [`menu_at`] keeps it on screen from there.
764- ActionId::Theme => self.open_picker(Pick::Theme, Point::default(), cx),
765- // Nothing to cancel while nothing is exporting; the export guard in
766- // the key handler is what answers this one while there is.
767- ActionId::CancelExport => {}
768- ActionId::ShowActions => self.show_actions(cx),
769- }
770- }
771-
772- /// Says something to the user. The one door: every message in this editor
773- /// comes through here, so "queued rather than overwritten" is a property of
774- /// the field and not of seventy call sites remembering to be polite.
775- ///
776- /// A repeat of what is already at the back is dropped -- holding a key that
777- /// refuses would otherwise fill the queue with one sentence, and the count
778- /// on the bar would be a count of how long the key was held.
779- fn notify_user(&mut self, message: SharedString) {
780- push_notice(&mut self.notices, message);
781- }
782-
783- /// Answers the message on the bar and brings up the next one. Whether there
784- /// was one to answer, because a key that dismissed a notice owes a repaint
785- /// and a key that dismissed nothing does not.
786- fn dismiss_notice(&mut self) -> bool {
787- self.notices.pop_front().is_some()
788- }
789-
790- /// The magnet off and on again, in words: a snap that stops working
791- /// silently reads as a bug, and one that starts working silently reads as
792- /// one too. The line goes with it -- nothing is being promised any more.
793- fn toggle_snap(&mut self, cx: &mut Context<Self>) {
794- self.snap = !self.snap;
795- self.snap_cue = None;
796- self.ghost = None;
797- self.notify_user(match self.snap {
798- true => "SNAP ON — drags land on clip edges, the playhead and the start".into(),
799- false => "SNAP OFF — drags land exactly where the hand leaves them".into(),
800- });
801- cx.notify();
802- }
803-
804- /// The actions card, from its key, from the panel button, or from its own
805- /// row: open, with an empty search box -- a card that opens showing the
806- /// last search would hide most of the list for a reason nobody remembers.
807- fn show_actions(&mut self, cx: &mut Context<Self>) {
808- self.keys_open = true;
809- self.keys_search.clear();
810- self.scroll_keys(None);
811- self.rebinding = None;
812- // One card at a time, the rule the other cards follow.
813- self.export_open = false;
814- cx.notify();
815- }
816-
817- /// Moves the actions card's row list by `by` pixels, or puts it back at the
818- /// top (`None`). Back to the top after every keystroke that changes the
819- /// search: a filtered list is shorter than the offset a scrolled one left
820- /// behind, and a card showing the empty space past its last row reads as a
821- /// search that found nothing.
822- ///
823- /// Clamped to what there is to scroll, so the list cannot be pushed off
824- /// either end -- `max_offset` is what the last paint measured, which is the
825- /// only place that number exists.
826- fn scroll_keys(&self, by: Option<f32>) {
827- let at = match by {
828- Some(by) => (f32::from(self.keys_scroll.offset().y) + by)
829- .clamp(-f32::from(self.keys_scroll.max_offset().height), 0.),
830- None => 0.,
831- };
832- self.keys_scroll.set_offset(point(px(0.), px(at)));
833- }
834-
835- /// The cues over the picture, off and on. Says which it is now *and* what is
836- /// on screen while they are on: a toggle whose answer is invisible when the
837- /// playhead happens to sit between two cues would read as broken.
838- fn toggle_subtitles(&mut self, cx: &mut Context<Self>) {
839- self.subs_on = !self.subs_on;
840- // Named with its film here too: a notice saying "SUBTITLES ON — eng"
841- // over a timeline holding two films' eng tracks names neither.
842- let label = self
843- .session
844- .as_ref()
845- .and_then(|session| sub_pick_name(session.subtitles(), self.sub_track))
846- .unwrap_or_else(|| "nothing imported".to_string());
847- self.notify_user(
848- match self.subs_on {
849- true => format!("SUBTITLES ON — {label}"),
850- false => format!("SUBTITLES OFF — {label} is still on the timeline"),
851- }
852- .into(),
853- );
854- cx.notify();
855- }
856-
857- /// The subtitle track the overlay and the strip are showing: the one a
858- /// library row picked, or the first there is. `None` with no timeline and
859- /// for an index left over from one that is gone.
860- fn subtitle_track(&self) -> Option<&engine::subtitle::SubtitleTrack> {
861- self.session.as_ref()?.subtitles().get(self.sub_track)
862- }
863-
864- /// Whether the editor can be asked for `action` right now, and why not when
865- /// it cannot. `on` is the clip the question is about -- the one a clip menu
866- /// was opened on -- and `None` asks about the marked clip instead, which is
867- /// what a menu that hangs over no clip in particular means by "this one".
868- ///
869- /// The player's half of [`enable`]: it reads the state, the table decides.
870- fn enable(&self, action: ActionId, on: Option<(Lane, usize)>) -> Enable {
871- enable(action, self.ctx(on))
872- }
873-
874- /// The state every one of those questions is asked against, read off the
875- /// player once: [`menu_items`] filters a whole menu with it, so the rows a
876- /// menu draws and the answers it dims them by come from the same reading.
877- fn ctx(&self, on: Option<(Lane, usize)>) -> Ctx {
878- let Some(session) = &self.session else {
879- return Ctx::default();
880- };
881- let clip = on
882- .or(self.selected)
883- .and_then(|(lane, idx)| session.lane_clips(lane).get(idx).map(|clip| (*clip, lane)));
884- Ctx {
885- clip,
886- image: clip.is_some_and(|(clip, _)| {
887- session
888- .sources()
889- .get(clip.source)
890- .is_some_and(|s| engine::is_image(&s.path))
891- }),
892- playhead: frame_at(session.now(), self.fps),
893- timeline: true,
894- clipboard: self.clipboard.is_some(),
895- subtitles: !session.subtitles().is_empty(),
896- playable: !nothing_to_play(Some(session)),
897- exporting: self.exporting().is_some(),
898- }
899- }
900-
901- /// The same reading for a library row: whether this file can join this
902- /// timeline -- the very answer the list greys the row by, so the menu over a
903- /// row and the row under it cannot disagree -- and how many clips play it.
904- /// [`Player::ctx`] for the other panel.
905- fn row_ctx(&self, path: &Path, stream: usize) -> RowCtx {
906- let placed = self.session.as_ref().map_or(0, |session| {
907- let of_row = session
908- .sources()
909- .iter()
910- .position(|s| s.path == path && s.audio_stream == stream);
911- of_row.map_or(0, |idx| {
912- session
913- .lanes()
914- .into_iter()
915- .flat_map(|lane| session.lane_clips(lane))
916- .filter(|c| c.source == idx)
917- .count()
918- })
919- });
920- let sources = self
921- .session
922- .as_ref()
923- .map_or(&[][..], PlaybackSession::sources);
924- RowCtx {
925- timeline: self.session.is_some(),
926- exporting: self.exporting().is_some(),
927- usable: library_rows(
928- sources,
929- &self.streams,
930- &self.decoders,
931- self.timeline_audio(),
932- |path| {
933- self.session
934- .as_ref()
935- .map_or(0, |session| session.file_frames(path))
936- },
937- )
938- .iter()
939- .any(|row| row.path == path && row.stream == stream && row.unusable.is_none()),
940- placed,
941- }
942- }
943-
944- /// The one place a clip becomes *the* selected one: a click, a right-click
945- /// that opens the menu, and every selection key go through here, so what a
946- /// keyboard marks and what a pointer marks are the same state marked the
947- /// same way (group and all -- see [`marked`]).
948- fn select(&mut self, target: (Lane, usize), cx: &mut Context<Self>) {
949- self.selected = Some(target);
950- cx.notify();
951- }
952-
953- /// Every clip the playhead is over, one per lane, in the order the lanes are
954- /// drawn -- video first, which is the order [`PlaybackSession::lanes`] comes
955- /// in. What the select key walks.
956- fn under_playhead(&self) -> Vec<(Lane, usize)> {
957- let Some(session) = &self.session else {
958- return Vec::new();
959- };
960- let now = session.now();
961- session
962- .lanes()
963- .into_iter()
964- .filter_map(|lane| Some((lane, session.lane_clip_at(lane, now)?)))
965- .collect()
966- }
967-
968- /// Selects the clip under the playhead, and on a repeat press the next
969- /// lane's -- so one key reaches every clip the playhead is over, which is
970- /// what makes selection (and everything that acts on a selection: delete,
971- /// lift, the equalizer, the grade) reachable with no pointer at all.
972- fn select_under_playhead(&mut self, cx: &mut Context<Self>) {
973- let under = self.under_playhead();
974- let Some(&first) = under.first() else {
975- self.notify_user("NOTHING UNDER THE PLAYHEAD — move it onto a clip first".into());
976- cx.notify();
977- return;
978- };
979- // Where the current selection sits in that walk decides what "again"
980- // means; a selection off the playhead starts the walk over.
981- let next = self
982- .selected
983- .and_then(|sel| under.iter().position(|&clip| clip == sel))
984- .map_or(first, |at| under[(at + 1) % under.len()]);
985- self.select(next, cx);
986- }
987-
988- /// Walks the selection along its own lane, wrapping at either end. Nothing
989- /// selected means nothing to walk from, so it selects under the playhead
990- /// exactly as the select key does: either key can start as well as continue.
991- fn select_step(&mut self, forward: bool, cx: &mut Context<Self>) {
992- let clips = self
993- .selected
994- .zip(self.session.as_ref())
995- .map_or(0, |((lane, _), session)| session.lane_clips(lane).len());
996- match (self.selected, clips) {
997- // An empty lane is a selection nothing can be stepped from -- as is
998- // no selection at all, and the playhead answers both.
999- (Some((lane, idx)), len) if len > 0 => {
1000- let next = if forward {
1001- (idx + 1) % len
1002- } else {
1003- (idx + len - 1) % len
1004- };
1005- self.select((lane, next), cx);
1006- }
1007- _ => self.select_under_playhead(cx),
1008- }
1009- }
1010-
1011- /// Cycles the fit policy of the clip the picture is coming from -- the
1012- /// clicked one when it is a video clip, else the composite's own, exactly as
1013- /// the colour card picks its target. A whole card for one four-valued
1014- /// setting would be a card to close; a stroke that cycles it and says what
1015- /// it landed on is the same setting with nothing to dismiss.
1016- ///
1017- /// Only means anything when the clip is not the project's size -- a clip
1018- /// that already fills the canvas looks the same under all four -- so the
1019- /// notice says the size it is placing, not just the word.
1020- fn cycle_fit(&mut self, cx: &mut Context<Self>) {
1021- if self.exporting().is_some() {
1022- return;
1023- }
1024- let Some(session) = &mut self.session else {
1025- self.notify_user("no timeline to fit — open a file first".into());
1026- cx.notify();
1027- return;
1028- };
1029- let target = self
1030- .selected
1031- .filter(|(lane, _)| lane.kind == LaneKind::Video)
1032- .or_else(|| session.video_clip_at(session.now()));
1033- let Some((lane, idx)) = target else {
1034- self.notify_user("no clip under the playhead to fit".into());
1035- cx.notify();
1036- return;
1037- };
1038- let next = next_fit(session.fit_of(lane, idx));
1039- self.apply_fit(lane, idx, next, cx);
1040- }
1041-
1042- /// One clip's fit policy set, whichever asked: the stroke that steps to the
1043- /// next one and the list that names one outright come through here, so they
1044- /// cannot differ in what they do or in what they say they did.
1045- fn apply_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy, cx: &mut Context<Self>) {
1046- if let Some(session) = &mut self.session
1047- && session.set_fit(lane, idx, fit)
1048- {
1049- let (w, h) = session.resolution();
1050- self.notify_user(format!("FIT POLICY: {} on {w}x{h}", fit_label(fit)).into());
1051- self.reset_after_reseek();
1052- }
1053- cx.notify();
1054- }
1055-
1056- /// The scale against the bed it is drawn on and the timeline it is drawn
1057- /// from: every clamp, zoom and scroll is worked out through this, and the
1058- /// bed is measured off the ruler's probe rather than remembered, so a
1059- /// resized window is a resized view on the very next answer.
1060- fn view(&self) -> View {
1061- View {
1062- scale: self.scale,
1063- bed: f32::from(self.ruler.get().size.width),
1064- duration: self.drawn_duration(),
1065- fps: self.fps,
1066- }
1067- }
1068-
1069- /// Magnifies the timeline about a point that stays put: `anchor` is how many
1070- /// pixels along the bed to hold still (a ctrl+wheel holds the pointer), and
1071- /// with none it is the playhead -- so the frame being worked on is still the
1072- /// frame on screen after the zoom. Clamped at both ends by [`View`]: out
1073- /// stops at the whole timeline on the bed, in at a handful of frames.
1074- fn zoom(&mut self, factor: f32, anchor: Option<f32>, cx: &mut Context<Self>) {
1075- let view = self.view();
1076- let at = self.playhead(view.duration);
1077- let anchor = anchor.unwrap_or_else(|| self.scale.px_at(at).clamp(0., view.bed));
1078- self.scale = view.zoomed(factor, anchor);
1079- // The view a hand chose. A zoom about the playhead leaves it on the
1080- // bed, so this is given back on the very next frame and only a zoom
1081- // that took the head off screen -- ctrl+wheel away from it -- holds.
1082- self.panned = true;
1083- cx.notify();
1084- }
1085-
1086- /// All the way back out: the whole timeline across the bed, and the one
1087- /// thing that reads the timeline's own length to decide how wide a second
1088- /// is drawn.
1089- fn zoom_fit(&mut self, cx: &mut Context<Self>) {
1090- self.scale = self.view().fit();
1091- cx.notify();
1092- }
1093-
1094- /// Slides the view along the timeline by `notches` of the wheel, later in
1095- /// time for a positive one and [`SCROLL_NOTCH_SHARE`] of the bed each. The
1096- /// scale is untouched: this is the timeline's scrollbar, and the only thing
1097- /// on the panel that moves what is on screen without magnifying it.
1098- fn scroll_view(&mut self, notches: f32, cx: &mut Context<Self>) {
1099- let view = self.view();
1100- // Nothing painted yet: there is no bed to measure a notch against, and
1101- // a start moved against a zero width would be a jump to the head.
1102- if view.bed <= 0. {
1103- return;
1104- }
1105- self.scale = view.scrolled(notches * view.bed * SCROLL_NOTCH_SHARE);
1106- // The one gesture whose whole purpose is to look away from the
1107- // playhead: while playing it wins over the follow, which is what every
1108- // editor does with a scroll during playback.
1109- self.panned = true;
1110- cx.notify();
1111- }
1112-
1113- /// One notch of the wheel anywhere over the timeline -- the ruler or a
1114- /// lane's bed alike, since a hand aims at the clip it is working on and not
1115- /// at the strip above it. Ctrl zooms about the pointer, bare scrolls the
1116- /// view along: the mapping Premiere, Movavi and CapCut share, and the one
1117- /// the user named.
1118- ///
1119- /// The anchor is measured off the ruler's probe wherever the pointer is,
1120- /// because that probe *is* the bed's x-to-time mapping ([`HEADER_W`]) and
1121- /// every lane is drawn through the same one.
1122- fn timeline_wheel(&mut self, event: &ScrollWheelEvent, cx: &mut Context<Self>) {
1123- let d = wheel_delta(event);
1124- if d == 0. {
1125- return;
1126- }
1127- let factor = match d > 0. {
1128- true => ZOOM_STEP,
1129- false => 1. / ZOOM_STEP,
1130- };
1131- match event.modifiers.control {
1132- true => {
1133- let anchor = px_along(event.position.x, self.ruler.get());
1134- self.zoom(factor, Some(anchor), cx);
1135- }
1136- // Up is back towards the head of the timeline, the way a wheel up
1137- // is back towards the top of a page.
1138- false => self.scroll_view(-d.signum(), cx),
1139- }
1140- }
1141-
1142- /// Cycles the *project's* resolution through [`RESOLUTIONS`], starting from
1143- /// the media's own -- the one size that must stay reachable, since a project
1144- /// moved off it has no other way back (the resolution is not an undo step).
1145- /// Every clip is recomposed onto it, so this is what makes "the project
1146- /// resolution and the media's are different things" a thing a user can see.
1147- fn cycle_resolution(&mut self, cx: &mut Context<Self>) {
1148- if self.exporting().is_some() {
1149- return;
1150- }
1151- let Some(session) = &mut self.session else {
1152- self.notify_user("no timeline to resize — open a file first".into());
1153- cx.notify();
1154- return;
1155- };
1156- let (width, height) = next_resolution(session.resolution(), session.native_resolution());
1157- self.apply_resolution(width, height, cx);
1158- }
1159-
1160- /// The project resized, whichever asked: the stroke that steps to the next
1161- /// size and the list that names one outright come through here.
1162- fn apply_resolution(&mut self, width: u32, height: u32, cx: &mut Context<Self>) {
1163- if let Some(session) = &mut self.session
1164- && session.set_resolution(width, height)
1165- {
1166- self.notify_user(format!("PROJECT: {width}x{height}").into());
1167- self.reset_after_reseek();
1168- }
1169- cx.notify();
1170- }
1171-
1172- /// The project cut at another rate: the list names one and this is where it
1173- /// happens, the way [`apply_resolution`](Self::apply_resolution) is for a
1174- /// size. The whole timeline is conformed to it by the engine
1175- /// ([`PlaybackSession::set_frame_rate`]) -- same seconds, same footage --
1176- /// and the rate the app itself counts frames in follows, since every
1177- /// timecode, ruler mark and step key here is measured in it.
1178- fn apply_frame_rate(&mut self, fps: f64, cx: &mut Context<Self>) {
1179- if let Some(session) = &mut self.session
1180- && session.set_frame_rate(fps)
1181- {
1182- self.fps = session.meta().frame_rate;
1183- self.notify_user(format!("PROJECT: {} fps", fps_label(fps)).into());
1184- self.reset_after_reseek();
1185- }
1186- cx.notify();
1187- }
1188-
1189- /// The project's HDR media shown another way: the list names a rendition and
1190- /// this is where it happens, the way [`apply_resolution`](Self::apply_resolution)
1191- /// is for a size. The engine remaps the frame under the playhead at once
1192- /// ([`PlaybackSession::set_tone`]), so the picture on screen is the picked
1193- /// one before the notice has faded -- and an SDR project is unmoved, which
1194- /// is what the notice says rather than pretending something happened.
1195- fn apply_tone(&mut self, preset: Preset, cx: &mut Context<Self>) {
1196- if let Some(session) = &mut self.session
1197- && session.set_tone(preset)
1198- {
1199- self.notify_user(format!("HDR: {} — affects HDR media", tone_label(preset)).into());
1200- self.reset_after_reseek();
1201- }
1202- cx.notify();
1203- }
1204-
1205- /// Opens a choice list on a setting, where it was asked for. One floating
1206- /// thing at a time: the click that opens it is the click that closes
1207- /// whatever menu it was opened from.
1208- fn open_picker(&mut self, of: Pick, at: Point<Pixels>, cx: &mut Context<Self>) {
1209- // On the row that is in force, so the first ↑ or ↓ steps off the
1210- // current value rather than off the top of the list.
1211- let sel = self
1212- .choices(of)
1213- .iter()
1214- .position(|(.., picked)| *picked)
1215- .unwrap_or(0);
1216- self.context_menu = None;
1217- self.library_menu = None;
1218- self.picker = Some(Picker { of, at, sel });
1219- cx.notify();
1220- }
1221-
1222- /// A row of the open list was picked. Closes the list first -- the rule
1223- /// every menu item here follows -- then does exactly what the stroke for
1224- /// that setting does, through the same door.
1225- fn choose(&mut self, choice: Choice, cx: &mut Context<Self>) {
1226- self.picker = None;
1227- match choice {
1228- Choice::Size(w, h) => self.apply_resolution(w, h, cx),
1229- Choice::Fps(fps) => self.apply_frame_rate(fps, cx),
1230- Choice::Fit(lane, idx, fit) => self.apply_fit(lane, idx, fit, cx),
1231- Choice::Tone(preset) => self.apply_tone(preset, cx),
1232- // In force for the next paint -- every token is read through
1233- // [`ui::theme::palette`], so one store repaints the whole window --
1234- // and kept for the next launch. A file that could not be written is
1235- // said out loud: the difference between "picked" and "picked for
1236- // good" is the user's to know.
1237- Choice::Theme(id) => {
1238- ui::theme::set(id);
1239- if let Err(e) = ui::theme::save(id) {
1240- let path = ui::theme::config_path();
1241- self.notify_user(
1242- format!("THEME COULD NOT BE KEPT — {} — {e}", path.display()).into(),
1243- );
1244- }
1245- cx.notify();
1246- }
1247- // The same field the row's key steps, set outright: a list picks a
1248- // value, it does not step to one.
1249- Choice::AudioRate(kbps) => {
1250- self.audio_kbps = kbps;
1251- cx.notify();
1252- }
1253- }
1254- }
1255-
1256- /// Every value the open list offers, in the order it lists them. Empty
1257- /// without a timeline, which is the state where nothing here has a value to
1258- /// offer -- and where the surfaces that open the list are dimmed anyway.
1259- fn choices(&self, of: Pick) -> Vec<ChoiceRow> {
1260- // The palette is not the project's, so it is offered before the
1261- // timeline is asked about: an empty window is painted too, and its
1262- // Theme button is live there like the snap beside it.
1263- if of == Pick::Theme {
1264- return ui::theme::PaletteId::ALL
1265- .into_iter()
1266- .map(|id| {
1267- (
1268- Choice::Theme(id),
1269- id.label().into(),
1270- id.detail().into(),
1271- id == ui::theme::active(),
1272- )
1273- })
1274- .collect();
1275- }
1276- let Some(session) = &self.session else {
1277- return Vec::new();
1278- };
1279- match of {
1280- Pick::Resolution => {
1281- resolution_choices(session.resolution(), session.native_resolution())
1282- }
1283- Pick::Fps => fps_choices(session.meta().frame_rate, session.native_frame_rate()),
1284- Pick::Fit(lane, idx) => {
1285- fit_choices(lane, idx, session.fit_of(lane, idx), session.resolution())
1286- }
1287- Pick::AudioRate => audio_rate_choices(self.audio_kbps),
1288- Pick::Tone => tone_choices(session.tone()),
1289- // Answered above, with or without a timeline.
1290- Pick::Theme => Vec::new(),
1291- }
1292- }
1293-
1294- /// Opens the colour card on the clip a grade would go on: the clip that was
1295- /// clicked when it is a video one, and otherwise the clip the picture is
1296- /// coming from -- the one the engine's own compositing rule picks, which is
1297- /// what a person means by "this shot". The fallback stands even now that a
1298- /// selection key exists: a grade asked for with nothing selected still means
1299- /// the shot on screen.
1300- fn open_color(&mut self, cx: &mut Context<Self>) {
1301- if self.exporting().is_some() {
1302- return;
1303- }
1304- let Some(session) = &self.session else {
1305- self.notify_user("no timeline to grade — open a file first".into());
1306- cx.notify();
1307- return;
1308- };
1309- let target = self
1310- .selected
1311- .filter(|(lane, _)| lane.kind == LaneKind::Video)
1312- .or_else(|| session.video_clip_at(session.now()));
1313- match target {
1314- Some(clip) => {
1315- self.color_open = Some(clip);
1316- self.color_band = 0;
1317- self.color_dragging = false;
1318- // A sample the last card held back belongs to the clip it was
1319- // dragged on, and this may be another one.
1320- self.pending_color = None;
1321- // One card at a time, the rule both the others already follow.
1322- self.keys_open = false;
1323- self.export_open = false;
1324- self.context_menu = None;
1325- }
1326- None => self.notify_user("no clip under the playhead to grade".into()),
1327- }
1328- cx.notify();
1329- }
1330-
1331- /// What the card's clip is graded by right now -- the identity for one
1332- /// nobody has graded, which is what the sliders start at. A sample a drag is
1333- /// still holding wins over the clip's own: it is what the hand has asked
1334- /// for, so it is what the sliders show and what the next sample builds on.
1335- fn color_params(&self) -> ColorParams {
1336- if let Some(params) = self.pending_color {
1337- return params;
1338- }
1339- self.color_open
1340- .zip(self.session.as_ref())
1341- .and_then(|((lane, idx), session)| session.color_of(lane, idx).copied())
1342- .unwrap_or_default()
1343- }
1344-
1345- /// Puts `params` on the card's clip, or takes the grade off when they are
1346- /// the identity -- a slider walked back to the middle leaves the clip
1347- /// ungraded rather than carrying a do-nothing entry, which is what keeps an
1348- /// untouched project byte-identical. The engine reseeks on the edit, so the
1349- /// frame on screen repaints through the new grade; this only owes the flags
1350- /// that reseek clears.
1351- fn set_color(&mut self, params: ColorParams, cx: &mut Context<Self>) {
1352- self.write_color(params, false, cx);
1353- }
1354-
1355- /// Both writes: `live` is the one that takes no undo step, which is what
1356- /// every sample *inside* a drag goes through
1357- /// (`PlaybackSession::set_color_live`). Either way the engine reseeks, so
1358- /// the picture -- and the histogram counted off it -- is regraded at once.
1359- fn write_color(&mut self, params: ColorParams, live: bool, cx: &mut Context<Self>) {
1360- // Any write supersedes a held sample, whichever way it arrived -- a key,
1361- // a reset, or the flush that took this one out of the stash.
1362- self.pending_color = None;
1363- let Some((lane, idx)) = self.color_open else {
1364- return;
1365- };
1366- let Some(session) = &mut self.session else {
1367- return;
1368- };
1369- let grade = Some(params).filter(|p| !p.is_identity());
1370- let took = match live {
1371- true => session.set_color_live(lane, idx, grade),
1372- false => session.set_color(lane, idx, grade),
1373- };
1374- if took {
1375- self.reset_after_reseek();
1376- }
1377- cx.notify();
1378- }
1379-
1380- /// Moves the picked slider by `steps` of [`COLOR_STEP`], clamped to that
1381- /// band's range. One edit, so one undo step per press.
1382- fn nudge_color(&mut self, steps: f32, cx: &mut Context<Self>) {
1383- let mut params = self.color_params();
1384- let (_, low, high) = COLOR_BANDS[self.color_band];
1385- let value = band_mut(&mut params, self.color_band);
1386- *value = (*value + steps * COLOR_STEP).clamp(low, high);
1387- self.set_color(params, cx);
1388- }
1389-
1390- /// Where the pointer sits along a slider, as that band's value: the left end
1391- /// of the bar is the bottom of its range and the right end the top. Called
1392- /// on every pointer sample, so the grade -- and the picture, and the
1393- /// histogram over it -- moves under the hand.
1394- ///
1395- /// `first` is the press: it takes the undo step the whole gesture rolls back
1396- /// to, and every sample after it is live. That is why it writes even when
1397- /// the value did not change -- without that snapshot the rest of the drag
1398- /// would be unundoable.
1399- ///
1400- /// Values land on the [`COLOR_STEP`] grid the keys use, which also bounds
1401- /// one drag to forty-odd entries in the project's colour table.
1402- ///
1403- /// Samples crossed while the worker still owes a frame are held rather than
1404- /// written ([`stash_or_write`]): a reopen costs half a second on a big film,
1405- /// so a bar-wide sweep that wrote every step would queue forty opens, cancel
1406- /// thirty-nine of them and freeze the window for the sum. What is written is
1407- /// one grade per frame the worker actually delivers.
1408- fn drag_color(&mut self, x: Pixels, first: bool, cx: &mut Context<Self>) {
1409- let (_, low, high) = COLOR_BANDS[self.color_band];
1410- let along = frac_along(x, self.color_bars[self.color_band].get());
1411- let value = color_snap(low + along * (high - low)).clamp(low, high);
1412- let mut params = self.color_params();
1413- let at = band_mut(&mut params, self.color_band);
1414- if *at == value && !first {
1415- return;
1416- }
1417- *at = value;
1418- let busy = self.seek_since.is_some();
1419- match stash_or_write(&mut self.pending_color, params, first, busy) {
1420- Some(params) => self.write_color(params, !first, cx),
1421- // The sliders draw off the held sample, so the handle goes on
1422- // following the hand while the picture catches up.
1423- None => cx.notify(),
1424- }
1425- }
1426-
1427- /// Opens the speed card on the clip whose rate is to change: the selected
1428- /// one, or -- with nothing selected -- the clip the picture is coming from,
1429- /// which is what a person means by "this shot". Either half of a take will
1430- /// do: a rate applies to the whole group, so opening it on the sound and
1431- /// opening it on the picture are the same card.
1432- fn open_speed(&mut self, cx: &mut Context<Self>) {
1433- if self.exporting().is_some() {
1434- return;
1435- }
1436- let Some(session) = &self.session else {
1437- self.notify_user("no timeline to re-time — open a file first".into());
1438- cx.notify();
1439- return;
1440- };
1441- match self
1442- .selected
1443- .or_else(|| session.video_clip_at(session.now()))
1444- {
1445- Some(clip) => {
1446- self.speed_open = Some(clip);
1447- self.speed_dragging = false;
1448- // The colour card's rule: a held sample is the last clip's.
1449- self.pending_speed = None;
1450- // One card at a time, the rule the other four follow.
1451- self.keys_open = false;
1452- self.export_open = false;
1453- self.eq_open = None;
1454- self.color_open = None;
1455- self.close_silence();
1456- self.context_menu = None;
1457- }
1458- None => self.notify_user("no clip under the playhead to re-time".into()),
1459- }
1460- cx.notify();
1461- }
1462-
1463- /// What the card's clip plays at right now -- real time for one nobody has
1464- /// touched, which is where the bar starts.
1465- fn card_speed(&self) -> Speed {
1466- if let Some(speed) = self.pending_speed {
1467- return speed;
1468- }
1469- self.speed_open
1470- .zip(self.session.as_ref())
1471- .map_or(Speed::NORMAL, |((lane, idx), session)| {
1472- session.speed_of(lane, idx)
1473- })
1474- }
1475-
1476- /// Writes a rate at the card's clip and its whole group -- one undo step for
1477- /// the lot ([`engine::PlaybackSession::set_speed`]). The engine reseeks, so
1478- /// the picture runs at the new rate and the sound is resampled from the next
1479- /// chunk on; a refusal (a slower clip would run into its neighbour) comes
1480- /// back in the engine's own words and *names* the clip in the way, because
1481- /// "it did not fit" is not something a person can go and fix.
1482- fn set_speed(&mut self, speed: Speed, cx: &mut Context<Self>) {
1483- self.write_speed(speed, false, cx);
1484- }
1485-
1486- /// Both writes: `live` is the one that takes no undo step, which is what
1487- /// every sample *inside* a drag goes through -- so a drag from 1.00x to
1488- /// 2.00x is one undo press and lands back where the hand picked it up, and
1489- /// the whole linked group comes back with it.
1490- fn write_speed(&mut self, speed: Speed, live: bool, cx: &mut Context<Self>) {
1491- // The colour card's rule: a write supersedes whatever a drag was holding.
1492- self.pending_speed = None;
1493- let Some((lane, idx)) = self.speed_open else {
1494- return;
1495- };
1496- let Some(session) = &mut self.session else {
1497- return;
1498- };
1499- if speed != session.speed_of(lane, idx) {
1500- let wrote = match live {
1501- true => session.set_speed_live(lane, idx, speed),
1502- false => session.set_speed(lane, idx, speed),
1503- };
1504- match wrote {
1505- Ok(()) => self.reset_after_reseek(),
1506- Err(e) => self.notify_user(e.to_string().into()),
1507- }
1508- }
1509- cx.notify();
1510- }
1511-
1512- /// One [`SPEED_STEP`] per keystroke, clamped to what a [`Speed`] can hold.
1513- fn nudge_speed(&mut self, steps: i32, cx: &mut Context<Self>) {
1514- let at = i32::from(self.card_speed().permille()) + steps * SPEED_STEP;
1515- self.set_speed(speed_at(at), cx);
1516- }
1517-
1518- /// Where the pointer sits along the bar, as a rate: the left end is
1519- /// [`Speed::MIN`] and the right end [`Speed::MAX`], on the same
1520- /// [`SPEED_STEP`] grid the keys move on -- so a drag can land on exactly
1521- /// 1.00x and the same drag twice is one entry, not forty.
1522- /// `first` is the press: it takes the undo step the whole gesture rolls back
1523- /// to, and every sample after it is live -- the colour card's rule, for the
1524- /// colour card's reason.
1525- fn drag_speed(&mut self, x: Pixels, first: bool, cx: &mut Context<Self>) {
1526- let along = frac_along(x, self.speed_bar.get());
1527- let lo = f32::from(Speed::MIN.permille());
1528- let hi = f32::from(Speed::MAX.permille());
1529- let raw = lo + along * (hi - lo);
1530- // Snapped to the grid, then to real time itself when it is within half a
1531- // step of it: 1.00x is the one value a hand must be able to hit, and
1532- // nothing about the bar's geometry guarantees a pixel lands on it.
1533- let stepped = (raw / SPEED_STEP as f32).round() as i32 * SPEED_STEP;
1534- // Held back while the worker is busy, the colour card's way and for a
1535- // sharper reason: a live rate also restarts the sound, so a sweep that
1536- // wrote every step would restart it forty times.
1537- let busy = self.seek_since.is_some();
1538- match stash_or_write(&mut self.pending_speed, speed_at(stepped), first, busy) {
1539- Some(speed) => self.write_speed(speed, !first, cx),
1540- None => cx.notify(),
1541- }
1542- }
1543-
1544- /// Writes what a slider drag held back, now that the worker has delivered.
1545- /// The gate is the frame that landed and never a timer: a 100 ms tick
1546- /// ([`SCRUB_GAP`]) says nothing about a reopen that costs half a second, and
1547- /// a drag gated on one would still queue opens nobody sees.
1548- ///
1549- /// Called again by the release, where readiness is beside the point: the
1550- /// value the hand let go on is owed whatever the worker is doing, and a
1551- /// gesture may not end on a sample that was dropped.
1552- fn flush_drag(&mut self, cx: &mut Context<Self>) {
1553- if let Some(params) = self.pending_color.take() {
1554- self.write_color(params, true, cx);
1555- }
1556- if let Some(speed) = self.pending_speed.take() {
1557- self.write_speed(speed, true, cx);
1558- }
1559- }
1560-
1561- /// Opens the silence card on the clip to be scanned: the selected one, or
1562- /// -- with nothing selected -- the clip the picture is coming from, which is
1563- /// the rule the speed card follows and what a person means by "this shot".
1564- /// Either half of a take will do: both halves of an A/V take name the same
1565- /// file and play the same source frames, which is the whole of what a scan
1566- /// is of ([`ScanKey`]).
1567- ///
1568- /// The card is up on the next frame whatever the file is: a still is
1569- /// refused by name here, where the answer costs a look at the path, and
1570- /// everything the decoder has to open the file to know -- a track that is
1571- /// not there, a read that fails -- is refused the same way when the scan
1572- /// lands, because a fifty-second decode is not a thing to open a card
1573- /// behind ([`Player::start_silence_scan`]).
1574- fn open_silence(&mut self, cx: &mut Context<Self>) {
1575- if self.exporting().is_some() {
1576- return;
1577- }
1578- let Some(session) = &self.session else {
1579- self.notify_user("no timeline to scan — open a file first".into());
1580- cx.notify();
1581- return;
1582- };
1583- match self
1584- .selected
1585- .or_else(|| session.video_clip_at(session.now()))
1586- .map(|clip| audio_half(session, clip))
1587- {
1588- Some((lane, idx)) => {
1589- let found = self.session.as_ref().and_then(|session| {
1590- let clip = *session.lane_clips(lane).get(idx)?;
1591- Some((session.sources().get(clip.source)?.clone(), clip))
1592- });
1593- // A still is asked *before* the decoder is: handing a png to the
1594- // mp4 demuxer answers "a box with a larger size than it", which
1595- // is a true sentence about a container and nothing a person can
1596- // act on. A picture has no sound for the same reason a silent
1597- // video has none, so it is refused in the same words.
1598- let Some((source, clip)) = found else {
1599- cx.notify();
1600- return;
1601- };
1602- if engine::is_image(&source.path) {
1603- self.notify_user(unscannable(lane, idx, &source.path).into());
1604- cx.notify();
1605- return;
1606- }
1607- self.silence_open = Some((lane, idx));
1608- self.silence_field = 0;
1609- // One card at a time, the rule the other four follow.
1610- self.keys_open = false;
1611- self.export_open = false;
1612- self.eq_open = None;
1613- self.color_open = None;
1614- self.speed_open = None;
1615- self.context_menu = None;
1616- // The clip's own range, not the file's: the scan reads what this
1617- // clip plays and nothing else, so a take cut in half costs half
1618- // the decode and finds only what is still on the timeline.
1619- let key = (
1620- source.path.clone(),
1621- source.audio_stream,
1622- clip.in_frame,
1623- clip.out_frame,
1624- );
1625- match scan_plan(
1626- self.silence_levels.contains_key(&key),
1627- self.silence_scan.as_ref().map(|scan| &scan.key),
1628- &key,
1629- ) {
1630- ScanPlan::Marks => self.scan_silences(),
1631- ScanPlan::Start => self.start_silence_scan(key, cx),
1632- ScanPlan::Wait => {}
1633- }
1634- }
1635- None => self.notify_user("no clip under the playhead to scan".into()),
1636- }
1637- cx.notify();
1638- }
1639-
1640- /// Opens the mix card. `lane` is the row it lands on -- the track whose
1641- /// header was clicked -- and `None` starts at the top, which is what the
1642- /// stroke means.
1643- ///
1644- /// Nothing here is a clip's, so nothing is refused for want of a selection:
1645- /// a timeline with no audio track at all still has a limiter to set, and a
1646- /// fader on an empty track is the level the next take lands at.
1647- fn open_mix(&mut self, lane: Option<Lane>, cx: &mut Context<Self>) {
1648- if self.exporting().is_some() {
1649- return;
1650- }
1651- self.mix_open = true;
1652- self.mix_field = lane
1653- .and_then(|lane| self.mix_lanes().iter().position(|&l| l == lane))
1654- .unwrap_or(0);
1655- // One card at a time, the rule the other five follow.
1656- self.keys_open = false;
1657- self.export_open = false;
1658- self.eq_open = None;
1659- self.color_open = None;
1660- self.speed_open = None;
1661- self.close_silence();
1662- self.context_menu = None;
1663- cx.notify();
1664- }
1665-
1666- /// The audio tracks the card shows a fader for, top to bottom: *every* one
1667- /// of them, empty ones included -- what the timeline lays out, not what the
1668- /// mixer happens to open (`Project::audio_lanes` leaves an empty track out,
1669- /// and a fader that disappeared when a track was cleared would be a setting
1670- /// nobody could reach).
1671- fn mix_lanes(&self) -> Vec<Lane> {
1672- self.session.as_ref().map_or_else(Vec::new, |session| {
1673- session
1674- .lanes()
1675- .into_iter()
1676- .filter(|l| l.kind == LaneKind::Audio)
1677- .collect()
1678- })
1679- }
1680-
1681- /// Moves the row the card has picked: a fader by [`MIX_DB_STEP`], the
1682- /// ceiling by the same, and the switch either way (a ring of two, like the
1683- /// silence card's unit row).
1684- ///
1685- /// Every one of them goes through the session, which hands it straight to
1686- /// the running mixer: what the ear hears while the arrow is held is the mix
1687- /// that is being set, and nothing is rebuilt to make that true -- no reseek,
1688- /// so no `reset_after_reseek` and no blink in the picture behind the card
1689- /// ([`engine::PlaybackSession::set_lane_gain_db`]).
1690- fn nudge_mix(&mut self, steps: i32, cx: &mut Context<Self>) {
1691- let lanes = self.mix_lanes();
1692- let Some(session) = self.session.as_mut() else {
1693- return;
1694- };
1695- match lanes.get(self.mix_field) {
1696- Some(&lane) => {
1697- let at = session.lane_gain_db(lane) + steps as f32 * MIX_DB_STEP;
1698- session.set_lane_gain_db(lane, at);
1699- }
1700- None => {
1701- let limiter = session.limiter();
1702- let at = match self.mix_field - lanes.len() {
1703- 0 => Limiter {
1704- on: limiter.on,
1705- ..limiter
1706- }
1707- .with_ceiling(limiter.ceiling_db + steps as f32 * MIX_DB_STEP),
1708- _ => Limiter {
1709- on: !limiter.on,
1710- ..limiter
1711- },
1712- };
1713- session.set_limiter(at);
1714- }
1715- }
1716- cx.notify();
1717- }
1718-
1719- /// Closes it and drops the preview with it: marks left on the lane after
1720- /// the card is gone would name frames the next edit has already moved.
1721- fn close_silence(&mut self) {
1722- self.silence_open = None;
1723- self.silence_marks.clear();
1724- self.cancel_silence_scan();
1725- }
1726-
1727- /// Tells the worker nobody is waiting any more. It gives up at its next
1728- /// chunk and the levels it had are dropped: half a track is not an answer,
1729- /// and the flag stays set on the [`Arc`] the landing closure holds, which is
1730- /// how that closure knows to keep its hands off the card.
1731- fn cancel_silence_scan(&mut self) {
1732- if let Some(scan) = self.silence_scan.take() {
1733- scan.progress
1734- .cancel
1735- .store(true, std::sync::atomic::Ordering::Relaxed);
1736- }
1737- }
1738-
1739- /// Hands the decode to a worker and returns at once -- the card is drawn by
1740- /// the very next frame, saying it is scanning. Fifty-one seconds on a 25 GB
1741- /// film is what this used to cost on the render thread, with the card
1742- /// marked open and nothing on screen.
1743- ///
1744- /// Whatever was scanning is cancelled first: one card, one scan, and the
1745- /// clip that has just been asked about is the one worth the disk.
1746- ///
1747- /// Only the clip's own `[in, out)` is read -- source frames over the
1748- /// project's rate, the same seconds [`engine::Project`] hands the decoder
1749- /// for playback -- so half a take is half a wait.
1750- fn start_silence_scan(&mut self, key: ScanKey, cx: &mut Context<Self>) {
1751- self.cancel_silence_scan();
1752- self.silence_marks.clear();
1753- let progress = Arc::new(engine::silence::Progress::default());
1754- let range = source_secs(&key, self.fps);
1755- let scan = cx.background_executor().spawn({
1756- let (key, progress) = (key.clone(), Arc::clone(&progress));
1757- async move { engine::silence::levels_with_progress(&key.0, key.1, range, &progress) }
1758- });
1759- let now = Instant::now();
1760- self.silence_scan = Some(SilenceScan {
1761- key: key.clone(),
1762- started: now,
1763- progress: Arc::clone(&progress),
1764- seen: 0,
1765- since: now,
1766- });
1767- cx.spawn(async move |this, cx| {
1768- let landed = scan.await;
1769- this.update(cx, |this, cx| {
1770- // Cancelled means the card moved on or closed: the levels are a
1771- // prefix of a track nobody asked about any more.
1772- if progress.cancel.load(std::sync::atomic::Ordering::Relaxed) {
1773- return;
1774- }
1775- this.silence_scan = None;
1776- match landed {
1777- Ok(Some(levels)) => {
1778- this.silence_levels.insert(key.clone(), Arc::new(levels));
1779- this.scan_silences();
1780- }
1781- // A source with no audio track is not one long silence: it
1782- // is a clip this card has nothing to say about, named so the
1783- // user knows which one it meant.
1784- Ok(None) => {
1785- if let Some((lane, idx)) = this.silence_open {
1786- this.notify_user(unscannable(lane, idx, &key.0).into());
1787- }
1788- this.close_silence();
1789- }
1790- Err(e) => {
1791- this.close_silence();
1792- this.notify_user(format!("SCAN FAILED: {e}").into());
1793- }
1794- }
1795- cx.notify();
1796- })
1797- .ok();
1798- })
1799- .detach();
1800- cx.notify();
1801- }
1802-
1803- /// Keeps the scanning line's stall clock, for [`Player::poll_import`]'s
1804- /// reason: sampled once per frame rather than while drawing.
1805- fn poll_silence(&mut self) {
1806- if let Some(scan) = &mut self.silence_scan {
1807- scan.poll();
1808- }
1809- }
1810-
1811- /// Applies the settings to levels already in hand and replaces the preview
1812- /// -- never stacks on it. Arithmetic only: the decode is
1813- /// [`Player::start_silence_scan`]'s and happens once per source, so every
1814- /// run here is numbers already read, which is what makes moving a threshold
1815- /// feel like moving a slider. A source still being scanned has no marks yet
1816- /// and says so on the card.
1817- ///
1818- /// Changes nothing about the project: a preview is not an edit, and no undo
1819- /// step is spent until a button is pressed.
1820- fn scan_silences(&mut self) {
1821- let Some((lane, idx)) = self.silence_open else {
1822- return;
1823- };
1824- self.silence_marks.clear();
1825- // Copied out before anything is written back: the cache below lives on
1826- // the same struct the session does.
1827- let Some((clip, source)) = self.session.as_ref().and_then(|session| {
1828- let clip = *session.lane_clips(lane).get(idx)?;
1829- Some((clip, session.sources().get(clip.source)?.clone()))
1830- }) else {
1831- return;
1832- };
1833- // Nothing read yet: the worker is running and the card is drawing its
1834- // line. The marks arrive with the levels.
1835- let Some(levels) = self
1836- .silence_levels
1837- .get(&(
1838- source.path.clone(),
1839- source.audio_stream,
1840- clip.in_frame,
1841- clip.out_frame,
1842- ))
1843- .cloned()
1844- else {
1845- return;
1846- };
1847- self.silence_marks = engine::silence::timeline_regions(
1848- &clip,
1849- self.fps,
1850- &engine::silence::regions(&levels, self.silence),
1851- );
1852- }
1853-
1854- /// Moves the picked row by `steps` and re-runs the scan against it, so the
1855- /// marks on the lane are always what the numbers on the card say.
1856- fn nudge_silence(&mut self, steps: i32) {
1857- let secs = |at: f64| {
1858- (at + f64::from(steps) * SILENCE_SECS_STEP)
1859- .clamp(SILENCE_SECS_RANGE.0, SILENCE_SECS_RANGE.1)
1860- };
1861- match self.silence_field {
1862- // Round either way, like the fit policy's cycle: three choices are
1863- // a ring, not a range.
1864- 0 => {
1865- let at = SCOPES.iter().position(|&s| s == self.silence_scope);
1866- let step = steps.rem_euclid(SCOPES.len() as i32) as usize;
1867- self.silence_scope = SCOPES[(at.unwrap_or(0) + step) % SCOPES.len()];
1868- }
1869- 1 => {
1870- self.silence.threshold_db = (self.silence.threshold_db
1871- + steps as f32 * SILENCE_DB_STEP)
1872- .clamp(SILENCE_DB_RANGE.0, SILENCE_DB_RANGE.1)
1873- }
1874- // Two spellings of the same level, so either arrow flips it -- a
1875- // ring of two, like the scope row's.
1876- 2 => self.silence_dbfs = !self.silence_dbfs,
1877- 3 => self.silence.min_silence = secs(self.silence.min_silence),
1878- 4 => self.silence.padding = secs(self.silence.padding),
1879- 5 => self.silence.min_keep = secs(self.silence.min_keep),
1880- _ => {
1881- self.silence_factor =
1882- silence_rate(i32::from(self.silence_factor.permille()) + steps * SPEED_STEP)
1883- }
1884- }
1885- // Neither the scope nor the rate is part of the scan, but re-running is
1886- // cheap (the levels are cached) and one path is one place for the marks
1887- // to come from.
1888- self.scan_silences();
1889- }
1890-
1891- /// Which lanes an apply reaches, as the card's scope row says it: the
1892- /// lanes of the take the scanned clip belongs to, that clip's lane alone,
1893- /// or every lane there is.
1894- ///
1895- /// The take's lanes are the ones carrying its group id -- a link is one
1896- /// span on however many lanes, so "the take" is exactly the set of lanes
1897- /// that would otherwise be pulled apart. Nothing widens behind the user's
1898- /// back: [`Project::cut_regions`] refuses a scope that would split a take,
1899- /// and this row is how the user says the take instead.
1900- fn silence_lanes(&self) -> Vec<Lane> {
1901- let (Some((lane, idx)), Some(session)) = (self.silence_open, self.session.as_ref()) else {
1902- return Vec::new();
1903- };
1904- match self.silence_scope {
1905- Scope::Track => vec![lane],
1906- Scope::Everything => session.lanes(),
1907- Scope::Take => match session.lane_clips(lane).get(idx).and_then(|c| c.link) {
1908- None => vec![lane],
1909- Some(id) => session
1910- .lanes()
1911- .into_iter()
1912- .filter(|&l| {
1913- l == lane || session.lane_clips(l).iter().any(|c| c.link == Some(id))
1914- })
1915- .collect(),
1916- },
1917- }
1918- }
1919-
1920- /// What an apply acts on: the previewed set and the lanes it reaches, or
1921- /// nothing at all with a notice saying so in the numbers that found
1922- /// nothing.
1923- fn previewed(&mut self) -> Option<(Vec<(u32, u32)>, Vec<Lane>)> {
1924- if self.silence_marks.is_empty() {
1925- self.notify_user(
1926- format!(
1927- "no silence under {:.0} dBFS lasting {:.2} s — raise the threshold or forgive less",
1928- self.silence.threshold_db, self.silence.min_silence
1929- )
1930- .into(),
1931- );
1932- return None;
1933- }
1934- Some((self.silence_marks.clone(), self.silence_lanes()))
1935- }
1936-
1937- /// What an apply says afterwards: which tracks it reached, and -- when that
1938- /// was not all of them -- that the rest were left where they were. The
1939- /// scope is a choice, so the confirmation has to name the choice.
1940- fn silence_reach(&self, lanes: &[Lane]) -> String {
1941- let named = lanes
1942- .iter()
1943- .map(|l| l.label())
1944- .collect::<Vec<_>>()
1945- .join("+");
1946- match self.silence_scope {
1947- Scope::Everything => "on every track".to_string(),
1948- _ => format!("on {named} — other tracks untouched"),
1949- }
1950- }
1951-
1952- /// Cuts every previewed silence out of the lanes the scope names, rippling
1953- /// each hole closed -- one edit and **one** undo press however many there
1954- /// were ([`engine::PlaybackSession::cut_regions`]). Tracks outside the
1955- /// scope do not move; a scope that would take half a take with it comes
1956- /// back refused in the engine's own words, naming both halves.
1957- fn cut_silences(&mut self, cx: &mut Context<Self>) {
1958- let Some((regions, lanes)) = self.previewed() else {
1959- cx.notify();
1960- return;
1961- };
1962- let saved = f64::from(regions.iter().map(|&(_, len)| len).sum::<u32>()) / self.fps;
1963- let (count, reach) = (regions.len(), self.silence_reach(&lanes));
1964- let Some(session) = self.session.as_mut() else {
1965- cx.notify();
1966- return;
1967- };
1968- match session.cut_regions(&regions, &lanes) {
1969- Ok(()) => {
1970- self.close_silence();
1971- // Every hole closed moves the clips after it up a place, so the
1972- // selection now names a different clip than the one that is
1973- // highlighted -- dropped here as after every other edit that
1974- // moves indexes (a delete, a paste, an undo).
1975- self.selected = None;
1976- self.reset_after_reseek();
1977- self.notify_user(
1978- format!(
1979- "{count} SILENCES CUT {reach} — {} shorter, {} takes it back",
1980- secs_label(saved),
1981- self.keymap.display(ActionId::Undo)
1982- )
1983- .into(),
1984- );
1985- }
1986- Err(e) => self.notify_user(e.to_string().into()),
1987- }
1988- cx.notify();
1989- }
1990-
1991- /// Plays them fast instead of cutting them, closing the room each one no
1992- /// longer needs. One undo press like the cut, and the same scope; the
1993- /// refusals (a clip lapping over a silence, a scope that would split a
1994- /// take) come back in the engine's own words and name the lane and frame,
1995- /// and the card stays up so the numbers that produced it are still on
1996- /// screen.
1997- fn speed_silences(&mut self, cx: &mut Context<Self>) {
1998- let Some((regions, lanes)) = self.previewed() else {
1999- cx.notify();
2000- return;
2001- };
2002- let (count, rate) = (regions.len(), self.silence_factor);
2003- let reach = self.silence_reach(&lanes);
2004- let Some(session) = self.session.as_mut() else {
2005- cx.notify();
2006- return;
2007- };
2008- match session.speed_regions(&regions, rate, &lanes) {
2009- Ok(()) => {
2010- self.close_silence();
2011- // Splitting each silence out and closing the room it no longer
2012- // needs moves indexes exactly as the cut does: the selection
2013- // goes with them.
2014- self.selected = None;
2015- self.reset_after_reseek();
2016- self.notify_user(
2017- format!(
2018- "{count} SILENCES AT {rate} {reach} — {} takes it back",
2019- self.keymap.display(ActionId::Undo)
2020- )
2021- .into(),
2022- );
2023- }
2024- Err(e) => self.notify_user(e.to_string().into()),
2025- }
2026- cx.notify();
2027- }
2028-
2029- /// Whether a card owns the window. While one does the timeline under it is
2030- /// out of reach, so a right-click there opens no menu -- the same rule the
2031- /// key handler and the drop target already follow.
2032- /// Whether anything at all is drawn over the window -- a card, a menu or an
2033- /// open list. What the hover labels stand aside for ([`OVERLAID`]): a
2034- /// tooltip belongs to the surface the pointer is on, and while one of these
2035- /// is up that surface is behind it.
2036- fn overlaid(&self) -> bool {
2037- self.modal()
2038- || self.context_menu.is_some()
2039- || self.library_menu.is_some()
2040- || self.picker.is_some()
2041- }
2042-
2043- fn modal(&self) -> bool {
2044- self.keys_open
2045- || self.export_open
2046- || self.eq_open.is_some()
2047- || self.color_open.is_some()
2048- || self.speed_open.is_some()
2049- || self.silence_open.is_some()
2050- || self.mix_open
2051- || self.exporting().is_some()
2052- }
2053-
2054- /// The pointer's way out of whatever card is up: what every scrim's press
2055- /// calls, so `esc` is *a* way out and never the only one. One list, and the
2056- /// same one [`Player::modal`] reads -- a card that can be counted there but
2057- /// not closed here is a card a hand alone cannot shut, which is what
2058- /// `every_card_closes_without_the_keyboard` fails on.
2059- ///
2060- /// Every card at once because only one is ever up (`export_open`): closing
2061- /// "the" card and closing all of them are the same act.
2062- fn close_card(&mut self) {
2063- self.keys_open = false;
2064- self.keys_search.clear();
2065- self.rebinding = None;
2066- self.export_open = false;
2067- // The two things typed *into* the export card go with it: a field left
2068- // open would take the next keystroke for a card that is gone.
2069- self.mbps_edit = None;
2070- self.picker = None;
2071- self.eq_open = None;
2072- self.eq_dragging = false;
2073- self.color_open = None;
2074- self.speed_open = None;
2075- // Marks and a running scan go with this one, which is why it is a call
2076- // and not an assignment ([`Player::close_silence`]).
2077- if self.silence_open.is_some() {
2078- self.close_silence();
2079- }
2080- self.mix_open = false;
2081- }
2082-
2083- /// Which of [`Repeat`]'s three the window is in, for the hold gate at the
2084- /// top of the key handler. Not [`Player::modal`]: that asks whether an
2085- /// overlay is up at all, and here the cards with sliders in them are
2086- /// exactly the ones that answer differently from the keys menu and the
2087- /// export card.
2088- fn repeat_scope(&self) -> Repeat {
2089- // A number being typed is a value under the arrows, exactly as a card's
2090- // slider is -- so a held arrow runs it. Asked before the export card
2091- // below, which otherwise repeats nothing.
2092- if self.mbps_edit.is_some() {
2093- Repeat::Card
2094- } else if self.rebinding.is_some()
2095- || self.keys_open
2096- || self.export_open
2097- || self.exporting().is_some()
2098- {
2099- Repeat::Nothing
2100- } else if self.eq_open.is_some()
2101- || self.color_open.is_some()
2102- || self.speed_open.is_some()
2103- || self.silence_open.is_some()
2104- || self.mix_open
2105- {
2106- Repeat::Card
2107- } else {
2108- Repeat::Keymap
2109- }
2110- }
2111-
2112- /// Opens the equalizer on the selected clip. Audio only, and it says so
2113- /// rather than opening a card of bands that would reach nothing: a video
2114- /// clip carries no sound of its own here (the sound is the audio lane's),
2115- /// and the model would take the setting without anything ever playing it.
2116- fn open_eq(&mut self, cx: &mut Context<Self>) {
2117- if self.exporting().is_some() {
2118- return;
2119- }
2120- let refusal = match (self.selected, &self.session) {
2121- (_, None) => Some("NO TIMELINE — open a file first".to_string()),
2122- (None, _) => Some(format!(
2123- "NOTHING SELECTED — click an audio clip or press {}, then ask again",
2124- self.keymap.display(ActionId::Select)
2125- )),
2126- (Some((lane, _)), _) if lane.kind != LaneKind::Audio => Some(
2127- "NOT AN AUDIO CLIP — the equalizer works on the sound, so pick a clip in an audio lane".to_string(),
2128- ),
2129- _ => None,
2130- };
2131- if let Some(refusal) = refusal {
2132- self.notify_user(refusal.into());
2133- cx.notify();
2134- return;
2135- }
2136- let (lane, idx) = self.selected.expect("checked above");
2137- let session = self.session.as_ref().expect("checked above");
2138- // What the clip already plays through, or the flat default -- so the
2139- // card opens on the curve that is in force and a reopen shows the last
2140- // drag rather than a fresh set of zeroes.
2141- self.eq_params = session
2142- .eq_of(lane, idx)
2143- .cloned()
2144- .unwrap_or_else(EqParams::default_layout);
2145- self.eq_band = 0;
2146- self.eq_dragging = false;
2147- self.eq_open = Some((lane, idx));
2148- // One card at a time, the rule the other two already follow.
2149- self.keys_open = false;
2150- self.export_open = false;
2151- self.context_menu = None;
2152- cx.notify();
2153- }
2154-
2155- /// Writes what the card is showing at its clip: one undo step, one entry in
2156- /// the append-only equalizer table, so this is called once per *gesture* --
2157- /// the end of a drag, a keystroke -- and never per pointer sample.
2158- ///
2159- /// A curve that moves nothing is stored as *no* equalizer at all, which is
2160- /// what keeps a clip nobody has touched on the identity path through
2161- /// playback and export (`engine::eq::EqParams::is_identity`).
2162- fn commit_eq(&mut self, cx: &mut Context<Self>) {
2163- let Some((lane, idx)) = self.eq_open else {
2164- return;
2165- };
2166- let params = (!self.eq_params.is_identity()).then(|| self.eq_params.clone());
2167- if let Some(session) = &mut self.session {
2168- session.set_eq(lane, idx, params);
2169- }
2170- // `set_eq` reseeks inside the engine -- that is what makes the change
2171- // audible at once -- and a reseek is what these flags are about.
2172- self.reset_after_reseek();
2173- cx.notify();
2174- }
2175-
2176- /// Changes the picked band in place and says whether anything moved. Every
2177- /// edit of a band goes through here -- the drag, each key, each stepper
2178- /// button -- so the card has exactly one place that clamps a band into what
2179- /// the graph can draw, and no caller has to remember the limits.
2180- fn set_band(&mut self, change: impl FnOnce(&mut Band)) -> bool {
2181- let Some(band) = self.eq_params.bands.get_mut(self.eq_band) else {
2182- return false;
2183- };
2184- let was = *band;
2185- change(band);
2186- band.freq_hz = band.freq_hz.clamp(EQ_FREQ_LOW, EQ_FREQ_HIGH);
2187- band.gain_db = band.gain_db.clamp(-EQ_GAIN_LIMIT, EQ_GAIN_LIMIT);
2188- band.q = band.q.clamp(EQ_Q_LOW, EQ_Q_HIGH);
2189- *band != was
2190- }
2191-
2192- /// The keyboard's and the buttons' version of a drag: one step on the picked
2193- /// band, committed straight away -- neither has a release to wait for.
2194- fn nudge_band(&mut self, change: impl FnOnce(&mut Band), cx: &mut Context<Self>) {
2195- if self.set_band(change) {
2196- self.commit_eq(cx);
2197- }
2198- }
2199-
2200- /// Where the pointer sits in the graph, as the picked band's frequency and
2201- /// gain: across is the frequency axis and down is the gain one, so the
2202- /// handle follows the hand both ways rather than sliding up a rail. Called
2203- /// on every pointer sample, so the curve bends under it; the write is the
2204- /// release's ([`commit_eq`](Player::commit_eq)).
2205- fn drag_band(&mut self, at: Point<Pixels>, cx: &mut Context<Self>) {
2206- let bounds = self.eq_graph.get();
2207- let gain = (0.5 - frac_down(at.y, bounds)) * 2. * EQ_GAIN_LIMIT;
2208- let freq = eq_freq(frac_along(at.x, bounds));
2209- if self.set_band(|b| {
2210- b.gain_db = gain;
2211- b.freq_hz = freq;
2212- }) {
2213- cx.notify();
2214- }
2215- }
2216-
2217- /// A band added beside the picked one, at the frequency with the most room
2218- /// around it ([`inserted_band`]), and picked so the next keystroke moves the
2219- /// band that was just made. Refused rather than silently ignored at the cap.
2220- fn add_band(&mut self, cx: &mut Context<Self>) {
2221- if self.eq_params.bands.len() >= EQ_BANDS_MAX {
2222- self.notify_user(
2223- format!(
2224- "EQUALIZER FULL — {EQ_BANDS_MAX} bands is all this card holds; move one instead"
2225- )
2226- .into(),
2227- );
2228- cx.notify();
2229- return;
2230- }
2231- let band = inserted_band(&self.eq_params.bands, self.eq_band);
2232- self.eq_band = (self.eq_band + 1).min(self.eq_params.bands.len());
2233- self.eq_params.bands.insert(self.eq_band, band);
2234- self.commit_eq(cx);
2235- }
2236-
2237- /// Takes the picked band out. The last one stays: an equalizer of no bands
2238- /// is a card with nothing to edit, and flattening is what "off" means here.
2239- fn remove_band(&mut self, cx: &mut Context<Self>) {
2240- if self.eq_params.bands.len() <= 1 {
2241- self.notify_user("LAST BAND — flatten it instead (r), or close the card".into());
2242- cx.notify();
2243- return;
2244- }
2245- self.eq_params.bands.remove(self.eq_band);
2246- self.eq_band = self.eq_band.min(self.eq_params.bands.len() - 1);
2247- self.commit_eq(cx);
2248- }
2249-
2250- /// Which band a press on the graph grabs: the nearest one along the
2251- /// frequency axis, so the whole box is the handle rather than a 10 px dot
2252- /// -- and a press that misses every dot still moves the band it is under.
2253- fn nearest_band(&self, x: Pixels) -> usize {
2254- let at = frac_along(x, self.eq_graph.get());
2255- self.eq_params
2256- .bands
2257- .iter()
2258- .enumerate()
2259- .min_by(|(_, a), (_, b)| {
2260- (eq_x(a.freq_hz) - at)
2261- .abs()
2262- .total_cmp(&(eq_x(b.freq_hz) - at).abs())
2263- })
2264- .map_or(0, |(i, _)| i)
2265- }
2266-
2267- /// Jumps the timeline.
2268- fn seek(&mut self, t: f64, cx: &mut Context<Self>) {
2269- if self.exporting().is_some() {
2270- return;
2271- }
2272- let Some(session) = &mut self.session else {
2273- return;
2274- };
2275- session.seek(t);
2276- self.reset_after_reseek();
2277- cx.notify();
2278- }
2279-
2280- /// The keyboard's seek: whole frames along the timeline, through the same
2281- /// door a ruler click uses -- so a step while playing keeps playing, exactly
2282- /// as a click does. It starts from the frame the transport is showing, which
2283- /// past the end is the last one, and that is what lets a step back off EOS
2284- /// revive the picture (the engine's seek leaves [`Transport::Ended`]). Both
2285- /// ends clamp, so the two go-to actions are this same step asked for more
2286- /// frames than the timeline has. Selection is untouched: a seek is not an
2287- /// edit, and nothing it does moves a clip index.
2288- fn step(&mut self, frames: i64, cx: &mut Context<Self>) {
2289- let ended = self.transport() == Transport::Ended;
2290- let Some(session) = &self.session else {
2291- return;
2292- };
2293- let last = ((session.timeline_duration() * self.fps).round() as i64 - 1).max(0);
2294- let now = match ended {
2295- true => last,
2296- false => i64::from(frame_at(session.now(), self.fps)),
2297- };
2298- let target = now.saturating_add(frames).clamp(0, last);
2299- self.seek(target as f64 / self.fps, cx);
2300- }
2301-
2302- /// Splits the clip under the playhead. Metadata only: the timeline->source
2303- /// mapping is unchanged, so nothing reseeks and no flag is touched.
2304- fn cut(&mut self, cx: &mut Context<Self>) {
2305- if self.exporting().is_some() {
2306- return;
2307- }
2308- // Snapped to the source's own grid where one is within reach
2309- // ([`Player::cut_frame`]): a cut a third of a second off a sync point
2310- // looks identical on the bed and turns an export that copies its
2311- // picture in minutes into one that codes every frame of it for hours.
2312- // The playhead goes with it -- what was cut has to be where the line
2313- // is, or the next stroke acts a few frames from where it looks.
2314- let Some(session) = &self.session else {
2315- return;
2316- };
2317- let now = frame_at(session.now(), self.fps);
2318- let at = self.cut_frame(now);
2319- if at != now {
2320- self.seek(f64::from(at) / self.fps, cx);
2321- }
2322- if let Some(session) = &mut self.session {
2323- session.cut_at(f64::from(at) / self.fps);
2324- }
2325- self.selected = None;
2326- cx.notify();
2327- }
2328-
2329- /// Rejoins whatever meets under the playhead and puts it back in one group
2330- /// -- the inverse of [`Player::cut`], and metadata only like it. The engine
2331- /// decides what is joinable; a refusal is worded here, because `false` is
2332- /// all it says and a key that looks broken is worse than one that explains
2333- /// itself.
2334- fn regroup(&mut self, cx: &mut Context<Self>) {
2335- if self.exporting().is_some() {
2336- return;
2337- }
2338- if let Some(session) = &mut self.session {
2339- if session.regroup_at(session.now()) {
2340- self.selected = None;
2341- } else {
2342- self.notify_user(
2343- "NOTHING TO REGROUP — put the playhead where two clips meet, on frames that were cut apart"
2344- .into(),
2345- );
2346- }
2347- }
2348- cx.notify();
2349- }
2350-
2351- /// Takes the selected clip out of its group, so the picture and the sound
2352- /// under it are edited apart from here on: each half selects, moves, trims
2353- /// and is removed alone, and both draw outlined instead of tinted. The
2354- /// selection stays -- the half that was clicked is still the half in hand.
2355- fn detach(&mut self, cx: &mut Context<Self>) {
2356- if self.exporting().is_some() {
2357- return;
2358- }
2359- match (&mut self.session, self.selected) {
2360- (Some(session), Some((lane, idx))) => {
2361- if !session.ungroup(lane, idx) {
2362- self.notify_user(
2363- "NOTHING DETACHED — that clip is not grouped with another".into(),
2364- );
2365- }
2366- }
2367- (Some(_), None) => {
2368- self.notify_user("NOTHING DETACHED — click the take to take apart first".into())
2369- }
2370- (None, _) => {}
2371- }
2372- cx.notify();
2373- }
2374-
2375- /// Puts the selected clip back in a group with the clip covering exactly the
2376- /// same frames on another track -- the way back from [`Player::detach`], and
2377- /// the way to group a picture with sound it was never opened with. The
2378- /// partner is not clicked because there is nothing to choose: a group id
2379- /// names one span, so only a clip covering these very frames could join it,
2380- /// and the engine words what to do when none does.
2381- fn group(&mut self, cx: &mut Context<Self>) {
2382- if self.exporting().is_some() {
2383- return;
2384- }
2385- let partner = match (&self.session, self.selected) {
2386- (Some(session), Some((lane, idx))) => span_partner(session, lane, idx),
2387- _ => None,
2388- };
2389- match (&mut self.session, self.selected, partner) {
2390- (Some(session), Some((lane, idx)), Some((other, o_idx))) => {
2391- if let Err(e) = session.group(lane, idx, other, o_idx) {
2392- self.notify_user(format!("NOT GROUPED — {e}").into());
2393- }
2394- }
2395- (Some(_), Some(_), None) => {
2396- self.notify_user(
2397- "NOTHING TO GROUP WITH — no clip on another track covers exactly these frames"
2398- .into(),
2399- )
2400- }
2401- (Some(_), None, _) => {
2402- self.notify_user("NOTHING GROUPED — click one of the halves first".into())
2403- }
2404- (None, ..) => {}
2405- }
2406- cx.notify();
2407- }
2408-
2409- /// Drops the selected clip and closes the hole: a whole take goes, both
2410- /// lanes of it, and everything after it moves up. A half with no take under
2411- /// it in the video lane -- what a lift leaves behind -- has nothing to
2412- /// ripple, so that one is lifted instead. The engine reseeks itself, so all
2413- /// this owes is the flag reset.
2414- fn delete_selected(&mut self, cx: &mut Context<Self>) {
2415- if self.exporting().is_some() {
2416- return;
2417- }
2418- let selected = self.selected.take();
2419- // Whichever lane it was clicked in: the index is that lane's own, and
2420- // the ripple cuts the clip's span out of every lane -- a group covers
2421- // one span, so deleting a take by its audio half is the same edit as by
2422- // its picture. What is not a whole take is lifted instead, which is what
2423- // reaches a clip on an added track ([`whole_take`]).
2424- let deleted = match (&mut self.session, selected) {
2425- (Some(session), Some((lane, idx))) => match whole_take(session, lane, idx) {
2426- true => session.delete_clip(lane, idx),
2427- false => session.lift_clip(lane, idx),
2428- },
2429- _ => false,
2430- };
2431- if selected.is_some() && !deleted {
2432- self.notify_user("NOTHING DELETED — that clip is no longer there".into());
2433- }
2434- if deleted {
2435- self.reset_after_reseek();
2436- }
2437- cx.notify();
2438- }
2439-
2440- /// Lifts the selected half out and leaves the hole: black picture there if
2441- /// it was the video lane, silence if it was the audio one, and nothing else
2442- /// moves. What Delete is not.
2443- fn lift_selected(&mut self, cx: &mut Context<Self>) {
2444- if self.exporting().is_some() {
2445- return;
2446- }
2447- match (&mut self.session, self.selected.take()) {
2448- (Some(session), Some((lane, idx))) => {
2449- if session.lift_clip(lane, idx) {
2450- self.reset_after_reseek();
2451- } else {
2452- self.notify_user("NOTHING LIFTED — that half is no longer there".into());
2453- }
2454- }
2455- (Some(_), None) => {
2456- self.notify_user("NOTHING LIFTED — click the half to remove first".into())
2457- }
2458- (None, _) => {}
2459- }
2460- cx.notify();
2461- }
2462-
2463- /// Copies the selected clip. Nothing on screen changes, so no notify.
2464- fn copy_selected(&mut self) {
2465- let session = self.session.as_ref();
2466- // Out of the lane it was clicked in: the audio half of a group is a
2467- // different clip from the video one, and copying the wrong lane's
2468- // frames is a paste of the wrong thing.
2469- if let Some(clip) = self
2470- .selected
2471- .and_then(|(lane, idx)| session?.lane_clips(lane).get(idx).copied())
2472- {
2473- self.clipboard = Some(clip);
2474- }
2475- }
2476-
2477- /// Starts a peak decode -- and a stream probe -- for every source that has
2478- /// arrived since the last
2479- /// repaint. One call from the render rather than three at the doors,
2480- /// because argv, an import and a project load are all doors and only this
2481- /// one is guaranteed to run after each of them.
2482- ///
2483- /// The decode itself runs on a background thread, like the file chooser:
2484- /// whole-file audio decode is ~1 s for a half-hour source, and on the render
2485- /// path that is the window not painting for a second. The lane draws a bed
2486- /// meanwhile and the repaint comes with the peaks. The entry is written
2487- /// *before* the spawn, so the sixty repaints that happen while a decode runs
2488- /// start no further ones.
2489- fn cache_media(&mut self, cx: &mut Context<Self>) {
2490- let Some(session) = &self.session else {
2491- return;
2492- };
2493- // How big each still is, for the row that has to say so. Inline, unlike
2494- // the two below: an image header is a few bytes off the front of the
2495- // file, where a sample table is a parse and a decode is a second.
2496- for path in unseen_paths(session.sources(), &self.sizes) {
crates/app/src/player/actions.rsadded+382 -0
@@ -0,0 +1,382 @@
1+//! Every action arrives here: the one dispatch, the notice queue, and the
2+//! delegations to the oracle that say whether an action can be asked for.
3+
4+use crate::*;
5+
6+impl Player {
7+ /// What an action does, wherever it was asked for -- a stroke, or the clip
8+ /// menu item that names the same action. One table, so the two can never
9+ /// come to mean different things.
10+ pub(crate) fn act(&mut self, action: ActionId, cx: &mut Context<Self>) {
11+ // Two doors, one oracle. This used to be the asymmetry the whole
12+ // toolbar was built on: the buttons dimmed themselves off
13+ // [`enable`] while the keyboard walked straight past it, so with no
14+ // file open `s` toggled the snap and `v` added a track while the very
15+ // same controls sat dim and *dead* to the pointer. Whatever refuses the
16+ // button refuses the key, in the oracle's own words -- and a refusal
17+ // that is silent from the keyboard is a bug the same size.
18+ match self.enable(action, None) {
19+ Enable::Yes => {}
20+ // A state refusal is spoken: the thing exists and cannot happen
21+ // *now*, which is exactly what a silent key press fails to say.
22+ Enable::No(why) => {
23+ self.notify_user(format!("{} — {why}", action.label()).into());
24+ cx.notify();
25+ return;
26+ }
27+ // A class refusal is not: the action does not exist for what is in
28+ // front of the user, and `esc` with nothing exporting must not
29+ // answer with a line about exports.
30+ Enable::Hidden(_) => return,
31+ }
32+ match action {
33+ ActionId::Play => self.toggle_or_restart(cx),
34+ ActionId::StepBack => self.step(-1, cx),
35+ ActionId::StepForward => self.step(1, cx),
36+ // A second is however many frames this timeline runs at.
37+ ActionId::JumpBack => self.step(-(self.fps.round() as i64), cx),
38+ ActionId::JumpForward => self.step(self.fps.round() as i64, cx),
39+ // The ends, as a step nothing can be far enough from.
40+ ActionId::GoStart => self.step(i64::MIN, cx),
41+ ActionId::GoEnd => self.step(i64::MAX, cx),
42+ // Not a step at all: the grid these land on is the *source's*, and
43+ // where the next one is depends on the file rather than on the rate.
44+ ActionId::PrevSyncPoint => self.jump_sync(false, cx),
45+ ActionId::NextSyncPoint => self.jump_sync(true, cx),
46+ ActionId::Export => self.open_export(cx),
47+ ActionId::Save => self.save_project(cx),
48+ ActionId::Copy => self.copy_selected(),
49+ ActionId::Paste => self.paste(cx),
50+ ActionId::Cut => self.cut(cx),
51+ ActionId::Regroup => self.regroup(cx),
52+ ActionId::Detach => self.detach(cx),
53+ ActionId::Group => self.group(cx),
54+ ActionId::Select => self.select_under_playhead(cx),
55+ ActionId::SelectNext => self.select_step(true, cx),
56+ ActionId::SelectPrev => self.select_step(false, cx),
57+ ActionId::Delete => self.delete_selected(cx),
58+ ActionId::Lift => self.lift_selected(cx),
59+ ActionId::Color => self.open_color(cx),
60+ ActionId::Fit => self.cycle_fit(cx),
61+ ActionId::Resolution => self.cycle_resolution(cx),
62+ // The playhead is what a key zoom is aimed at: it is the one place
63+ // on the timeline the user is certainly looking at, and keeping it
64+ // still is what every editor does.
65+ ActionId::ZoomIn => self.zoom(ZOOM_STEP, None, cx),
66+ ActionId::ZoomOut => self.zoom(1. / ZOOM_STEP, None, cx),
67+ ActionId::ZoomFit => self.zoom_fit(cx),
68+ ActionId::Undo => self.undo(cx),
69+ ActionId::AddVideoLane => self.add_lane(LaneKind::Video, cx),
70+ ActionId::AddAudioLane => self.add_lane(LaneKind::Audio, cx),
71+ // The last track of that kind: the one the add key put there, so the
72+ // two strokes undo each other press for press. Any other track goes
73+ // through the × in its own header.
74+ ActionId::RemoveVideoLane => self.remove_last_lane(LaneKind::Video, cx),
75+ ActionId::RemoveAudioLane => self.remove_last_lane(LaneKind::Audio, cx),
76+ // The same chooser the + S button opens, and the picked row -- the
77+ // one the panel draws highlighted -- for the removal: the × on any
78+ // other row is that row's own door, and both doors are one call.
79+ ActionId::AddSubtitleTrack => self.pick_and_add_subtitles(cx),
80+ ActionId::RemoveSubtitleTrack => self.remove_subtitle_track(self.sub_track, cx),
81+ ActionId::ToggleMute => self.set_volume(|volume| volume.muted = !volume.muted, cx),
82+ ActionId::VolumeUp => self.set_volume(|volume| volume.step(true), cx),
83+ ActionId::VolumeDown => self.set_volume(|volume| volume.step(false), cx),
84+ ActionId::Equalizer => self.open_eq(cx),
85+ ActionId::Speed => self.open_speed(cx),
86+ ActionId::Silence => self.open_silence(cx),
87+ ActionId::Mix => self.open_mix(None, cx),
88+ ActionId::ToggleSnap => self.toggle_snap(cx),
89+ ActionId::ToggleSubtitles => self.toggle_subtitles(cx),
90+ // The keyboard's door to the same list the toolbar button opens.
91+ // At the window's corner, since a stroke names no place -- and
92+ // [`menu_at`] keeps it on screen from there.
93+ ActionId::Theme => self.open_picker(Pick::Theme, Point::default(), cx),
94+ // Nothing to cancel while nothing is exporting; the export guard in
95+ // the key handler is what answers this one while there is.
96+ ActionId::CancelExport => {}
97+ ActionId::ShowActions => self.show_actions(cx),
98+ }
99+ }
100+
101+ /// Says something to the user. The one door: every message in this editor
102+ /// comes through here, so "queued rather than overwritten" is a property of
103+ /// the field and not of seventy call sites remembering to be polite.
104+ ///
105+ /// A repeat of what is already at the back is dropped -- holding a key that
106+ /// refuses would otherwise fill the queue with one sentence, and the count
107+ /// on the bar would be a count of how long the key was held.
108+ pub(crate) fn notify_user(&mut self, message: SharedString) {
109+ push_notice(&mut self.notices, message);
110+ }
111+
112+ /// Answers the message on the bar and brings up the next one. Whether there
113+ /// was one to answer, because a key that dismissed a notice owes a repaint
114+ /// and a key that dismissed nothing does not.
115+ pub(crate) fn dismiss_notice(&mut self) -> bool {
116+ self.notices.pop_front().is_some()
117+ }
118+
119+ /// The magnet off and on again, in words: a snap that stops working
120+ /// silently reads as a bug, and one that starts working silently reads as
121+ /// one too. The line goes with it -- nothing is being promised any more.
122+ pub(crate) fn toggle_snap(&mut self, cx: &mut Context<Self>) {
123+ self.snap = !self.snap;
124+ self.snap_cue = None;
125+ self.ghost = None;
126+ self.notify_user(match self.snap {
127+ true => "SNAP ON — drags land on clip edges, the playhead and the start".into(),
128+ false => "SNAP OFF — drags land exactly where the hand leaves them".into(),
129+ });
130+ cx.notify();
131+ }
132+
133+ /// The actions card, from its key, from the panel button, or from its own
134+ /// row: open, with an empty search box -- a card that opens showing the
135+ /// last search would hide most of the list for a reason nobody remembers.
136+ pub(crate) fn show_actions(&mut self, cx: &mut Context<Self>) {
137+ self.keys_open = true;
138+ self.keys_search.clear();
139+ self.scroll_keys(None);
140+ self.rebinding = None;
141+ // One card at a time, the rule the other cards follow.
142+ self.export_open = false;
143+ cx.notify();
144+ }
145+
146+ /// Moves the actions card's row list by `by` pixels, or puts it back at the
147+ /// top (`None`). Back to the top after every keystroke that changes the
148+ /// search: a filtered list is shorter than the offset a scrolled one left
149+ /// behind, and a card showing the empty space past its last row reads as a
150+ /// search that found nothing.
151+ ///
152+ /// Clamped to what there is to scroll, so the list cannot be pushed off
153+ /// either end -- `max_offset` is what the last paint measured, which is the
154+ /// only place that number exists.
155+ pub(crate) fn scroll_keys(&self, by: Option<f32>) {
156+ let at = match by {
157+ Some(by) => (f32::from(self.keys_scroll.offset().y) + by)
158+ .clamp(-f32::from(self.keys_scroll.max_offset().height), 0.),
159+ None => 0.,
160+ };
161+ self.keys_scroll.set_offset(point(px(0.), px(at)));
162+ }
163+
164+ /// The cues over the picture, off and on. Says which it is now *and* what is
165+ /// on screen while they are on: a toggle whose answer is invisible when the
166+ /// playhead happens to sit between two cues would read as broken.
167+ pub(crate) fn toggle_subtitles(&mut self, cx: &mut Context<Self>) {
168+ self.subs_on = !self.subs_on;
169+ // Named with its film here too: a notice saying "SUBTITLES ON — eng"
170+ // over a timeline holding two films' eng tracks names neither.
171+ let label = self
172+ .session
173+ .as_ref()
174+ .and_then(|session| sub_pick_name(session.subtitles(), self.sub_track))
175+ .unwrap_or_else(|| "nothing imported".to_string());
176+ self.notify_user(
177+ match self.subs_on {
178+ true => format!("SUBTITLES ON — {label}"),
179+ false => format!("SUBTITLES OFF — {label} is still on the timeline"),
180+ }
181+ .into(),
182+ );
183+ cx.notify();
184+ }
185+
186+ /// The subtitle track the overlay and the strip are showing: the one a
187+ /// library row picked, or the first there is. `None` with no timeline and
188+ /// for an index left over from one that is gone.
189+ pub(crate) fn subtitle_track(&self) -> Option<&engine::subtitle::SubtitleTrack> {
190+ self.session.as_ref()?.subtitles().get(self.sub_track)
191+ }
192+
193+ /// Whether the editor can be asked for `action` right now, and why not when
194+ /// it cannot. `on` is the clip the question is about -- the one a clip menu
195+ /// was opened on -- and `None` asks about the marked clip instead, which is
196+ /// what a menu that hangs over no clip in particular means by "this one".
197+ ///
198+ /// The player's half of [`enable`]: it reads the state, the table decides.
199+ pub(crate) fn enable(&self, action: ActionId, on: Option<(Lane, usize)>) -> Enable {
200+ enable(action, self.ctx(on))
201+ }
202+
203+ /// The state every one of those questions is asked against, read off the
204+ /// player once: [`menu_items`] filters a whole menu with it, so the rows a
205+ /// menu draws and the answers it dims them by come from the same reading.
206+ pub(crate) fn ctx(&self, on: Option<(Lane, usize)>) -> Ctx {
207+ let Some(session) = &self.session else {
208+ return Ctx::default();
209+ };
210+ let clip = on
211+ .or(self.selected)
212+ .and_then(|(lane, idx)| session.lane_clips(lane).get(idx).map(|clip| (*clip, lane)));
213+ Ctx {
214+ clip,
215+ image: clip.is_some_and(|(clip, _)| {
216+ session
217+ .sources()
218+ .get(clip.source)
219+ .is_some_and(|s| engine::is_image(&s.path))
220+ }),
221+ playhead: frame_at(session.now(), self.fps),
222+ timeline: true,
223+ clipboard: self.clipboard.is_some(),
224+ subtitles: !session.subtitles().is_empty(),
225+ playable: !nothing_to_play(Some(session)),
226+ exporting: self.exporting().is_some(),
227+ }
228+ }
229+
230+ /// The same reading for a library row: whether this file can join this
231+ /// timeline -- the very answer the list greys the row by, so the menu over a
232+ /// row and the row under it cannot disagree -- and how many clips play it.
233+ /// [`Player::ctx`] for the other panel.
234+ pub(crate) fn row_ctx(&self, path: &Path, stream: usize) -> RowCtx {
235+ let placed = self.session.as_ref().map_or(0, |session| {
236+ let of_row = session
237+ .sources()
238+ .iter()
239+ .position(|s| s.path == path && s.audio_stream == stream);
240+ of_row.map_or(0, |idx| {
241+ session
242+ .lanes()
243+ .into_iter()
244+ .flat_map(|lane| session.lane_clips(lane))
245+ .filter(|c| c.source == idx)
246+ .count()
247+ })
248+ });
249+ let sources = self
250+ .session
251+ .as_ref()
252+ .map_or(&[][..], PlaybackSession::sources);
253+ RowCtx {
254+ timeline: self.session.is_some(),
255+ exporting: self.exporting().is_some(),
256+ usable: library_rows(
257+ sources,
258+ &self.streams,
259+ &self.decoders,
260+ self.timeline_audio(),
261+ |path| {
262+ self.session
263+ .as_ref()
264+ .map_or(0, |session| session.file_frames(path))
265+ },
266+ )
267+ .iter()
268+ .any(|row| row.path == path && row.stream == stream && row.unusable.is_none()),
269+ placed,
270+ }
271+ }
272+
273+ /// Which of [`Repeat`]'s three the window is in, for the hold gate at the
274+ /// top of the key handler. Not [`Player::modal`]: that asks whether an
275+ /// overlay is up at all, and here the cards with sliders in them are
276+ /// exactly the ones that answer differently from the keys menu and the
277+ /// export card.
278+ pub(crate) fn repeat_scope(&self) -> Repeat {
279+ // A number being typed is a value under the arrows, exactly as a card's
280+ // slider is -- so a held arrow runs it. Asked before the export card
281+ // below, which otherwise repeats nothing.
282+ if self.mbps_edit.is_some() {
283+ Repeat::Card
284+ } else if self.rebinding.is_some()
285+ || self.keys_open
286+ || self.export_open
287+ || self.exporting().is_some()
288+ {
289+ Repeat::Nothing
290+ } else if self.eq_open.is_some()
291+ || self.color_open.is_some()
292+ || self.speed_open.is_some()
293+ || self.silence_open.is_some()
294+ || self.mix_open
295+ {
296+ Repeat::Card
297+ } else {
298+ Repeat::Keymap
299+ }
300+ }
301+
302+ /// One item of a library row's menu, done. Every one of them closes the
303+ /// menu first -- the list under it is about to be rebuilt -- except the one
304+ /// that turns the card over.
305+ pub(crate) fn act_on_row(&mut self, item: RowItem, cx: &mut Context<Self>) {
306+ let Some(menu) = self.library_menu.clone() else {
307+ return;
308+ };
309+ match item {
310+ RowItem::Properties => {
311+ if let Some(open) = &mut self.library_menu {
312+ open.details = true;
313+ }
314+ }
315+ RowItem::Add => {
316+ self.library_menu = None;
317+ self.insert_source(&menu.path, menu.stream, None, None, cx);
318+ }
319+ RowItem::Remove => {
320+ self.library_menu = None;
321+ self.remove_source(&menu.path, menu.stream, cx);
322+ }
323+ RowItem::Reveal => {
324+ self.library_menu = None;
325+ // Another process starting: off the UI thread, exactly as the
326+ // export notice's own click starts it.
327+ cx.background_executor()
328+ .spawn(async move { show_in_file_manager(&menu.path) })
329+ .detach();
330+ }
331+ }
332+ cx.notify();
333+ }
334+
335+ pub(crate) fn undo(&mut self, cx: &mut Context<Self>) {
336+ if self.session.as_mut().is_some_and(PlaybackSession::undo) {
337+ self.reset_after_reseek();
338+ }
339+ self.selected = None;
340+ cx.notify();
341+ }
342+
343+ /// The stroke a waiting row was after: it becomes the whole of what reaches
344+ /// that action, which is what the row was showing. A chord another action
345+ /// already holds is refused by the keymap and the row keeps waiting, so the
346+ /// next stroke is another try rather than a lost one. A binding that took
347+ /// holds either way:
348+ /// what a failed write costs is only the next run, which is what the notice
349+ /// is for.
350+ pub(crate) fn capture(&mut self, action: ActionId, key: &str, ctrl: bool) {
351+ let chord = keymap::Chord {
352+ key: key.to_string(),
353+ ctrl,
354+ };
355+ // Only a stroke the file can spell and read back as itself: gpui reports
356+ // "+" for shift+=, which is the chord grammar's separator, so binding it
357+ // would write a line the next load would have to drop. Refused here, in
358+ // front of the user, rather than silently costing that binding later.
359+ // The row keeps waiting, as it does for a stroke already taken.
360+ if !chord.bindable() {
361+ let text = format!("THAT KEY CANNOT BE BOUND — {}", chord.pretty());
362+ eprintln!("{text}");
363+ self.notify_user(text.into());
364+ return;
365+ }
366+ let text = match self.keymap.rebind_action(action, chord.clone()) {
367+ Ok(()) => {
368+ self.rebinding = None;
369+ match self.keymap.save() {
370+ Ok(()) => return,
371+ Err(e) => format!(
372+ "KEYBINDINGS NOT SAVED — {}: {e}",
373+ Keymap::config_path().display()
374+ ),
375+ }
376+ }
377+ Err(holder) => format!("ALREADY BOUND — {} is {}", chord.pretty(), holder.label()),
378+ };
379+ eprintln!("{text}");
380+ self.notify_user(text.into());
381+ }
382+}
crates/app/src/player/cards.rsadded+1102 -0
@@ -0,0 +1,1102 @@
1+//! The cards the window opens over itself: the pickers, colour, speed,
2+//! silence, the mixer and the equalizer.
3+
4+use crate::*;
5+
6+impl Player {
7+ /// Cycles the *project's* resolution through [`RESOLUTIONS`], starting from
8+ /// the media's own -- the one size that must stay reachable, since a project
9+ /// moved off it has no other way back (the resolution is not an undo step).
10+ /// Every clip is recomposed onto it, so this is what makes "the project
11+ /// resolution and the media's are different things" a thing a user can see.
12+ pub(crate) fn cycle_resolution(&mut self, cx: &mut Context<Self>) {
13+ if self.exporting().is_some() {
14+ return;
15+ }
16+ let Some(session) = &mut self.session else {
17+ self.notify_user("no timeline to resize — open a file first".into());
18+ cx.notify();
19+ return;
20+ };
21+ let (width, height) = next_resolution(session.resolution(), session.native_resolution());
22+ self.apply_resolution(width, height, cx);
23+ }
24+
25+ /// The project resized, whichever asked: the stroke that steps to the next
26+ /// size and the list that names one outright come through here.
27+ pub(crate) fn apply_resolution(&mut self, width: u32, height: u32, cx: &mut Context<Self>) {
28+ if let Some(session) = &mut self.session
29+ && session.set_resolution(width, height)
30+ {
31+ self.notify_user(format!("PROJECT: {width}x{height}").into());
32+ self.reset_after_reseek();
33+ }
34+ cx.notify();
35+ }
36+
37+ /// The project cut at another rate: the list names one and this is where it
38+ /// happens, the way [`apply_resolution`](Self::apply_resolution) is for a
39+ /// size. The whole timeline is conformed to it by the engine
40+ /// ([`PlaybackSession::set_frame_rate`]) -- same seconds, same footage --
41+ /// and the rate the app itself counts frames in follows, since every
42+ /// timecode, ruler mark and step key here is measured in it.
43+ pub(crate) fn apply_frame_rate(&mut self, fps: f64, cx: &mut Context<Self>) {
44+ if let Some(session) = &mut self.session
45+ && session.set_frame_rate(fps)
46+ {
47+ self.fps = session.meta().frame_rate;
48+ self.notify_user(format!("PROJECT: {} fps", fps_label(fps)).into());
49+ self.reset_after_reseek();
50+ }
51+ cx.notify();
52+ }
53+
54+ /// The project's HDR media shown another way: the list names a rendition and
55+ /// this is where it happens, the way [`apply_resolution`](Self::apply_resolution)
56+ /// is for a size. The engine remaps the frame under the playhead at once
57+ /// ([`PlaybackSession::set_tone`]), so the picture on screen is the picked
58+ /// one before the notice has faded -- and an SDR project is unmoved, which
59+ /// is what the notice says rather than pretending something happened.
60+ pub(crate) fn apply_tone(&mut self, preset: Preset, cx: &mut Context<Self>) {
61+ if let Some(session) = &mut self.session
62+ && session.set_tone(preset)
63+ {
64+ self.notify_user(format!("HDR: {} — affects HDR media", tone_label(preset)).into());
65+ self.reset_after_reseek();
66+ }
67+ cx.notify();
68+ }
69+
70+ /// Opens a choice list on a setting, where it was asked for. One floating
71+ /// thing at a time: the click that opens it is the click that closes
72+ /// whatever menu it was opened from.
73+ pub(crate) fn open_picker(&mut self, of: Pick, at: Point<Pixels>, cx: &mut Context<Self>) {
74+ // On the row that is in force, so the first ↑ or ↓ steps off the
75+ // current value rather than off the top of the list.
76+ let sel = self
77+ .choices(of)
78+ .iter()
79+ .position(|(.., picked)| *picked)
80+ .unwrap_or(0);
81+ self.context_menu = None;
82+ self.library_menu = None;
83+ self.picker = Some(Picker { of, at, sel });
84+ cx.notify();
85+ }
86+
87+ /// A row of the open list was picked. Closes the list first -- the rule
88+ /// every menu item here follows -- then does exactly what the stroke for
89+ /// that setting does, through the same door.
90+ pub(crate) fn choose(&mut self, choice: Choice, cx: &mut Context<Self>) {
91+ self.picker = None;
92+ match choice {
93+ Choice::Size(w, h) => self.apply_resolution(w, h, cx),
94+ Choice::Fps(fps) => self.apply_frame_rate(fps, cx),
95+ Choice::Fit(lane, idx, fit) => self.apply_fit(lane, idx, fit, cx),
96+ Choice::Tone(preset) => self.apply_tone(preset, cx),
97+ // In force for the next paint -- every token is read through
98+ // [`ui::theme::palette`], so one store repaints the whole window --
99+ // and kept for the next launch. A file that could not be written is
100+ // said out loud: the difference between "picked" and "picked for
101+ // good" is the user's to know.
102+ Choice::Theme(id) => {
103+ ui::theme::set(id);
104+ if let Err(e) = ui::theme::save(id) {
105+ let path = ui::theme::config_path();
106+ self.notify_user(
107+ format!("THEME COULD NOT BE KEPT — {} — {e}", path.display()).into(),
108+ );
109+ }
110+ cx.notify();
111+ }
112+ // The same field the row's key steps, set outright: a list picks a
113+ // value, it does not step to one.
114+ Choice::AudioRate(kbps) => {
115+ self.audio_kbps = kbps;
116+ cx.notify();
117+ }
118+ }
119+ }
120+
121+ /// Every value the open list offers, in the order it lists them. Empty
122+ /// without a timeline, which is the state where nothing here has a value to
123+ /// offer -- and where the surfaces that open the list are dimmed anyway.
124+ pub(crate) fn choices(&self, of: Pick) -> Vec<ChoiceRow> {
125+ // The palette is not the project's, so it is offered before the
126+ // timeline is asked about: an empty window is painted too, and its
127+ // Theme button is live there like the snap beside it.
128+ if of == Pick::Theme {
129+ return ui::theme::PaletteId::ALL
130+ .into_iter()
131+ .map(|id| {
132+ (
133+ Choice::Theme(id),
134+ id.label().into(),
135+ id.detail().into(),
136+ id == ui::theme::active(),
137+ )
138+ })
139+ .collect();
140+ }
141+ let Some(session) = &self.session else {
142+ return Vec::new();
143+ };
144+ match of {
145+ Pick::Resolution => {
146+ resolution_choices(session.resolution(), session.native_resolution())
147+ }
148+ Pick::Fps => fps_choices(session.meta().frame_rate, session.native_frame_rate()),
149+ Pick::Fit(lane, idx) => {
150+ fit_choices(lane, idx, session.fit_of(lane, idx), session.resolution())
151+ }
152+ Pick::AudioRate => audio_rate_choices(self.audio_kbps),
153+ Pick::Tone => tone_choices(session.tone()),
154+ // Answered above, with or without a timeline.
155+ Pick::Theme => Vec::new(),
156+ }
157+ }
158+
159+ /// Opens the colour card on the clip a grade would go on: the clip that was
160+ /// clicked when it is a video one, and otherwise the clip the picture is
161+ /// coming from -- the one the engine's own compositing rule picks, which is
162+ /// what a person means by "this shot". The fallback stands even now that a
163+ /// selection key exists: a grade asked for with nothing selected still means
164+ /// the shot on screen.
165+ pub(crate) fn open_color(&mut self, cx: &mut Context<Self>) {
166+ if self.exporting().is_some() {
167+ return;
168+ }
169+ let Some(session) = &self.session else {
170+ self.notify_user("no timeline to grade — open a file first".into());
171+ cx.notify();
172+ return;
173+ };
174+ let target = self
175+ .selected
176+ .filter(|(lane, _)| lane.kind == LaneKind::Video)
177+ .or_else(|| session.video_clip_at(session.now()));
178+ match target {
179+ Some(clip) => {
180+ self.color_open = Some(clip);
181+ self.color_band = 0;
182+ self.color_dragging = false;
183+ // A sample the last card held back belongs to the clip it was
184+ // dragged on, and this may be another one.
185+ self.pending_color = None;
186+ // One card at a time, the rule both the others already follow.
187+ self.keys_open = false;
188+ self.export_open = false;
189+ self.context_menu = None;
190+ }
191+ None => self.notify_user("no clip under the playhead to grade".into()),
192+ }
193+ cx.notify();
194+ }
195+
196+ /// What the card's clip is graded by right now -- the identity for one
197+ /// nobody has graded, which is what the sliders start at. A sample a drag is
198+ /// still holding wins over the clip's own: it is what the hand has asked
199+ /// for, so it is what the sliders show and what the next sample builds on.
200+ pub(crate) fn color_params(&self) -> ColorParams {
201+ if let Some(params) = self.pending_color {
202+ return params;
203+ }
204+ self.color_open
205+ .zip(self.session.as_ref())
206+ .and_then(|((lane, idx), session)| session.color_of(lane, idx).copied())
207+ .unwrap_or_default()
208+ }
209+
210+ /// Puts `params` on the card's clip, or takes the grade off when they are
211+ /// the identity -- a slider walked back to the middle leaves the clip
212+ /// ungraded rather than carrying a do-nothing entry, which is what keeps an
213+ /// untouched project byte-identical. The engine reseeks on the edit, so the
214+ /// frame on screen repaints through the new grade; this only owes the flags
215+ /// that reseek clears.
216+ pub(crate) fn set_color(&mut self, params: ColorParams, cx: &mut Context<Self>) {
217+ self.write_color(params, false, cx);
218+ }
219+
220+ /// Both writes: `live` is the one that takes no undo step, which is what
221+ /// every sample *inside* a drag goes through
222+ /// (`PlaybackSession::set_color_live`). Either way the engine reseeks, so
223+ /// the picture -- and the histogram counted off it -- is regraded at once.
224+ pub(crate) fn write_color(&mut self, params: ColorParams, live: bool, cx: &mut Context<Self>) {
225+ // Any write supersedes a held sample, whichever way it arrived -- a key,
226+ // a reset, or the flush that took this one out of the stash.
227+ self.pending_color = None;
228+ let Some((lane, idx)) = self.color_open else {
229+ return;
230+ };
231+ let Some(session) = &mut self.session else {
232+ return;
233+ };
234+ let grade = Some(params).filter(|p| !p.is_identity());
235+ let took = match live {
236+ true => session.set_color_live(lane, idx, grade),
237+ false => session.set_color(lane, idx, grade),
238+ };
239+ if took {
240+ self.reset_after_reseek();
241+ }
242+ cx.notify();
243+ }
244+
245+ /// Moves the picked slider by `steps` of [`COLOR_STEP`], clamped to that
246+ /// band's range. One edit, so one undo step per press.
247+ pub(crate) fn nudge_color(&mut self, steps: f32, cx: &mut Context<Self>) {
248+ let mut params = self.color_params();
249+ let (_, low, high) = COLOR_BANDS[self.color_band];
250+ let value = band_mut(&mut params, self.color_band);
251+ *value = (*value + steps * COLOR_STEP).clamp(low, high);
252+ self.set_color(params, cx);
253+ }
254+
255+ /// Where the pointer sits along a slider, as that band's value: the left end
256+ /// of the bar is the bottom of its range and the right end the top. Called
257+ /// on every pointer sample, so the grade -- and the picture, and the
258+ /// histogram over it -- moves under the hand.
259+ ///
260+ /// `first` is the press: it takes the undo step the whole gesture rolls back
261+ /// to, and every sample after it is live. That is why it writes even when
262+ /// the value did not change -- without that snapshot the rest of the drag
263+ /// would be unundoable.
264+ ///
265+ /// Values land on the [`COLOR_STEP`] grid the keys use, which also bounds
266+ /// one drag to forty-odd entries in the project's colour table.
267+ ///
268+ /// Samples crossed while the worker still owes a frame are held rather than
269+ /// written ([`stash_or_write`]): a reopen costs half a second on a big film,
270+ /// so a bar-wide sweep that wrote every step would queue forty opens, cancel
271+ /// thirty-nine of them and freeze the window for the sum. What is written is
272+ /// one grade per frame the worker actually delivers.
273+ pub(crate) fn drag_color(&mut self, x: Pixels, first: bool, cx: &mut Context<Self>) {
274+ let (_, low, high) = COLOR_BANDS[self.color_band];
275+ let along = frac_along(x, self.color_bars[self.color_band].get());
276+ let value = color_snap(low + along * (high - low)).clamp(low, high);
277+ let mut params = self.color_params();
278+ let at = band_mut(&mut params, self.color_band);
279+ if *at == value && !first {
280+ return;
281+ }
282+ *at = value;
283+ let busy = self.seek_since.is_some();
284+ match stash_or_write(&mut self.pending_color, params, first, busy) {
285+ Some(params) => self.write_color(params, !first, cx),
286+ // The sliders draw off the held sample, so the handle goes on
287+ // following the hand while the picture catches up.
288+ None => cx.notify(),
289+ }
290+ }
291+
292+ /// Opens the speed card on the clip whose rate is to change: the selected
293+ /// one, or -- with nothing selected -- the clip the picture is coming from,
294+ /// which is what a person means by "this shot". Either half of a take will
295+ /// do: a rate applies to the whole group, so opening it on the sound and
296+ /// opening it on the picture are the same card.
297+ pub(crate) fn open_speed(&mut self, cx: &mut Context<Self>) {
298+ if self.exporting().is_some() {
299+ return;
300+ }
301+ let Some(session) = &self.session else {
302+ self.notify_user("no timeline to re-time — open a file first".into());
303+ cx.notify();
304+ return;
305+ };
306+ match self
307+ .selected
308+ .or_else(|| session.video_clip_at(session.now()))
309+ {
310+ Some(clip) => {
311+ self.speed_open = Some(clip);
312+ self.speed_dragging = false;
313+ // The colour card's rule: a held sample is the last clip's.
314+ self.pending_speed = None;
315+ // One card at a time, the rule the other four follow.
316+ self.keys_open = false;
317+ self.export_open = false;
318+ self.eq_open = None;
319+ self.color_open = None;
320+ self.close_silence();
321+ self.context_menu = None;
322+ }
323+ None => self.notify_user("no clip under the playhead to re-time".into()),
324+ }
325+ cx.notify();
326+ }
327+
328+ /// What the card's clip plays at right now -- real time for one nobody has
329+ /// touched, which is where the bar starts.
330+ pub(crate) fn card_speed(&self) -> Speed {
331+ if let Some(speed) = self.pending_speed {
332+ return speed;
333+ }
334+ self.speed_open
335+ .zip(self.session.as_ref())
336+ .map_or(Speed::NORMAL, |((lane, idx), session)| {
337+ session.speed_of(lane, idx)
338+ })
339+ }
340+
341+ /// Writes a rate at the card's clip and its whole group -- one undo step for
342+ /// the lot ([`engine::PlaybackSession::set_speed`]). The engine reseeks, so
343+ /// the picture runs at the new rate and the sound is resampled from the next
344+ /// chunk on; a refusal (a slower clip would run into its neighbour) comes
345+ /// back in the engine's own words and *names* the clip in the way, because
346+ /// "it did not fit" is not something a person can go and fix.
347+ pub(crate) fn set_speed(&mut self, speed: Speed, cx: &mut Context<Self>) {
348+ self.write_speed(speed, false, cx);
349+ }
350+
351+ /// Both writes: `live` is the one that takes no undo step, which is what
352+ /// every sample *inside* a drag goes through -- so a drag from 1.00x to
353+ /// 2.00x is one undo press and lands back where the hand picked it up, and
354+ /// the whole linked group comes back with it.
355+ pub(crate) fn write_speed(&mut self, speed: Speed, live: bool, cx: &mut Context<Self>) {
356+ // The colour card's rule: a write supersedes whatever a drag was holding.
357+ self.pending_speed = None;
358+ let Some((lane, idx)) = self.speed_open else {
359+ return;
360+ };
361+ let Some(session) = &mut self.session else {
362+ return;
363+ };
364+ if speed != session.speed_of(lane, idx) {
365+ let wrote = match live {
366+ true => session.set_speed_live(lane, idx, speed),
367+ false => session.set_speed(lane, idx, speed),
368+ };
369+ match wrote {
370+ Ok(()) => self.reset_after_reseek(),
371+ Err(e) => self.notify_user(e.to_string().into()),
372+ }
373+ }
374+ cx.notify();
375+ }
376+
377+ /// One [`SPEED_STEP`] per keystroke, clamped to what a [`Speed`] can hold.
378+ pub(crate) fn nudge_speed(&mut self, steps: i32, cx: &mut Context<Self>) {
379+ let at = i32::from(self.card_speed().permille()) + steps * SPEED_STEP;
380+ self.set_speed(speed_at(at), cx);
381+ }
382+
383+ /// Where the pointer sits along the bar, as a rate: the left end is
384+ /// [`Speed::MIN`] and the right end [`Speed::MAX`], on the same
385+ /// [`SPEED_STEP`] grid the keys move on -- so a drag can land on exactly
386+ /// 1.00x and the same drag twice is one entry, not forty.
387+ /// `first` is the press: it takes the undo step the whole gesture rolls back
388+ /// to, and every sample after it is live -- the colour card's rule, for the
389+ /// colour card's reason.
390+ pub(crate) fn drag_speed(&mut self, x: Pixels, first: bool, cx: &mut Context<Self>) {
391+ let along = frac_along(x, self.speed_bar.get());
392+ let lo = f32::from(Speed::MIN.permille());
393+ let hi = f32::from(Speed::MAX.permille());
394+ let raw = lo + along * (hi - lo);
395+ // Snapped to the grid, then to real time itself when it is within half a
396+ // step of it: 1.00x is the one value a hand must be able to hit, and
397+ // nothing about the bar's geometry guarantees a pixel lands on it.
398+ let stepped = (raw / SPEED_STEP as f32).round() as i32 * SPEED_STEP;
399+ // Held back while the worker is busy, the colour card's way and for a
400+ // sharper reason: a live rate also restarts the sound, so a sweep that
401+ // wrote every step would restart it forty times.
402+ let busy = self.seek_since.is_some();
403+ match stash_or_write(&mut self.pending_speed, speed_at(stepped), first, busy) {
404+ Some(speed) => self.write_speed(speed, !first, cx),
405+ None => cx.notify(),
406+ }
407+ }
408+
409+ /// Writes what a slider drag held back, now that the worker has delivered.
410+ /// The gate is the frame that landed and never a timer: a 100 ms tick
411+ /// ([`SCRUB_GAP`]) says nothing about a reopen that costs half a second, and
412+ /// a drag gated on one would still queue opens nobody sees.
413+ ///
414+ /// Called again by the release, where readiness is beside the point: the
415+ /// value the hand let go on is owed whatever the worker is doing, and a
416+ /// gesture may not end on a sample that was dropped.
417+ pub(crate) fn flush_drag(&mut self, cx: &mut Context<Self>) {
418+ if let Some(params) = self.pending_color.take() {
419+ self.write_color(params, true, cx);
420+ }
421+ if let Some(speed) = self.pending_speed.take() {
422+ self.write_speed(speed, true, cx);
423+ }
424+ }
425+
426+ /// Opens the silence card on the clip to be scanned: the selected one, or
427+ /// -- with nothing selected -- the clip the picture is coming from, which is
428+ /// the rule the speed card follows and what a person means by "this shot".
429+ /// Either half of a take will do: both halves of an A/V take name the same
430+ /// file and play the same source frames, which is the whole of what a scan
431+ /// is of ([`ScanKey`]).
432+ ///
433+ /// The card is up on the next frame whatever the file is: a still is
434+ /// refused by name here, where the answer costs a look at the path, and
435+ /// everything the decoder has to open the file to know -- a track that is
436+ /// not there, a read that fails -- is refused the same way when the scan
437+ /// lands, because a fifty-second decode is not a thing to open a card
438+ /// behind ([`Player::start_silence_scan`]).
439+ pub(crate) fn open_silence(&mut self, cx: &mut Context<Self>) {
440+ if self.exporting().is_some() {
441+ return;
442+ }
443+ let Some(session) = &self.session else {
444+ self.notify_user("no timeline to scan — open a file first".into());
445+ cx.notify();
446+ return;
447+ };
448+ match self
449+ .selected
450+ .or_else(|| session.video_clip_at(session.now()))
451+ .map(|clip| audio_half(session, clip))
452+ {
453+ Some((lane, idx)) => {
454+ let found = self.session.as_ref().and_then(|session| {
455+ let clip = *session.lane_clips(lane).get(idx)?;
456+ Some((session.sources().get(clip.source)?.clone(), clip))
457+ });
458+ // A still is asked *before* the decoder is: handing a png to the
459+ // mp4 demuxer answers "a box with a larger size than it", which
460+ // is a true sentence about a container and nothing a person can
461+ // act on. A picture has no sound for the same reason a silent
462+ // video has none, so it is refused in the same words.
463+ let Some((source, clip)) = found else {
464+ cx.notify();
465+ return;
466+ };
467+ if engine::is_image(&source.path) {
468+ self.notify_user(unscannable(lane, idx, &source.path).into());
469+ cx.notify();
470+ return;
471+ }
472+ self.silence_open = Some((lane, idx));
473+ self.silence_field = 0;
474+ // One card at a time, the rule the other four follow.
475+ self.keys_open = false;
476+ self.export_open = false;
477+ self.eq_open = None;
478+ self.color_open = None;
479+ self.speed_open = None;
480+ self.context_menu = None;
481+ // The clip's own range, not the file's: the scan reads what this
482+ // clip plays and nothing else, so a take cut in half costs half
483+ // the decode and finds only what is still on the timeline.
484+ let key = (
485+ source.path.clone(),
486+ source.audio_stream,
487+ clip.in_frame,
488+ clip.out_frame,
489+ );
490+ match scan_plan(
491+ self.silence_levels.contains_key(&key),
492+ self.silence_scan.as_ref().map(|scan| &scan.key),
493+ &key,
494+ ) {
495+ ScanPlan::Marks => self.scan_silences(),
496+ ScanPlan::Start => self.start_silence_scan(key, cx),
497+ ScanPlan::Wait => {}
498+ }
499+ }
500+ None => self.notify_user("no clip under the playhead to scan".into()),
501+ }
502+ cx.notify();
503+ }
504+
505+ /// Opens the mix card. `lane` is the row it lands on -- the track whose
506+ /// header was clicked -- and `None` starts at the top, which is what the
507+ /// stroke means.
508+ ///
509+ /// Nothing here is a clip's, so nothing is refused for want of a selection:
510+ /// a timeline with no audio track at all still has a limiter to set, and a
511+ /// fader on an empty track is the level the next take lands at.
512+ pub(crate) fn open_mix(&mut self, lane: Option<Lane>, cx: &mut Context<Self>) {
513+ if self.exporting().is_some() {
514+ return;
515+ }
516+ self.mix_open = true;
517+ self.mix_field = lane
518+ .and_then(|lane| self.mix_lanes().iter().position(|&l| l == lane))
519+ .unwrap_or(0);
520+ // One card at a time, the rule the other five follow.
521+ self.keys_open = false;
522+ self.export_open = false;
523+ self.eq_open = None;
524+ self.color_open = None;
525+ self.speed_open = None;
526+ self.close_silence();
527+ self.context_menu = None;
528+ cx.notify();
529+ }
530+
531+ /// The audio tracks the card shows a fader for, top to bottom: *every* one
532+ /// of them, empty ones included -- what the timeline lays out, not what the
533+ /// mixer happens to open (`Project::audio_lanes` leaves an empty track out,
534+ /// and a fader that disappeared when a track was cleared would be a setting
535+ /// nobody could reach).
536+ pub(crate) fn mix_lanes(&self) -> Vec<Lane> {
537+ self.session.as_ref().map_or_else(Vec::new, |session| {
538+ session
539+ .lanes()
540+ .into_iter()
541+ .filter(|l| l.kind == LaneKind::Audio)
542+ .collect()
543+ })
544+ }
545+
546+ /// Moves the row the card has picked: a fader by [`MIX_DB_STEP`], the
547+ /// ceiling by the same, and the switch either way (a ring of two, like the
548+ /// silence card's unit row).
549+ ///
550+ /// Every one of them goes through the session, which hands it straight to
551+ /// the running mixer: what the ear hears while the arrow is held is the mix
552+ /// that is being set, and nothing is rebuilt to make that true -- no reseek,
553+ /// so no `reset_after_reseek` and no blink in the picture behind the card
554+ /// ([`engine::PlaybackSession::set_lane_gain_db`]).
555+ pub(crate) fn nudge_mix(&mut self, steps: i32, cx: &mut Context<Self>) {
556+ let lanes = self.mix_lanes();
557+ let Some(session) = self.session.as_mut() else {
558+ return;
559+ };
560+ match lanes.get(self.mix_field) {
561+ Some(&lane) => {
562+ let at = session.lane_gain_db(lane) + steps as f32 * MIX_DB_STEP;
563+ session.set_lane_gain_db(lane, at);
564+ }
565+ None => {
566+ let limiter = session.limiter();
567+ let at = match self.mix_field - lanes.len() {
568+ 0 => Limiter {
569+ on: limiter.on,
570+ ..limiter
571+ }
572+ .with_ceiling(limiter.ceiling_db + steps as f32 * MIX_DB_STEP),
573+ _ => Limiter {
574+ on: !limiter.on,
575+ ..limiter
576+ },
577+ };
578+ session.set_limiter(at);
579+ }
580+ }
581+ cx.notify();
582+ }
583+
584+ /// Closes it and drops the preview with it: marks left on the lane after
585+ /// the card is gone would name frames the next edit has already moved.
586+ pub(crate) fn close_silence(&mut self) {
587+ self.silence_open = None;
588+ self.silence_marks.clear();
589+ self.cancel_silence_scan();
590+ }
591+
592+ /// Tells the worker nobody is waiting any more. It gives up at its next
593+ /// chunk and the levels it had are dropped: half a track is not an answer,
594+ /// and the flag stays set on the [`Arc`] the landing closure holds, which is
595+ /// how that closure knows to keep its hands off the card.
596+ pub(crate) fn cancel_silence_scan(&mut self) {
597+ if let Some(scan) = self.silence_scan.take() {
598+ scan.progress
599+ .cancel
600+ .store(true, std::sync::atomic::Ordering::Relaxed);
601+ }
602+ }
603+
604+ /// Hands the decode to a worker and returns at once -- the card is drawn by
605+ /// the very next frame, saying it is scanning. Fifty-one seconds on a 25 GB
606+ /// film is what this used to cost on the render thread, with the card
607+ /// marked open and nothing on screen.
608+ ///
609+ /// Whatever was scanning is cancelled first: one card, one scan, and the
610+ /// clip that has just been asked about is the one worth the disk.
611+ ///
612+ /// Only the clip's own `[in, out)` is read -- source frames over the
613+ /// project's rate, the same seconds [`engine::Project`] hands the decoder
614+ /// for playback -- so half a take is half a wait.
615+ pub(crate) fn start_silence_scan(&mut self, key: ScanKey, cx: &mut Context<Self>) {
616+ self.cancel_silence_scan();
617+ self.silence_marks.clear();
618+ let progress = Arc::new(engine::silence::Progress::default());
619+ let range = source_secs(&key, self.fps);
620+ let scan = cx.background_executor().spawn({
621+ let (key, progress) = (key.clone(), Arc::clone(&progress));
622+ async move { engine::silence::levels_with_progress(&key.0, key.1, range, &progress) }
623+ });
624+ let now = Instant::now();
625+ self.silence_scan = Some(SilenceScan {
626+ key: key.clone(),
627+ started: now,
628+ progress: Arc::clone(&progress),
629+ seen: 0,
630+ since: now,
631+ });
632+ cx.spawn(async move |this, cx| {
633+ let landed = scan.await;
634+ this.update(cx, |this, cx| {
635+ // Cancelled means the card moved on or closed: the levels are a
636+ // prefix of a track nobody asked about any more.
637+ if progress.cancel.load(std::sync::atomic::Ordering::Relaxed) {
638+ return;
639+ }
640+ this.silence_scan = None;
641+ match landed {
642+ Ok(Some(levels)) => {
643+ this.silence_levels.insert(key.clone(), Arc::new(levels));
644+ this.scan_silences();
645+ }
646+ // A source with no audio track is not one long silence: it
647+ // is a clip this card has nothing to say about, named so the
648+ // user knows which one it meant.
649+ Ok(None) => {
650+ if let Some((lane, idx)) = this.silence_open {
651+ this.notify_user(unscannable(lane, idx, &key.0).into());
652+ }
653+ this.close_silence();
654+ }
655+ Err(e) => {
656+ this.close_silence();
657+ this.notify_user(format!("SCAN FAILED: {e}").into());
658+ }
659+ }
660+ cx.notify();
661+ })
662+ .ok();
663+ })
664+ .detach();
665+ cx.notify();
666+ }
667+
668+ /// Keeps the scanning line's stall clock, for [`Player::poll_import`]'s
669+ /// reason: sampled once per frame rather than while drawing.
670+ pub(crate) fn poll_silence(&mut self) {
671+ if let Some(scan) = &mut self.silence_scan {
672+ scan.poll();
673+ }
674+ }
675+
676+ /// Applies the settings to levels already in hand and replaces the preview
677+ /// -- never stacks on it. Arithmetic only: the decode is
678+ /// [`Player::start_silence_scan`]'s and happens once per source, so every
679+ /// run here is numbers already read, which is what makes moving a threshold
680+ /// feel like moving a slider. A source still being scanned has no marks yet
681+ /// and says so on the card.
682+ ///
683+ /// Changes nothing about the project: a preview is not an edit, and no undo
684+ /// step is spent until a button is pressed.
685+ pub(crate) fn scan_silences(&mut self) {
686+ let Some((lane, idx)) = self.silence_open else {
687+ return;
688+ };
689+ self.silence_marks.clear();
690+ // Copied out before anything is written back: the cache below lives on
691+ // the same struct the session does.
692+ let Some((clip, source)) = self.session.as_ref().and_then(|session| {
693+ let clip = *session.lane_clips(lane).get(idx)?;
694+ Some((clip, session.sources().get(clip.source)?.clone()))
695+ }) else {
696+ return;
697+ };
698+ // Nothing read yet: the worker is running and the card is drawing its
699+ // line. The marks arrive with the levels.
700+ let Some(levels) = self
701+ .silence_levels
702+ .get(&(
703+ source.path.clone(),
704+ source.audio_stream,
705+ clip.in_frame,
706+ clip.out_frame,
707+ ))
708+ .cloned()
709+ else {
710+ return;
711+ };
712+ self.silence_marks = engine::silence::timeline_regions(
713+ &clip,
714+ self.fps,
715+ &engine::silence::regions(&levels, self.silence),
716+ );
717+ }
718+
719+ /// Moves the picked row by `steps` and re-runs the scan against it, so the
720+ /// marks on the lane are always what the numbers on the card say.
721+ pub(crate) fn nudge_silence(&mut self, steps: i32) {
722+ let secs = |at: f64| {
723+ (at + f64::from(steps) * SILENCE_SECS_STEP)
724+ .clamp(SILENCE_SECS_RANGE.0, SILENCE_SECS_RANGE.1)
725+ };
726+ match self.silence_field {
727+ // Round either way, like the fit policy's cycle: three choices are
728+ // a ring, not a range.
729+ 0 => {
730+ let at = SCOPES.iter().position(|&s| s == self.silence_scope);
731+ let step = steps.rem_euclid(SCOPES.len() as i32) as usize;
732+ self.silence_scope = SCOPES[(at.unwrap_or(0) + step) % SCOPES.len()];
733+ }
734+ 1 => {
735+ self.silence.threshold_db = (self.silence.threshold_db
736+ + steps as f32 * SILENCE_DB_STEP)
737+ .clamp(SILENCE_DB_RANGE.0, SILENCE_DB_RANGE.1)
738+ }
739+ // Two spellings of the same level, so either arrow flips it -- a
740+ // ring of two, like the scope row's.
741+ 2 => self.silence_dbfs = !self.silence_dbfs,
742+ 3 => self.silence.min_silence = secs(self.silence.min_silence),
743+ 4 => self.silence.padding = secs(self.silence.padding),
744+ 5 => self.silence.min_keep = secs(self.silence.min_keep),
745+ _ => {
746+ self.silence_factor =
747+ silence_rate(i32::from(self.silence_factor.permille()) + steps * SPEED_STEP)
748+ }
749+ }
750+ // Neither the scope nor the rate is part of the scan, but re-running is
751+ // cheap (the levels are cached) and one path is one place for the marks
752+ // to come from.
753+ self.scan_silences();
754+ }
755+
756+ /// Which lanes an apply reaches, as the card's scope row says it: the
757+ /// lanes of the take the scanned clip belongs to, that clip's lane alone,
758+ /// or every lane there is.
759+ ///
760+ /// The take's lanes are the ones carrying its group id -- a link is one
761+ /// span on however many lanes, so "the take" is exactly the set of lanes
762+ /// that would otherwise be pulled apart. Nothing widens behind the user's
763+ /// back: [`Project::cut_regions`] refuses a scope that would split a take,
764+ /// and this row is how the user says the take instead.
765+ pub(crate) fn silence_lanes(&self) -> Vec<Lane> {
766+ let (Some((lane, idx)), Some(session)) = (self.silence_open, self.session.as_ref()) else {
767+ return Vec::new();
768+ };
769+ match self.silence_scope {
770+ Scope::Track => vec![lane],
771+ Scope::Everything => session.lanes(),
772+ Scope::Take => match session.lane_clips(lane).get(idx).and_then(|c| c.link) {
773+ None => vec![lane],
774+ Some(id) => session
775+ .lanes()
776+ .into_iter()
777+ .filter(|&l| {
778+ l == lane || session.lane_clips(l).iter().any(|c| c.link == Some(id))
779+ })
780+ .collect(),
781+ },
782+ }
783+ }
784+
785+ /// What an apply acts on: the previewed set and the lanes it reaches, or
786+ /// nothing at all with a notice saying so in the numbers that found
787+ /// nothing.
788+ pub(crate) fn previewed(&mut self) -> Option<(Vec<(u32, u32)>, Vec<Lane>)> {
789+ if self.silence_marks.is_empty() {
790+ self.notify_user(
791+ format!(
792+ "no silence under {:.0} dBFS lasting {:.2} s — raise the threshold or forgive less",
793+ self.silence.threshold_db, self.silence.min_silence
794+ )
795+ .into(),
796+ );
797+ return None;
798+ }
799+ Some((self.silence_marks.clone(), self.silence_lanes()))
800+ }
801+
802+ /// What an apply says afterwards: which tracks it reached, and -- when that
803+ /// was not all of them -- that the rest were left where they were. The
804+ /// scope is a choice, so the confirmation has to name the choice.
805+ pub(crate) fn silence_reach(&self, lanes: &[Lane]) -> String {
806+ let named = lanes
807+ .iter()
808+ .map(|l| l.label())
809+ .collect::<Vec<_>>()
810+ .join("+");
811+ match self.silence_scope {
812+ Scope::Everything => "on every track".to_string(),
813+ _ => format!("on {named} — other tracks untouched"),
814+ }
815+ }
816+
817+ /// Cuts every previewed silence out of the lanes the scope names, rippling
818+ /// each hole closed -- one edit and **one** undo press however many there
819+ /// were ([`engine::PlaybackSession::cut_regions`]). Tracks outside the
820+ /// scope do not move; a scope that would take half a take with it comes
821+ /// back refused in the engine's own words, naming both halves.
822+ pub(crate) fn cut_silences(&mut self, cx: &mut Context<Self>) {
823+ let Some((regions, lanes)) = self.previewed() else {
824+ cx.notify();
825+ return;
826+ };
827+ let saved = f64::from(regions.iter().map(|&(_, len)| len).sum::<u32>()) / self.fps;
828+ let (count, reach) = (regions.len(), self.silence_reach(&lanes));
829+ let Some(session) = self.session.as_mut() else {
830+ cx.notify();
831+ return;
832+ };
833+ match session.cut_regions(&regions, &lanes) {
834+ Ok(()) => {
835+ self.close_silence();
836+ // Every hole closed moves the clips after it up a place, so the
837+ // selection now names a different clip than the one that is
838+ // highlighted -- dropped here as after every other edit that
839+ // moves indexes (a delete, a paste, an undo).
840+ self.selected = None;
841+ self.reset_after_reseek();
842+ self.notify_user(
843+ format!(
844+ "{count} SILENCES CUT {reach} — {} shorter, {} takes it back",
845+ secs_label(saved),
846+ self.keymap.display(ActionId::Undo)
847+ )
848+ .into(),
849+ );
850+ }
851+ Err(e) => self.notify_user(e.to_string().into()),
852+ }
853+ cx.notify();
854+ }
855+
856+ /// Plays them fast instead of cutting them, closing the room each one no
857+ /// longer needs. One undo press like the cut, and the same scope; the
858+ /// refusals (a clip lapping over a silence, a scope that would split a
859+ /// take) come back in the engine's own words and name the lane and frame,
860+ /// and the card stays up so the numbers that produced it are still on
861+ /// screen.
862+ pub(crate) fn speed_silences(&mut self, cx: &mut Context<Self>) {
863+ let Some((regions, lanes)) = self.previewed() else {
864+ cx.notify();
865+ return;
866+ };
867+ let (count, rate) = (regions.len(), self.silence_factor);
868+ let reach = self.silence_reach(&lanes);
869+ let Some(session) = self.session.as_mut() else {
870+ cx.notify();
871+ return;
872+ };
873+ match session.speed_regions(&regions, rate, &lanes) {
874+ Ok(()) => {
875+ self.close_silence();
876+ // Splitting each silence out and closing the room it no longer
877+ // needs moves indexes exactly as the cut does: the selection
878+ // goes with them.
879+ self.selected = None;
880+ self.reset_after_reseek();
881+ self.notify_user(
882+ format!(
883+ "{count} SILENCES AT {rate} {reach} — {} takes it back",
884+ self.keymap.display(ActionId::Undo)
885+ )
886+ .into(),
887+ );
888+ }
889+ Err(e) => self.notify_user(e.to_string().into()),
890+ }
891+ cx.notify();
892+ }
893+
894+ /// Whether a card owns the window. While one does the timeline under it is
895+ /// out of reach, so a right-click there opens no menu -- the same rule the
896+ /// key handler and the drop target already follow.
897+ /// Whether anything at all is drawn over the window -- a card, a menu or an
898+ /// open list. What the hover labels stand aside for ([`OVERLAID`]): a
899+ /// tooltip belongs to the surface the pointer is on, and while one of these
900+ /// is up that surface is behind it.
901+ pub(crate) fn overlaid(&self) -> bool {
902+ self.modal()
903+ || self.context_menu.is_some()
904+ || self.library_menu.is_some()
905+ || self.picker.is_some()
906+ }
907+
908+ pub(crate) fn modal(&self) -> bool {
909+ self.keys_open
910+ || self.export_open
911+ || self.eq_open.is_some()
912+ || self.color_open.is_some()
913+ || self.speed_open.is_some()
914+ || self.silence_open.is_some()
915+ || self.mix_open
916+ || self.exporting().is_some()
917+ }
918+
919+ /// The pointer's way out of whatever card is up: what every scrim's press
920+ /// calls, so `esc` is *a* way out and never the only one. One list, and the
921+ /// same one [`Player::modal`] reads -- a card that can be counted there but
922+ /// not closed here is a card a hand alone cannot shut, which is what
923+ /// `every_card_closes_without_the_keyboard` fails on.
924+ ///
925+ /// Every card at once because only one is ever up (`export_open`): closing
926+ /// "the" card and closing all of them are the same act.
927+ pub(crate) fn close_card(&mut self) {
928+ self.keys_open = false;
929+ self.keys_search.clear();
930+ self.rebinding = None;
931+ self.export_open = false;
932+ // The two things typed *into* the export card go with it: a field left
933+ // open would take the next keystroke for a card that is gone.
934+ self.mbps_edit = None;
935+ self.picker = None;
936+ self.eq_open = None;
937+ self.eq_dragging = false;
938+ self.color_open = None;
939+ self.speed_open = None;
940+ // Marks and a running scan go with this one, which is why it is a call
941+ // and not an assignment ([`Player::close_silence`]).
942+ if self.silence_open.is_some() {
943+ self.close_silence();
944+ }
945+ self.mix_open = false;
946+ }
947+
948+ /// Opens the equalizer on the selected clip. Audio only, and it says so
949+ /// rather than opening a card of bands that would reach nothing: a video
950+ /// clip carries no sound of its own here (the sound is the audio lane's),
951+ /// and the model would take the setting without anything ever playing it.
952+ pub(crate) fn open_eq(&mut self, cx: &mut Context<Self>) {
953+ if self.exporting().is_some() {
954+ return;
955+ }
956+ let refusal = match (self.selected, &self.session) {
957+ (_, None) => Some("NO TIMELINE — open a file first".to_string()),
958+ (None, _) => Some(format!(
959+ "NOTHING SELECTED — click an audio clip or press {}, then ask again",
960+ self.keymap.display(ActionId::Select)
961+ )),
962+ (Some((lane, _)), _) if lane.kind != LaneKind::Audio => Some(
963+ "NOT AN AUDIO CLIP — the equalizer works on the sound, so pick a clip in an audio lane".to_string(),
964+ ),
965+ _ => None,
966+ };
967+ if let Some(refusal) = refusal {
968+ self.notify_user(refusal.into());
969+ cx.notify();
970+ return;
971+ }
972+ let (lane, idx) = self.selected.expect("checked above");
973+ let session = self.session.as_ref().expect("checked above");
974+ // What the clip already plays through, or the flat default -- so the
975+ // card opens on the curve that is in force and a reopen shows the last
976+ // drag rather than a fresh set of zeroes.
977+ self.eq_params = session
978+ .eq_of(lane, idx)
979+ .cloned()
980+ .unwrap_or_else(EqParams::default_layout);
981+ self.eq_band = 0;
982+ self.eq_dragging = false;
983+ self.eq_open = Some((lane, idx));
984+ // One card at a time, the rule the other two already follow.
985+ self.keys_open = false;
986+ self.export_open = false;
987+ self.context_menu = None;
988+ cx.notify();
989+ }
990+
991+ /// Writes what the card is showing at its clip: one undo step, one entry in
992+ /// the append-only equalizer table, so this is called once per *gesture* --
993+ /// the end of a drag, a keystroke -- and never per pointer sample.
994+ ///
995+ /// A curve that moves nothing is stored as *no* equalizer at all, which is
996+ /// what keeps a clip nobody has touched on the identity path through
997+ /// playback and export (`engine::eq::EqParams::is_identity`).
998+ pub(crate) fn commit_eq(&mut self, cx: &mut Context<Self>) {
999+ let Some((lane, idx)) = self.eq_open else {
1000+ return;
1001+ };
1002+ let params = (!self.eq_params.is_identity()).then(|| self.eq_params.clone());
1003+ if let Some(session) = &mut self.session {
1004+ session.set_eq(lane, idx, params);
1005+ }
1006+ // `set_eq` reseeks inside the engine -- that is what makes the change
1007+ // audible at once -- and a reseek is what these flags are about.
1008+ self.reset_after_reseek();
1009+ cx.notify();
1010+ }
1011+
1012+ /// Changes the picked band in place and says whether anything moved. Every
1013+ /// edit of a band goes through here -- the drag, each key, each stepper
1014+ /// button -- so the card has exactly one place that clamps a band into what
1015+ /// the graph can draw, and no caller has to remember the limits.
1016+ pub(crate) fn set_band(&mut self, change: impl FnOnce(&mut Band)) -> bool {
1017+ let Some(band) = self.eq_params.bands.get_mut(self.eq_band) else {
1018+ return false;
1019+ };
1020+ let was = *band;
1021+ change(band);
1022+ band.freq_hz = band.freq_hz.clamp(EQ_FREQ_LOW, EQ_FREQ_HIGH);
1023+ band.gain_db = band.gain_db.clamp(-EQ_GAIN_LIMIT, EQ_GAIN_LIMIT);
1024+ band.q = band.q.clamp(EQ_Q_LOW, EQ_Q_HIGH);
1025+ *band != was
1026+ }
1027+
1028+ /// The keyboard's and the buttons' version of a drag: one step on the picked
1029+ /// band, committed straight away -- neither has a release to wait for.
1030+ pub(crate) fn nudge_band(&mut self, change: impl FnOnce(&mut Band), cx: &mut Context<Self>) {
1031+ if self.set_band(change) {
1032+ self.commit_eq(cx);
1033+ }
1034+ }
1035+
1036+ /// Where the pointer sits in the graph, as the picked band's frequency and
1037+ /// gain: across is the frequency axis and down is the gain one, so the
1038+ /// handle follows the hand both ways rather than sliding up a rail. Called
1039+ /// on every pointer sample, so the curve bends under it; the write is the
1040+ /// release's ([`commit_eq`](Player::commit_eq)).
1041+ pub(crate) fn drag_band(&mut self, at: Point<Pixels>, cx: &mut Context<Self>) {
1042+ let bounds = self.eq_graph.get();
1043+ let gain = (0.5 - frac_down(at.y, bounds)) * 2. * EQ_GAIN_LIMIT;
1044+ let freq = eq_freq(frac_along(at.x, bounds));
1045+ if self.set_band(|b| {
1046+ b.gain_db = gain;
1047+ b.freq_hz = freq;
1048+ }) {
1049+ cx.notify();
1050+ }
1051+ }
1052+
1053+ /// A band added beside the picked one, at the frequency with the most room
1054+ /// around it ([`inserted_band`]), and picked so the next keystroke moves the
1055+ /// band that was just made. Refused rather than silently ignored at the cap.
1056+ pub(crate) fn add_band(&mut self, cx: &mut Context<Self>) {
1057+ if self.eq_params.bands.len() >= EQ_BANDS_MAX {
1058+ self.notify_user(
1059+ format!(
1060+ "EQUALIZER FULL — {EQ_BANDS_MAX} bands is all this card holds; move one instead"
1061+ )
1062+ .into(),
1063+ );
1064+ cx.notify();
1065+ return;
1066+ }
1067+ let band = inserted_band(&self.eq_params.bands, self.eq_band);
1068+ self.eq_band = (self.eq_band + 1).min(self.eq_params.bands.len());
1069+ self.eq_params.bands.insert(self.eq_band, band);
1070+ self.commit_eq(cx);
1071+ }
1072+
1073+ /// Takes the picked band out. The last one stays: an equalizer of no bands
1074+ /// is a card with nothing to edit, and flattening is what "off" means here.
1075+ pub(crate) fn remove_band(&mut self, cx: &mut Context<Self>) {
1076+ if self.eq_params.bands.len() <= 1 {
1077+ self.notify_user("LAST BAND — flatten it instead (r), or close the card".into());
1078+ cx.notify();
1079+ return;
1080+ }
1081+ self.eq_params.bands.remove(self.eq_band);
1082+ self.eq_band = self.eq_band.min(self.eq_params.bands.len() - 1);
1083+ self.commit_eq(cx);
1084+ }
1085+
1086+ /// Which band a press on the graph grabs: the nearest one along the
1087+ /// frequency axis, so the whole box is the handle rather than a 10 px dot
1088+ /// -- and a press that misses every dot still moves the band it is under.
1089+ pub(crate) fn nearest_band(&self, x: Pixels) -> usize {
1090+ let at = frac_along(x, self.eq_graph.get());
1091+ self.eq_params
1092+ .bands
1093+ .iter()
1094+ .enumerate()
1095+ .min_by(|(_, a), (_, b)| {
1096+ (eq_x(a.freq_hz) - at)
1097+ .abs()
1098+ .total_cmp(&(eq_x(b.freq_hz) - at).abs())
1099+ })
1100+ .map_or(0, |(i, _)| i)
1101+ }
1102+}
crates/app/src/player/export.rsadded+551 -0
@@ -0,0 +1,551 @@
1+//! What is cached about the media and the machine, and the export the
2+//! two of them decide.
3+
4+use crate::*;
5+
6+impl Player {
7+ /// Starts a peak decode -- and a stream probe -- for every source that has
8+ /// arrived since the last
9+ /// repaint. One call from the render rather than three at the doors,
10+ /// because argv, an import and a project load are all doors and only this
11+ /// one is guaranteed to run after each of them.
12+ ///
13+ /// The decode itself runs on a background thread, like the file chooser:
14+ /// whole-file audio decode is ~1 s for a half-hour source, and on the render
15+ /// path that is the window not painting for a second. The lane draws a bed
16+ /// meanwhile and the repaint comes with the peaks. The entry is written
17+ /// *before* the spawn, so the sixty repaints that happen while a decode runs
18+ /// start no further ones.
19+ pub(crate) fn cache_media(&mut self, cx: &mut Context<Self>) {
20+ let Some(session) = &self.session else {
21+ return;
22+ };
23+ // How big each still is, for the row that has to say so. Inline, unlike
24+ // the two below: an image header is a few bytes off the front of the
25+ // file, where a sample table is a parse and a decode is a second.
26+ for path in unseen_paths(session.sources(), &self.sizes) {
27+ let size = engine::is_image(&path)
28+ .then(|| engine::image_size(&path).ok())
29+ .flatten();
30+ self.sizes.insert(path, size);
31+ }
32+ // Which audio streams each file has, for the library's rows. Header
33+ // only, but a big file's sample tables are not free to parse, so it
34+ // goes off the render thread like the peaks do.
35+ for path in unseen_paths(session.sources(), &self.streams) {
36+ self.streams.insert(path.clone(), Vec::new());
37+ let probed = cx.background_executor().spawn({
38+ let path = path.clone();
39+ async move { engine::AudioSession::probe_streams(&path).unwrap_or_default() }
40+ });
41+ cx.spawn(async move |this, cx| {
42+ let probed = probed.await;
43+ this.update(cx, |this, cx| {
44+ this.streams.insert(path, probed);
45+ cx.notify();
46+ })
47+ .ok();
48+ })
49+ .detach();
50+ }
51+ // What each file is coded at, for the card that says so. Header and
52+ // sample table only, but a Matroska indexes no samples and its open
53+ // walks every cluster header -- 6.7 s on a 12.9 GB film -- so this of
54+ // all of them cannot be on the render thread.
55+ for path in unseen_paths(session.sources(), &self.bitrates) {
56+ self.bitrates.insert(path.clone(), None);
57+ let probed = cx.background_executor().spawn({
58+ let path = path.clone();
59+ async move { engine::probe_bitrate(&path) }
60+ });
61+ cx.spawn(async move |this, cx| {
62+ let probed = probed.await;
63+ this.update(cx, |this, cx| {
64+ this.bitrates.insert(path, Some(probed));
65+ cx.notify();
66+ })
67+ .ok();
68+ })
69+ .detach();
70+ }
71+ // Where this file's own groups of pictures begin, for the cut that
72+ // wants to land on one ([`Player::sync_frames`]). The heaviest probe
73+ // here -- a Matroska's whole cluster walk, seconds on a film -- and the
74+ // one nothing waits for: until it answers, the snap is the clip-edge
75+ // snap it always was.
76+ for path in unseen_paths(session.sources(), &self.syncs) {
77+ self.syncs.insert(path.clone(), Vec::new());
78+ let probed = cx.background_executor().spawn({
79+ let path = path.clone();
80+ async move { engine::demux::sync_points(&path) }
81+ });
82+ cx.spawn(async move |this, cx| {
83+ let probed = probed.await;
84+ this.update(cx, |this, cx| {
85+ this.syncs.insert(path, probed);
86+ cx.notify();
87+ })
88+ .ok();
89+ })
90+ .detach();
91+ }
92+ // Which decoder each file will run on, for the row that says so before
93+ // a frame of it plays. Off the render thread like the streams above: a
94+ // stream the plugin takes costs one VA-API init (~90 ms) to answer.
95+ for path in unseen_paths(session.sources(), &self.decoders) {
96+ self.decoders.insert(path.clone(), None);
97+ let probed = cx.background_executor().spawn({
98+ let path = path.clone();
99+ // A song and a source no decoder here takes are both `None`:
100+ // the row says nothing about them rather than guessing, and
101+ // import refused the second at the door anyway.
102+ async move { engine::decode::probe(&path).ok() }
103+ });
104+ cx.spawn(async move |this, cx| {
105+ let probed = probed.await;
106+ this.update(cx, |this, cx| {
107+ this.decoders.insert(path, probed);
108+ cx.notify();
109+ })
110+ .ok();
111+ })
112+ .detach();
113+ }
114+ for key in unseen_sources(session.sources(), &self.waves) {
115+ self.waves.insert(key.clone(), Wave::Loading);
116+ let decoded = cx.background_executor().spawn({
117+ let (path, stream) = key.clone();
118+ async move {
119+ engine::waveform::peaks(&path, stream, WAVE_BPS)
120+ .map(|peaks| peaks.map(|peaks| Arc::new(normalise(peaks))))
121+ .inspect_err(|e| eprintln!("waveform: {}: {e}", path.display()))
122+ }
123+ });
124+ cx.spawn(async move |this, cx| {
125+ let decoded = decoded.await;
126+ this.update(cx, |this, cx| {
127+ this.waves.insert(
128+ key,
129+ match decoded {
130+ Ok(Some(peaks)) => Wave::Peaks(peaks),
131+ // No audio track: an answer, and not worth asking
132+ // about again.
133+ Ok(None) => Wave::Silent,
134+ // A file whose sound we could not read is not a
135+ // silent one, and a lane that drew it as silent is
136+ // how a broken decode passes for a design choice.
137+ Err(_) => Wave::Failed,
138+ },
139+ );
140+ cx.notify();
141+ })
142+ .ok();
143+ })
144+ .detach();
145+ }
146+ }
147+
148+ /// Probes what an export would open, once per (settings, resolution, cuts)
149+ /// and only while the export card is up -- it opens the very VA-API encoder
150+ /// the export would and asks [`engine::export::planned_seats`] the very
151+ /// question the export asks itself, which is what makes the card's line a
152+ /// measurement instead of a promise, and also what makes it too slow for
153+ /// the render thread. Written before the spawn, like the probes above, so
154+ /// the repaints during it start no second one.
155+ ///
156+ /// The cuts are in the key because they are in the answer: moving one onto
157+ /// a sync point is exactly what turns "SW encode" into "copy", and a card
158+ /// that kept the old line would be lying about the file it is about to
159+ /// write.
160+ pub(crate) fn cache_export_seat(&mut self, cx: &mut Context<Self>) {
161+ let Some(session) = &self.session else {
162+ return;
163+ };
164+ let settings =
165+ export_settings(self.quality, self.custom_mbps, self.format, self.audio_kbps);
166+ if !self.export_open {
167+ return;
168+ }
169+ // A format with no picture has no seat to probe -- and the *last*
170+ // format's is not its answer: cleared rather than left standing, or
171+ // picking MP3 after AV1 would read "SW encode (rav1e) · MP3 · SW
172+ // (rusty_mp3)", which names an encoder that will not run.
173+ if !settings.format.has_video() {
174+ self.export_seat = None;
175+ return;
176+ }
177+ // The timeline an export would be started with, owned so the probe can
178+ // run on a worker -- and the clips beside it, which are what tells this
179+ // that the question has changed.
180+ let (project, meta) = session.export_snapshot();
181+ let clips: Vec<Clip> = session
182+ .lanes()
183+ .into_iter()
184+ .flat_map(|lane| session.lane_clips(lane).to_vec())
185+ .collect();
186+ // Cloned rather than copied: the settings carry the picked subtitle
187+ // rows, which is a `Vec` ([`engine::export::ExportSettings`]).
188+ let key = (settings.clone(), (meta.width, meta.height), clips);
189+ if self
190+ .export_seat
191+ .as_ref()
192+ .is_some_and(|(asked, size, cuts, _)| (asked, size, cuts) == (&key.0, &key.1, &key.2))
193+ {
194+ return;
195+ }
196+ self.export_seat = Some((key.0.clone(), key.1, key.2.clone(), None));
197+ let probed = cx.background_executor().spawn(async move {
198+ engine::export::planned_seats(&project, &meta, &settings)
199+ });
200+ cx.spawn(async move |this, cx| {
201+ let probed = probed.await;
202+ this.update(cx, |this, cx| {
203+ // Only if the card is still asking the same question: a format
204+ // changed while the plugin opened has a probe of its own.
205+ if let Some(seat) = this.export_seat.as_mut().filter(|(asked, size, cuts, _)| {
206+ (asked, size, cuts) == (&key.0, &key.1, &key.2)
207+ }) {
208+ seat.3 = Some(probed);
209+ }
210+ cx.notify();
211+ })
212+ .ok();
213+ })
214+ .detach();
215+ }
216+
217+ /// Asks the plugin what this machine's GPU can do, once, the first time the
218+ /// export card is up to show it. Off the render thread for `cache_export_seat`'s
219+ /// reason: the plugin initialises VA-API to answer, and a driver that is
220+ /// slow to load must not be a frame the user waits for.
221+ pub(crate) fn cache_hw_caps(&mut self, cx: &mut Context<Self>) {
222+ if !self.export_open || self.hw_caps.is_some() {
223+ return;
224+ }
225+ // Written before the spawn, exactly as the probes above are, so the
226+ // repaints during it start no second one.
227+ self.hw_caps = Some("asking the driver…".into());
228+ let asked = cx
229+ .background_executor()
230+ .spawn(async move { engine::caps::hardware() });
231+ cx.spawn(async move |this, cx| {
232+ let line = asked.await;
233+ this.update(cx, |this, cx| {
234+ this.hw_caps = Some(line.into());
235+ cx.notify();
236+ })
237+ .ok();
238+ })
239+ .detach();
240+ }
241+
242+ /// The export that owns the UI, if any. A cancelled one does not: it has
243+ /// its own copy of the edit list and owes only its own cleanup.
244+ pub(crate) fn exporting(&self) -> Option<&ExportHandle> {
245+ self.export.as_ref().filter(|_| !self.cancelling)
246+ }
247+
248+ /// What the export action does now: opens the card, which is where the
249+ /// quality, the destination and the decision to write at all are. Nothing
250+ /// is encoded until the button in it is pressed.
251+ pub(crate) fn open_export(&mut self, cx: &mut Context<Self>) {
252+ if self.export.is_some() {
253+ return;
254+ }
255+ // Nothing to write out, and a refusal rather than a card about it: the
256+ // window is empty and the export path is not even chosen yet.
257+ if self.session.is_none() {
258+ self.notify_user("NOTHING TO EXPORT — open a file first".into());
259+ cx.notify();
260+ return;
261+ }
262+ self.export_open = true;
263+ // One card at a time, and a waiting row must not outlive the card it
264+ // was waiting in. Nor may a half-typed number: the card opens on the
265+ // bitrate it will write, never on digits left behind by a closed one.
266+ self.keys_open = false;
267+ self.rebinding = None;
268+ self.mbps_edit = None;
269+ cx.notify();
270+ }
271+
272+ /// A format row was clicked. The destination follows it at once -- a WAV
273+ /// written to a path ending in `.mp4` is a file every player will lie
274+ /// about -- keeping whatever stem the save dialog last left there.
275+ pub(crate) fn set_format(&mut self, format: Format) {
276+ // The one door both the row and its initial go through, so a format the
277+ // card greys out cannot be picked by keyboard either.
278+ if let Some(why) = self
279+ .session
280+ .as_ref()
281+ .and_then(|session| format_refusal(session, format))
282+ {
283+ self.notify_user(format!("NOT {} — {why}", format_label(format)).into());
284+ return;
285+ }
286+ self.format = format;
287+ self.export_path = retarget(&self.export_path, format);
288+ }
289+
290+ /// The container row: the same codec in the other box, which retargets the
291+ /// destination exactly as picking a codec does -- and does nothing at all
292+ /// for a codec with only one box, so the stroke cannot invent a choice the
293+ /// card is not offering.
294+ pub(crate) fn cycle_container(&mut self) {
295+ self.set_format(next_container(self.format));
296+ }
297+
298+ /// The quality rows by keyboard, wrapping. Refused by name where the format
299+ /// has no bitrate to pick: a key that silently does nothing is the card
300+ /// looking broken.
301+ pub(crate) fn cycle_quality(&mut self) {
302+ if let Some(why) = bitrate_refusal(self.format) {
303+ self.notify_user(why.into());
304+ return;
305+ }
306+ let at = Quality::ALL
307+ .iter()
308+ .position(|&q| q == self.quality)
309+ .unwrap_or(0);
310+ self.quality = Quality::ALL[(at + 1) % Quality::ALL.len()];
311+ }
312+
313+ /// The sound's rate by keyboard, wrapping through the offered ones -- the
314+ /// picture's quality row for the other half of the file. Refused by name
315+ /// where this timeline in this format has no rate to pick, exactly as
316+ /// [`Player::cycle_quality`] is: a key that silently does nothing is the
317+ /// card looking broken.
318+ pub(crate) fn cycle_audio_kbps(&mut self) {
319+ if let Some(why) = self.audio_rate_refusal() {
320+ self.notify_user(why.into());
321+ return;
322+ }
323+ self.audio_kbps = next_audio_kbps(self.audio_kbps);
324+ }
325+
326+ /// Why the sound row is not a choice right now, the engine answering about
327+ /// the very project it would export. No session is the same answer as no
328+ /// sound: there is nothing to write either way.
329+ pub(crate) fn audio_rate_refusal(&self) -> Option<&'static str> {
330+ match &self.session {
331+ Some(session) => session.audio_rate_refusal(self.format),
332+ None => Some("no sound to write"),
333+ }
334+ }
335+
336+ /// The custom bitrate by pointer: the typed digits were the only control in
337+ /// this card a mouse could not reach. Clamped to the range the row states
338+ /// (the engine's own 1..50 Mbps), and picking the row is part of the step --
339+ /// a stepper that moves a number nobody is using would move nothing.
340+ pub(crate) fn nudge_mbps(&mut self, step: i32) {
341+ self.custom_mbps =
342+ (self.custom_mbps as i32 + step).clamp(MBPS_MIN as i32, MBPS_MAX as i32) as u32;
343+ self.quality = Quality::Custom;
344+ }
345+
346+ /// The same number under the wheel, one step a notch, up for more: fifty
347+ /// presses of a stepper is not a way to reach the top of this range, and the
348+ /// wheel is what this editor already moves a value with (the timeline's
349+ /// zoom and scroll are the same gesture). Hold-to-run stays the keyboard's,
350+ /// as it is on every other card here -- a button that repeats while held is
351+ /// not a thing this program has.
352+ ///
353+ /// It moves the *field* while one is open, exactly as ↑↓ do, so the two
354+ /// ways in never disagree about which number is being changed.
355+ pub(crate) fn wheel_mbps(&mut self, event: &ScrollWheelEvent) {
356+ let by = wheel_delta(event);
357+ if by == 0. {
358+ return;
359+ }
360+ let by = by.signum() as i32;
361+ match &mut self.mbps_edit {
362+ Some(edit) => edit.step(by),
363+ None => self.nudge_mbps(by),
364+ }
365+ }
366+
367+ /// Opens the custom bitrate's field on the number the row is carrying, and
368+ /// picks the row while it is at it: a field typed into is the row being
369+ /// chosen, and a number nobody is using would be a number typed at nothing.
370+ /// Nothing is committed here -- until enter, the card still exports at the
371+ /// bitrate it had.
372+ pub(crate) fn edit_mbps(&mut self) {
373+ self.quality = Quality::Custom;
374+ self.mbps_edit = Some(NumberEdit::new(self.custom_mbps));
375+ }
376+
377+ /// The card's Destination row: the desktop's save dialog, on a background
378+ /// thread like the import chooser -- the user may sit in it and the window
379+ /// behind must not freeze. No chooser at all leaves the default path, which
380+ /// is what the refusal says.
381+ pub(crate) fn pick_destination(&mut self, cx: &mut Context<Self>) {
382+ let default = self.export_path.clone();
383+ let picked = cx
384+ .background_executor()
385+ .spawn(async move { pick_save(&default) });
386+ cx.spawn(async move |this, cx| {
387+ let picked = picked.await;
388+ this.update(cx, |this, cx| {
389+ // The dialog outlives the card: an export started meanwhile
390+ // took the old path and its notice must name what it wrote.
391+ if this.export.is_some() {
392+ return;
393+ }
394+ match picked {
395+ // The stem is the user's, the extension is the format's: a
396+ // FLAC named `.mp4` is a file every player lies about.
397+ Ok(Some(path)) => this.export_path = retarget(&path, this.format),
398+ // Cancelled: the default stands, as it did before.
399+ Ok(None) => {}
400+ Err(text) => {
401+ eprintln!("{text}");
402+ this.notify_user(text.into());
403+ }
404+ }
405+ cx.notify();
406+ })
407+ .ok();
408+ })
409+ .detach();
410+ }
411+
412+ /// The subtitle tracks an export of this timeline carries: every one with a
413+ /// cue left in the exported range ([`PlaybackSession::timeline_cues`], the
414+ /// very map the file is written from), in the library's own order.
415+ ///
416+ /// Worked out from the cues each time rather than kept as a pick, which is
417+ /// what makes it impossible to desync: a row added or taken off shifts every
418+ /// index after it, and a stored list would then name tracks nobody chose.
419+ /// `Player::sub_track` stays what it always was -- which track the *overlay*
420+ /// draws -- and has no say here.
421+ ///
422+ /// The honest input and not the final answer: the engine filters it again
423+ /// per track (a track that could not be read, a picture one) and says so in
424+ /// the card's own words ([`engine::export::planned_subtitles`]).
425+ pub(crate) fn export_subs(&self) -> Vec<usize> {
426+ let Some(session) = self.session.as_ref() else {
427+ return Vec::new();
428+ };
429+ (0..session.subtitles().len())
430+ .filter(|&i| !session.timeline_cues(i).is_empty())
431+ .collect()
432+ }
433+
434+ /// That list in the card's words ([`subtitle_plan`]): what travels, and the
435+ /// reason beside every track that does not -- including the ones
436+ /// [`Self::export_subs`] filtered out before the engine ever saw them.
437+ pub(crate) fn subtitle_line(&self) -> String {
438+ let Some(session) = self.session.as_ref() else {
439+ return "none".to_string();
440+ };
441+ let picks = self.export_subs();
442+ let plan = session.planned_subtitles(self.format, picks.iter().copied());
443+ match self.format.has_video() {
444+ true => subtitle_plan(plan, session.subtitles(), &picks),
445+ // A format that is the sound alone has nowhere to put any of them
446+ // and the engine says that once, about the file. Naming the cues of
447+ // each track under it answers a question the format already closed.
448+ false => plan,
449+ }
450+ }
451+
452+ /// Writes the edit list out, at the settings the card was left at. Playback
453+ /// stops first: the exporter opens its own decoder -- and, on the hardware
454+ /// path, an encoder -- so a running player would only compete with it for
455+ /// the GPU. A cancelled export still winding down holds this off for the
456+ /// frame it takes to notice, which is what keeps its `remove_file` off the
457+ /// new output.
458+ pub(crate) fn start_export(&mut self, cx: &mut Context<Self>) {
459+ if self.export.is_some() {
460+ return;
461+ }
462+ let mut settings =
463+ export_settings(self.quality, self.custom_mbps, self.format, self.audio_kbps);
464+ // Whatever is on the timeline travels -- every track with a cue in the
465+ // exported range, not the one row the overlay happens to be drawing.
466+ // Set here rather than inside `export_settings`, which the card also
467+ // calls for the *estimate* and which nothing else needs a subtitle for.
468+ settings.subtitles = self.export_subs();
469+ let Some(session) = &mut self.session else {
470+ self.notify_user("NOTHING TO EXPORT — open a file first".into());
471+ cx.notify();
472+ return;
473+ };
474+ // An emptied timeline is a timeline; it is simply not a file. Refused by
475+ // name here rather than written as a project of no frames -- and the
476+ // engine refuses it again on the worker (`export::start`), so a caller
477+ // that is not this button cannot get past it either. Two fences on
478+ // purpose: this one is the one with a keystroke to blame.
479+ if session.is_empty() {
480+ self.notify_user("NOTHING TO EXPORT — the timeline is empty".into());
481+ cx.notify();
482+ return;
483+ }
484+ // The format row can be refused *after* it was picked -- mp4 is the
485+ // default and an audio-only timeline (or a second audio lane) is one
486+ // edit away -- so the button asks again rather than starting a worker
487+ // that will only settle with the same refusal minutes later.
488+ if let Some(why) = format_refusal(session, self.format) {
489+ self.notify_user(format!("NOT EXPORTED — {why}").into());
490+ cx.notify();
491+ return;
492+ }
493+ session.pause();
494+ self.export = Some(session.export_to_with(&self.export_path, &settings));
495+ // The clock starts with the worker, not with the first repaint that
496+ // happens to notice it.
497+ self.export_started = Some(Instant::now());
498+ self.export_marks.clear();
499+ // The card has been answered; the progress line takes the panel from
500+ // here, and it is the running export's escape that matters now.
501+ self.export_open = false;
502+ cx.notify();
503+ }
504+
505+ /// Gives the editor back at once and leaves the worker to stop at its next
506+ /// frame and delete what it has written.
507+ pub(crate) fn cancel_export(&mut self) {
508+ if let Some(export) = &self.export {
509+ export.cancel();
510+ self.cancelling = true;
511+ }
512+ }
513+
514+ /// Takes the export's verdict once it has one. The only place the app
515+ /// touches the handle's completion side.
516+ pub(crate) fn poll_export(&mut self) {
517+ // Sampled here rather than while drawing: a repaint stays a repaint,
518+ // and this runs once per repaint either way.
519+ if let (Some(progress), Some(started)) = (
520+ self.exporting().map(ExportHandle::progress),
521+ self.export_started,
522+ ) {
523+ note_progress(
524+ &mut self.export_marks,
525+ started.elapsed().as_secs_f32(),
526+ progress,
527+ );
528+ }
529+ let Some(result) = self.export.as_ref().and_then(ExportHandle::result) else {
530+ return;
531+ };
532+ self.export = None;
533+ self.export_started = None;
534+ // A cancellation is reported as an error, and the one who asked for it
535+ // has had the editor back since the keystroke. Nothing to say.
536+ if std::mem::take(&mut self.cancelling) {
537+ return;
538+ }
539+ let text = match result {
540+ Ok(()) => {
541+ // Written and still where it was written: the bar carries it
542+ // until some other notice takes the bar.
543+ self.exported = Some(self.export_path.clone());
544+ format!("{EXPORT_DONE}{}", file_name(&self.export_path))
545+ }
546+ Err(e) => format!("EXPORT FAILED: {e}"),
547+ };
548+ eprintln!("{text}");
549+ self.notify_user(text.into());
550+ }
551+}
crates/app/src/player/library.rsadded+929 -0
@@ -0,0 +1,929 @@
1+//! What comes in and what goes out: the sources, the imports, the
2+//! subtitles, the project file and the lanes.
3+
4+use crate::*;
5+
6+impl Player {
7+ /// The one way a library row reaches the timeline: the Add button and a row
8+ /// dragged onto a lane both come here, so there is a single answer to what
9+ /// "add this source" does. The whole source goes in as one grouped take at
10+ /// `at` -- the frame the pointer let it go on, or the playhead for the
11+ /// button, which names no place. It is the same insert a paste makes, so
12+ /// everything after it moves along rather than being painted over. Reseeks
13+ /// like every other edit, and drops the timeline's selection with it: the
14+ /// insert has just moved the indices it pointed at.
15+ pub(crate) fn insert_source(
16+ &mut self,
17+ path: &Path,
18+ stream: usize,
19+ onto: Option<Lane>,
20+ at: Option<u32>,
21+ cx: &mut Context<Self>,
22+ ) {
23+ if self.exporting().is_some() {
24+ return;
25+ }
26+ // The lane the pointer named cannot hold this kind of file: refused by
27+ // name, in the same words the ghost was tinted by on the way down
28+ // ([`lane_refuses`]). The Add button names no lane and so is never
29+ // refused here -- where a file goes when nobody says is the engine's
30+ // choice, in `place_stream_at`, not one made twice here.
31+ if let Some(why) = onto.and_then(|lane| lane_refuses(path, lane)) {
32+ self.notify_user(why.into());
33+ cx.notify();
34+ return;
35+ }
36+ // The engine's own length for the file, noted when the import took it
37+ // in: a row that has never been on a lane is placeable at its full
38+ // length, which is the whole point of an import that only fills the
39+ // library.
40+ let fps = self.fps;
41+ let placed = match &mut self.session {
42+ // Seconds, because that is what the engine's own door takes: the
43+ // frame the pointer named goes back through the same rate every box
44+ // on the bed is drawn at, so it lands on the frame it was let go on
45+ // rather than a neighbouring one.
46+ Some(session) => {
47+ let at = at.map_or_else(|| session.now(), |frame| f64::from(frame) / fps);
48+ session.place_stream_at(at, path, stream, onto)
49+ }
50+ None => Ok(false),
51+ };
52+ match placed {
53+ Ok(true) => {
54+ self.selected = None;
55+ self.reset_after_reseek();
56+ }
57+ // The engine's own words: a stream that cannot join this timeline
58+ // says which property disagrees, exactly as a refused import does.
59+ Err(e) => self.notify_user(format!("NOTHING ADDED — {e}").into()),
60+ Ok(false) => {
61+ self.notify_user("NOTHING ADDED — that file could not be placed here".into())
62+ }
63+ }
64+ cx.notify();
65+ }
66+
67+ /// Takes a library row's file out of the list, which is the one thing a row
68+ /// can lose. Refused in the engine's own words while clips still play from
69+ /// it -- and those words name the lanes holding them, so the refusal says
70+ /// what to delete first. The list itself is the report that it worked: the
71+ /// row is gone from it.
72+ pub(crate) fn remove_source(&mut self, path: &Path, stream: usize, cx: &mut Context<Self>) {
73+ if self.exporting().is_some() {
74+ return;
75+ }
76+ let removed = self
77+ .session
78+ .as_mut()
79+ .map(|session| session.remove_source(path, stream));
80+ let text = match removed {
81+ Some(Ok(idx)) => {
82+ // The picked row may be the one that just went, and the engine
83+ // reseeks, so this owes the flag reset like every other edit.
84+ if self.selected_asset.as_ref() == Some(&(path.to_path_buf(), stream)) {
85+ self.selected_asset = None;
86+ }
87+ // A copied clip names its source by *index*, and every index
88+ // past the one that went has just moved down: without this the
89+ // next paste puts some other file on the timeline.
90+ self.clipboard = clipboard_after_remove(self.clipboard, idx);
91+ self.reset_after_reseek();
92+ // The last row leaves a session naming no file: nothing to
93+ // play, nothing to save and nothing to show, which is the empty
94+ // window the editor launches as. The next import scaffolds a
95+ // fresh timeline from whatever file it is, at that file's own
96+ // rate -- which is why the session goes rather than lingering
97+ // on with the gone file's parameters.
98+ match self
99+ .session
100+ .as_ref()
101+ .is_some_and(|s| s.sources().is_empty())
102+ {
103+ true => {
104+ self.close_session();
105+ format!(
106+ "REMOVED {} — the library is empty; import a file to start again",
107+ file_name(path)
108+ )
109+ }
110+ // The undo stack goes with it (`Project::remove_source`):
111+ // said here, because a `z` that does nothing afterwards
112+ // would otherwise read as a bug.
113+ false => format!(
114+ "REMOVED {} — there is nothing left to undo",
115+ file_name(path)
116+ ),
117+ }
118+ }
119+ Some(Err(e)) => format!("NOT REMOVED — {e}"),
120+ None => "NO TIMELINE — open a file first".to_string(),
121+ };
122+ self.notify_user(text.into());
123+ cx.notify();
124+ }
125+
126+ /// Back to the window the editor launches as: no timeline, no library, no
127+ /// picture -- and the hint that says to open a file. What removing the last
128+ /// library row leaves, since a session whose library is empty has nothing
129+ /// left to be ([`Player::remove_source`]).
130+ ///
131+ /// Everything a *loaded project* resets goes here for its reasons (an index
132+ /// into a timeline that is gone names nothing), plus the three per-file
133+ /// caches: they are keyed by path, and the next file to arrive fills them
134+ /// again.
135+ pub(crate) fn close_session(&mut self) {
136+ self.session = None;
137+ // The picture goes with it, or the empty window would keep showing the
138+ // last frame of a timeline that no longer exists.
139+ //
140+ // corner-cut: its atlas tile is not released -- `window.drop_image` wants
141+ // a `&mut Window` this door has no other reason to take. One tile per
142+ // emptied library, against one per displayed frame in `pump`; the
143+ // upgrade path is threading the window through `act_on_row`.
144+ self.image = None;
145+ // The drawn cue with it, and its tile for the same reason as above.
146+ self.sub_image = None;
147+ self.clipboard = None;
148+ self.selected = None;
149+ self.selected_asset = None;
150+ // The subtitle rows go with the timeline they were on.
151+ self.sub_track = 0;
152+ self.context_menu = None;
153+ self.library_menu = None;
154+ self.eq_open = None;
155+ self.color_open = None;
156+ self.speed_open = None;
157+ self.close_silence();
158+ self.waves.clear();
159+ self.streams.clear();
160+ self.bitrates.clear();
161+ self.sizes.clear();
162+ self.syncs.clear();
163+ // Scanned off sources that are not in the library any more.
164+ self.silence_levels.clear();
165+ // Every gesture in flight, dropped for `reset_after_reseek`'s reason
166+ // (it drops the trim below): a drag holds a bar, a clip or a band of a
167+ // timeline that has just stopped existing.
168+ self.scrubbing = false;
169+ self.volume_dragging = false;
170+ self.eq_dragging = false;
171+ self.speed_dragging = false;
172+ self.color_dragging = false;
173+ self.pending_color = None;
174+ self.pending_speed = None;
175+ self.displayed = 0;
176+ self.dropped = 0;
177+ self.started = None;
178+ // The empty window's own: no name in the titlebar, nowhere chosen to
179+ // export or save to yet, and a rate that only keeps the timecode
180+ // reading in frames until a file brings its own (`main`).
181+ self.name = NO_FILE.into();
182+ self.export_path = PathBuf::new();
183+ self.project_path = PathBuf::new();
184+ self.fps = 30.;
185+ // No decoder to wait for a frame from: the hint is what shows. The
186+ // transport reads `Stopped` from the session being gone, so there is no
187+ // end-of-stream state left to clear here.
188+ self.reset_after_reseek();
189+ self.seek_since = None;
190+ }
191+
192+ /// The rate and layout the whole timeline's audio is, taken from the stream
193+ /// of the first source that could have one: what a library row has to match
194+ /// to be placeable. `None` until that file has been probed, and then nothing
195+ /// is greyed for it.
196+ ///
197+ /// The first source that is *not a still*, which is the rule the engine
198+ /// holds every import to (`playback::audio_source_of`) -- a picture at the
199+ /// head of the list (a removal moves indexes) has no stream to describe
200+ /// anything with.
201+ pub(crate) fn timeline_audio(&self) -> Option<(u32, u16)> {
202+ let first = self
203+ .session
204+ .as_ref()?
205+ .sources()
206+ .iter()
207+ .find(|s| !engine::is_image(&s.path))?;
208+ let info = self
209+ .streams
210+ .get(&first.path)?
211+ .iter()
212+ .find(|s| s.index == first.audio_stream)?;
213+ Some((info.sample_rate, info.channels))
214+ }
215+
216+ /// Queues a file for the library. Nothing is read here: the reading is
217+ /// [`read_ahead`] on a worker, and [`Player::take_import`] is what finally
218+ /// touches the timeline, one repaint later and with the pages warm. A drop
219+ /// is not a key press, so the export guard on the key handler does not
220+ /// cover it and this checks for itself.
221+ ///
222+ /// One file at a time, in arrival order: a drop can carry six and argv can
223+ /// name more, and six header walks racing over one disk finish no sooner
224+ /// than six in a row -- while the line above the panel has exactly one file
225+ /// to name.
226+ pub(crate) fn import(&mut self, path: &std::path::Path, cx: &mut Context<Self>) {
227+ if self.exporting().is_some() {
228+ return;
229+ }
230+ self.imports.push_back(path.to_path_buf());
231+ self.start_import(cx);
232+ }
233+
234+ /// Starts the worker for the next queued file, if no worker is running.
235+ /// Called again as each import lands, which is what drains the queue.
236+ pub(crate) fn start_import(&mut self, cx: &mut Context<Self>) {
237+ if self.importing.is_some() {
238+ return;
239+ }
240+ let Some(path) = self.imports.pop_front() else {
241+ return;
242+ };
243+ let stage = Arc::new(std::sync::atomic::AtomicU8::new(ImportStage::Header as u8));
244+ let cancelled = Arc::new(std::sync::atomic::AtomicBool::new(false));
245+ // The fork is made here, once, and carried to the landing: an import is
246+ // *probed* on the worker and registered from what came back, while the
247+ // file argv named -- and a file arriving at a window with no timeline to
248+ // import into -- is *opened* on the worker and handed over whole. None
249+ // of the three leaves the UI thread anything to read: a cold 24 GB
250+ // header walk is twenty seconds, and the window keeps painting through
251+ // all of them.
252+ let what = arrival(self.opening.as_deref(), &path);
253+ // The timeline the file will be checked against, taken here because the
254+ // worker cannot reach the session: two clones and no disk
255+ // ([`PlaybackSession::import_gate`]). `None` is a window with nothing to
256+ // import into, which is the fork that opens the file outright.
257+ let gate = self.session.as_ref().map(PlaybackSession::import_gate);
258+ let read = cx.background_executor().spawn({
259+ let (path, stage) = (path.clone(), Arc::clone(&stage));
260+ async move { open_ahead(what, &path, &stage, gate) }
261+ });
262+ let now = Instant::now();
263+ self.importing = Some(Import {
264+ path: path.clone(),
265+ started: now,
266+ stage,
267+ seen: ImportStage::Header,
268+ since: now,
269+ cancelled: Arc::clone(&cancelled),
270+ });
271+ cx.spawn(async move |this, cx| {
272+ let landed = read.await;
273+ this.update(cx, |this, cx| {
274+ this.importing = None;
275+ // Cancelled while it read: the window was given back at the
276+ // click and said so then, so what the worker carried is dropped
277+ // without a second word ([`Player::cancel_import`]).
278+ if cancelled.load(std::sync::atomic::Ordering::Relaxed) {
279+ return;
280+ }
281+ this.take_import(&path, landed, cx);
282+ // The next one is started by the repaint this notified, which
283+ // is also what starts the files argv named ([`poll_import`]).
284+ })
285+ .ok();
286+ })
287+ .detach();
288+ cx.notify();
289+ }
290+
291+ /// Keeps the import line's two clocks honest: the elapsed one runs from the
292+ /// worker, and the stall one from the last time the stage it is naming
293+ /// actually changed. Sampled here rather than while drawing, for
294+ /// [`Player::poll_export`]'s reason.
295+ ///
296+ /// ...and starts whatever is queued behind it, which is the one place the
297+ /// files argv named can begin: they are put in the queue before there is a
298+ /// context to spawn a worker from.
299+ pub(crate) fn poll_import(&mut self, cx: &mut Context<Self>) {
300+ match &mut self.importing {
301+ Some(import) => {
302+ import.poll();
303+ }
304+ None => self.start_import(cx),
305+ }
306+ }
307+
308+ /// The Cancel beside the import line: the window is given back at once and
309+ /// the file does not land. Everything queued behind it goes too -- a person
310+ /// who has stopped an import of six dropped files has stopped the six, and
311+ /// leaving five to start themselves would be the same wait under another
312+ /// name.
313+ ///
314+ /// The read in flight is *not* stopped, for the reason [`Import::cancelled`]
315+ /// gives, and the notice says as much rather than promising the disk went
316+ /// quiet.
317+ pub(crate) fn cancel_import(&mut self, cx: &mut Context<Self>) {
318+ let Some(import) = self.importing.take() else {
319+ return;
320+ };
321+ import
322+ .cancelled
323+ .store(true, std::sync::atomic::Ordering::Relaxed);
324+ let waiting = self.imports.len();
325+ self.imports.clear();
326+ let tail = match waiting {
327+ 0 => String::new(),
328+ n => format!(" — {n} more dropped from the queue"),
329+ };
330+ let text = format!(
331+ "IMPORT CANCELLED: {}{tail} — the read already running finishes unheeded",
332+ file_name(&import.path)
333+ );
334+ eprintln!("{text}");
335+ self.notify_user(text.into());
336+ cx.notify();
337+ }
338+
339+ /// Takes a read-ahead file into the library and nowhere else: the timeline
340+ /// is not touched, and the row is dragged onto a lane when it is wanted
341+ /// there. Nothing moves, so nothing reseeks; a refusal is shown as the
342+ /// engine worded it and changes nothing.
343+ ///
344+ /// The export guard again, and not for the caller's sake: an export can
345+ /// have started during the seconds the worker was reading, and a drop
346+ /// during an export has always been a silent no-op.
347+ pub(crate) fn take_import(&mut self, path: &std::path::Path, landed: Landed, cx: &mut Context<Self>) {
348+ if self.exporting().is_some() {
349+ return;
350+ }
351+ // The file argv named is the one file in the queue that is not an
352+ // import: it *is* the timeline, and the worker has already opened it.
353+ // All that is left here is to hang everything derived from it off the
354+ // window -- the clock, the title, where an export and a save go -- and
355+ // that is arithmetic, not a read.
356+ let (subs, probe) = match landed {
357+ Landed::Read(subs, probe) => (subs, probe),
358+ what => {
359+ // Only when *this* is the file argv named: a project dropped
360+ // while that one is still being read must not make it land as
361+ // an import.
362+ if self.opening.as_deref() == Some(path) {
363+ self.opening = None;
364+ }
365+ match what {
366+ Landed::Project(opened) => self.install_project(path, opened, cx),
367+ Landed::Media(opened, place) => {
368+ let text = self.install_media(path, opened, place);
369+ eprintln!("{text}");
370+ self.notify_user(text.into());
371+ cx.notify();
372+ }
373+ Landed::Read(..) => unreachable!("matched above"),
374+ }
375+ // The line a launch has always printed, now printed when the
376+ // file actually arrives: it is the mark that says the timeline
377+ // is up, as the window's own appearance is the other one.
378+ if let Some(meta) = self.session.as_ref().map(PlaybackSession::meta) {
379+ println!(
380+ "{}: {}x{} @ {:.2} fps, {} samples",
381+ path.display(),
382+ meta.width,
383+ meta.height,
384+ meta.frame_rate,
385+ meta.frame_count
386+ );
387+ }
388+ return;
389+ }
390+ };
391+ // An empty window has no library to add to yet: the file opens one, and
392+ // the timeline under it stays empty, because an import is an import
393+ // whether or not a session was already up. A file *named at launch* is
394+ // the other fork -- that one is an open, and it does become the
395+ // timeline (`main`).
396+ // A subtitle file is not a source and lands on no lane: it joins the
397+ // timeline's own list of them, which is what the library's subtitle
398+ // section shows and what the overlay draws. With no timeline open there
399+ // is nothing for the cues to be timed against, and it says so.
400+ if is_subtitle(path) {
401+ self.take_subtitles(path, subs, cx);
402+ return;
403+ }
404+ // The container was read on the worker and what came back is registered
405+ // here ([`engine::PlaybackSession::import_probed`]): no header walk, no
406+ // decoder open, no probe of the timeline's own first source -- the three
407+ // reads that used to be spent on this thread. A song and a still fork
408+ // before the demuxer and pay their own small read
409+ // ([`engine::PlaybackSession::import`]); a window whose timeline went
410+ // away while the worker read falls to the slow door below, which is the
411+ // one that can still open one.
412+ let registered = match (self.session.as_mut(), probe) {
413+ (Some(session), Some(Ok(probe))) => Some(session.import_probed(path, probe)),
414+ (Some(_), Some(Err(refused))) => Some(Err(refused)),
415+ (Some(session), None) => Some(session.import(path)),
416+ (None, _) => None,
417+ };
418+ let text = match registered {
419+ Some(Ok(_)) => {
420+ // The file's own subtitle tracks with it, exactly as an open
421+ // takes them: an import is the other door the same file arrives
422+ // through. The cues were read on the worker
423+ // ([`read_ahead`]); what happens here is the push.
424+ let tail = self
425+ .session
426+ .as_mut()
427+ .and_then(|session| subtitle_tail(session, subs))
428+ .unwrap_or_default();
429+ format!(
430+ "IMPORTED {} to the library — drag it onto a lane to place it{tail}",
431+ file_name(path)
432+ )
433+ }
434+ // Named, because two files can fail in one launch and the queue now
435+ // shows both: "No such file or directory" twice over, with nothing
436+ // saying which file, is two messages that answer nothing.
437+ Some(Err(e)) => format!("IMPORT FAILED: {} — {e}", file_name(path)),
438+ None => self.open_media(path, false, subs),
439+ };
440+ eprintln!("{text}");
441+ self.notify_user(text.into());
442+ cx.notify();
443+ }
444+
445+ /// Takes a file as the session an empty window is waiting for. Everything
446+ /// derived from the media -- the clock, the title, where an export and a
447+ /// save go -- is set here, exactly as a launch with a file argument sets
448+ /// it. Paused with its first frame showing, like every other way a timeline
449+ /// arrives.
450+ ///
451+ /// `place` is the difference between the two doors that come here: a file
452+ /// *opened* is the timeline, one *imported* into an empty window fills the
453+ /// library and leaves the lanes empty for a drag.
454+ pub(crate) fn open_media(&mut self, path: &std::path::Path, place: bool, subs: Subs) -> String {
455+ self.install_media(path, open_session(path, place, subs), place)
456+ }
457+
458+ /// The second half of it: everything the window derives from a session that
459+ /// has already been opened. Split from the open itself because the file
460+ /// argv named is opened on a worker ([`open_ahead`]) -- the twelve seconds
461+ /// of a cold header walk are not the UI thread's to spend -- and lands
462+ /// here, where nothing is read and nothing blocks.
463+ pub(crate) fn install_media(
464+ &mut self,
465+ path: &std::path::Path,
466+ opened: Result<(PlaybackSession, String), String>,
467+ place: bool,
468+ ) -> String {
469+ match opened {
470+ Ok((session, subs)) => {
471+ self.fps = session.meta().frame_rate;
472+ // Read before the session moves: a file that plays silent says
473+ // so here or nowhere.
474+ let silent = audio_notice(&session);
475+ // A file replaces the one that was open, and track 3 of that one
476+ // is not track 3 of this.
477+ self.sub_track = 0;
478+ self.session = Some(session);
479+ // A fresh session comes up at full volume; the player's own
480+ // setting outlives the file, so it is pushed at every new one.
481+ self.apply_volume();
482+ // Beside the new file, but still the format the card is set to:
483+ // opening another clip is not a change of mind about that.
484+ self.export_path = retarget(&export_path(path), self.format);
485+ self.project_path = project_path(path);
486+ self.name = file_name(path).into();
487+ self.reset_after_reseek();
488+ let name = file_name(path);
489+ // The library is filled and the timeline is empty; the only
490+ // thing that says so is this line, so it says what to do next.
491+ let what = match place {
492+ true => format!("OPENED {name}"),
493+ false => {
494+ format!("IMPORTED {name} to the library — drag it onto a lane to place it")
495+ }
496+ };
497+ format!("{what}{}{subs}", silent.unwrap_or_default())
498+ }
499+ Err(e) => format!("OPEN FAILED: {e}"),
500+ }
501+ }
502+
503+ /// The Import button: asks the desktop for a path and takes it the same way
504+ /// a drop would. The chooser is another process and the user may sit in it,
505+ /// so it runs on a background thread -- blocking here would freeze the
506+ /// window behind the dialog.
507+ pub(crate) fn pick_and_import(&mut self, cx: &mut Context<Self>) {
508+ if self.exporting().is_some() {
509+ return;
510+ }
511+ let picked = cx
512+ .background_executor()
513+ .spawn(async { pick_file("edith — import") });
514+ cx.spawn(async move |this, cx| {
515+ let picked = picked.await;
516+ this.update(cx, |this, cx| match picked {
517+ // One queue, and the fork is made when its worker starts
518+ // ([`arrival`]): a project replaces the timeline, media joins
519+ // the library, and neither is read on this thread.
520+ Ok(Some(path)) => this.import(&path, cx),
521+ // Cancelled: the user already knows what happened.
522+ Ok(None) => {}
523+ Err(text) => {
524+ eprintln!("{text}");
525+ this.notify_user(text.into());
526+ cx.notify();
527+ }
528+ })
529+ .ok();
530+ })
531+ .detach();
532+ }
533+
534+ /// The `+ S` button and its key: asks the desktop for a file and takes the
535+ /// subtitle tracks out of it -- a standalone `.srt`/`.vtt`/`.ass` is one of
536+ /// them, a Matroska however many are inside. Only the subtitles: the file
537+ /// itself does not join the library, which is what the Import button beside
538+ /// this one is for.
539+ ///
540+ /// The chooser is another process and the user may sit in it, so it runs on
541+ /// a background thread, exactly as [`Player::pick_and_import`] does.
542+ pub(crate) fn pick_and_add_subtitles(&mut self, cx: &mut Context<Self>) {
543+ // What dims the `+ S` button, asked here as well so the key answers the
544+ // same question -- and *before* the chooser rather than after it: a door
545+ // that opens a dialog, waits for a file and only then says the timeline
546+ // was never there is the second door disagreeing with the first.
547+ if let Some(why) = self.enable(ActionId::AddSubtitleTrack, None).why() {
548+ let text = format!("NO SUBTITLES ADDED — {why}");
549+ eprintln!("{text}");
550+ self.notify_user(text.into());
551+ cx.notify();
552+ return;
553+ }
554+ let picked = cx
555+ .background_executor()
556+ .spawn(async { pick_file("edith — subtitles to add") });
557+ cx.spawn(async move |this, cx| {
558+ let picked = picked.await;
559+ this.update(cx, |this, cx| match picked {
560+ Ok(Some(path)) => this.add_subtitles(&path, cx),
561+ // Cancelled: the user already knows what happened.
562+ Ok(None) => {}
563+ Err(text) => {
564+ eprintln!("{text}");
565+ this.notify_user(text.into());
566+ cx.notify();
567+ }
568+ })
569+ .ok();
570+ })
571+ .detach();
572+ }
573+
574+ /// Takes a file's subtitle tracks onto the timeline, off the render thread.
575+ /// The walk reads the whole container for its cues
576+ /// (`engine::PlaybackSession::parse_subtitles`) -- ~200 ms on a two-hour 4K
577+ /// remux and 1.3 s on a cold 3 GB one -- and a button that costs the window
578+ /// that many frames is a button that freezes it. So the *parse* is the
579+ /// worker's, whole, and the UI thread only pushes what came back
580+ /// ([`PlaybackSession::add_subtitle_tracks`]): no borrow crosses the await,
581+ /// because the parse is an associated fn that owns nothing.
582+ pub(crate) fn add_subtitles(&mut self, path: &std::path::Path, cx: &mut Context<Self>) {
583+ // Nothing to time the cues against: said now rather than after a walk
584+ // of a 25 GB file that was never going to be kept.
585+ if self.session.is_none() {
586+ self.landed_subtitles(path, None, cx);
587+ return;
588+ }
589+ self.notify_user(format!("READING {} for subtitles…", file_name(path)).into());
590+ let parsed = cx.background_executor().spawn({
591+ let path = path.to_path_buf();
592+ async move { engine::PlaybackSession::parse_subtitles(&path) }
593+ });
594+ let path = path.to_path_buf();
595+ cx.spawn(async move |this, cx| {
596+ let parsed = parsed.await;
597+ this.update(cx, |this, cx| {
598+ // The dedupe lives inside the push, so a second `+ S` on the
599+ // same file still answers 0 and still says so below.
600+ let added = this
601+ .session
602+ .as_mut()
603+ .map(|session| parsed.and_then(|tracks| pushed(session, &path, tracks)));
604+ this.landed_subtitles(&path, added, cx);
605+ })
606+ .ok();
607+ })
608+ .detach();
609+ cx.notify();
610+ }
611+
612+ /// Every subtitle track a `.srt`/`.vtt`/`.ass` carries, onto the timeline
613+ /// and nowhere else: they are not clips and land on no lane. The cues came
614+ /// off the worker that read the file ([`read_ahead`]), like every other
615+ /// door's do, and what is left here is the push. The engine dedupes by
616+ /// (file, track), so the same `.srt` twice is one row and says so.
617+ pub(crate) fn take_subtitles(&mut self, path: &std::path::Path, subs: Subs, cx: &mut Context<Self>) {
618+ let added = self
619+ .session
620+ .as_mut()
621+ .map(|session| subs.and_then(|tracks| pushed(session, path, tracks)));
622+ self.landed_subtitles(path, added, cx);
623+ }
624+
625+ /// What the timeline says once the tracks are on it, whichever worker did
626+ /// the reading: the `+ S` button and its key ([`Self::add_subtitles`]), a
627+ /// dropped or imported subtitle file ([`Self::take_subtitles`]), and a
628+ /// window with nothing to time cues against all word the outcome here,
629+ /// once, so no two doors can drift apart.
630+ pub(crate) fn landed_subtitles(
631+ &mut self,
632+ path: &std::path::Path,
633+ added: Option<engine::Result<usize>>,
634+ cx: &mut Context<Self>,
635+ ) {
636+ let text = match added {
637+ Some(Ok(0)) => format!(
638+ "{}'s subtitles are on the timeline already",
639+ file_name(path)
640+ ),
641+ Some(Ok(n)) => format!(
642+ "SUBTITLES {} — {n} track(s), showing over the picture, {} hides them",
643+ file_name(path),
644+ self.keymap.display(ActionId::ToggleSubtitles)
645+ ),
646+ Some(Err(e)) => format!("SUBTITLE IMPORT FAILED: {e}"),
647+ None => "NO SUBTITLES ADDED — open a file for them to run against first".to_string(),
648+ };
649+ eprintln!("{text}");
650+ self.notify_user(text.into());
651+ cx.notify();
652+ }
653+
654+ /// The × on a subtitle row, and the stroke that takes the picked one off:
655+ /// the track leaves the timeline and the pick moves with it. Every index
656+ /// past the one that went moves down
657+ /// ([`engine::Project::remove_subtitles`]), so a pick left where it was
658+ /// would name a *different* track -- and the pick is what an export writes
659+ /// into the file.
660+ ///
661+ /// Not an undo step: subtitles are not on the history's snapshots, so the
662+ /// way back is putting the file's subtitles on again -- which is a door of
663+ /// its own ([`Player::pick_and_add_subtitles`]) and reads the subtitles
664+ /// alone, never the media. The notice says that rather than promising a
665+ /// ctrl+z that would do nothing.
666+ pub(crate) fn remove_subtitle_track(&mut self, track: usize, cx: &mut Context<Self>) {
667+ // The one availability oracle, for the same reason the × on a row and
668+ // the stroke are one call: an empty list is not a failure, it is an
669+ // action with nothing to act on, and the engine's "there is no subtitle
670+ // track 0" is an index nobody typed. A real removal that fails still
671+ // says what the engine said, below.
672+ if let Some(why) = self.enable(ActionId::RemoveSubtitleTrack, None).why() {
673+ let text = format!("NO SUBTITLES REMOVED — {why}");
674+ eprintln!("{text}");
675+ self.notify_user(text.into());
676+ cx.notify();
677+ return;
678+ }
679+ // Read before it goes: a notice naming an index names nothing.
680+ let name = self
681+ .session
682+ .as_ref()
683+ .and_then(|session| sub_pick_name(session.subtitles(), track))
684+ .unwrap_or_else(|| format!("subtitle track {track}"));
685+ let text = match self
686+ .session
687+ .as_mut()
688+ .map(|session| session.remove_subtitles(track))
689+ {
690+ Some(Ok(())) => {
691+ let left = self
692+ .session
693+ .as_ref()
694+ .map_or(0, |session| session.subtitles().len());
695+ self.sub_track = sub_pick_after_removal(self.sub_track, track, left);
696+ // The drawn cue is keyed by that index ([`Player::sub_picture`])
697+ // and the index now stands for another track.
698+ //
699+ // corner-cut: its atlas tile is not released -- `close_session`'s
700+ // note, for its reason and with its upgrade path.
701+ self.sub_image = None;
702+ format!(
703+ "{name} REMOVED — {} puts a file's subtitles back on, the file itself stays off",
704+ self.keymap.display(ActionId::AddSubtitleTrack)
705+ )
706+ }
707+ Some(Err(e)) => format!("NO SUBTITLES REMOVED — {e}"),
708+ None => "NO SUBTITLES REMOVED — open a file first".to_string(),
709+ };
710+ eprintln!("{text}");
711+ self.notify_user(text.into());
712+ cx.notify();
713+ }
714+
715+ /// Swaps the whole timeline for one restored from a `.edith`, for
716+ /// [`Player::install_media`]'s reason: the open is a worker's -- a project
717+ /// naming a 24 GB film opens that film, which is the same twenty seconds
718+ /// ([`arrival`] sends every `.edith` through the one queue) -- and this is
719+ /// what is left once it lands. Nothing is replaced until the new session is
720+ /// in hand, so a refusal is shown as the engine worded it and leaves what is
721+ /// playing alone.
722+ pub(crate) fn install_project(
723+ &mut self,
724+ path: &std::path::Path,
725+ opened: Result<PlaybackSession, String>,
726+ cx: &mut Context<Self>,
727+ ) {
728+ if self.exporting().is_some() {
729+ return;
730+ }
731+ let text = match opened {
732+ Ok(session) => {
733+ self.fps = session.meta().frame_rate;
734+ let silent = audio_notice(&session);
735+ // A project is named after itself but still exports beside its
736+ // media: that is the only place an export has ever landed.
737+ self.export_path = retarget(&export_path(&session.sources()[0].path), self.format);
738+ self.session = Some(session);
739+ self.apply_volume();
740+ self.project_path = path.to_path_buf();
741+ self.name = file_name(path).into();
742+ // A copied clip names its source by index, which means a
743+ // different file -- or none -- in another project.
744+ self.clipboard = None;
745+ self.selected = None;
746+ // A menu can be up while a project is dropped on the window --
747+ // the scrim swallows clicks, never a drop -- and its index
748+ // would name some other timeline's clip. The two clip cards
749+ // hold a (lane, idx) of the old timeline for the same reason.
750+ self.context_menu = None;
751+ self.eq_open = None;
752+ self.color_open = None;
753+ // Marks are timeline frames of the timeline that was.
754+ self.close_silence();
755+ // A different set of sources: the row that was picked is not
756+ // the file that index names any more -- and neither is the
757+ // subtitle track that was showing.
758+ self.selected_asset = None;
759+ self.sub_track = 0;
760+ // The counters describe one timeline; the eof line must not
761+ // report the old one's frames against the new one.
762+ self.displayed = 0;
763+ self.dropped = 0;
764+ self.started = None;
765+ // Loaded paused at its saved playhead, so the still it owes
766+ // reaches the screen the way a seek's does. The old picture is
767+ // released by the swap in `pump`, as after any other seek.
768+ self.reset_after_reseek();
769+ format!("LOADED {}{}", file_name(path), silent.unwrap_or_default())
770+ }
771+ Err(e) => format!("OPEN FAILED: {e}"),
772+ };
773+ eprintln!("{text}");
774+ self.notify_user(text.into());
775+ cx.notify();
776+ }
777+
778+ /// Writes the timeline back to its project file. Overwrites silently, like
779+ /// an export: the path was chosen once and the notice is the confirmation.
780+ pub(crate) fn save_project(&mut self, cx: &mut Context<Self>) {
781+ let saved = self
782+ .session
783+ .as_ref()
784+ .map(|session| session.save_project(&self.project_path));
785+ let text = match saved {
786+ Some(Ok(())) => format!("SAVED {}", file_name(&self.project_path)),
787+ Some(Err(e)) => format!("SAVE FAILED: {e}"),
788+ None => "NOTHING TO SAVE — open a file first".to_string(),
789+ };
790+ eprintln!("{text}");
791+ self.notify_user(text.into());
792+ cx.notify();
793+ }
794+
795+ /// A new empty track under the ones already there. One undo step in the
796+ /// engine, so the stroke that takes back an edit takes back a track too, and
797+ /// no reseek: nothing plays differently until something is dropped on it.
798+ /// The selection stays -- the lanes it indexes into have not moved.
799+ pub(crate) fn add_lane(&mut self, kind: LaneKind, cx: &mut Context<Self>) {
800+ if self.exporting().is_some() {
801+ return;
802+ }
803+ match &mut self.session {
804+ Some(session) => {
805+ let lane = session.add_lane(kind);
806+ self.notify_user(
807+ format!(
808+ "{} ADDED — drag a clip onto it, {} takes it back",
809+ lane.label(),
810+ self.keymap.display(ActionId::Undo)
811+ )
812+ .into(),
813+ );
814+ }
815+ None => self.notify_user("NO TRACK ADDED — open a file first".into()),
816+ }
817+ cx.notify();
818+ }
819+
820+ /// The × in a track's header: the add taken back, one undo step, and the
821+ /// engine's own words when it refuses -- those name the clips still on the
822+ /// track, so the notice says what to delete first. A removal never deletes a
823+ /// clip.
824+ ///
825+ /// Everything holding a `(lane, idx)` is dropped, because the tracks below
826+ /// the one that went have just moved up an `ord`
827+ /// ([`engine::Project::remove_lane`]): a selection or an open card kept
828+ /// across it would be pointing at the *next* track's clip.
829+ pub(crate) fn remove_lane(&mut self, lane: Lane, cx: &mut Context<Self>) {
830+ if self.exporting().is_some() {
831+ return;
832+ }
833+ let removed = self
834+ .session
835+ .as_mut()
836+ .map(|session| session.remove_lane(lane));
837+ let text = match removed {
838+ Some(Ok(())) => {
839+ self.selected = None;
840+ self.context_menu = None;
841+ self.eq_open = None;
842+ self.color_open = None;
843+ self.speed_open = None;
844+ self.close_silence();
845+ format!(
846+ "{} REMOVED — {} brings it back",
847+ lane.label(),
848+ self.keymap.display(ActionId::Undo)
849+ )
850+ }
851+ Some(Err(e)) => format!("NO TRACK REMOVED — {e}"),
852+ None => "NO TRACK REMOVED — open a file first".to_string(),
853+ };
854+ self.notify_user(text.into());
855+ cx.notify();
856+ }
857+
858+ /// A header let go over another header: the track in the hand takes that
859+ /// one's place in the stack, clips and all
860+ /// ([`engine::Project::move_lane`]), one undo step. The gesture every
861+ /// editor reorders tracks with, and the only way the order is ever changed
862+ /// -- there is no second list of it to keep in step.
863+ ///
864+ /// Display order is the stack, so moving a video track past another video
865+ /// track changes which picture wins, here and in an export alike; audio is
866+ /// summed and does not care, which is what makes `A1` above `V1` a purely
867+ /// visual arrangement. A label is a position among the tracks of its kind,
868+ /// so a track that crossed one of its own kind comes back under a different
869+ /// name -- and everything holding a `(lane, idx)` is dropped exactly then,
870+ /// for [`Player::remove_lane`]'s reason: those handles now name another
871+ /// track's clip. A move that crossed only the other kind renames nothing
872+ /// and keeps the selection.
873+ pub(crate) fn reorder_lane(&mut self, lane: Lane, onto: Lane, cx: &mut Context<Self>) {
874+ self.lane_drop = None;
875+ if self.exporting().is_some() {
876+ return;
877+ }
878+ let Some(session) = self.session.as_mut() else {
879+ return;
880+ };
881+ let Some(to) = session.lanes().iter().position(|&l| l == onto) else {
882+ return;
883+ };
884+ // Picked up and put back down where it was is a click, and a click says
885+ // nothing -- `move_lane` refuses it and every other no-op.
886+ let Some(moved) = session.move_lane(lane, to) else {
887+ cx.notify();
888+ return;
889+ };
890+ if moved != lane {
891+ self.selected = None;
892+ self.context_menu = None;
893+ self.eq_open = None;
894+ self.color_open = None;
895+ self.speed_open = None;
896+ self.close_silence();
897+ }
898+ self.notify_user(
899+ format!(
900+ "{} IS TRACK {} NOW — {} puts it back",
901+ moved.label(),
902+ to + 1,
903+ self.keymap.display(ActionId::Undo)
904+ )
905+ .into(),
906+ );
907+ cx.notify();
908+ }
909+
910+ /// What the remove keys act on: the last track of that kind, which is the
911+ /// one the matching add key appended. Nothing at all before a file is open,
912+ /// where the timeline drawn is a placeholder pair.
913+ pub(crate) fn remove_last_lane(&mut self, kind: LaneKind, cx: &mut Context<Self>) {
914+ let last = self.session.as_ref().and_then(|session| {
915+ session
916+ .lanes()
917+ .into_iter()
918+ .filter(|l| l.kind == kind)
919+ .next_back()
920+ });
921+ match last {
922+ Some(lane) => self.remove_lane(lane, cx),
923+ None => {
924+ self.notify_user("NO TRACK REMOVED — open a file first".into());
925+ cx.notify();
926+ }
927+ }
928+ }
929+}
crates/app/src/player/mod.rsadded+10 -0
@@ -0,0 +1,10 @@
1+//! What the window does, one module per kind of doing. The state itself
2+//! (`struct Player`) stays beside the render in `main.rs`; these are the
3+//! detached halves of the one `impl` it used to carry.
4+pub mod actions;
5+pub mod cards;
6+pub mod export;
7+pub mod library;
8+pub mod timeline_edit;
9+pub mod transport;
10+pub mod view;
crates/app/src/player/timeline_edit.rsadded+895 -0
@@ -0,0 +1,895 @@
1+//! Editing the timeline itself: the cuts, the clipboard, the drags, the
2+//! snapping and the trims.
3+
4+use crate::*;
5+
6+impl Player {
7+ /// Splits the clip under the playhead. Metadata only: the timeline->source
8+ /// mapping is unchanged, so nothing reseeks and no flag is touched.
9+ pub(crate) fn cut(&mut self, cx: &mut Context<Self>) {
10+ if self.exporting().is_some() {
11+ return;
12+ }
13+ // Snapped to the source's own grid where one is within reach
14+ // ([`Player::cut_frame`]): a cut a third of a second off a sync point
15+ // looks identical on the bed and turns an export that copies its
16+ // picture in minutes into one that codes every frame of it for hours.
17+ // The playhead goes with it -- what was cut has to be where the line
18+ // is, or the next stroke acts a few frames from where it looks.
19+ let Some(session) = &self.session else {
20+ return;
21+ };
22+ let now = frame_at(session.now(), self.fps);
23+ let at = self.cut_frame(now);
24+ if at != now {
25+ self.seek(f64::from(at) / self.fps, cx);
26+ }
27+ if let Some(session) = &mut self.session {
28+ session.cut_at(f64::from(at) / self.fps);
29+ }
30+ self.selected = None;
31+ cx.notify();
32+ }
33+
34+ /// Rejoins whatever meets under the playhead and puts it back in one group
35+ /// -- the inverse of [`Player::cut`], and metadata only like it. The engine
36+ /// decides what is joinable; a refusal is worded here, because `false` is
37+ /// all it says and a key that looks broken is worse than one that explains
38+ /// itself.
39+ pub(crate) fn regroup(&mut self, cx: &mut Context<Self>) {
40+ if self.exporting().is_some() {
41+ return;
42+ }
43+ if let Some(session) = &mut self.session {
44+ if session.regroup_at(session.now()) {
45+ self.selected = None;
46+ } else {
47+ self.notify_user(
48+ "NOTHING TO REGROUP — put the playhead where two clips meet, on frames that were cut apart"
49+ .into(),
50+ );
51+ }
52+ }
53+ cx.notify();
54+ }
55+
56+ /// Takes the selected clip out of its group, so the picture and the sound
57+ /// under it are edited apart from here on: each half selects, moves, trims
58+ /// and is removed alone, and both draw outlined instead of tinted. The
59+ /// selection stays -- the half that was clicked is still the half in hand.
60+ pub(crate) fn detach(&mut self, cx: &mut Context<Self>) {
61+ if self.exporting().is_some() {
62+ return;
63+ }
64+ match (&mut self.session, self.selected) {
65+ (Some(session), Some((lane, idx))) => {
66+ if !session.ungroup(lane, idx) {
67+ self.notify_user(
68+ "NOTHING DETACHED — that clip is not grouped with another".into(),
69+ );
70+ }
71+ }
72+ (Some(_), None) => {
73+ self.notify_user("NOTHING DETACHED — click the take to take apart first".into())
74+ }
75+ (None, _) => {}
76+ }
77+ cx.notify();
78+ }
79+
80+ /// Puts the selected clip back in a group with the clip covering exactly the
81+ /// same frames on another track -- the way back from [`Player::detach`], and
82+ /// the way to group a picture with sound it was never opened with. The
83+ /// partner is not clicked because there is nothing to choose: a group id
84+ /// names one span, so only a clip covering these very frames could join it,
85+ /// and the engine words what to do when none does.
86+ pub(crate) fn group(&mut self, cx: &mut Context<Self>) {
87+ if self.exporting().is_some() {
88+ return;
89+ }
90+ let partner = match (&self.session, self.selected) {
91+ (Some(session), Some((lane, idx))) => span_partner(session, lane, idx),
92+ _ => None,
93+ };
94+ match (&mut self.session, self.selected, partner) {
95+ (Some(session), Some((lane, idx)), Some((other, o_idx))) => {
96+ if let Err(e) = session.group(lane, idx, other, o_idx) {
97+ self.notify_user(format!("NOT GROUPED — {e}").into());
98+ }
99+ }
100+ (Some(_), Some(_), None) => {
101+ self.notify_user(
102+ "NOTHING TO GROUP WITH — no clip on another track covers exactly these frames"
103+ .into(),
104+ )
105+ }
106+ (Some(_), None, _) => {
107+ self.notify_user("NOTHING GROUPED — click one of the halves first".into())
108+ }
109+ (None, ..) => {}
110+ }
111+ cx.notify();
112+ }
113+
114+ /// Drops the selected clip and closes the hole: a whole take goes, both
115+ /// lanes of it, and everything after it moves up. A half with no take under
116+ /// it in the video lane -- what a lift leaves behind -- has nothing to
117+ /// ripple, so that one is lifted instead. The engine reseeks itself, so all
118+ /// this owes is the flag reset.
119+ pub(crate) fn delete_selected(&mut self, cx: &mut Context<Self>) {
120+ if self.exporting().is_some() {
121+ return;
122+ }
123+ let selected = self.selected.take();
124+ // Whichever lane it was clicked in: the index is that lane's own, and
125+ // the ripple cuts the clip's span out of every lane -- a group covers
126+ // one span, so deleting a take by its audio half is the same edit as by
127+ // its picture. What is not a whole take is lifted instead, which is what
128+ // reaches a clip on an added track ([`whole_take`]).
129+ let deleted = match (&mut self.session, selected) {
130+ (Some(session), Some((lane, idx))) => match whole_take(session, lane, idx) {
131+ true => session.delete_clip(lane, idx),
132+ false => session.lift_clip(lane, idx),
133+ },
134+ _ => false,
135+ };
136+ if selected.is_some() && !deleted {
137+ self.notify_user("NOTHING DELETED — that clip is no longer there".into());
138+ }
139+ if deleted {
140+ self.reset_after_reseek();
141+ }
142+ cx.notify();
143+ }
144+
145+ /// Lifts the selected half out and leaves the hole: black picture there if
146+ /// it was the video lane, silence if it was the audio one, and nothing else
147+ /// moves. What Delete is not.
148+ pub(crate) fn lift_selected(&mut self, cx: &mut Context<Self>) {
149+ if self.exporting().is_some() {
150+ return;
151+ }
152+ match (&mut self.session, self.selected.take()) {
153+ (Some(session), Some((lane, idx))) => {
154+ if session.lift_clip(lane, idx) {
155+ self.reset_after_reseek();
156+ } else {
157+ self.notify_user("NOTHING LIFTED — that half is no longer there".into());
158+ }
159+ }
160+ (Some(_), None) => {
161+ self.notify_user("NOTHING LIFTED — click the half to remove first".into())
162+ }
163+ (None, _) => {}
164+ }
165+ cx.notify();
166+ }
167+
168+ /// Copies the selected clip. Nothing on screen changes, so no notify.
169+ pub(crate) fn copy_selected(&mut self) {
170+ let session = self.session.as_ref();
171+ // Out of the lane it was clicked in: the audio half of a group is a
172+ // different clip from the video one, and copying the wrong lane's
173+ // frames is a paste of the wrong thing.
174+ if let Some(clip) = self
175+ .selected
176+ .and_then(|(lane, idx)| session?.lane_clips(lane).get(idx).copied())
177+ {
178+ self.clipboard = Some(clip);
179+ }
180+ }
181+
182+ /// The group id of the clicked clip, which is what marks the other half.
183+ pub(crate) fn selected_link(&self) -> Option<u32> {
184+ let (lane, idx) = self.selected?;
185+ self.session.as_ref()?.lane_clips(lane).get(idx)?.link
186+ }
187+
188+ /// Drops the copied clip in at the playhead. The engine reseeks itself, so
189+ /// like a delete this owes the flag reset -- and the selection, whose index
190+ /// the insert has just moved.
191+ pub(crate) fn paste(&mut self, cx: &mut Context<Self>) {
192+ let pasted = match (&mut self.session, self.clipboard) {
193+ (Some(session), Some(clip)) => session.paste_at(session.now(), clip),
194+ _ => false,
195+ };
196+ if pasted {
197+ self.selected = None;
198+ self.reset_after_reseek();
199+ }
200+ cx.notify();
201+ }
202+
203+ /// A clip let go at window `x` over lane `to`: it lands with its head where
204+ /// the hand is carrying it ([`Player::drop_frame`]), on the track it was
205+ /// dropped on, taking its whole take with it -- one undo step for the
206+ /// gesture. Dropped back where it was picked up it is not an edit at all, so
207+ /// nothing is said about it. The engine reseeks, so all this owes is the
208+ /// flag reset -- and the selection, whose index was that lane's own and now
209+ /// names a different clip there.
210+ pub(crate) fn move_clip(&mut self, from: Lane, idx: usize, to: Lane, x: Pixels, cx: &mut Context<Self>) {
211+ if self.exporting().is_some() {
212+ return;
213+ }
214+ let (Some((start, _)), Some(was)) = (
215+ self.drop_frame(from, idx, x),
216+ self.session
217+ .as_ref()
218+ .and_then(|session| session.lane_clips(from).get(idx).map(|c| c.start)),
219+ ) else {
220+ return;
221+ };
222+ let moved = self
223+ .session
224+ .as_mut()
225+ .is_some_and(|session| session.move_clip_to(from, idx, to, start));
226+ let (kind, lanes) = match from.kind {
227+ LaneKind::Video => ("picture", "video"),
228+ LaneKind::Audio => ("sound", "audio"),
229+ };
230+ match moved {
231+ true => {
232+ self.selected = None;
233+ self.reset_after_reseek();
234+ }
235+ // The three ways a drag is refused, told apart by what the
236+ // front-end already knows: a lane's kind, and where the clip was.
237+ // Everything else that could refuse (a clip that is not there)
238+ // cannot be dragged.
239+ false if from.kind != to.kind => {
240+ self.notify_user(
241+ format!(
242+ "NOT ON {} — that is a {kind} clip; drop it on a {lanes} lane",
243+ to.label()
244+ )
245+ .into(),
246+ )
247+ }
248+ // Picked up and put back down where it was: a click, and a click
249+ // says nothing.
250+ false if from == to && start == was => {}
251+ false => {
252+ self.notify_user(
253+ format!(
254+ "NOT MOVED — another clip already covers those frames on {}",
255+ to.label()
256+ )
257+ .into(),
258+ )
259+ }
260+ }
261+ cx.notify();
262+ }
263+
264+ /// Where a clip let go at window `x` over lane `to` wants its head: the
265+ /// frame under the pointer, less however far into the box the hand grabbed
266+ /// it (so the clip does not jump under the pointer), pulled onto a
267+ /// neighbouring edge when it lands within [`SNAP_PX`] of one. `None` when
268+ /// there is no such clip to move. The engine has the last word on where it
269+ /// may actually go -- this is the ask, not the answer.
270+ ///
271+ /// corner-cut: the bed now runs past the last frame whenever the timeline is
272+ /// shorter than the view ([`Scale::time_at`] clamps at the head only), so a
273+ /// clip *can* be dragged out there. Zoomed in against the far end it cannot:
274+ /// the scroll clamp pins the bed's right edge to the duration, and the
275+ /// pointer has no pixel past it. The upgrade is to let the scroll clamp
276+ /// leave a screen of empty bed after the end, the way every NLE does.
277+ pub(crate) fn drop_frame(&self, from: Lane, idx: usize, x: Pixels) -> Option<(u32, Option<u32>)> {
278+ let clip = self.session.as_ref()?.lane_clips(from).get(idx).copied()?;
279+ let marks = self.snap_targets(Some((from, idx)));
280+ Some(landing(
281+ self.frame_under(x),
282+ self.grab,
283+ clip.frames(),
284+ self.snap,
285+ self.snap_frames(),
286+ &marks,
287+ ))
288+ }
289+
290+ /// The same answer for a library row on its way down: nothing is in the hand
291+ /// yet, so there is no grab offset to take off and no length to snap by --
292+ /// the file's own is not known until the engine has placed it -- and only
293+ /// its head lands. Asked by the line, by the ghost and by the drop itself
294+ /// ([`Player::insert_source`]), so all three name one frame.
295+ pub(crate) fn place_frame(&self, x: Pixels) -> (u32, Option<u32>) {
296+ let marks = self.snap_targets(None);
297+ landing(
298+ self.frame_under(x),
299+ 0,
300+ 0,
301+ self.snap,
302+ self.snap_frames(),
303+ &marks,
304+ )
305+ }
306+
307+ /// Which index the clip in the hand is at *now*: [`live_idx`] against the
308+ /// lane the drag named, since a stroke during the gesture moves the indices
309+ /// gpui froze into the payload. Both halves of a drag ask it -- the line
310+ /// drawn in flight and the drop that commits -- so the promise and the
311+ /// landing are made about one clip.
312+ pub(crate) fn dragged(&self, drag: &ClipDrag) -> Option<usize> {
313+ let session = self.session.as_ref()?;
314+ live_idx(session.lane_clips(drag.lane), drag.idx, drag.clip)
315+ }
316+
317+ /// The line while the clip is still in the hand: the very answer
318+ /// [`Player::drop_frame`] will commit, worked out on every move of the drag,
319+ /// so what the eye was promised is where the release puts it. A pointer that
320+ /// has wandered off the bed promises nothing.
321+ pub(crate) fn preview_drop(&mut self, from: Lane, idx: usize, x: Pixels, cx: &mut Context<Self>) {
322+ let cue = self.drop_frame(from, idx, x).and_then(|(_, cue)| cue);
323+ self.set_cue(cue, x, cx);
324+ }
325+
326+ /// The same line for a library row on its way to a lane: it goes down at
327+ /// the frame it is let go on ([`Player::place_frame`]), so that frame is
328+ /// what snaps and what is drawn.
329+ pub(crate) fn preview_place(&mut self, x: Pixels, cx: &mut Context<Self>) {
330+ let cue = self.place_frame(x).1;
331+ self.set_cue(cue, x, cx);
332+ }
333+
334+ /// The shadow the clip in the hand would fill, on the lane the pointer is
335+ /// over: its head where [`Player::drop_frame`] says the release will put it
336+ /// -- the same call the drop makes, so the box drawn and the box committed
337+ /// are one answer -- and its own length at this zoom. A lane of the other
338+ /// kind refuses the drop ([`Project::move_clip`]), and the shadow says so
339+ /// before the release does.
340+ pub(crate) fn preview_ghost(&mut self, drag: &ClipDrag, to: Lane, x: Pixels, cx: &mut Context<Self>) {
341+ let ghost = self
342+ .dragged(drag)
343+ .and_then(|idx| self.drop_frame(drag.lane, idx, x))
344+ .map(|(start, _)| Ghost {
345+ lane: to,
346+ start,
347+ frames: drag.clip.frames(),
348+ tint: self.clip_tint(drag.clip.source),
349+ refused: drag.lane.kind != to.kind,
350+ });
351+ self.set_ghost(ghost, cx);
352+ }
353+
354+ /// The line the track in the hand would drop into, on the row the pointer
355+ /// is over: at that row's top edge when the header is coming up from below
356+ /// and at its bottom edge when it is going down, which is the slot
357+ /// [`Player::reorder_lane`] commits to at the release. Nothing at all over
358+ /// its own row, where a release changes nothing.
359+ pub(crate) fn preview_lane_drop(&mut self, from: Lane, onto: Lane, cx: &mut Context<Self>) {
360+ let lanes = self
361+ .session
362+ .as_ref()
363+ .map_or_else(Vec::new, PlaybackSession::lanes);
364+ let at = |lane: Lane| lanes.iter().position(|&l| l == lane);
365+ let next = match (at(from), at(onto)) {
366+ (Some(i), Some(j)) if i != j => Some(LaneDrop {
367+ lane: onto,
368+ above: j < i,
369+ }),
370+ _ => None,
371+ };
372+ // Only when it has actually changed: a drag move fires on every painted
373+ // frame, and a redraw per frame that draws the same line is a redraw
374+ // for nothing.
375+ if self.lane_drop != next {
376+ self.lane_drop = next;
377+ cx.notify();
378+ }
379+ }
380+
381+ /// The line taken back down again, by the row that drew it and by no other:
382+ /// the pointer has been carried off `lane`, so the slot it was promising is
383+ /// no longer the one a release would commit to.
384+ pub(crate) fn forget_lane_drop(&mut self, lane: Lane, cx: &mut Context<Self>) {
385+ if self.lane_drop.is_some_and(|d| d.lane == lane) {
386+ self.lane_drop = None;
387+ cx.notify();
388+ }
389+ }
390+
391+ /// The same shadow for a library row: its head at [`Player::place_frame`],
392+ /// which is where the drop inserts it, and the file's own length for its
393+ /// width -- the length the library row already reports. A file this lane
394+ /// cannot hold ([`lane_refuses`]) is tinted as refused, which is the answer
395+ /// the release would give in words.
396+ pub(crate) fn preview_ghost_asset(&mut self, path: &Path, to: Lane, x: Pixels, cx: &mut Context<Self>) {
397+ let ghost = Ghost {
398+ lane: to,
399+ start: self.place_frame(x).0,
400+ frames: self
401+ .session
402+ .as_ref()
403+ .map_or(0, |session| session.file_frames(path)),
404+ // A path with no source entry has no colour of its own, and the
405+ // shadow wears the lane's own instead of borrowing another file's.
406+ tint: file_tint(self.sources(), path).unwrap_or(BG_RAISED()),
407+ refused: lane_refuses(path, to).is_some(),
408+ };
409+ self.set_ghost(Some(ghost), cx);
410+ }
411+
412+ /// Sets the shadow, or takes it away, repainting only when it moved -- the
413+ /// listeners below run it on every pointer sample of a drag. Cleared by the
414+ /// root and set again by the lane under the pointer, in that order (gpui
415+ /// runs the capture phase parent-first), so a pointer over no lane at all
416+ /// leaves nothing drawn.
417+ pub(crate) fn set_ghost(&mut self, ghost: Option<Ghost>, cx: &mut Context<Self>) {
418+ if ghost != self.ghost {
419+ self.ghost = ghost;
420+ cx.notify();
421+ }
422+ }
423+
424+ /// The swatch a clip from source `n` wears: [`source_tint`] over the first
425+ /// source entry naming that *file*, since two audio streams of one file are
426+ /// two sources and one colour. Every box on a lane and every ghost a drag
427+ /// draws asks this, so the shadow is recognisably the thing in the hand.
428+ pub(crate) fn clip_tint(&self, source: usize) -> u32 {
429+ self.sources()
430+ .get(source)
431+ .and_then(|entry| file_tint(self.sources(), &entry.path))
432+ .unwrap_or_else(|| source_tint(source))
433+ }
434+
435+ pub(crate) fn sources(&self) -> &[Source] {
436+ self.session
437+ .as_ref()
438+ .map_or(&[][..], PlaybackSession::sources)
439+ }
440+
441+ /// Sets the line, or takes it away, and repaints only when it moved: a
442+ /// pointer dragged off the bed (up to the library, say) is not promising a
443+ /// landing any more.
444+ pub(crate) fn set_cue(&mut self, cue: Option<u32>, x: Pixels, cx: &mut Context<Self>) {
445+ let bed = self.ruler.get();
446+ let cue = cue.filter(|_| x >= bed.left() && x <= bed.right());
447+ if cue != self.snap_cue {
448+ self.snap_cue = cue;
449+ cx.notify();
450+ }
451+ }
452+
453+ /// Every edge this timeline offers a gesture: [`snap_marks`] over all of its
454+ /// lanes, so a clip meets a take one track over as readily as one beside it.
455+ pub(crate) fn snap_targets(&self, skip: Option<(Lane, usize)>) -> Vec<u32> {
456+ let Some(session) = &self.session else {
457+ return Vec::new();
458+ };
459+ let lanes = session.lanes();
460+ let clips: Vec<&[Clip]> = lanes.iter().map(|&lane| session.lane_clips(lane)).collect();
461+ let skip = skip.and_then(|(lane, idx)| Some((lanes.iter().position(|&l| l == lane)?, idx)));
462+ snap_marks(&clips, skip, frame_at(session.now(), self.fps))
463+ }
464+
465+ /// Where a gesture at `raw` lands and the mark that pulled it there, with
466+ /// the switch honoured: snapping off, nothing moves and no line is drawn.
467+ pub(crate) fn snap_to(&self, raw: u32, len: u32, marks: &[u32]) -> (u32, Option<u32>) {
468+ snap_cue(self.snap, raw, len, self.snap_frames(), marks)
469+ }
470+
471+ /// Every timeline frame that is a *source* sync point: each clip's own
472+ /// grid ([`Player::syncs`]), moved onto the frames the clip plays it at.
473+ /// Ascending, because the clips are and each grid is.
474+ ///
475+ /// This is the difference between an export that copies its picture and one
476+ /// that decodes and re-codes every frame of a feature film. A cut anywhere
477+ /// else leaves the copy path with a region that begins between two sync
478+ /// points -- pictures whose references are not in the file -- and the whole
479+ /// export falls back to the encoder ([`engine::export`] states the rule).
480+ ///
481+ /// Only clips at their own speed, and only video lanes: a re-timed clip is
482+ /// resampled pictures, which is not a copy at any cut, and a sound lane has
483+ /// no groups of pictures to begin with.
484+ pub(crate) fn sync_frames(&self) -> Vec<u32> {
485+ let Some(session) = &self.session else {
486+ return Vec::new();
487+ };
488+ let sources = session.sources();
489+ let mut marks = Vec::new();
490+ for lane in session.lanes() {
491+ if lane.kind != LaneKind::Video {
492+ continue;
493+ }
494+ for clip in session.lane_clips(lane) {
495+ let Some(keys) = sources
496+ .get(clip.source)
497+ .and_then(|entry| self.syncs.get(&entry.path))
498+ .filter(|_| clip.speed.is_normal())
499+ else {
500+ continue;
501+ };
502+ marks.extend(
503+ keys.iter()
504+ .filter(|&&key| key >= clip.in_frame && key < clip.out_frame)
505+ .map(|&key| clip.start + (key - clip.in_frame)),
506+ );
507+ }
508+ }
509+ marks.sort_unstable();
510+ marks
511+ }
512+
513+ /// The frame a cut asked for at `raw` really lands on: the nearest source
514+ /// sync point within the snap's own tolerance, or `raw` itself where the
515+ /// magnet is off, where nothing is near enough, or where the source has no
516+ /// grid to offer (the walk has not answered yet, or the file is not one
517+ /// this project can copy at all).
518+ ///
519+ /// The same tolerance the clip-edge snap uses, so one switch and one
520+ /// distance govern every landing on this timeline.
521+ pub(crate) fn cut_frame(&self, raw: u32) -> u32 {
522+ if !self.snap {
523+ return raw;
524+ }
525+ let tol = self.snap_frames();
526+ self.sync_frames()
527+ .into_iter()
528+ .filter(|mark| mark.abs_diff(raw) <= tol)
529+ .min_by_key(|mark| mark.abs_diff(raw))
530+ .unwrap_or(raw)
531+ }
532+
533+ /// Whether the playhead is standing exactly on one: what the timeline's own
534+ /// line says out loud, so "a cut here is copied" is on screen before the cut
535+ /// rather than discovered in the export card afterwards.
536+ ///
537+ /// Asked every repaint, so it walks the *playhead* into each clip's source
538+ /// and looks it up in that source's own sorted grid -- where
539+ /// [`Player::sync_frames`] builds the whole list, which is a film's worth of
540+ /// marks to allocate and sort sixty times a second.
541+ pub(crate) fn on_sync_point(&self) -> bool {
542+ let Some(session) = &self.session else {
543+ return false;
544+ };
545+ let now = frame_at(session.now(), self.fps);
546+ let sources = session.sources();
547+ session.lanes().into_iter().any(|lane| {
548+ lane.kind == LaneKind::Video
549+ && session.lane_clips(lane).iter().any(|clip| {
550+ clip.speed.is_normal()
551+ && (clip.start..clip.start + (clip.out_frame - clip.in_frame))
552+ .contains(&now)
553+ && sources
554+ .get(clip.source)
555+ .and_then(|entry| self.syncs.get(&entry.path))
556+ .is_some_and(|keys| {
557+ keys.binary_search(&(clip.in_frame + (now - clip.start))).is_ok()
558+ })
559+ })
560+ })
561+ }
562+
563+ /// Puts the playhead on the sync point before or after it -- the keyboard's
564+ /// half of placing a cut where the export can copy it, and the only way to
565+ /// reach one exactly on a timeline zoomed out to a whole film, where one
566+ /// pixel is seconds.
567+ pub(crate) fn jump_sync(&mut self, forward: bool, cx: &mut Context<Self>) {
568+ let Some(session) = &self.session else {
569+ return;
570+ };
571+ let now = frame_at(session.now(), self.fps);
572+ let marks = self.sync_frames();
573+ let mark = match forward {
574+ true => marks.iter().find(|&&mark| mark > now).copied(),
575+ false => marks.iter().rev().find(|&&mark| mark < now).copied(),
576+ };
577+ match mark {
578+ Some(mark) => self.seek(f64::from(mark) / self.fps, cx),
579+ // Said rather than swallowed: the two most likely reasons are a walk
580+ // that has not answered yet and a source with no grid at all, and a
581+ // key that does nothing looks broken either way.
582+ None => self.notify_user(match marks.is_empty() {
583+ true => "NO SYNC POINTS — this source has no keyframe grid to jump by (or it is \
584+ still being read)"
585+ .into(),
586+ false => "NO SYNC POINT THAT WAY — the playhead is past the last one".into(),
587+ }),
588+ }
589+ }
590+
591+ /// [`SNAP_PX`] in timeline frames at the scale the bed is drawn at: the bed's
592+ /// own width drops out of it, since a pixel is now worth the same stretch of
593+ /// timeline wherever the view sits.
594+ pub(crate) fn snap_frames(&self) -> u32 {
595+ self.scale.snap_frames(self.fps)
596+ }
597+
598+ /// Opens the clip menu on the box under the pointer, from the right button
599+ /// wherever it was pressed on that box -- its middle or one of its edge
600+ /// strips, which cover the middle's own listener. Selecting first is part of
601+ /// it: every item acts on the clip the menu names.
602+ pub(crate) fn open_menu(&mut self, lane: Lane, idx: usize, at: Point<Pixels>, cx: &mut Context<Self>) {
603+ if self.modal() {
604+ return;
605+ }
606+ self.select((lane, idx), cx);
607+ self.context_menu = Some(ContextMenu {
608+ lane,
609+ idx,
610+ at,
611+ details: false,
612+ });
613+ cx.notify();
614+ }
615+
616+ /// A press on a clip's edge: the start of the drag that changes how much of
617+ /// its source it plays. It selects the clip as a press anywhere else on the
618+ /// box does -- the edge strip covers the box's own listener (`occlude`), so
619+ /// this is the only one that fires there.
620+ pub(crate) fn start_trim(&mut self, lane: Lane, idx: usize, edge: Edge, cx: &mut Context<Self>) {
621+ if self.modal() || self.exporting().is_some() {
622+ return;
623+ }
624+ let Some(clip) = self
625+ .session
626+ .as_ref()
627+ .and_then(|session| session.lane_clips(lane).get(idx).copied())
628+ else {
629+ return;
630+ };
631+ self.select((lane, idx), cx);
632+ self.trim = Some(Trim {
633+ lane,
634+ idx,
635+ edge,
636+ // Where the edge already is: a press that never moves is not an
637+ // edit, and `Project::trim` refuses exactly that.
638+ to: match edge {
639+ Edge::Start => clip.start,
640+ Edge::End => clip.end(),
641+ },
642+ link: clip.link,
643+ });
644+ cx.notify();
645+ }
646+
647+ /// Where the pointer has pulled the edge to, clamped to the room the engine
648+ /// says that edge has. Along the same bed the ruler is measured on and
649+ /// against the same duration the boxes are drawn to, so the edge tracks the
650+ /// pointer exactly.
651+ pub(crate) fn trim_to(&mut self, x: Pixels, cx: &mut Context<Self>) {
652+ let Some(trim) = self.trim else {
653+ return;
654+ };
655+ // The edge is pulled onto the same marks a whole clip is, by itself:
656+ // there is no other end travelling with it, so it snaps at length zero.
657+ let marks = self.snap_targets(Some((trim.lane, trim.idx)));
658+ let (at, cue) = self.snap_to(self.frame_under(x), 0, &marks);
659+ let Some((lo, hi)) = self
660+ .session
661+ .as_ref()
662+ .and_then(|session| session.trim_room(trim.lane, trim.idx, trim.edge))
663+ else {
664+ return;
665+ };
666+ let to = at.clamp(lo, hi);
667+ // The line only stands where the edge actually stopped: a mark the
668+ // engine's own room clamped away was never reached.
669+ self.set_cue(cue.filter(|_| to == at), x, cx);
670+ self.trim = Some(Trim { to, ..trim });
671+ cx.notify();
672+ }
673+
674+ /// The timeline frame a pointer at window x is on: along the same bed the
675+ /// ruler is measured on, through the same [`Scale`] every box is drawn
676+ /// through, so a zoomed-in panel answers with the frame under the pointer
677+ /// and not with the one that would have been there unzoomed. The one
678+ /// question a trim, a grab and a drop all ask.
679+ pub(crate) fn frame_under(&self, x: Pixels) -> u32 {
680+ frame_at(
681+ self.scale.time_at(px_along(x, self.ruler.get())),
682+ self.fps,
683+ )
684+ }
685+
686+ /// The release: the whole drag reaches the engine as one edit, so it is one
687+ /// undo step. The selection survives it -- a trim inserts and removes
688+ /// nothing, so every index a lane had still names the clip it named.
689+ pub(crate) fn commit_trim(&mut self, cx: &mut Context<Self>) {
690+ let Some(trim) = self.trim.take() else {
691+ return;
692+ };
693+ let trimmed = self
694+ .session
695+ .as_mut()
696+ .is_some_and(|session| session.trim_clip(trim.lane, trim.idx, trim.edge, trim.to));
697+ if trimmed {
698+ self.reset_after_reseek();
699+ }
700+ cx.notify();
701+ }
702+
703+ /// The clip as the drag is showing it: an edge under the pointer moves its
704+ /// own box, and the boxes of the halves linked to it, before anything is
705+ /// committed. Display only -- the project is not touched until the release.
706+ pub(crate) fn trimmed(&self, lane: Lane, idx: usize, clip: Clip) -> Clip {
707+ let Some(trim) = self.trim.filter(|t| {
708+ (t.lane, t.idx) == (lane, idx) || (t.link.is_some() && t.link == clip.link)
709+ }) else {
710+ return clip;
711+ };
712+ let still = self.session.as_ref().is_some_and(|session| {
713+ session
714+ .sources()
715+ .get(clip.source)
716+ .is_some_and(|s| engine::is_image(&s.path))
717+ });
718+ trimmed_clip(clip, trim.edge, trim.to, still)
719+ }
720+
721+ /// How long the timeline is *drawn* as: its own length, and while a tail is
722+ /// being dragged the furthest that tail may reach. A bed that ends exactly
723+ /// at the last frame has nowhere to put a pointer that means "longer", so
724+ /// without this the last clip on the timeline could be pulled in and never
725+ /// let back out.
726+ ///
727+ /// Scroll room only, now that a second is an absolute number of pixels
728+ /// ([`Scale`]): the extra length loosens [`View::settled`]'s clamp, which is
729+ /// where the pixels past the last frame come from, and moves no box by a
730+ /// pixel. It is still the *only* headroom at the tail -- zoomed in against
731+ /// the end, that clamp pins the bed's right edge to the duration and an
732+ /// End-trim of the last clip would have nowhere to be dragged to. What it
733+ /// must not do is be read as a length anyone is told: the timecode reads
734+ /// `PlaybackSession::timeline_duration` for exactly that reason.
735+ pub(crate) fn drawn_duration(&self) -> f64 {
736+ let Some(session) = &self.session else {
737+ return 0.;
738+ };
739+ let duration = session.timeline_duration();
740+ match self.trim {
741+ Some(trim) if trim.edge == Edge::End => {
742+ let (_, hi) = session
743+ .trim_room(trim.lane, trim.idx, trim.edge)
744+ .unwrap_or((0, 0));
745+ duration.max(f64::from(hi) / self.fps)
746+ }
747+ _ => duration,
748+ }
749+ }
750+
751+ /// Where the playhead is, as the panel draws it: pinned to the out point
752+ /// once playback is done, and clamped to the drawn duration otherwise -- a
753+ /// tail being dragged draws past the timeline it is about to become.
754+ pub(crate) fn playhead(&self, duration: f64) -> f64 {
755+ if self.transport() == Transport::Ended {
756+ duration
757+ } else {
758+ self.session
759+ .as_ref()
760+ .map_or(0., PlaybackSession::now)
761+ .clamp(0., duration)
762+ }
763+ }
764+
765+ /// One sample of whatever drag is in the hand: the equalizer's handle, a
766+ /// clip's edge, a colour bar, the speed bar, the volume slider or the
767+ /// playhead. Each of those starts on a strip a few pixels wide that the
768+ /// pointer leaves immediately, so none of them can be tracked from the
769+ /// element it started on -- the gesture is followed here instead, on a
770+ /// hitbox that covers everything the hand can reach.
771+ ///
772+ /// Registered on the root *and* on the scrim of every card that holds a
773+ /// slider ([`Player::drag_scrim`]). An occluding sheet ends gpui's hit test
774+ /// where it sits (`Hitbox::is_hovered`, window.rs:788), so while a card is
775+ /// up the root is not hovered anywhere under it and hears none of this: the
776+ /// press set a value and the drag then froze on it.
777+ pub(crate) fn drag_move(&mut self, event: &MouseMoveEvent, _: &mut Window, cx: &mut Context<Self>) {
778+ // A handle is 10 px across and the pointer leaves it at once, so
779+ // the equalizer drag is tracked here for the ruler's reason.
780+ if self.eq_dragging {
781+ if event.pressed_button == Some(MouseButton::Left) {
782+ self.drag_band(event.position, cx);
783+ } else {
784+ // Released outside the window: the up below never came,
785+ // so this is where the gesture ends -- and it still owes
786+ // the one write the whole drag is worth.
787+ self.eq_dragging = false;
788+ self.commit_eq(cx);
789+ }
790+ return;
791+ }
792+ // A clip edge is 6 px wide and the pointer leaves it on the
793+ // first drag, so the gesture is tracked here for the same
794+ // reason -- and it ends here too when the button came up
795+ // outside the window, still owing its one edit.
796+ if self.trim.is_some() {
797+ match event.pressed_button {
798+ Some(MouseButton::Left) => self.trim_to(event.position.x, cx),
799+ _ => self.commit_trim(cx),
800+ }
801+ return;
802+ }
803+ // A colour slider is 4 px tall and the pointer leaves it just as
804+ // fast; every sample is live, so the release owes no write of
805+ // its own -- what the last sample set is what the clip carries.
806+ if self.color_dragging {
807+ if event.pressed_button == Some(MouseButton::Left) {
808+ self.drag_color(event.position.x, false, cx);
809+ } else {
810+ // The release happened outside the window, so this is
811+ // where the gesture ends -- and it may not end on a
812+ // sample the worker was too busy to take.
813+ self.color_dragging = false;
814+ self.flush_drag(cx);
815+ }
816+ return;
817+ }
818+ // The speed bar, the same 4 px and the same live writes: the
819+ // press took the undo step and every sample since is live.
820+ if self.speed_dragging {
821+ if event.pressed_button == Some(MouseButton::Left) {
822+ self.drag_speed(event.position.x, false, cx);
823+ } else {
824+ self.speed_dragging = false;
825+ self.flush_drag(cx);
826+ }
827+ return;
828+ }
829+ // The volume slider, the same live writes: what the hand is on
830+ // is what the speakers are doing, and there is nothing to undo.
831+ if self.volume_dragging {
832+ if event.pressed_button == Some(MouseButton::Left) {
833+ self.drag_volume(event.position.x, cx);
834+ } else {
835+ self.volume_dragging = false;
836+ }
837+ return;
838+ }
839+ if !self.scrubbing {
840+ return;
841+ }
842+ if event.pressed_button == Some(MouseButton::Left) {
843+ self.scrub_to(event.position.x, false, cx);
844+ } else {
845+ // A release outside the window never reaches the handler
846+ // below, so the first button-up move is when we learn the
847+ // drag is over. Without this the next hover would scrub.
848+ self.scrubbing = false;
849+ }
850+ }
851+
852+ /// Where a drag ends: the release lands exactly, and whatever the gesture
853+ /// owes -- one undo step for the equalizer and the trim, a flush for the
854+ /// live-writing bars -- is paid here. On the root and on a card's scrim
855+ /// both, for [`Player::drag_move`]'s reason: a release over an open card
856+ /// never reaches the root.
857+ pub(crate) fn drag_release(&mut self, event: &MouseUpEvent, _: &mut Window, cx: &mut Context<Self>) {
858+ if std::mem::take(&mut self.eq_dragging) {
859+ // The release lands exactly, then the gesture is written
860+ // once -- the append-only table's whole reason.
861+ self.drag_band(event.position, cx);
862+ self.commit_eq(cx);
863+ return;
864+ }
865+ if self.trim.is_some() {
866+ // The release lands exactly, then the gesture is
867+ // written once -- one edit, one undo step.
868+ self.trim_to(event.position.x, cx);
869+ self.commit_trim(cx);
870+ return;
871+ }
872+ if std::mem::take(&mut self.color_dragging) {
873+ // The release lands exactly where the hand let go, and
874+ // it is a live write like every other sample: the undo
875+ // step the gesture rolls back to was the press's. The
876+ // flush is what makes "exactly" true while the worker is
877+ // still busy -- the sample above would only be held.
878+ self.drag_color(event.position.x, false, cx);
879+ self.flush_drag(cx);
880+ return;
881+ }
882+ if std::mem::take(&mut self.speed_dragging) {
883+ self.drag_speed(event.position.x, false, cx);
884+ self.flush_drag(cx);
885+ return;
886+ }
887+ if std::mem::take(&mut self.volume_dragging) {
888+ self.drag_volume(event.position.x, cx);
889+ return;
890+ }
891+ if std::mem::take(&mut self.scrubbing) {
892+ self.scrub_to(event.position.x, true, cx);
893+ }
894+ }
895+}
crates/app/src/player/transport.rsadded+308 -0
@@ -0,0 +1,308 @@
1+//! Where the playhead is and where it is going: the pump, the seeks, the
2+//! volume and the one button that starts it.
3+
4+use crate::*;
5+
6+impl Player {
7+ /// Catches the display up to the clock: everything already due is taken off
8+ /// the channel and only the last of them is shown, which *is* the
9+ /// drop-when-behind policy. A frame that is not due yet waits in `held`, and
10+ /// while the clock is paused *nothing* is due -- a repaint re-presents the
11+ /// frame already on screen, whatever asked for the repaint.
12+ pub(crate) fn pump(&mut self, window: &mut Window) {
13+ // Where the transport was before this drain, so the crossing into
14+ // `Ended` can be recognised as the one transition it is.
15+ let was = self.transport();
16+ // No timeline, nothing to catch up to: the window is showing its empty
17+ // state and there is no decoder to drain.
18+ let Some(session) = &mut self.session else {
19+ return;
20+ };
21+ let target = session.now() * self.fps;
22+ let mut newest: Option<Frame> = None;
23+ // A frame the screen is owed: a seek's landing, and the one readiness
24+ // signal there is ([`Player::reset_after_reseek`]).
25+ let owed = self.seek_since.is_some();
26+ // Paused, the clock is frozen and *nothing new is due*. Whatever the
27+ // decoder is still handing over is the backlog it was behind by when
28+ // the pause landed -- frames at a position the transport has already
29+ // left -- and taking one per repaint is what walked the picture on
30+ // after the sound had stopped, at exactly the rate the pointer was
31+ // moved over the timeline. Gated here, at the one place a frame ever
32+ // reaches the screen, rather than in the handlers that repaint: a
33+ // hover, a notice, a resize and a vsync are all the same event to this.
34+ // An owed frame is still taken, playing or not -- a scrub is paused by
35+ // definition, and its landing is the whole point of it.
36+ while session.is_playing() || owed {
37+ let frame = match self.held.take() {
38+ Some(frame) => frame,
39+ // Nothing waiting means either a clip boundary being rebuilt or
40+ // the real end of the timeline, and only the engine can tell
41+ // them apart -- `frame.index` is already a timeline index.
42+ None => match session.try_frame() {
43+ Some(frame) => frame,
44+ None => break,
45+ },
46+ };
47+ if f64::from(frame.index) <= target {
48+ self.dropped += u32::from(newest.is_some());
49+ newest = Some(frame);
50+ } else {
51+ self.held = Some(frame);
52+ break;
53+ }
54+ }
55+
56+ // How far behind the master clock the picture just handed over is, in
57+ // seconds. Measured off a frame that really arrived and nothing else: a
58+ // clip boundary being reopened delivers nothing at all for hundreds of
59+ // milliseconds, and restarting *that* would only cancel the open it is
60+ // waiting on.
61+ let late = newest
62+ .as_ref()
63+ .map_or(0., |f| (target - f64::from(f.index)) / self.fps);
64+
65+ if let Some(frame) = newest {
66+ self.displayed += 1;
67+ self.seek_since = None;
68+ self.started.get_or_insert_with(|| {
69+ eprintln!("first frame displayed (index {})", frame.index);
70+ Instant::now()
71+ });
72+ let buf = image::RgbaImage::from_raw(frame.width, frame.height, frame.bgra)
73+ .expect("frame buffer sized width*height*4");
74+ // Counted here rather than under `color_open`, because the card
75+ // opens on a frame that was pumped before it: gating this on the
76+ // card would leave its graph flat until something reseeked. A
77+ // thousandth of the pixels, against a conversion that just touched
78+ // all of them.
79+ self.histogram = histogram(buf.as_raw());
80+ let next = Arc::new(RenderImage::new(vec![image::Frame::new(buf)]));
81+ if let Some(old) = self.image.replace(next) {
82+ // Every RenderImage gets a fresh id and its own atlas tile:
83+ // without this the sprite atlas grows for the whole video.
84+ let _ = window.drop_image(old);
85+ }
86+ }
87+
88+ // Audio is the master clock and a decoder that cannot keep up with it
89+ // never gets back on its own: it hands over every frame in order,
90+ // whether or not its moment has passed, so what it is behind by only
91+ // grows -- a minute in, the picture is seconds behind what is being
92+ // heard, and that is the whole of "the video can't catch the audio".
93+ // Past `LATE_RESYNC` the backlog is abandoned and the picture restarted
94+ // at the clock, which touches neither the sound nor the clock
95+ // (`PlaybackSession::resync_picture`), so nothing the ear is following
96+ // moves. Never on a frame a seek owed: that one is late by however long
97+ // its own reopen took, and answering it with another reopen is a loop.
98+ //
99+ // corner-cut: on a machine that cannot decode the file in real time at
100+ // all this settles into one restart per `RESYNC_GAP` -- in sync, and
101+ // stuttering, which is the honest picture of what that machine can do.
102+ // The upgrade path is dropping late frames *inside* the worker (skip
103+ // the convert and the send for anything already past due), which needs
104+ // the deadline shared with it.
105+ if !owed && session.is_playing() && should_resync(late, self.resynced) {
106+ eprintln!("picture {late:.3}s behind the clock: restarting it there");
107+ session.resync_picture();
108+ self.held = None;
109+ self.resynced = Some(Instant::now());
110+ }
111+
112+ if self.transport() == Transport::Ended {
113+ // A seek whose worker never produced a frame (vanished file) would
114+ // otherwise repaint at vsync forever. Held clear for as long as the
115+ // state does, not just on the crossing: nothing else is coming.
116+ self.seek_since = None;
117+ if was != Transport::Ended {
118+ // Ended is a *stopped* transport, so the clock stops with it,
119+ // on the out point the timecode and the playhead have been
120+ // showing all along. Nothing else ever stopped it: past the
121+ // last frame wall time takes over and `now()` walks off the end
122+ // of the timeline for as long as the window is left open -- and
123+ // the playhead is what a cut, a paste, an insert and the
124+ // analyser all act at, so every one of them was aiming into
125+ // empty space (measured: a 5 s timeline recognised its end at
126+ // clock 17.5 s under a slow renderer). End of stream is left
127+ // set, so this is still `Ended` and the next press restarts.
128+ if let Some(session) = &mut self.session {
129+ session.halt_at_end();
130+ }
131+ let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64());
132+ eprintln!(
133+ "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s",
134+ self.displayed,
135+ self.dropped,
136+ self.session.as_ref().map_or(0., PlaybackSession::now)
137+ );
138+ }
139+ }
140+ }
141+
142+ /// Where the transport is, asked of the session rather than remembered:
143+ /// end of stream is the engine's own flag (any seek clears it, which is why
144+ /// an edit past the end revives the picture) and so is the clock. A held
145+ /// frame is one still owed to the screen, so the end is not the end yet.
146+ pub(crate) fn transport(&self) -> Transport {
147+ let Some(session) = &self.session else {
148+ return Transport::Stopped;
149+ };
150+ transport(
151+ session.is_playing(),
152+ session.is_eos() && self.held.is_none(),
153+ )
154+ }
155+
156+ /// A frame owed to the screen after a reseek, and the buffered one dropped:
157+ /// what stops the picture from staying frozen on the old last frame. The
158+ /// end-of-stream flag itself is the engine's and its own seek clears it --
159+ /// edits reseek inside the engine and still owe this.
160+ pub(crate) fn reset_after_reseek(&mut self) {
161+ self.held = None;
162+ // Restarted on every reseek, not only on the first: what it measures is
163+ // the open now standing, which is what a person is waiting on.
164+ self.seek_since = Some(Instant::now());
165+ // A seek is a person saying where to look, so it takes the view back
166+ // from an earlier scroll: the frame asked for is the one to be shown.
167+ self.panned = false;
168+ // An edit moves the indices a drag in flight is holding -- a stroke
169+ // during one is exactly that -- and an edge committed against a moved
170+ // index would trim a clip nobody grabbed. Dropping it is the whole fix:
171+ // nothing has been written yet.
172+ self.trim = None;
173+ // ...and the shadow a drag is drawn under promises a landing on a lane
174+ // this edit has just reshaped. The next move of the drag draws it
175+ // again; until then it says nothing.
176+ self.ghost = None;
177+ }
178+
179+ /// Jumps the timeline.
180+ pub(crate) fn seek(&mut self, t: f64, cx: &mut Context<Self>) {
181+ if self.exporting().is_some() {
182+ return;
183+ }
184+ let Some(session) = &mut self.session else {
185+ return;
186+ };
187+ session.seek(t);
188+ self.reset_after_reseek();
189+ cx.notify();
190+ }
191+
192+ /// The keyboard's seek: whole frames along the timeline, through the same
193+ /// door a ruler click uses -- so a step while playing keeps playing, exactly
194+ /// as a click does. It starts from the frame the transport is showing, which
195+ /// past the end is the last one, and that is what lets a step back off EOS
196+ /// revive the picture (the engine's seek leaves [`Transport::Ended`]). Both
197+ /// ends clamp, so the two go-to actions are this same step asked for more
198+ /// frames than the timeline has. Selection is untouched: a seek is not an
199+ /// edit, and nothing it does moves a clip index.
200+ pub(crate) fn step(&mut self, frames: i64, cx: &mut Context<Self>) {
201+ let ended = self.transport() == Transport::Ended;
202+ let Some(session) = &self.session else {
203+ return;
204+ };
205+ let last = ((session.timeline_duration() * self.fps).round() as i64 - 1).max(0);
206+ let now = match ended {
207+ true => last,
208+ false => i64::from(frame_at(session.now(), self.fps)),
209+ };
210+ let target = now.saturating_add(frames).clamp(0, last);
211+ self.seek(target as f64 / self.fps, cx);
212+ }
213+
214+ /// Seeks to where the pointer sits along the ruler. `commit` is the press
215+ /// and the release, which must land exactly even when the throttle below
216+ /// would have skipped them.
217+ pub(crate) fn scrub_to(&mut self, x: Pixels, commit: bool, cx: &mut Context<Self>) {
218+ let Some(session) = &self.session else {
219+ return;
220+ };
221+ // Clamped to the timeline here rather than in the mapping: there is bed
222+ // past the last frame now, and a seek out there is a seek to the end.
223+ let t = self
224+ .scale
225+ .time_at(px_along(x, self.ruler.get()))
226+ .clamp(0., session.timeline_duration());
227+ let target = (t * self.fps) as u32;
228+ if commit || scrub_due(target, self.last_target, self.last_scrub.elapsed()) {
229+ self.last_target = target;
230+ self.last_scrub = Instant::now();
231+ self.seek(t, cx);
232+ }
233+ }
234+
235+ /// The play binding and the transport button share it: once the timeline is finished
236+ /// the only sensible "play" is from the top.
237+ /// Pushes the current volume at the session, which is the only place it is
238+ /// ever pushed: after a change here, and after a session arrives. A session
239+ /// starts at full volume, so a file opened while muted has to be told --
240+ /// that is the whole reason this is not just called from the key handler.
241+ /// Silent no-op with no timeline, or with a run that has no audio device.
242+ pub(crate) fn apply_volume(&self) {
243+ if let Some(session) = &self.session {
244+ session.set_gain(self.volume.gain());
245+ }
246+ }
247+
248+ /// The mute key and the two volume keys, and the click on the button. The
249+ /// picture is not touched: silencing the output is not pausing it, so the
250+ /// clock -- which the device still drives -- runs straight through.
251+ pub(crate) fn set_volume(&mut self, change: impl FnOnce(&mut Volume), cx: &mut Context<Self>) {
252+ change(&mut self.volume);
253+ self.apply_volume();
254+ cx.notify();
255+ }
256+
257+ /// Where the pointer sits along the slider, as a level. The press and every
258+ /// sample after it come here, so the sound follows the hand rather than the
259+ /// release -- there is nothing to undo about a monitoring level, which is
260+ /// why this writes live and keeps no gesture state beyond the flag.
261+ pub(crate) fn drag_volume(&mut self, x: Pixels, cx: &mut Context<Self>) {
262+ let along = frac_along(x, self.volume_bar.get());
263+ self.set_volume(|volume| volume.set_along(along), cx);
264+ }
265+
266+ pub(crate) fn toggle_or_restart(&mut self, cx: &mut Context<Self>) {
267+ if self.exporting().is_some() {
268+ return;
269+ }
270+ // Nothing to play is a message, not a transport state. An empty
271+ // timeline is [`Transport::Ended`] from its one black frame onward, so
272+ // the restart below would start a clock against a zero-length timeline
273+ // -- and it is Ended again by the next repaint, so no later press could
274+ // ever stop it: the button would read "Pause" and never pause. A delete
275+ // can empty the timeline mid-play, and that press must still stop it.
276+ if nothing_to_play(self.session.as_ref()) {
277+ match self.session.as_mut().filter(|s| s.is_playing()) {
278+ Some(session) => session.pause(),
279+ None => self.notify_user(NOTHING_TO_PLAY.into()),
280+ }
281+ cx.notify();
282+ return;
283+ }
284+ // Pressing play is asking to watch, so a view scrolled away while
285+ // paused comes back to the head with it -- as a seek's does.
286+ self.panned = false;
287+ match self.transport() {
288+ // Nothing open: the button is dimmed and the key says nothing.
289+ Transport::Stopped => {}
290+ // Back to the top and away, for the key and the button alike --
291+ // whichever asked, the transport was showing Play.
292+ state if state.restarts() => {
293+ self.seek(0., cx);
294+ if let Some(session) = &mut self.session {
295+ session.play();
296+ }
297+ }
298+ _ => {
299+ if let Some(session) = &mut self.session {
300+ session.toggle();
301+ // A paused timeline animates nothing; this is the repaint
302+ // that puts the new glyph up.
303+ cx.notify();
304+ }
305+ }
306+ }
307+ }
308+}
crates/app/src/player/view.rsadded+204 -0
@@ -0,0 +1,204 @@
1+//! What of the timeline is on the bed and what of it is picked: the zoom,
2+//! the scroll and the selection.
3+
4+use crate::*;
5+
6+impl Player {
7+ /// The one place a clip becomes *the* selected one: a click, a right-click
8+ /// that opens the menu, and every selection key go through here, so what a
9+ /// keyboard marks and what a pointer marks are the same state marked the
10+ /// same way (group and all -- see [`marked`]).
11+ pub(crate) fn select(&mut self, target: (Lane, usize), cx: &mut Context<Self>) {
12+ self.selected = Some(target);
13+ cx.notify();
14+ }
15+
16+ /// Every clip the playhead is over, one per lane, in the order the lanes are
17+ /// drawn -- video first, which is the order [`PlaybackSession::lanes`] comes
18+ /// in. What the select key walks.
19+ pub(crate) fn under_playhead(&self) -> Vec<(Lane, usize)> {
20+ let Some(session) = &self.session else {
21+ return Vec::new();
22+ };
23+ let now = session.now();
24+ session
25+ .lanes()
26+ .into_iter()
27+ .filter_map(|lane| Some((lane, session.lane_clip_at(lane, now)?)))
28+ .collect()
29+ }
30+
31+ /// Selects the clip under the playhead, and on a repeat press the next
32+ /// lane's -- so one key reaches every clip the playhead is over, which is
33+ /// what makes selection (and everything that acts on a selection: delete,
34+ /// lift, the equalizer, the grade) reachable with no pointer at all.
35+ pub(crate) fn select_under_playhead(&mut self, cx: &mut Context<Self>) {
36+ let under = self.under_playhead();
37+ let Some(&first) = under.first() else {
38+ self.notify_user("NOTHING UNDER THE PLAYHEAD — move it onto a clip first".into());
39+ cx.notify();
40+ return;
41+ };
42+ // Where the current selection sits in that walk decides what "again"
43+ // means; a selection off the playhead starts the walk over.
44+ let next = self
45+ .selected
46+ .and_then(|sel| under.iter().position(|&clip| clip == sel))
47+ .map_or(first, |at| under[(at + 1) % under.len()]);
48+ self.select(next, cx);
49+ }
50+
51+ /// Walks the selection along its own lane, wrapping at either end. Nothing
52+ /// selected means nothing to walk from, so it selects under the playhead
53+ /// exactly as the select key does: either key can start as well as continue.
54+ pub(crate) fn select_step(&mut self, forward: bool, cx: &mut Context<Self>) {
55+ let clips = self
56+ .selected
57+ .zip(self.session.as_ref())
58+ .map_or(0, |((lane, _), session)| session.lane_clips(lane).len());
59+ match (self.selected, clips) {
60+ // An empty lane is a selection nothing can be stepped from -- as is
61+ // no selection at all, and the playhead answers both.
62+ (Some((lane, idx)), len) if len > 0 => {
63+ let next = if forward {
64+ (idx + 1) % len
65+ } else {
66+ (idx + len - 1) % len
67+ };
68+ self.select((lane, next), cx);
69+ }
70+ _ => self.select_under_playhead(cx),
71+ }
72+ }
73+
74+ /// Cycles the fit policy of the clip the picture is coming from -- the
75+ /// clicked one when it is a video clip, else the composite's own, exactly as
76+ /// the colour card picks its target. A whole card for one four-valued
77+ /// setting would be a card to close; a stroke that cycles it and says what
78+ /// it landed on is the same setting with nothing to dismiss.
79+ ///
80+ /// Only means anything when the clip is not the project's size -- a clip
81+ /// that already fills the canvas looks the same under all four -- so the
82+ /// notice says the size it is placing, not just the word.
83+ pub(crate) fn cycle_fit(&mut self, cx: &mut Context<Self>) {
84+ if self.exporting().is_some() {
85+ return;
86+ }
87+ let Some(session) = &mut self.session else {
88+ self.notify_user("no timeline to fit — open a file first".into());
89+ cx.notify();
90+ return;
91+ };
92+ let target = self
93+ .selected
94+ .filter(|(lane, _)| lane.kind == LaneKind::Video)
95+ .or_else(|| session.video_clip_at(session.now()));
96+ let Some((lane, idx)) = target else {
97+ self.notify_user("no clip under the playhead to fit".into());
98+ cx.notify();
99+ return;
100+ };
101+ let next = next_fit(session.fit_of(lane, idx));
102+ self.apply_fit(lane, idx, next, cx);
103+ }
104+
105+ /// One clip's fit policy set, whichever asked: the stroke that steps to the
106+ /// next one and the list that names one outright come through here, so they
107+ /// cannot differ in what they do or in what they say they did.
108+ pub(crate) fn apply_fit(&mut self, lane: Lane, idx: usize, fit: FitPolicy, cx: &mut Context<Self>) {
109+ if let Some(session) = &mut self.session
110+ && session.set_fit(lane, idx, fit)
111+ {
112+ let (w, h) = session.resolution();
113+ self.notify_user(format!("FIT POLICY: {} on {w}x{h}", fit_label(fit)).into());
114+ self.reset_after_reseek();
115+ }
116+ cx.notify();
117+ }
118+
119+ /// The scale against the bed it is drawn on and the timeline it is drawn
120+ /// from: every clamp, zoom and scroll is worked out through this, and the
121+ /// bed is measured off the ruler's probe rather than remembered, so a
122+ /// resized window is a resized view on the very next answer.
123+ pub(crate) fn view(&self) -> View {
124+ View {
125+ scale: self.scale,
126+ bed: f32::from(self.ruler.get().size.width),
127+ duration: self.drawn_duration(),
128+ fps: self.fps,
129+ }
130+ }
131+
132+ /// Magnifies the timeline about a point that stays put: `anchor` is how many
133+ /// pixels along the bed to hold still (a ctrl+wheel holds the pointer), and
134+ /// with none it is the playhead -- so the frame being worked on is still the
135+ /// frame on screen after the zoom. Clamped at both ends by [`View`]: out
136+ /// stops at the whole timeline on the bed, in at a handful of frames.
137+ pub(crate) fn zoom(&mut self, factor: f32, anchor: Option<f32>, cx: &mut Context<Self>) {
138+ let view = self.view();
139+ let at = self.playhead(view.duration);
140+ let anchor = anchor.unwrap_or_else(|| self.scale.px_at(at).clamp(0., view.bed));
141+ self.scale = view.zoomed(factor, anchor);
142+ // The view a hand chose. A zoom about the playhead leaves it on the
143+ // bed, so this is given back on the very next frame and only a zoom
144+ // that took the head off screen -- ctrl+wheel away from it -- holds.
145+ self.panned = true;
146+ cx.notify();
147+ }
148+
149+ /// All the way back out: the whole timeline across the bed, and the one
150+ /// thing that reads the timeline's own length to decide how wide a second
151+ /// is drawn.
152+ pub(crate) fn zoom_fit(&mut self, cx: &mut Context<Self>) {
153+ self.scale = self.view().fit();
154+ cx.notify();
155+ }
156+
157+ /// Slides the view along the timeline by `notches` of the wheel, later in
158+ /// time for a positive one and [`SCROLL_NOTCH_SHARE`] of the bed each. The
159+ /// scale is untouched: this is the timeline's scrollbar, and the only thing
160+ /// on the panel that moves what is on screen without magnifying it.
161+ pub(crate) fn scroll_view(&mut self, notches: f32, cx: &mut Context<Self>) {
162+ let view = self.view();
163+ // Nothing painted yet: there is no bed to measure a notch against, and
164+ // a start moved against a zero width would be a jump to the head.
165+ if view.bed <= 0. {
166+ return;
167+ }
168+ self.scale = view.scrolled(notches * view.bed * SCROLL_NOTCH_SHARE);
169+ // The one gesture whose whole purpose is to look away from the
170+ // playhead: while playing it wins over the follow, which is what every
171+ // editor does with a scroll during playback.
172+ self.panned = true;
173+ cx.notify();
174+ }
175+
176+ /// One notch of the wheel anywhere over the timeline -- the ruler or a
177+ /// lane's bed alike, since a hand aims at the clip it is working on and not
178+ /// at the strip above it. Ctrl zooms about the pointer, bare scrolls the
179+ /// view along: the mapping Premiere, Movavi and CapCut share, and the one
180+ /// the user named.
181+ ///
182+ /// The anchor is measured off the ruler's probe wherever the pointer is,
183+ /// because that probe *is* the bed's x-to-time mapping ([`HEADER_W`]) and
184+ /// every lane is drawn through the same one.
185+ pub(crate) fn timeline_wheel(&mut self, event: &ScrollWheelEvent, cx: &mut Context<Self>) {
186+ let d = wheel_delta(event);
187+ if d == 0. {
188+ return;
189+ }
190+ let factor = match d > 0. {
191+ true => ZOOM_STEP,
192+ false => 1. / ZOOM_STEP,
193+ };
194+ match event.modifiers.control {
195+ true => {
196+ let anchor = px_along(event.position.x, self.ruler.get());
197+ self.zoom(factor, Some(anchor), cx);
198+ }
199+ // Up is back towards the head of the timeline, the way a wheel up
200+ // is back towards the top of a page.
201+ false => self.scroll_view(-d.signum(), cx),
202+ }
203+ }
204+}