Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

fix: implement native GPUI clipboard transfers

Richie McIlroy657e0f17086d
diff --git a/apps/desktop-gpui/Cargo.lock b/apps/desktop-gpui/Cargo.lock
index 1a4ac2dd8..504a5feea 100644
--- a/apps/desktop-gpui/Cargo.lock
+++ b/apps/desktop-gpui/Cargo.lock
@@ -1551,6 +1551,7 @@ dependencies = [
"cap-utils",
"chrono",
"cidre",
+ "clipboard-rs",
"core-foundation 0.10.1",
"core-video",
"cosmic-text 0.14.2",
@@ -2226,6 +2227,31 @@ version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
+[[package]]
+name = "clipboard-rs"
+version = "0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "afede46921767868c5c7f8f55202bdd8bec0bab6bc9605174200f45924f93c62"
+dependencies = [
+ "clipboard-win",
+ "image 0.25.10",
+ "objc2 0.6.4",
+ "objc2-app-kit 0.3.2",
+ "objc2-foundation 0.3.2",
+ "windows 0.59.0",
+ "x11rb",
+]
+
+[[package]]
+name = "clipboard-win"
+version = "5.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bde03770d3df201d4fb868f2c9c59e66a3e4e2bd06692a0fe701e7103c7e84d4"
+dependencies = [
+ "error-code",
+ "windows-win",
+]
+
[[package]]
name = "cmake"
version = "0.1.58"
@@ -3487,6 +3513,12 @@ dependencies = [
"windows-sys 0.61.2",
]
+[[package]]
+name = "error-code"
+version = "3.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7"
+
[[package]]
name = "esaxx-rs"
version = "0.1.10"
@@ -12462,6 +12494,16 @@ dependencies = [
"windows-targets 0.52.6",
]
+[[package]]
+name = "windows"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f919aee0a93304be7f62e8e5027811bbba96bcb1de84d6618be56e43f8a32a1"
+dependencies = [
+ "windows-core 0.59.0",
+ "windows-targets 0.53.5",
+]
+
[[package]]
name = "windows"
version = "0.60.0"
@@ -12575,6 +12617,19 @@ dependencies = [
"windows-targets 0.52.6",
]
+[[package]]
+name = "windows-core"
+version = "0.59.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "810ce18ed2112484b0d4e15d022e5f598113e220c53e373fb31e67e21670c1ce"
+dependencies = [
+ "windows-implement 0.59.0",
+ "windows-interface 0.59.3",
+ "windows-result 0.3.4",
+ "windows-strings 0.3.1",
+ "windows-targets 0.53.5",
+]
+
[[package]]
name = "windows-core"
version = "0.60.1"
@@ -13004,6 +13059,15 @@ dependencies = [
"windows-link 0.2.1",
]
+[[package]]
+name = "windows-win"
+version = "3.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "58e23e33622b3b52f948049acbec9bcc34bf6e26d74176b88941f213c75cf2dc"
+dependencies = [
+ "error-code",
+]
+
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.42.2"
diff --git a/apps/desktop-gpui/Cargo.toml b/apps/desktop-gpui/Cargo.toml
index b2d12446f..623a243ca 100644
--- a/apps/desktop-gpui/Cargo.toml
+++ b/apps/desktop-gpui/Cargo.toml
@@ -175,6 +175,7 @@ tokio = { version = "1", features = ["rt-multi-thread", "time"] }
libc = "0.2"
[target.'cfg(windows)'.dependencies]
+clipboard-rs = "0.2.4"
raw-window-handle = "0.6"
tray-icon = { version = "0.21.1", default-features = false }
windows-sys = { version = "0.59", features = [
diff --git a/apps/desktop-gpui/patches/zed-gpui.patch b/apps/desktop-gpui/patches/zed-gpui.patch
index cecc831ae..5b79c8bb8 100644
--- a/apps/desktop-gpui/patches/zed-gpui.patch
+++ b/apps/desktop-gpui/patches/zed-gpui.patch
@@ -1,8 +1,34 @@
+diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rs
+index 900e78a367e2..d0cab13a2cb7 100644
+--- a/crates/gpui/src/app.rs
++++ b/crates/gpui/src/app.rs
+@@ -1350,6 +1350,11 @@
+ self.platform.write_to_clipboard(item)
+ }
+
++ /// Writes data to the platform clipboard, returning an error when the platform cannot accept it.
++ pub fn try_write_to_clipboard(&self, item: ClipboardItem) -> Result<()> {
++ self.platform.try_write_to_clipboard(item)
++ }
++
+ /// Reads data from the primary selection buffer.
+ /// Only available on Linux.
+ #[cfg(any(target_os = "linux", target_os = "freebsd"))]
diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs
-index 20600c3eb519..11bf6cfb0a00 100644
+index 20600c3eb519..9d92bb46f943 100644
--- a/crates/gpui/src/platform.rs
+++ b/crates/gpui/src/platform.rs
-@@ -812,6 +812,17 @@
+@@ -298,6 +298,9 @@
+
+ fn read_from_clipboard(&self) -> Option<ClipboardItem>;
+ fn write_to_clipboard(&self, item: ClipboardItem);
++ fn try_write_to_clipboard(&self, _item: ClipboardItem) -> Result<()> {
++ anyhow::bail!("Writing this clipboard item is unsupported")
++ }
+
+ #[cfg(any(target_os = "linux", target_os = "freebsd"))]
+ fn read_from_primary(&self) -> Option<ClipboardItem>;
+@@ -812,6 +815,17 @@
detail: Option<&str>,
answers: &[PromptButton],
) -> Option<oneshot::Receiver<usize>>;
diff --git a/apps/desktop-gpui/patches/zed-linux.patch b/apps/desktop-gpui/patches/zed-linux.patch
index 89f7cc4fe..e84a49f5d 100644
--- a/apps/desktop-gpui/patches/zed-linux.patch
+++ b/apps/desktop-gpui/patches/zed-linux.patch
@@ -1,11 +1,67 @@
+diff --git a/crates/gpui_linux/src/linux/platform.rs b/crates/gpui_linux/src/linux/platform.rs
+index 876f931663fa..062af4e8c9b9 100644
+--- a/crates/gpui_linux/src/linux/platform.rs
++++ b/crates/gpui_linux/src/linux/platform.rs
+@@ -87,6 +87,9 @@
+ fn reveal_path(&self, path: PathBuf);
+ fn write_to_primary(&self, item: ClipboardItem);
+ fn write_to_clipboard(&self, item: ClipboardItem);
++ fn try_write_to_clipboard(&self, _item: ClipboardItem) -> anyhow::Result<()> {
++ anyhow::bail!("Writing this clipboard item is unsupported")
++ }
+ fn read_from_primary(&self) -> Option<ClipboardItem>;
+ fn read_from_clipboard(&self) -> Option<ClipboardItem>;
+ fn active_window(&self) -> Option<AnyWindowHandle>;
+@@ -735,6 +738,10 @@
+ self.inner.write_to_clipboard(item)
+ }
+
++ fn try_write_to_clipboard(&self, item: ClipboardItem) -> anyhow::Result<()> {
++ self.inner.try_write_to_clipboard(item)
++ }
++
+ fn read_from_primary(&self) -> Option<ClipboardItem> {
+ self.inner.read_from_primary()
+ }
diff --git a/crates/gpui_linux/src/linux/wayland/client.rs b/crates/gpui_linux/src/linux/wayland/client.rs
-index fdc40a3de87e..09c7fb416e8a 100644
+index fdc40a3de87e..c41fa8d6aebb 100644
--- a/crates/gpui_linux/src/linux/wayland/client.rs
+++ b/crates/gpui_linux/src/linux/wayland/client.rs
-@@ -1301,6 +1301,25 @@
+@@ -1121,6 +1121,30 @@
+ }
+ }
+
++ fn try_write_to_clipboard(&self, item: gpui::ClipboardItem) -> anyhow::Result<()> {
++ let mut state = self.0.borrow_mut();
++ let data_device_manager = state.globals.data_device_manager.clone().ok_or_else(|| {
++ anyhow::anyhow!("Wayland clipboard data device manager is unavailable")
++ })?;
++ let data_device = state
++ .data_device
++ .clone()
++ .ok_or_else(|| anyhow::anyhow!("Wayland clipboard data device is unavailable"))?;
++ if state.mouse_focused_window.is_none() && state.keyboard_focused_window.is_none() {
++ anyhow::bail!("Wayland clipboard requires a focused window");
++ }
++
++ let mime_types = state.clipboard.mime_types(&item)?;
++ state.clipboard.set(item);
++ let serial = state.serial_tracker.get_latest();
++ let data_source = data_device_manager.create_data_source(&state.globals.qh, ());
++ for mime_type in mime_types {
++ data_source.offer(mime_type);
++ }
++ data_device.set_selection(Some(&data_source), serial);
++ Ok(())
++ }
++
+ fn read_from_primary(&self) -> Option<gpui::ClipboardItem> {
+ self.0.borrow_mut().clipboard.read_primary()
+ }
+@@ -1301,6 +1325,25 @@
delegate_noop!(WaylandClientStatePtr: ignore wp_viewporter::WpViewporter);
delegate_noop!(WaylandClientStatePtr: ignore wp_viewport::WpViewport);
-
+
+impl Dispatch<WlCallback, super::window::VisibilitySync> for WaylandClientStatePtr {
+ fn event(
+ this: &mut WaylandClientStatePtr,
@@ -28,6 +84,305 @@ index fdc40a3de87e..09c7fb416e8a 100644
impl Dispatch<WlCallback, ObjectId> for WaylandClientStatePtr {
fn event(
state: &mut WaylandClientStatePtr,
+diff --git a/crates/gpui_linux/src/linux/wayland/clipboard.rs b/crates/gpui_linux/src/linux/wayland/clipboard.rs
+index dfedf53f6dfa..fb40a8b391f1 100644
+--- a/crates/gpui_linux/src/linux/wayland/clipboard.rs
++++ b/crates/gpui_linux/src/linux/wayland/clipboard.rs
+@@ -1,6 +1,6 @@
+ use std::{
+ fs::File,
+- io::{ErrorKind, Write},
++ io::{self, ErrorKind, Write},
+ os::fd::{AsRawFd, BorrowedFd, OwnedFd},
+ };
+
+@@ -15,11 +15,13 @@
+ platform::{PIPE_READ_TIMEOUT, read_fd_with_timeout},
+ };
+ use gpui::{ClipboardEntry, ClipboardItem, Image, ImageFormat, hash};
++use url::Url;
+
+ /// Text mime types that we'll offer to other programs.
+ pub(crate) const TEXT_MIME_TYPES: [&str; 3] =
+ ["text/plain;charset=utf-8", "UTF8_STRING", "text/plain"];
+ pub(crate) const FILE_LIST_MIME_TYPE: &str = "text/uri-list";
++pub(crate) const GNOME_COPY_FILES_MIME_TYPE: &str = "x-special/gnome-copied-files";
+
+ /// Text mime types that we'll accept from other programs.
+ pub(crate) const ALLOWED_TEXT_MIME_TYPES: [&str; 2] = ["text/plain;charset=utf-8", "UTF8_STRING"];
+@@ -180,20 +182,94 @@
+ self.self_mime.clone()
+ }
+
+- pub fn send(&self, _mime_type: String, fd: OwnedFd) {
+- if let Some(text) = self.contents.as_ref().and_then(|contents| contents.text()) {
+- self.send_internal(fd, text.as_bytes().to_owned());
++ pub(crate) fn mime_types(&self, item: &ClipboardItem) -> anyhow::Result<Vec<String>> {
++ let has_text = item
++ .entries()
++ .iter()
++ .any(|entry| matches!(entry, ClipboardEntry::String(_)));
++ let has_image = item.entries().iter().any(
++ |entry| matches!(entry, ClipboardEntry::Image(image) if !image.bytes().is_empty()),
++ );
++ let has_files = item.entries().iter().any(|entry| {
++ matches!(entry, ClipboardEntry::ExternalPaths(paths) if !paths.paths().is_empty())
++ });
++
++ if !has_text && !has_image && !has_files {
++ anyhow::bail!("clipboard item has no transferable data");
++ }
++ if has_files {
++ file_uris(item)?;
++ }
++
++ let mut mime_types = Vec::new();
++ if has_text {
++ mime_types.extend(
++ TEXT_MIME_TYPES
++ .iter()
++ .map(|mime_type| (*mime_type).to_owned()),
++ );
++ }
++ for entry in item.entries() {
++ if let ClipboardEntry::Image(image) = entry
++ && !image.bytes().is_empty()
++ {
++ mime_types.push(image.format().mime_type().to_owned());
++ }
++ }
++ if has_files {
++ mime_types.push(FILE_LIST_MIME_TYPE.to_owned());
++ mime_types.push(GNOME_COPY_FILES_MIME_TYPE.to_owned());
++ }
++ mime_types.push(self.self_mime());
++ Ok(mime_types)
++ }
++
++ pub fn send(&self, mime_type: String, fd: OwnedFd) {
++ let Some(contents) = self.contents.as_ref() else {
++ return;
++ };
++ match Self::bytes_for_mime(contents, &mime_type) {
++ Ok(Some(bytes)) => self.send_internal(fd, bytes),
++ Ok(None) => log::warn!("No clipboard payload is available for MIME type {mime_type}"),
++ Err(error) => log::error!("Failed to prepare clipboard MIME type {mime_type}: {error}"),
++ }
++ }
++
++ pub fn send_primary(&self, mime_type: String, fd: OwnedFd) {
++ let Some(contents) = self.primary_contents.as_ref() else {
++ return;
++ };
++ match Self::bytes_for_mime(contents, &mime_type) {
++ Ok(Some(bytes)) => self.send_internal(fd, bytes),
++ Ok(None) => {
++ log::warn!("No primary clipboard payload is available for MIME type {mime_type}")
++ }
++ Err(error) => {
++ log::error!("Failed to prepare primary clipboard MIME type {mime_type}: {error}")
++ }
+ }
+ }
+
+- pub fn send_primary(&self, _mime_type: String, fd: OwnedFd) {
+- if let Some(text) = self
+- .primary_contents
+- .as_ref()
+- .and_then(|contents| contents.text())
+- {
+- self.send_internal(fd, text.as_bytes().to_owned());
++ fn bytes_for_mime(item: &ClipboardItem, mime_type: &str) -> anyhow::Result<Option<Vec<u8>>> {
++ if TEXT_MIME_TYPES.contains(&mime_type) {
++ return Ok(text_bytes(item));
++ }
++ if mime_type == FILE_LIST_MIME_TYPE {
++ return Ok(Some(file_uris(item)?.join("\r\n").into_bytes()));
++ }
++ if mime_type == GNOME_COPY_FILES_MIME_TYPE {
++ return Ok(Some(
++ format!("copy\n{}", file_uris(item)?.join("\n")).into_bytes(),
++ ));
+ }
++ for entry in item.entries() {
++ if let ClipboardEntry::Image(image) = entry
++ && image.format().mime_type() == mime_type
++ {
++ return Ok(Some(image.bytes().to_vec()));
++ }
++ }
++ Ok(None)
+ }
+
+ pub fn read(&mut self) -> Option<ClipboardItem> {
+@@ -233,31 +309,145 @@
+ }
+
+ fn send_internal(&self, fd: OwnedFd, bytes: Vec<u8>) {
++ if let Err(error) = set_nonblocking(&fd) {
++ log::error!("Failed to set Wayland clipboard pipe nonblocking: {error}");
++ drop(fd);
++ return;
++ }
+ let mut written = 0;
+- self.loop_handle
+- .insert_source(
+- calloop::generic::Generic::new(
+- File::from(fd),
+- calloop::Interest::WRITE,
+- calloop::Mode::Level,
+- ),
+- move |_, file, _| {
+- let file = unsafe { file.get_mut() };
+- loop {
+- match file.write(&bytes[written..]) {
+- Ok(n) if written + n == bytes.len() => {
+- written += n;
+- break Ok(PostAction::Remove);
+- }
+- Ok(n) => written += n,
+- Err(err) if err.kind() == ErrorKind::WouldBlock => {
+- break Ok(PostAction::Continue);
+- }
+- Err(_) => break Ok(PostAction::Remove),
++ if let Err(error) = self.loop_handle.insert_source(
++ calloop::generic::Generic::new(
++ File::from(fd),
++ calloop::Interest::WRITE,
++ calloop::Mode::Level,
++ ),
++ move |_, file, _| {
++ let file = unsafe { file.get_mut() };
++ loop {
++ match file.write(&bytes[written..]) {
++ Ok(n) if written + n == bytes.len() => {
++ written += n;
++ break Ok(PostAction::Remove);
+ }
++ Ok(0) => break Ok(PostAction::Remove),
++ Ok(n) => written += n,
++ Err(err) if err.kind() == ErrorKind::Interrupted => continue,
++ Err(err) if err.kind() == ErrorKind::WouldBlock => {
++ break Ok(PostAction::Continue);
++ }
++ Err(err) if err.kind() == ErrorKind::WriteZero => {
++ break Ok(PostAction::Remove);
++ }
++ Err(_) => break Ok(PostAction::Remove),
+ }
+- },
++ }
++ },
++ ) {
++ log::error!("Failed to schedule Wayland clipboard transfer: {error}");
++ }
++ }
++}
++
++fn set_nonblocking(fd: &OwnedFd) -> io::Result<()> {
++ let raw_fd = fd.as_raw_fd();
++ let flags = unsafe { libc::fcntl(raw_fd, libc::F_GETFL) };
++ if flags == -1 {
++ return Err(io::Error::last_os_error());
++ }
++ if unsafe { libc::fcntl(raw_fd, libc::F_SETFL, flags | libc::O_NONBLOCK) } == -1 {
++ return Err(io::Error::last_os_error());
++ }
++ Ok(())
++}
++
++fn text_bytes(item: &ClipboardItem) -> Option<Vec<u8>> {
++ let mut text = String::new();
++ let mut has_text = false;
++ for entry in item.entries() {
++ if let ClipboardEntry::String(value) = entry {
++ has_text = true;
++ text.push_str(value.text());
++ }
++ }
++ has_text.then(|| text.into_bytes())
++}
++
++fn file_uris(item: &ClipboardItem) -> anyhow::Result<Vec<String>> {
++ let mut uris = Vec::new();
++ for entry in item.entries() {
++ if let ClipboardEntry::ExternalPaths(paths) = entry {
++ for path in paths.paths() {
++ let uri = Url::from_file_path(path).map_err(|_| {
++ anyhow::anyhow!("cannot convert {} to a file URI", path.display())
++ })?;
++ uris.push(uri.to_string());
++ }
++ }
++ }
++ if uris.is_empty() {
++ anyhow::bail!("clipboard file list is empty");
++ }
++ Ok(uris)
++}
++
++#[cfg(test)]
++mod tests {
++ use std::path::PathBuf;
++
++ use super::*;
++
++ #[test]
++ fn file_uris_percent_encode_paths() {
++ let item = ClipboardItem {
++ entries: vec![ClipboardEntry::ExternalPaths(gpui::ExternalPaths(
++ smallvec::smallvec![
++ PathBuf::from("/tmp/clip board/#café.txt"),
++ PathBuf::from("/tmp/second.txt")
++ ],
++ ))],
++ };
++
++ assert_eq!(
++ file_uris(&item).unwrap(),
++ vec![
++ "file:///tmp/clip%20board/%23caf%C3%A9.txt".to_owned(),
++ "file:///tmp/second.txt".to_owned()
++ ]
++ );
++ }
++
++ #[test]
++ fn image_payload_uses_its_declared_mime() {
++ let bytes = vec![1, 2, 3];
++ let image = Image::from_bytes(ImageFormat::Png, bytes.clone());
++ let item = ClipboardItem::new_image(&image);
++
++ assert_eq!(
++ Clipboard::bytes_for_mime(&item, "image/png").unwrap(),
++ Some(bytes)
++ );
++ assert_eq!(
++ Clipboard::bytes_for_mime(&item, "image/jpeg").unwrap(),
++ None
++ );
++ }
++
++ #[test]
++ fn gnome_payload_contains_all_file_uris() {
++ let item = ClipboardItem {
++ entries: vec![ClipboardEntry::ExternalPaths(gpui::ExternalPaths(
++ smallvec::smallvec![PathBuf::from("/tmp/one.txt"), PathBuf::from("/tmp/two.txt")],
++ ))],
++ };
++
++ assert_eq!(
++ String::from_utf8(
++ Clipboard::bytes_for_mime(&item, GNOME_COPY_FILES_MIME_TYPE)
++ .unwrap()
++ .unwrap()
+ )
+- .unwrap();
++ .unwrap(),
++ "copy\nfile:///tmp/one.txt\nfile:///tmp/two.txt"
++ );
+ }
+ }
diff --git a/crates/gpui_linux/src/linux/wayland/window.rs b/crates/gpui_linux/src/linux/wayland/window.rs
index 993b2ff3fadc..e8916c11025f 100644
--- a/crates/gpui_linux/src/linux/wayland/window.rs
@@ -1033,20 +1388,51 @@ index 993b2ff3fadc..e8916c11025f 100644
+ }
+}
diff --git a/crates/gpui_linux/src/linux/x11/client.rs b/crates/gpui_linux/src/linux/x11/client.rs
+index 0c8c9b4e20b8..701ae28fe440 100644
--- a/crates/gpui_linux/src/linux/x11/client.rs
+++ b/crates/gpui_linux/src/linux/x11/client.rs
-@@ -814,3 +814,2 @@
+@@ -811,11 +811,12 @@
+ let [atom, arg1, arg2, arg3, arg4] = event.data.as_data32();
+ let mut state = self.0.borrow_mut();
+
- if atom == state.atoms.WM_DELETE_WINDOW && window.should_close() {
- // window "x" button clicked by user
- // Rest of the close logic is handled in drop_window()
+ if atom == state.atoms.WM_DELETE_WINDOW {
+ // Closing can flush app effects that open another window.
-@@ -818 +817,3 @@
+ drop(state);
- window.close();
+ if window.should_close() {
+ window.close();
+ }
-@@ -1797 +1798,16 @@
+ state = self.0.borrow_mut();
+ } else if atom == state.atoms._NET_WM_SYNC_REQUEST {
+ window.state.borrow_mut().last_sync_counter =
+@@ -1756,6 +1757,20 @@
+ state.clipboard_item.replace(item);
+ }
+
++ fn try_write_to_clipboard(&self, item: gpui::ClipboardItem) -> anyhow::Result<()> {
++ let mut state = self.0.borrow_mut();
++ state
++ .clipboard
++ .set_item(
++ &item,
++ clipboard::ClipboardKind::Clipboard,
++ clipboard::WaitConfig::None,
++ )
++ .context("X11: Failed to write clipboard item")?;
++ state.clipboard_item.replace(item);
++ Ok(())
++ }
++
+ fn read_from_primary(&self) -> Option<gpui::ClipboardItem> {
+ let state = self.0.borrow_mut();
+ state
+@@ -1794,7 +1809,22 @@
+ return;
+ };
+
- event_loop.run(None, &mut self.clone(), |_| {}).log_err();
+ let xcb_connection = self.0.borrow().xcb_connection.clone();
+ let loop_signal = event_loop.get_signal();
@@ -1064,6 +1450,168 @@ diff --git a/crates/gpui_linux/src/linux/x11/client.rs b/crates/gpui_linux/src/l
+ }
+ })
+ .log_err();
+ }
+
+ fn active_window(&self) -> Option<AnyWindowHandle> {
+diff --git a/crates/gpui_linux/src/linux/x11/clipboard.rs b/crates/gpui_linux/src/linux/x11/clipboard.rs
+index 706e7b096588..591535333fa2 100644
+--- a/crates/gpui_linux/src/linux/x11/clipboard.rs
++++ b/crates/gpui_linux/src/linux/x11/clipboard.rs
+@@ -22,6 +22,7 @@
+ borrow::Cow,
+ cell::RefCell,
+ collections::{HashMap, hash_map::Entry},
++ path::PathBuf,
+ sync::{
+ Arc,
+ atomic::{AtomicBool, Ordering},
+@@ -47,8 +48,9 @@
+ wrapper::ConnectionExt as _,
+ };
+
+-use gpui::{ClipboardItem, Image, ImageFormat, hash};
++use gpui::{ClipboardEntry, ClipboardItem, Image, ImageFormat, hash};
+ use strum::IntoEnumIterator;
++use url::Url;
+
+ type Result<T, E = Error> = std::result::Result<T, E>;
+
+@@ -77,8 +79,9 @@
+ TEXT,
+ TEXT_MIME_UNKNOWN: b"text/plain",
+
+- // HTML: b"text/html",
+- // URI_LIST: b"text/uri-list",
++ FILE_LIST: b"text/uri-list",
++ GNOME_COPY_FILES: b"x-special/gnome-copied-files",
++ NAUTILUS_FILE_LIST: b"x-special/nautilus-clipboard",
+
+ PNG__MIME: ImageFormat::mime_type(ImageFormat::Png ).as_bytes(),
+ JPEG_MIME: ImageFormat::mime_type(ImageFormat::Jpeg).as_bytes(),
+@@ -990,6 +993,47 @@
+ self.inner.write(data, selection, wait)
+ }
+
++ pub(crate) fn set_item(
++ &self,
++ item: &ClipboardItem,
++ selection: ClipboardKind,
++ wait: WaitConfig,
++ ) -> Result<()> {
++ let mut data = Vec::new();
++ let atoms = self.inner.atoms;
++ let mut text = String::new();
++ let mut has_text = false;
++
++ for entry in item.entries() {
++ match entry {
++ ClipboardEntry::String(value) => {
++ has_text = true;
++ text.push_str(value.text());
++ }
++ ClipboardEntry::Image(image) => data.push(ClipboardData {
++ bytes: image.bytes().to_vec(),
++ format: self.image_format_atom(image.format()),
++ }),
++ ClipboardEntry::ExternalPaths(paths) => {
++ data.extend(file_uri_list_to_clipboard_data(paths.paths(), atoms)?);
++ }
++ }
++ }
++
++ if has_text {
++ data.push(ClipboardData {
++ bytes: text.into_bytes(),
++ format: atoms.UTF8_STRING,
++ });
++ }
++
++ if data.is_empty() {
++ return Err(Error::unknown("clipboard item has no transferable data"));
++ }
++
++ self.inner.write(data, selection, wait)
++ }
++
+ fn image_format_atom(&self, format: ImageFormat) -> Atom {
+ match format {
+ ImageFormat::Png => self.inner.atoms.PNG__MIME,
+@@ -1014,7 +1058,7 @@
+ let format = self.image_format_atom(image.format);
+ let data = vec![ClipboardData {
+ bytes: image.bytes,
+- format: self.inner.atoms.PNG__MIME,
++ format,
+ }];
+ self.inner.write(data, selection, wait)
+ }
+@@ -1138,6 +1182,66 @@
+ }
+ }
+
++fn file_uri_list_to_clipboard_data(paths: &[PathBuf], atoms: Atoms) -> Result<Vec<ClipboardData>> {
++ if paths.is_empty() {
++ return Err(Error::unknown("clipboard file list is empty"));
++ }
++
++ let uris = paths
++ .iter()
++ .map(|path| {
++ Url::from_file_path(path)
++ .map(|url| url.to_string())
++ .map_err(|_| {
++ Error::unknown(format!("cannot convert {} to a file URI", path.display()))
++ })
++ })
++ .collect::<Result<Vec<_>>>()?;
++ let plain_paths = paths
++ .iter()
++ .map(|path| path.to_string_lossy().into_owned())
++ .collect::<Vec<_>>();
++ let plain_crlf = plain_paths.join("\r\n");
++ let plain_lf = plain_paths.join("\n");
++ let uri_crlf = uris.join("\r\n");
++ let gnome = format!("copy\n{}", uris.join("\n"));
++
++ Ok(vec![
++ ClipboardData {
++ bytes: plain_crlf.as_bytes().to_vec(),
++ format: atoms.TEXT_MIME_UNKNOWN,
++ },
++ ClipboardData {
++ bytes: plain_crlf.as_bytes().to_vec(),
++ format: atoms.UTF8_MIME_0,
++ },
++ ClipboardData {
++ bytes: plain_lf.as_bytes().to_vec(),
++ format: atoms.STRING,
++ },
++ ClipboardData {
++ bytes: plain_lf.as_bytes().to_vec(),
++ format: atoms.TEXT,
++ },
++ ClipboardData {
++ bytes: plain_lf.as_bytes().to_vec(),
++ format: atoms.UTF8_STRING,
++ },
++ ClipboardData {
++ bytes: uri_crlf.as_bytes().to_vec(),
++ format: atoms.FILE_LIST,
++ },
++ ClipboardData {
++ bytes: gnome.as_bytes().to_vec(),
++ format: atoms.GNOME_COPY_FILES,
++ },
++ ClipboardData {
++ bytes: gnome.into_bytes(),
++ format: atoms.NAUTILUS_FILE_LIST,
++ },
++ ])
++}
++
+ /// Clipboard selection
+ ///
+ /// Linux has a concept of clipboard "selections" which tend to be used in different contexts. This
diff --git a/crates/gpui_linux/src/linux/x11/window.rs b/crates/gpui_linux/src/linux/x11/window.rs
--- a/crates/gpui_linux/src/linux/x11/window.rs
+++ b/crates/gpui_linux/src/linux/x11/window.rs
diff --git a/apps/desktop-gpui/src/editor_export.rs b/apps/desktop-gpui/src/editor_export.rs
index 516e53828..05d062323 100644
--- a/apps/desktop-gpui/src/editor_export.rs
+++ b/apps/desktop-gpui/src/editor_export.rs
@@ -1,6 +1,6 @@
//! Editor export page -- `routes/editor/ExportPage.tsx`, 1:1 layout.
-use std::path::PathBuf;
+use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Duration;
@@ -207,6 +207,10 @@ impl ExportUi {
advanced_open: false,
organization_id: None,
});
+ Self::from_preferences(prefs)
+ }
+
+ fn from_preferences(prefs: ExportPrefs) -> Self {
Self {
destination: ExportDestination::from_slug(&prefs.export_to),
format: ExportFormatKind::from_slug(&prefs.format),
@@ -270,6 +274,36 @@ impl ExportUi {
self.custom_bpp
.is_some_and(|bpp| (bpp - self.compression.bits_per_pixel()).abs() > 0.001)
}
+
+ fn clipboard_retry_path(&self) -> Option<&Path> {
+ if self.phase == ExportPhase::Failed && self.destination == ExportDestination::Clipboard {
+ self.output_path.as_deref()
+ } else {
+ None
+ }
+ }
+
+ fn copy_completed_export(
+ &mut self,
+ path: PathBuf,
+ copy: impl FnOnce(&Path) -> Result<(), String>,
+ ) {
+ self.output_path = Some(path.clone());
+ self.error = None;
+ if self.close_requested || self.cancel.load(Ordering::Relaxed) {
+ self.phase = ExportPhase::Idle;
+ return;
+ }
+
+ self.phase = ExportPhase::Copying;
+ match copy(&path) {
+ Ok(()) => self.phase = ExportPhase::Done,
+ Err(error) => {
+ self.phase = ExportPhase::Failed;
+ self.error = Some(error);
+ }
+ }
+ }
}
fn has_transparent_background(project: &cap_project::ProjectConfiguration) -> bool {
@@ -643,29 +677,9 @@ impl EditorWindow {
if destination == ExportDestination::Clipboard {
let _ = this.update(cx, |this, cx| {
if let Some(ui) = this.export.as_mut() {
- ui.phase = ExportPhase::Copying;
- }
- cx.notify();
- });
- let copied = cx
- .background_executor()
- .spawn({
- let path = path.clone();
- async move { platform::copy_file_to_clipboard(&path) }
- })
- .await;
- let _ = this.update(cx, |this, cx| {
- if let Some(ui) = this.export.as_mut() {
- match copied {
- Ok(()) => {
- ui.phase = ExportPhase::Done;
- ui.output_path = Some(path);
- }
- Err(error) => {
- ui.phase = ExportPhase::Failed;
- ui.error = Some(error);
- }
- }
+ ui.copy_completed_export(path, |path| {
+ platform::copy_file_to_clipboard(path, cx)
+ });
}
cx.notify();
});
@@ -710,6 +724,19 @@ impl EditorWindow {
}));
}
+ fn retry_clipboard_copy(&mut self, window: &mut Window, cx: &mut Context<Self>) {
+ let Some(ui) = self.export.as_mut() else {
+ return;
+ };
+ let Some(path) = ui.clipboard_retry_path().map(Path::to_path_buf) else {
+ return;
+ };
+ ui.cancel = Arc::new(AtomicBool::new(false));
+ ui.copy_completed_export(path, |path| platform::copy_file_to_clipboard(path, cx));
+ cx.notify();
+ self.finish_requested_export_close(window, cx);
+ }
+
fn start_share_sign_in(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let Some(ui) = self.export.as_mut() else {
return;
@@ -1864,6 +1891,9 @@ impl EditorWindow {
}
ExportPhase::Done if ui.destination == ExportDestination::Link => "Upload complete",
ExportPhase::Done => "Export complete",
+ ExportPhase::Failed if ui.clipboard_retry_path().is_some() => {
+ "Export complete; clipboard copy failed"
+ }
ExportPhase::Failed => "Export failed",
ExportPhase::Idle | ExportPhase::ChoosingFile => "",
};
@@ -1982,8 +2012,24 @@ impl EditorWindow {
)
})
.when(ui.phase == ExportPhase::Done || ui.phase == ExportPhase::Failed, |this| {
- this .when(
- ui.phase == ExportPhase::Done && ui.destination == ExportDestination::File,
+ this.when(ui.clipboard_retry_path().is_some(), |this| {
+ this.child(
+ ui::Button::plain(
+ &theme,
+ "export-retry-copy",
+ ui::ButtonVariant::Gray,
+ ui::ButtonSize::Md,
+ )
+ .icon("icons/copy.svg")
+ .label("Retry Copy")
+ .on_click(cx.listener(|this, _, window, cx| {
+ this.retry_clipboard_copy(window, cx);
+ })),
+ )
+ })
+ .when(
+ (ui.phase == ExportPhase::Done && ui.destination == ExportDestination::File)
+ || ui.clipboard_retry_path().is_some(),
|this| {
let path = ui.output_path.clone();
this.child(
@@ -2175,12 +2221,81 @@ async fn run_export(
#[cfg(test)]
mod tests {
- use super::{ExportPhase, cancel_matching_export};
+ use super::{ExportDestination, ExportPhase, ExportUi, cancel_matching_export};
+ use crate::store::ExportPrefs;
+ use std::path::PathBuf;
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};
+ fn clipboard_export() -> ExportUi {
+ ExportUi::from_preferences(ExportPrefs {
+ format: "Mp4".into(),
+ fps: 30,
+ export_to: "clipboard".into(),
+ resolution: "720p".into(),
+ compression: "Maximum".into(),
+ optimize_filesize: false,
+ cursor_only: false,
+ custom_bpp: None,
+ force_ffmpeg_decoder: false,
+ advanced_open: false,
+ organization_id: None,
+ })
+ }
+
+ #[test]
+ fn failed_clipboard_copy_retries_the_completed_file() {
+ let mut ui = clipboard_export();
+ let output = PathBuf::from("finished recording.mp4");
+ ui.copy_completed_export(output.clone(), |path| {
+ assert_eq!(path, output);
+ Err("Clipboard is busy".into())
+ });
+ assert_eq!(ui.phase, ExportPhase::Failed);
+ assert_eq!(ui.error.as_deref(), Some("Clipboard is busy"));
+ let retry = ui.clipboard_retry_path().unwrap().to_path_buf();
+ assert_eq!(retry, output);
+
+ ui.copy_completed_export(retry, |path| {
+ assert_eq!(path, output);
+ Ok(())
+ });
+ assert_eq!(ui.phase, ExportPhase::Done);
+ assert_eq!(ui.output_path, Some(output));
+ assert!(ui.error.is_none());
+ assert!(ui.clipboard_retry_path().is_none());
+ }
+
+ #[test]
+ fn cancellation_or_close_prevents_late_clipboard_mutation() {
+ for closing in [false, true] {
+ let mut ui = clipboard_export();
+ ui.close_requested = closing;
+ ui.cancel.store(!closing, Ordering::Relaxed);
+ let output = PathBuf::from("finished recording.mp4");
+ ui.copy_completed_export(output.clone(), |_| {
+ panic!("cancelled exports must not replace the clipboard")
+ });
+ assert_eq!(ui.phase, ExportPhase::Idle);
+ assert_eq!(ui.output_path, Some(output));
+ assert!(ui.clipboard_retry_path().is_none());
+ }
+ }
+
+ #[test]
+ fn incomplete_or_non_clipboard_exports_cannot_retry_copy() {
+ let mut ui = clipboard_export();
+ ui.phase = ExportPhase::Failed;
+ assert!(ui.clipboard_retry_path().is_none());
+ ui.output_path = Some(PathBuf::from("finished recording.mp4"));
+ ui.destination = ExportDestination::File;
+ assert!(ui.clipboard_retry_path().is_none());
+ ui.destination = ExportDestination::Link;
+ assert!(ui.clipboard_retry_path().is_none());
+ }
+
#[test]
fn declining_cancel_preserves_the_running_export() {
let cancel = Arc::new(AtomicBool::new(false));
diff --git a/apps/desktop-gpui/src/main_window.rs b/apps/desktop-gpui/src/main_window.rs
index a2cebbd33..11bd2e252 100644
--- a/apps/desktop-gpui/src/main_window.rs
+++ b/apps/desktop-gpui/src/main_window.rs
@@ -4310,9 +4310,13 @@ impl MainWindow {
.child(
self.library_action(("lib-ss-copy", index), "icons/copy.svg", {
let png = png.clone();
- move |_, _, _| {
- if let Err(error) = crate::platform::copy_image_to_clipboard(&png) {
+ move |_, _, cx| {
+ if let Err(error) = crate::platform::copy_image_to_clipboard(&png, cx) {
tracing::warn!("copying screenshot failed: {error}");
+ cx.spawn(async move |_| {
+ crate::platform::alert_dialog("Could not copy screenshot", &error);
+ })
+ .detach();
}
}
}),
diff --git a/apps/desktop-gpui/src/platform.rs b/apps/desktop-gpui/src/platform.rs
index 2b9d0ae14..186b1fde8 100644
--- a/apps/desktop-gpui/src/platform.rs
+++ b/apps/desktop-gpui/src/platform.rs
@@ -110,6 +110,23 @@ pub fn active_material(cx: &gpui::App) -> Option<MaterialKind> {
.and_then(|material| material.0)
}
+fn clipboard_file_path(path: &std::path::Path) -> Result<std::path::PathBuf, String> {
+ let path = std::path::absolute(path)
+ .map_err(|error| format!("Could not resolve the clipboard file: {error}"))?;
+ let metadata = std::fs::metadata(&path)
+ .map_err(|error| format!("Could not read the clipboard file: {error}"))?;
+ if !metadata.is_file() {
+ return Err("Only files can be copied to the clipboard".into());
+ }
+ Ok(path)
+}
+
+pub fn copy_image_to_clipboard(path: &std::path::Path, cx: &gpui::App) -> Result<(), String> {
+ let bytes = std::fs::read(path)
+ .map_err(|error| format!("Could not read the clipboard image: {error}"))?;
+ copy_image_bytes_to_clipboard(&bytes, cx)
+}
+
#[cfg(any(not(target_os = "macos"), test))]
fn confirmation_accepted(result: rfd::MessageDialogResult, accept: &str) -> bool {
match result {
@@ -1187,56 +1204,62 @@ mod mac {
}
}
- pub fn copy_file_to_clipboard(path: &std::path::Path) -> Result<(), String> {
+ pub fn copy_file_to_clipboard(path: &std::path::Path, _cx: &gpui::App) -> Result<(), String> {
+ use objc2::rc::autoreleasepool;
+ use objc2::runtime::Bool;
use objc2::{class, msg_send};
use objc2_foundation::NSString;
- unsafe {
+ let path = super::clipboard_file_path(path)?;
+ let path = path
+ .to_str()
+ .ok_or("The clipboard file path is not valid Unicode")?;
+ autoreleasepool(|_| unsafe {
let pasteboard: *mut AnyObject = msg_send![class!(NSPasteboard), generalPasteboard];
if pasteboard.is_null() {
return Err("Clipboard unavailable".into());
}
- let _: isize = msg_send![pasteboard, clearContents];
let url_class = class!(NSURL);
- let ns_path = NSString::from_str(&path.to_string_lossy());
+ let ns_path = NSString::from_str(path);
let url: *mut AnyObject = msg_send![url_class, fileURLWithPath: &*ns_path];
if url.is_null() {
return Err("Failed to build file URL".into());
}
let objects: *mut AnyObject = msg_send![class!(NSArray), arrayWithObject: url];
- let ok: bool = msg_send![pasteboard, writeObjects: objects];
- if ok {
+ let _: isize = msg_send![pasteboard, clearContents];
+ let ok: Bool = msg_send![pasteboard, writeObjects: objects];
+ if ok.as_bool() {
Ok(())
} else {
Err("Failed to copy file to clipboard".into())
}
- }
+ })
}
- pub fn copy_image_to_clipboard(path: &std::path::Path) -> Result<(), String> {
+ pub fn copy_image_bytes_to_clipboard(bytes: &[u8], _cx: &gpui::App) -> Result<(), String> {
+ use objc2::rc::autoreleasepool;
+ use objc2::runtime::Bool;
use objc2::{class, msg_send};
- use objc2_foundation::NSString;
+ use objc2_foundation::NSData;
- unsafe {
+ autoreleasepool(|_| unsafe {
let pasteboard: *mut AnyObject = msg_send![class!(NSPasteboard), generalPasteboard];
if pasteboard.is_null() {
return Err("Clipboard unavailable".into());
}
- let _: isize = msg_send![pasteboard, clearContents];
- let ns_path = NSString::from_str(&path.to_string_lossy());
+ let data = NSData::with_bytes(bytes);
let image: *mut AnyObject = msg_send![class!(NSImage), alloc];
- let image: *mut AnyObject = msg_send![image, initWithContentsOfFile: &*ns_path];
- if image.is_null() {
- return Err("Failed to load image".into());
- }
- let objects: *mut AnyObject = msg_send![class!(NSArray), arrayWithObject: image];
- let ok: bool = msg_send![pasteboard, writeObjects: objects];
- if ok {
+ let image: *mut AnyObject = msg_send![image, initWithData: &*data];
+ let image = Id::from_raw(image).ok_or("Failed to load image")?;
+ let objects: *mut AnyObject = msg_send![class!(NSArray), arrayWithObject: &*image];
+ let _: isize = msg_send![pasteboard, clearContents];
+ let ok: Bool = msg_send![pasteboard, writeObjects: objects];
+ if ok.as_bool() {
Ok(())
} else {
Err("Failed to copy image to clipboard".into())
}
- }
+ })
}
fn open_file_panel(extensions: &[&str]) -> Option<std::path::PathBuf> {
@@ -1919,36 +1942,27 @@ mod stub {
dialog.save_file()
}
- pub fn copy_file_to_clipboard(path: &std::path::Path) -> Result<(), String> {
- #[cfg(windows)]
- {
- let _ = path;
- Err("Copy to clipboard is not available yet on Windows".into())
- }
- #[cfg(not(windows))]
- {
- let uri = format!("file://{}", path.display());
- let copied = std::process::Command::new("wl-copy")
- .arg(&uri)
- .status()
- .ok()
- .is_some_and(|status| status.success())
- || std::process::Command::new("xclip")
- .args(["-selection", "clipboard"])
- .arg(path)
- .status()
- .ok()
- .is_some_and(|status| status.success());
- if copied {
- Ok(())
- } else {
- Err("Failed to copy file to clipboard".into())
- }
- }
- }
-
- pub fn copy_image_to_clipboard(path: &std::path::Path) -> Result<(), String> {
- copy_file_to_clipboard(path)
+ pub fn copy_file_to_clipboard(path: &std::path::Path, cx: &gpui::App) -> Result<(), String> {
+ let path = super::clipboard_file_path(path)?;
+ cx.try_write_to_clipboard(
+ gpui::ClipboardEntry::ExternalPaths(gpui::ExternalPaths(vec![path].into())).into(),
+ )
+ .map_err(|error| format!("Could not copy the file to the clipboard: {error}"))
+ }
+
+ pub fn copy_image_bytes_to_clipboard(bytes: &[u8], cx: &gpui::App) -> Result<(), String> {
+ let format = match image::guess_format(bytes).map_err(|error| error.to_string())? {
+ image::ImageFormat::Png => gpui::ImageFormat::Png,
+ image::ImageFormat::Jpeg => gpui::ImageFormat::Jpeg,
+ image::ImageFormat::WebP => gpui::ImageFormat::Webp,
+ image::ImageFormat::Gif => gpui::ImageFormat::Gif,
+ image::ImageFormat::Bmp => gpui::ImageFormat::Bmp,
+ image::ImageFormat::Tiff => gpui::ImageFormat::Tiff,
+ _ => return Err("Unsupported clipboard image format".into()),
+ };
+ let image = gpui::Image::from_bytes(format, bytes.to_vec());
+ cx.try_write_to_clipboard(gpui::ClipboardItem::new_image(&image))
+ .map_err(|error| format!("Could not copy the image to the clipboard: {error}"))
}
pub fn desktop_picture_path() -> Option<std::path::PathBuf> {
None
diff --git a/apps/desktop-gpui/src/platform/windows.rs b/apps/desktop-gpui/src/platform/windows.rs
index 96dffdc6a..d7e81fbff 100644
--- a/apps/desktop-gpui/src/platform/windows.rs
+++ b/apps/desktop-gpui/src/platform/windows.rs
@@ -612,12 +612,29 @@ pub fn save_file_panel(suggested: &str, extensions: &[&str]) -> Option<PathBuf>
dialog.save_file()
}
-pub fn copy_file_to_clipboard(_path: &Path) -> Result<(), String> {
- Err("Copy to clipboard is not available yet on Windows".into())
-}
-
-pub fn copy_image_to_clipboard(path: &Path) -> Result<(), String> {
- copy_file_to_clipboard(path)
+pub fn copy_file_to_clipboard(path: &Path, _cx: &gpui::App) -> Result<(), String> {
+ use clipboard_rs::{Clipboard, ClipboardContext};
+
+ let path = super::clipboard_file_path(path)?;
+ let path = path
+ .to_str()
+ .ok_or("The clipboard file path is not valid Unicode")?;
+ ClipboardContext::new()
+ .map_err(|error| format!("Clipboard unavailable: {error}"))?
+ .set_files(vec![path.to_owned()])
+ .map_err(|error| format!("Could not copy the file to the clipboard: {error}"))
+}
+
+pub fn copy_image_bytes_to_clipboard(bytes: &[u8], _cx: &gpui::App) -> Result<(), String> {
+ use clipboard_rs::common::RustImage;
+ use clipboard_rs::{Clipboard, ClipboardContext, RustImageData};
+
+ let image = RustImageData::from_bytes(bytes)
+ .map_err(|error| format!("Could not load the clipboard image: {error}"))?;
+ ClipboardContext::new()
+ .map_err(|error| format!("Clipboard unavailable: {error}"))?
+ .set_image(image)
+ .map_err(|error| format!("Could not copy the image to the clipboard: {error}"))
}
pub fn desktop_picture_path() -> Option<PathBuf> {
diff --git a/apps/desktop-gpui/src/screenshot_editor.rs b/apps/desktop-gpui/src/screenshot_editor.rs
index 50d904da0..3504b6059 100644
--- a/apps/desktop-gpui/src/screenshot_editor.rs
+++ b/apps/desktop-gpui/src/screenshot_editor.rs
@@ -1967,59 +1967,22 @@ impl ScreenshotEditorWindow {
match result {
Ok(bytes) => match destination {
ExportDestination::Clipboard => {
- // The clipboard seam this app has is "NSImage from a
- // path" (`platform::copy_image_to_clipboard`); a temp
- // file bridges the rendered bytes to it.
- let path = std::env::temp_dir()
- .join(format!("cap-screenshot-copy-{}.png", std::process::id()));
- let written =
- cx.background_executor()
- .spawn({
- let path = path.clone();
- async move {
- std::fs::write(&path, &bytes).map_err(|e| e.to_string())
- }
- })
- .await;
- match written {
- Ok(()) => {
- let copied = this.update_in(cx, |_, _, _| {
- crate::platform::copy_image_to_clipboard(&path)
- });
- match copied {
- Ok(Err(error)) => {
- tracing::error!("copying the screenshot failed: {error}");
- this.update_in(cx, |this, window, cx| {
- this.toast_error(error, window, cx)
- })
- .ok();
- }
- Ok(Ok(())) => {
- this.update_in(cx, |this, window, cx| {
- this.toast_success(
- "Screenshot copied to clipboard!",
- window,
- cx,
- )
- })
- .ok();
- }
- Err(_) => {}
+ this.update_in(cx, |this, window, cx| {
+ match crate::platform::copy_image_bytes_to_clipboard(&bytes, cx) {
+ Ok(()) => {
+ this.toast_success(
+ "Screenshot copied to clipboard!",
+ window,
+ cx,
+ );
+ }
+ Err(error) => {
+ tracing::error!("copying the screenshot failed: {error}");
+ this.toast_error(error, window, cx);
}
- cx.background_executor()
- .spawn(async move {
- let _ = std::fs::remove_file(&path);
- })
- .detach();
- }
- Err(error) => {
- tracing::error!("writing the clipboard temp file failed: {error}");
- this.update_in(cx, |this, window, cx| {
- this.toast_error(error, window, cx)
- })
- .ok();
}
- }
+ })
+ .ok();
}
ExportDestination::File => {
let dest =
diff --git a/apps/desktop-gpui/src/settings_window.rs b/apps/desktop-gpui/src/settings_window.rs
index 3f6a072c1..e092c0193 100644
--- a/apps/desktop-gpui/src/settings_window.rs
+++ b/apps/desktop-gpui/src/settings_window.rs
@@ -2304,9 +2304,13 @@ impl SettingsWindow {
cx,
{
let png = png.clone();
- move |_this, _window, _cx| {
- if let Err(error) = crate::platform::copy_image_to_clipboard(&png) {
+ move |_this, _window, cx| {
+ if let Err(error) = crate::platform::copy_image_to_clipboard(&png, cx) {
tracing::warn!("copying screenshot failed: {error}");
+ cx.spawn(async move |_, _| {
+ crate::platform::alert_dialog("Could not copy screenshot", &error);
+ })
+ .detach();
}
}
},