From 5231711ccc82c562c71aa7e0a897a4c078254a7c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 19 Aug 2026 20:45:42 +0300 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20feat(app):=20a=20library=20row=20pr?= =?UTF-8?q?eviews=20its=20file=20over=20the=20timeline?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A row's ▶ button (and esc, or the banner's own Stop) opens the file in place of the picture without touching the edit's own playhead or undo stack: PlaybackSession::open already builds exactly this session, so the pump, transport, seek, step, volume and end-of-stream handling all route through a new active_session()/active_session_mut() that reads the preview while one is up and the timeline otherwise. --- crates/app/src/main.rs | 13 +++ crates/app/src/player/actions.rs | 2 +- crates/app/src/player/library.rs | 64 ++++++++++++++ crates/app/src/player/transport.rs | 61 +++++++++---- crates/app/src/render.rs | 8 ++ crates/app/src/tests/media.rs | 28 ++++++ crates/app/src/ui/library.rs | 30 ++++++- crates/app/src/ui/preview.rs | 134 +++++++++++++++++++++++++++++ 8 files changed, 322 insertions(+), 18 deletions(-) diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 111eeb6..4317451 100644 --- a/crates/app/src/main.rs +++ b/crates/app/src/main.rs @@ -73,6 +73,17 @@ struct Player { /// waits: the first media import or project load is what fills it, and /// until then every action that needs a timeline says so instead of acting. session: Option, + /// A library row's own file, opened and playing in place of the + /// timeline's picture, and never written to `session` or its undo stack: + /// a preview is watched, not edited. `Some` is what [`Player::pump`] and + /// [`Player::transport`] read first -- the timeline's own session and its + /// silence scan sit untouched underneath until this clears again + /// ([`Player::close_preview`]). + preview_session: Option, + /// Whether the timeline was playing when a preview took it over + /// ([`Player::open_preview`] pauses it so the two sounds never overlap): + /// what [`Player::close_preview`] resumes, and only then. + preview_playing: bool, /// Timeline seconds -> frame index, so the clock can be compared to what /// the decoder hands over. fps: f64, @@ -647,6 +658,8 @@ fn main() { seek_since: None, resynced: None, session: None, + preview_session: None, + preview_playing: false, // Full and unmuted, which is what the session it was just // handed is already set to: nothing to push at startup. volume: Volume::default(), diff --git a/crates/app/src/player/actions.rs b/crates/app/src/player/actions.rs index 3cdc351..d979b5e 100644 --- a/crates/app/src/player/actions.rs +++ b/crates/app/src/player/actions.rs @@ -252,7 +252,7 @@ impl Player { timeline: true, clipboard: self.clipboard.is_some(), subtitles: !session.subtitles().is_empty(), - playable: !nothing_to_play(Some(session)), + playable: !nothing_to_play(self.active_session()), exporting: self.exporting().is_some(), picks: picks.len(), pick_lanes, diff --git a/crates/app/src/player/library.rs b/crates/app/src/player/library.rs index 82b6332..a8a278d 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -191,6 +191,70 @@ impl Player { self.seek_since = None; } + /// The row's own play button: opens `path` as a session of its own and + /// shows it in place of the timeline's picture, without moving the + /// timeline's playhead or touching its undo stack -- what a library + /// preview is. [`PlaybackSession::open`] already builds exactly this (a + /// one-clip session, ungraded, passthrough), so nothing new is asked of + /// the engine. + /// + /// corner-cut: opens the file's own first audio stream rather than the + /// row's particular one -- `PlaybackSession::open` takes no stream + /// argument. Ceiling: a remux with several audio tracks previews on its + /// first. Upgrade path: an engine door that opens a chosen stream. + pub(crate) fn open_preview(&mut self, path: &std::path::Path, cx: &mut Context) { + if self.exporting().is_some() { + return; + } + // The timeline would otherwise keep playing under the preview -- two + // soundtracks at once -- so it is paused here and resumed on the way + // out only if this is what paused it ([`Player::close_preview`]). + self.preview_playing = self.session.as_ref().is_some_and(PlaybackSession::is_playing); + if let Some(session) = self.session.as_mut() { + session.pause(); + } + match PlaybackSession::open(path) { + Ok(mut session) => { + session.drop_late_pictures(true); + session.set_gain(self.volume.gain()); + self.preview_session = Some(session); + self.notify_user( + format!("PREVIEWING {} — not on the timeline; esc stops it", file_name(path)) + .into(), + ); + } + Err(e) => self.notify_user(format!("PREVIEW FAILED: {e}").into()), + } + self.reset_after_reseek(); + cx.notify(); + } + + /// The way out of a preview: `esc`, or the banner's own button. The + /// timeline was never pumped while the preview played, so its picture is + /// stale where it left off -- a reseek to the position it is already at + /// is what brings a fresh frame back, exactly as loading a project does. + pub(crate) fn close_preview(&mut self, cx: &mut Context) { + if self.preview_session.take().is_none() { + return; + } + self.notify_user("PREVIEW STOPPED — back to the timeline".into()); + match self.session.as_ref().map(PlaybackSession::now) { + Some(now) => { + self.seek(now, cx); + if self.preview_playing { + if let Some(session) = self.session.as_mut() { + session.play(); + } + } + } + None => { + self.image = None; + cx.notify(); + } + } + self.preview_playing = false; + } + /// The rate and layout the whole timeline's audio is, taken from the stream /// of the first source that could have one: what a library row has to match /// to be placeable. `None` until that file has been probed, and then nothing diff --git a/crates/app/src/player/transport.rs b/crates/app/src/player/transport.rs index f5a5529..8ff02bd 100644 --- a/crates/app/src/player/transport.rs +++ b/crates/app/src/player/transport.rs @@ -4,6 +4,27 @@ use crate::*; impl Player { + /// The session the transport, the pump and the clock all read: the + /// preview while one is showing, the timeline otherwise -- never both, so + /// a preview is watched without moving the edit's own playhead. See + /// [`preview_session`](Player) for what stays untouched underneath. + pub(crate) fn active_session(&self) -> Option<&PlaybackSession> { + self.preview_session.as_ref().or(self.session.as_ref()) + } + + pub(crate) fn active_session_mut(&mut self) -> Option<&mut PlaybackSession> { + self.preview_session.as_mut().or(self.session.as_mut()) + } + + /// The active session's own frame rate rather than the timeline's: a + /// preview of a file shot at another rate clocks and steps at *its* rate, + /// not the edit's. + pub(crate) fn active_fps(&self) -> f64 { + self.preview_session + .as_ref() + .map_or(self.fps, |s| s.meta().frame_rate) + } + /// Catches the display up to the clock: everything already due is taken off /// the channel and only the last of them is shown, which *is* the /// drop-when-behind policy. A frame that is not due yet waits in `held`, and @@ -13,9 +34,16 @@ impl Player { // Where the transport was before this drain, so the crossing into // `Ended` can be recognised as the one transition it is. let was = self.transport(); + let fps = self.active_fps(); // No timeline, nothing to catch up to: the window is showing its empty // state and there is no decoder to drain. - let Some(session) = &mut self.session else { + // A direct field borrow rather than the `active_session_mut` helper: the + // rest of this function reads and writes other fields on `self` + // (`held`, `seek_since`, `dropped`, `displayed`, ...) alongside + // `session`, and only a borrow of the two Option fields themselves -- + // not a call through a `&mut self` method -- lets the borrow checker + // see those as disjoint. + let Some(session) = self.preview_session.as_mut().or(self.session.as_mut()) else { return; }; // Whether the span now decoding has yet to hand over a picture, read @@ -24,7 +52,7 @@ impl Player { // reopen took -- is exactly what the resync below must not answer with // another reopen. let priming = session.picture_priming(); - let target = session.now() * self.fps; + let target = session.now() * fps; let mut newest: Option = None; // A frame the screen is owed: a seek's landing, and the one readiness // signal there is ([`Player::reset_after_reseek`]). @@ -66,7 +94,7 @@ impl Player { // waiting on. let late = newest .as_ref() - .map_or(0., |f| (target - f64::from(f.index)) / self.fps); + .map_or(0., |f| (target - f64::from(f.index)) / fps); if let Some(frame) = newest { self.displayed += 1; @@ -137,7 +165,7 @@ impl Player { // empty space (measured: a 5 s timeline recognised its end at // clock 17.5 s under a slow renderer). End of stream is left // set, so this is still `Ended` and the next press restarts. - if let Some(session) = &mut self.session { + if let Some(session) = self.active_session_mut() { session.halt_at_end(); } let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64()); @@ -145,7 +173,7 @@ impl Player { "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s", self.displayed, self.dropped, - self.session.as_ref().map_or(0., PlaybackSession::now) + self.active_session().map_or(0., PlaybackSession::now) ); } } @@ -156,7 +184,7 @@ impl Player { /// an edit past the end revives the picture) and so is the clock. A held /// frame is one still owed to the screen, so the end is not the end yet. pub(crate) fn transport(&self) -> Transport { - let Some(session) = &self.session else { + let Some(session) = self.active_session() else { return Transport::Stopped; }; transport( @@ -193,7 +221,7 @@ impl Player { if self.exporting().is_some() { return; } - let Some(session) = &mut self.session else { + let Some(session) = self.active_session_mut() else { return; }; session.seek(t); @@ -211,16 +239,17 @@ impl Player { /// edit, and nothing it does moves a clip index. pub(crate) fn step(&mut self, frames: i64, cx: &mut Context) { let ended = self.transport() == Transport::Ended; - let Some(session) = &self.session else { + let fps = self.active_fps(); + let Some(session) = self.active_session() else { return; }; - let last = ((session.timeline_duration() * self.fps).round() as i64 - 1).max(0); + let last = ((session.timeline_duration() * fps).round() as i64 - 1).max(0); let now = match ended { true => last, - false => i64::from(frame_at(session.now(), self.fps)), + false => i64::from(frame_at(session.now(), fps)), }; let target = now.saturating_add(frames).clamp(0, last); - self.seek(target as f64 / self.fps, cx); + self.seek(target as f64 / fps, cx); } /// Seeks to where the pointer sits along the ruler. `commit` is the press @@ -252,7 +281,7 @@ impl Player { /// that is the whole reason this is not just called from the key handler. /// Silent no-op with no timeline, or with a run that has no audio device. pub(crate) fn apply_volume(&self) { - if let Some(session) = &self.session { + if let Some(session) = self.active_session() { session.set_gain(self.volume.gain()); } } @@ -285,8 +314,8 @@ impl Player { // -- and it is Ended again by the next repaint, so no later press could // ever stop it: the button would read "Pause" and never pause. A delete // can empty the timeline mid-play, and that press must still stop it. - if nothing_to_play(self.session.as_ref()) { - match self.session.as_mut().filter(|s| s.is_playing()) { + if nothing_to_play(self.active_session()) { + match self.active_session_mut().filter(|s| s.is_playing()) { Some(session) => session.pause(), None => self.notify_user(NOTHING_TO_PLAY.into()), } @@ -303,12 +332,12 @@ impl Player { // whichever asked, the transport was showing Play. state if state.restarts() => { self.seek(0., cx); - if let Some(session) = &mut self.session { + if let Some(session) = self.active_session_mut() { session.play(); } } _ => { - if let Some(session) = &mut self.session { + if let Some(session) = self.active_session_mut() { session.toggle(); // A paused timeline animates nothing; this is the repaint // that puts the new glyph up. diff --git a/crates/app/src/render.rs b/crates/app/src/render.rs index ed76d46..29f334f 100644 --- a/crates/app/src/render.rs +++ b/crates/app/src/render.rs @@ -461,6 +461,13 @@ impl Render for Player { return; } } + // The innermost thing left on screen once no menu is up: a + // preview takes the picture over the timeline's own, and + // escape is its own way out, same as every card above it. + if key == ESCAPE && !ctrl && this.preview_session.is_some() { + this.close_preview(cx); + return; + } if let Some(action) = action { this.act(action, window, cx); } @@ -607,6 +614,7 @@ impl Render for Player { // After the picture, so the plate is drawn // over it rather than under. .children(self.subtitle_overlay(position, window)) + .children(self.preview_badge(cx)) // The three transient lines hang off the // bottom of the picture rather than taking // a row of the column: a notice that diff --git a/crates/app/src/tests/media.rs b/crates/app/src/tests/media.rs index cc700ba..8915b8f 100644 --- a/crates/app/src/tests/media.rs +++ b/crates/app/src/tests/media.rs @@ -1130,3 +1130,31 @@ fn exactly_one_subtitle_lane_is_shown_whatever_the_pick_and_whatever_is_left() { // A pick that is not a subtitle lane at all cannot name one either. assert_eq!(active_lane(Some(Lane::V1), &[s1, s2]), Some(s1)); } + +/// A library preview's whole point ([`Player::open_preview`], +/// [`Player::close_preview`]): the timeline's own session is untouched by +/// one showing over it. `Player` cannot be built here -- it takes a gpui +/// `Context`, which this test binary has no `TestAppContext` to hand it +/// (see the crate's other tests for the same limit) -- so this exercises +/// the two sessions `open_preview`/`close_preview` juggle directly: seeking +/// and playing one, exactly as a preview session's own life does, leaves +/// the other's position and clock exactly where they were. +#[test] +fn a_second_session_playing_never_moves_the_first() { + let mut timeline = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + timeline.seek(0.5); + let before = timeline.now(); + let before_playing = timeline.is_playing(); + + // Stands in for the preview session `open_preview` opens over it. + let mut preview = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture"); + preview.seek(1.0); + preview.play(); + + assert_eq!(timeline.now(), before, "the preview's seek moved the wrong session"); + assert_eq!( + timeline.is_playing(), + before_playing, + "the preview's play moved the wrong session" + ); +} diff --git a/crates/app/src/ui/library.rs b/crates/app/src/ui/library.rs index e57427f..50f1a3a 100644 --- a/crates/app/src/ui/library.rs +++ b/crates/app/src/ui/library.rs @@ -170,14 +170,20 @@ impl Player { // name alone was, and the detail line under it ran on under the // switch and was cut mid-word -- and an unusable row draws no switch // and so pays nothing for one. + // Two switches now sit at the end of a usable row -- the preview + // play button beside the stand-in toggle -- so the text gives up + // twice the room it gave up for one. let text_w = row_text_w(width) - match usable { - true => HIT_MIN + 6., + true => 2. * (HIT_MIN + 6.), false => 0., }; let (path, stream) = (row.path.clone(), row.stream); let dragged = (path.clone(), stream); let menu_path = path.clone(); + let preview_path = path.clone(); + let preview_tip: SharedString = + format!("Preview {} — plays it without touching the timeline", row.name).into(); div() .id(("asset", i)) .flex_none() @@ -282,6 +288,28 @@ impl Player { // the window speaks says which way it is set -- lit like a // picked row when there is one, dimmed like an unusable one // when there is not. + .when(usable, |d| { + d.child( + div() + .id(("preview-play", i)) + .flex_none() + .w(px(HIT_MIN)) + .h_full() + .flex() + .items_center() + .justify_center() + .rounded(px(3.)) + .text_size(px(11.)) + .cursor_pointer() + .hover(|s| s.bg(rgb(BG_HOVER()))) + .tooltip(move |_, cx| cx.new(|_| Tip(preview_tip.clone())).into()) + .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| { + cx.stop_propagation(); + this.open_preview(&preview_path, cx); + })) + .child("▶"), + ) + }) .when(usable, |d| { d.child( div() diff --git a/crates/app/src/ui/preview.rs b/crates/app/src/ui/preview.rs index 9f5171e..b38daa3 100644 --- a/crates/app/src/ui/preview.rs +++ b/crates/app/src/ui/preview.rs @@ -1,8 +1,80 @@ //! The picture: what is drawn over it and what is read off it. use crate::*; +use std::path::{Path, PathBuf}; impl Player { + /// The one thing that says a preview is up rather than the timeline: a + /// banner over the top of the picture, and a click of its own -- the + /// keyboard has `esc`, and a hand with only a mouse needs a way out too. + pub(crate) fn preview_badge(&self, cx: &mut Context) -> Option { + self.preview_session.is_some().then(|| { + div() + .absolute() + .top_0() + .left_0() + .right_0() + .flex() + .items_center() + .justify_center() + .gap(px(8.)) + .p(px(4.)) + .bg(rgba(SUB_SHADE())) + .text_size(px(11.)) + .text_color(rgb(FG_PRIMARY())) + .child("PREVIEW — not on the timeline") + .child( + div() + .id("preview-stop") + .px(px(6.)) + .rounded(px(3.)) + .cursor_pointer() + .bg(rgb(BG_RAISED())) + .hover(|s| s.bg(rgb(BG_HOVER()))) + .on_click(cx.listener(|this, _: &ClickEvent, _, cx| this.close_preview(cx))) + .child("Stop (esc)"), + ) + }) + } + + /// The frame on screen right now, written to a PNG: `image` and its + /// `as_bytes` are gpui's own cached copy of what was last handed to the + /// atlas ([`Player::pump`]), so this reads no decoder and races nothing -- + /// works during preview or on the timeline, whichever is showing. + pub(crate) fn take_screenshot(&mut self, cx: &mut Context) { + let no_frame = || "NO FRAME TO SAVE — nothing is showing yet".to_string(); + let Some(image) = self.image.clone() else { + self.notify_user(no_frame().into()); + cx.notify(); + return; + }; + let Some(bytes) = image.as_bytes(0) else { + self.notify_user(no_frame().into()); + cx.notify(); + return; + }; + let size = image.size(0); + let stem = self + .active_session() + .and_then(|s| s.sources().first()) + .map_or_else(|| self.name.to_string(), |s| file_name(&s.path)); + let stem = std::path::Path::new(&stem) + .file_stem() + .map_or(stem.clone(), |s| s.to_string_lossy().into_owned()); + let tc = timecode( + self.active_session().map_or(0., PlaybackSession::now), + self.active_fps(), + ) + .replace(':', "-"); + let text = match save_screenshot(bytes, size.width.0 as u32, size.height.0 as u32, &stem, &tc) + { + Ok(path) => format!("SAVED {}", path.display()), + Err(e) => format!("SCREENSHOT FAILED: {e}"), + }; + self.notify_user(text.into()); + cx.notify(); + } + /// The cues the *subtitle lanes* put on screen at `at`, over the picture and /// nothing else: bottom-centred where every player puts them, white on a /// plate so the film underneath cannot swallow them, and each cue its own @@ -201,3 +273,65 @@ impl Player { } } } + +/// `~/Pictures/edith`, or `.` with no `HOME` -- [`keymap::config_path_in`]'s +/// own fallback, for the same reason: a screenshot has to land somewhere even +/// on a machine with no desktop environment set up. +pub(crate) fn screenshots_dir() -> PathBuf { + std::env::var_os("HOME") + .map_or_else(|| PathBuf::from("."), PathBuf::from) + .join("Pictures") + .join("edith") +} + +/// Where a screenshot goes: `stem-tc.png` in `dir`, or the same name with a +/// numeric suffix if that one is already taken -- a screenshot never +/// overwrites another the way an export overwrites its own path. +pub(crate) fn screenshot_path(dir: &Path, stem: &str, tc: &str) -> PathBuf { + let base = format!("{stem}-{tc}"); + let first = dir.join(format!("{base}.png")); + if !first.exists() { + return first; + } + let mut n = 2; + loop { + let path = dir.join(format!("{base}-{n}.png")); + if !path.exists() { + return path; + } + n += 1; + } +} + +/// The swap every BGRA frame needs to become the RGBA a PNG writes: gpui's +/// atlas is BGRA with straight alpha ([`Player::sub_picture`]'s own comment), +/// and `image::save` writes RGBA. +pub(crate) fn bgra_to_rgba(bgra: &[u8]) -> Vec { + let mut out = bgra.to_vec(); + for pixel in out.chunks_exact_mut(4) { + pixel.swap(0, 2); + } + out +} + +/// Writes `bgra` (`w`x`h`, gpui's own layout) to a fresh PNG under +/// [`screenshots_dir`], creating the directory if this is the first one. +/// Never called on the render thread's own budget for more than a channel +/// swap and one `image::save` -- there is no decode here, only a copy already +/// in memory. +pub(crate) fn save_screenshot( + bgra: &[u8], + w: u32, + h: u32, + stem: &str, + tc: &str, +) -> Result { + let dir = screenshots_dir(); + std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?; + let path = screenshot_path(&dir, stem, tc); + let rgba = bgra_to_rgba(bgra); + let buf = image::RgbaImage::from_raw(w, h, rgba) + .ok_or_else(|| "frame buffer sized w*h*4".to_string())?; + buf.save(&path).map_err(|e| e.to_string())?; + Ok(path) +}