diff --git a/apps/desktop-gpui/locales/de.toml b/apps/desktop-gpui/locales/de.toml index b454336e273..762130e3c14 100644 --- a/apps/desktop-gpui/locales/de.toml +++ b/apps/desktop-gpui/locales/de.toml @@ -2654,6 +2654,7 @@ file = "Datei" link = "Link zum Teilen" [editor.export.done] +copy_file = "Datei kopieren" copy_link = "Link kopieren" instant_hint = "Verwenden Sie für Ihre nächste Aufnahme den Instant-Modus, wenn Sie direkt nach dem Stoppen einen Link möchten." link_copied = "Link kopiert" @@ -2661,6 +2662,7 @@ open_file = "Datei öffnen" open_link = "Link öffnen" retry_copy = "Erneut kopieren" reuploaded = "Ihre neueste Bearbeitung ist unter demselben Link bereit" +saved_copy = "Kopie gespeichert als {name}" uploaded = "Ihr Cap wurde erfolgreich hochgeladen" [editor.export.enhance] diff --git a/apps/desktop-gpui/locales/en.toml b/apps/desktop-gpui/locales/en.toml index a6747ce8074..521e2732521 100644 --- a/apps/desktop-gpui/locales/en.toml +++ b/apps/desktop-gpui/locales/en.toml @@ -2656,6 +2656,7 @@ file = { text = "File", context = "Export destination." } link = { text = "Shareable Link", context = "Export destination." } [editor.export.done] +copy_file = "Copy File" copy_link = "Copy link" instant_hint = "Use Instant Mode for your next recording if you want a link the moment you stop." link_copied = "Link copied" @@ -2663,6 +2664,7 @@ open_file = "Open File" open_link = "Open link" retry_copy = "Retry Copy" reuploaded = "Your latest edit is ready at the same link" +saved_copy = { text = "Saved a copy as {name}", context = "{name} is the new file's name, for example Demo copy.mp4." } uploaded = "Your Cap has been uploaded successfully" [editor.export.enhance] diff --git a/apps/desktop-gpui/locales/es.toml b/apps/desktop-gpui/locales/es.toml index b32dac34ceb..473b7096b56 100644 --- a/apps/desktop-gpui/locales/es.toml +++ b/apps/desktop-gpui/locales/es.toml @@ -2654,6 +2654,7 @@ file = "Archivo" link = "Enlace para compartir" [editor.export.done] +copy_file = "Copiar archivo" copy_link = "Copiar enlace" instant_hint = "Usa el modo Instant en tu próxima grabación si quieres un enlace en cuanto te detengas." link_copied = "Enlace copiado" @@ -2661,6 +2662,7 @@ open_file = "Abrir archivo" open_link = "Abrir enlace" retry_copy = "Reintentar copia" reuploaded = "Tu última edición está lista en el mismo enlace" +saved_copy = "Copia guardada como {name}" uploaded = "Tu Cap se subió correctamente" [editor.export.enhance] diff --git a/apps/desktop-gpui/locales/fr.toml b/apps/desktop-gpui/locales/fr.toml index 1363a5a32cc..37ad854ab5c 100644 --- a/apps/desktop-gpui/locales/fr.toml +++ b/apps/desktop-gpui/locales/fr.toml @@ -2654,6 +2654,7 @@ file = "Fichier" link = "Lien de partage" [editor.export.done] +copy_file = "Copier le fichier" copy_link = "Copier le lien" instant_hint = "Utilisez le mode Instant pour votre prochain enregistrement si vous voulez un lien dès que vous arrêtez." link_copied = "Lien copié" @@ -2661,6 +2662,7 @@ open_file = "Ouvrir le fichier" open_link = "Ouvrir le lien" retry_copy = "Réessayer la copie" reuploaded = "Votre dernière modification est disponible sur le même lien" +saved_copy = "Copie enregistrée sous {name}" uploaded = "Votre Cap a bien été mis en ligne" [editor.export.enhance] diff --git a/apps/desktop-gpui/locales/hi.toml b/apps/desktop-gpui/locales/hi.toml index d0c3ce84122..9306a9be288 100644 --- a/apps/desktop-gpui/locales/hi.toml +++ b/apps/desktop-gpui/locales/hi.toml @@ -2654,6 +2654,7 @@ file = "फ़ाइल" link = "शेयर लिंक" [editor.export.done] +copy_file = "फ़ाइल कॉपी करें" copy_link = "लिंक कॉपी करें" instant_hint = "अगर आप रोकते ही लिंक चाहते हैं, तो अगली रिकॉर्डिंग के लिए Instant मोड इस्तेमाल करें।" link_copied = "लिंक कॉपी हो गया" @@ -2661,6 +2662,7 @@ open_file = "फ़ाइल खोलें" open_link = "लिंक खोलें" retry_copy = "फिर से कॉपी करें" reuploaded = "आपका नया संपादन उसी लिंक पर तैयार है" +saved_copy = "कॉपी {name} के रूप में सहेजी गई" uploaded = "आपका Cap सफलतापूर्वक अपलोड हो गया" [editor.export.enhance] diff --git a/apps/desktop-gpui/locales/ja.toml b/apps/desktop-gpui/locales/ja.toml index 967be8d9989..75a9390212f 100644 --- a/apps/desktop-gpui/locales/ja.toml +++ b/apps/desktop-gpui/locales/ja.toml @@ -2654,6 +2654,7 @@ file = "ファイル" link = "共有リンク" [editor.export.done] +copy_file = "ファイルをコピー" copy_link = "リンクをコピー" instant_hint = "停止した瞬間にリンクが欲しい場合は、次の録画でInstantモードを使ってください。" link_copied = "リンクをコピーしました" @@ -2661,6 +2662,7 @@ open_file = "ファイルを開く" open_link = "リンクを開く" retry_copy = "コピーを再試行" reuploaded = "最新の編集内容が同じリンクで利用できます" +saved_copy = "コピーを{name}として保存しました" uploaded = "録画のアップロードが完了しました" [editor.export.enhance] diff --git a/apps/desktop-gpui/locales/zh-CN.toml b/apps/desktop-gpui/locales/zh-CN.toml index c7bae3ffead..62dcf9d0af6 100644 --- a/apps/desktop-gpui/locales/zh-CN.toml +++ b/apps/desktop-gpui/locales/zh-CN.toml @@ -2654,6 +2654,7 @@ file = "文件" link = "分享链接" [editor.export.done] +copy_file = "复制文件" copy_link = "复制链接" instant_hint = "如果想在停止录制时立即获得链接,下次录制请使用 Instant 模式。" link_copied = "链接已复制" @@ -2661,6 +2662,7 @@ open_file = "打开文件" open_link = "打开链接" retry_copy = "重新复制" reuploaded = "你最新的编辑已在同一链接上就绪" +saved_copy = "已将副本保存为 {name}" uploaded = "你的录制已成功上传" [editor.export.enhance] diff --git a/apps/desktop-gpui/src/editor_export.rs b/apps/desktop-gpui/src/editor_export.rs index 664ea8ce09c..afb4f590583 100644 --- a/apps/desktop-gpui/src/editor_export.rs +++ b/apps/desktop-gpui/src/editor_export.rs @@ -414,6 +414,7 @@ pub struct ExportUi { pub rendered: u32, pub total_frames: u32, pub output_path: Option, + copied_file: Option, pub error: Option, pub cancel: Arc, pub export_task: Option>, @@ -571,6 +572,7 @@ impl ExportUi { rendered: 0, total_frames: 0, output_path: None, + copied_file: None, error: None, cancel: Arc::new(AtomicBool::new(false)), export_task: None, @@ -1334,6 +1336,7 @@ impl EditorWindow { ui.rendered = 0; ui.total_frames = 0; ui.output_path = None; + ui.copied_file = None; cx.notify(); ui.export_task = Some(cx.spawn_in(window, async move |this, cx| { @@ -2014,6 +2017,44 @@ impl EditorWindow { ) } + /// Runs in the `Copying` phase so closing the panel, starting another + /// export and installing an update all wait for the copy to finish. + fn duplicate_output(&mut self, window: &mut Window, cx: &mut Context) { + let Some(ui) = self + .export + .as_mut() + .filter(|ui| ui.phase == ExportPhase::Done) + else { + return; + }; + let Some(source) = ui.output_path.clone() else { + return; + }; + ui.phase = ExportPhase::Copying; + ui.copied_file = None; + ui.error = None; + cx.notify(); + cx.spawn_in(window, async move |this, cx| { + let result = cx + .background_executor() + .spawn(async move { library::duplicate_file(&source) }) + .await; + this.update_in(cx, |this, window, cx| { + if let Some(ui) = this.export.as_mut() { + ui.phase = ExportPhase::Done; + match result { + Ok(path) => ui.copied_file = Some(path), + Err(error) => ui.error = Some(error), + } + } + cx.notify(); + this.finish_requested_export_close(window, cx); + }) + .ok(); + }) + .detach(); + } + fn retry_clipboard_copy(&mut self, window: &mut Window, cx: &mut Context) { let Some(ui) = self.export.as_mut() else { return; @@ -4027,6 +4068,7 @@ impl EditorWindow { let mut wash: Hsla = editor.window.into(); wash.a = 0.94; + let cancellable = ui.phase.is_busy() && ui.phase != ExportPhase::Copying; div() .absolute() @@ -4107,7 +4149,20 @@ impl EditorWindow { .child(error), ) }) - .when(ui.phase.is_busy(), |this| { + .when_some( + ui.copied_file.as_ref().and_then(|path| path.file_name()), + |this, name| { + this.child( + div() + .max_w(px(360.)) + .text_size(px(12.)) + .text_color(Hsla::from(editor.text_2)) + .text_center() + .child(tr::editor::export::done::saved_copy(name.to_string_lossy())), + ) + }, + ) + .when(cancellable, |this| { this.child( ui::Button::plain( &theme, @@ -4214,6 +4269,27 @@ impl EditorWindow { } }), ) + .when( + ui.phase == ExportPhase::Done + && ui.format != ExportFormatKind::Tracks, + |this| { + this.child( + ui::Button::plain( + &theme, + "export-copy-file", + ui::ButtonVariant::Gray, + ui::ButtonSize::Md, + ) + .icon("icons/copy.svg") + .label(tr::editor::export::done::copy_file()) + .on_click( + cx.listener(|this, _, window, cx| { + this.duplicate_output(window, cx); + }), + ), + ) + }, + ) }, ) .when( diff --git a/apps/desktop-gpui/src/i18n/editor_shell_surface_tests.rs b/apps/desktop-gpui/src/i18n/editor_shell_surface_tests.rs index 02ab6576c31..285f2177645 100644 --- a/apps/desktop-gpui/src/i18n/editor_shell_surface_tests.rs +++ b/apps/desktop-gpui/src/i18n/editor_shell_surface_tests.rs @@ -49,6 +49,7 @@ const FORMATTED: &[&str] = &[ "editor.clips.removed_media", "editor.clips.save_before_recording_failed", "editor.clips.split", + "editor.export.done.saved_copy", "editor.export.estimate.gigabytes", "editor.export.estimate.gigabytes_range", "editor.export.estimate.hours", @@ -221,6 +222,7 @@ fn editor_shell_surfaces_match_the_literals_they_replaced() { (tr::editor::export::destination::clipboard(), "Clipboard"), (tr::editor::export::destination::file(), "File"), (tr::editor::export::destination::link(), "Shareable Link"), + (tr::editor::export::done::copy_file(), "Copy File"), (tr::editor::export::done::copy_link(), "Copy link"), ( tr::editor::export::done::instant_hint(), @@ -1650,6 +1652,10 @@ fn editor_shell_messages_format_like_the_code_they_replaced() { tr::editor::clips::append_error(&message), format!("Failed to add clip: {message}") ); + assert_eq!( + tr::editor::export::done::saved_copy("Demo copy.mp4"), + "Saved a copy as Demo copy.mp4" + ); assert_eq!( tr::editor::clips::import_error(&message), format!("Failed to import clip: {message}") diff --git a/apps/desktop-gpui/src/library.rs b/apps/desktop-gpui/src/library.rs index c5d6317e18b..c7f6a1c0a1d 100644 --- a/apps/desktop-gpui/src/library.rs +++ b/apps/desktop-gpui/src/library.rs @@ -16,6 +16,9 @@ //! all it does is fan jobs out to that executor. Nothing here touches gpui //! state. +mod file_copy; +pub use file_copy::duplicate_file; + use std::{ collections::HashSet, path::{Path, PathBuf}, diff --git a/apps/desktop-gpui/src/library/file_copy.rs b/apps/desktop-gpui/src/library/file_copy.rs new file mode 100644 index 00000000000..859c7b1103a --- /dev/null +++ b/apps/desktop-gpui/src/library/file_copy.rs @@ -0,0 +1,157 @@ +use std::{ + ffi::OsString, + fs::{File, OpenOptions}, + io::{self, ErrorKind}, + path::{Path, PathBuf}, +}; + +const MAX_FILE_NAME_BYTES: usize = 255; + +fn copy_path(source: &Path, number: u64) -> PathBuf { + let mut suffix = OsString::from(" copy"); + if number > 1 { + suffix.push(format!(" {number}")); + } + if let Some(extension) = source.extension() { + suffix.push("."); + suffix.push(extension); + } + let stem = source.file_stem().unwrap_or_default(); + let mut name = if stem.len() + suffix.len() > MAX_FILE_NAME_BYTES { + let mut stem = stem.to_string_lossy().into_owned(); + while stem.len() + suffix.len() > MAX_FILE_NAME_BYTES && stem.pop().is_some() {} + OsString::from(stem) + } else { + stem.to_os_string() + }; + name.push(suffix); + source.with_file_name(name) +} + +pub fn duplicate_file(source: &Path) -> Result { + duplicate(source).map_err(|error| format!("Failed to copy file: {error}")) +} + +fn duplicate(source: &Path) -> io::Result { + let mut input = File::open(source)?; + if !input.metadata()?.is_file() { + return Err(io::Error::new( + ErrorKind::InvalidInput, + "only files can be copied", + )); + } + let mut number = 1; + loop { + let destination = copy_path(source, number); + match OpenOptions::new() + .write(true) + .create_new(true) + .open(&destination) + { + Ok(mut output) => { + if let Err(error) = io::copy(&mut input, &mut output) { + drop(output); + let _ = std::fs::remove_file(&destination); + return Err(error); + } + return Ok(destination); + } + // Windows reports a directory already at the name as access denied. + Err(error) + if error.kind() == ErrorKind::AlreadyExists + || (error.kind() == ErrorKind::PermissionDenied && destination.is_dir()) => + { + number += 1; + } + Err(error) => return Err(error), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn copy_names_preserve_extensions() { + for (source, expected) in [ + ("video.mp4", "video copy.mp4"), + ("video.final.mp4", "video.final copy.mp4"), + ("recording", "recording copy"), + (".hidden", ".hidden copy"), + ("日本語.png", "日本語 copy.png"), + ("video copy.mp4", "video copy copy.mp4"), + ] { + assert_eq!(copy_path(Path::new(source), 1), Path::new(expected)); + } + assert_eq!( + copy_path(Path::new("/output/video.mp4"), 2), + Path::new("/output/video copy 2.mp4") + ); + } + + #[test] + fn copies_of_the_longest_names_still_fit() { + let dir = tempfile::tempdir().unwrap(); + for stem in ["a".repeat(251), "日".repeat(83)] { + let source = dir.path().join(format!("{stem}.mp4")); + std::fs::write(&source, b"frames").unwrap(); + let first = duplicate_file(&source).unwrap(); + let second = duplicate_file(&source).unwrap(); + for (copy, suffix) in [(first, " copy.mp4"), (second, " copy 2.mp4")] { + let name = copy.file_name().unwrap().to_str().unwrap(); + assert!(name.len() <= 255, "{name}"); + assert!(name.ends_with(suffix), "{name}"); + assert_eq!(std::fs::read(copy).unwrap(), b"frames"); + } + } + } + + #[test] + fn existing_copies_are_never_overwritten() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("video.final.mp4"); + std::fs::write(&source, b"original").unwrap(); + std::fs::write(dir.path().join("video.final copy.mp4"), b"first").unwrap(); + std::fs::create_dir(dir.path().join("video.final copy 2.mp4")).unwrap(); + let copy = duplicate_file(&source).unwrap(); + assert_eq!(copy, dir.path().join("video.final copy 3.mp4")); + assert_eq!(std::fs::read(copy).unwrap(), b"original"); + assert_eq!( + std::fs::read(dir.path().join("video.final copy.mp4")).unwrap(), + b"first" + ); + assert_eq!(std::fs::read(source).unwrap(), b"original"); + assert!(dir.path().join("video.final copy 2.mp4").is_dir()); + } + + #[test] + fn concurrent_copies_get_distinct_names() { + let dir = tempfile::tempdir().unwrap(); + let source = dir.path().join("screenshot.png"); + std::fs::write(&source, b"pixels").unwrap(); + let copies = std::thread::scope(|scope| { + let first = scope.spawn(|| duplicate_file(&source).unwrap()); + let second = scope.spawn(|| duplicate_file(&source).unwrap()); + [first.join().unwrap(), second.join().unwrap()] + }); + assert_ne!(copies[0], copies[1]); + for copy in copies { + assert_eq!(std::fs::read(copy).unwrap(), b"pixels"); + } + } + + #[test] + fn missing_files_and_project_directories_fail_without_a_copy() { + let dir = tempfile::tempdir().unwrap(); + assert!( + duplicate_file(&dir.path().join("missing.mp4")) + .unwrap_err() + .starts_with("Failed to copy file:") + ); + let project = dir.path().join("recording.cap"); + std::fs::create_dir(&project).unwrap(); + assert!(duplicate_file(&project).is_err()); + assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 1); + } +}