forge
Explore
Log in

Don't you dare go Hollow

A library row previews its file over the timeline

Browse files at this commit

5231711ccc82c562c71aa7e0a897a4c078254a7cAhmet Kaan GümüşParent: 1ac24b8
  • feat
    • a library row previews its file over the timeline
Show full message
✨ feat(app): a library row previews its file over the timeline

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.rsmodified+13 -0
@@ -73,6 +73,17 @@ struct Player {
73 /// waits: the first media import or project load is what fills it, and73 /// waits: the first media import or project load is what fills it, and
74 /// until then every action that needs a timeline says so instead of acting.74 /// until then every action that needs a timeline says so instead of acting.
75 session: Option<PlaybackSession>,75 session: Option<PlaybackSession>,
76+ /// A library row's own file, opened and playing in place of the
77+ /// timeline's picture, and never written to `session` or its undo stack:
78+ /// a preview is watched, not edited. `Some` is what [`Player::pump`] and
79+ /// [`Player::transport`] read first -- the timeline's own session and its
80+ /// silence scan sit untouched underneath until this clears again
81+ /// ([`Player::close_preview`]).
82+ preview_session: Option<PlaybackSession>,
83+ /// Whether the timeline was playing when a preview took it over
84+ /// ([`Player::open_preview`] pauses it so the two sounds never overlap):
85+ /// what [`Player::close_preview`] resumes, and only then.
86+ preview_playing: bool,
76 /// Timeline seconds -> frame index, so the clock can be compared to what87 /// Timeline seconds -> frame index, so the clock can be compared to what
77 /// the decoder hands over.88 /// the decoder hands over.
78 fps: f64,89 fps: f64,
@@ -647,6 +658,8 @@ fn main() {
647 seek_since: None,658 seek_since: None,
648 resynced: None,659 resynced: None,
649 session: None,660 session: None,
661+ preview_session: None,
662+ preview_playing: false,
650 // Full and unmuted, which is what the session it was just663 // Full and unmuted, which is what the session it was just
651 // handed is already set to: nothing to push at startup.664 // handed is already set to: nothing to push at startup.
652 volume: Volume::default(),665 volume: Volume::default(),
crates/app/src/player/actions.rsmodified+1 -1
@@ -252,7 +252,7 @@ impl Player {
252 timeline: true,252 timeline: true,
253 clipboard: self.clipboard.is_some(),253 clipboard: self.clipboard.is_some(),
254 subtitles: !session.subtitles().is_empty(),254 subtitles: !session.subtitles().is_empty(),
255- playable: !nothing_to_play(Some(session)),255+ playable: !nothing_to_play(self.active_session()),
256 exporting: self.exporting().is_some(),256 exporting: self.exporting().is_some(),
257 picks: picks.len(),257 picks: picks.len(),
258 pick_lanes,258 pick_lanes,
crates/app/src/player/library.rsmodified+64 -0
@@ -191,6 +191,70 @@ impl Player {
191 self.seek_since = None;191 self.seek_since = None;
192 }192 }
193 193
194+ /// The row's own play button: opens `path` as a session of its own and
195+ /// shows it in place of the timeline's picture, without moving the
196+ /// timeline's playhead or touching its undo stack -- what a library
197+ /// preview is. [`PlaybackSession::open`] already builds exactly this (a
198+ /// one-clip session, ungraded, passthrough), so nothing new is asked of
199+ /// the engine.
200+ ///
201+ /// corner-cut: opens the file's own first audio stream rather than the
202+ /// row's particular one -- `PlaybackSession::open` takes no stream
203+ /// argument. Ceiling: a remux with several audio tracks previews on its
204+ /// first. Upgrade path: an engine door that opens a chosen stream.
205+ pub(crate) fn open_preview(&mut self, path: &std::path::Path, cx: &mut Context<Self>) {
206+ if self.exporting().is_some() {
207+ return;
208+ }
209+ // The timeline would otherwise keep playing under the preview -- two
210+ // soundtracks at once -- so it is paused here and resumed on the way
211+ // out only if this is what paused it ([`Player::close_preview`]).
212+ self.preview_playing = self.session.as_ref().is_some_and(PlaybackSession::is_playing);
213+ if let Some(session) = self.session.as_mut() {
214+ session.pause();
215+ }
216+ match PlaybackSession::open(path) {
217+ Ok(mut session) => {
218+ session.drop_late_pictures(true);
219+ session.set_gain(self.volume.gain());
220+ self.preview_session = Some(session);
221+ self.notify_user(
222+ format!("PREVIEWING {} — not on the timeline; esc stops it", file_name(path))
223+ .into(),
224+ );
225+ }
226+ Err(e) => self.notify_user(format!("PREVIEW FAILED: {e}").into()),
227+ }
228+ self.reset_after_reseek();
229+ cx.notify();
230+ }
231+
232+ /// The way out of a preview: `esc`, or the banner's own button. The
233+ /// timeline was never pumped while the preview played, so its picture is
234+ /// stale where it left off -- a reseek to the position it is already at
235+ /// is what brings a fresh frame back, exactly as loading a project does.
236+ pub(crate) fn close_preview(&mut self, cx: &mut Context<Self>) {
237+ if self.preview_session.take().is_none() {
238+ return;
239+ }
240+ self.notify_user("PREVIEW STOPPED — back to the timeline".into());
241+ match self.session.as_ref().map(PlaybackSession::now) {
242+ Some(now) => {
243+ self.seek(now, cx);
244+ if self.preview_playing {
245+ if let Some(session) = self.session.as_mut() {
246+ session.play();
247+ }
248+ }
249+ }
250+ None => {
251+ self.image = None;
252+ cx.notify();
253+ }
254+ }
255+ self.preview_playing = false;
256+ }
257+
194 /// The rate and layout the whole timeline's audio is, taken from the stream258 /// The rate and layout the whole timeline's audio is, taken from the stream
195 /// of the first source that could have one: what a library row has to match259 /// of the first source that could have one: what a library row has to match
196 /// to be placeable. `None` until that file has been probed, and then nothing260 /// to be placeable. `None` until that file has been probed, and then nothing
crates/app/src/player/transport.rsmodified+45 -16
@@ -4,6 +4,27 @@
4 use crate::*;4 use crate::*;
5 5
6 impl Player {6 impl Player {
7+ /// The session the transport, the pump and the clock all read: the
8+ /// preview while one is showing, the timeline otherwise -- never both, so
9+ /// a preview is watched without moving the edit's own playhead. See
10+ /// [`preview_session`](Player) for what stays untouched underneath.
11+ pub(crate) fn active_session(&self) -> Option<&PlaybackSession> {
12+ self.preview_session.as_ref().or(self.session.as_ref())
13+ }
14+
15+ pub(crate) fn active_session_mut(&mut self) -> Option<&mut PlaybackSession> {
16+ self.preview_session.as_mut().or(self.session.as_mut())
17+ }
18+
19+ /// The active session's own frame rate rather than the timeline's: a
20+ /// preview of a file shot at another rate clocks and steps at *its* rate,
21+ /// not the edit's.
22+ pub(crate) fn active_fps(&self) -> f64 {
23+ self.preview_session
24+ .as_ref()
25+ .map_or(self.fps, |s| s.meta().frame_rate)
26+ }
27+
7 /// Catches the display up to the clock: everything already due is taken off28 /// 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* the29 /// 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`, and30 /// drop-when-behind policy. A frame that is not due yet waits in `held`, and
@@ -13,9 +34,16 @@ impl Player {
13 // Where the transport was before this drain, so the crossing into34 // Where the transport was before this drain, so the crossing into
14 // `Ended` can be recognised as the one transition it is.35 // `Ended` can be recognised as the one transition it is.
15 let was = self.transport();36 let was = self.transport();
37+ let fps = self.active_fps();
16 // No timeline, nothing to catch up to: the window is showing its empty38 // No timeline, nothing to catch up to: the window is showing its empty
17 // state and there is no decoder to drain.39 // state and there is no decoder to drain.
18- let Some(session) = &mut self.session else {40+ // A direct field borrow rather than the `active_session_mut` helper: the
41+ // rest of this function reads and writes other fields on `self`
42+ // (`held`, `seek_since`, `dropped`, `displayed`, ...) alongside
43+ // `session`, and only a borrow of the two Option fields themselves --
44+ // not a call through a `&mut self` method -- lets the borrow checker
45+ // see those as disjoint.
46+ let Some(session) = self.preview_session.as_mut().or(self.session.as_mut()) else {
19 return;47 return;
20 };48 };
21 // Whether the span now decoding has yet to hand over a picture, read49 // Whether the span now decoding has yet to hand over a picture, read
@@ -24,7 +52,7 @@ impl Player {
24 // reopen took -- is exactly what the resync below must not answer with52 // reopen took -- is exactly what the resync below must not answer with
25 // another reopen.53 // another reopen.
26 let priming = session.picture_priming();54 let priming = session.picture_priming();
27- let target = session.now() * self.fps;55+ let target = session.now() * fps;
28 let mut newest: Option<Frame> = None;56 let mut newest: Option<Frame> = None;
29 // A frame the screen is owed: a seek's landing, and the one readiness57 // A frame the screen is owed: a seek's landing, and the one readiness
30 // signal there is ([`Player::reset_after_reseek`]).58 // signal there is ([`Player::reset_after_reseek`]).
@@ -66,7 +94,7 @@ impl Player {
66 // waiting on.94 // waiting on.
67 let late = newest95 let late = newest
68 .as_ref()96 .as_ref()
69- .map_or(0., |f| (target - f64::from(f.index)) / self.fps);97+ .map_or(0., |f| (target - f64::from(f.index)) / fps);
70 98
71 if let Some(frame) = newest {99 if let Some(frame) = newest {
72 self.displayed += 1;100 self.displayed += 1;
@@ -137,7 +165,7 @@ impl Player {
137 // empty space (measured: a 5 s timeline recognised its end at165 // empty space (measured: a 5 s timeline recognised its end at
138 // clock 17.5 s under a slow renderer). End of stream is left166 // clock 17.5 s under a slow renderer). End of stream is left
139 // set, so this is still `Ended` and the next press restarts.167 // set, so this is still `Ended` and the next press restarts.
140- if let Some(session) = &mut self.session {168+ if let Some(session) = self.active_session_mut() {
141 session.halt_at_end();169 session.halt_at_end();
142 }170 }
143 let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64());171 let elapsed = self.started.map_or(0.0, |t| t.elapsed().as_secs_f64());
@@ -145,7 +173,7 @@ impl Player {
145 "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s",173 "eof after {elapsed:.3}s wall: {} frames displayed, {} dropped, clock {:.3}s",
146 self.displayed,174 self.displayed,
147 self.dropped,175 self.dropped,
148- self.session.as_ref().map_or(0., PlaybackSession::now)176+ self.active_session().map_or(0., PlaybackSession::now)
149 );177 );
150 }178 }
151 }179 }
@@ -156,7 +184,7 @@ impl Player {
156 /// an edit past the end revives the picture) and so is the clock. A held184 /// an edit past the end revives the picture) and so is the clock. A held
157 /// frame is one still owed to the screen, so the end is not the end yet.185 /// frame is one still owed to the screen, so the end is not the end yet.
158 pub(crate) fn transport(&self) -> Transport {186 pub(crate) fn transport(&self) -> Transport {
159- let Some(session) = &self.session else {187+ let Some(session) = self.active_session() else {
160 return Transport::Stopped;188 return Transport::Stopped;
161 };189 };
162 transport(190 transport(
@@ -193,7 +221,7 @@ impl Player {
193 if self.exporting().is_some() {221 if self.exporting().is_some() {
194 return;222 return;
195 }223 }
196- let Some(session) = &mut self.session else {224+ let Some(session) = self.active_session_mut() else {
197 return;225 return;
198 };226 };
199 session.seek(t);227 session.seek(t);
@@ -211,16 +239,17 @@ impl Player {
211 /// edit, and nothing it does moves a clip index.239 /// edit, and nothing it does moves a clip index.
212 pub(crate) fn step(&mut self, frames: i64, cx: &mut Context<Self>) {240 pub(crate) fn step(&mut self, frames: i64, cx: &mut Context<Self>) {
213 let ended = self.transport() == Transport::Ended;241 let ended = self.transport() == Transport::Ended;
214- let Some(session) = &self.session else {242+ let fps = self.active_fps();
243+ let Some(session) = self.active_session() else {
215 return;244 return;
216 };245 };
217- let last = ((session.timeline_duration() * self.fps).round() as i64 - 1).max(0);246+ let last = ((session.timeline_duration() * fps).round() as i64 - 1).max(0);
218 let now = match ended {247 let now = match ended {
219 true => last,248 true => last,
220- false => i64::from(frame_at(session.now(), self.fps)),249+ false => i64::from(frame_at(session.now(), fps)),
221 };250 };
222 let target = now.saturating_add(frames).clamp(0, last);251 let target = now.saturating_add(frames).clamp(0, last);
223- self.seek(target as f64 / self.fps, cx);252+ self.seek(target as f64 / fps, cx);
224 }253 }
225 254
226 /// Seeks to where the pointer sits along the ruler. `commit` is the press255 /// Seeks to where the pointer sits along the ruler. `commit` is the press
@@ -252,7 +281,7 @@ impl Player {
252 /// that is the whole reason this is not just called from the key handler.281 /// that is the whole reason this is not just called from the key handler.
253 /// Silent no-op with no timeline, or with a run that has no audio device.282 /// Silent no-op with no timeline, or with a run that has no audio device.
254 pub(crate) fn apply_volume(&self) {283 pub(crate) fn apply_volume(&self) {
255- if let Some(session) = &self.session {284+ if let Some(session) = self.active_session() {
256 session.set_gain(self.volume.gain());285 session.set_gain(self.volume.gain());
257 }286 }
258 }287 }
@@ -285,8 +314,8 @@ impl Player {
285 // -- and it is Ended again by the next repaint, so no later press could314 // -- and it is Ended again by the next repaint, so no later press could
286 // ever stop it: the button would read "Pause" and never pause. A delete315 // ever stop it: the button would read "Pause" and never pause. A delete
287 // can empty the timeline mid-play, and that press must still stop it.316 // can empty the timeline mid-play, and that press must still stop it.
288- if nothing_to_play(self.session.as_ref()) {317+ if nothing_to_play(self.active_session()) {
289- match self.session.as_mut().filter(|s| s.is_playing()) {318+ match self.active_session_mut().filter(|s| s.is_playing()) {
290 Some(session) => session.pause(),319 Some(session) => session.pause(),
291 None => self.notify_user(NOTHING_TO_PLAY.into()),320 None => self.notify_user(NOTHING_TO_PLAY.into()),
292 }321 }
@@ -303,12 +332,12 @@ impl Player {
303 // whichever asked, the transport was showing Play.332 // whichever asked, the transport was showing Play.
304 state if state.restarts() => {333 state if state.restarts() => {
305 self.seek(0., cx);334 self.seek(0., cx);
306- if let Some(session) = &mut self.session {335+ if let Some(session) = self.active_session_mut() {
307 session.play();336 session.play();
308 }337 }
309 }338 }
310 _ => {339 _ => {
311- if let Some(session) = &mut self.session {340+ if let Some(session) = self.active_session_mut() {
312 session.toggle();341 session.toggle();
313 // A paused timeline animates nothing; this is the repaint342 // A paused timeline animates nothing; this is the repaint
314 // that puts the new glyph up.343 // that puts the new glyph up.
crates/app/src/render.rsmodified+8 -0
@@ -461,6 +461,13 @@ impl Render for Player {
461 return;461 return;
462 }462 }
463 }463 }
464+ // The innermost thing left on screen once no menu is up: a
465+ // preview takes the picture over the timeline's own, and
466+ // escape is its own way out, same as every card above it.
467+ if key == ESCAPE && !ctrl && this.preview_session.is_some() {
468+ this.close_preview(cx);
469+ return;
470+ }
464 if let Some(action) = action {471 if let Some(action) = action {
465 this.act(action, window, cx);472 this.act(action, window, cx);
466 }473 }
@@ -607,6 +614,7 @@ impl Render for Player {
607 // After the picture, so the plate is drawn614 // After the picture, so the plate is drawn
608 // over it rather than under.615 // over it rather than under.
609 .children(self.subtitle_overlay(position, window))616 .children(self.subtitle_overlay(position, window))
617+ .children(self.preview_badge(cx))
610 // The three transient lines hang off the618 // The three transient lines hang off the
611 // bottom of the picture rather than taking619 // bottom of the picture rather than taking
612 // a row of the column: a notice that620 // a row of the column: a notice that
crates/app/src/tests/media.rsmodified+28 -0
@@ -1130,3 +1130,31 @@ fn exactly_one_subtitle_lane_is_shown_whatever_the_pick_and_whatever_is_left() {
1130 // A pick that is not a subtitle lane at all cannot name one either.1130 // A pick that is not a subtitle lane at all cannot name one either.
1131 assert_eq!(active_lane(Some(Lane::V1), &[s1, s2]), Some(s1));1131 assert_eq!(active_lane(Some(Lane::V1), &[s1, s2]), Some(s1));
1132 }1132 }
1133+
1134+/// A library preview's whole point ([`Player::open_preview`],
1135+/// [`Player::close_preview`]): the timeline's own session is untouched by
1136+/// one showing over it. `Player` cannot be built here -- it takes a gpui
1137+/// `Context`, which this test binary has no `TestAppContext` to hand it
1138+/// (see the crate's other tests for the same limit) -- so this exercises
1139+/// the two sessions `open_preview`/`close_preview` juggle directly: seeking
1140+/// and playing one, exactly as a preview session's own life does, leaves
1141+/// the other's position and clock exactly where they were.
1142+#[test]
1143+fn a_second_session_playing_never_moves_the_first() {
1144+ let mut timeline = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1145+ timeline.seek(0.5);
1146+ let before = timeline.now();
1147+ let before_playing = timeline.is_playing();
1148+
1149+ // Stands in for the preview session `open_preview` opens over it.
1150+ let mut preview = PlaybackSession::open(asset("test_av.mp4")).expect("open the fixture");
1151+ preview.seek(1.0);
1152+ preview.play();
1153+
1154+ assert_eq!(timeline.now(), before, "the preview's seek moved the wrong session");
1155+ assert_eq!(
1156+ timeline.is_playing(),
1157+ before_playing,
1158+ "the preview's play moved the wrong session"
1159+ );
1160+}
crates/app/src/ui/library.rsmodified+29 -1
@@ -170,14 +170,20 @@ impl Player {
170 // name alone was, and the detail line under it ran on under the170 // name alone was, and the detail line under it ran on under the
171 // switch and was cut mid-word -- and an unusable row draws no switch171 // switch and was cut mid-word -- and an unusable row draws no switch
172 // and so pays nothing for one.172 // and so pays nothing for one.
173+ // Two switches now sit at the end of a usable row -- the preview
174+ // play button beside the stand-in toggle -- so the text gives up
175+ // twice the room it gave up for one.
173 let text_w = row_text_w(width)176 let text_w = row_text_w(width)
174 - match usable {177 - match usable {
175- true => HIT_MIN + 6.,178+ true => 2. * (HIT_MIN + 6.),
176 false => 0.,179 false => 0.,
177 };180 };
178 let (path, stream) = (row.path.clone(), row.stream);181 let (path, stream) = (row.path.clone(), row.stream);
179 let dragged = (path.clone(), stream);182 let dragged = (path.clone(), stream);
180 let menu_path = path.clone();183 let menu_path = path.clone();
184+ let preview_path = path.clone();
185+ let preview_tip: SharedString =
186+ format!("Preview {} — plays it without touching the timeline", row.name).into();
181 div()187 div()
182 .id(("asset", i))188 .id(("asset", i))
183 .flex_none()189 .flex_none()
@@ -282,6 +288,28 @@ impl Player {
282 // the window speaks says which way it is set -- lit like a288 // the window speaks says which way it is set -- lit like a
283 // picked row when there is one, dimmed like an unusable one289 // picked row when there is one, dimmed like an unusable one
284 // when there is not.290 // when there is not.
291+ .when(usable, |d| {
292+ d.child(
293+ div()
294+ .id(("preview-play", i))
295+ .flex_none()
296+ .w(px(HIT_MIN))
297+ .h_full()
298+ .flex()
299+ .items_center()
300+ .justify_center()
301+ .rounded(px(3.))
302+ .text_size(px(11.))
303+ .cursor_pointer()
304+ .hover(|s| s.bg(rgb(BG_HOVER())))
305+ .tooltip(move |_, cx| cx.new(|_| Tip(preview_tip.clone())).into())
306+ .on_click(cx.listener(move |this, _: &ClickEvent, _, cx| {
307+ cx.stop_propagation();
308+ this.open_preview(&preview_path, cx);
309+ }))
310+ .child("▶"),
311+ )
312+ })
285 .when(usable, |d| {313 .when(usable, |d| {
286 d.child(314 d.child(
287 div()315 div()
crates/app/src/ui/preview.rsmodified+134 -0
@@ -1,8 +1,80 @@
1 //! The picture: what is drawn over it and what is read off it.1 //! The picture: what is drawn over it and what is read off it.
2 2
3 use crate::*;3 use crate::*;
4+use std::path::{Path, PathBuf};
4 5
5 impl Player {6 impl Player {
7+ /// The one thing that says a preview is up rather than the timeline: a
8+ /// banner over the top of the picture, and a click of its own -- the
9+ /// keyboard has `esc`, and a hand with only a mouse needs a way out too.
10+ pub(crate) fn preview_badge(&self, cx: &mut Context<Self>) -> Option<impl IntoElement> {
11+ self.preview_session.is_some().then(|| {
12+ div()
13+ .absolute()
14+ .top_0()
15+ .left_0()
16+ .right_0()
17+ .flex()
18+ .items_center()
19+ .justify_center()
20+ .gap(px(8.))
21+ .p(px(4.))
22+ .bg(rgba(SUB_SHADE()))
23+ .text_size(px(11.))
24+ .text_color(rgb(FG_PRIMARY()))
25+ .child("PREVIEW — not on the timeline")
26+ .child(
27+ div()
28+ .id("preview-stop")
29+ .px(px(6.))
30+ .rounded(px(3.))
31+ .cursor_pointer()
32+ .bg(rgb(BG_RAISED()))
33+ .hover(|s| s.bg(rgb(BG_HOVER())))
34+ .on_click(cx.listener(|this, _: &ClickEvent, _, cx| this.close_preview(cx)))
35+ .child("Stop (esc)"),
36+ )
37+ })
38+ }
39+
40+ /// The frame on screen right now, written to a PNG: `image` and its
41+ /// `as_bytes` are gpui's own cached copy of what was last handed to the
42+ /// atlas ([`Player::pump`]), so this reads no decoder and races nothing --
43+ /// works during preview or on the timeline, whichever is showing.
44+ pub(crate) fn take_screenshot(&mut self, cx: &mut Context<Self>) {
45+ let no_frame = || "NO FRAME TO SAVE — nothing is showing yet".to_string();
46+ let Some(image) = self.image.clone() else {
47+ self.notify_user(no_frame().into());
48+ cx.notify();
49+ return;
50+ };
51+ let Some(bytes) = image.as_bytes(0) else {
52+ self.notify_user(no_frame().into());
53+ cx.notify();
54+ return;
55+ };
56+ let size = image.size(0);
57+ let stem = self
58+ .active_session()
59+ .and_then(|s| s.sources().first())
60+ .map_or_else(|| self.name.to_string(), |s| file_name(&s.path));
61+ let stem = std::path::Path::new(&stem)
62+ .file_stem()
63+ .map_or(stem.clone(), |s| s.to_string_lossy().into_owned());
64+ let tc = timecode(
65+ self.active_session().map_or(0., PlaybackSession::now),
66+ self.active_fps(),
67+ )
68+ .replace(':', "-");
69+ let text = match save_screenshot(bytes, size.width.0 as u32, size.height.0 as u32, &stem, &tc)
70+ {
71+ Ok(path) => format!("SAVED {}", path.display()),
72+ Err(e) => format!("SCREENSHOT FAILED: {e}"),
73+ };
74+ self.notify_user(text.into());
75+ cx.notify();
76+ }
77+
6 /// The cues the *subtitle lanes* put on screen at `at`, over the picture and78 /// The cues the *subtitle lanes* put on screen at `at`, over the picture and
7 /// nothing else: bottom-centred where every player puts them, white on a79 /// nothing else: bottom-centred where every player puts them, white on a
8 /// plate so the film underneath cannot swallow them, and each cue its own80 /// plate so the film underneath cannot swallow them, and each cue its own
@@ -201,3 +273,65 @@ impl Player {
201 }273 }
202 }274 }
203 }275 }
276+
277+/// `~/Pictures/edith`, or `.` with no `HOME` -- [`keymap::config_path_in`]'s
278+/// own fallback, for the same reason: a screenshot has to land somewhere even
279+/// on a machine with no desktop environment set up.
280+pub(crate) fn screenshots_dir() -> PathBuf {
281+ std::env::var_os("HOME")
282+ .map_or_else(|| PathBuf::from("."), PathBuf::from)
283+ .join("Pictures")
284+ .join("edith")
285+}
286+
287+/// Where a screenshot goes: `stem-tc.png` in `dir`, or the same name with a
288+/// numeric suffix if that one is already taken -- a screenshot never
289+/// overwrites another the way an export overwrites its own path.
290+pub(crate) fn screenshot_path(dir: &Path, stem: &str, tc: &str) -> PathBuf {
291+ let base = format!("{stem}-{tc}");
292+ let first = dir.join(format!("{base}.png"));
293+ if !first.exists() {
294+ return first;
295+ }
296+ let mut n = 2;
297+ loop {
298+ let path = dir.join(format!("{base}-{n}.png"));
299+ if !path.exists() {
300+ return path;
301+ }
302+ n += 1;
303+ }
304+}
305+
306+/// The swap every BGRA frame needs to become the RGBA a PNG writes: gpui's
307+/// atlas is BGRA with straight alpha ([`Player::sub_picture`]'s own comment),
308+/// and `image::save` writes RGBA.
309+pub(crate) fn bgra_to_rgba(bgra: &[u8]) -> Vec<u8> {
310+ let mut out = bgra.to_vec();
311+ for pixel in out.chunks_exact_mut(4) {
312+ pixel.swap(0, 2);
313+ }
314+ out
315+}
316+
317+/// Writes `bgra` (`w`x`h`, gpui's own layout) to a fresh PNG under
318+/// [`screenshots_dir`], creating the directory if this is the first one.
319+/// Never called on the render thread's own budget for more than a channel
320+/// swap and one `image::save` -- there is no decode here, only a copy already
321+/// in memory.
322+pub(crate) fn save_screenshot(
323+ bgra: &[u8],
324+ w: u32,
325+ h: u32,
326+ stem: &str,
327+ tc: &str,
328+) -> Result<PathBuf, String> {
329+ let dir = screenshots_dir();
330+ std::fs::create_dir_all(&dir).map_err(|e| format!("{}: {e}", dir.display()))?;
331+ let path = screenshot_path(&dir, stem, tc);
332+ let rgba = bgra_to_rgba(bgra);
333+ let buf = image::RgbaImage::from_raw(w, h, rgba)
334+ .ok_or_else(|| "frame buffer sized w*h*4".to_string())?;
335+ buf.save(&path).map_err(|e| e.to_string())?;
336+ Ok(path)
337+}