forge
Explore
Log in

Don't you dare go Hollow

Export UI — e to export, esc cancels, ruler as progress

Browse files at this commit

9eac4be8a14d8570c4c7183cff4e6a372f8e175aAhmet Kaan GümüşParent: 86d5c15
  • feat
    • export UI — e to export, esc cancels, ruler as progress
Show full message
✨ feat(app): export UI — e to export, esc cancels, ruler as progress

`e` writes the edit list to <source>.export.mp4: playback pauses, the
timecode slot becomes `EXPORT n% — esc cancels` and the ruler's accent
fill doubles as the progress bar. Edit, scrub, seek and transport input
is dead for the duration; the raf gate keeps repainting so progress moves
while the clock is stopped. The verdict holds the slot for two seconds.

`esc` gives the editor back on the keystroke, but the handle is kept until
the worker settles: its last act is to delete the partial file, and a
second export started in that window would be what it deleted.
crates/app/src/main.rsmodified+180 -9
@@ -1,9 +1,10 @@
11 use std::cell::Cell;
2+use std::path::PathBuf;
23 use std::rc::Rc;
34 use std::sync::Arc;
45 use std::time::{Duration, Instant};
56
6-use engine::{Clip, Frame, PlaybackSession};
7+use engine::{Clip, ExportHandle, Frame, PlaybackSession};
78 use gpui::{
89 App, Application, Bounds, Context, FocusHandle, KeyDownEvent, MouseButton, MouseDownEvent,
910 MouseMoveEvent, MouseUpEvent, PathBuilder, Pixels, RenderImage, SharedString, TitlebarOptions,
@@ -62,6 +63,19 @@ struct Player {
6263 last_target: u32,
6364 /// Playback was started once, on the first render. Space owns it after that.
6465 launched: bool,
66+ /// The running export. While it owns the UI the editor is read-only.
67+ export: Option<ExportHandle>,
68+ /// The export above was cancelled and is only winding down. The editor is
69+ /// already free -- the worker took its own copy of the edit list -- but the
70+ /// handle is held until the worker settles, because its last act is to
71+ /// delete the output file and a second export must not be what it deletes.
72+ cancelling: bool,
73+ /// Where an export writes. Built once from the source path, which is not
74+ /// otherwise kept.
75+ export_path: PathBuf,
76+ /// What the last export left in the timecode slot, and when. Cleared by
77+ /// `NOTICE` passing or by the next key, whichever comes first.
78+ notice: Option<(SharedString, Instant)>,
6579 displayed: u32,
6680 dropped: u32,
6781 /// Wall clock of the first displayed frame -- the real-speed measurement.
@@ -144,6 +158,9 @@ impl Player {
144158
145159 /// Jumps the timeline.
146160 fn seek(&mut self, t: f64, cx: &mut Context<Self>) {
161+ if self.exporting().is_some() {
162+ return;
163+ }
147164 self.session.seek(t);
148165 self.reset_after_reseek();
149166 cx.notify();
@@ -152,6 +169,9 @@ impl Player {
152169 /// Splits the clip under the playhead. Metadata only: the timeline->source
153170 /// mapping is unchanged, so nothing reseeks and no flag is touched.
154171 fn cut(&mut self, cx: &mut Context<Self>) {
172+ if self.exporting().is_some() {
173+ return;
174+ }
155175 self.session.cut_at(self.session.now());
156176 self.selected = None;
157177 cx.notify();
@@ -160,6 +180,9 @@ impl Player {
160180 /// Drops the selected clip. The engine reseeks itself, so all this owes is
161181 /// the flag reset.
162182 fn delete_selected(&mut self, cx: &mut Context<Self>) {
183+ if self.exporting().is_some() {
184+ return;
185+ }
163186 if self
164187 .selected
165188 .take()
@@ -214,6 +237,9 @@ impl Player {
214237 /// Space and the transport button share it: once the timeline is finished
215238 /// the only sensible "play" is from the top.
216239 fn toggle_or_restart(&mut self, cx: &mut Context<Self>) {
240+ if self.exporting().is_some() {
241+ return;
242+ }
217243 if self.done {
218244 self.seek(0., cx);
219245 self.session.play();
@@ -223,6 +249,55 @@ impl Player {
223249 cx.notify();
224250 }
225251 }
252+
253+ /// The export that owns the UI, if any. A cancelled one does not: it has
254+ /// its own copy of the edit list and owes only its own cleanup.
255+ fn exporting(&self) -> Option<&ExportHandle> {
256+ self.export.as_ref().filter(|_| !self.cancelling)
257+ }
258+
259+ /// Writes the edit list out beside the source. Playback stops first: the
260+ /// exporter opens its own decoder -- and, on the hardware path, an encoder --
261+ /// so a running player would only compete with it for the GPU. A cancelled
262+ /// export still winding down holds this off for the frame it takes to
263+ /// notice, which is what keeps its `remove_file` off the new output.
264+ fn start_export(&mut self, cx: &mut Context<Self>) {
265+ if self.export.is_some() {
266+ return;
267+ }
268+ self.session.pause();
269+ self.export = Some(self.session.export_to(&self.export_path));
270+ cx.notify();
271+ }
272+
273+ /// Gives the editor back at once and leaves the worker to stop at its next
274+ /// frame and delete what it has written.
275+ fn cancel_export(&mut self) {
276+ if let Some(export) = &self.export {
277+ export.cancel();
278+ self.cancelling = true;
279+ }
280+ }
281+
282+ /// Takes the export's verdict once it has one. The only place the app
283+ /// touches the handle's completion side.
284+ fn poll_export(&mut self) {
285+ let Some(result) = self.export.as_ref().and_then(ExportHandle::result) else {
286+ return;
287+ };
288+ self.export = None;
289+ // A cancellation is reported as an error, and the one who asked for it
290+ // has had the editor back since the keystroke. Nothing to say.
291+ if std::mem::take(&mut self.cancelling) {
292+ return;
293+ }
294+ let text = match result {
295+ Ok(()) => format!("EXPORT DONE → {}", file_name(&self.export_path)),
296+ Err(e) => format!("EXPORT FAILED: {e}"),
297+ };
298+ eprintln!("{text}");
299+ self.notice = Some((text.into(), Instant::now()));
300+ }
226301 }
227302
228303 impl Render for Player {
@@ -235,12 +310,26 @@ impl Render for Player {
235310 }
236311 self.session.tick();
237312 self.pump(window);
313+ self.poll_export();
314+ if self
315+ .notice
316+ .as_ref()
317+ .is_some_and(|(_, at)| at.elapsed() >= NOTICE)
318+ {
319+ self.notice = None;
320+ }
238321 // No shadow flag: the clock is the only truth about play state.
239322 let playing = self.session.is_playing();
240323 // A paused timeline has nothing to animate; the toggle handlers notify,
241324 // which is what starts the loop again. A paused seek keeps the loop
242- // running by itself until `pump` has the frame it asked for.
243- if (playing && !self.done) || self.pending_seek {
325+ // running by itself until `pump` has the frame it asked for. An export
326+ // pauses playback and still needs the loop: its progress, and the
327+ // message it leaves behind, only reach the screen on a repaint.
328+ if (playing && !self.done)
329+ || self.pending_seek
330+ || self.export.is_some()
331+ || self.notice.is_some()
332+ {
244333 window.request_animation_frame();
245334 }
246335
@@ -264,6 +353,18 @@ impl Render for Player {
264353 if event.is_held {
265354 return;
266355 }
356+ // Any key retires the last export's message, whatever it was.
357+ this.notice = None;
358+ // An export is reading the edit list every other key here would
359+ // change, so escape is the only one that means anything until
360+ // it is over.
361+ if this.exporting().is_some() {
362+ if event.keystroke.key.as_str() == "escape" {
363+ this.cancel_export();
364+ }
365+ cx.notify();
366+ return;
367+ }
267368 // On linux gpui reports ctrl-c as key "c" with the control
268369 // modifier set (the control code is mapped back), so the plain
269370 // and modified bindings are told apart here and nowhere else.
@@ -272,6 +373,7 @@ impl Render for Player {
272373 event.keystroke.modifiers.control,
273374 ) {
274375 ("space", _) => this.toggle_or_restart(cx),
376+ ("e", false) => this.start_export(cx),
275377 ("c", true) => this.copy_selected(),
276378 ("v", true) => this.paste(cx),
277379 ("c", false) => this.cut(cx),
@@ -352,6 +454,27 @@ impl Player {
352454 } else {
353455 0.
354456 };
457+ // An export owns the timecode slot and the ruler while it runs: the
458+ // percentage and the accent bar are the same number, so the playhead
459+ // fill doubles as the progress bar for free.
460+ let (label, filled) = if let Some(export) = self.exporting() {
461+ let progress = export.progress();
462+ (
463+ format!("EXPORT {}% — esc cancels", (progress * 100.) as u32),
464+ progress,
465+ )
466+ } else if let Some((notice, _)) = &self.notice {
467+ (notice.to_string(), filled)
468+ } else {
469+ (
470+ format!(
471+ "{} / {}",
472+ timecode(position, self.fps),
473+ timecode(duration, self.fps)
474+ ),
475+ filled,
476+ )
477+ };
355478 div()
356479 .flex_none()
357480 .h(px(PANEL_H))
@@ -380,11 +503,14 @@ impl Player {
380503 delete_glyph(),
381504 cx.listener(|this, _: &MouseDownEvent, _, cx| this.delete_selected(cx)),
382505 ))
383- .child(div().flex_none().w(px(TIME_W)).child(format!(
384- "{} / {}",
385- timecode(position, self.fps),
386- timecode(duration, self.fps)
387- ))),
506+ // Fixed width and one line whatever it says: an export
507+ // label is longer than a timecode and must not push the
508+ // row around, nor wrap and change its height.
509+ //
510+ // ponytail: a long file name is ellipsized at TIME_W --
511+ // the whole path is on stderr. Upgrade path is a status
512+ // line of its own under the ruler, not a wider slot.
513+ .child(div().flex_none().w(px(TIME_W)).truncate().child(label)),
388514 )
389515 // Press to seek, drag to scrub: the move and release halves live on
390516 // the root, since the pointer leaves this 6 px strip immediately.
@@ -462,6 +588,26 @@ fn scrub_due(target: u32, last_target: u32, since: Duration) -> bool {
462588 target != last_target && since >= SCRUB_GAP
463589 }
464590
591+/// How long a finished export's message holds the timecode slot.
592+const NOTICE: Duration = Duration::from_secs(2);
593+
594+/// Where an export goes: the source path with `.export.mp4` for an extension,
595+/// so it lands beside the original and can never be the original.
596+fn export_path(source: &str) -> PathBuf {
597+ let mut path = PathBuf::from(source);
598+ path.set_extension("export.mp4");
599+ path
600+}
601+
602+/// The tail of a path, for showing. A path that is all root has none, and reads
603+/// as itself.
604+fn file_name(path: &std::path::Path) -> String {
605+ path.file_name().map_or_else(
606+ || path.display().to_string(),
607+ |n| n.to_string_lossy().into(),
608+ )
609+}
610+
465611 /// A clip's share of the lane. A timeline with no length reads as one full-width
466612 /// box rather than as NaN, which gpui would carry into layout.
467613 fn width_frac(len: f64, total: f64) -> f32 {
@@ -586,7 +732,7 @@ fn timecode(t: f64, fps: f64) -> String {
586732
587733 #[cfg(test)]
588734 mod tests {
589- use super::{frac_along, scrub_due, timecode, width_frac};
735+ use super::{export_path, frac_along, scrub_due, timecode, width_frac};
590736 use gpui::{Bounds, Pixels, point, px, size};
591737 use std::time::Duration;
592738
@@ -632,6 +778,26 @@ mod tests {
632778 assert!(scrub_due(1, 0, Duration::from_secs(9)));
633779 }
634780
781+ #[test]
782+ fn export_lands_beside_the_source_and_never_on_it() {
783+ // The whole point: the export of an .mp4 is never that .mp4.
784+ assert_eq!(
785+ export_path("assets/test_baseline.mp4"),
786+ std::path::Path::new("assets/test_baseline.export.mp4")
787+ );
788+ // A second export of an export is still not its own source.
789+ assert_eq!(
790+ export_path("a.export.mp4"),
791+ std::path::Path::new("a.export.export.mp4")
792+ );
793+ // Extensionless and dotted-directory names keep the directory intact.
794+ assert_eq!(export_path("clip"), std::path::Path::new("clip.export.mp4"));
795+ assert_eq!(
796+ export_path("/v.1/clip.MP4"),
797+ std::path::Path::new("/v.1/clip.export.mp4")
798+ );
799+ }
800+
635801 #[test]
636802 fn clip_boxes_split_the_lane_by_duration() {
637803 // 1 s + 3 s of a 4 s timeline: a quarter and three quarters.
@@ -656,6 +822,7 @@ fn main() {
656822 }
657823 };
658824 let meta = *session.meta();
825+ let out = export_path(&path);
659826 let name: SharedString = std::path::Path::new(&path)
660827 .file_name()
661828 .map_or_else(|| path.clone(), |n| n.to_string_lossy().into_owned())
@@ -697,6 +864,10 @@ fn main() {
697864 last_scrub: Instant::now(),
698865 last_target: 0,
699866 launched: false,
867+ export: None,
868+ cancelling: false,
869+ export_path: out.clone(),
870+ notice: None,
700871 displayed: 0,
701872 dropped: 0,
702873 started: None,