diff --git a/crates/app/src/keymap.rs b/crates/app/src/keymap.rs index abf6eea..f8fac03 100644 --- a/crates/app/src/keymap.rs +++ b/crates/app/src/keymap.rs @@ -134,11 +134,18 @@ actions! { /// toolbar's Theme button. It was a build feature once, which made it a /// choice only whoever compiled the binary could make. Theme, + /// The whole window, borderless over the screen: a player's own control, + /// on the platform's own toggle ([`gpui::Window::toggle_fullscreen`]). + Fullscreen, CancelExport, /// Opens the actions card -- the list every other action is on. A door of /// its own, because a card reachable only by a button in the panel is one a /// hand on the keyboard has to leave the keyboard for. ShowActions, + /// Saves the frame on screen to a PNG: whatever is showing, the timeline's + /// own picture or a library preview's, since both write through the one + /// `self.image` the atlas already holds. + Screenshot, } impl ActionId { @@ -197,8 +204,10 @@ impl ActionId { ActionId::ToggleProxies => "Proxies on / off for the picture", ActionId::ToggleAutoProxies => "Make proxies on import: on / off", ActionId::Theme => "Theme: the window's colours…", + ActionId::Fullscreen => "Fullscreen on / off", ActionId::CancelExport => "Cancel export", ActionId::ShowActions => "All actions and their keys…", + ActionId::Screenshot => "Save the frame on screen as a PNG", } } @@ -255,8 +264,10 @@ impl ActionId { ActionId::ToggleProxies => "toggle-proxies", ActionId::ToggleAutoProxies => "toggle-auto-proxies", ActionId::Theme => "theme", + ActionId::Fullscreen => "fullscreen", ActionId::CancelExport => "cancel-export", ActionId::ShowActions => "show-actions", + ActionId::Screenshot => "screenshot", } } @@ -317,7 +328,10 @@ impl ActionId { | ActionId::ToggleAutoProxies // ...and what the whole window is painted in: it edits nothing at // all, it is what one is looking *with*. - | ActionId::Theme => Category::View, + | ActionId::Theme + // ...and whether that window fills the screen: a way of looking, + // same as the zoom and the theme beside it. + | ActionId::Fullscreen => Category::View, ActionId::Cut | ActionId::Regroup | ActionId::Detach @@ -354,7 +368,11 @@ impl ActionId { ActionId::Save | ActionId::Export | ActionId::CancelExport - | ActionId::ShowActions => Category::File, + | ActionId::ShowActions + // It writes a file like the three above it, and touches no edit + // list -- what an export's own allow-list already means it stays + // out of, not what puts it in this heading. + | ActionId::Screenshot => Category::File, } } } @@ -908,6 +926,10 @@ impl Keymap { // it is a preference set once, not a stroke wanted under a hand // that is editing. b(ActionId::Theme, "h", true), + // Every other player's key for it, and free here: nothing in + // this table answers to "f11" (gpui lowercases the keysym + // name it gets from xkb, same as "f1" below). + b(ActionId::Fullscreen, "f11", false), // A chord, and the only escape in this table: bare `esc` is the // stroke a hand throws at anything on screen, and throwing it // at a running export used to delete an hour of encoding. The @@ -919,6 +941,9 @@ impl Keymap { // (platform.rs:880, the keysym's own name lowercased) -- and // not a letter, so it takes nothing away from the clip keys. b(ActionId::ShowActions, "f1", false), + // "w" is free entirely, bare and ctrl both -- nothing else in + // this table answers to it. + b(ActionId::Screenshot, "w", false), ], } } @@ -1182,7 +1207,9 @@ mod tests { #[test] fn every_default_stroke_reaches_its_action() { let k = Keymap::defaults(); - assert_eq!(k.entries().len(), 53); + assert_eq!(k.entries().len(), 55); + assert_eq!(k.lookup("f11", false), Some(ActionId::Fullscreen)); + assert_eq!(k.lookup("w", false), Some(ActionId::Screenshot)); assert_eq!(k.lookup("p", true), Some(ActionId::ToggleProxies)); assert_eq!(k.lookup("o", true), Some(ActionId::ToggleAutoProxies)); assert_eq!(k.lookup("f1", false), Some(ActionId::ShowActions)); diff --git a/crates/app/src/main.rs b/crates/app/src/main.rs index 1946af9..c82d272 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, @@ -669,6 +680,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/oracle.rs b/crates/app/src/oracle.rs index 60bcc7d..9f81fe0 100644 --- a/crates/app/src/oracle.rs +++ b/crates/app/src/oracle.rs @@ -98,7 +98,9 @@ pub(crate) fn enable(action: ActionId, ctx: Ctx) -> Enable { // The window's own colours: there is always a window, and repainting it // touches no timeline -- so this one is live even while an export is // reading one, which is the only state that dims the list above. - if action == ActionId::Theme { + // ...and whether that window fills the screen: also always there, also + // touching no timeline, live through an export the same way. + if action == ActionId::Theme || action == ActionId::Fullscreen { return Enable::Yes; } if action == ActionId::ShowActions { diff --git a/crates/app/src/player/actions.rs b/crates/app/src/player/actions.rs index f1b34b6..b467af0 100644 --- a/crates/app/src/player/actions.rs +++ b/crates/app/src/player/actions.rs @@ -7,7 +7,7 @@ impl Player { /// What an action does, wherever it was asked for -- a stroke, or the clip /// menu item that names the same action. One table, so the two can never /// come to mean different things. - pub(crate) fn act(&mut self, action: ActionId, cx: &mut Context) { + pub(crate) fn act(&mut self, action: ActionId, window: &mut Window, cx: &mut Context) { // Two doors, one oracle. This used to be the asymmetry the whole // toolbar was built on: the buttons dimmed themselves off // [`enable`] while the keyboard walked straight past it, so with no @@ -97,10 +97,15 @@ impl Player { // At the window's corner, since a stroke names no place -- and // [`menu_at`] keeps it on screen from there. ActionId::Theme => self.open_picker(Pick::Theme, Point::default(), cx), + // The platform's own toggle (gpui::Window::toggle_fullscreen); the + // window reports its own new state back through `is_fullscreen`, + // there is no local bool to keep in step with it. + ActionId::Fullscreen => window.toggle_fullscreen(), // Nothing to cancel while nothing is exporting; the export guard in // the key handler is what answers this one while there is. ActionId::CancelExport => {} ActionId::ShowActions => self.show_actions(cx), + ActionId::Screenshot => self.take_screenshot(cx), } } @@ -248,7 +253,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 d83bc9e..14a138a 100644 --- a/crates/app/src/player/library.rs +++ b/crates/app/src/player/library.rs @@ -207,6 +207,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 f72a78d..d3e1c9a 100644 --- a/crates/app/src/render.rs +++ b/crates/app/src/render.rs @@ -95,7 +95,7 @@ impl Render for Player { div() .track_focus(&self.focus) - .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| { + .on_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| { let key = event.keystroke.key.as_str(); let ctrl = event.keystroke.modifiers.control; // `is_held` is the auto-repeat, and a value is the one thing @@ -474,8 +474,15 @@ 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, cx); + this.act(action, window, cx); } })) // The whole window is the drop target: gpui turns an external file @@ -561,7 +568,7 @@ impl Render for Player { // it. Nothing here moves when the state changes -- the regions are // fixed and the panels keep their room whether or not anything is // open in them. - .child(self.topbar(cx)) + .child(self.topbar(window, cx)) .child( div() .flex_1() @@ -619,6 +626,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/editing.rs b/crates/app/src/tests/editing.rs index 49974ac..67fcfed 100644 --- a/crates/app/src/tests/editing.rs +++ b/crates/app/src/tests/editing.rs @@ -884,9 +884,13 @@ fn the_clip_menu_dims_what_the_playhead_is_not_on_and_stays_in_the_window() { for action in ActionId::ALL { // Nothing may touch the edit list while an export is reading it -- // and the palette does not: it repaints this window and writes one - // word to the user's own config file, which is why it is the one - // action besides the cancel that stays live here. - let allowed = action == ActionId::CancelExport || action == ActionId::Theme; + // word to the user's own config file, which is why it is one of the + // actions besides the cancel that stay live here. Fullscreen is the + // same kind of thing: the platform's own window toggle, touching no + // edit list either. + let allowed = action == ActionId::CancelExport + || action == ActionId::Theme + || action == ActionId::Fullscreen; assert_eq!( whole(action, busy).yes(), allowed, diff --git a/crates/app/src/tests/media.rs b/crates/app/src/tests/media.rs index c7b0e0f..78a9938 100644 --- a/crates/app/src/tests/media.rs +++ b/crates/app/src/tests/media.rs @@ -2,6 +2,7 @@ //! command line, the scans, the codecs offered, and the subtitles found. use super::*; +use crate::ui::preview::{bgra_to_rgba, screenshot_path}; /// The import line's own state machine, driven the way a repaint drives /// it: the worker writes a stage, the poll notices it changed and restarts @@ -1184,3 +1185,85 @@ 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" + ); +} + +/// [`bgra_to_rgba`] and [`save_screenshot`]'s own PNG write, round-tripped: a +/// synthetic 2x2 frame -- one pixel per corner, alpha and channel order all +/// distinct -- decodes back to the same pixels a viewer would see, in RGBA. +#[test] +fn a_screenshot_frame_round_trips_through_its_png() { + // BGRA, gpui's own layout: red top-left, green top-right, blue + // bottom-left, and a half-alpha white bottom-right. + #[rustfmt::skip] + let bgra: Vec = vec![ + 0, 0, 255, 255, 0, 255, 0, 255, + 255, 0, 0, 255, 255, 255, 255, 128, + ]; + let rgba = bgra_to_rgba(&bgra); + assert_eq!(rgba[0..4], [255, 0, 0, 255], "red survives the channel swap"); + assert_eq!(rgba[4..8], [0, 255, 0, 255], "green is unmoved by the swap"); + assert_eq!(rgba[8..12], [0, 0, 255, 255], "blue swaps into place"); + assert_eq!(rgba[12..16], [255, 255, 255, 128], "alpha is untouched"); + + let dir = std::env::temp_dir().join(format!("edith-screenshot-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("scratch dir"); + let path = dir.join("roundtrip.png"); + let buf = image::RgbaImage::from_raw(2, 2, rgba.clone()).expect("2x2 rgba buffer"); + buf.save(&path).expect("png write"); + let decoded = image::open(&path).expect("png read").to_rgba8(); + assert_eq!(decoded.into_raw(), rgba, "the PNG round-trips the pixels exactly"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// [`screenshot_path`]'s no-clobber rule: the same stem and timecode taken +/// twice in a row lands on `-2`, and a third time on `-3` -- a screenshot +/// never overwrites the one before it, unlike an export's own path. +#[test] +fn a_repeated_screenshot_name_gets_a_numeric_suffix() { + let dir = std::env::temp_dir().join(format!("edith-screenshot-suffix-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("scratch dir"); + + let first = screenshot_path(&dir, "A Film", "00-01-02"); + assert_eq!(first, dir.join("A Film-00-01-02.png")); + std::fs::write(&first, b"stand-in for a PNG").expect("write the first"); + + let second = screenshot_path(&dir, "A Film", "00-01-02"); + assert_eq!(second, dir.join("A Film-00-01-02-2.png")); + std::fs::write(&second, b"stand-in for a PNG").expect("write the second"); + + let third = screenshot_path(&dir, "A Film", "00-01-02"); + assert_eq!(third, dir.join("A Film-00-01-02-3.png")); + + // A different timecode never collides with either of the above. + let elsewhere = screenshot_path(&dir, "A Film", "00-01-03"); + assert_eq!(elsewhere, dir.join("A Film-00-01-03.png")); + + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/app/src/ui/library.rs b/crates/app/src/ui/library.rs index 0e22828..0e3b07d 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/overlays.rs b/crates/app/src/ui/overlays.rs index 15def03..9d9b817 100644 --- a/crates/app/src/ui/overlays.rs +++ b/crates/app/src/ui/overlays.rs @@ -304,14 +304,14 @@ impl Player { .when(!refusal.yes(), |d| d.opacity(0.4).cursor_not_allowed()) .when(refusal.yes(), |d| { d.cursor_pointer().hover(|s| s.bg(rgb(BG_HOVER()))).on_click( - cx.listener(move |this, _: &ClickEvent, _, cx| { + cx.listener(move |this, _: &ClickEvent, window, cx| { // The card goes first: several of // these open a card of their own, // and every edit moves the indices // the menus are holding. this.keys_open = false; this.rebinding = None; - this.act(action, cx); + this.act(action, window, cx); cx.notify(); }), ) @@ -578,7 +578,7 @@ impl Player { .when(enabled, |d| { d.cursor_pointer() .hover(|s| s.bg(rgb(BG_HOVER()))) - .on_click(cx.listener(move |this, event: &ClickEvent, _, cx| { + .on_click(cx.listener(move |this, event: &ClickEvent, window, cx| { // Closed first: the action moves the very // indices this menu is holding. this.context_menu = None; @@ -594,7 +594,7 @@ impl Player { cx, ); } else { - this.act(action, cx); + this.act(action, window, cx); } })) }) 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) +} diff --git a/crates/app/src/ui/toolbar.rs b/crates/app/src/ui/toolbar.rs index 47a7be4..687bb21 100644 --- a/crates/app/src/ui/toolbar.rs +++ b/crates/app/src/ui/toolbar.rs @@ -49,8 +49,9 @@ impl Player { /// write a file on the right. Export is the one accented button in the /// window -- the primary action of an editor, where every consumer editor /// puts it -- and it keeps its rect while it is a Cancel. - pub(crate) fn topbar(&self, cx: &mut Context) -> impl IntoElement { + pub(crate) fn topbar(&self, window: &mut Window, cx: &mut Context) -> impl IntoElement { let exporting = self.exporting().is_some(); + let fullscreen = window.is_fullscreen(); div() .flex_none() .h(px(TOPBAR_H)) @@ -76,6 +77,24 @@ impl Player { .truncate() .child(self.name.clone()), ) + // The window's own control, in the fixed rect the mute button uses + // for the same reason (toolbar.rs:194-203): fullscreen swaps the + // word and the colour, never the box. + .child(self.action_control( + "fullscreen", + 0., + BG_RAISED(), + None, + match fullscreen { + true => "Exit fullscreen", + false => "Fullscreen", + }, + "fills the screen with the window, or gives it back", + ActionId::Fullscreen, + cx.listener(|this, _: &ClickEvent, window, cx| { + this.act(ActionId::Fullscreen, window, cx) + }), + )) .child(self.action_control( "save", 0., @@ -159,6 +178,16 @@ impl Player { .bg(rgb(BG_PANEL())) .border_t_1() .border_color(rgb(STROKE_DIVIDER())) + .child(self.action_control( + "screenshot", + 0., + BG_RAISED(), + None, + "Shot", + "saves the frame on screen as a PNG in ~/Pictures/edith", + ActionId::Screenshot, + cx.listener(|this, _: &ClickEvent, _, cx| this.take_screenshot(cx)), + )) .child(self.action_control( "transport", 40.,